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/base/address_list.h"
20 #include "net/test/embedded_test_server/tcp_listen_socket.h"
28 namespace test_server
{
30 class EmbeddedTestServerConnectionListener
;
35 // This class is required to be able to have composition instead of inheritance,
36 class HttpListenSocket
: public TCPListenSocket
{
38 HttpListenSocket(const SocketDescriptor socket_descriptor
,
39 StreamListenSocket::Delegate
* delegate
);
40 ~HttpListenSocket() override
;
41 virtual void Listen();
43 // Listen on the current IO thread. If the IO thread has changed since this
44 // object is constructed, call |ListenOnIOThread| to make sure it listens on
45 // the right thread. Otherwise must call |Listen| instead.
46 void ListenOnIOThread();
49 friend class EmbeddedTestServer
;
51 // Detaches the current from |thread_checker_|.
52 void DetachFromThread();
54 base::ThreadChecker thread_checker_
;
57 // Class providing an HTTP server for testing purpose. This is a basic server
58 // providing only an essential subset of HTTP/1.1 protocol. Especially,
59 // it assumes that the request syntax is correct. It *does not* support
60 // a Chunked Transfer Encoding.
62 // The common use case for unit tests is below:
65 // test_server_.reset(new EmbeddedTestServer());
66 // ASSERT_TRUE(test_server_.InitializeAndWaitUntilReady());
67 // test_server_->RegisterRequestHandler(
68 // base::Bind(&FooTest::HandleRequest, base::Unretained(this)));
71 // scoped_ptr<HttpResponse> HandleRequest(const HttpRequest& request) {
72 // GURL absolute_url = test_server_->GetURL(request.relative_url);
73 // if (absolute_url.path() != "/test")
74 // return scoped_ptr<HttpResponse>();
76 // scoped_ptr<BasicHttpResponse> http_response(new BasicHttpResponse());
77 // http_response->set_code(test_server::SUCCESS);
78 // http_response->set_content("hello");
79 // http_response->set_content_type("text/plain");
80 // return http_response.Pass();
83 // For a test that spawns another process such as browser_tests, it is
84 // suggested to call InitializeAndWaitUntilReady in SetUpOnMainThread after
85 // the process is spawned. If you have to do it before the process spawns,
86 // you need to stop the server's thread so that there is no no other
87 // threads running while spawning the process. To do so, please follow
88 // the following example:
91 // ASSERT_TRUE(embedded_test_server()->InitializeAndWaitUntilReady());
92 // // EmbeddedTestServer spawns a thread to initialize socket.
93 // // Stop the thread in preparation for fork and exec.
94 // embedded_test_server()->StopThread();
96 // InProcessBrowserTest::SetUp();
99 // void SetUpOnMainThread() {
100 // embedded_test_server()->RestartThreadAndListen();
103 class EmbeddedTestServer
: public StreamListenSocket::Delegate
{
105 typedef base::Callback
<scoped_ptr
<HttpResponse
>(
106 const HttpRequest
& request
)> HandleRequestCallback
;
108 // Creates a http test server. InitializeAndWaitUntilReady() must be called
109 // to start the server.
110 EmbeddedTestServer();
111 ~EmbeddedTestServer() override
;
113 // Sets a connection listener, that would be notified when various connection
114 // events happen. May only be called before the server is started. Caller
115 // maintains ownership of the listener.
116 void SetConnectionListener(EmbeddedTestServerConnectionListener
* listener
);
118 // Initializes and waits until the server is ready to accept requests.
119 bool InitializeAndWaitUntilReady() WARN_UNUSED_RESULT
;
121 // Shuts down the http server and waits until the shutdown is complete.
122 bool ShutdownAndWaitUntilComplete() WARN_UNUSED_RESULT
;
124 // Checks if the server is started.
125 bool Started() const {
126 return listen_socket_
.get() != NULL
;
129 // Returns the base URL to the server, which looks like
130 // http://127.0.0.1:<port>/, where <port> is the actual port number used by
132 const GURL
& base_url() const { return base_url_
; }
134 // Returns a URL to the server based on the given relative URL, which
135 // should start with '/'. For example: GetURL("/path?query=foo") =>
136 // http://127.0.0.1:<port>/path?query=foo.
137 GURL
GetURL(const std::string
& relative_url
) const;
139 // Similar to the above method with the difference that it uses the supplied
140 // |hostname| for the URL instead of 127.0.0.1. The hostname should be
141 // resolved to 127.0.0.1.
142 GURL
GetURL(const std::string
& hostname
,
143 const std::string
& relative_url
) const;
145 // Returns the address list needed to connect to the server.
146 bool GetAddressList(net::AddressList
* address_list
) const WARN_UNUSED_RESULT
;
148 // Returns the port number used by the server.
149 uint16
port() const { return port_
; }
151 // Registers request handler which serves files from |directory|.
152 // For instance, a request to "/foo.html" is served by "foo.html" under
153 // |directory|. Files under sub directories are also handled in the same way
154 // (i.e. "/foo/bar.html" is served by "foo/bar.html" under |directory|).
155 void ServeFilesFromDirectory(const base::FilePath
& directory
);
157 // The most general purpose method. Any request processing can be added using
158 // this method. Takes ownership of the object. The |callback| is called
160 void RegisterRequestHandler(const HandleRequestCallback
& callback
);
162 // Stops IO thread that handles http requests.
165 // Restarts IO thread and listen on the socket.
166 void RestartThreadAndListen();
171 // Initializes and starts the server. If initialization succeeds, Starts()
173 void InitializeOnIOThread();
174 void ListenOnIOThread();
176 // Shuts down the server.
177 void ShutdownOnIOThread();
179 // Handles a request when it is parsed. It passes the request to registed
180 // request handlers and sends a http response.
181 void HandleRequest(HttpConnection
* connection
,
182 scoped_ptr
<HttpRequest
> request
);
184 // StreamListenSocket::Delegate overrides:
185 void DidAccept(StreamListenSocket
* server
,
186 scoped_ptr
<StreamListenSocket
> connection
) override
;
187 void DidRead(StreamListenSocket
* connection
,
189 int length
) override
;
190 void DidClose(StreamListenSocket
* connection
) override
;
192 HttpConnection
* FindConnection(StreamListenSocket
* socket
);
194 // Posts a task to the |io_thread_| and waits for a reply.
195 bool PostTaskToIOThreadAndWait(
196 const base::Closure
& closure
) WARN_UNUSED_RESULT
;
198 scoped_ptr
<base::Thread
> io_thread_
;
200 scoped_ptr
<HttpListenSocket
> listen_socket_
;
201 EmbeddedTestServerConnectionListener
* connection_listener_
;
205 // Owns the HttpConnection objects.
206 std::map
<StreamListenSocket
*, HttpConnection
*> connections_
;
208 // Vector of registered request handlers.
209 std::vector
<HandleRequestCallback
> request_handlers_
;
211 base::ThreadChecker thread_checker_
;
213 // Note: This should remain the last member so it'll be destroyed and
214 // invalidate its weak pointers before any other members are destroyed.
215 base::WeakPtrFactory
<EmbeddedTestServer
> weak_factory_
;
217 DISALLOW_COPY_AND_ASSIGN(EmbeddedTestServer
);
220 } // namespace test_server
223 #endif // NET_TEST_EMBEDDED_TEST_SERVER_EMBEDDED_TEST_SERVER_H_