1 // Copyright 2020 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 "components/ukm/ukm_test_helper.h"
10 #include "base/containers/contains.h"
11 #include "base/feature_list.h"
12 #include "base/run_loop.h"
13 #include "components/metrics/log_decoder.h"
14 #include "components/metrics/metrics_logs_event_manager.h"
15 #include "components/metrics/unsent_log_store.h"
16 #include "ukm_test_helper.h"
20 UkmTestHelper::UkmTestHelper(UkmService* ukm_service)
21 : ukm_service_(ukm_service) {}
23 bool UkmTestHelper::IsExtensionRecordingEnabled() const {
24 return ukm_service_ ? ukm_service_->recording_enabled(EXTENSIONS) : false;
27 bool UkmTestHelper::IsRecordingEnabled() const {
28 return ukm_service_ ? ukm_service_->recording_enabled() : false;
31 bool UkmTestHelper::IsReportUserNoisedUserBirthYearAndGenderEnabled() {
32 return base::FeatureList::IsEnabled(
33 ukm::kReportUserNoisedUserBirthYearAndGender);
36 uint64_t UkmTestHelper::GetClientId() {
37 return ukm_service_->client_id_;
40 std::unique_ptr<Report> UkmTestHelper::GetUkmReport() {
44 metrics::UnsentLogStore* log_store =
45 ukm_service_->reporting_service_.ukm_log_store();
46 if (log_store->has_staged_log()) {
47 // For testing purposes, we examine the content of a staged log without
48 // ever sending the log, so discard any previously staged log.
49 log_store->DiscardStagedLog();
52 log_store->StageNextLog();
53 if (!log_store->has_staged_log())
56 std::unique_ptr<ukm::Report> report = std::make_unique<ukm::Report>();
57 if (!metrics::DecodeLogDataToProto(log_store->staged_log(), report.get()))
63 UkmSource* UkmTestHelper::GetSource(SourceId source_id) {
67 auto it = ukm_service_->sources().find(source_id);
68 return it == ukm_service_->sources().end() ? nullptr : it->second.get();
71 bool UkmTestHelper::HasSource(SourceId source_id) {
72 return ukm_service_ && base::Contains(ukm_service_->sources(), source_id);
75 bool UkmTestHelper::IsSourceObsolete(SourceId source_id) {
76 return ukm_service_ &&
77 base::Contains(ukm_service_->recordings_.obsolete_source_ids,
81 void UkmTestHelper::RecordSourceForTesting(SourceId source_id) {
83 ukm_service_->UpdateSourceURL(source_id, GURL("http://example.com"));
86 void UkmTestHelper::BuildAndStoreLog() {
87 // Wait for initialization to complete before flushing.
88 base::RunLoop run_loop;
89 ukm_service_->SetInitializationCompleteCallbackForTesting(
90 run_loop.QuitClosure());
93 ukm_service_->Flush(metrics::MetricsLogsEventManager::CreateReason::kUnknown);
96 bool UkmTestHelper::HasUnsentLogs() {
97 return ukm_service_ &&
98 ukm_service_->reporting_service_.ukm_log_store()->has_unsent_logs();
101 void UkmTestHelper::SetMsbbConsent() {
102 DCHECK(ukm_service_);
103 ukm_service_->UpdateRecording(ukm::MSBB);