clang-tools  14.0.0git
TraceTests.cpp
Go to the documentation of this file.
1 //===-- TraceTests.cpp - Tracing unit tests ---------------------*- C++ -*-===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 
9 #include "TestTracer.h"
10 #include "support/Context.h"
11 #include "support/Trace.h"
12 #include "llvm/ADT/DenseMap.h"
13 #include "llvm/ADT/SmallString.h"
14 #include "llvm/ADT/StringExtras.h"
15 #include "llvm/ADT/StringRef.h"
16 #include "llvm/Support/SourceMgr.h"
17 #include "llvm/Support/Threading.h"
18 #include "llvm/Support/YAMLParser.h"
19 #include "gmock/gmock.h"
20 #include "gtest/gtest.h"
21 
22 namespace clang {
23 namespace clangd {
24 namespace {
25 
26 using testing::_;
27 using testing::ElementsAre;
28 using testing::SizeIs;
29 using testing::StartsWith;
30 
31 MATCHER_P(StringNode, Val, "") {
32  if (arg->getType() != llvm::yaml::Node::NK_Scalar) {
33  *result_listener << "is a " << arg->getVerbatimTag();
34  return false;
35  }
36  llvm::SmallString<32> S;
37  return Val == static_cast<llvm::yaml::ScalarNode *>(arg)->getValue(S);
38 }
39 
40 // Checks that N is a Mapping (JS object) with the expected scalar properties.
41 // The object must have all the Expected properties, but may have others.
42 bool VerifyObject(llvm::yaml::Node &N,
43  std::map<std::string, std::string> Expected) {
44  auto *M = llvm::dyn_cast<llvm::yaml::MappingNode>(&N);
45  if (!M) {
46  ADD_FAILURE() << "Not an object";
47  return false;
48  }
49  bool Match = true;
50  llvm::SmallString<32> Tmp;
51  for (auto &Prop : *M) {
52  auto *K = llvm::dyn_cast_or_null<llvm::yaml::ScalarNode>(Prop.getKey());
53  if (!K)
54  continue;
55  std::string KS = K->getValue(Tmp).str();
56  auto I = Expected.find(KS);
57  if (I == Expected.end())
58  continue; // Ignore properties with no assertion.
59 
60  auto *V = llvm::dyn_cast_or_null<llvm::yaml::ScalarNode>(Prop.getValue());
61  if (!V) {
62  ADD_FAILURE() << KS << " is not a string";
63  Match = false;
64  continue;
65  }
66  std::string VS = V->getValue(Tmp).str();
67  if (VS != I->second) {
68  ADD_FAILURE() << KS << " expected " << I->second << " but actual " << VS;
69  Match = false;
70  }
71  Expected.erase(I);
72  }
73  for (const auto &P : Expected) {
74  ADD_FAILURE() << P.first << " missing, expected " << P.second;
75  Match = false;
76  }
77  return Match;
78 }
79 
80 TEST(TraceTest, SmokeTest) {
81  // Capture some events.
82  std::string JSON;
83  {
84  llvm::raw_string_ostream OS(JSON);
85  auto JSONTracer = trace::createJSONTracer(OS);
86  trace::Session Session(*JSONTracer);
87  {
88  trace::Span Tracer("A");
89  trace::log("B");
90  }
91  }
92 
93  // Get the root JSON object using the YAML parser.
94  llvm::SourceMgr SM;
95  llvm::yaml::Stream Stream(JSON, SM);
96  auto Doc = Stream.begin();
97  ASSERT_NE(Doc, Stream.end());
98  auto *Root = llvm::dyn_cast_or_null<llvm::yaml::MappingNode>(Doc->getRoot());
99  ASSERT_NE(Root, nullptr) << "Root should be an object";
100 
101  // Check whether we expect thread name events on this platform.
102  llvm::SmallString<32> ThreadName;
103  get_thread_name(ThreadName);
104  bool ThreadsHaveNames = !ThreadName.empty();
105 
106  // We expect in order:
107  // displayTimeUnit: "ns"
108  // traceEvents: [process name, thread name, start span, log, end span]
109  // (The order doesn't matter, but the YAML parser is awkward to use otherwise)
110  auto Prop = Root->begin();
111  ASSERT_NE(Prop, Root->end()) << "Expected displayTimeUnit property";
112  ASSERT_THAT(Prop->getKey(), StringNode("displayTimeUnit"));
113  EXPECT_THAT(Prop->getValue(), StringNode("ns"));
114  ASSERT_NE(++Prop, Root->end()) << "Expected traceEvents property";
115  EXPECT_THAT(Prop->getKey(), StringNode("traceEvents"));
116  auto *Events =
117  llvm::dyn_cast_or_null<llvm::yaml::SequenceNode>(Prop->getValue());
118  ASSERT_NE(Events, nullptr) << "traceEvents should be an array";
119  auto Event = Events->begin();
120  ASSERT_NE(Event, Events->end()) << "Expected process name";
121  EXPECT_TRUE(VerifyObject(*Event, {{"ph", "M"}, {"name", "process_name"}}));
122  if (ThreadsHaveNames) {
123  ASSERT_NE(++Event, Events->end()) << "Expected thread name";
124  EXPECT_TRUE(VerifyObject(*Event, {{"ph", "M"}, {"name", "thread_name"}}));
125  }
126  ASSERT_NE(++Event, Events->end()) << "Expected log message";
127  EXPECT_TRUE(VerifyObject(*Event, {{"ph", "i"}, {"name", "Log"}}));
128  ASSERT_NE(++Event, Events->end()) << "Expected span end";
129  EXPECT_TRUE(VerifyObject(*Event, {{"ph", "X"}, {"name", "A"}}));
130  ASSERT_EQ(++Event, Events->end());
131  ASSERT_EQ(++Prop, Root->end());
132 }
133 
134 TEST(MetricsTracer, LatencyTest) {
135  trace::TestTracer Tracer;
136  constexpr llvm::StringLiteral MetricName = "span_latency";
137  constexpr llvm::StringLiteral OpName = "op_name";
138  {
139  // A span should record latencies to span_latency by default.
140  trace::Span SpanWithLat(OpName);
141  EXPECT_THAT(Tracer.takeMetric(MetricName, OpName), SizeIs(0));
142  }
143  EXPECT_THAT(Tracer.takeMetric(MetricName, OpName), SizeIs(1));
144 }
145 
146 class CSVMetricsTracerTest : public ::testing::Test {
147 protected:
148  CSVMetricsTracerTest()
150  }
151  trace::Metric Dist = {"dist", trace::Metric::Distribution, "lbl"};
152  trace::Metric Counter = {"cnt", trace::Metric::Counter};
153 
154  std::vector<std::string> outputLines() {
155  // Deliberately don't flush output stream, the tracer should do that.
156  // This is important when clangd crashes.
157  llvm::SmallVector<llvm::StringRef> Lines;
158  llvm::StringRef(Output).split(Lines, "\r\n");
159  return {Lines.begin(), Lines.end()};
160  }
161 
162  std::string Output;
163  llvm::raw_string_ostream OS;
164  std::unique_ptr<trace::EventTracer> Tracer;
166 };
167 
168 TEST_F(CSVMetricsTracerTest, RecordsValues) {
169  Dist.record(1, "x");
170  Counter.record(1, "");
171  Dist.record(2, "y");
172 
173  ASSERT_THAT(outputLines(),
174  ElementsAre("Kind,Metric,Label,Value,Timestamp",
175  StartsWith("d,dist,x,1.000000e+00,"),
176  StartsWith("c,cnt,,1.000000e+00,"),
177  StartsWith("d,dist,y,2.000000e+00,"), ""));
178 }
179 
180 TEST_F(CSVMetricsTracerTest, Escaping) {
181  Dist.record(1, ",");
182  Dist.record(1, "a\"b");
183  Dist.record(1, "a\nb");
184 
185  EXPECT_THAT(outputLines(), ElementsAre(_, StartsWith(R"(d,dist,",",1)"),
186  StartsWith(R"(d,dist,"a""b",1)"),
187  StartsWith("d,dist,\"a\nb\",1"), ""));
188 }
189 
190 TEST_F(CSVMetricsTracerTest, IgnoresArgs) {
191  trace::Span Tracer("Foo");
192  EXPECT_EQ(nullptr, Tracer.Args);
193 }
194 
195 } // namespace
196 } // namespace clangd
197 } // namespace clang
clang::clangd::TEST
TEST(BackgroundQueueTest, Priority)
Definition: BackgroundIndexTests.cpp:751
Session
trace::Session Session
Definition: TraceTests.cpp:165
Expected
std::vector< const char * > Expected
Definition: PrintASTTests.cpp:27
Tracer
std::unique_ptr< trace::EventTracer > Tracer
Definition: TraceTests.cpp:164
Root
ASTNode Root
Definition: DumpAST.cpp:332
clang::clangd::trace::Metric::record
void record(double Value, llvm::StringRef Label="") const
Records a measurement for this metric to active tracer.
Definition: Trace.cpp:330
Trace.h
clang::clangd::TEST_F
TEST_F(BackgroundIndexTest, NoCrashOnErrorFile)
Definition: BackgroundIndexTests.cpp:94
SourceMgr
llvm::SourceMgr * SourceMgr
Definition: ConfigCompile.cpp:102
clang::clangd::trace::log
void log(const llvm::Twine &Message)
Records a single instant event, associated with the current thread.
Definition: Trace.cpp:278
clang::clangd::trace::createJSONTracer
std::unique_ptr< EventTracer > createJSONTracer(llvm::raw_ostream &OS, bool Pretty)
Create an instance of EventTracer that produces an output in the Trace Event format supported by Chro...
Definition: Trace.cpp:269
clang::tidy::abseil::getValue
static double getValue(const IntegerLiteral *IntLit, const FloatingLiteral *FloatLit)
Definition: DurationFactoryScaleCheck.cpp:38
M
const google::protobuf::Message & M
Definition: Server.cpp:309
clang::clangd::trace::createCSVMetricTracer
std::unique_ptr< EventTracer > createCSVMetricTracer(llvm::raw_ostream &OS)
Create an instance of EventTracer that outputs metric measurements as CSV.
Definition: Trace.cpp:274
clang::clangd::trace::Metric::Distribution
@ Distribution
A distribution of values with a meaningful mean and count.
Definition: Trace.h:52
Output
std::string Output
Definition: TraceTests.cpp:162
TestTracer.h
Counter
trace::Metric Counter
Definition: TraceTests.cpp:152
clang::clangd::trace::Metric::Counter
@ Counter
An aggregate number whose rate of change over time is meaningful.
Definition: Trace.h:46
clang::clangd::MATCHER_P
MATCHER_P(Named, N, "")
Definition: BackgroundIndexTests.cpp:31
clang
===– Representation.cpp - ClangDoc Representation --------—*- C++ -*-===//
Definition: ApplyReplacements.h:27
OS
llvm::raw_string_ostream OS
Definition: TraceTests.cpp:163
Dist
trace::Metric Dist
Definition: TraceTests.cpp:151
clang::clangd::CompletionItemKind::Event
@ Event
Lines
unsigned Lines
Definition: FunctionSizeCheck.cpp:113
K
Kind K
Definition: Rename.cpp:442
Context.h