xref: /aosp_15_r20/external/cronet/net/test/embedded_test_server/simple_connection_listener.h (revision 6777b5387eb2ff775bb5750e3f5d96f37fb7352b)
1 // Copyright 2017 The Chromium Authors
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_SIMPLE_CONNECTION_LISTENER_H_
6 #define NET_TEST_EMBEDDED_TEST_SERVER_SIMPLE_CONNECTION_LISTENER_H_
7 
8 #include "base/run_loop.h"
9 #include "net/test/embedded_test_server/embedded_test_server_connection_listener.h"
10 
11 namespace net {
12 
13 class StreamSocket;
14 
15 namespace test_server {
16 
17 // Waits for a specified number of connection attempts to be seen.
18 class SimpleConnectionListener : public EmbeddedTestServerConnectionListener {
19  public:
20   enum AllowAdditionalConnections {
21     // Add an expect failure if more than the specified number of connections
22     // are seen.
23     FAIL_ON_ADDITIONAL_CONNECTIONS,
24     // Silently ignores extra connection attempts.
25     ALLOW_ADDITIONAL_CONNECTIONS
26   };
27 
28   // A connection listener that waits for the specified number of total
29   // connections when WaitForConnections() is called.  Must be created on a
30   // thread with a SingleThreadedTaskRunner.
31   SimpleConnectionListener(
32       int expected_connections,
33       AllowAdditionalConnections allow_additional_connections);
34 
35   SimpleConnectionListener(const SimpleConnectionListener&) = delete;
36   SimpleConnectionListener& operator=(const SimpleConnectionListener&) = delete;
37 
38   // Must be torn down only after the EmbeddedTestServer it's attached to is
39   // shut down.
40   ~SimpleConnectionListener() override;
41 
42   std::unique_ptr<StreamSocket> AcceptedSocket(
43       std::unique_ptr<StreamSocket> socket) override;
44   void ReadFromSocket(const StreamSocket& socket, int rv) override;
45   void OnResponseCompletedSuccessfully(
46       std::unique_ptr<StreamSocket> socket) override;
47 
48   // Wait until the expected number of connections have been seen.
49   void WaitForConnections();
50 
51  private:
52   int seen_connections_ = 0;
53 
54   const int expected_connections_;
55   const AllowAdditionalConnections allow_additional_connections_;
56 
57   base::RunLoop run_loop_;
58 };
59 
60 }  // namespace test_server
61 }  // namespace net
62 
63 #endif  // NET_TEST_EMBEDDED_TEST_SERVER_SIMPLE_CONNECTION_LISTENER_H_
64