metrics_state_manager_unittest.cc 31 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768
  1. // Copyright 2014 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. #include "components/metrics/metrics_state_manager.h"
  5. #include <ctype.h>
  6. #include <stddef.h>
  7. #include <stdint.h>
  8. #include <memory>
  9. #include <string>
  10. #include <utility>
  11. #include "base/bind.h"
  12. #include "base/command_line.h"
  13. #include "base/files/file_path.h"
  14. #include "base/strings/string_number_conversions.h"
  15. #include "base/strings/string_util.h"
  16. #include "base/test/metrics/histogram_tester.h"
  17. #include "base/test/scoped_feature_list.h"
  18. #include "build/build_config.h"
  19. #include "components/metrics/client_info.h"
  20. #include "components/metrics/metrics_data_validation.h"
  21. #include "components/metrics/metrics_log.h"
  22. #include "components/metrics/metrics_pref_names.h"
  23. #include "components/metrics/metrics_service.h"
  24. #include "components/metrics/metrics_switches.h"
  25. #include "components/metrics/test/test_enabled_state_provider.h"
  26. #include "components/prefs/testing_pref_service.h"
  27. #include "components/variations/pref_names.h"
  28. #include "testing/gmock/include/gmock/gmock.h"
  29. #include "testing/gtest/include/gtest/gtest.h"
  30. namespace metrics {
  31. namespace {
  32. // Verifies that the client id follows the expected pattern.
  33. void VerifyClientId(const std::string& client_id) {
  34. EXPECT_EQ(36U, client_id.length());
  35. for (size_t i = 0; i < client_id.length(); ++i) {
  36. char current = client_id[i];
  37. if (i == 8 || i == 13 || i == 18 || i == 23)
  38. EXPECT_EQ('-', current);
  39. else
  40. EXPECT_TRUE(isxdigit(current));
  41. }
  42. }
  43. MATCHER(HaveClonedInstallInfo, "") {
  44. return (
  45. !arg.FindPreference(prefs::kClonedResetCount)->IsDefaultValue() &&
  46. !arg.FindPreference(prefs::kFirstClonedResetTimestamp)
  47. ->IsDefaultValue() &&
  48. !arg.FindPreference(prefs::kLastClonedResetTimestamp)->IsDefaultValue());
  49. }
  50. MATCHER(HaveNoClonedInstallInfo, "") {
  51. return (
  52. arg.FindPreference(prefs::kClonedResetCount)->IsDefaultValue() &&
  53. arg.FindPreference(prefs::kFirstClonedResetTimestamp)->IsDefaultValue() &&
  54. arg.FindPreference(prefs::kLastClonedResetTimestamp)->IsDefaultValue());
  55. }
  56. } // namespace
  57. class MetricsStateManagerTest : public testing::Test {
  58. public:
  59. MetricsStateManagerTest()
  60. : test_begin_time_(base::Time::Now().ToTimeT()),
  61. enabled_state_provider_(new TestEnabledStateProvider(false, false)) {
  62. MetricsService::RegisterPrefs(prefs_.registry());
  63. }
  64. MetricsStateManagerTest(const MetricsStateManagerTest&) = delete;
  65. MetricsStateManagerTest& operator=(const MetricsStateManagerTest&) = delete;
  66. std::unique_ptr<MetricsStateManager> CreateStateManager(
  67. const std::string& external_client_id = "") {
  68. std::unique_ptr<MetricsStateManager> state_manager =
  69. MetricsStateManager::Create(
  70. &prefs_, enabled_state_provider_.get(), std::wstring(),
  71. base::FilePath(), StartupVisibility::kUnknown,
  72. base::BindRepeating(
  73. &MetricsStateManagerTest::MockStoreClientInfoBackup,
  74. base::Unretained(this)),
  75. base::BindRepeating(
  76. &MetricsStateManagerTest::LoadFakeClientInfoBackup,
  77. base::Unretained(this)),
  78. external_client_id);
  79. state_manager->InstantiateFieldTrialList();
  80. return state_manager;
  81. }
  82. // Sets metrics reporting as enabled for testing.
  83. void EnableMetricsReporting() {
  84. enabled_state_provider_->set_consent(true);
  85. enabled_state_provider_->set_enabled(true);
  86. }
  87. void SetClientInfoPrefs(const ClientInfo& client_info) {
  88. prefs_.SetString(prefs::kMetricsClientID, client_info.client_id);
  89. prefs_.SetInt64(prefs::kInstallDate, client_info.installation_date);
  90. prefs_.SetInt64(prefs::kMetricsReportingEnabledTimestamp,
  91. client_info.reporting_enabled_date);
  92. }
  93. void SetFakeClientInfoBackup(const ClientInfo& client_info) {
  94. fake_client_info_backup_ = std::make_unique<ClientInfo>();
  95. fake_client_info_backup_->client_id = client_info.client_id;
  96. fake_client_info_backup_->installation_date = client_info.installation_date;
  97. fake_client_info_backup_->reporting_enabled_date =
  98. client_info.reporting_enabled_date;
  99. }
  100. // The number of times that the code tries to load ClientInfo.
  101. int client_info_load_count_ = 0;
  102. protected:
  103. TestingPrefServiceSimple prefs_;
  104. // Last ClientInfo stored by the MetricsStateManager via
  105. // MockStoreClientInfoBackup.
  106. std::unique_ptr<ClientInfo> stored_client_info_backup_;
  107. // If set, will be returned via LoadFakeClientInfoBackup if requested by the
  108. // MetricsStateManager.
  109. std::unique_ptr<ClientInfo> fake_client_info_backup_;
  110. const int64_t test_begin_time_;
  111. private:
  112. // Stores the |client_info| in |stored_client_info_backup_| for verification
  113. // by the tests later.
  114. void MockStoreClientInfoBackup(const ClientInfo& client_info) {
  115. stored_client_info_backup_ = std::make_unique<ClientInfo>();
  116. stored_client_info_backup_->client_id = client_info.client_id;
  117. stored_client_info_backup_->installation_date =
  118. client_info.installation_date;
  119. stored_client_info_backup_->reporting_enabled_date =
  120. client_info.reporting_enabled_date;
  121. // Respect the contract that storing an empty client_id voids the existing
  122. // backup (required for the last section of the ForceClientIdCreation test
  123. // below).
  124. if (client_info.client_id.empty())
  125. fake_client_info_backup_.reset();
  126. }
  127. // Hands out a copy of |fake_client_info_backup_| if it is set.
  128. std::unique_ptr<ClientInfo> LoadFakeClientInfoBackup() {
  129. ++client_info_load_count_;
  130. if (!fake_client_info_backup_)
  131. return nullptr;
  132. std::unique_ptr<ClientInfo> backup_copy(new ClientInfo);
  133. backup_copy->client_id = fake_client_info_backup_->client_id;
  134. backup_copy->installation_date =
  135. fake_client_info_backup_->installation_date;
  136. backup_copy->reporting_enabled_date =
  137. fake_client_info_backup_->reporting_enabled_date;
  138. return backup_copy;
  139. }
  140. std::unique_ptr<TestEnabledStateProvider> enabled_state_provider_;
  141. };
  142. TEST_F(MetricsStateManagerTest, ClientIdCorrectlyFormatted_ConsentInitially) {
  143. // With consent set initially, client id should be created in the constructor.
  144. EnableMetricsReporting();
  145. std::unique_ptr<MetricsStateManager> state_manager(CreateStateManager());
  146. const std::string client_id = state_manager->client_id();
  147. VerifyClientId(client_id);
  148. }
  149. TEST_F(MetricsStateManagerTest, ClientIdCorrectlyFormatted_ConsentLater) {
  150. // With consent set initially, client id should be created on consent grant.
  151. std::unique_ptr<MetricsStateManager> state_manager(CreateStateManager());
  152. EXPECT_EQ(std::string(), state_manager->client_id());
  153. EnableMetricsReporting();
  154. state_manager->ForceClientIdCreation();
  155. const std::string client_id = state_manager->client_id();
  156. VerifyClientId(client_id);
  157. }
  158. TEST_F(MetricsStateManagerTest, EntropySourceUsed_Low) {
  159. // Set the install date pref, which makes sure we don't trigger the first run
  160. // behavior where a provisional client id is generated and used to return a
  161. // high entropy source.
  162. prefs_.SetInt64(prefs::kInstallDate, base::Time::Now().ToTimeT());
  163. std::unique_ptr<MetricsStateManager> state_manager(CreateStateManager());
  164. state_manager->CreateDefaultEntropyProvider();
  165. EXPECT_EQ(state_manager->entropy_source_returned(),
  166. MetricsStateManager::ENTROPY_SOURCE_LOW);
  167. EXPECT_EQ(state_manager->initial_client_id_for_testing(), "");
  168. }
  169. TEST_F(MetricsStateManagerTest, EntropySourceUsed_High) {
  170. EnableMetricsReporting();
  171. std::unique_ptr<MetricsStateManager> state_manager(CreateStateManager());
  172. state_manager->CreateDefaultEntropyProvider();
  173. EXPECT_EQ(state_manager->entropy_source_returned(),
  174. MetricsStateManager::ENTROPY_SOURCE_HIGH);
  175. EXPECT_EQ(state_manager->initial_client_id_for_testing(),
  176. state_manager->client_id());
  177. }
  178. // Check that setting the kMetricsResetIds pref to true causes the client id to
  179. // be reset. We do not check that the low entropy source is reset because we
  180. // cannot ensure that metrics state manager won't generate the same id again.
  181. TEST_F(MetricsStateManagerTest, ResetMetricsIDs) {
  182. // Set an initial client id in prefs. It should not be possible for the
  183. // metrics state manager to generate this id randomly.
  184. const std::string kInitialClientId = "initial client id";
  185. prefs_.SetString(prefs::kMetricsClientID, kInitialClientId);
  186. EnableMetricsReporting();
  187. // No cloned install info should have been stored.
  188. EXPECT_THAT(prefs_, HaveNoClonedInstallInfo());
  189. // Make sure the initial client id isn't reset by the metrics state manager.
  190. {
  191. std::unique_ptr<MetricsStateManager> state_manager(CreateStateManager());
  192. state_manager->ForceClientIdCreation();
  193. EXPECT_EQ(state_manager->client_id(), kInitialClientId);
  194. EXPECT_FALSE(state_manager->metrics_ids_were_reset_);
  195. EXPECT_THAT(prefs_, HaveNoClonedInstallInfo());
  196. }
  197. // Set the reset pref to cause the IDs to be reset.
  198. prefs_.SetBoolean(prefs::kMetricsResetIds, true);
  199. // Cause the actual reset to happen.
  200. {
  201. std::unique_ptr<MetricsStateManager> state_manager(CreateStateManager());
  202. state_manager->ForceClientIdCreation();
  203. EXPECT_NE(state_manager->client_id(), kInitialClientId);
  204. EXPECT_TRUE(state_manager->metrics_ids_were_reset_);
  205. EXPECT_EQ(state_manager->previous_client_id_, kInitialClientId);
  206. EXPECT_EQ(client_info_load_count_, 0);
  207. state_manager->GetLowEntropySource();
  208. EXPECT_FALSE(prefs_.GetBoolean(prefs::kMetricsResetIds));
  209. EXPECT_THAT(prefs_, HaveClonedInstallInfo());
  210. EXPECT_EQ(prefs_.GetInteger(prefs::kClonedResetCount), 1);
  211. EXPECT_EQ(prefs_.GetInt64(prefs::kFirstClonedResetTimestamp),
  212. prefs_.GetInt64(prefs::kLastClonedResetTimestamp));
  213. }
  214. EXPECT_NE(prefs_.GetString(prefs::kMetricsClientID), kInitialClientId);
  215. }
  216. TEST_F(MetricsStateManagerTest, LogHasSessionShutdownCleanly) {
  217. std::unique_ptr<MetricsStateManager> state_manager(CreateStateManager());
  218. prefs_.SetBoolean(prefs::kStabilityExitedCleanly, false);
  219. state_manager->LogHasSessionShutdownCleanly(
  220. /*has_session_shutdown_cleanly=*/true);
  221. EXPECT_TRUE(prefs_.GetBoolean(prefs::kStabilityExitedCleanly));
  222. }
  223. TEST_F(MetricsStateManagerTest, LogSessionHasNotYetShutdownCleanly) {
  224. std::unique_ptr<MetricsStateManager> state_manager(CreateStateManager());
  225. ASSERT_TRUE(prefs_.GetBoolean(prefs::kStabilityExitedCleanly));
  226. state_manager->LogHasSessionShutdownCleanly(
  227. /*has_session_shutdown_cleanly=*/false);
  228. EXPECT_FALSE(prefs_.GetBoolean(prefs::kStabilityExitedCleanly));
  229. }
  230. TEST_F(MetricsStateManagerTest, ForceClientIdCreation) {
  231. const int64_t kFakeInstallationDate = 12345;
  232. prefs_.SetInt64(prefs::kInstallDate, kFakeInstallationDate);
  233. {
  234. std::unique_ptr<MetricsStateManager> state_manager(CreateStateManager());
  235. // client_id shouldn't be auto-generated if metrics reporting is not
  236. // enabled.
  237. EXPECT_EQ(state_manager->client_id(), std::string());
  238. EXPECT_EQ(prefs_.GetInt64(prefs::kMetricsReportingEnabledTimestamp), 0);
  239. // Confirm that the initial ForceClientIdCreation call creates the client id
  240. // and backs it up via MockStoreClientInfoBackup.
  241. EXPECT_FALSE(stored_client_info_backup_);
  242. EnableMetricsReporting();
  243. state_manager->ForceClientIdCreation();
  244. EXPECT_NE(state_manager->client_id(), std::string());
  245. EXPECT_GE(prefs_.GetInt64(prefs::kMetricsReportingEnabledTimestamp),
  246. test_begin_time_);
  247. ASSERT_TRUE(stored_client_info_backup_);
  248. EXPECT_EQ(client_info_load_count_, 1);
  249. EXPECT_EQ(state_manager->client_id(),
  250. stored_client_info_backup_->client_id);
  251. EXPECT_EQ(stored_client_info_backup_->installation_date,
  252. kFakeInstallationDate);
  253. EXPECT_EQ(prefs_.GetInt64(prefs::kMetricsReportingEnabledTimestamp),
  254. stored_client_info_backup_->reporting_enabled_date);
  255. }
  256. }
  257. TEST_F(MetricsStateManagerTest,
  258. ForceClientIdCreation_ConsentIntitially_NoInstallDate) {
  259. // Confirm that the initial ForceClientIdCreation call creates the install
  260. // date and then backs it up via MockStoreClientInfoBackup.
  261. EXPECT_FALSE(stored_client_info_backup_);
  262. EnableMetricsReporting();
  263. std::unique_ptr<MetricsStateManager> state_manager(CreateStateManager());
  264. ASSERT_TRUE(stored_client_info_backup_);
  265. EXPECT_NE(stored_client_info_backup_->installation_date, 0);
  266. EXPECT_EQ(client_info_load_count_, 1);
  267. }
  268. #if !BUILDFLAG(IS_WIN)
  269. TEST_F(MetricsStateManagerTest, ProvisionalClientId_PromotedToClientId) {
  270. // Force enable the creation of a provisional client ID on first run for
  271. // consistency between Chromium and Chrome builds.
  272. MetricsStateManager::enable_provisional_client_id_for_testing_ = true;
  273. std::unique_ptr<MetricsStateManager> state_manager(CreateStateManager());
  274. // Verify that there was a provisional client id created.
  275. std::string provisional_client_id =
  276. prefs_.GetString(prefs::kMetricsProvisionalClientID);
  277. VerifyClientId(provisional_client_id);
  278. // No client id should have been stored.
  279. EXPECT_TRUE(prefs_.FindPreference(prefs::kMetricsClientID)->IsDefaultValue());
  280. int low_entropy_source = state_manager->GetLowEntropySource();
  281. // The default entropy provider should be the high entropy one since we a
  282. // the provisional client ID.
  283. state_manager->CreateDefaultEntropyProvider();
  284. EXPECT_EQ(state_manager->entropy_source_returned(),
  285. MetricsStateManager::ENTROPY_SOURCE_HIGH);
  286. // Forcing client id creation should promote the provisional client id to
  287. // become the real client id and keep the low entropy source.
  288. EnableMetricsReporting();
  289. state_manager->ForceClientIdCreation();
  290. std::string client_id = state_manager->client_id();
  291. EXPECT_EQ(provisional_client_id, client_id);
  292. EXPECT_EQ(prefs_.GetString(prefs::kMetricsClientID), client_id);
  293. EXPECT_TRUE(prefs_.FindPreference(prefs::kMetricsProvisionalClientID)
  294. ->IsDefaultValue());
  295. EXPECT_TRUE(prefs_.GetString(prefs::kMetricsProvisionalClientID).empty());
  296. EXPECT_EQ(state_manager->GetLowEntropySource(), low_entropy_source);
  297. EXPECT_EQ(client_info_load_count_, 1);
  298. }
  299. TEST_F(MetricsStateManagerTest, ProvisionalClientId_PersistedAcrossFirstRuns) {
  300. // Force enable the creation of a provisional client ID on first run for
  301. // consistency between Chromium and Chrome builds.
  302. MetricsStateManager::enable_provisional_client_id_for_testing_ = true;
  303. std::string provisional_client_id;
  304. // Simulate a first run, and verify that a provisional client id is generated.
  305. // We also do not enable nor disable UMA in order to simulate exiting during
  306. // the first run flow.
  307. {
  308. std::unique_ptr<MetricsStateManager> state_manager(CreateStateManager());
  309. // Verify that there was a provisional client id created.
  310. provisional_client_id =
  311. prefs_.GetString(prefs::kMetricsProvisionalClientID);
  312. VerifyClientId(provisional_client_id);
  313. // No client id should have been stored.
  314. EXPECT_TRUE(
  315. prefs_.FindPreference(prefs::kMetricsClientID)->IsDefaultValue());
  316. // The default entropy provider should be the high entropy one since we a
  317. // the provisional client ID.
  318. state_manager->CreateDefaultEntropyProvider();
  319. EXPECT_EQ(state_manager->entropy_source_returned(),
  320. MetricsStateManager::ENTROPY_SOURCE_HIGH);
  321. }
  322. // Now, simulate a second run, and verify that the provisional client ID is
  323. // the same.
  324. {
  325. std::unique_ptr<MetricsStateManager> state_manager(CreateStateManager());
  326. // Verify that the same provisional client ID as the first run is used.
  327. EXPECT_EQ(provisional_client_id,
  328. prefs_.GetString(prefs::kMetricsProvisionalClientID));
  329. // There still should not be any stored client ID.
  330. EXPECT_TRUE(prefs_.FindPreference(prefs::kMetricsClientID));
  331. // The default entropy provider should be the high entropy one since we a
  332. // the provisional client ID.
  333. state_manager->CreateDefaultEntropyProvider();
  334. EXPECT_EQ(state_manager->entropy_source_returned(),
  335. MetricsStateManager::ENTROPY_SOURCE_HIGH);
  336. }
  337. }
  338. #endif // !BUILDFLAG(IS_WIN)
  339. TEST_F(MetricsStateManagerTest, LoadPrefs) {
  340. ClientInfo client_info;
  341. client_info.client_id = "AAAAAAAA-BBBB-CCCC-DDDD-EEEEEEEEEEEF";
  342. client_info.installation_date = 1112;
  343. client_info.reporting_enabled_date = 2223;
  344. SetClientInfoPrefs(client_info);
  345. EnableMetricsReporting();
  346. {
  347. EXPECT_FALSE(fake_client_info_backup_);
  348. EXPECT_FALSE(stored_client_info_backup_);
  349. std::unique_ptr<MetricsStateManager> state_manager(CreateStateManager());
  350. // client_id should be auto-obtained from the constructor when metrics
  351. // reporting is enabled.
  352. EXPECT_EQ(state_manager->client_id(), client_info.client_id);
  353. // The backup should not be modified.
  354. ASSERT_FALSE(stored_client_info_backup_);
  355. // Re-forcing client id creation shouldn't cause another backup and
  356. // shouldn't affect the existing client id.
  357. state_manager->ForceClientIdCreation();
  358. EXPECT_FALSE(stored_client_info_backup_);
  359. EXPECT_EQ(state_manager->client_id(), client_info.client_id);
  360. EXPECT_EQ(client_info_load_count_, 0);
  361. }
  362. }
  363. TEST_F(MetricsStateManagerTest, PreferPrefs) {
  364. ClientInfo client_info;
  365. client_info.client_id = "AAAAAAAA-BBBB-CCCC-DDDD-EEEEEEEEEEEF";
  366. client_info.installation_date = 1112;
  367. client_info.reporting_enabled_date = 2223;
  368. SetClientInfoPrefs(client_info);
  369. ClientInfo client_info2;
  370. client_info2.client_id = "AAAAAAAA-BBBB-CCCC-DDDD-EEEEEEEEEEEE";
  371. client_info2.installation_date = 1111;
  372. client_info2.reporting_enabled_date = 2222;
  373. SetFakeClientInfoBackup(client_info2);
  374. EnableMetricsReporting();
  375. {
  376. // The backup should be ignored if we already have a client id.
  377. EXPECT_FALSE(stored_client_info_backup_);
  378. std::unique_ptr<MetricsStateManager> state_manager(CreateStateManager());
  379. EXPECT_EQ(state_manager->client_id(), client_info.client_id);
  380. // The backup should not be modified.
  381. ASSERT_FALSE(stored_client_info_backup_);
  382. EXPECT_EQ(client_info_load_count_, 0);
  383. }
  384. }
  385. TEST_F(MetricsStateManagerTest, RestoreBackup) {
  386. ClientInfo client_info;
  387. client_info.client_id = "AAAAAAAA-BBBB-CCCC-DDDD-EEEEEEEEEEEF";
  388. client_info.installation_date = 1112;
  389. client_info.reporting_enabled_date = 2223;
  390. SetClientInfoPrefs(client_info);
  391. ClientInfo client_info2;
  392. client_info2.client_id = "AAAAAAAA-BBBB-CCCC-DDDD-EEEEEEEEEEEE";
  393. client_info2.installation_date = 1111;
  394. client_info2.reporting_enabled_date = 2222;
  395. SetFakeClientInfoBackup(client_info2);
  396. prefs_.ClearPref(prefs::kMetricsClientID);
  397. prefs_.ClearPref(prefs::kMetricsReportingEnabledTimestamp);
  398. EnableMetricsReporting();
  399. {
  400. // The backup should kick in if the client id has gone missing. It should
  401. // replace remaining and missing dates as well.
  402. EXPECT_FALSE(stored_client_info_backup_);
  403. std::unique_ptr<MetricsStateManager> state_manager(CreateStateManager());
  404. EXPECT_EQ(state_manager->client_id(), client_info2.client_id);
  405. EXPECT_EQ(prefs_.GetInt64(prefs::kInstallDate),
  406. client_info2.installation_date);
  407. EXPECT_EQ(prefs_.GetInt64(prefs::kMetricsReportingEnabledTimestamp),
  408. client_info2.reporting_enabled_date);
  409. EXPECT_TRUE(stored_client_info_backup_);
  410. EXPECT_EQ(client_info_load_count_, 1);
  411. }
  412. }
  413. TEST_F(MetricsStateManagerTest, ResetBackup) {
  414. ClientInfo client_info;
  415. client_info.client_id = "AAAAAAAA-BBBB-CCCC-DDDD-EEEEEEEEEEEE";
  416. client_info.installation_date = 1111;
  417. client_info.reporting_enabled_date = 2222;
  418. SetFakeClientInfoBackup(client_info);
  419. SetClientInfoPrefs(client_info);
  420. prefs_.SetBoolean(prefs::kMetricsResetIds, true);
  421. EnableMetricsReporting();
  422. {
  423. // Upon request to reset metrics ids, the existing backup should not be
  424. // restored.
  425. std::unique_ptr<MetricsStateManager> state_manager(CreateStateManager());
  426. // A brand new client id should have been generated.
  427. EXPECT_NE(state_manager->client_id(), std::string());
  428. EXPECT_NE(state_manager->client_id(), client_info.client_id);
  429. EXPECT_TRUE(state_manager->metrics_ids_were_reset_);
  430. EXPECT_EQ(state_manager->previous_client_id_, client_info.client_id);
  431. EXPECT_TRUE(stored_client_info_backup_);
  432. EXPECT_EQ(client_info_load_count_, 0);
  433. // The installation date should not have been affected.
  434. EXPECT_EQ(prefs_.GetInt64(prefs::kInstallDate),
  435. client_info.installation_date);
  436. // The metrics-reporting-enabled date will be reset to Now().
  437. EXPECT_GE(prefs_.GetInt64(prefs::kMetricsReportingEnabledTimestamp),
  438. test_begin_time_);
  439. }
  440. }
  441. TEST_F(MetricsStateManagerTest, CheckProvider) {
  442. int64_t kInstallDate = 1373051956;
  443. int64_t kInstallDateExpected = 1373050800; // Computed from kInstallDate.
  444. int64_t kEnabledDate = 1373001211;
  445. int64_t kEnabledDateExpected = 1373000400; // Computed from kEnabledDate.
  446. ClientInfo client_info;
  447. client_info.client_id = "AAAAAAAA-BBBB-CCCC-DDDD-EEEEEEEEEEEE";
  448. client_info.installation_date = kInstallDate;
  449. client_info.reporting_enabled_date = kEnabledDate;
  450. SetFakeClientInfoBackup(client_info);
  451. SetClientInfoPrefs(client_info);
  452. std::unique_ptr<MetricsStateManager> state_manager(CreateStateManager());
  453. std::unique_ptr<MetricsProvider> provider = state_manager->GetProvider();
  454. SystemProfileProto system_profile;
  455. provider->ProvideSystemProfileMetrics(&system_profile);
  456. EXPECT_EQ(system_profile.install_date(), kInstallDateExpected);
  457. EXPECT_EQ(system_profile.uma_enabled_date(), kEnabledDateExpected);
  458. base::HistogramTester histogram_tester;
  459. ChromeUserMetricsExtension uma_proto;
  460. provider->ProvidePreviousSessionData(&uma_proto);
  461. // The client_id field in the proto should not be overwritten.
  462. EXPECT_FALSE(uma_proto.has_client_id());
  463. // Nothing should have been emitted to the cloned install histogram.
  464. histogram_tester.ExpectTotalCount("UMA.IsClonedInstall", 0);
  465. }
  466. TEST_F(MetricsStateManagerTest, CheckProviderLogNormal) {
  467. base::test::ScopedFeatureList scoped_feature_list;
  468. std::unique_ptr<MetricsStateManager> state_manager(CreateStateManager());
  469. // Set the random seed to have a deterministic test.
  470. std::unique_ptr<MetricsProvider> provider =
  471. state_manager->GetProviderAndSetRandomSeedForTesting(42);
  472. base::HistogramTester histogram_tester;
  473. ChromeUserMetricsExtension uma_proto;
  474. provider->ProvideCurrentSessionData(&uma_proto);
  475. histogram_tester.ExpectUniqueSample("UMA.DataValidation.LogNormal", 189, 1);
  476. }
  477. TEST_F(MetricsStateManagerTest, CheckProviderLogNormalWithParams) {
  478. base::test::ScopedFeatureList scoped_feature_list;
  479. scoped_feature_list.InitAndEnableFeatureWithParameters(
  480. kNonUniformityValidationFeature, {{"delta", "10.0"}});
  481. std::unique_ptr<MetricsStateManager> state_manager(CreateStateManager());
  482. // Set the random seed to have a deterministic test.
  483. std::unique_ptr<MetricsProvider> provider =
  484. state_manager->GetProviderAndSetRandomSeedForTesting(42);
  485. base::HistogramTester histogram_tester;
  486. ChromeUserMetricsExtension uma_proto;
  487. provider->ProvideCurrentSessionData(&uma_proto);
  488. histogram_tester.ExpectUniqueSample("UMA.DataValidation.LogNormal", 2081, 1);
  489. }
  490. TEST_F(MetricsStateManagerTest, CheckClientIdWasNotUsedToAssignFieldTrial) {
  491. EnableMetricsReporting();
  492. ClientInfo client_info;
  493. client_info.client_id = "AAAAAAAA-BBBB-CCCC-DDDD-EEEEEEEEEEEE";
  494. client_info.installation_date = 1373051956;
  495. client_info.reporting_enabled_date = 1373001211;
  496. SetFakeClientInfoBackup(client_info);
  497. SetClientInfoPrefs(client_info);
  498. std::unique_ptr<MetricsStateManager> state_manager(CreateStateManager());
  499. std::unique_ptr<MetricsProvider> provider = state_manager->GetProvider();
  500. // The client_id in the new log doesn't match the initial_client_id we used to
  501. // assign field trials.
  502. prefs_.SetString(prefs::kMetricsClientID, "New client id");
  503. SystemProfileProto system_profile;
  504. provider->ProvideSystemProfileMetrics(&system_profile);
  505. EXPECT_TRUE(system_profile.has_client_id_was_used_for_trial_assignment());
  506. EXPECT_FALSE(system_profile.client_id_was_used_for_trial_assignment());
  507. }
  508. TEST_F(MetricsStateManagerTest, CheckClientIdWasUsedToAssignFieldTrial) {
  509. EnableMetricsReporting();
  510. ClientInfo client_info;
  511. client_info.client_id = "AAAAAAAA-BBBB-CCCC-DDDD-EEEEEEEEEEEE";
  512. client_info.installation_date = 1373051956;
  513. client_info.reporting_enabled_date = 1373001211;
  514. SetFakeClientInfoBackup(client_info);
  515. SetClientInfoPrefs(client_info);
  516. std::unique_ptr<MetricsStateManager> state_manager(CreateStateManager());
  517. std::unique_ptr<MetricsProvider> provider = state_manager->GetProvider();
  518. SystemProfileProto system_profile;
  519. provider->ProvideSystemProfileMetrics(&system_profile);
  520. EXPECT_TRUE(system_profile.client_id_was_used_for_trial_assignment());
  521. }
  522. TEST_F(MetricsStateManagerTest, CheckProviderResetIds) {
  523. int64_t kInstallDate = 1373001211;
  524. int64_t kInstallDateExpected = 1373000400; // Computed from kInstallDate.
  525. int64_t kEnabledDate = 1373051956;
  526. int64_t kEnabledDateExpected = 1373050800; // Computed from kEnabledDate.
  527. ClientInfo client_info;
  528. client_info.client_id = "AAAAAAAA-BBBB-CCCC-DDDD-EEEEEEEEEEEE";
  529. client_info.installation_date = kInstallDate;
  530. client_info.reporting_enabled_date = kEnabledDate;
  531. SetFakeClientInfoBackup(client_info);
  532. SetClientInfoPrefs(client_info);
  533. // Set the reset pref to cause the IDs to be reset.
  534. prefs_.SetBoolean(prefs::kMetricsResetIds, true);
  535. std::unique_ptr<MetricsStateManager> state_manager(CreateStateManager());
  536. // Verify that MetricsStateManager has the a new client_id after reset and has
  537. // the right previous_client_id (equals to the client_id before being reset).
  538. EXPECT_NE(state_manager->client_id(), client_info.client_id);
  539. EXPECT_TRUE(state_manager->metrics_ids_were_reset_);
  540. EXPECT_EQ(state_manager->previous_client_id_, client_info.client_id);
  541. EXPECT_EQ(client_info_load_count_, 0);
  542. uint64_t hashed_previous_client_id =
  543. MetricsLog::Hash(state_manager->previous_client_id_);
  544. std::unique_ptr<MetricsProvider> provider = state_manager->GetProvider();
  545. SystemProfileProto system_profile;
  546. provider->ProvideSystemProfileMetrics(&system_profile);
  547. EXPECT_EQ(system_profile.install_date(), kInstallDateExpected);
  548. EXPECT_EQ(system_profile.uma_enabled_date(), kEnabledDateExpected);
  549. auto cloned_install_info = system_profile.cloned_install_info();
  550. EXPECT_EQ(cloned_install_info.count(), 1);
  551. EXPECT_EQ(cloned_install_info.cloned_from_client_id(),
  552. hashed_previous_client_id);
  553. // Make sure the first_timestamp is updated and is the same as the
  554. // last_timestamp.
  555. EXPECT_EQ(cloned_install_info.last_timestamp(),
  556. cloned_install_info.first_timestamp());
  557. EXPECT_NE(cloned_install_info.first_timestamp(), 0);
  558. base::HistogramTester histogram_tester;
  559. ChromeUserMetricsExtension uma_proto;
  560. // The system_profile in the |uma_proto| is provided in
  561. // https://source.chromium.org/chromium/chromium/src/+/main:components/metrics/metrics_service.cc;drc=4b86ff6c58f5651a4e2f44abb22d93c3593155cb;l=759
  562. // and it's hard to be tested here. For logs from the previous session:
  563. // 1. if the previous session is the detection session, the
  564. // |uma_proto.system_profile| won't contain the latest cloned_install_info
  565. // message.
  566. // 2. if the previous session is a normal session, the
  567. // |uma_proto.system_profile| should contain the cloned_install_info message
  568. // as long as it's saved in prefs.
  569. provider->ProvidePreviousSessionData(&uma_proto);
  570. EXPECT_EQ(uma_proto.client_id(), hashed_previous_client_id);
  571. histogram_tester.ExpectUniqueSample("UMA.IsClonedInstall", 1, 1);
  572. // Since we set the pref and didn't call SaveMachineId(), this should do
  573. // nothing
  574. provider->ProvideCurrentSessionData(&uma_proto);
  575. histogram_tester.ExpectUniqueSample("UMA.IsClonedInstall", 1, 1);
  576. // Set the pref through SaveMachineId and expect previous to do nothing and
  577. // current to log the histogram
  578. prefs_.SetInteger(prefs::kMetricsMachineId, 2216820);
  579. state_manager->cloned_install_detector_.SaveMachineId(&prefs_, "test");
  580. provider->ProvideCurrentSessionData(&uma_proto);
  581. histogram_tester.ExpectUniqueSample("UMA.IsClonedInstall", 1, 2);
  582. }
  583. TEST_F(MetricsStateManagerTest,
  584. CheckProviderResetIds_PreviousIdOnlyReportInResetSession) {
  585. int64_t kInstallDate = 1373001211;
  586. int64_t kInstallDateExpected = 1373000400; // Computed from kInstallDate.
  587. int64_t kEnabledDate = 1373051956;
  588. int64_t kEnabledDateExpected = 1373050800; // Computed from kEnabledDate.
  589. ClientInfo client_info;
  590. client_info.client_id = "AAAAAAAA-BBBB-CCCC-DDDD-EEEEEEEEEEEE";
  591. client_info.installation_date = kInstallDate;
  592. client_info.reporting_enabled_date = kEnabledDate;
  593. SetFakeClientInfoBackup(client_info);
  594. SetClientInfoPrefs(client_info);
  595. // In the reset session:
  596. // Set the reset pref to cause the IDs to be reset.
  597. prefs_.SetBoolean(prefs::kMetricsResetIds, true);
  598. {
  599. std::unique_ptr<MetricsStateManager> state_manager(CreateStateManager());
  600. EXPECT_NE(state_manager->client_id(), client_info.client_id);
  601. EXPECT_TRUE(state_manager->metrics_ids_were_reset_);
  602. // Verify that MetricsStateManager has the right previous_client_id (the ID
  603. // that was there before being reset).
  604. EXPECT_EQ(state_manager->previous_client_id_, client_info.client_id);
  605. EXPECT_EQ(client_info_load_count_, 0);
  606. std::unique_ptr<MetricsProvider> provider = state_manager->GetProvider();
  607. SystemProfileProto system_profile;
  608. provider->ProvideSystemProfileMetrics(&system_profile);
  609. EXPECT_EQ(system_profile.install_date(), kInstallDateExpected);
  610. EXPECT_EQ(system_profile.uma_enabled_date(), kEnabledDateExpected);
  611. auto cloned_install_info = system_profile.cloned_install_info();
  612. // |cloned_from_client_id| should be uploaded in the reset session.
  613. EXPECT_EQ(cloned_install_info.cloned_from_client_id(),
  614. MetricsLog::Hash(state_manager->previous_client_id_));
  615. // Make sure the first_timestamp is updated and is the same as the
  616. // last_timestamp.
  617. EXPECT_EQ(cloned_install_info.count(), 1);
  618. EXPECT_EQ(cloned_install_info.last_timestamp(),
  619. cloned_install_info.first_timestamp());
  620. EXPECT_NE(cloned_install_info.last_timestamp(), 0);
  621. }
  622. // In the normal session:
  623. {
  624. std::unique_ptr<MetricsStateManager> state_manager(CreateStateManager());
  625. EXPECT_FALSE(state_manager->metrics_ids_were_reset_);
  626. std::unique_ptr<MetricsProvider> provider = state_manager->GetProvider();
  627. SystemProfileProto system_profile;
  628. provider->ProvideSystemProfileMetrics(&system_profile);
  629. auto cloned_install_info = system_profile.cloned_install_info();
  630. // |cloned_from_client_id| shouldn't be reported in the normal session.
  631. EXPECT_FALSE(cloned_install_info.has_cloned_from_client_id());
  632. // Other cloned_install_info fields should continue be reported once set.
  633. EXPECT_EQ(cloned_install_info.count(), 1);
  634. EXPECT_EQ(cloned_install_info.last_timestamp(),
  635. cloned_install_info.first_timestamp());
  636. EXPECT_NE(cloned_install_info.last_timestamp(), 0);
  637. }
  638. }
  639. TEST_F(MetricsStateManagerTest, UseExternalClientId) {
  640. base::HistogramTester histogram_tester;
  641. std::string external_client_id = "AAAAAAAA-BBBB-CCCC-DDDD-EEEEEEEEEEEE";
  642. std::unique_ptr<MetricsStateManager> state_manager(
  643. CreateStateManager(external_client_id));
  644. EnableMetricsReporting();
  645. state_manager->ForceClientIdCreation();
  646. EXPECT_EQ(external_client_id, state_manager->client_id());
  647. histogram_tester.ExpectUniqueSample("UMA.ClientIdSource", 5, 1);
  648. }
  649. } // namespace metrics