xref: /aosp_15_r20/external/webrtc/test/run_loop.h (revision d9f758449e529ab9291ac668be2861e7a55c2422)
1 /*
2  *  Copyright (c) 2013 The WebRTC project authors. All Rights Reserved.
3  *
4  *  Use of this source code is governed by a BSD-style license
5  *  that can be found in the LICENSE file in the root of the source
6  *  tree. An additional intellectual property rights grant can be found
7  *  in the file PATENTS.  All contributing project authors may
8  *  be found in the AUTHORS file in the root of the source tree.
9  */
10 #ifndef TEST_RUN_LOOP_H_
11 #define TEST_RUN_LOOP_H_
12 
13 #include <utility>
14 
15 #include "absl/functional/any_invocable.h"
16 #include "api/task_queue/task_queue_base.h"
17 #include "rtc_base/thread.h"
18 
19 namespace webrtc {
20 namespace test {
21 
22 // This utility class allows you to run a TaskQueue supported interface on the
23 // main test thread, call Run() while doing things asynchonously and break
24 // the loop (from the same thread) from a callback by calling Quit().
25 class RunLoop {
26  public:
27   RunLoop();
28   ~RunLoop();
29 
30   TaskQueueBase* task_queue();
31 
32   void Run();
33   void Quit();
34 
35   void Flush();
36 
PostTask(absl::AnyInvocable<void ()&&> task)37   void PostTask(absl::AnyInvocable<void() &&> task) {
38     task_queue()->PostTask(std::move(task));
39   }
40 
41  private:
42   class FakeSocketServer : public rtc::SocketServer {
43    public:
44     FakeSocketServer();
45     ~FakeSocketServer();
46 
47     void FailNextWait();
48 
49    private:
50     bool Wait(webrtc::TimeDelta max_wait_duration, bool process_io) override;
51     void WakeUp() override;
52 
53     rtc::Socket* CreateSocket(int family, int type) override;
54 
55    private:
56     bool fail_next_wait_ = false;
57   };
58 
59   class WorkerThread : public rtc::Thread {
60    public:
61     explicit WorkerThread(rtc::SocketServer* ss);
62 
63    private:
64     CurrentTaskQueueSetter tq_setter_;
65   };
66 
67   FakeSocketServer socket_server_;
68   WorkerThread worker_thread_{&socket_server_};
69 };
70 
71 }  // namespace test
72 }  // namespace webrtc
73 
74 #endif  // TEST_RUN_LOOP_H_
75