1 // Copyright (c) 2012 The Chromium Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
5 #ifndef NET_TEST_EMBEDDED_TEST_SERVER_EMBEDDED_TEST_SERVER_H_
6 #define NET_TEST_EMBEDDED_TEST_SERVER_EMBEDDED_TEST_SERVER_H_
12 #include "base/basictypes.h"
13 #include "base/callback.h"
14 #include "base/compiler_specific.h"
15 #include "base/memory/ref_counted.h"
16 #include "base/memory/weak_ptr.h"
17 #include "base/threading/thread.h"
18 #include "base/threading/thread_checker.h"
19 #include "net/socket/tcp_listen_socket.h"
27 namespace test_server
{
33 // This class is required to be able to have composition instead of inheritance,
34 class HttpListenSocket
: public TCPListenSocket
{
36 HttpListenSocket(const SocketDescriptor socket_descriptor
,
37 StreamListenSocket::Delegate
* delegate
);
38 ~HttpListenSocket() override
;
39 virtual void Listen();
41 // Listen on the current IO thread. If the IO thread has changed since this
42 // object is constructed, call |ListenOnIOThread| to make sure it listens on
43 // the right thread. Otherwise must call |Listen| instead.
44 void ListenOnIOThread();
47 friend class EmbeddedTestServer
;
49 // Detaches the current from |thread_checker_|.
50 void DetachFromThread();
52 base::ThreadChecker thread_checker_
;
55 // Class providing an HTTP server for testing purpose. This is a basic server
56 // providing only an essential subset of HTTP/1.1 protocol. Especially,
57 // it assumes that the request syntax is correct. It *does not* support
58 // a Chunked Transfer Encoding.
60 // The common use case for unit tests is below:
63 // test_server_.reset(new EmbeddedTestServer());
64 // ASSERT_TRUE(test_server_.InitializeAndWaitUntilReady());
65 // test_server_->RegisterRequestHandler(
66 // base::Bind(&FooTest::HandleRequest, base::Unretained(this)));
69 // scoped_ptr<HttpResponse> HandleRequest(const HttpRequest& request) {
70 // GURL absolute_url = test_server_->GetURL(request.relative_url);
71 // if (absolute_url.path() != "/test")
72 // return scoped_ptr<HttpResponse>();
74 // scoped_ptr<HttpResponse> http_response(new HttpResponse());
75 // http_response->set_code(test_server::SUCCESS);
76 // http_response->set_content("hello");
77 // http_response->set_content_type("text/plain");
78 // return http_response.Pass();
81 // For a test that spawns another process such as browser_tests, it is
82 // suggested to call InitializeAndWaitUntilReady in SetUpOnMainThread after
83 // the process is spawned. If you have to do it before the process spawns,
84 // you need to stop the server's thread so that there is no no other
85 // threads running while spawning the process. To do so, please follow
86 // the following example:
89 // ASSERT_TRUE(embedded_test_server()->InitializeAndWaitUntilReady());
90 // // EmbeddedTestServer spawns a thread to initialize socket.
91 // // Stop the thread in preparation for fork and exec.
92 // embedded_test_server()->StopThread();
94 // InProcessBrowserTest::SetUp();
97 // void SetUpOnMainThread() {
98 // embedded_test_server()->RestartThreadAndListen();
101 class EmbeddedTestServer
: public StreamListenSocket::Delegate
{
103 typedef base::Callback
<scoped_ptr
<HttpResponse
>(
104 const HttpRequest
& request
)> HandleRequestCallback
;
106 // Creates a http test server. InitializeAndWaitUntilReady() must be called
107 // to start the server.
108 EmbeddedTestServer();
109 ~EmbeddedTestServer() override
;
111 // Initializes and waits until the server is ready to accept requests.
112 bool InitializeAndWaitUntilReady() WARN_UNUSED_RESULT
;
114 // Shuts down the http server and waits until the shutdown is complete.
115 bool ShutdownAndWaitUntilComplete() WARN_UNUSED_RESULT
;
117 // Checks if the server is started.
118 bool Started() const {
119 return listen_socket_
.get() != NULL
;
122 // Returns the base URL to the server, which looks like
123 // http://127.0.0.1:<port>/, where <port> is the actual port number used by
125 const GURL
& base_url() const { return base_url_
; }
127 // Returns a URL to the server based on the given relative URL, which
128 // should start with '/'. For example: GetURL("/path?query=foo") =>
129 // http://127.0.0.1:<port>/path?query=foo.
130 GURL
GetURL(const std::string
& relative_url
) const;
132 // Similar to the above method with the difference that it uses the supplied
133 // |hostname| for the URL instead of 127.0.0.1. The hostname should be
134 // resolved to 127.0.0.1.
135 GURL
GetURL(const std::string
& hostname
,
136 const std::string
& relative_url
) const;
138 // Returns the port number used by the server.
139 uint16
port() const { return port_
; }
141 // Registers request handler which serves files from |directory|.
142 // For instance, a request to "/foo.html" is served by "foo.html" under
143 // |directory|. Files under sub directories are also handled in the same way
144 // (i.e. "/foo/bar.html" is served by "foo/bar.html" under |directory|).
145 void ServeFilesFromDirectory(const base::FilePath
& directory
);
147 // The most general purpose method. Any request processing can be added using
148 // this method. Takes ownership of the object. The |callback| is called
150 void RegisterRequestHandler(const HandleRequestCallback
& callback
);
152 // Stops IO thread that handles http requests.
155 // Restarts IO thread and listen on the socket.
156 void RestartThreadAndListen();
161 // Initializes and starts the server. If initialization succeeds, Starts()
163 void InitializeOnIOThread();
164 void ListenOnIOThread();
166 // Shuts down the server.
167 void ShutdownOnIOThread();
169 // Handles a request when it is parsed. It passes the request to registed
170 // request handlers and sends a http response.
171 void HandleRequest(HttpConnection
* connection
,
172 scoped_ptr
<HttpRequest
> request
);
174 // StreamListenSocket::Delegate overrides:
175 void DidAccept(StreamListenSocket
* server
,
176 scoped_ptr
<StreamListenSocket
> connection
) override
;
177 void DidRead(StreamListenSocket
* connection
,
179 int length
) override
;
180 void DidClose(StreamListenSocket
* connection
) override
;
182 HttpConnection
* FindConnection(StreamListenSocket
* socket
);
184 // Posts a task to the |io_thread_| and waits for a reply.
185 bool PostTaskToIOThreadAndWait(
186 const base::Closure
& closure
) WARN_UNUSED_RESULT
;
188 scoped_ptr
<base::Thread
> io_thread_
;
190 scoped_ptr
<HttpListenSocket
> listen_socket_
;
194 // Owns the HttpConnection objects.
195 std::map
<StreamListenSocket
*, HttpConnection
*> connections_
;
197 // Vector of registered request handlers.
198 std::vector
<HandleRequestCallback
> request_handlers_
;
200 base::ThreadChecker thread_checker_
;
202 // Note: This should remain the last member so it'll be destroyed and
203 // invalidate its weak pointers before any other members are destroyed.
204 base::WeakPtrFactory
<EmbeddedTestServer
> weak_factory_
;
206 DISALLOW_COPY_AND_ASSIGN(EmbeddedTestServer
);
209 } // namespace test_servers
212 #endif // NET_TEST_EMBEDDED_TEST_SERVER_EMBEDDED_TEST_SERVER_H_