Merge Chromium + Blink git repositories
[chromium-blink-merge.git] / chrome / app / chrome_watcher_client_unittest_win.cc
blob20d1d32ad1a246c0928a441b2e530d3644e4b0c2
1 // Copyright 2015 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.
5 #include "chrome/app/chrome_watcher_client_win.h"
7 #include <windows.h>
8 #include <string>
9 #include "base/base_switches.h"
10 #include "base/bind.h"
11 #include "base/command_line.h"
12 #include "base/logging.h"
13 #include "base/process/process_handle.h"
14 #include "base/strings/string16.h"
15 #include "base/strings/string_number_conversions.h"
16 #include "base/strings/utf_string_conversions.h"
17 #include "base/synchronization/waitable_event.h"
18 #include "base/test/multiprocess_test.h"
19 #include "base/threading/simple_thread.h"
20 #include "base/time/time.h"
21 #include "base/win/scoped_handle.h"
22 #include "testing/gtest/include/gtest/gtest.h"
23 #include "testing/multiprocess_func_list.h"
25 namespace {
27 const char kParentHandle[] = "parent-handle";
28 const char kEventHandle[] = "event-handle";
29 const char kNamedEventSuffix[] = "named-event-suffix";
31 const base::char16 kExitEventBaseName[] = L"ChromeWatcherClientTestExitEvent_";
32 const base::char16 kInitializeEventBaseName[] =
33 L"ChromeWatcherClientTestInitializeEvent_";
35 base::win::ScopedHandle InterpretHandleSwitch(base::CommandLine& cmd_line,
36 const char* switch_name) {
37 std::string str_handle =
38 cmd_line.GetSwitchValueASCII(switch_name);
39 if (str_handle.empty()) {
40 LOG(ERROR) << "Switch " << switch_name << " unexpectedly absent.";
41 return base::win::ScopedHandle();
44 unsigned int_handle = 0;
45 if (!base::StringToUint(str_handle, &int_handle)) {
46 LOG(ERROR) << "Switch " << switch_name << " has invalid value "
47 << str_handle;
48 return base::win::ScopedHandle();
51 return base::win::ScopedHandle(
52 reinterpret_cast<base::ProcessHandle>(int_handle));
55 // Simulates a Chrome watcher process. Exits when the global exit event is
56 // signaled. Signals the "on initialized" event (passed on the command-line)
57 // when the global initialization event is signaled.
58 MULTIPROCESS_TEST_MAIN(ChromeWatcherClientTestProcess) {
59 base::CommandLine* cmd_line = base::CommandLine::ForCurrentProcess();
61 base::string16 named_event_suffix =
62 base::ASCIIToUTF16(cmd_line->GetSwitchValueASCII(kNamedEventSuffix));
63 if (named_event_suffix.empty()) {
64 LOG(ERROR) << "Switch " << kNamedEventSuffix << " unexpectedly absent.";
65 return 1;
68 base::win::ScopedHandle exit_event(::CreateEvent(
69 NULL, FALSE, FALSE, (kExitEventBaseName + named_event_suffix).c_str()));
70 if (!exit_event.IsValid()) {
71 LOG(ERROR) << "Failed to create event named "
72 << kExitEventBaseName + named_event_suffix;
73 return 1;
76 base::win::ScopedHandle initialize_event(
77 ::CreateEvent(NULL, FALSE, FALSE,
78 (kInitializeEventBaseName + named_event_suffix).c_str()));
79 if (!initialize_event.IsValid()) {
80 LOG(ERROR) << "Failed to create event named "
81 << kInitializeEventBaseName + named_event_suffix;
82 return 1;
85 base::win::ScopedHandle parent_process(
86 InterpretHandleSwitch(*cmd_line, kParentHandle));
87 if (!parent_process.IsValid())
88 return 1;
90 base::win::ScopedHandle on_initialized_event(
91 InterpretHandleSwitch(*cmd_line, kEventHandle));
92 if (!on_initialized_event.IsValid())
93 return 1;
95 while (true) {
96 // We loop as a convenient way to continue waiting for the exit_event after
97 // the initialize_event is signaled. We expect to get initialize_event zero
98 // or one times before exit_event, never more.
99 HANDLE handles[] = {exit_event.Get(), initialize_event.Get()};
100 DWORD result =
101 ::WaitForMultipleObjects(arraysize(handles), handles, FALSE, INFINITE);
102 switch (result) {
103 case WAIT_OBJECT_0:
104 // exit_event
105 return 0;
106 case WAIT_OBJECT_0 + 1:
107 // initialize_event
108 ::SetEvent(on_initialized_event.Get());
109 break;
110 case WAIT_FAILED:
111 PLOG(ERROR) << "Unexpected failure in WaitForMultipleObjects.";
112 return 1;
113 default:
114 NOTREACHED() << "Unexpected result from WaitForMultipleObjects: "
115 << result;
116 return 1;
121 // Implements a thread to launch the ChromeWatcherClient and block on
122 // EnsureInitialized. Provides various helpers to interact with the
123 // ChromeWatcherClient.
124 class ChromeWatcherClientThread : public base::SimpleThread {
125 public:
126 ChromeWatcherClientThread()
127 : SimpleThread("ChromeWatcherClientTest thread"),
128 client_(base::Bind(&ChromeWatcherClientThread::GenerateCommandLine,
129 base::Unretained(this))),
130 complete_(false, false),
131 result_(false) {}
133 // Waits up to |timeout| for the call to EnsureInitialized to complete. If it
134 // does, sets |result| to the return value of EnsureInitialized and returns
135 // true. Otherwise returns false.
136 bool WaitForResultWithTimeout(base::TimeDelta timeout, bool* result) {
137 if (!complete_.TimedWait(timeout))
138 return false;
139 *result = result_;
140 return true;
143 // Waits indefinitely for the call to WaitForInitialization to complete.
144 // Returns the return value of WaitForInitialization.
145 bool WaitForResult() {
146 complete_.Wait();
147 return result_;
150 ChromeWatcherClient& client() { return client_; }
152 base::string16 NamedEventSuffix() {
153 return base::UintToString16(base::GetCurrentProcId());
156 // base::SimpleThread implementation.
157 void Run() override {
158 result_ = client_.LaunchWatcher();
159 if (result_)
160 result_ = client_.EnsureInitialized();
161 complete_.Signal();
164 private:
165 // Returns a command line to launch back into ChromeWatcherClientTestProcess.
166 base::CommandLine GenerateCommandLine(HANDLE parent_handle,
167 DWORD main_thread_id,
168 HANDLE on_initialized_event) {
169 base::CommandLine ret = base::GetMultiProcessTestChildBaseCommandLine();
170 ret.AppendSwitchASCII(switches::kTestChildProcess,
171 "ChromeWatcherClientTestProcess");
172 ret.AppendSwitchASCII(kEventHandle,
173 base::UintToString(reinterpret_cast<unsigned int>(
174 on_initialized_event)));
175 ret.AppendSwitchASCII(
176 kParentHandle,
177 base::UintToString(reinterpret_cast<unsigned int>(parent_handle)));
179 // Our child does not actually need the main thread ID, but we verify here
180 // that the correct ID is being passed from the client.
181 EXPECT_EQ(::GetCurrentThreadId(), main_thread_id);
183 ret.AppendSwitchASCII(kNamedEventSuffix,
184 base::UTF16ToASCII(NamedEventSuffix()));
185 return ret;
188 // The instance under test.
189 ChromeWatcherClient client_;
190 // Signaled when WaitForInitialization returns.
191 base::WaitableEvent complete_;
192 // The return value of WaitForInitialization.
193 bool result_;
195 DISALLOW_COPY_AND_ASSIGN(ChromeWatcherClientThread);
198 } // namespace
200 class ChromeWatcherClientTest : public testing::Test {
201 protected:
202 // Sends a signal to the simulated watcher process to exit. Returns true if
203 // successful.
204 bool SignalExit() { return ::SetEvent(exit_event_.Get()) != FALSE; }
206 // Sends a signal to the simulated watcher process to signal its
207 // "initialization". Returns true if successful.
208 bool SignalInitialize() {
209 return ::SetEvent(initialize_event_.Get()) != FALSE;
212 // The helper thread, which also provides access to the ChromeWatcherClient.
213 ChromeWatcherClientThread& thread() { return thread_; }
215 // testing::Test implementation.
216 void SetUp() override {
217 exit_event_.Set(::CreateEvent(
218 NULL, FALSE, FALSE,
219 (kExitEventBaseName + thread_.NamedEventSuffix()).c_str()));
220 ASSERT_TRUE(exit_event_.IsValid());
221 initialize_event_.Set(::CreateEvent(
222 NULL, FALSE, FALSE,
223 (kInitializeEventBaseName + thread_.NamedEventSuffix()).c_str()));
224 ASSERT_TRUE(initialize_event_.IsValid());
227 void TearDown() override {
228 // Even if we never launched, the following is harmless.
229 SignalExit();
230 thread_.client().WaitForExit(nullptr);
231 thread_.Join();
234 private:
235 // Used to launch and block on the Chrome watcher process in a background
236 // thread.
237 ChromeWatcherClientThread thread_;
238 // Used to signal the Chrome watcher process to exit.
239 base::win::ScopedHandle exit_event_;
240 // Used to signal the Chrome watcher process to signal its own
241 // initialization..
242 base::win::ScopedHandle initialize_event_;
245 TEST_F(ChromeWatcherClientTest, SuccessTest) {
246 thread().Start();
247 bool result = false;
248 // Give a broken implementation a chance to exit unexpectedly.
249 ASSERT_FALSE(thread().WaitForResultWithTimeout(
250 base::TimeDelta::FromMilliseconds(100), &result));
251 ASSERT_TRUE(SignalInitialize());
252 ASSERT_TRUE(thread().WaitForResult());
253 // The watcher should still be running. Give a broken implementation a chance
254 // to exit unexpectedly, then signal it to exit.
255 int exit_code = 0;
256 ASSERT_FALSE(thread().client().WaitForExitWithTimeout(
257 base::TimeDelta::FromMilliseconds(100), &exit_code));
258 SignalExit();
259 ASSERT_TRUE(thread().client().WaitForExit(&exit_code));
260 ASSERT_EQ(0, exit_code);
263 TEST_F(ChromeWatcherClientTest, FailureTest) {
264 thread().Start();
265 bool result = false;
266 // Give a broken implementation a chance to exit unexpectedly.
267 ASSERT_FALSE(thread().WaitForResultWithTimeout(
268 base::TimeDelta::FromMilliseconds(100), &result));
269 ASSERT_TRUE(SignalExit());
270 ASSERT_FALSE(thread().WaitForResult());
271 int exit_code = 0;
272 ASSERT_TRUE(
273 thread().client().WaitForExitWithTimeout(base::TimeDelta(), &exit_code));
274 ASSERT_EQ(0, exit_code);