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 virtual ~HttpListenSocket();
39 virtual void Listen();
43 base::ThreadChecker thread_checker_;
46 // Class providing an HTTP server for testing purpose. This is a basic server
47 // providing only an essential subset of HTTP/1.1 protocol. Especially,
48 // it assumes that the request syntax is correct. It *does not* support
49 // a Chunked Transfer Encoding.
51 // The common use case is below:
53 // base::Thread io_thread_;
54 // scoped_ptr<EmbeddedTestServer> test_server_;
57 // base::Thread::Options thread_options;
58 // thread_options.message_loop_type = base::MessageLoop::TYPE_IO;
59 // ASSERT_TRUE(io_thread_.StartWithOptions(thread_options));
61 // test_server_.reset(
62 // new EmbeddedTestServer(io_thread_.message_loop_proxy()));
63 // ASSERT_TRUE(test_server_.InitializeAndWaitUntilReady());
64 // test_server_->RegisterRequestHandler(
65 // base::Bind(&FooTest::HandleRequest, base::Unretained(this)));
68 // scoped_ptr<HttpResponse> HandleRequest(const HttpRequest& request) {
69 // GURL absolute_url = test_server_->GetURL(request.relative_url);
70 // if (absolute_url.path() != "/test")
71 // return scoped_ptr<HttpResponse>();
73 // scoped_ptr<HttpResponse> http_response(new HttpResponse());
74 // http_response->set_code(test_server::SUCCESS);
75 // http_response->set_content("hello");
76 // http_response->set_content_type("text/plain");
77 // return http_response.Pass();
80 class EmbeddedTestServer : public StreamListenSocket::Delegate {
82 typedef base::Callback<scoped_ptr<HttpResponse>(
83 const HttpRequest& request)> HandleRequestCallback;
85 // Creates a http test server. InitializeAndWaitUntilReady() must be called
86 // to start the server.
88 virtual ~EmbeddedTestServer();
90 // Initializes and waits until the server is ready to accept requests.
91 bool InitializeAndWaitUntilReady() WARN_UNUSED_RESULT;
93 // Shuts down the http server and waits until the shutdown is complete.
94 bool ShutdownAndWaitUntilComplete() WARN_UNUSED_RESULT;
96 // Checks if the server is started.
97 bool Started() const {
98 return listen_socket_.get() != NULL;
101 // Returns the base URL to the server, which looks like
102 // http://127.0.0.1:<port>/, where <port> is the actual port number used by
104 const GURL& base_url() const { return base_url_; }
106 // Returns a URL to the server based on the given relative URL, which
107 // should start with '/'. For example: GetURL("/path?query=foo") =>
108 // http://127.0.0.1:<port>/path?query=foo.
109 GURL GetURL(const std::string& relative_url) const;
111 // Returns the port number used by the server.
112 int port() const { return port_; }
114 // Registers request handler which serves files from |directory|.
115 // For instance, a request to "/foo.html" is served by "foo.html" under
116 // |directory|. Files under sub directories are also handled in the same way
117 // (i.e. "/foo/bar.html" is served by "foo/bar.html" under |directory|).
118 void ServeFilesFromDirectory(const base::FilePath& directory);
120 // The most general purpose method. Any request processing can be added using
121 // this method. Takes ownership of the object. The |callback| is called
123 void RegisterRequestHandler(const HandleRequestCallback& callback);
126 // Initializes and starts the server. If initialization succeeds, Starts()
128 void InitializeOnIOThread();
130 // Shuts down the server.
131 void ShutdownOnIOThread();
133 // Handles a request when it is parsed. It passes the request to registed
134 // request handlers and sends a http response.
135 void HandleRequest(HttpConnection* connection,
136 scoped_ptr<HttpRequest> request);
138 // StreamListenSocket::Delegate overrides:
139 virtual void DidAccept(StreamListenSocket* server,
140 scoped_ptr<StreamListenSocket> connection) OVERRIDE;
141 virtual void DidRead(StreamListenSocket* connection,
143 int length) OVERRIDE;
144 virtual void DidClose(StreamListenSocket* connection) OVERRIDE;
146 HttpConnection* FindConnection(StreamListenSocket* socket);
148 // Posts a task to the |io_thread_| and waits for a reply.
149 bool PostTaskToIOThreadAndWait(
150 const base::Closure& closure) WARN_UNUSED_RESULT;
152 base::Thread io_thread_;
154 scoped_ptr<HttpListenSocket> listen_socket_;
158 // Owns the HttpConnection objects.
159 std::map<StreamListenSocket*, HttpConnection*> connections_;
161 // Vector of registered request handlers.
162 std::vector<HandleRequestCallback> request_handlers_;
164 // Note: This should remain the last member so it'll be destroyed and
165 // invalidate its weak pointers before any other members are destroyed.
166 base::WeakPtrFactory<EmbeddedTestServer> weak_factory_;
168 base::ThreadChecker thread_checker_;
170 DISALLOW_COPY_AND_ASSIGN(EmbeddedTestServer);
173 } // namespace test_servers
176 #endif // NET_TEST_EMBEDDED_TEST_SERVER_EMBEDDED_TEST_SERVER_H_