1 // Copyright 2013 The Chromium Authors
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/chrome_process_singleton.h"
7 #include "base/command_line.h"
8 #include "base/compiler_specific.h"
9 #include "base/files/file_path.h"
10 #include "base/files/scoped_temp_dir.h"
11 #include "base/functional/bind.h"
12 #include "base/functional/callback.h"
13 #include "build/build_config.h"
14 #include "testing/gtest/include/gtest/gtest.h"
18 bool ServerCallback(int* callback_count,
19 const base::CommandLine& command_line,
20 const base::FilePath& current_directory) {
25 bool ClientCallback(const base::CommandLine& command_line,
26 const base::FilePath& current_directory) {
33 TEST(ChromeProcessSingletonTest, Basic) {
34 base::ScopedTempDir profile_dir;
35 ASSERT_TRUE(profile_dir.CreateUniqueTempDir());
37 int callback_count = 0;
39 ChromeProcessSingleton ps1(profile_dir.GetPath());
41 base::BindRepeating(&ServerCallback, base::Unretained(&callback_count)));
43 ChromeProcessSingleton ps2(profile_dir.GetPath());
44 ps2.Unlock(base::BindRepeating(&ClientCallback));
46 EXPECT_FALSE(ps1.IsSingletonInstanceForTesting());
47 EXPECT_FALSE(ps2.IsSingletonInstanceForTesting());
49 ProcessSingleton::NotifyResult result = ps1.NotifyOtherProcessOrCreate();
51 ASSERT_EQ(ProcessSingleton::PROCESS_NONE, result);
52 ASSERT_EQ(0, callback_count);
54 result = ps2.NotifyOtherProcessOrCreate();
55 ASSERT_EQ(ProcessSingleton::PROCESS_NOTIFIED, result);
57 EXPECT_TRUE(ps1.IsSingletonInstanceForTesting());
58 EXPECT_FALSE(ps2.IsSingletonInstanceForTesting());
60 ASSERT_EQ(1, callback_count);
63 TEST(ChromeProcessSingletonTest, Lock) {
64 base::ScopedTempDir profile_dir;
65 ASSERT_TRUE(profile_dir.CreateUniqueTempDir());
67 int callback_count = 0;
69 ChromeProcessSingleton ps1(profile_dir.GetPath());
71 ChromeProcessSingleton ps2(profile_dir.GetPath());
72 ps2.Unlock(base::BindRepeating(&ClientCallback));
74 EXPECT_FALSE(ps1.IsSingletonInstanceForTesting());
75 EXPECT_FALSE(ps2.IsSingletonInstanceForTesting());
77 ProcessSingleton::NotifyResult result = ps1.NotifyOtherProcessOrCreate();
79 ASSERT_EQ(ProcessSingleton::PROCESS_NONE, result);
80 ASSERT_EQ(0, callback_count);
82 result = ps2.NotifyOtherProcessOrCreate();
83 ASSERT_EQ(ProcessSingleton::PROCESS_NOTIFIED, result);
85 ASSERT_EQ(0, callback_count);
87 base::BindRepeating(&ServerCallback, base::Unretained(&callback_count)));
88 ASSERT_EQ(1, callback_count);
90 EXPECT_TRUE(ps1.IsSingletonInstanceForTesting());
91 EXPECT_FALSE(ps2.IsSingletonInstanceForTesting());