• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
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 // Use TestTraceProcessor to load a perfetto trace and run queries on the trace.
6 // Documentation on how to use the trace processor and write queries can be
7 // found here: https://perfetto.dev/docs/analysis/trace-processor.
8 // TODO(b/224531105): Implement EXTRACT_ARGS to return multiple args to simplify
9 // queries.
10 
11 #ifndef BASE_TEST_TEST_TRACE_PROCESSOR_H_
12 #define BASE_TEST_TEST_TRACE_PROCESSOR_H_
13 
14 #include <string_view>
15 
16 #include "base/test/test_trace_processor_impl.h"
17 #include "base/test/trace_test_utils.h"
18 #include "base/types/expected.h"
19 #include "build/build_config.h"
20 
21 #if !BUILDFLAG(IS_WIN)
22 #define TEST_TRACE_PROCESSOR_ENABLED
23 #endif
24 
25 namespace base::test {
26 
27 
28 using perfetto::protos::gen::TraceConfig;
29 
30 TraceConfig DefaultTraceConfig(std::string_view category_filter_string,
31                                bool privacy_filtering);
32 
33 // Use TestTraceProcessor to record Perfetto traces in unit and browser tests.
34 // This API can be used to start and stop traces, run SQL queries on the trace
35 // and write expectations against the query result.
36 //
37 // Example:
38 //
39 //   TestTraceProcessor test_trace_processor;
40 //   test_trace_processor.StartTrace();
41 //
42 //   /* do stuff */
43 //
44 //   absl::Status status = test_trace_processor.StopAndParseTrace();
45 //   ASSERT_TRUE(status.ok()) << status.message();
46 //
47 //   std::string query = "YOUR QUERY";
48 //   auto result = test_trace_processor.RunQuery(query);
49 //
50 //   ASSERT_TRUE(result.has_value()) << result.message();
51 //   EXPECT_THAT(result.value(), /* your expectations */);
52 
53 class TestTraceProcessor {
54  public:
55   using QueryResult = std::vector<std::vector<std::string>>;
56 
57   TestTraceProcessor();
58   ~TestTraceProcessor();
59 
60   // Privacy filtering removes high entropy and high information fields and
61   // only allows categories, event names, and arguments listed in
62   // `services/tracing/perfetto/privacy_filtered_fields-inl.h`
63   void StartTrace(std::string_view category_filter_string,
64                   bool privacy_filtering = false);
65   void StartTrace(
66       const TraceConfig& config,
67       perfetto::BackendType backend = perfetto::kUnspecifiedBackend);
68 
69   absl::Status StopAndParseTrace();
70 
71   base::expected<QueryResult, std::string> RunQuery(const std::string& query);
72 
73  private:
74   TestTraceProcessorImpl test_trace_processor_;
75   std::unique_ptr<perfetto::TracingSession> session_;
76 };
77 
78 
79 }  // namespace base::test
80 
81 #endif  // BASE_TEST_TEST_TRACE_PROCESSOR_H_
82