embedded_test_server.h revision f2477e01787aa58f445919b809d89e252beef54f
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. 4 5#ifndef NET_TEST_EMBEDDED_TEST_SERVER_EMBEDDED_TEST_SERVER_H_ 6#define NET_TEST_EMBEDDED_TEST_SERVER_EMBEDDED_TEST_SERVER_H_ 7 8#include <map> 9#include <string> 10#include <vector> 11 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" 20#include "url/gurl.h" 21 22namespace base { 23class FilePath; 24} 25 26namespace net { 27namespace test_server { 28 29class HttpConnection; 30class HttpResponse; 31struct HttpRequest; 32 33// This class is required to be able to have composition instead of inheritance, 34class HttpListenSocket : public TCPListenSocket { 35 public: 36 HttpListenSocket(const SocketDescriptor socket_descriptor, 37 StreamListenSocket::Delegate* delegate); 38 virtual ~HttpListenSocket(); 39 virtual void Listen(); 40 41 private: 42 43 base::ThreadChecker thread_checker_; 44}; 45 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. 50// 51// The common use case is below: 52// 53// base::Thread io_thread_; 54// scoped_ptr<EmbeddedTestServer> test_server_; 55// 56// void SetUp() { 57// base::Thread::Options thread_options; 58// thread_options.message_loop_type = base::MessageLoop::TYPE_IO; 59// ASSERT_TRUE(io_thread_.StartWithOptions(thread_options)); 60// 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))); 66// } 67// 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>(); 72// 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(); 78// } 79// 80class EmbeddedTestServer : public StreamListenSocket::Delegate { 81 public: 82 typedef base::Callback<scoped_ptr<HttpResponse>( 83 const HttpRequest& request)> HandleRequestCallback; 84 85 // Creates a http test server. InitializeAndWaitUntilReady() must be called 86 // to start the server. 87 EmbeddedTestServer(); 88 virtual ~EmbeddedTestServer(); 89 90 // Initializes and waits until the server is ready to accept requests. 91 bool InitializeAndWaitUntilReady() WARN_UNUSED_RESULT; 92 93 // Shuts down the http server and waits until the shutdown is complete. 94 bool ShutdownAndWaitUntilComplete() WARN_UNUSED_RESULT; 95 96 // Checks if the server is started. 97 bool Started() const { 98 return listen_socket_.get() != NULL; 99 } 100 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 103 // the server. 104 const GURL& base_url() const { return base_url_; } 105 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; 110 111 // Returns the port number used by the server. 112 int port() const { return port_; } 113 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); 119 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 122 // on UI thread. 123 void RegisterRequestHandler(const HandleRequestCallback& callback); 124 125 private: 126 // Initializes and starts the server. If initialization succeeds, Starts() 127 // will return true. 128 void InitializeOnIOThread(); 129 130 // Shuts down the server. 131 void ShutdownOnIOThread(); 132 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); 137 138 // StreamListenSocket::Delegate overrides: 139 virtual void DidAccept(StreamListenSocket* server, 140 scoped_ptr<StreamListenSocket> connection) OVERRIDE; 141 virtual void DidRead(StreamListenSocket* connection, 142 const char* data, 143 int length) OVERRIDE; 144 virtual void DidClose(StreamListenSocket* connection) OVERRIDE; 145 146 HttpConnection* FindConnection(StreamListenSocket* socket); 147 148 // Posts a task to the |io_thread_| and waits for a reply. 149 bool PostTaskToIOThreadAndWait( 150 const base::Closure& closure) WARN_UNUSED_RESULT; 151 152 scoped_ptr<base::Thread> io_thread_; 153 154 scoped_ptr<HttpListenSocket> listen_socket_; 155 int port_; 156 GURL base_url_; 157 158 // Owns the HttpConnection objects. 159 std::map<StreamListenSocket*, HttpConnection*> connections_; 160 161 // Vector of registered request handlers. 162 std::vector<HandleRequestCallback> request_handlers_; 163 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_; 167 168 base::ThreadChecker thread_checker_; 169 170 DISALLOW_COPY_AND_ASSIGN(EmbeddedTestServer); 171}; 172 173} // namespace test_servers 174} // namespace net 175 176#endif // NET_TEST_EMBEDDED_TEST_SERVER_EMBEDDED_TEST_SERVER_H_ 177