1 // Copyright 2014 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 5 #ifndef IOS_WEB_PUBLIC_TEST_WEB_TASK_ENVIRONMENT_H_ 6 #define IOS_WEB_PUBLIC_TEST_WEB_TASK_ENVIRONMENT_H_ 7 8 #include "base/test/task_environment.h" 9 10 // WebTaskEnvironment is the iOS equivalent of content::BrowserTaskEnvironment. 11 // 12 // It's is a convenience class for creating a set of TestWebThreads and a thread 13 // pool in unit tests. For most tests, it is sufficient to just instantiate the 14 // WebTaskEnvironment as a member variable. It is a good idea to put the 15 // WebTaskEnvironment as the first member variable in test classes, so it is 16 // destroyed last, and the test threads always exist from the perspective of 17 // other classes. 18 // 19 // By default, all of the created TestWebThreads will be backed by a single 20 // shared MessageLoop. If a test truly needs separate threads, it can do so by 21 // passing the appropriate combination of option values during the 22 // WebTaskEnvironment construction. 23 // 24 // To synchronously run tasks posted to TestWebThreads that use the shared 25 // MessageLoop, call RunLoop::Run/RunUntilIdle() on the thread where the 26 // WebTaskEnvironment lives. The destructor of WebTaskEnvironment runs remaining 27 // TestWebThreads tasks and remaining BLOCK_SHUTDOWN thread pool tasks. 28 // 29 // Some tests using the IO thread expect a MessageLoopForIO. Passing IO_MAINLOOP 30 // will use a MessageLoopForIO for the main MessageLoop. Most of the time, this 31 // avoids needing to use a REAL_IO_THREAD. 32 33 #include <memory> 34 35 #include "base/macros.h" 36 37 namespace base { 38 class MessageLoop; 39 } // namespace base 40 41 namespace web { 42 43 class TestWebThread; 44 45 class WebTaskEnvironment : public base::test::TaskEnvironment { 46 public: 47 // Used to specify the type of MessageLoop that backs the UI thread, and 48 // which of the named WebThreads should be backed by a real 49 // threads. The UI thread is always the main thread in a unit test. 50 enum Options { 51 DEFAULT = 0, 52 IO_MAINLOOP = 1 << 0, 53 REAL_IO_THREAD = 1 << 1, 54 }; 55 56 explicit WebTaskEnvironment( 57 int options = Options::DEFAULT, 58 base::test::TaskEnvironment::TimeSource time_source = 59 base::test::TaskEnvironment::TimeSource::DEFAULT); 60 61 ~WebTaskEnvironment() override; 62 63 private: 64 void Init(int options); 65 66 std::unique_ptr<TestWebThread> ui_thread_; 67 std::unique_ptr<TestWebThread> io_thread_; 68 69 DISALLOW_COPY_AND_ASSIGN(WebTaskEnvironment); 70 }; 71 72 } // namespace web 73 74 #endif // IOS_WEB_PUBLIC_TEST_WEB_TASK_ENVIRONMENT_H_ 75