1 // Copyright (c) 2013 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 CHROME_TEST_CHROMEDRIVER_NET_TEST_HTTP_SERVER_H_
6 #define CHROME_TEST_CHROMEDRIVER_NET_TEST_HTTP_SERVER_H_
10 #include "base/basictypes.h"
11 #include "base/compiler_specific.h"
12 #include "base/memory/ref_counted.h"
13 #include "base/synchronization/lock.h"
14 #include "base/synchronization/waitable_event.h"
15 #include "base/threading/thread.h"
16 #include "net/server/http_server.h"
23 // HTTP server for web socket testing purposes that runs on its own thread.
24 // All public methods are thread safe and may be called on any thread, unless
26 class TestHttpServer
: public net::HttpServer::Delegate
{
28 enum WebSocketRequestAction
{
34 enum WebSocketMessageAction
{
39 // Creates an http server. By default it accepts WebSockets and echoes
40 // WebSocket messages back.
42 ~TestHttpServer() override
;
44 // Starts the server. Returns whether it was started successfully.
47 // Stops the server. May be called multiple times.
50 // Waits until all open connections are closed. Returns true if all
51 // connections are closed, or false if a timeout is exceeded.
52 bool WaitForConnectionsToClose();
54 // Sets the action to perform when receiving a WebSocket connect request.
55 void SetRequestAction(WebSocketRequestAction action
);
57 // Sets the action to perform when receiving a WebSocket message.
58 void SetMessageAction(WebSocketMessageAction action
);
60 // Returns the web socket URL that points to the server.
61 GURL
web_socket_url() const;
63 // Overridden from net::HttpServer::Delegate:
64 void OnConnect(int connection_id
) override
;
65 void OnHttpRequest(int connection_id
,
66 const net::HttpServerRequestInfo
& info
) override
{}
67 void OnWebSocketRequest(int connection_id
,
68 const net::HttpServerRequestInfo
& info
) override
;
69 void OnWebSocketMessage(int connection_id
, const std::string
& data
) override
;
70 void OnClose(int connection_id
) override
;
73 void StartOnServerThread(bool* success
, base::WaitableEvent
* event
);
74 void StopOnServerThread(base::WaitableEvent
* event
);
78 // Access only on the server thread.
79 scoped_ptr
<net::HttpServer
> server_
;
81 // Access only on the server thread.
82 std::set
<int> connections_
;
84 base::WaitableEvent all_closed_event_
;
86 // Protects |web_socket_url_|.
87 mutable base::Lock url_lock_
;
90 // Protects the action flags.
91 base::Lock action_lock_
;
92 WebSocketRequestAction request_action_
;
93 WebSocketMessageAction message_action_
;
95 DISALLOW_COPY_AND_ASSIGN(TestHttpServer
);
98 #endif // CHROME_TEST_CHROMEDRIVER_NET_TEST_HTTP_SERVER_H_