1 // Copyright 2023 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. 4 5 #ifndef COMPONENTS_METRICS_STRUCTURED_TEST_TEST_STRUCTURED_METRICS_PROVIDER_H_ 6 #define COMPONENTS_METRICS_STRUCTURED_TEST_TEST_STRUCTURED_METRICS_PROVIDER_H_ 7 8 #include "base/files/scoped_temp_dir.h" 9 #include "components/metrics/metrics_provider.h" 10 #include "components/metrics/structured/event.h" 11 #include "components/metrics/structured/recorder.h" 12 #include "components/metrics/structured/structured_metrics_recorder.h" 13 14 namespace metrics::structured { 15 16 class EventsProto; 17 18 // TestStructuredMetricsProvider is a wrapper of StructuredMetricsProvider to 19 // be used for testing. 20 class TestStructuredMetricsProvider : public Recorder::RecorderImpl { 21 public: 22 TestStructuredMetricsProvider(); 23 explicit TestStructuredMetricsProvider( 24 std::unique_ptr<StructuredMetricsRecorder> recorder); 25 ~TestStructuredMetricsProvider() override; 26 TestStructuredMetricsProvider(const TestStructuredMetricsProvider&) = delete; 27 TestStructuredMetricsProvider& operator=( 28 const TestStructuredMetricsProvider&) = delete; 29 30 const EventsProto& ReadEvents() const; 31 32 // Returns pointer to the first event with the hash |project_name_hash| and 33 // |event_name_hash|. If no event is found, returns std::nullopt. 34 std::optional<const StructuredEventProto*> FindEvent( 35 uint64_t project_name_hash, 36 uint64_t event_name_hash); 37 38 // Returns a vector of pointers to the events with the hash 39 // |project_name_hash| and |event_name_hash|. 40 std::vector<const StructuredEventProto*> FindEvents( 41 uint64_t project_name_hash, 42 uint64_t event_name_hash); 43 44 void EnableRecording(); 45 void DisableRecording(); 46 47 // Waits until the recorder is fully initialized. 48 void WaitUntilReady(); 49 50 // Sets a callback that will be called after the event is flushed to 51 // persistence. 52 void SetOnEventsRecordClosure( 53 base::RepeatingCallback<void(const Event& event)> event_record_callback); 54 55 private: 56 // Recorder::RecorderImpl: 57 void OnEventRecord(const Event& event) override; 58 59 std::unique_ptr<StructuredMetricsRecorder> structured_metrics_recorder_; 60 61 base::ScopedTempDir temp_dir_; 62 63 base::RepeatingCallback<void(const Event& event)> event_record_callback_; 64 }; 65 66 } // namespace metrics::structured 67 68 #endif // COMPONENTS_METRICS_STRUCTURED_TEST_TEST_STRUCTURED_METRICS_PROVIDER_H_ 69