Allow the minimum time between banner trigger visits to be varied via field trials.
[chromium-blink-merge.git] / chrome / browser / process_singleton_win_unittest.cc
blob332c5a2881a7aca8c572dbb2a907e4452747c637
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/browser/process_singleton.h"
7 #include <windows.h>
9 #include "base/bind.h"
10 #include "base/command_line.h"
11 #include "base/compiler_specific.h"
12 #include "base/files/file_path.h"
13 #include "base/files/scoped_temp_dir.h"
14 #include "base/logging.h"
15 #include "base/memory/scoped_ptr.h"
16 #include "base/process/launch.h"
17 #include "base/process/process.h"
18 #include "base/process/process_handle.h"
19 #include "base/strings/string16.h"
20 #include "base/strings/stringprintf.h"
21 #include "base/test/multiprocess_test.h"
22 #include "base/win/scoped_handle.h"
23 #include "base/win/wrapped_window_proc.h"
24 #include "chrome/browser/chrome_process_finder_win.h"
25 #include "chrome/common/chrome_constants.h"
26 #include "chrome/common/chrome_switches.h"
27 #include "content/public/common/result_codes.h"
28 #include "testing/gtest/include/gtest/gtest.h"
29 #include "testing/multiprocess_func_list.h"
31 namespace {
33 const char kReadyEventNameFlag[] = "ready_event_name";
34 const char kContinueEventNameFlag[] = "continue_event_name";
35 const char kCreateWindowFlag[] = "create_window";
36 const int kErrorResultCode = 0x345;
38 bool NotificationCallback(const base::CommandLine& command_line,
39 const base::FilePath& current_directory) {
40 // This is never called in this test, but would signal that the singleton
41 // notification was successfully handled.
42 NOTREACHED();
43 return true;
46 // The ProcessSingleton kills hung browsers with no visible windows without user
47 // interaction. If a hung browser has visible UI, however, it asks the user
48 // first.
49 // This class is the very minimal implementation to create a visible window
50 // in the hung test process to allow testing the latter path.
51 class ScopedVisibleWindow {
52 public:
53 ScopedVisibleWindow() : class_(0), window_(NULL) {}
54 ~ScopedVisibleWindow() {
55 if (window_)
56 ::DestroyWindow(window_);
57 if (class_)
58 ::UnregisterClass(reinterpret_cast<LPCWSTR>(class_), NULL);
61 bool Create() {
62 WNDCLASSEX wnd_cls = {0};
63 base::win::InitializeWindowClass(
64 L"ProcessSingletonTest", base::win::WrappedWindowProc<::DefWindowProc>,
65 0, // style
66 0, // class_extra
67 0, // window_extra
68 NULL, // cursor
69 NULL, // background
70 NULL, // menu_name
71 NULL, // large_icon
72 NULL, // small_icon
73 &wnd_cls);
75 class_ = ::RegisterClassEx(&wnd_cls);
76 if (!class_)
77 return false;
78 window_ = ::CreateWindow(reinterpret_cast<LPCWSTR>(class_), 0, WS_POPUP, 0,
79 0, 0, 0, 0, 0, NULL, 0);
80 if (!window_)
81 return false;
82 ::ShowWindow(window_, SW_SHOW);
84 DCHECK(window_);
85 return true;
88 private:
89 ATOM class_;
90 HWND window_;
92 DISALLOW_COPY_AND_ASSIGN(ScopedVisibleWindow);
95 MULTIPROCESS_TEST_MAIN(ProcessSingletonTestProcessMain) {
96 base::CommandLine* cmd_line = base::CommandLine::ForCurrentProcess();
97 base::FilePath user_data_dir =
98 cmd_line->GetSwitchValuePath(switches::kUserDataDir);
99 if (user_data_dir.empty())
100 return kErrorResultCode;
102 base::string16 ready_event_name =
103 cmd_line->GetSwitchValueNative(kReadyEventNameFlag);
105 base::win::ScopedHandle ready_event(
106 ::OpenEvent(EVENT_MODIFY_STATE, FALSE, ready_event_name.c_str()));
107 if (!ready_event.IsValid())
108 return kErrorResultCode;
110 base::string16 continue_event_name =
111 cmd_line->GetSwitchValueNative(kContinueEventNameFlag);
113 base::win::ScopedHandle continue_event(
114 ::OpenEvent(SYNCHRONIZE, FALSE, continue_event_name.c_str()));
115 if (!continue_event.IsValid())
116 return kErrorResultCode;
118 ScopedVisibleWindow visible_window;
119 if (cmd_line->HasSwitch(kCreateWindowFlag)) {
120 if (!visible_window.Create())
121 return kErrorResultCode;
124 // Instantiate the process singleton.
125 ProcessSingleton process_singleton(user_data_dir,
126 base::Bind(&NotificationCallback));
128 if (!process_singleton.Create())
129 return kErrorResultCode;
131 // Signal ready and block for the continue event.
132 if (!::SetEvent(ready_event.Get()))
133 return kErrorResultCode;
135 if (::WaitForSingleObject(continue_event.Get(), INFINITE) != WAIT_OBJECT_0)
136 return kErrorResultCode;
138 return 0;
141 // This fixture is for testing the Windows platform-specific failure modes
142 // of rendezvous, specifically the ones where the singleton-owning process
143 // is hung.
144 class ProcessSingletonTest : public base::MultiProcessTest {
145 protected:
146 enum WindowOption { WITH_WINDOW, NO_WINDOW };
148 ProcessSingletonTest()
149 : window_option_(NO_WINDOW), should_kill_called_(false) {}
151 void SetUp() override {
152 ASSERT_NO_FATAL_FAILURE(base::MultiProcessTest::SetUp());
154 // Drop the process finder notification timeout to one second for testing.
155 old_notification_timeout_ = chrome::SetNotificationTimeoutForTesting(
156 base::TimeDelta::FromSeconds(1));
159 void TearDown() override {
160 chrome::SetNotificationTimeoutForTesting(old_notification_timeout_);
162 if (browser_victim_.IsValid()) {
163 EXPECT_TRUE(::SetEvent(continue_event_.Get()));
164 EXPECT_TRUE(browser_victim_.WaitForExit(nullptr));
167 base::MultiProcessTest::TearDown();
170 void LaunchHungBrowserProcess(WindowOption window_option) {
171 // Create a unique user data dir to rendezvous on.
172 ASSERT_TRUE(user_data_dir_.CreateUniqueTempDir());
174 // Create the named "ready" event, this is unique to our process.
175 ready_event_name_ =
176 base::StringPrintf(L"ready-event-%d", base::GetCurrentProcId());
177 base::win::ScopedHandle ready_event(
178 ::CreateEvent(NULL, TRUE, FALSE, ready_event_name_.c_str()));
179 ASSERT_TRUE(ready_event.IsValid());
181 // Create the named "continue" event, this is unique to our process.
182 continue_event_name_ =
183 base::StringPrintf(L"continue-event-%d", base::GetCurrentProcId());
184 continue_event_.Set(
185 ::CreateEvent(NULL, TRUE, FALSE, continue_event_name_.c_str()));
186 ASSERT_TRUE(continue_event_.IsValid());
188 window_option_ = window_option;
190 base::LaunchOptions options;
191 options.start_hidden = true;
192 browser_victim_ =
193 SpawnChildWithOptions("ProcessSingletonTestProcessMain", options);
195 // Wait for the ready event (or process exit).
196 HANDLE handles[] = {ready_event.Get(), browser_victim_.Handle()};
197 // The wait should always return because either |ready_event| is signaled or
198 // |browser_victim_| died unexpectedly or exited on error.
199 DWORD result =
200 ::WaitForMultipleObjects(arraysize(handles), handles, FALSE, INFINITE);
201 ASSERT_EQ(WAIT_OBJECT_0, result);
204 base::CommandLine MakeCmdLine(const std::string& procname) override {
205 base::CommandLine cmd_line = base::MultiProcessTest::MakeCmdLine(procname);
207 cmd_line.AppendSwitchPath(switches::kUserDataDir, user_data_dir_.path());
208 cmd_line.AppendSwitchNative(kReadyEventNameFlag, ready_event_name_);
209 cmd_line.AppendSwitchNative(kContinueEventNameFlag, continue_event_name_);
210 if (window_option_ == WITH_WINDOW)
211 cmd_line.AppendSwitch(kCreateWindowFlag);
213 return cmd_line;
216 void PrepareTest(WindowOption window_option, bool allow_kill) {
217 ASSERT_NO_FATAL_FAILURE(LaunchHungBrowserProcess(window_option));
219 // The ready event has been signalled - the process singleton is held by
220 // the hung sub process.
221 test_singleton_.reset(new ProcessSingleton(
222 user_data_dir(), base::Bind(&NotificationCallback)));
224 test_singleton_->OverrideShouldKillRemoteProcessCallbackForTesting(
225 base::Bind(&ProcessSingletonTest::MockShouldKillRemoteProcess,
226 base::Unretained(this), allow_kill));
229 base::Process* browser_victim() { return &browser_victim_; }
230 const base::FilePath& user_data_dir() const { return user_data_dir_.path(); }
231 ProcessSingleton* test_singleton() const { return test_singleton_.get(); }
232 bool should_kill_called() const { return should_kill_called_; }
234 private:
235 bool MockShouldKillRemoteProcess(bool allow_kill) {
236 should_kill_called_ = true;
237 return allow_kill;
240 base::string16 ready_event_name_;
241 base::string16 continue_event_name_;
243 WindowOption window_option_;
244 base::ScopedTempDir user_data_dir_;
245 base::Process browser_victim_;
246 base::win::ScopedHandle continue_event_;
248 scoped_ptr<ProcessSingleton> test_singleton_;
250 base::TimeDelta old_notification_timeout_;
251 bool should_kill_called_;
253 DISALLOW_COPY_AND_ASSIGN(ProcessSingletonTest);
256 } // namespace
258 TEST_F(ProcessSingletonTest, KillsHungBrowserWithNoWindows) {
259 ASSERT_NO_FATAL_FAILURE(PrepareTest(NO_WINDOW, false));
261 // As the hung browser has no visible window, it'll be killed without
262 // user interaction.
263 ProcessSingleton::NotifyResult notify_result =
264 test_singleton()->NotifyOtherProcessOrCreate();
265 ASSERT_EQ(ProcessSingleton::PROFILE_IN_USE, notify_result);
267 // The should-kill callback should not have been called, as the "browser" does
268 // not have visible window.
269 EXPECT_FALSE(should_kill_called());
271 // Verify that the hung browser has beem terminated with the
272 // RESULT_CODE_HUNG exit code.
273 int exit_code = 0;
274 EXPECT_TRUE(
275 browser_victim()->WaitForExitWithTimeout(base::TimeDelta(), &exit_code));
276 EXPECT_EQ(content::RESULT_CODE_HUNG, exit_code);
279 TEST_F(ProcessSingletonTest, DoesntKillWithoutUserPermission) {
280 ASSERT_NO_FATAL_FAILURE(PrepareTest(WITH_WINDOW, false));
282 // As the hung browser has a visible window, this should query the user
283 // before killing the hung process.
284 ProcessSingleton::NotifyResult notify_result =
285 test_singleton()->NotifyOtherProcessOrCreate();
286 ASSERT_EQ(ProcessSingleton::PROCESS_NOTIFIED, notify_result);
288 // The should-kill callback should have been called, as the "browser" has a
289 // visible window.
290 EXPECT_TRUE(should_kill_called());
292 // Make sure the process hasn't been killed.
293 int exit_code = 0;
294 EXPECT_FALSE(
295 browser_victim()->WaitForExitWithTimeout(base::TimeDelta(), &exit_code));
298 TEST_F(ProcessSingletonTest, KillWithUserPermission) {
299 ASSERT_NO_FATAL_FAILURE(PrepareTest(WITH_WINDOW, true));
301 // As the hung browser has a visible window, this should query the user
302 // before killing the hung process.
303 ProcessSingleton::NotifyResult notify_result =
304 test_singleton()->NotifyOtherProcessOrCreate();
305 ASSERT_EQ(ProcessSingleton::PROFILE_IN_USE, notify_result);
307 // The should-kill callback should have been called, as the "browser" has a
308 // visible window.
309 EXPECT_TRUE(should_kill_called());
311 // Verify that the hung browser has beem terminated with the
312 // RESULT_CODE_HUNG exit code.
313 int exit_code = 0;
314 EXPECT_TRUE(
315 browser_victim()->WaitForExitWithTimeout(base::TimeDelta(), &exit_code));
316 EXPECT_EQ(content::RESULT_CODE_HUNG, exit_code);