1 // Copyright 2020 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 #include "chrome/browser/chromeos/device_name_store.h"
6 
7 #include "base/strings/string_util.h"
8 #include "chrome/common/pref_names.h"
9 #include "components/prefs/testing_pref_service.h"
10 #include "content/public/test/browser_task_environment.h"
11 #include "testing/gtest/include/gtest/gtest.h"
12 
13 namespace chromeos {
14 
15 class DeviceNameStoreTest : public ::testing::Test {
16  public:
DeviceNameStoreTest()17   DeviceNameStoreTest() {
18     DeviceNameStore::RegisterLocalStatePrefs(local_state_.registry());
19     device_name_store_.Initialize(&local_state_);
20   }
21   ~DeviceNameStoreTest() override = default;
22 
device_name_store()23   DeviceNameStore* device_name_store() { return &device_name_store_; }
24 
25  private:
26   // Run on the UI thread.
27   content::BrowserTaskEnvironment task_environment_;
28 
29   // Test backing store for prefs.
30   TestingPrefServiceSimple local_state_;
31 
32   DeviceNameStore device_name_store_;
33 };
34 
TEST_F(DeviceNameStoreTest,Initialize)35 TEST_F(DeviceNameStoreTest, Initialize) {
36   TestingPrefServiceSimple local_state;
37   DeviceNameStore device_name_store;
38 
39   DeviceNameStore::RegisterLocalStatePrefs(local_state.registry());
40 
41   // The device name is not set yet.
42   EXPECT_TRUE(local_state.GetString(prefs::kDeviceName).empty());
43 
44   device_name_store.Initialize(&local_state);
45 
46   // Initialize now set the device name and persisted it to the local state.
47   std::string device_name = device_name_store.GetDeviceName();
48   std::string persisted_device_name = local_state.GetString(prefs::kDeviceName);
49   EXPECT_FALSE(device_name.empty());
50   EXPECT_FALSE(persisted_device_name.empty());
51   EXPECT_EQ(device_name, persisted_device_name);
52 }
53 
54 // Tests that the format of the generated device name matches the form
55 // ChromeOS_123456.
TEST_F(DeviceNameStoreTest,GenerateDeviceName)56 TEST_F(DeviceNameStoreTest, GenerateDeviceName) {
57   // The device name is already generated at this point because of the call to
58   // Initialize during test setup.
59   std::string device_name = device_name_store()->GetDeviceName();
60   EXPECT_TRUE(base::StartsWith(device_name, "ChromeOS_"));
61 
62   // Check that the string after the prefix is composed of digits.
63   std::string digits = device_name.substr(strlen("ChromeOS_"));
64   for (size_t i = 0; i < digits.length(); ++i) {
65     EXPECT_TRUE(base::IsAsciiDigit(digits[i]));
66   }
67 }
68 
69 }  // namespace chromeos
70