Commit 34d462f6 authored by Roger McFarlane's avatar Roger McFarlane Committed by Commit Bot

Add end-to-end tests for demographic metrics in UMA and UKM

Bug: 992573
Change-Id: I5a27682828538c72fbe8fc71c78cbadc8fdef23e
Reviewed-on: https://chromium-review.googlesource.com/c/chromium/src/+/1872643
Commit-Queue: Roger McFarlane <rogerm@chromium.org>
Reviewed-by: default avatarAlexei Svitkine <asvitkine@chromium.org>
Reviewed-by: default avatarRobert Kaplow <rkaplow@chromium.org>
Cr-Commit-Position: refs/heads/master@{#728621}
parent 188ae61d
...@@ -4,6 +4,32 @@ ...@@ -4,6 +4,32 @@
import("//components/metrics/generate_expired_histograms_array.gni") import("//components/metrics/generate_expired_histograms_array.gni")
static_library("test_support") {
testonly = true
sources = [
"testing/demographic_metrics_test_utils.cc",
"testing/demographic_metrics_test_utils.h",
"testing/sync_metrics_test_utils.cc",
"testing/sync_metrics_test_utils.h",
]
deps = [
"//base",
"//chrome/browser",
"//components/network_time",
"//components/prefs",
"//components/signin/public/identity_manager",
"//components/sync",
"//components/sync/base",
"//components/sync/test/fake_server",
"//third_party/metrics_proto",
]
if (!is_android && !is_fuchsia) {
deps += [ "//chrome/test:sync_integration_test_support" ]
}
}
generate_expired_histograms_array("expired_histograms_array") { generate_expired_histograms_array("expired_histograms_array") {
inputs = [ inputs = [
"//tools/metrics/histograms/histograms.xml", "//tools/metrics/histograms/histograms.xml",
......
// Copyright 2019 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "components/metrics/metrics_service.h"
#include <string>
#include <vector>
#include "base/command_line.h"
#include "base/feature_list.h"
#include "base/memory/weak_ptr.h"
#include "base/optional.h"
#include "base/test/metrics/histogram_tester.h"
#include "chrome/browser/browser_process.h"
#include "chrome/browser/metrics/chrome_metrics_service_accessor.h"
#include "chrome/browser/metrics/chrome_metrics_services_manager_client.h"
#include "chrome/browser/metrics/testing/demographic_metrics_test_utils.h"
#include "chrome/browser/metrics/testing/sync_metrics_test_utils.h"
#include "chrome/browser/profiles/profile.h"
#include "chrome/browser/profiles/profile_manager.h"
#include "chrome/browser/sync/test/integration/profile_sync_service_harness.h"
#include "chrome/browser/sync/test/integration/sync_test.h"
#include "components/metrics/delegating_provider.h"
#include "components/metrics/demographic_metrics_provider.h"
#include "components/metrics/metrics_switches.h"
#include "components/metrics_services_manager/metrics_services_manager.h"
#include "components/sync/driver/sync_user_settings.h"
#include "testing/gmock/include/gmock/gmock-matchers.h"
#include "testing/gmock/include/gmock/gmock.h"
#include "third_party/metrics_proto/chrome_user_metrics_extension.pb.h"
#include "third_party/metrics_proto/user_demographics.pb.h"
#include "third_party/zlib/google/compression_utils.h"
namespace metrics {
namespace {
class MetricsServiceUserDemographicsBrowserTest
: public SyncTest,
public testing::WithParamInterface<test::DemographicsTestParams> {
public:
MetricsServiceUserDemographicsBrowserTest() : SyncTest(SINGLE_CLIENT) {
if (GetParam().enable_feature) {
// Enable UMA and reporting of the synced user's birth year and gender.
scoped_feature_list_.InitWithFeatures(
// enabled_features =
{internal::kMetricsReportingFeature,
DemographicMetricsProvider::kDemographicMetricsReporting},
// disabled_features =
{});
} else {
scoped_feature_list_.InitWithFeatures(
// enabled_features =
{internal::kMetricsReportingFeature},
// disabled_features =
{DemographicMetricsProvider::kDemographicMetricsReporting});
}
}
void SetUpCommandLine(base::CommandLine* command_line) override {
// Enable the metrics service for testing (in recording-only mode).
command_line->AppendSwitch(switches::kMetricsRecordingOnly);
}
void SetUp() override {
// Consent for metrics and crash reporting for testing.
ChromeMetricsServiceAccessor::SetMetricsAndCrashReportingForTesting(
&metrics_consent_);
SyncTest::SetUp();
}
// Forces a log record to be generated. Returns a copy of the record on
// success; otherwise, returns std::nullopt.
base::Optional<ChromeUserMetricsExtension> GenerateLogRecord() {
// Make sure that the metrics service is instantiated.
MetricsService* const metrics_service =
g_browser_process->GetMetricsServicesManager()->GetMetricsService();
if (metrics_service == nullptr) {
LOG(ERROR) << "Metrics service is not available";
return base::nullopt;
}
// Force the creation of a log record (i.e., trigger all metrics providers).
metrics_service->CloseCurrentLogForTest();
// Stage/serialize the log record for transmission.
MetricsLogStore* const log_store = metrics_service->LogStoreForTest();
log_store->StageNextLog();
if (!log_store->has_staged_log()) {
LOG(ERROR) << "No staged log.";
return base::nullopt;
}
// Decompress the staged log.
std::string uncompressed_log;
if (!compression::GzipUncompress(log_store->staged_log(),
&uncompressed_log)) {
LOG(ERROR) << "Decompression failed.";
return base::nullopt;
}
// Deserialize and return the log.
ChromeUserMetricsExtension uma_proto;
if (!uma_proto.ParseFromString(uncompressed_log)) {
LOG(ERROR) << "Deserialization failed.";
return base::nullopt;
}
return uma_proto;
}
private:
bool metrics_consent_ = true;
base::test::ScopedFeatureList scoped_feature_list_;
DISALLOW_COPY_AND_ASSIGN(MetricsServiceUserDemographicsBrowserTest);
};
// TODO(crbug/1016118): Add the remaining test cases.
IN_PROC_BROWSER_TEST_P(MetricsServiceUserDemographicsBrowserTest,
AddSyncedUserBirthYearAndGenderToProtoData) {
test::DemographicsTestParams param = GetParam();
base::HistogramTester histogram;
const int test_birth_year =
test::UpdateNetworkTimeAndGetMinimalEligibleBirthYear();
const UserDemographicsProto::Gender test_gender =
UserDemographicsProto::GENDER_FEMALE;
// Add the test synced user birth year and gender priority prefs to the sync
// server data.
test::AddUserBirthYearAndGenderToSyncServer(GetFakeServer()->AsWeakPtr(),
test_birth_year, test_gender);
Profile* test_profile = ProfileManager::GetActiveUserProfile();
// Enable sync for the test profile.
std::unique_ptr<ProfileSyncServiceHarness> test_profile_harness =
test::InitializeProfileForSync(test_profile,
GetFakeServer()->AsWeakPtr());
test_profile_harness->SetupSync();
// Make sure that there is only one Profile to allow reporting the user's
// birth year and gender.
ASSERT_EQ(1, num_clients());
// Generate a log record.
base::Optional<ChromeUserMetricsExtension> uma_proto = GenerateLogRecord();
ASSERT_TRUE(uma_proto.has_value());
// Check log content and the histogram.
if (param.expect_reported_demographics) {
EXPECT_EQ(test::GetNoisedBirthYear(test_birth_year, *test_profile),
uma_proto->user_demographics().birth_year());
EXPECT_EQ(test_gender, uma_proto->user_demographics().gender());
histogram.ExpectUniqueSample("UMA.UserDemographics.Status",
syncer::UserDemographicsStatus::kSuccess, 1);
} else {
EXPECT_FALSE(uma_proto->has_user_demographics());
histogram.ExpectTotalCount("UMA.UserDemographics.Status", /*count=*/0);
}
test_profile_harness->service()->GetUserSettings()->SetSyncRequested(false);
}
#if defined(OS_CHROMEOS)
// Cannot test for the enabled feature on Chrome OS because there are always
// multiple profiles.
static const auto kDemographicsTestParams = testing::Values(
test::DemographicsTestParams{/*enable_feature=*/false,
/*expect_reported_demographics=*/false});
#else
static const auto kDemographicsTestParams = testing::Values(
test::DemographicsTestParams{/*enable_feature=*/false,
/*expect_reported_demographics=*/false},
test::DemographicsTestParams{/*enable_feature=*/true,
/*expect_reported_demographics=*/true});
#endif
INSTANTIATE_TEST_SUITE_P(,
MetricsServiceUserDemographicsBrowserTest,
kDemographicsTestParams);
} // namespace
} // namespace metrics
// Copyright 2019 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/browser/metrics/testing/demographic_metrics_test_utils.h"
#include "base/i18n/time_formatting.h"
#include "base/strings/stringprintf.h"
#include "base/time/time.h"
#include "chrome/browser/browser_process.h"
#include "chrome/browser/profiles/profile.h"
#include "components/network_time/network_time_tracker.h"
#include "components/prefs/pref_service.h"
#include "components/sync/base/pref_names.h"
#include "components/sync/base/user_demographics.h"
#include "components/sync/engine_impl/loopback_server/persistent_unique_client_entity.h"
#include "components/sync/protocol/sync.pb.h"
namespace metrics {
namespace test {
void AddUserBirthYearAndGenderToSyncServer(
base::WeakPtr<fake_server::FakeServer> fake_server,
int birth_year,
metrics::UserDemographicsProto::Gender gender) {
DCHECK(fake_server);
sync_pb::EntitySpecifics specifics;
specifics.mutable_priority_preference()->mutable_preference()->set_name(
syncer::prefs::kSyncDemographics);
specifics.mutable_priority_preference()->mutable_preference()->set_value(
base::StringPrintf("{\"birth_year\":%d,\"gender\":%d}", birth_year,
static_cast<int>(gender)));
fake_server->InjectEntity(
syncer::PersistentUniqueClientEntity::CreateFromSpecificsForTesting(
/*non_unique_name=*/syncer::prefs::kSyncDemographics,
/*client_tag=*/specifics.preference().name(), specifics,
/*creation_time=*/0,
/*last_modified_time=*/0));
}
int UpdateNetworkTimeAndGetMinimalEligibleBirthYear() {
base::Time now = base::Time::Now();
// Simulate the latency in the network to get the network time from the remote
// server.
constexpr base::TimeDelta kLatency = base::TimeDelta::FromMilliseconds(10);
// Simulate the time taken to call UpdateNetworkTime() since the moment the
// callback was created. When not testing with the fake sync server, the
// callback is called when doing an HTTP request to the sync server.
constexpr base::TimeDelta kCallbackDelay =
base::TimeDelta::FromMilliseconds(10);
// Simulate a network time that is a bit earlier than the now time.
base::Time network_time = now - kCallbackDelay - kLatency;
// Simulate the time in ticks at the moment the UpdateNetworkTime callback
// function is created, which time should be at least 1 millisecond behind the
// moment the callback is run to pass the DCHECK.
base::TimeTicks post_time = base::TimeTicks::Now() - kCallbackDelay;
g_browser_process->network_time_tracker()->UpdateNetworkTime(
network_time,
/*resolution=*/base::TimeDelta::FromMilliseconds(1), kLatency, post_time);
constexpr int kEligibleAge =
syncer::kUserDemographicsMinAgeInYears +
syncer::kUserDemographicsBirthYearNoiseOffsetRange;
base::Time::Exploded exploded_time;
now.UTCExplode(&exploded_time);
// Return the maximal birth year that is eligible for reporting the user's
// birth year and gender. The -1 year is the extra buffer that Sync uses to
// make sure that the user is at least 20 yo because the user only gives the
// year of their birth date. For example, considering that the current date is
// the 05 Jan 2019 and that the user was born the 05 Mar 1999, the age of the
// user would be computed to 20 yo when using the year resolution, but the
// user is in fact 19.
return exploded_time.year - kEligibleAge - 1;
}
int GetNoisedBirthYear(int raw_birth_year, const Profile& profile) {
int birth_year_offset = profile.GetPrefs()->GetInteger(
syncer::prefs::kSyncDemographicsBirthYearOffset);
return birth_year_offset + raw_birth_year;
}
} // namespace test
} // namespace metrics
// Copyright 2019 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef CHROME_BROWSER_METRICS_TESTING_DEMOGRAPHIC_METRICS_TEST_UTILS_H_
#define CHROME_BROWSER_METRICS_TESTING_DEMOGRAPHIC_METRICS_TEST_UTILS_H_
#include "base/memory/weak_ptr.h"
#include "components/sync/test/fake_server/fake_server.h"
#include "third_party/metrics_proto/user_demographics.pb.h"
// Helpers to support testing the user's noised birth year and gender metrics in
// browser tests.
class Profile;
namespace metrics {
namespace test {
// Parameters for the parameterized tests.
struct DemographicsTestParams {
// Enable the feature to report the user's birth year and gender.
bool enable_feature = false;
// Expectation for the user's noised birth year and gender to be reported.
// Having |enable_feature| set to true does not necessarily mean that
// |expect_reported_demographics| will be true because other conditions might
// stop the reporting of the user's noised birth year and gender, e.g.,
// sync is turned off.
bool expect_reported_demographics = false;
};
// Adds the User Demographic priority pref to the sync |fake_server|, which
// contains the test synced user's |birth_year| and |gender|.
void AddUserBirthYearAndGenderToSyncServer(
base::WeakPtr<fake_server::FakeServer> fake_server,
int birth_year,
metrics::UserDemographicsProto::Gender gender);
// Updates the network time that is used to compute the test synced user's age
// and returns the minimal elibible birth year for the user to provide their
// birth year and gender.
int UpdateNetworkTimeAndGetMinimalEligibleBirthYear();
// Gets the noised birth year of the user, where the |raw_birth_year|
// corresponds to the user birth year to noise and |profile| corresponds to the
// profile of the user that has the noise pref. This function should be run
// after the Demographic Metrics Provider is run.
int GetNoisedBirthYear(int raw_birth_year, const Profile& profile);
} // namespace test
} // namespace metrics
#endif // CHROME_BROWSER_METRICS_TESTING_DEMOGRAPHIC_METRICS_TEST_UTILS_H_
// Copyright 2019 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/browser/metrics/testing/sync_metrics_test_utils.h"
#include "chrome/browser/signin/identity_manager_factory.h"
#include "chrome/browser/sync/profile_sync_service_factory.h"
#include "chrome/browser/sync/test/integration/profile_sync_service_harness.h"
#include "chrome/browser/sync/test/integration/sync_test.h"
#include "components/signin/public/identity_manager/account_info.h"
#include "components/signin/public/identity_manager/identity_manager.h"
#include "components/sync/test/fake_server/fake_server_network_resources.h"
namespace metrics {
namespace test {
std::unique_ptr<ProfileSyncServiceHarness> InitializeProfileForSync(
Profile* profile,
base::WeakPtr<fake_server::FakeServer> fake_server) {
ProfileSyncServiceFactory::GetAsProfileSyncServiceForProfile(profile)
->OverrideNetworkForTest(
fake_server::CreateFakeServerHttpPostProviderFactory(
fake_server->AsWeakPtr()));
std::string username;
#if defined(OS_CHROMEOS)
// In browser tests, the profile may already by authenticated with stub
// account |user_manager::kStubUserEmail|.
CoreAccountInfo info =
IdentityManagerFactory::GetForProfile(profile)->GetPrimaryAccountInfo();
username = info.email;
#endif
if (username.empty()) {
username = "user@gmail.com";
}
std::unique_ptr<ProfileSyncServiceHarness> harness =
ProfileSyncServiceHarness::Create(
profile, username, "unused" /* password */,
ProfileSyncServiceHarness::SigninType::FAKE_SIGNIN);
return harness;
}
} // namespace test
} // namespace metrics
// Copyright 2019 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef CHROME_BROWSER_METRICS_TESTING_SYNC_METRICS_TEST_UTILS_H_
#define CHROME_BROWSER_METRICS_TESTING_SYNC_METRICS_TEST_UTILS_H_
#include "base/memory/weak_ptr.h"
#include "base/time/time.h"
#include "components/sync/test/fake_server/fake_server.h"
#include "third_party/metrics_proto/user_demographics.pb.h"
// Helpers to support sync in metrics browser tests.
class Profile;
class ProfileSyncServiceHarness;
namespace fake_server {
class FakeServer;
}
namespace metrics {
namespace test {
// Initializes and enables the test Sync service of the |profile|.
std::unique_ptr<ProfileSyncServiceHarness> InitializeProfileForSync(
Profile* profile,
base::WeakPtr<fake_server::FakeServer> fake_server);
} // namespace test
} // namespace metrics
#endif // CHROME_BROWSER_METRICS_TESTING_SYNC_METRICS_TEST_UTILS_H_
...@@ -9,6 +9,8 @@ ...@@ -9,6 +9,8 @@
#include "base/stl_util.h" #include "base/stl_util.h"
#include "base/strings/string_util.h" #include "base/strings/string_util.h"
#include "base/system/sys_info.h" #include "base/system/sys_info.h"
#include "base/test/metrics/histogram_tester.h"
#include "base/test/scoped_feature_list.h"
#include "build/build_config.h" #include "build/build_config.h"
#include "build/buildflag.h" #include "build/buildflag.h"
#include "chrome/browser/browser_process.h" #include "chrome/browser/browser_process.h"
...@@ -16,7 +18,9 @@ ...@@ -16,7 +18,9 @@
#include "chrome/browser/metrics/chrome_metrics_service_accessor.h" #include "chrome/browser/metrics/chrome_metrics_service_accessor.h"
#include "chrome/browser/metrics/chrome_metrics_service_client.h" #include "chrome/browser/metrics/chrome_metrics_service_client.h"
#include "chrome/browser/metrics/chrome_metrics_services_manager_client.h" #include "chrome/browser/metrics/chrome_metrics_services_manager_client.h"
#include "chrome/browser/metrics/testing/demographic_metrics_test_utils.h"
#include "chrome/browser/metrics/testing/metrics_reporting_pref_helper.h" #include "chrome/browser/metrics/testing/metrics_reporting_pref_helper.h"
#include "chrome/browser/metrics/testing/sync_metrics_test_utils.h"
#include "chrome/browser/profiles/profile_manager.h" #include "chrome/browser/profiles/profile_manager.h"
#include "chrome/browser/signin/identity_manager_factory.h" #include "chrome/browser/signin/identity_manager_factory.h"
#include "chrome/browser/sync/profile_sync_service_factory.h" #include "chrome/browser/sync/profile_sync_service_factory.h"
...@@ -30,6 +34,7 @@ ...@@ -30,6 +34,7 @@
#include "chrome/browser/unified_consent/unified_consent_service_factory.h" #include "chrome/browser/unified_consent/unified_consent_service_factory.h"
#include "chrome/test/base/in_process_browser_test.h" #include "chrome/test/base/in_process_browser_test.h"
#include "chrome/test/base/ui_test_utils.h" #include "chrome/test/base/ui_test_utils.h"
#include "components/metrics/demographic_metrics_provider.h"
#include "components/metrics_services_manager/metrics_services_manager.h" #include "components/metrics_services_manager/metrics_services_manager.h"
#include "components/signin/public/base/signin_buildflags.h" #include "components/signin/public/base/signin_buildflags.h"
#include "components/signin/public/identity_manager/identity_manager.h" #include "components/signin/public/identity_manager/identity_manager.h"
...@@ -54,6 +59,7 @@ ...@@ -54,6 +59,7 @@
#include "services/metrics/public/cpp/ukm_source.h" #include "services/metrics/public/cpp/ukm_source.h"
#include "services/network/test/test_network_quality_tracker.h" #include "services/network/test/test_network_quality_tracker.h"
#include "third_party/metrics_proto/ukm/report.pb.h" #include "third_party/metrics_proto/ukm/report.pb.h"
#include "third_party/metrics_proto/user_demographics.pb.h"
#include "third_party/zlib/google/compression_utils.h" #include "third_party/zlib/google/compression_utils.h"
#include "url/url_constants.h" #include "url/url_constants.h"
...@@ -211,7 +217,7 @@ class UkmBrowserTestBase : public SyncTest { ...@@ -211,7 +217,7 @@ class UkmBrowserTestBase : public SyncTest {
ukm::Report GetUkmReport() { ukm::Report GetUkmReport() {
EXPECT_TRUE(HasUnsentUkmLogs()); EXPECT_TRUE(HasUnsentUkmLogs());
metrics::UnsentLogStore* log_store = UnsentLogStore* log_store =
ukm_service()->reporting_service_.ukm_log_store(); ukm_service()->reporting_service_.ukm_log_store();
if (log_store->has_staged_log()) { if (log_store->has_staged_log()) {
// For testing purposes, we are examining the content of a staged log // For testing purposes, we are examining the content of a staged log
...@@ -231,36 +237,10 @@ class UkmBrowserTestBase : public SyncTest { ...@@ -231,36 +237,10 @@ class UkmBrowserTestBase : public SyncTest {
} }
protected: protected:
std::unique_ptr<ProfileSyncServiceHarness> InitializeProfileForSync(
Profile* profile) {
ProfileSyncServiceFactory::GetAsProfileSyncServiceForProfile(profile)
->OverrideNetworkForTest(
fake_server::CreateFakeServerHttpPostProviderFactory(
GetFakeServer()->AsWeakPtr()));
std::string username;
#if defined(OS_CHROMEOS)
// In browser tests, the profile may already by authenticated with stub
// account |user_manager::kStubUserEmail|.
CoreAccountInfo info =
IdentityManagerFactory::GetForProfile(profile)->GetPrimaryAccountInfo();
username = info.email;
#endif
if (username.empty()) {
username = "user@gmail.com";
}
std::unique_ptr<ProfileSyncServiceHarness> harness =
ProfileSyncServiceHarness::Create(
profile, username, "unused" /* password */,
ProfileSyncServiceHarness::SigninType::FAKE_SIGNIN);
return harness;
}
std::unique_ptr<ProfileSyncServiceHarness> EnableSyncForProfile( std::unique_ptr<ProfileSyncServiceHarness> EnableSyncForProfile(
Profile* profile) { Profile* profile) {
std::unique_ptr<ProfileSyncServiceHarness> harness = std::unique_ptr<ProfileSyncServiceHarness> harness =
InitializeProfileForSync(profile); test::InitializeProfileForSync(profile, GetFakeServer()->AsWeakPtr());
EXPECT_TRUE(harness->SetupSync()); EXPECT_TRUE(harness->SetupSync());
// If unified consent is enabled, then enable url-keyed-anonymized data // If unified consent is enabled, then enable url-keyed-anonymized data
...@@ -389,6 +369,36 @@ class UkmEnabledChecker : public SingleClientStatusChangeChecker { ...@@ -389,6 +369,36 @@ class UkmEnabledChecker : public SingleClientStatusChangeChecker {
DISALLOW_COPY_AND_ASSIGN(UkmEnabledChecker); DISALLOW_COPY_AND_ASSIGN(UkmEnabledChecker);
}; };
// Test the reporting of the synced user's birth year and gender.
class UkmBrowserTestWithDemographics
: public UkmBrowserTestBase,
public testing::WithParamInterface<test::DemographicsTestParams> {
public:
UkmBrowserTestWithDemographics() : UkmBrowserTestBase() {
test::DemographicsTestParams param = GetParam();
if (param.enable_feature) {
scoped_feature_list_.InitWithFeatures(
// enabled_features
{DemographicMetricsProvider::kDemographicMetricsReporting,
ukm::UkmService::kReportUserNoisedUserBirthYearAndGender},
// disabled_features
{});
} else {
scoped_feature_list_.InitWithFeatures(
// enabled_features
{},
// disabled_features
{DemographicMetricsProvider::kDemographicMetricsReporting,
ukm::UkmService::kReportUserNoisedUserBirthYearAndGender});
}
}
private:
base::test::ScopedFeatureList scoped_feature_list_;
DISALLOW_COPY_AND_ASSIGN(UkmBrowserTestWithDemographics);
};
// Make sure that UKM is disabled while an incognito window is open. // Make sure that UKM is disabled while an incognito window is open.
// Keep in sync with UkmTest.testRegularPlusIncognitoCheck in // Keep in sync with UkmTest.testRegularPlusIncognitoCheck in
// chrome/android/javatests/src/org/chromium/chrome/browser/metrics/ // chrome/android/javatests/src/org/chromium/chrome/browser/metrics/
...@@ -579,6 +589,76 @@ IN_PROC_BROWSER_TEST_F(UkmBrowserTest, LogProtoData) { ...@@ -579,6 +589,76 @@ IN_PROC_BROWSER_TEST_F(UkmBrowserTest, LogProtoData) {
CloseBrowserSynchronously(sync_browser); CloseBrowserSynchronously(sync_browser);
} }
// TODO(crbug/1016118): Add the remaining test cases.
IN_PROC_BROWSER_TEST_P(UkmBrowserTestWithDemographics,
AddSyncedUserBirthYearAndGenderToProtoData) {
test::DemographicsTestParams param = GetParam();
MetricsConsentOverride metrics_consent(true);
base::HistogramTester histogram;
const int test_birth_year =
test::UpdateNetworkTimeAndGetMinimalEligibleBirthYear();
const UserDemographicsProto::Gender test_gender =
UserDemographicsProto::GENDER_FEMALE;
// Add the test synced user birth year and gender priority prefs to the sync
// server data.
test::AddUserBirthYearAndGenderToSyncServer(GetFakeServer()->AsWeakPtr(),
test_birth_year, test_gender);
Profile* test_profile = ProfileManager::GetActiveUserProfile();
std::unique_ptr<ProfileSyncServiceHarness> harness =
EnableSyncForProfile(test_profile);
// Make sure that there is only one Profile to allow reporting the user's
// birth year and gender.
ASSERT_EQ(1, num_clients());
Browser* sync_browser = CreateBrowser(test_profile);
EXPECT_TRUE(ukm_enabled());
uint64_t original_client_id = client_id();
EXPECT_NE(0U, original_client_id);
// Log UKM metrics report.
BuildAndStoreUkmLog();
EXPECT_TRUE(HasUnsentUkmLogs());
// Check the log's content and the histogram.
ukm::Report report = GetUkmReport();
if (param.expect_reported_demographics) {
EXPECT_EQ(test::GetNoisedBirthYear(test_birth_year, *test_profile),
report.user_demographics().birth_year());
EXPECT_EQ(test_gender, report.user_demographics().gender());
histogram.ExpectUniqueSample("UKM.UserDemographics.Status",
syncer::UserDemographicsStatus::kSuccess, 1);
} else {
EXPECT_FALSE(report.has_user_demographics());
histogram.ExpectTotalCount("UKM.UserDemographics.Status", /*count=*/0);
}
harness->service()->GetUserSettings()->SetSyncRequested(false);
CloseBrowserSynchronously(sync_browser);
}
#if defined(OS_CHROMEOS)
// Cannot test for the enabled feature on Chrome OS because there are always
// multiple profiles.
static const auto kDemographicsTestParams = testing::Values(
test::DemographicsTestParams{/*enable_feature=*/false,
/*expect_reported_demographics=*/false});
#else
static const auto kDemographicsTestParams = testing::Values(
test::DemographicsTestParams{/*enable_feature=*/false,
/*expect_reported_demographics=*/false},
test::DemographicsTestParams{/*enable_feature=*/true,
/*expect_reported_demographics=*/true});
#endif
INSTANTIATE_TEST_SUITE_P(,
UkmBrowserTestWithDemographics,
kDemographicsTestParams);
// Verifies that network provider attaches effective connection type correctly // Verifies that network provider attaches effective connection type correctly
// to the UKM report. // to the UKM report.
IN_PROC_BROWSER_TEST_F(UkmBrowserTest, NetworkProviderPopulatesSystemProfile) { IN_PROC_BROWSER_TEST_F(UkmBrowserTest, NetworkProviderPopulatesSystemProfile) {
...@@ -903,8 +983,8 @@ IN_PROC_BROWSER_TEST_F(UkmBrowserTest, MetricsReportingCheck) { ...@@ -903,8 +983,8 @@ IN_PROC_BROWSER_TEST_F(UkmBrowserTest, MetricsReportingCheck) {
// Need to set the Metrics Default to OPT_OUT to trigger MetricsReporting. // Need to set the Metrics Default to OPT_OUT to trigger MetricsReporting.
DCHECK(g_browser_process); DCHECK(g_browser_process);
PrefService* local_state = g_browser_process->local_state(); PrefService* local_state = g_browser_process->local_state();
metrics::ForceRecordMetricsReportingDefaultState( ForceRecordMetricsReportingDefaultState(local_state,
local_state, metrics::EnableMetricsDefault::OPT_OUT); EnableMetricsDefault::OPT_OUT);
// Verify that kMetricsReportingFeature is disabled (i.e. other metrics // Verify that kMetricsReportingFeature is disabled (i.e. other metrics
// services will be sampled out). // services will be sampled out).
EXPECT_FALSE( EXPECT_FALSE(
...@@ -967,7 +1047,7 @@ IN_PROC_BROWSER_TEST_F(UkmBrowserTestWithSyncTransport, ...@@ -967,7 +1047,7 @@ IN_PROC_BROWSER_TEST_F(UkmBrowserTestWithSyncTransport,
// transport mode. // transport mode.
Profile* profile = ProfileManager::GetActiveUserProfile(); Profile* profile = ProfileManager::GetActiveUserProfile();
std::unique_ptr<ProfileSyncServiceHarness> harness = std::unique_ptr<ProfileSyncServiceHarness> harness =
InitializeProfileForSync(profile); test::InitializeProfileForSync(profile, GetFakeServer()->AsWeakPtr());
syncer::SyncService* sync_service = syncer::SyncService* sync_service =
ProfileSyncServiceFactory::GetForProfile(profile); ProfileSyncServiceFactory::GetForProfile(profile);
......
...@@ -684,6 +684,7 @@ if (!is_android) { ...@@ -684,6 +684,7 @@ if (!is_android) {
"//chrome:strings", "//chrome:strings",
"//chrome/browser", "//chrome/browser",
"//chrome/browser/devtools:test_support", "//chrome/browser/devtools:test_support",
"//chrome/browser/metrics:test_support",
"//chrome/browser/notifications/scheduler/test:test_support", "//chrome/browser/notifications/scheduler/test:test_support",
"//chrome/browser/profiling_host:profiling_browsertests", "//chrome/browser/profiling_host:profiling_browsertests",
"//chrome/browser/web_applications:browser_tests", "//chrome/browser/web_applications:browser_tests",
...@@ -999,6 +1000,7 @@ if (!is_android) { ...@@ -999,6 +1000,7 @@ if (!is_android) {
"../browser/metrics/desktop_session_duration/audible_contents_tracker_browsertest.cc", "../browser/metrics/desktop_session_duration/audible_contents_tracker_browsertest.cc",
"../browser/metrics/metrics_reporting_state_browsertest.cc", "../browser/metrics/metrics_reporting_state_browsertest.cc",
"../browser/metrics/metrics_service_browsertest.cc", "../browser/metrics/metrics_service_browsertest.cc",
"../browser/metrics/metrics_service_user_demographics_browsertest.cc",
"../browser/metrics/oom/out_of_memory_reporter_browsertest.cc", "../browser/metrics/oom/out_of_memory_reporter_browsertest.cc",
"../browser/metrics/process_memory_metrics_emitter_browsertest.cc", "../browser/metrics/process_memory_metrics_emitter_browsertest.cc",
"../browser/metrics/startup_metrics_browsertest.cc", "../browser/metrics/startup_metrics_browsertest.cc",
......
...@@ -166,9 +166,12 @@ class MetricsLog { ...@@ -166,9 +166,12 @@ class MetricsLog {
LogType log_type() const { return log_type_; } LogType log_type() const { return log_type_; }
protected:
// Exposed for the sake of mocking/accessing in test code. // Exposed for the sake of mocking/accessing in test code.
ChromeUserMetricsExtension* UmaProtoForTest() { return &uma_proto_; }
protected:
// Exposed for the sake of mocking/accessing in test code.
// TODO(1034679): migrate to public UmaProtoForTest() method.
ChromeUserMetricsExtension* uma_proto() { return &uma_proto_; } ChromeUserMetricsExtension* uma_proto() { return &uma_proto_; }
// Exposed to allow subclass to access to export the uma_proto. Can be used // Exposed to allow subclass to access to export the uma_proto. Can be used
......
...@@ -175,8 +175,16 @@ class MetricsService : public base::HistogramFlattener { ...@@ -175,8 +175,16 @@ class MetricsService : public base::HistogramFlattener {
return &synthetic_trial_registry_; return &synthetic_trial_registry_;
} }
// Test hook to close out the current log after adding any last information.
void CloseCurrentLogForTest() { CloseCurrentLog(); }
MetricsLogStore* LogStoreForTest() {
return reporting_service_.metrics_log_store();
}
protected: protected:
// Exposed for testing. // Exposed for testing.
// TODO(1034679): migrate these to public FooForTest() methods.
MetricsLogManager* log_manager() { return &log_manager_; } MetricsLogManager* log_manager() { return &log_manager_; }
MetricsLogStore* log_store() { MetricsLogStore* log_store() {
return reporting_service_.metrics_log_store(); return reporting_service_.metrics_log_store();
......
Markdown is supported
0%
or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment