{
"args": [
"./disable",
"8802537394206704161",
".*EmbeddedTestServerTest.ConnectionListenerComplete.*",
"linux"
],
"requests": "{\"QueryTestResults/{\\\"invocations\\\": [\\\"invocations/build-8802537394206704161\\\"], \\\"readMask\\\": {\\\"paths\\\": [\\\"test_id\\\", \\\"test_metadata\\\"]}, \\\"pageSize\\\": 1000, \\\"predicate\\\": {\\\"testIdRegexp\\\": \\\".*EmbeddedTestServerTest.ConnectionListenerComplete.*\\\"}}\": \"{\\\"testResults\\\":[{\\\"name\\\":\\\"invocations/task-chromium-swarm.appspot.com-5d7195e275a5f011/tests/ninja:%2F%2Fnet:net_unittests%2FEmbeddedTestServerTest.ConnectionListenerComplete%2FEmbeddedTestServerTestInstantiation.0/results/2ca5e86f-04120\\\",\\\"testId\\\":\\\"ninja://net:net_unittests/EmbeddedTestServerTest.ConnectionListenerComplete/EmbeddedTestServerTestInstantiation.0\\\",\\\"testMetadata\\\":{\\\"name\\\":\\\"EmbeddedTestServerTestInstantiation/EmbeddedTestServerTest.ConnectionListenerComplete/0\\\",\\\"location\\\":{\\\"repo\\\":\\\"https://chromium.googlesource.com/chromium/src\\\",\\\"fileName\\\":\\\"//net/test/embedded_test_server/embedded_test_server_unittest.cc\\\",\\\"line\\\":351}}},{\\\"name\\\":\\\"invocations/task-chromium-swarm.appspot.com-5d7195e275a5f011/tests/ninja:%2F%2Fnet:net_unittests%2FEmbeddedTestServerTest.ConnectionListenerComplete%2FEmbeddedTestServerTestInstantiation.0/results/2ca5e86f-04121\\\",\\\"testId\\\":\\\"ninja://net:net_unittests/EmbeddedTestServerTest.ConnectionListenerComplete/EmbeddedTestServerTestInstantiation.0\\\",\\\"testMetadata\\\":{\\\"name\\\":\\\"EmbeddedTestServerTestInstantiation/EmbeddedTestServerTest.ConnectionListenerComplete/0\\\",\\\"location\\\":{\\\"repo\\\":\\\"https://chromium.googlesource.com/chromium/src\\\",\\\"fileName\\\":\\\"//net/test/embedded_test_server/embedded_test_server_unittest.cc\\\",\\\"line\\\":351}}},{\\\"name\\\":\\\"invocations/task-chromium-swarm.appspot.com-5d7195e275a5f011/tests/ninja:%2F%2Fnet:net_unittests%2FEmbeddedTestServerTest.ConnectionListenerComplete%2FEmbeddedTestServerTestInstantiation.1/results/2ca5e86f-04122\\\",\\\"testId\\\":\\\"ninja://net:net_unittests/EmbeddedTestServerTest.ConnectionListenerComplete/EmbeddedTestServerTestInstantiation.1\\\",\\\"testMetadata\\\":{\\\"name\\\":\\\"EmbeddedTestServerTestInstantiation/EmbeddedTestServerTest.ConnectionListenerComplete/1\\\",\\\"location\\\":{\\\"repo\\\":\\\"https://chromium.googlesource.com/chromium/src\\\",\\\"fileName\\\":\\\"//net/test/embedded_test_server/embedded_test_server_unittest.cc\\\",\\\"line\\\":351}}},{\\\"name\\\":\\\"invocations/task-chromium-swarm.appspot.com-5d7195e275a5f011/tests/ninja:%2F%2Fnet:net_unittests%2FEmbeddedTestServerTest.ConnectionListenerComplete%2FEmbeddedTestServerTestInstantiation.2/results/2ca5e86f-04123\\\",\\\"testId\\\":\\\"ninja://net:net_unittests/EmbeddedTestServerTest.ConnectionListenerComplete/EmbeddedTestServerTestInstantiation.2\\\",\\\"testMetadata\\\":{\\\"name\\\":\\\"EmbeddedTestServerTestInstantiation/EmbeddedTestServerTest.ConnectionListenerComplete/2\\\",\\\"location\\\":{\\\"repo\\\":\\\"https://chromium.googlesource.com/chromium/src\\\",\\\"fileName\\\":\\\"//net/test/embedded_test_server/embedded_test_server_unittest.cc\\\",\\\"line\\\":351}}}]}\\n\"}",
"read_data": {
"net/test/embedded_test_server/embedded_test_server_unittest.cc": "// Copyright 2012 The Chromium Authors\n// Use of this source code is governed by a BSD-style license that can be\n// found in the LICENSE file.\n\n#include \"net/test/embedded_test_server/embedded_test_server.h\"\n\n#include <tuple>\n#include <utility>\n\n#include \"base/bind.h\"\n#include \"base/callback_helpers.h\"\n#include \"base/memory/weak_ptr.h\"\n#include \"base/message_loop/message_pump_type.h\"\n#include \"base/path_service.h\"\n#include \"base/run_loop.h\"\n#include \"base/strings/stringprintf.h\"\n#include \"base/synchronization/lock.h\"\n#include \"base/task/single_thread_task_executor.h\"\n#include \"base/task/single_thread_task_runner.h\"\n#include \"base/threading/thread.h\"\n#include \"base/threading/thread_task_runner_handle.h\"\n#include \"build/build_config.h\"\n#include \"net/base/test_completion_callback.h\"\n#include \"net/http/http_response_headers.h\"\n#include \"net/log/net_log_source.h\"\n#include \"net/socket/client_socket_factory.h\"\n#include \"net/socket/stream_socket.h\"\n#include \"net/test/embedded_test_server/embedded_test_server_connection_listener.h\"\n#include \"net/test/embedded_test_server/http_request.h\"\n#include \"net/test/embedded_test_server/http_response.h\"\n#include \"net/test/embedded_test_server/request_handler_util.h\"\n#include \"net/test/gtest_util.h\"\n#include \"net/test/test_with_task_environment.h\"\n#include \"net/traffic_annotation/network_traffic_annotation_test_helper.h\"\n#include \"net/url_request/url_request.h\"\n#include \"net/url_request/url_request_context.h\"\n#include \"net/url_request/url_request_context_builder.h\"\n#include \"net/url_request/url_request_test_util.h\"\n#include \"testing/gmock/include/gmock/gmock.h\"\n#include \"testing/gtest/include/gtest/gtest.h\"\n\nusing net::test::IsOk;\n\nnamespace net::test_server {\n\n// Gets notified by the EmbeddedTestServer on incoming connections being\n// accepted, read from, or closed.\nclass TestConnectionListener\n : public net::test_server::EmbeddedTestServerConnectionListener {\n public:\n TestConnectionListener()\n : task_runner_(base::ThreadTaskRunnerHandle::Get()) {}\n\n TestConnectionListener(const TestConnectionListener&) = delete;\n TestConnectionListener& operator=(const TestConnectionListener&) = delete;\n\n ~TestConnectionListener() override = default;\n\n // Get called from the EmbeddedTestServer thread to be notified that\n // a connection was accepted.\n std::unique_ptr<StreamSocket> AcceptedSocket(\n std::unique_ptr<StreamSocket> connection) override {\n base::AutoLock lock(lock_);\n ++socket_accepted_count_;\n accept_loop_.Quit();\n return connection;\n }\n\n // Get called from the EmbeddedTestServer thread to be notified that\n // a connection was read from.\n void ReadFromSocket(const net::StreamSocket& connection, int rv) override {\n base::AutoLock lock(lock_);\n did_read_from_socket_ = true;\n }\n\n void OnResponseCompletedSuccessfully(\n std::unique_ptr<StreamSocket> socket) override {\n base::AutoLock lock(lock_);\n did_get_socket_on_complete_ = socket && socket->IsConnected();\n complete_loop_.Quit();\n }\n\n void WaitUntilFirstConnectionAccepted() { accept_loop_.Run(); }\n\n void WaitUntilGotSocketFromResponseCompleted() { complete_loop_.Run(); }\n\n size_t SocketAcceptedCount() const {\n base::AutoLock lock(lock_);\n return socket_accepted_count_;\n }\n\n bool DidReadFromSocket() const {\n base::AutoLock lock(lock_);\n return did_read_from_socket_;\n }\n\n bool DidGetSocketOnComplete() const {\n base::AutoLock lock(lock_);\n return did_get_socket_on_complete_;\n }\n\n private:\n size_t socket_accepted_count_ = 0;\n bool did_read_from_socket_ = false;\n bool did_get_socket_on_complete_ = false;\n\n base::RunLoop accept_loop_;\n base::RunLoop complete_loop_;\n scoped_refptr<base::SingleThreadTaskRunner> task_runner_;\n\n mutable base::Lock lock_;\n};\n\nstruct EmbeddedTestServerConfig {\n EmbeddedTestServer::Type type;\n HttpConnection::Protocol protocol;\n};\n\nstd::vector<EmbeddedTestServerConfig> EmbeddedTestServerConfigs() {\n return {\n {EmbeddedTestServer::TYPE_HTTP, HttpConnection::Protocol::kHttp1},\n {EmbeddedTestServer::TYPE_HTTPS, HttpConnection::Protocol::kHttp1},\n {EmbeddedTestServer::TYPE_HTTPS, HttpConnection::Protocol::kHttp2},\n };\n}\n\nclass EmbeddedTestServerTest\n : public testing::TestWithParam<EmbeddedTestServerConfig>,\n public WithTaskEnvironment {\n public:\n EmbeddedTestServerTest()\n : context_(CreateTestURLRequestContextBuilder()->Build()) {}\n\n void SetUp() override {\n server_ = std::make_unique<EmbeddedTestServer>(GetParam().type,\n GetParam().protocol);\n server_->AddDefaultHandlers();\n server_->SetConnectionListener(&connection_listener_);\n }\n\n void TearDown() override {\n if (server_->Started())\n ASSERT_TRUE(server_->ShutdownAndWaitUntilComplete());\n }\n\n // Handles |request| sent to |path| and returns the response per |content|,\n // |content type|, and |code|. Saves the request URL for verification.\n std::unique_ptr<HttpResponse> HandleRequest(const std::string& path,\n const std::string& content,\n const std::string& content_type,\n HttpStatusCode code,\n const HttpRequest& request) {\n request_relative_url_ = request.relative_url;\n request_absolute_url_ = request.GetURL();\n\n if (request_absolute_url_.path() == path) {\n auto http_response = std::make_unique<BasicHttpResponse>();\n http_response->set_code(code);\n http_response->set_content(content);\n http_response->set_content_type(content_type);\n return http_response;\n }\n\n return nullptr;\n }\n\n protected:\n std::string request_relative_url_;\n GURL request_absolute_url_;\n std::unique_ptr<URLRequestContext> context_;\n TestConnectionListener connection_listener_;\n std::unique_ptr<EmbeddedTestServer> server_;\n base::OnceClosure quit_run_loop_;\n};\n\nTEST_P(EmbeddedTestServerTest, GetBaseURL) {\n ASSERT_TRUE(server_->Start());\n if (GetParam().type == EmbeddedTestServer::TYPE_HTTPS) {\n EXPECT_EQ(base::StringPrintf(\"https://127.0.0.1:%u/\", server_->port()),\n server_->base_url().spec());\n } else {\n EXPECT_EQ(base::StringPrintf(\"http://127.0.0.1:%u/\", server_->port()),\n server_->base_url().spec());\n }\n}\n\nTEST_P(EmbeddedTestServerTest, GetURL) {\n ASSERT_TRUE(server_->Start());\n if (GetParam().type == EmbeddedTestServer::TYPE_HTTPS) {\n EXPECT_EQ(base::StringPrintf(\"https://127.0.0.1:%u/path?query=foo\",\n server_->port()),\n server_->GetURL(\"/path?query=foo\").spec());\n } else {\n EXPECT_EQ(base::StringPrintf(\"http://127.0.0.1:%u/path?query=foo\",\n server_->port()),\n server_->GetURL(\"/path?query=foo\").spec());\n }\n}\n\nTEST_P(EmbeddedTestServerTest, GetURLWithHostname) {\n ASSERT_TRUE(server_->Start());\n if (GetParam().type == EmbeddedTestServer::TYPE_HTTPS) {\n EXPECT_EQ(base::StringPrintf(\"https://foo.com:%d/path?query=foo\",\n server_->port()),\n server_->GetURL(\"foo.com\", \"/path?query=foo\").spec());\n } else {\n EXPECT_EQ(\n base::StringPrintf(\"http://foo.com:%d/path?query=foo\", server_->port()),\n server_->GetURL(\"foo.com\", \"/path?query=foo\").spec());\n }\n}\n\nTEST_P(EmbeddedTestServerTest, RegisterRequestHandler) {\n server_->RegisterRequestHandler(base::BindRepeating(\n &EmbeddedTestServerTest::HandleRequest, base::Unretained(this), \"/test\",\n \"<b>Worked!</b>\", \"text/html\", HTTP_OK));\n ASSERT_TRUE(server_->Start());\n\n TestDelegate delegate;\n std::unique_ptr<URLRequest> request(\n context_->CreateRequest(server_->GetURL(\"/test?q=foo\"), DEFAULT_PRIORITY,\n &delegate, TRAFFIC_ANNOTATION_FOR_TESTS));\n\n request->Start();\n delegate.RunUntilComplete();\n\n EXPECT_EQ(net::OK, delegate.request_status());\n ASSERT_TRUE(request->response_headers());\n EXPECT_EQ(HTTP_OK, request->response_headers()->response_code());\n EXPECT_EQ(\"<b>Worked!</b>\", delegate.data_received());\n std::string content_type;\n ASSERT_TRUE(request->response_headers()->GetNormalizedHeader(\"Content-Type\",\n &content_type));\n EXPECT_EQ(\"text/html\", content_type);\n\n EXPECT_EQ(\"/test?q=foo\", request_relative_url_);\n EXPECT_EQ(server_->GetURL(\"/test?q=foo\"), request_absolute_url_);\n}\n\nTEST_P(EmbeddedTestServerTest, ServeFilesFromDirectory) {\n base::FilePath src_dir;\n ASSERT_TRUE(base::PathService::Get(base::DIR_SRC_TEST_DATA_ROOT, &src_dir));\n server_->ServeFilesFromDirectory(\n src_dir.AppendASCII(\"net\").AppendASCII(\"data\"));\n ASSERT_TRUE(server_->Start());\n\n TestDelegate delegate;\n std::unique_ptr<URLRequest> request(\n context_->CreateRequest(server_->GetURL(\"/test.html\"), DEFAULT_PRIORITY,\n &delegate, TRAFFIC_ANNOTATION_FOR_TESTS));\n\n request->Start();\n delegate.RunUntilComplete();\n\n EXPECT_EQ(net::OK, delegate.request_status());\n ASSERT_TRUE(request->response_headers());\n EXPECT_EQ(HTTP_OK, request->response_headers()->response_code());\n EXPECT_EQ(\"<p>Hello World!</p>\", delegate.data_received());\n std::string content_type;\n ASSERT_TRUE(request->response_headers()->GetNormalizedHeader(\"Content-Type\",\n &content_type));\n EXPECT_EQ(\"text/html\", content_type);\n}\n\nTEST_P(EmbeddedTestServerTest, MockHeadersWithoutCRLF) {\n // Messing with raw headers isn't compatible with HTTP/2\n if (GetParam().protocol == HttpConnection::Protocol::kHttp2)\n return;\n\n base::FilePath src_dir;\n ASSERT_TRUE(base::PathService::Get(base::DIR_SRC_TEST_DATA_ROOT, &src_dir));\n server_->ServeFilesFromDirectory(\n src_dir.AppendASCII(\"net\").AppendASCII(\"data\").AppendASCII(\n \"embedded_test_server\"));\n ASSERT_TRUE(server_->Start());\n\n TestDelegate delegate;\n std::unique_ptr<URLRequest> request(context_->CreateRequest(\n server_->GetURL(\"/mock-headers-without-crlf.html\"), DEFAULT_PRIORITY,\n &delegate, TRAFFIC_ANNOTATION_FOR_TESTS));\n\n request->Start();\n delegate.RunUntilComplete();\n\n EXPECT_EQ(net::OK, delegate.request_status());\n ASSERT_TRUE(request->response_headers());\n EXPECT_EQ(HTTP_OK, request->response_headers()->response_code());\n EXPECT_EQ(\"<p>Hello World!</p>\", delegate.data_received());\n std::string content_type;\n ASSERT_TRUE(request->response_headers()->GetNormalizedHeader(\"Content-Type\",\n &content_type));\n EXPECT_EQ(\"text/html\", content_type);\n}\n\nTEST_P(EmbeddedTestServerTest, DefaultNotFoundResponse) {\n ASSERT_TRUE(server_->Start());\n\n TestDelegate delegate;\n std::unique_ptr<URLRequest> request(context_->CreateRequest(\n server_->GetURL(\"/non-existent\"), DEFAULT_PRIORITY, &delegate,\n TRAFFIC_ANNOTATION_FOR_TESTS));\n\n request->Start();\n delegate.RunUntilComplete();\n\n EXPECT_EQ(net::OK, delegate.request_status());\n ASSERT_TRUE(request->response_headers());\n EXPECT_EQ(HTTP_NOT_FOUND, request->response_headers()->response_code());\n}\n\nTEST_P(EmbeddedTestServerTest, ConnectionListenerAccept) {\n ASSERT_TRUE(server_->Start());\n\n net::AddressList address_list;\n EXPECT_TRUE(server_->GetAddressList(&address_list));\n\n std::unique_ptr<StreamSocket> socket =\n ClientSocketFactory::GetDefaultFactory()->CreateTransportClientSocket(\n address_list, nullptr, nullptr, NetLog::Get(), NetLogSource());\n TestCompletionCallback callback;\n ASSERT_THAT(callback.GetResult(socket->Connect(callback.callback())), IsOk());\n\n connection_listener_.WaitUntilFirstConnectionAccepted();\n\n EXPECT_EQ(1u, connection_listener_.SocketAcceptedCount());\n EXPECT_FALSE(connection_listener_.DidReadFromSocket());\n EXPECT_FALSE(connection_listener_.DidGetSocketOnComplete());\n}\n\nTEST_P(EmbeddedTestServerTest, ConnectionListenerRead) {\n ASSERT_TRUE(server_->Start());\n\n TestDelegate delegate;\n std::unique_ptr<URLRequest> request(context_->CreateRequest(\n server_->GetURL(\"/non-existent\"), DEFAULT_PRIORITY, &delegate,\n TRAFFIC_ANNOTATION_FOR_TESTS));\n\n request->Start();\n delegate.RunUntilComplete();\n\n EXPECT_EQ(1u, connection_listener_.SocketAcceptedCount());\n EXPECT_TRUE(connection_listener_.DidReadFromSocket());\n}\n\n// TODO(http://crbug.com/1166868): Flaky on ChromeOS.\n#if BUILDFLAG(IS_CHROMEOS)\n#define MAYBE_ConnectionListenerComplete DISABLED_ConnectionListenerComplete\n#else\n#define MAYBE_ConnectionListenerComplete ConnectionListenerComplete\n#endif\nTEST_P(EmbeddedTestServerTest, MAYBE_ConnectionListenerComplete) {\n // OnResponseCompletedSuccessfully() makes the assumption that a connection is\n // \"finished\" before the socket is closed, and in the case of HTTP/2 this is\n // not supported\n if (GetParam().protocol == HttpConnection::Protocol::kHttp2)\n return;\n\n ASSERT_TRUE(server_->Start());\n\n TestDelegate delegate;\n // Need to send a Keep-Alive response header since the EmbeddedTestServer only\n // invokes OnResponseCompletedSuccessfully() if the socket is still open, and\n // the network stack will close the socket if not reuable, resulting in\n // potentially racilly closing the socket before\n // OnResponseCompletedSuccessfully() is invoked.\n std::unique_ptr<URLRequest> request(context_->CreateRequest(\n server_->GetURL(\"/set-header?Connection: Keep-Alive\"), DEFAULT_PRIORITY,\n &delegate, TRAFFIC_ANNOTATION_FOR_TESTS));\n\n request->Start();\n delegate.RunUntilComplete();\n\n EXPECT_EQ(1u, connection_listener_.SocketAcceptedCount());\n EXPECT_TRUE(connection_listener_.DidReadFromSocket());\n\n connection_listener_.WaitUntilGotSocketFromResponseCompleted();\n EXPECT_TRUE(connection_listener_.DidGetSocketOnComplete());\n}\n\nTEST_P(EmbeddedTestServerTest, ConcurrentFetches) {\n server_->RegisterRequestHandler(base::BindRepeating(\n &EmbeddedTestServerTest::HandleRequest, base::Unretained(this), \"/test1\",\n \"Raspberry chocolate\", \"text/html\", HTTP_OK));\n server_->RegisterRequestHandler(base::BindRepeating(\n &EmbeddedTestServerTest::HandleRequest, base::Unretained(this), \"/test2\",\n \"Vanilla chocolate\", \"text/html\", HTTP_OK));\n server_->RegisterRequestHandler(base::BindRepeating(\n &EmbeddedTestServerTest::HandleRequest, base::Unretained(this), \"/test3\",\n \"No chocolates\", \"text/plain\", HTTP_NOT_FOUND));\n ASSERT_TRUE(server_->Start());\n\n TestDelegate delegate1;\n std::unique_ptr<URLRequest> request1(\n context_->CreateRequest(server_->GetURL(\"/test1\"), DEFAULT_PRIORITY,\n &delegate1, TRAFFIC_ANNOTATION_FOR_TESTS));\n TestDelegate delegate2;\n std::unique_ptr<URLRequest> request2(\n context_->CreateRequest(server_->GetURL(\"/test2\"), DEFAULT_PRIORITY,\n &delegate2, TRAFFIC_ANNOTATION_FOR_TESTS));\n TestDelegate delegate3;\n std::unique_ptr<URLRequest> request3(\n context_->CreateRequest(server_->GetURL(\"/test3\"), DEFAULT_PRIORITY,\n &delegate3, TRAFFIC_ANNOTATION_FOR_TESTS));\n\n // Fetch the three URLs concurrently. Have to manually create RunLoops when\n // running multiple requests simultaneously, to avoid the deprecated\n // RunUntilIdle() path.\n base::RunLoop run_loop1;\n base::RunLoop run_loop2;\n base::RunLoop run_loop3;\n delegate1.set_on_complete(run_loop1.QuitClosure());\n delegate2.set_on_complete(run_loop2.QuitClosure());\n delegate3.set_on_complete(run_loop3.QuitClosure());\n request1->Start();\n request2->Start();\n request3->Start();\n run_loop1.Run();\n run_loop2.Run();\n run_loop3.Run();\n\n EXPECT_EQ(net::OK, delegate2.request_status());\n ASSERT_TRUE(request1->response_headers());\n EXPECT_EQ(HTTP_OK, request1->response_headers()->response_code());\n EXPECT_EQ(\"Raspberry chocolate\", delegate1.data_received());\n std::string content_type1;\n ASSERT_TRUE(request1->response_headers()->GetNormalizedHeader(\n \"Content-Type\", &content_type1));\n EXPECT_EQ(\"text/html\", content_type1);\n\n EXPECT_EQ(net::OK, delegate2.request_status());\n ASSERT_TRUE(request2->response_headers());\n EXPECT_EQ(HTTP_OK, request2->response_headers()->response_code());\n EXPECT_EQ(\"Vanilla chocolate\", delegate2.data_received());\n std::string content_type2;\n ASSERT_TRUE(request2->response_headers()->GetNormalizedHeader(\n \"Content-Type\", &content_type2));\n EXPECT_EQ(\"text/html\", content_type2);\n\n EXPECT_EQ(net::OK, delegate3.request_status());\n ASSERT_TRUE(request3->response_headers());\n EXPECT_EQ(HTTP_NOT_FOUND, request3->response_headers()->response_code());\n EXPECT_EQ(\"No chocolates\", delegate3.data_received());\n std::string content_type3;\n ASSERT_TRUE(request3->response_headers()->GetNormalizedHeader(\n \"Content-Type\", &content_type3));\n EXPECT_EQ(\"text/plain\", content_type3);\n}\n\nnamespace {\n\nclass CancelRequestDelegate : public TestDelegate {\n public:\n CancelRequestDelegate() { set_on_complete(base::DoNothing()); }\n\n CancelRequestDelegate(const CancelRequestDelegate&) = delete;\n CancelRequestDelegate& operator=(const CancelRequestDelegate&) = delete;\n\n ~CancelRequestDelegate() override = default;\n\n void OnResponseStarted(URLRequest* request, int net_error) override {\n TestDelegate::OnResponseStarted(request, net_error);\n base::ThreadTaskRunnerHandle::Get()->PostDelayedTask(\n FROM_HERE, run_loop_.QuitClosure(), base::Seconds(1));\n }\n\n void WaitUntilDone() { run_loop_.Run(); }\n\n private:\n base::RunLoop run_loop_;\n};\n\nclass InfiniteResponse : public BasicHttpResponse {\n public:\n InfiniteResponse() = default;\n\n InfiniteResponse(const InfiniteResponse&) = delete;\n InfiniteResponse& operator=(const InfiniteResponse&) = delete;\n\n void SendResponse(base::WeakPtr<HttpResponseDelegate> delegate) override {\n delegate->SendResponseHeaders(code(), GetHttpReasonPhrase(code()),\n BuildHeaders());\n SendInfinite(delegate);\n }\n\n private:\n void SendInfinite(base::WeakPtr<HttpResponseDelegate> delegate) {\n delegate->SendContents(\"echo\", base::DoNothing());\n base::ThreadTaskRunnerHandle::Get()->PostTask(\n FROM_HERE, base::BindOnce(&InfiniteResponse::SendInfinite,\n weak_ptr_factory_.GetWeakPtr(), delegate));\n }\n\n base::WeakPtrFactory<InfiniteResponse> weak_ptr_factory_{this};\n};\n\nstd::unique_ptr<HttpResponse> HandleInfiniteRequest(\n const HttpRequest& request) {\n return std::make_unique<InfiniteResponse>();\n}\n\n} // anonymous namespace\n\n// Tests the case the connection is closed while the server is sending a\n// response. May non-deterministically end up at one of three paths\n// (Discover the close event synchronously, asynchronously, or server\n// shutting down before it is discovered).\nTEST_P(EmbeddedTestServerTest, CloseDuringWrite) {\n CancelRequestDelegate cancel_delegate;\n cancel_delegate.set_cancel_in_response_started(true);\n server_->RegisterRequestHandler(\n base::BindRepeating(&HandlePrefixedRequest, \"/infinite\",\n base::BindRepeating(&HandleInfiniteRequest)));\n ASSERT_TRUE(server_->Start());\n\n std::unique_ptr<URLRequest> request =\n context_->CreateRequest(server_->GetURL(\"/infinite\"), DEFAULT_PRIORITY,\n &cancel_delegate, TRAFFIC_ANNOTATION_FOR_TESTS);\n request->Start();\n cancel_delegate.WaitUntilDone();\n}\n\nconst struct CertificateValuesEntry {\n const EmbeddedTestServer::ServerCertificate server_cert;\n const bool is_expired;\n const char* common_name;\n const char* issuer_common_name;\n size_t certs_count;\n} kCertificateValuesEntry[] = {\n {EmbeddedTestServer::CERT_OK, false, \"127.0.0.1\", \"Test Root CA\", 1},\n {EmbeddedTestServer::CERT_OK_BY_INTERMEDIATE, false, \"127.0.0.1\",\n \"Test Intermediate CA\", 2},\n {EmbeddedTestServer::CERT_MISMATCHED_NAME, false, \"127.0.0.1\",\n \"Test Root CA\", 1},\n {EmbeddedTestServer::CERT_COMMON_NAME_IS_DOMAIN, false, \"localhost\",\n \"Test Root CA\", 1},\n {EmbeddedTestServer::CERT_EXPIRED, true, \"127.0.0.1\", \"Test Root CA\", 1},\n};\n\nTEST_P(EmbeddedTestServerTest, GetCertificate) {\n if (GetParam().type != EmbeddedTestServer::TYPE_HTTPS)\n return;\n\n for (const auto& cert_entry : kCertificateValuesEntry) {\n SCOPED_TRACE(cert_entry.server_cert);\n server_->SetSSLConfig(cert_entry.server_cert);\n scoped_refptr<X509Certificate> cert = server_->GetCertificate();\n ASSERT_TRUE(cert);\n EXPECT_EQ(cert->HasExpired(), cert_entry.is_expired);\n EXPECT_EQ(cert->subject().common_name, cert_entry.common_name);\n EXPECT_EQ(cert->issuer().common_name, cert_entry.issuer_common_name);\n EXPECT_EQ(cert->intermediate_buffers().size(), cert_entry.certs_count - 1);\n }\n}\n\nTEST_P(EmbeddedTestServerTest, AcceptCHFrame) {\n // The ACCEPT_CH frame is only supported for HTTP/2 connections\n if (GetParam().protocol == HttpConnection::Protocol::kHttp1)\n return;\n\n server_->SetAlpsAcceptCH(\"\", \"foo\");\n server_->SetSSLConfig(net::EmbeddedTestServer::CERT_OK);\n\n ASSERT_TRUE(server_->Start());\n\n TestDelegate delegate;\n std::unique_ptr<URLRequest> request_a(context_->CreateRequest(\n server_->GetURL(\"/non-existent\"), DEFAULT_PRIORITY, &delegate,\n TRAFFIC_ANNOTATION_FOR_TESTS));\n request_a->Start();\n delegate.RunUntilComplete();\n\n EXPECT_EQ(1u, delegate.transports().size());\n EXPECT_EQ(\"foo\", delegate.transports().back().accept_ch_frame);\n}\n\nTEST_P(EmbeddedTestServerTest, AcceptCHFrameDifferentOrigins) {\n // The ACCEPT_CH frame is only supported for HTTP/2 connections\n if (GetParam().protocol == HttpConnection::Protocol::kHttp1)\n return;\n\n server_->SetAlpsAcceptCH(\"a.test\", \"a\");\n server_->SetAlpsAcceptCH(\"b.test\", \"b\");\n server_->SetAlpsAcceptCH(\"c.b.test\", \"c\");\n server_->SetSSLConfig(net::EmbeddedTestServer::CERT_TEST_NAMES);\n\n ASSERT_TRUE(server_->Start());\n\n {\n TestDelegate delegate;\n std::unique_ptr<URLRequest> request_a(context_->CreateRequest(\n server_->GetURL(\"a.test\", \"/non-existent\"), DEFAULT_PRIORITY, &delegate,\n TRAFFIC_ANNOTATION_FOR_TESTS));\n request_a->Start();\n delegate.RunUntilComplete();\n\n EXPECT_EQ(1u, delegate.transports().size());\n EXPECT_EQ(\"a\", delegate.transports().back().accept_ch_frame);\n }\n\n {\n TestDelegate delegate;\n std::unique_ptr<URLRequest> request_a(context_->CreateRequest(\n server_->GetURL(\"b.test\", \"/non-existent\"), DEFAULT_PRIORITY, &delegate,\n TRAFFIC_ANNOTATION_FOR_TESTS));\n request_a->Start();\n delegate.RunUntilComplete();\n\n EXPECT_EQ(1u, delegate.transports().size());\n EXPECT_EQ(\"b\", delegate.transports().back().accept_ch_frame);\n }\n\n {\n TestDelegate delegate;\n std::unique_ptr<URLRequest> request_a(context_->CreateRequest(\n server_->GetURL(\"c.b.test\", \"/non-existent\"), DEFAULT_PRIORITY,\n &delegate, TRAFFIC_ANNOTATION_FOR_TESTS));\n request_a->Start();\n delegate.RunUntilComplete();\n\n EXPECT_EQ(1u, delegate.transports().size());\n EXPECT_EQ(\"c\", delegate.transports().back().accept_ch_frame);\n }\n}\n\nINSTANTIATE_TEST_SUITE_P(EmbeddedTestServerTestInstantiation,\n EmbeddedTestServerTest,\n testing::ValuesIn(EmbeddedTestServerConfigs()));\n// Below test exercises EmbeddedTestServer's ability to cope with the situation\n// where there is no MessageLoop available on the thread at EmbeddedTestServer\n// initialization and/or destruction.\n\ntypedef std::tuple<bool, bool, EmbeddedTestServerConfig> ThreadingTestParams;\n\nclass EmbeddedTestServerThreadingTest\n : public testing::TestWithParam<ThreadingTestParams>,\n public WithTaskEnvironment {};\n\nclass EmbeddedTestServerThreadingTestDelegate\n : public base::PlatformThread::Delegate {\n public:\n EmbeddedTestServerThreadingTestDelegate(\n bool message_loop_present_on_initialize,\n bool message_loop_present_on_shutdown,\n EmbeddedTestServerConfig config)\n : message_loop_present_on_initialize_(message_loop_present_on_initialize),\n message_loop_present_on_shutdown_(message_loop_present_on_shutdown),\n type_(config.type),\n protocol_(config.protocol) {}\n\n EmbeddedTestServerThreadingTestDelegate(\n const EmbeddedTestServerThreadingTestDelegate&) = delete;\n EmbeddedTestServerThreadingTestDelegate& operator=(\n const EmbeddedTestServerThreadingTestDelegate&) = delete;\n\n // base::PlatformThread::Delegate:\n void ThreadMain() override {\n std::unique_ptr<base::SingleThreadTaskExecutor> executor;\n if (message_loop_present_on_initialize_) {\n executor = std::make_unique<base::SingleThreadTaskExecutor>(\n base::MessagePumpType::IO);\n }\n\n // Create the test server instance.\n EmbeddedTestServer server(type_, protocol_);\n base::FilePath src_dir;\n ASSERT_TRUE(base::PathService::Get(base::DIR_SRC_TEST_DATA_ROOT, &src_dir));\n ASSERT_TRUE(server.Start());\n\n // Make a request and wait for the reply.\n if (!executor) {\n executor = std::make_unique<base::SingleThreadTaskExecutor>(\n base::MessagePumpType::IO);\n }\n\n auto context = CreateTestURLRequestContextBuilder()->Build();\n TestDelegate delegate;\n std::unique_ptr<URLRequest> request(\n context->CreateRequest(server.GetURL(\"/test?q=foo\"), DEFAULT_PRIORITY,\n &delegate, TRAFFIC_ANNOTATION_FOR_TESTS));\n\n request->Start();\n delegate.RunUntilComplete();\n request.reset();\n // Flush the socket pool on the same thread by destroying the context.\n context.reset();\n\n // Shut down.\n if (message_loop_present_on_shutdown_)\n executor.reset();\n\n ASSERT_TRUE(server.ShutdownAndWaitUntilComplete());\n }\n\n private:\n const bool message_loop_present_on_initialize_;\n const bool message_loop_present_on_shutdown_;\n const EmbeddedTestServer::Type type_;\n const HttpConnection::Protocol protocol_;\n};\n\nTEST_P(EmbeddedTestServerThreadingTest, RunTest) {\n // The actual test runs on a separate thread so it can screw with the presence\n // of a MessageLoop - the test suite already sets up a MessageLoop for the\n // main test thread.\n base::PlatformThreadHandle thread_handle;\n EmbeddedTestServerThreadingTestDelegate delegate(std::get<0>(GetParam()),\n std::get<1>(GetParam()),\n std::get<2>(GetParam()));\n ASSERT_TRUE(base::PlatformThread::Create(0, &delegate, &thread_handle));\n base::PlatformThread::Join(thread_handle);\n}\n\nINSTANTIATE_TEST_SUITE_P(\n EmbeddedTestServerThreadingTestInstantiation,\n EmbeddedTestServerThreadingTest,\n testing::Combine(testing::Bool(),\n testing::Bool(),\n testing::ValuesIn(EmbeddedTestServerConfigs())));\n\n} // namespace net::test_server\n"
},
"written_data": {
"net/test/embedded_test_server/embedded_test_server_unittest.cc": "// Copyright 2012 The Chromium Authors\n// Use of this source code is governed by a BSD-style license that can be\n// found in the LICENSE file.\n\n#include \"net/test/embedded_test_server/embedded_test_server.h\"\n\n#include <tuple>\n#include <utility>\n\n#include \"base/bind.h\"\n#include \"base/callback_helpers.h\"\n#include \"base/memory/weak_ptr.h\"\n#include \"base/message_loop/message_pump_type.h\"\n#include \"base/path_service.h\"\n#include \"base/run_loop.h\"\n#include \"base/strings/stringprintf.h\"\n#include \"base/synchronization/lock.h\"\n#include \"base/task/single_thread_task_executor.h\"\n#include \"base/task/single_thread_task_runner.h\"\n#include \"base/threading/thread.h\"\n#include \"base/threading/thread_task_runner_handle.h\"\n#include \"build/build_config.h\"\n#include \"net/base/test_completion_callback.h\"\n#include \"net/http/http_response_headers.h\"\n#include \"net/log/net_log_source.h\"\n#include \"net/socket/client_socket_factory.h\"\n#include \"net/socket/stream_socket.h\"\n#include \"net/test/embedded_test_server/embedded_test_server_connection_listener.h\"\n#include \"net/test/embedded_test_server/http_request.h\"\n#include \"net/test/embedded_test_server/http_response.h\"\n#include \"net/test/embedded_test_server/request_handler_util.h\"\n#include \"net/test/gtest_util.h\"\n#include \"net/test/test_with_task_environment.h\"\n#include \"net/traffic_annotation/network_traffic_annotation_test_helper.h\"\n#include \"net/url_request/url_request.h\"\n#include \"net/url_request/url_request_context.h\"\n#include \"net/url_request/url_request_context_builder.h\"\n#include \"net/url_request/url_request_test_util.h\"\n#include \"testing/gmock/include/gmock/gmock.h\"\n#include \"testing/gtest/include/gtest/gtest.h\"\n\nusing net::test::IsOk;\n\nnamespace net::test_server {\n\n// Gets notified by the EmbeddedTestServer on incoming connections being\n// accepted, read from, or closed.\nclass TestConnectionListener\n : public net::test_server::EmbeddedTestServerConnectionListener {\n public:\n TestConnectionListener()\n : task_runner_(base::ThreadTaskRunnerHandle::Get()) {}\n\n TestConnectionListener(const TestConnectionListener&) = delete;\n TestConnectionListener& operator=(const TestConnectionListener&) = delete;\n\n ~TestConnectionListener() override = default;\n\n // Get called from the EmbeddedTestServer thread to be notified that\n // a connection was accepted.\n std::unique_ptr<StreamSocket> AcceptedSocket(\n std::unique_ptr<StreamSocket> connection) override {\n base::AutoLock lock(lock_);\n ++socket_accepted_count_;\n accept_loop_.Quit();\n return connection;\n }\n\n // Get called from the EmbeddedTestServer thread to be notified that\n // a connection was read from.\n void ReadFromSocket(const net::StreamSocket& connection, int rv) override {\n base::AutoLock lock(lock_);\n did_read_from_socket_ = true;\n }\n\n void OnResponseCompletedSuccessfully(\n std::unique_ptr<StreamSocket> socket) override {\n base::AutoLock lock(lock_);\n did_get_socket_on_complete_ = socket && socket->IsConnected();\n complete_loop_.Quit();\n }\n\n void WaitUntilFirstConnectionAccepted() { accept_loop_.Run(); }\n\n void WaitUntilGotSocketFromResponseCompleted() { complete_loop_.Run(); }\n\n size_t SocketAcceptedCount() const {\n base::AutoLock lock(lock_);\n return socket_accepted_count_;\n }\n\n bool DidReadFromSocket() const {\n base::AutoLock lock(lock_);\n return did_read_from_socket_;\n }\n\n bool DidGetSocketOnComplete() const {\n base::AutoLock lock(lock_);\n return did_get_socket_on_complete_;\n }\n\n private:\n size_t socket_accepted_count_ = 0;\n bool did_read_from_socket_ = false;\n bool did_get_socket_on_complete_ = false;\n\n base::RunLoop accept_loop_;\n base::RunLoop complete_loop_;\n scoped_refptr<base::SingleThreadTaskRunner> task_runner_;\n\n mutable base::Lock lock_;\n};\n\nstruct EmbeddedTestServerConfig {\n EmbeddedTestServer::Type type;\n HttpConnection::Protocol protocol;\n};\n\nstd::vector<EmbeddedTestServerConfig> EmbeddedTestServerConfigs() {\n return {\n {EmbeddedTestServer::TYPE_HTTP, HttpConnection::Protocol::kHttp1},\n {EmbeddedTestServer::TYPE_HTTPS, HttpConnection::Protocol::kHttp1},\n {EmbeddedTestServer::TYPE_HTTPS, HttpConnection::Protocol::kHttp2},\n };\n}\n\nclass EmbeddedTestServerTest\n : public testing::TestWithParam<EmbeddedTestServerConfig>,\n public WithTaskEnvironment {\n public:\n EmbeddedTestServerTest()\n : context_(CreateTestURLRequestContextBuilder()->Build()) {}\n\n void SetUp() override {\n server_ = std::make_unique<EmbeddedTestServer>(GetParam().type,\n GetParam().protocol);\n server_->AddDefaultHandlers();\n server_->SetConnectionListener(&connection_listener_);\n }\n\n void TearDown() override {\n if (server_->Started())\n ASSERT_TRUE(server_->ShutdownAndWaitUntilComplete());\n }\n\n // Handles |request| sent to |path| and returns the response per |content|,\n // |content type|, and |code|. Saves the request URL for verification.\n std::unique_ptr<HttpResponse> HandleRequest(const std::string& path,\n const std::string& content,\n const std::string& content_type,\n HttpStatusCode code,\n const HttpRequest& request) {\n request_relative_url_ = request.relative_url;\n request_absolute_url_ = request.GetURL();\n\n if (request_absolute_url_.path() == path) {\n auto http_response = std::make_unique<BasicHttpResponse>();\n http_response->set_code(code);\n http_response->set_content(content);\n http_response->set_content_type(content_type);\n return http_response;\n }\n\n return nullptr;\n }\n\n protected:\n std::string request_relative_url_;\n GURL request_absolute_url_;\n std::unique_ptr<URLRequestContext> context_;\n TestConnectionListener connection_listener_;\n std::unique_ptr<EmbeddedTestServer> server_;\n base::OnceClosure quit_run_loop_;\n};\n\nTEST_P(EmbeddedTestServerTest, GetBaseURL) {\n ASSERT_TRUE(server_->Start());\n if (GetParam().type == EmbeddedTestServer::TYPE_HTTPS) {\n EXPECT_EQ(base::StringPrintf(\"https://127.0.0.1:%u/\", server_->port()),\n server_->base_url().spec());\n } else {\n EXPECT_EQ(base::StringPrintf(\"http://127.0.0.1:%u/\", server_->port()),\n server_->base_url().spec());\n }\n}\n\nTEST_P(EmbeddedTestServerTest, GetURL) {\n ASSERT_TRUE(server_->Start());\n if (GetParam().type == EmbeddedTestServer::TYPE_HTTPS) {\n EXPECT_EQ(base::StringPrintf(\"https://127.0.0.1:%u/path?query=foo\",\n server_->port()),\n server_->GetURL(\"/path?query=foo\").spec());\n } else {\n EXPECT_EQ(base::StringPrintf(\"http://127.0.0.1:%u/path?query=foo\",\n server_->port()),\n server_->GetURL(\"/path?query=foo\").spec());\n }\n}\n\nTEST_P(EmbeddedTestServerTest, GetURLWithHostname) {\n ASSERT_TRUE(server_->Start());\n if (GetParam().type == EmbeddedTestServer::TYPE_HTTPS) {\n EXPECT_EQ(base::StringPrintf(\"https://foo.com:%d/path?query=foo\",\n server_->port()),\n server_->GetURL(\"foo.com\", \"/path?query=foo\").spec());\n } else {\n EXPECT_EQ(\n base::StringPrintf(\"http://foo.com:%d/path?query=foo\", server_->port()),\n server_->GetURL(\"foo.com\", \"/path?query=foo\").spec());\n }\n}\n\nTEST_P(EmbeddedTestServerTest, RegisterRequestHandler) {\n server_->RegisterRequestHandler(base::BindRepeating(\n &EmbeddedTestServerTest::HandleRequest, base::Unretained(this), \"/test\",\n \"<b>Worked!</b>\", \"text/html\", HTTP_OK));\n ASSERT_TRUE(server_->Start());\n\n TestDelegate delegate;\n std::unique_ptr<URLRequest> request(\n context_->CreateRequest(server_->GetURL(\"/test?q=foo\"), DEFAULT_PRIORITY,\n &delegate, TRAFFIC_ANNOTATION_FOR_TESTS));\n\n request->Start();\n delegate.RunUntilComplete();\n\n EXPECT_EQ(net::OK, delegate.request_status());\n ASSERT_TRUE(request->response_headers());\n EXPECT_EQ(HTTP_OK, request->response_headers()->response_code());\n EXPECT_EQ(\"<b>Worked!</b>\", delegate.data_received());\n std::string content_type;\n ASSERT_TRUE(request->response_headers()->GetNormalizedHeader(\"Content-Type\",\n &content_type));\n EXPECT_EQ(\"text/html\", content_type);\n\n EXPECT_EQ(\"/test?q=foo\", request_relative_url_);\n EXPECT_EQ(server_->GetURL(\"/test?q=foo\"), request_absolute_url_);\n}\n\nTEST_P(EmbeddedTestServerTest, ServeFilesFromDirectory) {\n base::FilePath src_dir;\n ASSERT_TRUE(base::PathService::Get(base::DIR_SRC_TEST_DATA_ROOT, &src_dir));\n server_->ServeFilesFromDirectory(\n src_dir.AppendASCII(\"net\").AppendASCII(\"data\"));\n ASSERT_TRUE(server_->Start());\n\n TestDelegate delegate;\n std::unique_ptr<URLRequest> request(\n context_->CreateRequest(server_->GetURL(\"/test.html\"), DEFAULT_PRIORITY,\n &delegate, TRAFFIC_ANNOTATION_FOR_TESTS));\n\n request->Start();\n delegate.RunUntilComplete();\n\n EXPECT_EQ(net::OK, delegate.request_status());\n ASSERT_TRUE(request->response_headers());\n EXPECT_EQ(HTTP_OK, request->response_headers()->response_code());\n EXPECT_EQ(\"<p>Hello World!</p>\", delegate.data_received());\n std::string content_type;\n ASSERT_TRUE(request->response_headers()->GetNormalizedHeader(\"Content-Type\",\n &content_type));\n EXPECT_EQ(\"text/html\", content_type);\n}\n\nTEST_P(EmbeddedTestServerTest, MockHeadersWithoutCRLF) {\n // Messing with raw headers isn't compatible with HTTP/2\n if (GetParam().protocol == HttpConnection::Protocol::kHttp2)\n return;\n\n base::FilePath src_dir;\n ASSERT_TRUE(base::PathService::Get(base::DIR_SRC_TEST_DATA_ROOT, &src_dir));\n server_->ServeFilesFromDirectory(\n src_dir.AppendASCII(\"net\").AppendASCII(\"data\").AppendASCII(\n \"embedded_test_server\"));\n ASSERT_TRUE(server_->Start());\n\n TestDelegate delegate;\n std::unique_ptr<URLRequest> request(context_->CreateRequest(\n server_->GetURL(\"/mock-headers-without-crlf.html\"), DEFAULT_PRIORITY,\n &delegate, TRAFFIC_ANNOTATION_FOR_TESTS));\n\n request->Start();\n delegate.RunUntilComplete();\n\n EXPECT_EQ(net::OK, delegate.request_status());\n ASSERT_TRUE(request->response_headers());\n EXPECT_EQ(HTTP_OK, request->response_headers()->response_code());\n EXPECT_EQ(\"<p>Hello World!</p>\", delegate.data_received());\n std::string content_type;\n ASSERT_TRUE(request->response_headers()->GetNormalizedHeader(\"Content-Type\",\n &content_type));\n EXPECT_EQ(\"text/html\", content_type);\n}\n\nTEST_P(EmbeddedTestServerTest, DefaultNotFoundResponse) {\n ASSERT_TRUE(server_->Start());\n\n TestDelegate delegate;\n std::unique_ptr<URLRequest> request(context_->CreateRequest(\n server_->GetURL(\"/non-existent\"), DEFAULT_PRIORITY, &delegate,\n TRAFFIC_ANNOTATION_FOR_TESTS));\n\n request->Start();\n delegate.RunUntilComplete();\n\n EXPECT_EQ(net::OK, delegate.request_status());\n ASSERT_TRUE(request->response_headers());\n EXPECT_EQ(HTTP_NOT_FOUND, request->response_headers()->response_code());\n}\n\nTEST_P(EmbeddedTestServerTest, ConnectionListenerAccept) {\n ASSERT_TRUE(server_->Start());\n\n net::AddressList address_list;\n EXPECT_TRUE(server_->GetAddressList(&address_list));\n\n std::unique_ptr<StreamSocket> socket =\n ClientSocketFactory::GetDefaultFactory()->CreateTransportClientSocket(\n address_list, nullptr, nullptr, NetLog::Get(), NetLogSource());\n TestCompletionCallback callback;\n ASSERT_THAT(callback.GetResult(socket->Connect(callback.callback())), IsOk());\n\n connection_listener_.WaitUntilFirstConnectionAccepted();\n\n EXPECT_EQ(1u, connection_listener_.SocketAcceptedCount());\n EXPECT_FALSE(connection_listener_.DidReadFromSocket());\n EXPECT_FALSE(connection_listener_.DidGetSocketOnComplete());\n}\n\nTEST_P(EmbeddedTestServerTest, ConnectionListenerRead) {\n ASSERT_TRUE(server_->Start());\n\n TestDelegate delegate;\n std::unique_ptr<URLRequest> request(context_->CreateRequest(\n server_->GetURL(\"/non-existent\"), DEFAULT_PRIORITY, &delegate,\n TRAFFIC_ANNOTATION_FOR_TESTS));\n\n request->Start();\n delegate.RunUntilComplete();\n\n EXPECT_EQ(1u, connection_listener_.SocketAcceptedCount());\n EXPECT_TRUE(connection_listener_.DidReadFromSocket());\n}\n\n// TODO(http://crbug.com/1166868): Flaky on ChromeOS.\n#if BUILDFLAG(IS_CHROMEOS) || BUILDFLAG(IS_LINUX)\n#define MAYBE_ConnectionListenerComplete DISABLED_ConnectionListenerComplete\n#else\n#define MAYBE_ConnectionListenerComplete ConnectionListenerComplete\n#endif\nTEST_P(EmbeddedTestServerTest, MAYBE_ConnectionListenerComplete) {\n // OnResponseCompletedSuccessfully() makes the assumption that a connection is\n // \"finished\" before the socket is closed, and in the case of HTTP/2 this is\n // not supported\n if (GetParam().protocol == HttpConnection::Protocol::kHttp2)\n return;\n\n ASSERT_TRUE(server_->Start());\n\n TestDelegate delegate;\n // Need to send a Keep-Alive response header since the EmbeddedTestServer only\n // invokes OnResponseCompletedSuccessfully() if the socket is still open, and\n // the network stack will close the socket if not reuable, resulting in\n // potentially racilly closing the socket before\n // OnResponseCompletedSuccessfully() is invoked.\n std::unique_ptr<URLRequest> request(context_->CreateRequest(\n server_->GetURL(\"/set-header?Connection: Keep-Alive\"), DEFAULT_PRIORITY,\n &delegate, TRAFFIC_ANNOTATION_FOR_TESTS));\n\n request->Start();\n delegate.RunUntilComplete();\n\n EXPECT_EQ(1u, connection_listener_.SocketAcceptedCount());\n EXPECT_TRUE(connection_listener_.DidReadFromSocket());\n\n connection_listener_.WaitUntilGotSocketFromResponseCompleted();\n EXPECT_TRUE(connection_listener_.DidGetSocketOnComplete());\n}\n\nTEST_P(EmbeddedTestServerTest, ConcurrentFetches) {\n server_->RegisterRequestHandler(base::BindRepeating(\n &EmbeddedTestServerTest::HandleRequest, base::Unretained(this), \"/test1\",\n \"Raspberry chocolate\", \"text/html\", HTTP_OK));\n server_->RegisterRequestHandler(base::BindRepeating(\n &EmbeddedTestServerTest::HandleRequest, base::Unretained(this), \"/test2\",\n \"Vanilla chocolate\", \"text/html\", HTTP_OK));\n server_->RegisterRequestHandler(base::BindRepeating(\n &EmbeddedTestServerTest::HandleRequest, base::Unretained(this), \"/test3\",\n \"No chocolates\", \"text/plain\", HTTP_NOT_FOUND));\n ASSERT_TRUE(server_->Start());\n\n TestDelegate delegate1;\n std::unique_ptr<URLRequest> request1(\n context_->CreateRequest(server_->GetURL(\"/test1\"), DEFAULT_PRIORITY,\n &delegate1, TRAFFIC_ANNOTATION_FOR_TESTS));\n TestDelegate delegate2;\n std::unique_ptr<URLRequest> request2(\n context_->CreateRequest(server_->GetURL(\"/test2\"), DEFAULT_PRIORITY,\n &delegate2, TRAFFIC_ANNOTATION_FOR_TESTS));\n TestDelegate delegate3;\n std::unique_ptr<URLRequest> request3(\n context_->CreateRequest(server_->GetURL(\"/test3\"), DEFAULT_PRIORITY,\n &delegate3, TRAFFIC_ANNOTATION_FOR_TESTS));\n\n // Fetch the three URLs concurrently. Have to manually create RunLoops when\n // running multiple requests simultaneously, to avoid the deprecated\n // RunUntilIdle() path.\n base::RunLoop run_loop1;\n base::RunLoop run_loop2;\n base::RunLoop run_loop3;\n delegate1.set_on_complete(run_loop1.QuitClosure());\n delegate2.set_on_complete(run_loop2.QuitClosure());\n delegate3.set_on_complete(run_loop3.QuitClosure());\n request1->Start();\n request2->Start();\n request3->Start();\n run_loop1.Run();\n run_loop2.Run();\n run_loop3.Run();\n\n EXPECT_EQ(net::OK, delegate2.request_status());\n ASSERT_TRUE(request1->response_headers());\n EXPECT_EQ(HTTP_OK, request1->response_headers()->response_code());\n EXPECT_EQ(\"Raspberry chocolate\", delegate1.data_received());\n std::string content_type1;\n ASSERT_TRUE(request1->response_headers()->GetNormalizedHeader(\n \"Content-Type\", &content_type1));\n EXPECT_EQ(\"text/html\", content_type1);\n\n EXPECT_EQ(net::OK, delegate2.request_status());\n ASSERT_TRUE(request2->response_headers());\n EXPECT_EQ(HTTP_OK, request2->response_headers()->response_code());\n EXPECT_EQ(\"Vanilla chocolate\", delegate2.data_received());\n std::string content_type2;\n ASSERT_TRUE(request2->response_headers()->GetNormalizedHeader(\n \"Content-Type\", &content_type2));\n EXPECT_EQ(\"text/html\", content_type2);\n\n EXPECT_EQ(net::OK, delegate3.request_status());\n ASSERT_TRUE(request3->response_headers());\n EXPECT_EQ(HTTP_NOT_FOUND, request3->response_headers()->response_code());\n EXPECT_EQ(\"No chocolates\", delegate3.data_received());\n std::string content_type3;\n ASSERT_TRUE(request3->response_headers()->GetNormalizedHeader(\n \"Content-Type\", &content_type3));\n EXPECT_EQ(\"text/plain\", content_type3);\n}\n\nnamespace {\n\nclass CancelRequestDelegate : public TestDelegate {\n public:\n CancelRequestDelegate() { set_on_complete(base::DoNothing()); }\n\n CancelRequestDelegate(const CancelRequestDelegate&) = delete;\n CancelRequestDelegate& operator=(const CancelRequestDelegate&) = delete;\n\n ~CancelRequestDelegate() override = default;\n\n void OnResponseStarted(URLRequest* request, int net_error) override {\n TestDelegate::OnResponseStarted(request, net_error);\n base::ThreadTaskRunnerHandle::Get()->PostDelayedTask(\n FROM_HERE, run_loop_.QuitClosure(), base::Seconds(1));\n }\n\n void WaitUntilDone() { run_loop_.Run(); }\n\n private:\n base::RunLoop run_loop_;\n};\n\nclass InfiniteResponse : public BasicHttpResponse {\n public:\n InfiniteResponse() = default;\n\n InfiniteResponse(const InfiniteResponse&) = delete;\n InfiniteResponse& operator=(const InfiniteResponse&) = delete;\n\n void SendResponse(base::WeakPtr<HttpResponseDelegate> delegate) override {\n delegate->SendResponseHeaders(code(), GetHttpReasonPhrase(code()),\n BuildHeaders());\n SendInfinite(delegate);\n }\n\n private:\n void SendInfinite(base::WeakPtr<HttpResponseDelegate> delegate) {\n delegate->SendContents(\"echo\", base::DoNothing());\n base::ThreadTaskRunnerHandle::Get()->PostTask(\n FROM_HERE, base::BindOnce(&InfiniteResponse::SendInfinite,\n weak_ptr_factory_.GetWeakPtr(), delegate));\n }\n\n base::WeakPtrFactory<InfiniteResponse> weak_ptr_factory_{this};\n};\n\nstd::unique_ptr<HttpResponse> HandleInfiniteRequest(\n const HttpRequest& request) {\n return std::make_unique<InfiniteResponse>();\n}\n\n} // anonymous namespace\n\n// Tests the case the connection is closed while the server is sending a\n// response. May non-deterministically end up at one of three paths\n// (Discover the close event synchronously, asynchronously, or server\n// shutting down before it is discovered).\nTEST_P(EmbeddedTestServerTest, CloseDuringWrite) {\n CancelRequestDelegate cancel_delegate;\n cancel_delegate.set_cancel_in_response_started(true);\n server_->RegisterRequestHandler(\n base::BindRepeating(&HandlePrefixedRequest, \"/infinite\",\n base::BindRepeating(&HandleInfiniteRequest)));\n ASSERT_TRUE(server_->Start());\n\n std::unique_ptr<URLRequest> request =\n context_->CreateRequest(server_->GetURL(\"/infinite\"), DEFAULT_PRIORITY,\n &cancel_delegate, TRAFFIC_ANNOTATION_FOR_TESTS);\n request->Start();\n cancel_delegate.WaitUntilDone();\n}\n\nconst struct CertificateValuesEntry {\n const EmbeddedTestServer::ServerCertificate server_cert;\n const bool is_expired;\n const char* common_name;\n const char* issuer_common_name;\n size_t certs_count;\n} kCertificateValuesEntry[] = {\n {EmbeddedTestServer::CERT_OK, false, \"127.0.0.1\", \"Test Root CA\", 1},\n {EmbeddedTestServer::CERT_OK_BY_INTERMEDIATE, false, \"127.0.0.1\",\n \"Test Intermediate CA\", 2},\n {EmbeddedTestServer::CERT_MISMATCHED_NAME, false, \"127.0.0.1\",\n \"Test Root CA\", 1},\n {EmbeddedTestServer::CERT_COMMON_NAME_IS_DOMAIN, false, \"localhost\",\n \"Test Root CA\", 1},\n {EmbeddedTestServer::CERT_EXPIRED, true, \"127.0.0.1\", \"Test Root CA\", 1},\n};\n\nTEST_P(EmbeddedTestServerTest, GetCertificate) {\n if (GetParam().type != EmbeddedTestServer::TYPE_HTTPS)\n return;\n\n for (const auto& cert_entry : kCertificateValuesEntry) {\n SCOPED_TRACE(cert_entry.server_cert);\n server_->SetSSLConfig(cert_entry.server_cert);\n scoped_refptr<X509Certificate> cert = server_->GetCertificate();\n ASSERT_TRUE(cert);\n EXPECT_EQ(cert->HasExpired(), cert_entry.is_expired);\n EXPECT_EQ(cert->subject().common_name, cert_entry.common_name);\n EXPECT_EQ(cert->issuer().common_name, cert_entry.issuer_common_name);\n EXPECT_EQ(cert->intermediate_buffers().size(), cert_entry.certs_count - 1);\n }\n}\n\nTEST_P(EmbeddedTestServerTest, AcceptCHFrame) {\n // The ACCEPT_CH frame is only supported for HTTP/2 connections\n if (GetParam().protocol == HttpConnection::Protocol::kHttp1)\n return;\n\n server_->SetAlpsAcceptCH(\"\", \"foo\");\n server_->SetSSLConfig(net::EmbeddedTestServer::CERT_OK);\n\n ASSERT_TRUE(server_->Start());\n\n TestDelegate delegate;\n std::unique_ptr<URLRequest> request_a(context_->CreateRequest(\n server_->GetURL(\"/non-existent\"), DEFAULT_PRIORITY, &delegate,\n TRAFFIC_ANNOTATION_FOR_TESTS));\n request_a->Start();\n delegate.RunUntilComplete();\n\n EXPECT_EQ(1u, delegate.transports().size());\n EXPECT_EQ(\"foo\", delegate.transports().back().accept_ch_frame);\n}\n\nTEST_P(EmbeddedTestServerTest, AcceptCHFrameDifferentOrigins) {\n // The ACCEPT_CH frame is only supported for HTTP/2 connections\n if (GetParam().protocol == HttpConnection::Protocol::kHttp1)\n return;\n\n server_->SetAlpsAcceptCH(\"a.test\", \"a\");\n server_->SetAlpsAcceptCH(\"b.test\", \"b\");\n server_->SetAlpsAcceptCH(\"c.b.test\", \"c\");\n server_->SetSSLConfig(net::EmbeddedTestServer::CERT_TEST_NAMES);\n\n ASSERT_TRUE(server_->Start());\n\n {\n TestDelegate delegate;\n std::unique_ptr<URLRequest> request_a(context_->CreateRequest(\n server_->GetURL(\"a.test\", \"/non-existent\"), DEFAULT_PRIORITY, &delegate,\n TRAFFIC_ANNOTATION_FOR_TESTS));\n request_a->Start();\n delegate.RunUntilComplete();\n\n EXPECT_EQ(1u, delegate.transports().size());\n EXPECT_EQ(\"a\", delegate.transports().back().accept_ch_frame);\n }\n\n {\n TestDelegate delegate;\n std::unique_ptr<URLRequest> request_a(context_->CreateRequest(\n server_->GetURL(\"b.test\", \"/non-existent\"), DEFAULT_PRIORITY, &delegate,\n TRAFFIC_ANNOTATION_FOR_TESTS));\n request_a->Start();\n delegate.RunUntilComplete();\n\n EXPECT_EQ(1u, delegate.transports().size());\n EXPECT_EQ(\"b\", delegate.transports().back().accept_ch_frame);\n }\n\n {\n TestDelegate delegate;\n std::unique_ptr<URLRequest> request_a(context_->CreateRequest(\n server_->GetURL(\"c.b.test\", \"/non-existent\"), DEFAULT_PRIORITY,\n &delegate, TRAFFIC_ANNOTATION_FOR_TESTS));\n request_a->Start();\n delegate.RunUntilComplete();\n\n EXPECT_EQ(1u, delegate.transports().size());\n EXPECT_EQ(\"c\", delegate.transports().back().accept_ch_frame);\n }\n}\n\nINSTANTIATE_TEST_SUITE_P(EmbeddedTestServerTestInstantiation,\n EmbeddedTestServerTest,\n testing::ValuesIn(EmbeddedTestServerConfigs()));\n// Below test exercises EmbeddedTestServer's ability to cope with the situation\n// where there is no MessageLoop available on the thread at EmbeddedTestServer\n// initialization and/or destruction.\n\ntypedef std::tuple<bool, bool, EmbeddedTestServerConfig> ThreadingTestParams;\n\nclass EmbeddedTestServerThreadingTest\n : public testing::TestWithParam<ThreadingTestParams>,\n public WithTaskEnvironment {};\n\nclass EmbeddedTestServerThreadingTestDelegate\n : public base::PlatformThread::Delegate {\n public:\n EmbeddedTestServerThreadingTestDelegate(\n bool message_loop_present_on_initialize,\n bool message_loop_present_on_shutdown,\n EmbeddedTestServerConfig config)\n : message_loop_present_on_initialize_(message_loop_present_on_initialize),\n message_loop_present_on_shutdown_(message_loop_present_on_shutdown),\n type_(config.type),\n protocol_(config.protocol) {}\n\n EmbeddedTestServerThreadingTestDelegate(\n const EmbeddedTestServerThreadingTestDelegate&) = delete;\n EmbeddedTestServerThreadingTestDelegate& operator=(\n const EmbeddedTestServerThreadingTestDelegate&) = delete;\n\n // base::PlatformThread::Delegate:\n void ThreadMain() override {\n std::unique_ptr<base::SingleThreadTaskExecutor> executor;\n if (message_loop_present_on_initialize_) {\n executor = std::make_unique<base::SingleThreadTaskExecutor>(\n base::MessagePumpType::IO);\n }\n\n // Create the test server instance.\n EmbeddedTestServer server(type_, protocol_);\n base::FilePath src_dir;\n ASSERT_TRUE(base::PathService::Get(base::DIR_SRC_TEST_DATA_ROOT, &src_dir));\n ASSERT_TRUE(server.Start());\n\n // Make a request and wait for the reply.\n if (!executor) {\n executor = std::make_unique<base::SingleThreadTaskExecutor>(\n base::MessagePumpType::IO);\n }\n\n auto context = CreateTestURLRequestContextBuilder()->Build();\n TestDelegate delegate;\n std::unique_ptr<URLRequest> request(\n context->CreateRequest(server.GetURL(\"/test?q=foo\"), DEFAULT_PRIORITY,\n &delegate, TRAFFIC_ANNOTATION_FOR_TESTS));\n\n request->Start();\n delegate.RunUntilComplete();\n request.reset();\n // Flush the socket pool on the same thread by destroying the context.\n context.reset();\n\n // Shut down.\n if (message_loop_present_on_shutdown_)\n executor.reset();\n\n ASSERT_TRUE(server.ShutdownAndWaitUntilComplete());\n }\n\n private:\n const bool message_loop_present_on_initialize_;\n const bool message_loop_present_on_shutdown_;\n const EmbeddedTestServer::Type type_;\n const HttpConnection::Protocol protocol_;\n};\n\nTEST_P(EmbeddedTestServerThreadingTest, RunTest) {\n // The actual test runs on a separate thread so it can screw with the presence\n // of a MessageLoop - the test suite already sets up a MessageLoop for the\n // main test thread.\n base::PlatformThreadHandle thread_handle;\n EmbeddedTestServerThreadingTestDelegate delegate(std::get<0>(GetParam()),\n std::get<1>(GetParam()),\n std::get<2>(GetParam()));\n ASSERT_TRUE(base::PlatformThread::Create(0, &delegate, &thread_handle));\n base::PlatformThread::Join(thread_handle);\n}\n\nINSTANTIATE_TEST_SUITE_P(\n EmbeddedTestServerThreadingTestInstantiation,\n EmbeddedTestServerThreadingTest,\n testing::Combine(testing::Bool(),\n testing::Bool(),\n testing::ValuesIn(EmbeddedTestServerConfigs())));\n\n} // namespace net::test_server\n"
}
}