Transfer Password sync to use new sync API.
[chromium-blink-merge.git] / chrome / common / service_process_util_unittest.cc
blob4dc9c327e8b7dd41b38c58ab188dcf917e21df2d
1 // Copyright (c) 2012 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/common/service_process_util.h"
7 #include "base/basictypes.h"
8 #include "base/bind.h"
9 #include "base/command_line.h"
10 #include "base/files/file_path.h"
11 #include "base/process/kill.h"
12 #include "base/process/launch.h"
13 #include "base/strings/string_split.h"
15 #if !defined(OS_MACOSX)
16 #include "base/at_exit.h"
17 #include "base/memory/scoped_ptr.h"
18 #include "base/strings/string_util.h"
19 #include "base/strings/utf_string_conversions.h"
20 #include "base/test/multiprocess_test.h"
21 #include "base/test/test_timeouts.h"
22 #include "base/threading/thread.h"
23 #include "chrome/common/chrome_switches.h"
24 #include "chrome/common/chrome_version_info.h"
25 #include "testing/multiprocess_func_list.h"
27 #if defined(OS_WIN)
28 #include "base/win/win_util.h"
29 #endif
31 #if defined(OS_POSIX)
32 #include "chrome/common/auto_start_linux.h"
33 #endif
35 #if defined(USE_AURA)
36 // This test fails http://crbug.com/84854, and is very flaky on CrOS and
37 // somewhat flaky on other Linux.
38 #define MAYBE_ForceShutdown DISABLED_ForceShutdown
39 #else
40 #if defined(OS_LINUX) || defined(OS_WIN)
41 #define MAYBE_ForceShutdown DISABLED_ForceShutdown
42 #else
43 #define MAYBE_ForceShutdown ForceShutdown
44 #endif
45 #endif
47 namespace {
49 bool g_good_shutdown = false;
51 void ShutdownTask(base::MessageLoop* loop) {
52 // Quit the main message loop.
53 ASSERT_FALSE(g_good_shutdown);
54 g_good_shutdown = true;
55 loop->PostTask(FROM_HERE, base::MessageLoop::QuitClosure());
58 } // namespace
60 TEST(ServiceProcessUtilTest, ScopedVersionedName) {
61 std::string test_str = "test";
62 std::string scoped_name = GetServiceProcessScopedVersionedName(test_str);
63 chrome::VersionInfo version_info;
64 DCHECK(version_info.is_valid());
65 EXPECT_TRUE(EndsWith(scoped_name, test_str, true));
66 EXPECT_NE(std::string::npos, scoped_name.find(version_info.Version()));
69 class ServiceProcessStateTest : public base::MultiProcessTest {
70 public:
71 ServiceProcessStateTest();
72 virtual ~ServiceProcessStateTest();
73 virtual void SetUp();
74 base::MessageLoopProxy* IOMessageLoopProxy() {
75 return io_thread_.message_loop_proxy().get();
77 void LaunchAndWait(const std::string& name);
79 private:
80 // This is used to release the ServiceProcessState singleton after each test.
81 base::ShadowingAtExitManager at_exit_manager_;
82 base::Thread io_thread_;
85 ServiceProcessStateTest::ServiceProcessStateTest()
86 : io_thread_("ServiceProcessStateTestThread") {
89 ServiceProcessStateTest::~ServiceProcessStateTest() {
92 void ServiceProcessStateTest::SetUp() {
93 base::Thread::Options options(base::MessageLoop::TYPE_IO, 0);
94 ASSERT_TRUE(io_thread_.StartWithOptions(options));
97 void ServiceProcessStateTest::LaunchAndWait(const std::string& name) {
98 base::ProcessHandle handle = SpawnChild(name, false);
99 ASSERT_TRUE(handle);
100 int exit_code = 0;
101 ASSERT_TRUE(base::WaitForExitCode(handle, &exit_code));
102 ASSERT_EQ(exit_code, 0);
105 TEST_F(ServiceProcessStateTest, Singleton) {
106 ServiceProcessState state;
107 ASSERT_TRUE(state.Initialize());
108 LaunchAndWait("ServiceProcessStateTestSingleton");
111 TEST_F(ServiceProcessStateTest, ReadyState) {
112 ASSERT_FALSE(CheckServiceProcessReady());
113 ServiceProcessState state;
114 ASSERT_TRUE(state.Initialize());
115 ASSERT_TRUE(state.SignalReady(IOMessageLoopProxy(), base::Closure()));
116 LaunchAndWait("ServiceProcessStateTestReadyTrue");
117 state.SignalStopped();
118 LaunchAndWait("ServiceProcessStateTestReadyFalse");
121 TEST_F(ServiceProcessStateTest, AutoRun) {
122 ServiceProcessState state;
123 ASSERT_TRUE(state.AddToAutoRun());
124 scoped_ptr<CommandLine> autorun_command_line;
125 #if defined(OS_WIN)
126 std::string value_name = GetServiceProcessScopedName("_service_run");
127 base::string16 value;
128 EXPECT_TRUE(base::win::ReadCommandFromAutoRun(HKEY_CURRENT_USER,
129 base::UTF8ToWide(value_name),
130 &value));
131 autorun_command_line.reset(new CommandLine(CommandLine::FromString(value)));
132 #elif defined(OS_POSIX) && !defined(OS_MACOSX)
133 #if defined(GOOGLE_CHROME_BUILD)
134 std::string base_desktop_name = "google-chrome-service.desktop";
135 #else // CHROMIUM_BUILD
136 std::string base_desktop_name = "chromium-service.desktop";
137 #endif
138 std::string exec_value;
139 EXPECT_TRUE(AutoStart::GetAutostartFileValue(
140 GetServiceProcessScopedName(base_desktop_name), "Exec", &exec_value));
142 // Make sure |exec_value| doesn't contain strings a shell would
143 // treat specially.
144 ASSERT_EQ(std::string::npos, exec_value.find('#'));
145 ASSERT_EQ(std::string::npos, exec_value.find('\n'));
146 ASSERT_EQ(std::string::npos, exec_value.find('"'));
147 ASSERT_EQ(std::string::npos, exec_value.find('\''));
149 CommandLine::StringVector argv;
150 base::SplitString(exec_value, ' ', &argv);
151 ASSERT_GE(argv.size(), 2U)
152 << "Expected at least one command-line option in: " << exec_value;
153 autorun_command_line.reset(new CommandLine(argv));
154 #endif // defined(OS_WIN)
155 if (autorun_command_line.get()) {
156 EXPECT_EQ(autorun_command_line->GetSwitchValueASCII(switches::kProcessType),
157 std::string(switches::kServiceProcess));
159 ASSERT_TRUE(state.RemoveFromAutoRun());
160 #if defined(OS_WIN)
161 EXPECT_FALSE(base::win::ReadCommandFromAutoRun(HKEY_CURRENT_USER,
162 base::UTF8ToWide(value_name),
163 &value));
164 #elif defined(OS_POSIX) && !defined(OS_MACOSX)
165 EXPECT_FALSE(AutoStart::GetAutostartFileValue(
166 GetServiceProcessScopedName(base_desktop_name), "Exec", &exec_value));
167 #endif // defined(OS_WIN)
170 TEST_F(ServiceProcessStateTest, SharedMem) {
171 std::string version;
172 base::ProcessId pid;
173 #if defined(OS_WIN)
174 // On Posix, named shared memory uses a file on disk. This file
175 // could be lying around from previous crashes which could cause
176 // GetServiceProcessPid to lie. On Windows, we use a named event so we
177 // don't have this issue. Until we have a more stable shared memory
178 // implementation on Posix, this check will only execute on Windows.
179 ASSERT_FALSE(GetServiceProcessData(&version, &pid));
180 #endif // defined(OS_WIN)
181 ServiceProcessState state;
182 ASSERT_TRUE(state.Initialize());
183 ASSERT_TRUE(GetServiceProcessData(&version, &pid));
184 ASSERT_EQ(base::GetCurrentProcId(), pid);
187 TEST_F(ServiceProcessStateTest, MAYBE_ForceShutdown) {
188 base::ProcessHandle handle = SpawnChild("ServiceProcessStateTestShutdown",
189 true);
190 ASSERT_TRUE(handle);
191 for (int i = 0; !CheckServiceProcessReady() && i < 10; ++i) {
192 base::PlatformThread::Sleep(TestTimeouts::tiny_timeout());
194 ASSERT_TRUE(CheckServiceProcessReady());
195 std::string version;
196 base::ProcessId pid;
197 ASSERT_TRUE(GetServiceProcessData(&version, &pid));
198 ASSERT_TRUE(ForceServiceProcessShutdown(version, pid));
199 int exit_code = 0;
200 ASSERT_TRUE(base::WaitForExitCodeWithTimeout(handle,
201 &exit_code, TestTimeouts::action_max_timeout()));
202 base::CloseProcessHandle(handle);
203 ASSERT_EQ(exit_code, 0);
206 MULTIPROCESS_TEST_MAIN(ServiceProcessStateTestSingleton) {
207 ServiceProcessState state;
208 EXPECT_FALSE(state.Initialize());
209 return 0;
212 MULTIPROCESS_TEST_MAIN(ServiceProcessStateTestReadyTrue) {
213 EXPECT_TRUE(CheckServiceProcessReady());
214 return 0;
217 MULTIPROCESS_TEST_MAIN(ServiceProcessStateTestReadyFalse) {
218 EXPECT_FALSE(CheckServiceProcessReady());
219 return 0;
222 MULTIPROCESS_TEST_MAIN(ServiceProcessStateTestShutdown) {
223 base::MessageLoop message_loop;
224 message_loop.set_thread_name("ServiceProcessStateTestShutdownMainThread");
225 base::Thread io_thread_("ServiceProcessStateTestShutdownIOThread");
226 base::Thread::Options options(base::MessageLoop::TYPE_IO, 0);
227 EXPECT_TRUE(io_thread_.StartWithOptions(options));
228 ServiceProcessState state;
229 EXPECT_TRUE(state.Initialize());
230 EXPECT_TRUE(state.SignalReady(
231 io_thread_.message_loop_proxy().get(),
232 base::Bind(&ShutdownTask, base::MessageLoop::current())));
233 message_loop.PostDelayedTask(FROM_HERE,
234 base::MessageLoop::QuitClosure(),
235 TestTimeouts::action_max_timeout());
236 EXPECT_FALSE(g_good_shutdown);
237 message_loop.Run();
238 EXPECT_TRUE(g_good_shutdown);
239 return 0;
242 #else // !OS_MACOSX
244 #include <CoreFoundation/CoreFoundation.h>
246 #include "base/file_util.h"
247 #include "base/files/file_path.h"
248 #include "base/files/scoped_temp_dir.h"
249 #include "base/mac/mac_util.h"
250 #include "base/test/test_timeouts.h"
251 #include "base/threading/thread.h"
252 #include "chrome/common/mac/launchd.h"
253 #include "chrome/common/mac/mock_launchd.h"
254 #include "testing/gtest/include/gtest/gtest.h"
256 class ServiceProcessStateFileManipulationTest : public ::testing::Test {
257 protected:
258 ServiceProcessStateFileManipulationTest()
259 : io_thread_("ServiceProcessStateFileManipulationTest_IO") {
261 virtual ~ServiceProcessStateFileManipulationTest() { }
263 virtual void SetUp() {
264 base::Thread::Options options;
265 options.message_loop_type = base::MessageLoop::TYPE_IO;
266 ASSERT_TRUE(io_thread_.StartWithOptions(options));
267 ASSERT_TRUE(temp_dir_.CreateUniqueTempDir());
268 ASSERT_TRUE(MockLaunchd::MakeABundle(GetTempDirPath(),
269 "Test",
270 &bundle_path_,
271 &executable_path_));
272 mock_launchd_.reset(new MockLaunchd(executable_path_, &loop_,
273 false, false));
274 scoped_launchd_instance_.reset(
275 new Launchd::ScopedInstance(mock_launchd_.get()));
276 ASSERT_TRUE(service_process_state_.Initialize());
277 ASSERT_TRUE(service_process_state_.SignalReady(
278 io_thread_.message_loop_proxy().get(), base::Closure()));
279 loop_.PostDelayedTask(FROM_HERE,
280 base::MessageLoop::QuitClosure(),
281 TestTimeouts::action_max_timeout());
284 const MockLaunchd* mock_launchd() const { return mock_launchd_.get(); }
285 const base::FilePath& executable_path() const { return executable_path_; }
286 const base::FilePath& bundle_path() const { return bundle_path_; }
287 const base::FilePath& GetTempDirPath() const { return temp_dir_.path(); }
289 base::MessageLoopProxy* GetIOMessageLoopProxy() {
290 return io_thread_.message_loop_proxy().get();
292 void Run() { loop_.Run(); }
294 private:
295 base::ScopedTempDir temp_dir_;
296 base::MessageLoopForUI loop_;
297 base::Thread io_thread_;
298 base::FilePath executable_path_, bundle_path_;
299 scoped_ptr<MockLaunchd> mock_launchd_;
300 scoped_ptr<Launchd::ScopedInstance> scoped_launchd_instance_;
301 ServiceProcessState service_process_state_;
304 void DeleteFunc(const base::FilePath& file) {
305 EXPECT_TRUE(base::DeleteFile(file, true));
308 void MoveFunc(const base::FilePath& from, const base::FilePath& to) {
309 EXPECT_TRUE(base::Move(from, to));
312 void ChangeAttr(const base::FilePath& from, int mode) {
313 EXPECT_EQ(chmod(from.value().c_str(), mode), 0);
316 class ScopedAttributesRestorer {
317 public:
318 ScopedAttributesRestorer(const base::FilePath& path, int mode)
319 : path_(path), mode_(mode) {
321 ~ScopedAttributesRestorer() {
322 ChangeAttr(path_, mode_);
324 private:
325 base::FilePath path_;
326 int mode_;
329 void TrashFunc(const base::FilePath& src) {
330 FSRef path_ref;
331 FSRef new_path_ref;
332 EXPECT_TRUE(base::mac::FSRefFromPath(src.value(), &path_ref));
333 OSStatus status = FSMoveObjectToTrashSync(&path_ref,
334 &new_path_ref,
335 kFSFileOperationDefaultOptions);
336 EXPECT_EQ(status, noErr) << "FSMoveObjectToTrashSync " << status;
339 TEST_F(ServiceProcessStateFileManipulationTest, VerifyLaunchD) {
340 // There have been problems where launchd has gotten into a bad state, usually
341 // because something had deleted all the files in /tmp. launchd depends on
342 // a Unix Domain Socket that it creates at /tmp/launchd*/sock.
343 // The symptom of this problem is that the service process connect fails
344 // on Mac and "launch_msg(): Socket is not connected" appears.
345 // This test is designed to make sure that launchd is working.
346 // http://crbug/75518
348 CommandLine cl(base::FilePath("/bin/launchctl"));
349 cl.AppendArg("list");
350 cl.AppendArg("com.apple.launchctl.Aqua");
352 std::string output;
353 int exit_code = -1;
354 ASSERT_TRUE(base::GetAppOutputWithExitCode(cl, &output, &exit_code)
355 && exit_code == 0)
356 << " exit_code:" << exit_code << " " << output;
359 TEST_F(ServiceProcessStateFileManipulationTest, DeleteFile) {
360 GetIOMessageLoopProxy()->PostTask(
361 FROM_HERE,
362 base::Bind(&DeleteFunc, executable_path()));
363 Run();
364 ASSERT_TRUE(mock_launchd()->remove_called());
365 ASSERT_TRUE(mock_launchd()->delete_called());
368 TEST_F(ServiceProcessStateFileManipulationTest, DeleteBundle) {
369 GetIOMessageLoopProxy()->PostTask(
370 FROM_HERE,
371 base::Bind(&DeleteFunc, bundle_path()));
372 Run();
373 ASSERT_TRUE(mock_launchd()->remove_called());
374 ASSERT_TRUE(mock_launchd()->delete_called());
377 TEST_F(ServiceProcessStateFileManipulationTest, MoveBundle) {
378 base::FilePath new_loc = GetTempDirPath().AppendASCII("MoveBundle");
379 GetIOMessageLoopProxy()->PostTask(
380 FROM_HERE,
381 base::Bind(&MoveFunc, bundle_path(), new_loc));
382 Run();
383 ASSERT_TRUE(mock_launchd()->restart_called());
384 ASSERT_TRUE(mock_launchd()->write_called());
387 TEST_F(ServiceProcessStateFileManipulationTest, MoveFile) {
388 base::FilePath new_loc = GetTempDirPath().AppendASCII("MoveFile");
389 GetIOMessageLoopProxy()->PostTask(
390 FROM_HERE,
391 base::Bind(&MoveFunc, executable_path(), new_loc));
392 Run();
393 ASSERT_TRUE(mock_launchd()->remove_called());
394 ASSERT_TRUE(mock_launchd()->delete_called());
397 TEST_F(ServiceProcessStateFileManipulationTest, TrashBundle) {
398 FSRef bundle_ref;
399 ASSERT_TRUE(base::mac::FSRefFromPath(bundle_path().value(), &bundle_ref));
400 GetIOMessageLoopProxy()->PostTask(
401 FROM_HERE,
402 base::Bind(&TrashFunc, bundle_path()));
403 Run();
404 ASSERT_TRUE(mock_launchd()->remove_called());
405 ASSERT_TRUE(mock_launchd()->delete_called());
406 std::string path(base::mac::PathFromFSRef(bundle_ref));
407 base::FilePath file_path(path);
408 ASSERT_TRUE(base::DeleteFile(file_path, true));
411 TEST_F(ServiceProcessStateFileManipulationTest, ChangeAttr) {
412 ScopedAttributesRestorer restorer(bundle_path(), 0777);
413 GetIOMessageLoopProxy()->PostTask(
414 FROM_HERE,
415 base::Bind(&ChangeAttr, bundle_path(), 0222));
416 Run();
417 ASSERT_TRUE(mock_launchd()->remove_called());
418 ASSERT_TRUE(mock_launchd()->delete_called());
421 #endif // !OS_MACOSX