1 // Copyright 2011 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 BASE_TEST_THREAD_TEST_HELPER_H_ 6 #define BASE_TEST_THREAD_TEST_HELPER_H_ 7 8 #include "base/memory/ref_counted.h" 9 #include "base/synchronization/waitable_event.h" 10 #include "base/task/sequenced_task_runner.h" 11 12 namespace base { 13 14 // Helper class that executes code on a given target sequence/thread while 15 // blocking on the invoking sequence/thread. To use, derive from this class and 16 // overwrite RunTest. An alternative use of this class is to use it directly. It 17 // will then block until all pending tasks on a given sequence/thread have been 18 // executed. 19 class ThreadTestHelper : public RefCountedThreadSafe<ThreadTestHelper> { 20 public: 21 explicit ThreadTestHelper(scoped_refptr<SequencedTaskRunner> target_sequence); 22 23 ThreadTestHelper(const ThreadTestHelper&) = delete; 24 ThreadTestHelper& operator=(const ThreadTestHelper&) = delete; 25 26 // True if RunTest() was successfully executed on the target sequence. 27 [[nodiscard]] bool Run(); 28 29 virtual void RunTest(); 30 31 protected: 32 friend class RefCountedThreadSafe<ThreadTestHelper>; 33 34 virtual ~ThreadTestHelper(); 35 36 // Use this method to store the result of RunTest(). set_test_result(bool test_result)37 void set_test_result(bool test_result) { test_result_ = test_result; } 38 39 private: 40 void RunOnSequence(); 41 42 bool test_result_; 43 scoped_refptr<SequencedTaskRunner> target_sequence_; 44 WaitableEvent done_event_; 45 }; 46 47 } // namespace base 48 49 #endif // BASE_TEST_THREAD_TEST_HELPER_H_ 50