thread_test_helper.h 1.5 KB

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