1 // Copyright (c) 2012 The Chromium Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
9 #include "base/command_line.h"
10 #include "base/json/json_reader.h"
11 #include "base/json/json_writer.h"
12 #include "base/location.h"
13 #include "base/memory/ref_counted_memory.h"
14 #include "base/memory/scoped_ptr.h"
15 #include "base/memory/singleton.h"
16 #include "base/process/process_handle.h"
17 #include "base/single_thread_task_runner.h"
18 #include "base/strings/stringprintf.h"
19 #include "base/synchronization/waitable_event.h"
20 #include "base/threading/platform_thread.h"
21 #include "base/threading/thread.h"
22 #include "base/time/time.h"
23 #include "base/trace_event/trace_event.h"
24 #include "base/trace_event/trace_event_synthetic_delay.h"
25 #include "base/values.h"
26 #include "testing/gmock/include/gmock/gmock.h"
27 #include "testing/gtest/include/gtest/gtest.h"
30 namespace trace_event
{
45 const int kThreadId
= 42;
46 const int kAsyncId
= 5;
47 const char kAsyncIdStr
[] = "0x5";
48 const int kAsyncId2
= 6;
49 const char kAsyncId2Str
[] = "0x6";
51 class TraceEventTestFixture
: public testing::Test
{
53 void OnTraceDataCollected(
54 WaitableEvent
* flush_complete_event
,
55 const scoped_refptr
<base::RefCountedString
>& events_str
,
56 bool has_more_events
);
57 void OnWatchEventMatched() {
58 ++event_watch_notification_
;
60 DictionaryValue
* FindMatchingTraceEntry(const JsonKeyValue
* key_values
);
61 DictionaryValue
* FindNamePhase(const char* name
, const char* phase
);
62 DictionaryValue
* FindNamePhaseKeyValue(const char* name
,
66 void DropTracedMetadataRecords();
67 bool FindMatchingValue(const char* key
,
69 bool FindNonMatchingValue(const char* key
,
72 trace_parsed_
.Clear();
73 json_output_
.json_output
.clear();
77 BeginSpecificTrace("*");
80 void BeginSpecificTrace(const std::string
& filter
) {
81 event_watch_notification_
= 0;
82 TraceLog::GetInstance()->SetEnabled(
83 CategoryFilter(filter
),
84 TraceLog::RECORDING_MODE
,
88 void EndTraceAndFlush() {
89 WaitableEvent
flush_complete_event(false, false);
90 EndTraceAndFlushAsync(&flush_complete_event
);
91 flush_complete_event
.Wait();
94 // Used when testing thread-local buffers which requires the thread initiating
95 // flush to have a message loop.
96 void EndTraceAndFlushInThreadWithMessageLoop() {
97 WaitableEvent
flush_complete_event(false, false);
98 Thread
flush_thread("flush");
100 flush_thread
.task_runner()->PostTask(
101 FROM_HERE
, base::Bind(&TraceEventTestFixture::EndTraceAndFlushAsync
,
102 base::Unretained(this), &flush_complete_event
));
103 flush_complete_event
.Wait();
106 void EndTraceAndFlushAsync(WaitableEvent
* flush_complete_event
) {
107 TraceLog::GetInstance()->SetDisabled();
108 TraceLog::GetInstance()->Flush(
109 base::Bind(&TraceEventTestFixture::OnTraceDataCollected
,
110 base::Unretained(static_cast<TraceEventTestFixture
*>(this)),
111 base::Unretained(flush_complete_event
)));
114 void FlushMonitoring() {
115 WaitableEvent
flush_complete_event(false, false);
116 FlushMonitoring(&flush_complete_event
);
117 flush_complete_event
.Wait();
120 void FlushMonitoring(WaitableEvent
* flush_complete_event
) {
121 TraceLog::GetInstance()->FlushButLeaveBufferIntact(
122 base::Bind(&TraceEventTestFixture::OnTraceDataCollected
,
123 base::Unretained(static_cast<TraceEventTestFixture
*>(this)),
124 base::Unretained(flush_complete_event
)));
127 void SetUp() override
{
128 const char* name
= PlatformThread::GetName();
129 old_thread_name_
= name
? strdup(name
) : NULL
;
131 TraceLog::DeleteForTesting();
132 TraceLog
* tracelog
= TraceLog::GetInstance();
133 ASSERT_TRUE(tracelog
);
134 ASSERT_FALSE(tracelog
->IsEnabled());
135 trace_buffer_
.SetOutputCallback(json_output_
.GetCallback());
136 event_watch_notification_
= 0;
138 void TearDown() override
{
139 if (TraceLog::GetInstance())
140 EXPECT_FALSE(TraceLog::GetInstance()->IsEnabled());
141 PlatformThread::SetName(old_thread_name_
? old_thread_name_
: "");
142 free(old_thread_name_
);
143 old_thread_name_
= NULL
;
144 // We want our singleton torn down after each test.
145 TraceLog::DeleteForTesting();
148 char* old_thread_name_
;
149 ListValue trace_parsed_
;
150 TraceResultBuffer trace_buffer_
;
151 TraceResultBuffer::SimpleOutput json_output_
;
152 int event_watch_notification_
;
155 // We want our singleton torn down after each test.
156 ShadowingAtExitManager at_exit_manager_
;
160 void TraceEventTestFixture::OnTraceDataCollected(
161 WaitableEvent
* flush_complete_event
,
162 const scoped_refptr
<base::RefCountedString
>& events_str
,
163 bool has_more_events
) {
164 AutoLock
lock(lock_
);
165 json_output_
.json_output
.clear();
166 trace_buffer_
.Start();
167 trace_buffer_
.AddFragment(events_str
->data());
168 trace_buffer_
.Finish();
170 scoped_ptr
<Value
> root
;
171 root
.reset(base::JSONReader::DeprecatedRead(
172 json_output_
.json_output
, JSON_PARSE_RFC
| JSON_DETACHABLE_CHILDREN
));
175 LOG(ERROR
) << json_output_
.json_output
;
178 ListValue
* root_list
= NULL
;
179 ASSERT_TRUE(root
.get());
180 ASSERT_TRUE(root
->GetAsList(&root_list
));
182 // Move items into our aggregate collection
183 while (root_list
->GetSize()) {
184 scoped_ptr
<Value
> item
;
185 root_list
->Remove(0, &item
);
186 trace_parsed_
.Append(item
.release());
189 if (!has_more_events
)
190 flush_complete_event
->Signal();
193 static bool CompareJsonValues(const std::string
& lhs
,
194 const std::string
& rhs
,
207 static bool IsKeyValueInDict(const JsonKeyValue
* key_value
,
208 DictionaryValue
* dict
) {
210 std::string value_str
;
211 if (dict
->Get(key_value
->key
, &value
) &&
212 value
->GetAsString(&value_str
) &&
213 CompareJsonValues(value_str
, key_value
->value
, key_value
->op
))
216 // Recurse to test arguments
217 DictionaryValue
* args_dict
= NULL
;
218 dict
->GetDictionary("args", &args_dict
);
220 return IsKeyValueInDict(key_value
, args_dict
);
225 static bool IsAllKeyValueInDict(const JsonKeyValue
* key_values
,
226 DictionaryValue
* dict
) {
227 // Scan all key_values, they must all be present and equal.
228 while (key_values
&& key_values
->key
) {
229 if (!IsKeyValueInDict(key_values
, dict
))
236 DictionaryValue
* TraceEventTestFixture::FindMatchingTraceEntry(
237 const JsonKeyValue
* key_values
) {
239 size_t trace_parsed_count
= trace_parsed_
.GetSize();
240 for (size_t i
= 0; i
< trace_parsed_count
; i
++) {
242 trace_parsed_
.Get(i
, &value
);
243 if (!value
|| value
->GetType() != Value::TYPE_DICTIONARY
)
245 DictionaryValue
* dict
= static_cast<DictionaryValue
*>(value
);
247 if (IsAllKeyValueInDict(key_values
, dict
))
253 void TraceEventTestFixture::DropTracedMetadataRecords() {
254 scoped_ptr
<ListValue
> old_trace_parsed(trace_parsed_
.DeepCopy());
255 size_t old_trace_parsed_size
= old_trace_parsed
->GetSize();
256 trace_parsed_
.Clear();
258 for (size_t i
= 0; i
< old_trace_parsed_size
; i
++) {
260 old_trace_parsed
->Get(i
, &value
);
261 if (!value
|| value
->GetType() != Value::TYPE_DICTIONARY
) {
262 trace_parsed_
.Append(value
->DeepCopy());
265 DictionaryValue
* dict
= static_cast<DictionaryValue
*>(value
);
267 if (dict
->GetString("ph", &tmp
) && tmp
== "M")
270 trace_parsed_
.Append(value
->DeepCopy());
274 DictionaryValue
* TraceEventTestFixture::FindNamePhase(const char* name
,
276 JsonKeyValue key_values
[] = {
277 {"name", name
, IS_EQUAL
},
278 {"ph", phase
, IS_EQUAL
},
281 return FindMatchingTraceEntry(key_values
);
284 DictionaryValue
* TraceEventTestFixture::FindNamePhaseKeyValue(
289 JsonKeyValue key_values
[] = {
290 {"name", name
, IS_EQUAL
},
291 {"ph", phase
, IS_EQUAL
},
292 {key
, value
, IS_EQUAL
},
295 return FindMatchingTraceEntry(key_values
);
298 bool TraceEventTestFixture::FindMatchingValue(const char* key
,
300 JsonKeyValue key_values
[] = {
301 {key
, value
, IS_EQUAL
},
304 return FindMatchingTraceEntry(key_values
);
307 bool TraceEventTestFixture::FindNonMatchingValue(const char* key
,
309 JsonKeyValue key_values
[] = {
310 {key
, value
, IS_NOT_EQUAL
},
313 return FindMatchingTraceEntry(key_values
);
316 bool IsStringInDict(const char* string_to_match
, const DictionaryValue
* dict
) {
317 for (DictionaryValue::Iterator
it(*dict
); !it
.IsAtEnd(); it
.Advance()) {
318 if (it
.key().find(string_to_match
) != std::string::npos
)
321 std::string value_str
;
322 it
.value().GetAsString(&value_str
);
323 if (value_str
.find(string_to_match
) != std::string::npos
)
327 // Recurse to test arguments
328 const DictionaryValue
* args_dict
= NULL
;
329 dict
->GetDictionary("args", &args_dict
);
331 return IsStringInDict(string_to_match
, args_dict
);
336 const DictionaryValue
* FindTraceEntry(
337 const ListValue
& trace_parsed
,
338 const char* string_to_match
,
339 const DictionaryValue
* match_after_this_item
= NULL
) {
341 size_t trace_parsed_count
= trace_parsed
.GetSize();
342 for (size_t i
= 0; i
< trace_parsed_count
; i
++) {
343 const Value
* value
= NULL
;
344 trace_parsed
.Get(i
, &value
);
345 if (match_after_this_item
) {
346 if (value
== match_after_this_item
)
347 match_after_this_item
= NULL
;
350 if (!value
|| value
->GetType() != Value::TYPE_DICTIONARY
)
352 const DictionaryValue
* dict
= static_cast<const DictionaryValue
*>(value
);
354 if (IsStringInDict(string_to_match
, dict
))
360 std::vector
<const DictionaryValue
*> FindTraceEntries(
361 const ListValue
& trace_parsed
,
362 const char* string_to_match
) {
363 std::vector
<const DictionaryValue
*> hits
;
364 size_t trace_parsed_count
= trace_parsed
.GetSize();
365 for (size_t i
= 0; i
< trace_parsed_count
; i
++) {
366 const Value
* value
= NULL
;
367 trace_parsed
.Get(i
, &value
);
368 if (!value
|| value
->GetType() != Value::TYPE_DICTIONARY
)
370 const DictionaryValue
* dict
= static_cast<const DictionaryValue
*>(value
);
372 if (IsStringInDict(string_to_match
, dict
))
373 hits
.push_back(dict
);
378 const char kControlCharacters
[] = "\001\002\003\n\r";
380 void TraceWithAllMacroVariants(WaitableEvent
* task_complete_event
) {
382 TRACE_EVENT_BEGIN_ETW("TRACE_EVENT_BEGIN_ETW call", 0x1122, "extrastring1");
383 TRACE_EVENT_END_ETW("TRACE_EVENT_END_ETW call", 0x3344, "extrastring2");
384 TRACE_EVENT_INSTANT_ETW("TRACE_EVENT_INSTANT_ETW call",
385 0x5566, "extrastring3");
387 TRACE_EVENT0("all", "TRACE_EVENT0 call");
388 TRACE_EVENT1("all", "TRACE_EVENT1 call", "name1", "value1");
389 TRACE_EVENT2("all", "TRACE_EVENT2 call",
390 "name1", "\"value1\"",
391 "name2", "value\\2");
393 TRACE_EVENT_INSTANT0("all", "TRACE_EVENT_INSTANT0 call",
394 TRACE_EVENT_SCOPE_GLOBAL
);
395 TRACE_EVENT_INSTANT1("all", "TRACE_EVENT_INSTANT1 call",
396 TRACE_EVENT_SCOPE_PROCESS
, "name1", "value1");
397 TRACE_EVENT_INSTANT2("all", "TRACE_EVENT_INSTANT2 call",
398 TRACE_EVENT_SCOPE_THREAD
,
402 TRACE_EVENT_BEGIN0("all", "TRACE_EVENT_BEGIN0 call");
403 TRACE_EVENT_BEGIN1("all", "TRACE_EVENT_BEGIN1 call", "name1", "value1");
404 TRACE_EVENT_BEGIN2("all", "TRACE_EVENT_BEGIN2 call",
408 TRACE_EVENT_END0("all", "TRACE_EVENT_END0 call");
409 TRACE_EVENT_END1("all", "TRACE_EVENT_END1 call", "name1", "value1");
410 TRACE_EVENT_END2("all", "TRACE_EVENT_END2 call",
414 TRACE_EVENT_ASYNC_BEGIN0("all", "TRACE_EVENT_ASYNC_BEGIN0 call", kAsyncId
);
415 TRACE_EVENT_ASYNC_BEGIN1("all", "TRACE_EVENT_ASYNC_BEGIN1 call", kAsyncId
,
417 TRACE_EVENT_ASYNC_BEGIN2("all", "TRACE_EVENT_ASYNC_BEGIN2 call", kAsyncId
,
421 TRACE_EVENT_ASYNC_STEP_INTO0("all", "TRACE_EVENT_ASYNC_STEP_INTO0 call",
422 kAsyncId
, "step_begin1");
423 TRACE_EVENT_ASYNC_STEP_INTO1("all", "TRACE_EVENT_ASYNC_STEP_INTO1 call",
424 kAsyncId
, "step_begin2", "name1", "value1");
426 TRACE_EVENT_ASYNC_END0("all", "TRACE_EVENT_ASYNC_END0 call", kAsyncId
);
427 TRACE_EVENT_ASYNC_END1("all", "TRACE_EVENT_ASYNC_END1 call", kAsyncId
,
429 TRACE_EVENT_ASYNC_END2("all", "TRACE_EVENT_ASYNC_END2 call", kAsyncId
,
433 TRACE_EVENT_BEGIN_ETW("TRACE_EVENT_BEGIN_ETW0 call", kAsyncId
, NULL
);
434 TRACE_EVENT_BEGIN_ETW("TRACE_EVENT_BEGIN_ETW1 call", kAsyncId
, "value");
435 TRACE_EVENT_END_ETW("TRACE_EVENT_END_ETW0 call", kAsyncId
, NULL
);
436 TRACE_EVENT_END_ETW("TRACE_EVENT_END_ETW1 call", kAsyncId
, "value");
437 TRACE_EVENT_INSTANT_ETW("TRACE_EVENT_INSTANT_ETW0 call", kAsyncId
, NULL
);
438 TRACE_EVENT_INSTANT_ETW("TRACE_EVENT_INSTANT_ETW1 call", kAsyncId
, "value");
440 TRACE_COUNTER1("all", "TRACE_COUNTER1 call", 31415);
441 TRACE_COUNTER2("all", "TRACE_COUNTER2 call",
445 TRACE_COUNTER_ID1("all", "TRACE_COUNTER_ID1 call", 0x319009, 31415);
446 TRACE_COUNTER_ID2("all", "TRACE_COUNTER_ID2 call", 0x319009,
447 "a", 30000, "b", 1415);
449 TRACE_EVENT_COPY_BEGIN_WITH_ID_TID_AND_TIMESTAMP0("all",
450 "TRACE_EVENT_COPY_BEGIN_WITH_ID_TID_AND_TIMESTAMP0 call",
451 kAsyncId
, kThreadId
, 12345);
452 TRACE_EVENT_COPY_END_WITH_ID_TID_AND_TIMESTAMP0("all",
453 "TRACE_EVENT_COPY_END_WITH_ID_TID_AND_TIMESTAMP0 call",
454 kAsyncId
, kThreadId
, 23456);
456 TRACE_EVENT_BEGIN_WITH_ID_TID_AND_TIMESTAMP0("all",
457 "TRACE_EVENT_BEGIN_WITH_ID_TID_AND_TIMESTAMP0 call",
458 kAsyncId2
, kThreadId
, 34567);
459 TRACE_EVENT_ASYNC_STEP_PAST0("all", "TRACE_EVENT_ASYNC_STEP_PAST0 call",
460 kAsyncId2
, "step_end1");
461 TRACE_EVENT_ASYNC_STEP_PAST1("all", "TRACE_EVENT_ASYNC_STEP_PAST1 call",
462 kAsyncId2
, "step_end2", "name1", "value1");
464 TRACE_EVENT_END_WITH_ID_TID_AND_TIMESTAMP0("all",
465 "TRACE_EVENT_END_WITH_ID_TID_AND_TIMESTAMP0 call",
466 kAsyncId2
, kThreadId
, 45678);
468 TRACE_EVENT_OBJECT_CREATED_WITH_ID("all", "tracked object 1", 0x42);
469 TRACE_EVENT_OBJECT_SNAPSHOT_WITH_ID(
470 "all", "tracked object 1", 0x42, "hello");
471 TRACE_EVENT_OBJECT_DELETED_WITH_ID("all", "tracked object 1", 0x42);
473 TraceScopedTrackableObject
<int> trackable("all", "tracked object 2",
475 trackable
.snapshot("world");
477 TRACE_EVENT1(kControlCharacters
, kControlCharacters
,
478 kControlCharacters
, kControlCharacters
);
479 } // Scope close causes TRACE_EVENT0 etc to send their END events.
481 if (task_complete_event
)
482 task_complete_event
->Signal();
485 void ValidateAllTraceMacrosCreatedData(const ListValue
& trace_parsed
) {
486 const DictionaryValue
* item
= NULL
;
488 #define EXPECT_FIND_(string) \
489 item = FindTraceEntry(trace_parsed, string); \
491 #define EXPECT_NOT_FIND_(string) \
492 item = FindTraceEntry(trace_parsed, string); \
494 #define EXPECT_SUB_FIND_(string) \
496 EXPECT_TRUE(IsStringInDict(string, item));
498 EXPECT_FIND_("ETW Trace Event");
500 EXPECT_FIND_("TRACE_EVENT_BEGIN_ETW call");
503 EXPECT_TRUE(item
&& item
->GetString("args.id", &str_val
));
504 EXPECT_STREQ("0x1122", str_val
.c_str());
506 EXPECT_SUB_FIND_("extrastring1");
507 EXPECT_FIND_("TRACE_EVENT_END_ETW call");
508 EXPECT_FIND_("TRACE_EVENT_INSTANT_ETW call");
509 EXPECT_FIND_("TRACE_EVENT0 call");
513 EXPECT_TRUE((item
= FindTraceEntry(trace_parsed
, "TRACE_EVENT0 call")));
514 EXPECT_TRUE((item
&& item
->GetString("ph", &ph
)));
516 item
= FindTraceEntry(trace_parsed
, "TRACE_EVENT0 call", item
);
519 EXPECT_FIND_("TRACE_EVENT1 call");
520 EXPECT_SUB_FIND_("name1");
521 EXPECT_SUB_FIND_("value1");
522 EXPECT_FIND_("TRACE_EVENT2 call");
523 EXPECT_SUB_FIND_("name1");
524 EXPECT_SUB_FIND_("\"value1\"");
525 EXPECT_SUB_FIND_("name2");
526 EXPECT_SUB_FIND_("value\\2");
528 EXPECT_FIND_("TRACE_EVENT_INSTANT0 call");
531 EXPECT_TRUE((item
&& item
->GetString("s", &scope
)));
532 EXPECT_EQ("g", scope
);
534 EXPECT_FIND_("TRACE_EVENT_INSTANT1 call");
537 EXPECT_TRUE((item
&& item
->GetString("s", &scope
)));
538 EXPECT_EQ("p", scope
);
540 EXPECT_SUB_FIND_("name1");
541 EXPECT_SUB_FIND_("value1");
542 EXPECT_FIND_("TRACE_EVENT_INSTANT2 call");
545 EXPECT_TRUE((item
&& item
->GetString("s", &scope
)));
546 EXPECT_EQ("t", scope
);
548 EXPECT_SUB_FIND_("name1");
549 EXPECT_SUB_FIND_("value1");
550 EXPECT_SUB_FIND_("name2");
551 EXPECT_SUB_FIND_("value2");
553 EXPECT_FIND_("TRACE_EVENT_BEGIN0 call");
554 EXPECT_FIND_("TRACE_EVENT_BEGIN1 call");
555 EXPECT_SUB_FIND_("name1");
556 EXPECT_SUB_FIND_("value1");
557 EXPECT_FIND_("TRACE_EVENT_BEGIN2 call");
558 EXPECT_SUB_FIND_("name1");
559 EXPECT_SUB_FIND_("value1");
560 EXPECT_SUB_FIND_("name2");
561 EXPECT_SUB_FIND_("value2");
563 EXPECT_FIND_("TRACE_EVENT_END0 call");
564 EXPECT_FIND_("TRACE_EVENT_END1 call");
565 EXPECT_SUB_FIND_("name1");
566 EXPECT_SUB_FIND_("value1");
567 EXPECT_FIND_("TRACE_EVENT_END2 call");
568 EXPECT_SUB_FIND_("name1");
569 EXPECT_SUB_FIND_("value1");
570 EXPECT_SUB_FIND_("name2");
571 EXPECT_SUB_FIND_("value2");
573 EXPECT_FIND_("TRACE_EVENT_ASYNC_BEGIN0 call");
574 EXPECT_SUB_FIND_("id");
575 EXPECT_SUB_FIND_(kAsyncIdStr
);
576 EXPECT_FIND_("TRACE_EVENT_ASYNC_BEGIN1 call");
577 EXPECT_SUB_FIND_("id");
578 EXPECT_SUB_FIND_(kAsyncIdStr
);
579 EXPECT_SUB_FIND_("name1");
580 EXPECT_SUB_FIND_("value1");
581 EXPECT_FIND_("TRACE_EVENT_ASYNC_BEGIN2 call");
582 EXPECT_SUB_FIND_("id");
583 EXPECT_SUB_FIND_(kAsyncIdStr
);
584 EXPECT_SUB_FIND_("name1");
585 EXPECT_SUB_FIND_("value1");
586 EXPECT_SUB_FIND_("name2");
587 EXPECT_SUB_FIND_("value2");
589 EXPECT_FIND_("TRACE_EVENT_ASYNC_STEP_INTO0 call");
590 EXPECT_SUB_FIND_("id");
591 EXPECT_SUB_FIND_(kAsyncIdStr
);
592 EXPECT_SUB_FIND_("step_begin1");
593 EXPECT_FIND_("TRACE_EVENT_ASYNC_STEP_INTO1 call");
594 EXPECT_SUB_FIND_("id");
595 EXPECT_SUB_FIND_(kAsyncIdStr
);
596 EXPECT_SUB_FIND_("step_begin2");
597 EXPECT_SUB_FIND_("name1");
598 EXPECT_SUB_FIND_("value1");
600 EXPECT_FIND_("TRACE_EVENT_ASYNC_END0 call");
601 EXPECT_SUB_FIND_("id");
602 EXPECT_SUB_FIND_(kAsyncIdStr
);
603 EXPECT_FIND_("TRACE_EVENT_ASYNC_END1 call");
604 EXPECT_SUB_FIND_("id");
605 EXPECT_SUB_FIND_(kAsyncIdStr
);
606 EXPECT_SUB_FIND_("name1");
607 EXPECT_SUB_FIND_("value1");
608 EXPECT_FIND_("TRACE_EVENT_ASYNC_END2 call");
609 EXPECT_SUB_FIND_("id");
610 EXPECT_SUB_FIND_(kAsyncIdStr
);
611 EXPECT_SUB_FIND_("name1");
612 EXPECT_SUB_FIND_("value1");
613 EXPECT_SUB_FIND_("name2");
614 EXPECT_SUB_FIND_("value2");
616 EXPECT_FIND_("TRACE_EVENT_BEGIN_ETW0 call");
617 EXPECT_SUB_FIND_("id");
618 EXPECT_SUB_FIND_(kAsyncIdStr
);
619 EXPECT_SUB_FIND_("extra");
620 EXPECT_SUB_FIND_("NULL");
621 EXPECT_FIND_("TRACE_EVENT_BEGIN_ETW1 call");
622 EXPECT_SUB_FIND_("id");
623 EXPECT_SUB_FIND_(kAsyncIdStr
);
624 EXPECT_SUB_FIND_("extra");
625 EXPECT_SUB_FIND_("value");
626 EXPECT_FIND_("TRACE_EVENT_END_ETW0 call");
627 EXPECT_SUB_FIND_("id");
628 EXPECT_SUB_FIND_(kAsyncIdStr
);
629 EXPECT_SUB_FIND_("extra");
630 EXPECT_SUB_FIND_("NULL");
631 EXPECT_FIND_("TRACE_EVENT_END_ETW1 call");
632 EXPECT_SUB_FIND_("id");
633 EXPECT_SUB_FIND_(kAsyncIdStr
);
634 EXPECT_SUB_FIND_("extra");
635 EXPECT_SUB_FIND_("value");
636 EXPECT_FIND_("TRACE_EVENT_INSTANT_ETW0 call");
637 EXPECT_SUB_FIND_("id");
638 EXPECT_SUB_FIND_(kAsyncIdStr
);
639 EXPECT_SUB_FIND_("extra");
640 EXPECT_SUB_FIND_("NULL");
641 EXPECT_FIND_("TRACE_EVENT_INSTANT_ETW1 call");
642 EXPECT_SUB_FIND_("id");
643 EXPECT_SUB_FIND_(kAsyncIdStr
);
644 EXPECT_SUB_FIND_("extra");
645 EXPECT_SUB_FIND_("value");
647 EXPECT_FIND_("TRACE_COUNTER1 call");
650 EXPECT_TRUE((item
&& item
->GetString("ph", &ph
)));
654 EXPECT_TRUE((item
&& item
->GetInteger("args.value", &value
)));
655 EXPECT_EQ(31415, value
);
658 EXPECT_FIND_("TRACE_COUNTER2 call");
661 EXPECT_TRUE((item
&& item
->GetString("ph", &ph
)));
665 EXPECT_TRUE((item
&& item
->GetInteger("args.a", &value
)));
666 EXPECT_EQ(30000, value
);
668 EXPECT_TRUE((item
&& item
->GetInteger("args.b", &value
)));
669 EXPECT_EQ(1415, value
);
672 EXPECT_FIND_("TRACE_COUNTER_ID1 call");
675 EXPECT_TRUE((item
&& item
->GetString("id", &id
)));
676 EXPECT_EQ("0x319009", id
);
679 EXPECT_TRUE((item
&& item
->GetString("ph", &ph
)));
683 EXPECT_TRUE((item
&& item
->GetInteger("args.value", &value
)));
684 EXPECT_EQ(31415, value
);
687 EXPECT_FIND_("TRACE_COUNTER_ID2 call");
690 EXPECT_TRUE((item
&& item
->GetString("id", &id
)));
691 EXPECT_EQ("0x319009", id
);
694 EXPECT_TRUE((item
&& item
->GetString("ph", &ph
)));
698 EXPECT_TRUE((item
&& item
->GetInteger("args.a", &value
)));
699 EXPECT_EQ(30000, value
);
701 EXPECT_TRUE((item
&& item
->GetInteger("args.b", &value
)));
702 EXPECT_EQ(1415, value
);
705 EXPECT_FIND_("TRACE_EVENT_COPY_BEGIN_WITH_ID_TID_AND_TIMESTAMP0 call");
708 EXPECT_TRUE((item
&& item
->GetInteger("ts", &val
)));
709 EXPECT_EQ(12345, val
);
710 EXPECT_TRUE((item
&& item
->GetInteger("tid", &val
)));
711 EXPECT_EQ(kThreadId
, val
);
713 EXPECT_TRUE((item
&& item
->GetString("id", &id
)));
714 EXPECT_EQ(kAsyncIdStr
, id
);
717 EXPECT_FIND_("TRACE_EVENT_COPY_END_WITH_ID_TID_AND_TIMESTAMP0 call");
720 EXPECT_TRUE((item
&& item
->GetInteger("ts", &val
)));
721 EXPECT_EQ(23456, val
);
722 EXPECT_TRUE((item
&& item
->GetInteger("tid", &val
)));
723 EXPECT_EQ(kThreadId
, val
);
725 EXPECT_TRUE((item
&& item
->GetString("id", &id
)));
726 EXPECT_EQ(kAsyncIdStr
, id
);
729 EXPECT_FIND_("TRACE_EVENT_BEGIN_WITH_ID_TID_AND_TIMESTAMP0 call");
732 EXPECT_TRUE((item
&& item
->GetInteger("ts", &val
)));
733 EXPECT_EQ(34567, val
);
734 EXPECT_TRUE((item
&& item
->GetInteger("tid", &val
)));
735 EXPECT_EQ(kThreadId
, val
);
737 EXPECT_TRUE((item
&& item
->GetString("id", &id
)));
738 EXPECT_EQ(kAsyncId2Str
, id
);
741 EXPECT_FIND_("TRACE_EVENT_ASYNC_STEP_PAST0 call");
743 EXPECT_SUB_FIND_("id");
744 EXPECT_SUB_FIND_(kAsyncId2Str
);
745 EXPECT_SUB_FIND_("step_end1");
746 EXPECT_FIND_("TRACE_EVENT_ASYNC_STEP_PAST1 call");
747 EXPECT_SUB_FIND_("id");
748 EXPECT_SUB_FIND_(kAsyncId2Str
);
749 EXPECT_SUB_FIND_("step_end2");
750 EXPECT_SUB_FIND_("name1");
751 EXPECT_SUB_FIND_("value1");
754 EXPECT_FIND_("TRACE_EVENT_END_WITH_ID_TID_AND_TIMESTAMP0 call");
757 EXPECT_TRUE((item
&& item
->GetInteger("ts", &val
)));
758 EXPECT_EQ(45678, val
);
759 EXPECT_TRUE((item
&& item
->GetInteger("tid", &val
)));
760 EXPECT_EQ(kThreadId
, val
);
762 EXPECT_TRUE((item
&& item
->GetString("id", &id
)));
763 EXPECT_EQ(kAsyncId2Str
, id
);
766 EXPECT_FIND_("tracked object 1");
770 std::string snapshot
;
772 EXPECT_TRUE((item
&& item
->GetString("ph", &phase
)));
773 EXPECT_EQ("N", phase
);
774 EXPECT_TRUE((item
&& item
->GetString("id", &id
)));
775 EXPECT_EQ("0x42", id
);
777 item
= FindTraceEntry(trace_parsed
, "tracked object 1", item
);
779 EXPECT_TRUE(item
&& item
->GetString("ph", &phase
));
780 EXPECT_EQ("O", phase
);
781 EXPECT_TRUE(item
&& item
->GetString("id", &id
));
782 EXPECT_EQ("0x42", id
);
783 EXPECT_TRUE(item
&& item
->GetString("args.snapshot", &snapshot
));
784 EXPECT_EQ("hello", snapshot
);
786 item
= FindTraceEntry(trace_parsed
, "tracked object 1", item
);
788 EXPECT_TRUE(item
&& item
->GetString("ph", &phase
));
789 EXPECT_EQ("D", phase
);
790 EXPECT_TRUE(item
&& item
->GetString("id", &id
));
791 EXPECT_EQ("0x42", id
);
794 EXPECT_FIND_("tracked object 2");
798 std::string snapshot
;
800 EXPECT_TRUE(item
&& item
->GetString("ph", &phase
));
801 EXPECT_EQ("N", phase
);
802 EXPECT_TRUE(item
&& item
->GetString("id", &id
));
803 EXPECT_EQ("0x2128506", id
);
805 item
= FindTraceEntry(trace_parsed
, "tracked object 2", item
);
807 EXPECT_TRUE(item
&& item
->GetString("ph", &phase
));
808 EXPECT_EQ("O", phase
);
809 EXPECT_TRUE(item
&& item
->GetString("id", &id
));
810 EXPECT_EQ("0x2128506", id
);
811 EXPECT_TRUE(item
&& item
->GetString("args.snapshot", &snapshot
));
812 EXPECT_EQ("world", snapshot
);
814 item
= FindTraceEntry(trace_parsed
, "tracked object 2", item
);
816 EXPECT_TRUE(item
&& item
->GetString("ph", &phase
));
817 EXPECT_EQ("D", phase
);
818 EXPECT_TRUE(item
&& item
->GetString("id", &id
));
819 EXPECT_EQ("0x2128506", id
);
822 EXPECT_FIND_(kControlCharacters
);
823 EXPECT_SUB_FIND_(kControlCharacters
);
826 void TraceManyInstantEvents(int thread_id
, int num_events
,
827 WaitableEvent
* task_complete_event
) {
828 for (int i
= 0; i
< num_events
; i
++) {
829 TRACE_EVENT_INSTANT2("all", "multi thread event",
830 TRACE_EVENT_SCOPE_THREAD
,
835 if (task_complete_event
)
836 task_complete_event
->Signal();
839 void ValidateInstantEventPresentOnEveryThread(const ListValue
& trace_parsed
,
842 std::map
<int, std::map
<int, bool> > results
;
844 size_t trace_parsed_count
= trace_parsed
.GetSize();
845 for (size_t i
= 0; i
< trace_parsed_count
; i
++) {
846 const Value
* value
= NULL
;
847 trace_parsed
.Get(i
, &value
);
848 if (!value
|| value
->GetType() != Value::TYPE_DICTIONARY
)
850 const DictionaryValue
* dict
= static_cast<const DictionaryValue
*>(value
);
852 dict
->GetString("name", &name
);
853 if (name
!= "multi thread event")
858 EXPECT_TRUE(dict
->GetInteger("args.thread", &thread
));
859 EXPECT_TRUE(dict
->GetInteger("args.event", &event
));
860 results
[thread
][event
] = true;
863 EXPECT_FALSE(results
[-1][-1]);
864 for (int thread
= 0; thread
< num_threads
; thread
++) {
865 for (int event
= 0; event
< num_events
; event
++) {
866 EXPECT_TRUE(results
[thread
][event
]);
873 // Simple Test for emitting data and validating it was received.
874 TEST_F(TraceEventTestFixture
, DataCaptured
) {
875 TraceLog::GetInstance()->SetEnabled(
877 TraceLog::RECORDING_MODE
,
880 TraceWithAllMacroVariants(NULL
);
884 ValidateAllTraceMacrosCreatedData(trace_parsed_
);
887 class MockEnabledStateChangedObserver
:
888 public TraceLog::EnabledStateObserver
{
890 MOCK_METHOD0(OnTraceLogEnabled
, void());
891 MOCK_METHOD0(OnTraceLogDisabled
, void());
894 TEST_F(TraceEventTestFixture
, EnabledObserverFiresOnEnable
) {
895 MockEnabledStateChangedObserver observer
;
896 TraceLog::GetInstance()->AddEnabledStateObserver(&observer
);
898 EXPECT_CALL(observer
, OnTraceLogEnabled())
900 TraceLog::GetInstance()->SetEnabled(
902 TraceLog::RECORDING_MODE
,
904 testing::Mock::VerifyAndClear(&observer
);
905 EXPECT_TRUE(TraceLog::GetInstance()->IsEnabled());
908 TraceLog::GetInstance()->RemoveEnabledStateObserver(&observer
);
909 TraceLog::GetInstance()->SetDisabled();
912 TEST_F(TraceEventTestFixture
, EnabledObserverDoesntFireOnSecondEnable
) {
913 TraceLog::GetInstance()->SetEnabled(
915 TraceLog::RECORDING_MODE
,
918 testing::StrictMock
<MockEnabledStateChangedObserver
> observer
;
919 TraceLog::GetInstance()->AddEnabledStateObserver(&observer
);
921 EXPECT_CALL(observer
, OnTraceLogEnabled())
923 EXPECT_CALL(observer
, OnTraceLogDisabled())
925 TraceLog::GetInstance()->SetEnabled(
927 TraceLog::RECORDING_MODE
,
929 testing::Mock::VerifyAndClear(&observer
);
930 EXPECT_TRUE(TraceLog::GetInstance()->IsEnabled());
933 TraceLog::GetInstance()->RemoveEnabledStateObserver(&observer
);
934 TraceLog::GetInstance()->SetDisabled();
935 TraceLog::GetInstance()->SetDisabled();
938 TEST_F(TraceEventTestFixture
, EnabledObserverFiresOnFirstDisable
) {
939 CategoryFilter
cf_inc_all("*");
940 TraceLog::GetInstance()->SetEnabled(
942 TraceLog::RECORDING_MODE
,
944 TraceLog::GetInstance()->SetEnabled(
946 TraceLog::RECORDING_MODE
,
949 testing::StrictMock
<MockEnabledStateChangedObserver
> observer
;
950 TraceLog::GetInstance()->AddEnabledStateObserver(&observer
);
952 EXPECT_CALL(observer
, OnTraceLogEnabled())
954 EXPECT_CALL(observer
, OnTraceLogDisabled())
956 TraceLog::GetInstance()->SetDisabled();
957 testing::Mock::VerifyAndClear(&observer
);
960 TraceLog::GetInstance()->RemoveEnabledStateObserver(&observer
);
961 TraceLog::GetInstance()->SetDisabled();
964 TEST_F(TraceEventTestFixture
, EnabledObserverFiresOnDisable
) {
965 TraceLog::GetInstance()->SetEnabled(
967 TraceLog::RECORDING_MODE
,
970 MockEnabledStateChangedObserver observer
;
971 TraceLog::GetInstance()->AddEnabledStateObserver(&observer
);
973 EXPECT_CALL(observer
, OnTraceLogDisabled())
975 TraceLog::GetInstance()->SetDisabled();
976 testing::Mock::VerifyAndClear(&observer
);
979 TraceLog::GetInstance()->RemoveEnabledStateObserver(&observer
);
982 // Tests the IsEnabled() state of TraceLog changes before callbacks.
983 class AfterStateChangeEnabledStateObserver
984 : public TraceLog::EnabledStateObserver
{
986 AfterStateChangeEnabledStateObserver() {}
987 virtual ~AfterStateChangeEnabledStateObserver() {}
989 // TraceLog::EnabledStateObserver overrides:
990 void OnTraceLogEnabled() override
{
991 EXPECT_TRUE(TraceLog::GetInstance()->IsEnabled());
994 void OnTraceLogDisabled() override
{
995 EXPECT_FALSE(TraceLog::GetInstance()->IsEnabled());
999 TEST_F(TraceEventTestFixture
, ObserversFireAfterStateChange
) {
1000 AfterStateChangeEnabledStateObserver observer
;
1001 TraceLog::GetInstance()->AddEnabledStateObserver(&observer
);
1003 TraceLog::GetInstance()->SetEnabled(
1004 CategoryFilter("*"),
1005 TraceLog::RECORDING_MODE
,
1007 EXPECT_TRUE(TraceLog::GetInstance()->IsEnabled());
1009 TraceLog::GetInstance()->SetDisabled();
1010 EXPECT_FALSE(TraceLog::GetInstance()->IsEnabled());
1012 TraceLog::GetInstance()->RemoveEnabledStateObserver(&observer
);
1015 // Tests that a state observer can remove itself during a callback.
1016 class SelfRemovingEnabledStateObserver
1017 : public TraceLog::EnabledStateObserver
{
1019 SelfRemovingEnabledStateObserver() {}
1020 virtual ~SelfRemovingEnabledStateObserver() {}
1022 // TraceLog::EnabledStateObserver overrides:
1023 void OnTraceLogEnabled() override
{}
1025 void OnTraceLogDisabled() override
{
1026 TraceLog::GetInstance()->RemoveEnabledStateObserver(this);
1030 TEST_F(TraceEventTestFixture
, SelfRemovingObserver
) {
1031 ASSERT_EQ(0u, TraceLog::GetInstance()->GetObserverCountForTest());
1033 SelfRemovingEnabledStateObserver observer
;
1034 TraceLog::GetInstance()->AddEnabledStateObserver(&observer
);
1035 EXPECT_EQ(1u, TraceLog::GetInstance()->GetObserverCountForTest());
1037 TraceLog::GetInstance()->SetEnabled(
1038 CategoryFilter("*"),
1039 TraceLog::RECORDING_MODE
,
1041 TraceLog::GetInstance()->SetDisabled();
1042 // The observer removed itself on disable.
1043 EXPECT_EQ(0u, TraceLog::GetInstance()->GetObserverCountForTest());
1048 TRACE_EVENT_IS_NEW_TRACE(&is_new_trace
);
1049 return is_new_trace
;
1052 TEST_F(TraceEventTestFixture
, NewTraceRecording
) {
1053 ASSERT_FALSE(IsNewTrace());
1054 TraceLog::GetInstance()->SetEnabled(
1055 CategoryFilter("*"),
1056 TraceLog::RECORDING_MODE
,
1058 // First call to IsNewTrace() should succeed. But, the second shouldn't.
1059 ASSERT_TRUE(IsNewTrace());
1060 ASSERT_FALSE(IsNewTrace());
1063 // IsNewTrace() should definitely be false now.
1064 ASSERT_FALSE(IsNewTrace());
1066 // Start another trace. IsNewTrace() should become true again, briefly, as
1068 TraceLog::GetInstance()->SetEnabled(
1069 CategoryFilter("*"),
1070 TraceLog::RECORDING_MODE
,
1072 ASSERT_TRUE(IsNewTrace());
1073 ASSERT_FALSE(IsNewTrace());
1080 // Test that categories work.
1081 TEST_F(TraceEventTestFixture
, Categories
) {
1082 // Test that categories that are used can be retrieved whether trace was
1083 // enabled or disabled when the trace event was encountered.
1084 TRACE_EVENT_INSTANT0("c1", "name", TRACE_EVENT_SCOPE_THREAD
);
1085 TRACE_EVENT_INSTANT0("c2", "name", TRACE_EVENT_SCOPE_THREAD
);
1087 TRACE_EVENT_INSTANT0("c3", "name", TRACE_EVENT_SCOPE_THREAD
);
1088 TRACE_EVENT_INSTANT0("c4", "name", TRACE_EVENT_SCOPE_THREAD
);
1089 // Category groups containing more than one category.
1090 TRACE_EVENT_INSTANT0("c5,c6", "name", TRACE_EVENT_SCOPE_THREAD
);
1091 TRACE_EVENT_INSTANT0("c7,c8", "name", TRACE_EVENT_SCOPE_THREAD
);
1092 TRACE_EVENT_INSTANT0(TRACE_DISABLED_BY_DEFAULT("c9"), "name",
1093 TRACE_EVENT_SCOPE_THREAD
);
1096 std::vector
<std::string
> cat_groups
;
1097 TraceLog::GetInstance()->GetKnownCategoryGroups(&cat_groups
);
1098 EXPECT_TRUE(std::find(cat_groups
.begin(),
1099 cat_groups
.end(), "c1") != cat_groups
.end());
1100 EXPECT_TRUE(std::find(cat_groups
.begin(),
1101 cat_groups
.end(), "c2") != cat_groups
.end());
1102 EXPECT_TRUE(std::find(cat_groups
.begin(),
1103 cat_groups
.end(), "c3") != cat_groups
.end());
1104 EXPECT_TRUE(std::find(cat_groups
.begin(),
1105 cat_groups
.end(), "c4") != cat_groups
.end());
1106 EXPECT_TRUE(std::find(cat_groups
.begin(),
1107 cat_groups
.end(), "c5,c6") != cat_groups
.end());
1108 EXPECT_TRUE(std::find(cat_groups
.begin(),
1109 cat_groups
.end(), "c7,c8") != cat_groups
.end());
1110 EXPECT_TRUE(std::find(cat_groups
.begin(),
1112 "disabled-by-default-c9") != cat_groups
.end());
1113 // Make sure metadata isn't returned.
1114 EXPECT_TRUE(std::find(cat_groups
.begin(),
1115 cat_groups
.end(), "__metadata") == cat_groups
.end());
1117 const std::vector
<std::string
> empty_categories
;
1118 std::vector
<std::string
> included_categories
;
1119 std::vector
<std::string
> excluded_categories
;
1121 // Test that category filtering works.
1123 // Include nonexistent category -> no events
1125 included_categories
.clear();
1126 TraceLog::GetInstance()->SetEnabled(
1127 CategoryFilter("not_found823564786"),
1128 TraceLog::RECORDING_MODE
,
1130 TRACE_EVENT_INSTANT0("cat1", "name", TRACE_EVENT_SCOPE_THREAD
);
1131 TRACE_EVENT_INSTANT0("cat2", "name", TRACE_EVENT_SCOPE_THREAD
);
1133 DropTracedMetadataRecords();
1134 EXPECT_TRUE(trace_parsed_
.empty());
1136 // Include existent category -> only events of that category
1138 included_categories
.clear();
1139 TraceLog::GetInstance()->SetEnabled(
1140 CategoryFilter("inc"),
1141 TraceLog::RECORDING_MODE
,
1143 TRACE_EVENT_INSTANT0("inc", "name", TRACE_EVENT_SCOPE_THREAD
);
1144 TRACE_EVENT_INSTANT0("inc2", "name", TRACE_EVENT_SCOPE_THREAD
);
1146 DropTracedMetadataRecords();
1147 EXPECT_TRUE(FindMatchingValue("cat", "inc"));
1148 EXPECT_FALSE(FindNonMatchingValue("cat", "inc"));
1150 // Include existent wildcard -> all categories matching wildcard
1152 included_categories
.clear();
1153 TraceLog::GetInstance()->SetEnabled(
1154 CategoryFilter("inc_wildcard_*,inc_wildchar_?_end"),
1155 TraceLog::RECORDING_MODE
,
1157 TRACE_EVENT_INSTANT0("inc_wildcard_abc", "included",
1158 TRACE_EVENT_SCOPE_THREAD
);
1159 TRACE_EVENT_INSTANT0("inc_wildcard_", "included", TRACE_EVENT_SCOPE_THREAD
);
1160 TRACE_EVENT_INSTANT0("inc_wildchar_x_end", "included",
1161 TRACE_EVENT_SCOPE_THREAD
);
1162 TRACE_EVENT_INSTANT0("inc_wildchar_bla_end", "not_inc",
1163 TRACE_EVENT_SCOPE_THREAD
);
1164 TRACE_EVENT_INSTANT0("cat1", "not_inc", TRACE_EVENT_SCOPE_THREAD
);
1165 TRACE_EVENT_INSTANT0("cat2", "not_inc", TRACE_EVENT_SCOPE_THREAD
);
1166 TRACE_EVENT_INSTANT0("inc_wildcard_category,other_category", "included",
1167 TRACE_EVENT_SCOPE_THREAD
);
1168 TRACE_EVENT_INSTANT0(
1169 "non_included_category,inc_wildcard_category", "included",
1170 TRACE_EVENT_SCOPE_THREAD
);
1172 EXPECT_TRUE(FindMatchingValue("cat", "inc_wildcard_abc"));
1173 EXPECT_TRUE(FindMatchingValue("cat", "inc_wildcard_"));
1174 EXPECT_TRUE(FindMatchingValue("cat", "inc_wildchar_x_end"));
1175 EXPECT_FALSE(FindMatchingValue("name", "not_inc"));
1176 EXPECT_TRUE(FindMatchingValue("cat", "inc_wildcard_category,other_category"));
1177 EXPECT_TRUE(FindMatchingValue("cat",
1178 "non_included_category,inc_wildcard_category"));
1180 included_categories
.clear();
1182 // Exclude nonexistent category -> all events
1184 TraceLog::GetInstance()->SetEnabled(
1185 CategoryFilter("-not_found823564786"),
1186 TraceLog::RECORDING_MODE
,
1188 TRACE_EVENT_INSTANT0("cat1", "name", TRACE_EVENT_SCOPE_THREAD
);
1189 TRACE_EVENT_INSTANT0("cat2", "name", TRACE_EVENT_SCOPE_THREAD
);
1190 TRACE_EVENT_INSTANT0("category1,category2", "name", TRACE_EVENT_SCOPE_THREAD
);
1192 EXPECT_TRUE(FindMatchingValue("cat", "cat1"));
1193 EXPECT_TRUE(FindMatchingValue("cat", "cat2"));
1194 EXPECT_TRUE(FindMatchingValue("cat", "category1,category2"));
1196 // Exclude existent category -> only events of other categories
1198 TraceLog::GetInstance()->SetEnabled(
1199 CategoryFilter("-inc"),
1200 TraceLog::RECORDING_MODE
,
1202 TRACE_EVENT_INSTANT0("inc", "name", TRACE_EVENT_SCOPE_THREAD
);
1203 TRACE_EVENT_INSTANT0("inc2", "name", TRACE_EVENT_SCOPE_THREAD
);
1204 TRACE_EVENT_INSTANT0("inc2,inc", "name", TRACE_EVENT_SCOPE_THREAD
);
1205 TRACE_EVENT_INSTANT0("inc,inc2", "name", TRACE_EVENT_SCOPE_THREAD
);
1207 EXPECT_TRUE(FindMatchingValue("cat", "inc2"));
1208 EXPECT_FALSE(FindMatchingValue("cat", "inc"));
1209 EXPECT_TRUE(FindMatchingValue("cat", "inc2,inc"));
1210 EXPECT_TRUE(FindMatchingValue("cat", "inc,inc2"));
1212 // Exclude existent wildcard -> all categories not matching wildcard
1214 TraceLog::GetInstance()->SetEnabled(
1215 CategoryFilter("-inc_wildcard_*,-inc_wildchar_?_end"),
1216 TraceLog::RECORDING_MODE
,
1218 TRACE_EVENT_INSTANT0("inc_wildcard_abc", "not_inc",
1219 TRACE_EVENT_SCOPE_THREAD
);
1220 TRACE_EVENT_INSTANT0("inc_wildcard_", "not_inc",
1221 TRACE_EVENT_SCOPE_THREAD
);
1222 TRACE_EVENT_INSTANT0("inc_wildchar_x_end", "not_inc",
1223 TRACE_EVENT_SCOPE_THREAD
);
1224 TRACE_EVENT_INSTANT0("inc_wildchar_bla_end", "included",
1225 TRACE_EVENT_SCOPE_THREAD
);
1226 TRACE_EVENT_INSTANT0("cat1", "included", TRACE_EVENT_SCOPE_THREAD
);
1227 TRACE_EVENT_INSTANT0("cat2", "included", TRACE_EVENT_SCOPE_THREAD
);
1229 EXPECT_TRUE(FindMatchingValue("cat", "inc_wildchar_bla_end"));
1230 EXPECT_TRUE(FindMatchingValue("cat", "cat1"));
1231 EXPECT_TRUE(FindMatchingValue("cat", "cat2"));
1232 EXPECT_FALSE(FindMatchingValue("name", "not_inc"));
1236 // Test EVENT_WATCH_NOTIFICATION
1237 TEST_F(TraceEventTestFixture
, EventWatchNotification
) {
1238 // Basic one occurrence.
1240 TraceLog::WatchEventCallback callback
=
1241 base::Bind(&TraceEventTestFixture::OnWatchEventMatched
,
1242 base::Unretained(this));
1243 TraceLog::GetInstance()->SetWatchEvent("cat", "event", callback
);
1244 TRACE_EVENT_INSTANT0("cat", "event", TRACE_EVENT_SCOPE_THREAD
);
1246 EXPECT_EQ(event_watch_notification_
, 1);
1248 // Auto-reset after end trace.
1250 TraceLog::GetInstance()->SetWatchEvent("cat", "event", callback
);
1253 TRACE_EVENT_INSTANT0("cat", "event", TRACE_EVENT_SCOPE_THREAD
);
1255 EXPECT_EQ(event_watch_notification_
, 0);
1257 // Multiple occurrence.
1259 int num_occurrences
= 5;
1260 TraceLog::GetInstance()->SetWatchEvent("cat", "event", callback
);
1261 for (int i
= 0; i
< num_occurrences
; ++i
)
1262 TRACE_EVENT_INSTANT0("cat", "event", TRACE_EVENT_SCOPE_THREAD
);
1264 EXPECT_EQ(event_watch_notification_
, num_occurrences
);
1268 TraceLog::GetInstance()->SetWatchEvent("cat", "event", callback
);
1269 TRACE_EVENT_INSTANT0("wrong_cat", "event", TRACE_EVENT_SCOPE_THREAD
);
1271 EXPECT_EQ(event_watch_notification_
, 0);
1275 TraceLog::GetInstance()->SetWatchEvent("cat", "event", callback
);
1276 TRACE_EVENT_INSTANT0("cat", "wrong_event", TRACE_EVENT_SCOPE_THREAD
);
1278 EXPECT_EQ(event_watch_notification_
, 0);
1282 TraceLog::GetInstance()->SetWatchEvent("cat", "event", callback
);
1283 TraceLog::GetInstance()->CancelWatchEvent();
1284 TRACE_EVENT_INSTANT0("cat", "event", TRACE_EVENT_SCOPE_THREAD
);
1286 EXPECT_EQ(event_watch_notification_
, 0);
1289 // Test ASYNC_BEGIN/END events
1290 TEST_F(TraceEventTestFixture
, AsyncBeginEndEvents
) {
1293 unsigned long long id
= 0xfeedbeeffeedbeefull
;
1294 TRACE_EVENT_ASYNC_BEGIN0("cat", "name1", id
);
1295 TRACE_EVENT_ASYNC_STEP_INTO0("cat", "name1", id
, "step1");
1296 TRACE_EVENT_ASYNC_END0("cat", "name1", id
);
1297 TRACE_EVENT_BEGIN0("cat", "name2");
1298 TRACE_EVENT_ASYNC_BEGIN0("cat", "name3", 0);
1299 TRACE_EVENT_ASYNC_STEP_PAST0("cat", "name3", 0, "step2");
1303 EXPECT_TRUE(FindNamePhase("name1", "S"));
1304 EXPECT_TRUE(FindNamePhase("name1", "T"));
1305 EXPECT_TRUE(FindNamePhase("name1", "F"));
1308 StringAppendF(&id_str
, "0x%llx", id
);
1310 EXPECT_TRUE(FindNamePhaseKeyValue("name1", "S", "id", id_str
.c_str()));
1311 EXPECT_TRUE(FindNamePhaseKeyValue("name1", "T", "id", id_str
.c_str()));
1312 EXPECT_TRUE(FindNamePhaseKeyValue("name1", "F", "id", id_str
.c_str()));
1313 EXPECT_TRUE(FindNamePhaseKeyValue("name3", "S", "id", "0x0"));
1314 EXPECT_TRUE(FindNamePhaseKeyValue("name3", "p", "id", "0x0"));
1316 // BEGIN events should not have id
1317 EXPECT_FALSE(FindNamePhaseKeyValue("name2", "B", "id", "0"));
1320 // Test ASYNC_BEGIN/END events
1321 TEST_F(TraceEventTestFixture
, AsyncBeginEndPointerMangling
) {
1324 TraceLog::GetInstance()->SetProcessID(100);
1326 TRACE_EVENT_ASYNC_BEGIN0("cat", "name1", ptr
);
1327 TRACE_EVENT_ASYNC_BEGIN0("cat", "name2", ptr
);
1330 TraceLog::GetInstance()->SetProcessID(200);
1332 TRACE_EVENT_ASYNC_END0("cat", "name1", ptr
);
1335 DictionaryValue
* async_begin
= FindNamePhase("name1", "S");
1336 DictionaryValue
* async_begin2
= FindNamePhase("name2", "S");
1337 DictionaryValue
* async_end
= FindNamePhase("name1", "F");
1338 EXPECT_TRUE(async_begin
);
1339 EXPECT_TRUE(async_begin2
);
1340 EXPECT_TRUE(async_end
);
1342 Value
* value
= NULL
;
1343 std::string async_begin_id_str
;
1344 std::string async_begin2_id_str
;
1345 std::string async_end_id_str
;
1346 ASSERT_TRUE(async_begin
->Get("id", &value
));
1347 ASSERT_TRUE(value
->GetAsString(&async_begin_id_str
));
1348 ASSERT_TRUE(async_begin2
->Get("id", &value
));
1349 ASSERT_TRUE(value
->GetAsString(&async_begin2_id_str
));
1350 ASSERT_TRUE(async_end
->Get("id", &value
));
1351 ASSERT_TRUE(value
->GetAsString(&async_end_id_str
));
1353 EXPECT_STREQ(async_begin_id_str
.c_str(), async_begin2_id_str
.c_str());
1354 EXPECT_STRNE(async_begin_id_str
.c_str(), async_end_id_str
.c_str());
1357 // Test that static strings are not copied.
1358 TEST_F(TraceEventTestFixture
, StaticStringVsString
) {
1359 TraceLog
* tracer
= TraceLog::GetInstance();
1360 // Make sure old events are flushed:
1361 EXPECT_EQ(0u, tracer
->GetStatus().event_count
);
1362 const unsigned char* category_group_enabled
=
1363 TRACE_EVENT_API_GET_CATEGORY_GROUP_ENABLED("cat");
1367 // Test that string arguments are copied.
1368 TraceEventHandle handle1
=
1369 trace_event_internal::AddTraceEvent(
1370 TRACE_EVENT_PHASE_INSTANT
, category_group_enabled
, "name1", 0, 0,
1371 "arg1", std::string("argval"), "arg2", std::string("argval"));
1372 // Test that static TRACE_STR_COPY string arguments are copied.
1373 TraceEventHandle handle2
=
1374 trace_event_internal::AddTraceEvent(
1375 TRACE_EVENT_PHASE_INSTANT
, category_group_enabled
, "name2", 0, 0,
1376 "arg1", TRACE_STR_COPY("argval"),
1377 "arg2", TRACE_STR_COPY("argval"));
1378 EXPECT_GT(tracer
->GetStatus().event_count
, 1u);
1379 const TraceEvent
* event1
= tracer
->GetEventByHandle(handle1
);
1380 const TraceEvent
* event2
= tracer
->GetEventByHandle(handle2
);
1381 ASSERT_TRUE(event1
);
1382 ASSERT_TRUE(event2
);
1383 EXPECT_STREQ("name1", event1
->name());
1384 EXPECT_STREQ("name2", event2
->name());
1385 EXPECT_TRUE(event1
->parameter_copy_storage() != NULL
);
1386 EXPECT_TRUE(event2
->parameter_copy_storage() != NULL
);
1387 EXPECT_GT(event1
->parameter_copy_storage()->size(), 0u);
1388 EXPECT_GT(event2
->parameter_copy_storage()->size(), 0u);
1394 // Test that static literal string arguments are not copied.
1395 TraceEventHandle handle1
=
1396 trace_event_internal::AddTraceEvent(
1397 TRACE_EVENT_PHASE_INSTANT
, category_group_enabled
, "name1", 0, 0,
1398 "arg1", "argval", "arg2", "argval");
1399 // Test that static TRACE_STR_COPY NULL string arguments are not copied.
1400 const char* str1
= NULL
;
1401 const char* str2
= NULL
;
1402 TraceEventHandle handle2
=
1403 trace_event_internal::AddTraceEvent(
1404 TRACE_EVENT_PHASE_INSTANT
, category_group_enabled
, "name2", 0, 0,
1405 "arg1", TRACE_STR_COPY(str1
),
1406 "arg2", TRACE_STR_COPY(str2
));
1407 EXPECT_GT(tracer
->GetStatus().event_count
, 1u);
1408 const TraceEvent
* event1
= tracer
->GetEventByHandle(handle1
);
1409 const TraceEvent
* event2
= tracer
->GetEventByHandle(handle2
);
1410 ASSERT_TRUE(event1
);
1411 ASSERT_TRUE(event2
);
1412 EXPECT_STREQ("name1", event1
->name());
1413 EXPECT_STREQ("name2", event2
->name());
1414 EXPECT_TRUE(event1
->parameter_copy_storage() == NULL
);
1415 EXPECT_TRUE(event2
->parameter_copy_storage() == NULL
);
1420 // Test that data sent from other threads is gathered
1421 TEST_F(TraceEventTestFixture
, DataCapturedOnThread
) {
1425 WaitableEvent
task_complete_event(false, false);
1428 thread
.task_runner()->PostTask(
1429 FROM_HERE
, base::Bind(&TraceWithAllMacroVariants
, &task_complete_event
));
1430 task_complete_event
.Wait();
1434 ValidateAllTraceMacrosCreatedData(trace_parsed_
);
1437 // Test that data sent from multiple threads is gathered
1438 TEST_F(TraceEventTestFixture
, DataCapturedManyThreads
) {
1441 const int num_threads
= 4;
1442 const int num_events
= 4000;
1443 Thread
* threads
[num_threads
];
1444 WaitableEvent
* task_complete_events
[num_threads
];
1445 for (int i
= 0; i
< num_threads
; i
++) {
1446 threads
[i
] = new Thread(StringPrintf("Thread %d", i
));
1447 task_complete_events
[i
] = new WaitableEvent(false, false);
1448 threads
[i
]->Start();
1449 threads
[i
]->task_runner()->PostTask(
1450 FROM_HERE
, base::Bind(&TraceManyInstantEvents
, i
, num_events
,
1451 task_complete_events
[i
]));
1454 for (int i
= 0; i
< num_threads
; i
++) {
1455 task_complete_events
[i
]->Wait();
1458 // Let half of the threads end before flush.
1459 for (int i
= 0; i
< num_threads
/ 2; i
++) {
1462 delete task_complete_events
[i
];
1465 EndTraceAndFlushInThreadWithMessageLoop();
1466 ValidateInstantEventPresentOnEveryThread(trace_parsed_
,
1467 num_threads
, num_events
);
1469 // Let the other half of the threads end after flush.
1470 for (int i
= num_threads
/ 2; i
< num_threads
; i
++) {
1473 delete task_complete_events
[i
];
1477 // Test that thread and process names show up in the trace
1478 TEST_F(TraceEventTestFixture
, ThreadNames
) {
1479 // Create threads before we enable tracing to make sure
1480 // that tracelog still captures them.
1481 const int kNumThreads
= 4;
1482 const int kNumEvents
= 10;
1483 Thread
* threads
[kNumThreads
];
1484 PlatformThreadId thread_ids
[kNumThreads
];
1485 for (int i
= 0; i
< kNumThreads
; i
++)
1486 threads
[i
] = new Thread(StringPrintf("Thread %d", i
));
1491 // Now run some trace code on these threads.
1492 WaitableEvent
* task_complete_events
[kNumThreads
];
1493 for (int i
= 0; i
< kNumThreads
; i
++) {
1494 task_complete_events
[i
] = new WaitableEvent(false, false);
1495 threads
[i
]->Start();
1496 thread_ids
[i
] = threads
[i
]->thread_id();
1497 threads
[i
]->task_runner()->PostTask(
1498 FROM_HERE
, base::Bind(&TraceManyInstantEvents
, i
, kNumEvents
,
1499 task_complete_events
[i
]));
1501 for (int i
= 0; i
< kNumThreads
; i
++) {
1502 task_complete_events
[i
]->Wait();
1505 // Shut things down.
1506 for (int i
= 0; i
< kNumThreads
; i
++) {
1509 delete task_complete_events
[i
];
1516 const DictionaryValue
* item
;
1518 // Make sure we get thread name metadata.
1519 // Note, the test suite may have created a ton of threads.
1520 // So, we'll have thread names for threads we didn't create.
1521 std::vector
<const DictionaryValue
*> items
=
1522 FindTraceEntries(trace_parsed_
, "thread_name");
1523 for (int i
= 0; i
< static_cast<int>(items
.size()); i
++) {
1526 EXPECT_TRUE(item
->GetInteger("tid", &tmp_int
));
1528 // See if this thread name is one of the threads we just created
1529 for (int j
= 0; j
< kNumThreads
; j
++) {
1530 if (static_cast<int>(thread_ids
[j
]) != tmp_int
)
1533 std::string expected_name
= StringPrintf("Thread %d", j
);
1534 EXPECT_TRUE(item
->GetString("ph", &tmp
) && tmp
== "M");
1535 EXPECT_TRUE(item
->GetInteger("pid", &tmp_int
) &&
1536 tmp_int
== static_cast<int>(base::GetCurrentProcId()));
1537 // If the thread name changes or the tid gets reused, the name will be
1538 // a comma-separated list of thread names, so look for a substring.
1539 EXPECT_TRUE(item
->GetString("args.name", &tmp
) &&
1540 tmp
.find(expected_name
) != std::string::npos
);
1545 TEST_F(TraceEventTestFixture
, ThreadNameChanges
) {
1548 PlatformThread::SetName("");
1549 TRACE_EVENT_INSTANT0("drink", "water", TRACE_EVENT_SCOPE_THREAD
);
1551 PlatformThread::SetName("cafe");
1552 TRACE_EVENT_INSTANT0("drink", "coffee", TRACE_EVENT_SCOPE_THREAD
);
1554 PlatformThread::SetName("shop");
1555 // No event here, so won't appear in combined name.
1557 PlatformThread::SetName("pub");
1558 TRACE_EVENT_INSTANT0("drink", "beer", TRACE_EVENT_SCOPE_THREAD
);
1559 TRACE_EVENT_INSTANT0("drink", "wine", TRACE_EVENT_SCOPE_THREAD
);
1561 PlatformThread::SetName(" bar");
1562 TRACE_EVENT_INSTANT0("drink", "whisky", TRACE_EVENT_SCOPE_THREAD
);
1566 std::vector
<const DictionaryValue
*> items
=
1567 FindTraceEntries(trace_parsed_
, "thread_name");
1568 EXPECT_EQ(1u, items
.size());
1569 ASSERT_GT(items
.size(), 0u);
1570 const DictionaryValue
* item
= items
[0];
1573 EXPECT_TRUE(item
->GetInteger("tid", &tid
));
1574 EXPECT_EQ(PlatformThread::CurrentId(), static_cast<PlatformThreadId
>(tid
));
1576 std::string expected_name
= "cafe,pub, bar";
1578 EXPECT_TRUE(item
->GetString("args.name", &tmp
));
1579 EXPECT_EQ(expected_name
, tmp
);
1582 // Test that the disabled trace categories are included/excluded from the
1583 // trace output correctly.
1584 TEST_F(TraceEventTestFixture
, DisabledCategories
) {
1586 TRACE_EVENT_INSTANT0(TRACE_DISABLED_BY_DEFAULT("cc"), "first",
1587 TRACE_EVENT_SCOPE_THREAD
);
1588 TRACE_EVENT_INSTANT0("included", "first", TRACE_EVENT_SCOPE_THREAD
);
1591 const DictionaryValue
* item
= NULL
;
1592 ListValue
& trace_parsed
= trace_parsed_
;
1593 EXPECT_NOT_FIND_("disabled-by-default-cc");
1594 EXPECT_FIND_("included");
1598 BeginSpecificTrace("disabled-by-default-cc");
1599 TRACE_EVENT_INSTANT0(TRACE_DISABLED_BY_DEFAULT("cc"), "second",
1600 TRACE_EVENT_SCOPE_THREAD
);
1601 TRACE_EVENT_INSTANT0("other_included", "second", TRACE_EVENT_SCOPE_THREAD
);
1605 const DictionaryValue
* item
= NULL
;
1606 ListValue
& trace_parsed
= trace_parsed_
;
1607 EXPECT_FIND_("disabled-by-default-cc");
1608 EXPECT_FIND_("other_included");
1613 BeginSpecificTrace("other_included");
1614 TRACE_EVENT_INSTANT0(TRACE_DISABLED_BY_DEFAULT("cc") ",other_included",
1615 "first", TRACE_EVENT_SCOPE_THREAD
);
1616 TRACE_EVENT_INSTANT0("other_included," TRACE_DISABLED_BY_DEFAULT("cc"),
1617 "second", TRACE_EVENT_SCOPE_THREAD
);
1621 const DictionaryValue
* item
= NULL
;
1622 ListValue
& trace_parsed
= trace_parsed_
;
1623 EXPECT_FIND_("disabled-by-default-cc,other_included");
1624 EXPECT_FIND_("other_included,disabled-by-default-cc");
1628 TEST_F(TraceEventTestFixture
, NormallyNoDeepCopy
) {
1629 // Test that the TRACE_EVENT macros do not deep-copy their string. If they
1630 // do so it may indicate a performance regression, but more-over it would
1631 // make the DEEP_COPY overloads redundant.
1632 std::string
name_string("event name");
1635 TRACE_EVENT_INSTANT0("category", name_string
.c_str(),
1636 TRACE_EVENT_SCOPE_THREAD
);
1638 // Modify the string in place (a wholesale reassignment may leave the old
1639 // string intact on the heap).
1640 name_string
[0] = '@';
1644 EXPECT_FALSE(FindTraceEntry(trace_parsed_
, "event name"));
1645 EXPECT_TRUE(FindTraceEntry(trace_parsed_
, name_string
.c_str()));
1648 TEST_F(TraceEventTestFixture
, DeepCopy
) {
1649 static const char kOriginalName1
[] = "name1";
1650 static const char kOriginalName2
[] = "name2";
1651 static const char kOriginalName3
[] = "name3";
1652 std::string
name1(kOriginalName1
);
1653 std::string
name2(kOriginalName2
);
1654 std::string
name3(kOriginalName3
);
1655 std::string
arg1("arg1");
1656 std::string
arg2("arg2");
1657 std::string
val1("val1");
1658 std::string
val2("val2");
1661 TRACE_EVENT_COPY_INSTANT0("category", name1
.c_str(),
1662 TRACE_EVENT_SCOPE_THREAD
);
1663 TRACE_EVENT_COPY_BEGIN1("category", name2
.c_str(),
1665 TRACE_EVENT_COPY_END2("category", name3
.c_str(),
1667 arg2
.c_str(), val2
);
1669 // As per NormallyNoDeepCopy, modify the strings in place.
1670 name1
[0] = name2
[0] = name3
[0] = arg1
[0] = arg2
[0] = val1
[0] = val2
[0] = '@';
1674 EXPECT_FALSE(FindTraceEntry(trace_parsed_
, name1
.c_str()));
1675 EXPECT_FALSE(FindTraceEntry(trace_parsed_
, name2
.c_str()));
1676 EXPECT_FALSE(FindTraceEntry(trace_parsed_
, name3
.c_str()));
1678 const DictionaryValue
* entry1
= FindTraceEntry(trace_parsed_
, kOriginalName1
);
1679 const DictionaryValue
* entry2
= FindTraceEntry(trace_parsed_
, kOriginalName2
);
1680 const DictionaryValue
* entry3
= FindTraceEntry(trace_parsed_
, kOriginalName3
);
1681 ASSERT_TRUE(entry1
);
1682 ASSERT_TRUE(entry2
);
1683 ASSERT_TRUE(entry3
);
1686 EXPECT_FALSE(entry2
->GetInteger("args.@rg1", &i
));
1687 EXPECT_TRUE(entry2
->GetInteger("args.arg1", &i
));
1691 EXPECT_TRUE(entry3
->GetString("args.arg1", &s
));
1692 EXPECT_EQ("val1", s
);
1693 EXPECT_TRUE(entry3
->GetString("args.arg2", &s
));
1694 EXPECT_EQ("val2", s
);
1697 // Test that TraceResultBuffer outputs the correct result whether it is added
1698 // in chunks or added all at once.
1699 TEST_F(TraceEventTestFixture
, TraceResultBuffer
) {
1702 trace_buffer_
.Start();
1703 trace_buffer_
.AddFragment("bla1");
1704 trace_buffer_
.AddFragment("bla2");
1705 trace_buffer_
.AddFragment("bla3,bla4");
1706 trace_buffer_
.Finish();
1707 EXPECT_STREQ(json_output_
.json_output
.c_str(), "[bla1,bla2,bla3,bla4]");
1711 trace_buffer_
.Start();
1712 trace_buffer_
.AddFragment("bla1,bla2,bla3,bla4");
1713 trace_buffer_
.Finish();
1714 EXPECT_STREQ(json_output_
.json_output
.c_str(), "[bla1,bla2,bla3,bla4]");
1717 // Test that trace_event parameters are not evaluated if the tracing
1718 // system is disabled.
1719 TEST_F(TraceEventTestFixture
, TracingIsLazy
) {
1723 TRACE_EVENT_INSTANT1("category", "test", TRACE_EVENT_SCOPE_THREAD
, "a", a
++);
1726 TraceLog::GetInstance()->SetDisabled();
1728 TRACE_EVENT_INSTANT1("category", "test", TRACE_EVENT_SCOPE_THREAD
, "a", a
++);
1734 TEST_F(TraceEventTestFixture
, TraceEnableDisable
) {
1735 TraceLog
* trace_log
= TraceLog::GetInstance();
1736 CategoryFilter
cf_inc_all("*");
1737 trace_log
->SetEnabled(cf_inc_all
,
1738 TraceLog::RECORDING_MODE
,
1740 EXPECT_TRUE(trace_log
->IsEnabled());
1741 trace_log
->SetDisabled();
1742 EXPECT_FALSE(trace_log
->IsEnabled());
1744 trace_log
->SetEnabled(cf_inc_all
,
1745 TraceLog::RECORDING_MODE
,
1747 EXPECT_TRUE(trace_log
->IsEnabled());
1748 const std::vector
<std::string
> empty
;
1749 trace_log
->SetEnabled(CategoryFilter(),
1750 TraceLog::RECORDING_MODE
,
1752 EXPECT_TRUE(trace_log
->IsEnabled());
1753 trace_log
->SetDisabled();
1754 EXPECT_FALSE(trace_log
->IsEnabled());
1755 trace_log
->SetDisabled();
1756 EXPECT_FALSE(trace_log
->IsEnabled());
1759 TEST_F(TraceEventTestFixture
, TraceCategoriesAfterNestedEnable
) {
1760 TraceLog
* trace_log
= TraceLog::GetInstance();
1761 trace_log
->SetEnabled(CategoryFilter("foo,bar"),
1762 TraceLog::RECORDING_MODE
,
1764 EXPECT_TRUE(*trace_log
->GetCategoryGroupEnabled("foo"));
1765 EXPECT_TRUE(*trace_log
->GetCategoryGroupEnabled("bar"));
1766 EXPECT_FALSE(*trace_log
->GetCategoryGroupEnabled("baz"));
1767 trace_log
->SetEnabled(CategoryFilter("foo2"),
1768 TraceLog::RECORDING_MODE
,
1770 EXPECT_TRUE(*trace_log
->GetCategoryGroupEnabled("foo2"));
1771 EXPECT_FALSE(*trace_log
->GetCategoryGroupEnabled("baz"));
1772 // The "" becomes the default catergory set when applied.
1773 trace_log
->SetEnabled(CategoryFilter(),
1774 TraceLog::RECORDING_MODE
,
1776 EXPECT_TRUE(*trace_log
->GetCategoryGroupEnabled("foo"));
1777 EXPECT_TRUE(*trace_log
->GetCategoryGroupEnabled("baz"));
1778 EXPECT_STREQ("-*Debug,-*Test",
1779 trace_log
->GetCurrentCategoryFilter().ToString().c_str());
1780 trace_log
->SetDisabled();
1781 trace_log
->SetDisabled();
1782 trace_log
->SetDisabled();
1783 EXPECT_FALSE(*trace_log
->GetCategoryGroupEnabled("foo"));
1784 EXPECT_FALSE(*trace_log
->GetCategoryGroupEnabled("baz"));
1786 trace_log
->SetEnabled(CategoryFilter("-foo,-bar"),
1787 TraceLog::RECORDING_MODE
,
1789 EXPECT_FALSE(*trace_log
->GetCategoryGroupEnabled("foo"));
1790 EXPECT_TRUE(*trace_log
->GetCategoryGroupEnabled("baz"));
1791 trace_log
->SetEnabled(CategoryFilter("moo"),
1792 TraceLog::RECORDING_MODE
,
1794 EXPECT_TRUE(*trace_log
->GetCategoryGroupEnabled("baz"));
1795 EXPECT_TRUE(*trace_log
->GetCategoryGroupEnabled("moo"));
1796 EXPECT_FALSE(*trace_log
->GetCategoryGroupEnabled("foo"));
1797 EXPECT_STREQ("-foo,-bar",
1798 trace_log
->GetCurrentCategoryFilter().ToString().c_str());
1799 trace_log
->SetDisabled();
1800 trace_log
->SetDisabled();
1802 // Make sure disabled categories aren't cleared if we set in the second.
1803 trace_log
->SetEnabled(CategoryFilter("disabled-by-default-cc,foo"),
1804 TraceLog::RECORDING_MODE
,
1806 EXPECT_FALSE(*trace_log
->GetCategoryGroupEnabled("bar"));
1807 trace_log
->SetEnabled(CategoryFilter("disabled-by-default-gpu"),
1808 TraceLog::RECORDING_MODE
,
1810 EXPECT_TRUE(*trace_log
->GetCategoryGroupEnabled("disabled-by-default-cc"));
1811 EXPECT_TRUE(*trace_log
->GetCategoryGroupEnabled("disabled-by-default-gpu"));
1812 EXPECT_TRUE(*trace_log
->GetCategoryGroupEnabled("bar"));
1813 EXPECT_STREQ("disabled-by-default-cc,disabled-by-default-gpu",
1814 trace_log
->GetCurrentCategoryFilter().ToString().c_str());
1815 trace_log
->SetDisabled();
1816 trace_log
->SetDisabled();
1819 TEST_F(TraceEventTestFixture
, TraceSampling
) {
1820 TraceOptions
trace_options(RECORD_UNTIL_FULL
);
1821 trace_options
.enable_sampling
= true;
1822 TraceLog::GetInstance()->SetEnabled(CategoryFilter("*"),
1823 TraceLog::RECORDING_MODE
,
1826 TRACE_EVENT_SET_SAMPLING_STATE_FOR_BUCKET(1, "cc", "Stuff");
1827 TraceLog::GetInstance()->WaitSamplingEventForTesting();
1828 TRACE_EVENT_SET_SAMPLING_STATE_FOR_BUCKET(1, "cc", "Things");
1829 TraceLog::GetInstance()->WaitSamplingEventForTesting();
1833 // Make sure we hit at least once.
1834 EXPECT_TRUE(FindNamePhase("Stuff", "P"));
1835 EXPECT_TRUE(FindNamePhase("Things", "P"));
1838 TEST_F(TraceEventTestFixture
, TraceSamplingScope
) {
1839 TraceOptions
trace_options(RECORD_UNTIL_FULL
);
1840 trace_options
.enable_sampling
= true;
1841 TraceLog::GetInstance()->SetEnabled(CategoryFilter("*"),
1842 TraceLog::RECORDING_MODE
,
1845 TRACE_EVENT_SCOPED_SAMPLING_STATE("AAA", "name");
1846 TraceLog::GetInstance()->WaitSamplingEventForTesting();
1848 EXPECT_STREQ(TRACE_EVENT_GET_SAMPLING_STATE(), "AAA");
1849 TRACE_EVENT_SCOPED_SAMPLING_STATE("BBB", "name");
1850 TraceLog::GetInstance()->WaitSamplingEventForTesting();
1851 EXPECT_STREQ(TRACE_EVENT_GET_SAMPLING_STATE(), "BBB");
1853 TraceLog::GetInstance()->WaitSamplingEventForTesting();
1855 EXPECT_STREQ(TRACE_EVENT_GET_SAMPLING_STATE(), "AAA");
1856 TRACE_EVENT_SCOPED_SAMPLING_STATE("CCC", "name");
1857 TraceLog::GetInstance()->WaitSamplingEventForTesting();
1858 EXPECT_STREQ(TRACE_EVENT_GET_SAMPLING_STATE(), "CCC");
1860 TraceLog::GetInstance()->WaitSamplingEventForTesting();
1862 EXPECT_STREQ(TRACE_EVENT_GET_SAMPLING_STATE(), "AAA");
1863 TRACE_EVENT_SET_SAMPLING_STATE("DDD", "name");
1864 TraceLog::GetInstance()->WaitSamplingEventForTesting();
1865 EXPECT_STREQ(TRACE_EVENT_GET_SAMPLING_STATE(), "DDD");
1867 TraceLog::GetInstance()->WaitSamplingEventForTesting();
1868 EXPECT_STREQ(TRACE_EVENT_GET_SAMPLING_STATE(), "DDD");
1873 TEST_F(TraceEventTestFixture
, TraceContinuousSampling
) {
1874 TraceOptions
trace_options(RECORD_UNTIL_FULL
);
1875 trace_options
.enable_sampling
= true;
1877 TraceLog::GetInstance()->SetEnabled(CategoryFilter("*"),
1878 TraceLog::MONITORING_MODE
,
1881 TRACE_EVENT_SET_SAMPLING_STATE_FOR_BUCKET(1, "category", "AAA");
1882 TraceLog::GetInstance()->WaitSamplingEventForTesting();
1883 TRACE_EVENT_SET_SAMPLING_STATE_FOR_BUCKET(1, "category", "BBB");
1884 TraceLog::GetInstance()->WaitSamplingEventForTesting();
1888 // Make sure we can get the profiled data.
1889 EXPECT_TRUE(FindNamePhase("AAA", "P"));
1890 EXPECT_TRUE(FindNamePhase("BBB", "P"));
1893 TraceLog::GetInstance()->WaitSamplingEventForTesting();
1895 TRACE_EVENT_SET_SAMPLING_STATE_FOR_BUCKET(1, "category", "CCC");
1896 TraceLog::GetInstance()->WaitSamplingEventForTesting();
1897 TRACE_EVENT_SET_SAMPLING_STATE_FOR_BUCKET(1, "category", "DDD");
1898 TraceLog::GetInstance()->WaitSamplingEventForTesting();
1902 // Make sure the profiled data is accumulated.
1903 EXPECT_TRUE(FindNamePhase("AAA", "P"));
1904 EXPECT_TRUE(FindNamePhase("BBB", "P"));
1905 EXPECT_TRUE(FindNamePhase("CCC", "P"));
1906 EXPECT_TRUE(FindNamePhase("DDD", "P"));
1910 TraceLog::GetInstance()->SetDisabled();
1912 // Make sure disabling the continuous sampling thread clears
1913 // the profiled data.
1914 EXPECT_FALSE(FindNamePhase("AAA", "P"));
1915 EXPECT_FALSE(FindNamePhase("BBB", "P"));
1916 EXPECT_FALSE(FindNamePhase("CCC", "P"));
1917 EXPECT_FALSE(FindNamePhase("DDD", "P"));
1922 class MyData
: public ConvertableToTraceFormat
{
1926 void AppendAsTraceFormat(std::string
* out
) const override
{
1927 out
->append("{\"foo\":1}");
1931 ~MyData() override
{}
1932 DISALLOW_COPY_AND_ASSIGN(MyData
);
1935 TEST_F(TraceEventTestFixture
, ConvertableTypes
) {
1936 TraceLog::GetInstance()->SetEnabled(
1937 CategoryFilter("*"),
1938 TraceLog::RECORDING_MODE
,
1941 scoped_refptr
<ConvertableToTraceFormat
> data(new MyData());
1942 scoped_refptr
<ConvertableToTraceFormat
> data1(new MyData());
1943 scoped_refptr
<ConvertableToTraceFormat
> data2(new MyData());
1944 TRACE_EVENT1("foo", "bar", "data", data
);
1945 TRACE_EVENT2("foo", "baz",
1950 scoped_refptr
<ConvertableToTraceFormat
> convertData1(new MyData());
1951 scoped_refptr
<ConvertableToTraceFormat
> convertData2(new MyData());
1969 DictionaryValue
* dict
= FindNamePhase("bar", "X");
1972 const DictionaryValue
* args_dict
= NULL
;
1973 dict
->GetDictionary("args", &args_dict
);
1974 ASSERT_TRUE(args_dict
);
1976 const Value
* value
= NULL
;
1977 const DictionaryValue
* convertable_dict
= NULL
;
1978 EXPECT_TRUE(args_dict
->Get("data", &value
));
1979 ASSERT_TRUE(value
->GetAsDictionary(&convertable_dict
));
1982 EXPECT_TRUE(convertable_dict
->GetInteger("foo", &foo_val
));
1983 EXPECT_EQ(1, foo_val
);
1986 dict
= FindNamePhase("baz", "X");
1990 dict
->GetDictionary("args", &args_dict
);
1991 ASSERT_TRUE(args_dict
);
1994 convertable_dict
= NULL
;
1995 EXPECT_TRUE(args_dict
->Get("data1", &value
));
1996 ASSERT_TRUE(value
->GetAsDictionary(&convertable_dict
));
1999 convertable_dict
= NULL
;
2000 EXPECT_TRUE(args_dict
->Get("data2", &value
));
2001 ASSERT_TRUE(value
->GetAsDictionary(&convertable_dict
));
2003 // Convertable with other types.
2004 dict
= FindNamePhase("string_first", "X");
2008 dict
->GetDictionary("args", &args_dict
);
2009 ASSERT_TRUE(args_dict
);
2011 std::string str_value
;
2012 EXPECT_TRUE(args_dict
->GetString("str", &str_value
));
2013 EXPECT_STREQ("string value 1", str_value
.c_str());
2016 convertable_dict
= NULL
;
2018 EXPECT_TRUE(args_dict
->Get("convert", &value
));
2019 ASSERT_TRUE(value
->GetAsDictionary(&convertable_dict
));
2020 EXPECT_TRUE(convertable_dict
->GetInteger("foo", &foo_val
));
2021 EXPECT_EQ(1, foo_val
);
2023 dict
= FindNamePhase("string_second", "X");
2027 dict
->GetDictionary("args", &args_dict
);
2028 ASSERT_TRUE(args_dict
);
2030 EXPECT_TRUE(args_dict
->GetString("str", &str_value
));
2031 EXPECT_STREQ("string value 2", str_value
.c_str());
2034 convertable_dict
= NULL
;
2036 EXPECT_TRUE(args_dict
->Get("convert", &value
));
2037 ASSERT_TRUE(value
->GetAsDictionary(&convertable_dict
));
2038 EXPECT_TRUE(convertable_dict
->GetInteger("foo", &foo_val
));
2039 EXPECT_EQ(1, foo_val
);
2042 TEST_F(TraceEventTestFixture
, PrimitiveArgs
) {
2043 TraceLog::GetInstance()->SetEnabled(
2044 CategoryFilter("*"),
2045 TraceLog::RECORDING_MODE
,
2048 TRACE_EVENT1("foo", "event1", "int_one", 1);
2049 TRACE_EVENT1("foo", "event2", "int_neg_ten", -10);
2050 TRACE_EVENT1("foo", "event3", "float_one", 1.0f
);
2051 TRACE_EVENT1("foo", "event4", "float_half", .5f
);
2052 TRACE_EVENT1("foo", "event5", "float_neghalf", -.5f
);
2053 TRACE_EVENT1("foo", "event6", "float_infinity",
2054 std::numeric_limits
<float>::infinity());
2055 TRACE_EVENT1("foo", "event6b", "float_neg_infinity",
2056 -std::numeric_limits
<float>::infinity());
2057 TRACE_EVENT1("foo", "event7", "double_nan",
2058 std::numeric_limits
<double>::quiet_NaN());
2060 TRACE_EVENT1("foo", "event8", "pointer_null", p
);
2061 p
= reinterpret_cast<void*>(0xbadf00d);
2062 TRACE_EVENT1("foo", "event9", "pointer_badf00d", p
);
2063 TRACE_EVENT1("foo", "event10", "bool_true", true);
2064 TRACE_EVENT1("foo", "event11", "bool_false", false);
2065 TRACE_EVENT1("foo", "event12", "time_null",
2067 TRACE_EVENT1("foo", "event13", "time_one",
2068 base::Time::FromInternalValue(1));
2069 TRACE_EVENT1("foo", "event14", "timeticks_null",
2071 TRACE_EVENT1("foo", "event15", "timeticks_one",
2072 base::TimeTicks::FromInternalValue(1));
2075 const DictionaryValue
* args_dict
= NULL
;
2076 DictionaryValue
* dict
= NULL
;
2077 const Value
* value
= NULL
;
2078 std::string str_value
;
2080 double double_value
;
2083 dict
= FindNamePhase("event1", "X");
2085 dict
->GetDictionary("args", &args_dict
);
2086 ASSERT_TRUE(args_dict
);
2087 EXPECT_TRUE(args_dict
->GetInteger("int_one", &int_value
));
2088 EXPECT_EQ(1, int_value
);
2090 dict
= FindNamePhase("event2", "X");
2092 dict
->GetDictionary("args", &args_dict
);
2093 ASSERT_TRUE(args_dict
);
2094 EXPECT_TRUE(args_dict
->GetInteger("int_neg_ten", &int_value
));
2095 EXPECT_EQ(-10, int_value
);
2097 // 1f must be serlized to JSON as "1.0" in order to be a double, not an int.
2098 dict
= FindNamePhase("event3", "X");
2100 dict
->GetDictionary("args", &args_dict
);
2101 ASSERT_TRUE(args_dict
);
2102 EXPECT_TRUE(args_dict
->Get("float_one", &value
));
2103 EXPECT_TRUE(value
->IsType(Value::TYPE_DOUBLE
));
2104 EXPECT_TRUE(value
->GetAsDouble(&double_value
));
2105 EXPECT_EQ(1, double_value
);
2107 // .5f must be serlized to JSON as "0.5".
2108 dict
= FindNamePhase("event4", "X");
2110 dict
->GetDictionary("args", &args_dict
);
2111 ASSERT_TRUE(args_dict
);
2112 EXPECT_TRUE(args_dict
->Get("float_half", &value
));
2113 EXPECT_TRUE(value
->IsType(Value::TYPE_DOUBLE
));
2114 EXPECT_TRUE(value
->GetAsDouble(&double_value
));
2115 EXPECT_EQ(0.5, double_value
);
2117 // -.5f must be serlized to JSON as "-0.5".
2118 dict
= FindNamePhase("event5", "X");
2120 dict
->GetDictionary("args", &args_dict
);
2121 ASSERT_TRUE(args_dict
);
2122 EXPECT_TRUE(args_dict
->Get("float_neghalf", &value
));
2123 EXPECT_TRUE(value
->IsType(Value::TYPE_DOUBLE
));
2124 EXPECT_TRUE(value
->GetAsDouble(&double_value
));
2125 EXPECT_EQ(-0.5, double_value
);
2127 // Infinity is serialized to JSON as a string.
2128 dict
= FindNamePhase("event6", "X");
2130 dict
->GetDictionary("args", &args_dict
);
2131 ASSERT_TRUE(args_dict
);
2132 EXPECT_TRUE(args_dict
->GetString("float_infinity", &str_value
));
2133 EXPECT_STREQ("Infinity", str_value
.c_str());
2134 dict
= FindNamePhase("event6b", "X");
2136 dict
->GetDictionary("args", &args_dict
);
2137 ASSERT_TRUE(args_dict
);
2138 EXPECT_TRUE(args_dict
->GetString("float_neg_infinity", &str_value
));
2139 EXPECT_STREQ("-Infinity", str_value
.c_str());
2141 // NaN is serialized to JSON as a string.
2142 dict
= FindNamePhase("event7", "X");
2144 dict
->GetDictionary("args", &args_dict
);
2145 ASSERT_TRUE(args_dict
);
2146 EXPECT_TRUE(args_dict
->GetString("double_nan", &str_value
));
2147 EXPECT_STREQ("NaN", str_value
.c_str());
2149 // NULL pointers should be serialized as "0x0".
2150 dict
= FindNamePhase("event8", "X");
2152 dict
->GetDictionary("args", &args_dict
);
2153 ASSERT_TRUE(args_dict
);
2154 EXPECT_TRUE(args_dict
->GetString("pointer_null", &str_value
));
2155 EXPECT_STREQ("0x0", str_value
.c_str());
2157 // Other pointers should be serlized as a hex string.
2158 dict
= FindNamePhase("event9", "X");
2160 dict
->GetDictionary("args", &args_dict
);
2161 ASSERT_TRUE(args_dict
);
2162 EXPECT_TRUE(args_dict
->GetString("pointer_badf00d", &str_value
));
2163 EXPECT_STREQ("0xbadf00d", str_value
.c_str());
2165 dict
= FindNamePhase("event10", "X");
2167 dict
->GetDictionary("args", &args_dict
);
2168 ASSERT_TRUE(args_dict
);
2169 EXPECT_TRUE(args_dict
->GetBoolean("bool_true", &bool_value
));
2170 EXPECT_TRUE(bool_value
);
2172 dict
= FindNamePhase("event11", "X");
2174 dict
->GetDictionary("args", &args_dict
);
2175 ASSERT_TRUE(args_dict
);
2176 EXPECT_TRUE(args_dict
->GetBoolean("bool_false", &bool_value
));
2177 EXPECT_FALSE(bool_value
);
2179 dict
= FindNamePhase("event12", "X");
2181 dict
->GetDictionary("args", &args_dict
);
2182 ASSERT_TRUE(args_dict
);
2183 EXPECT_TRUE(args_dict
->GetInteger("time_null", &int_value
));
2184 EXPECT_EQ(0, int_value
);
2186 dict
= FindNamePhase("event13", "X");
2188 dict
->GetDictionary("args", &args_dict
);
2189 ASSERT_TRUE(args_dict
);
2190 EXPECT_TRUE(args_dict
->GetInteger("time_one", &int_value
));
2191 EXPECT_EQ(1, int_value
);
2193 dict
= FindNamePhase("event14", "X");
2195 dict
->GetDictionary("args", &args_dict
);
2196 ASSERT_TRUE(args_dict
);
2197 EXPECT_TRUE(args_dict
->GetInteger("timeticks_null", &int_value
));
2198 EXPECT_EQ(0, int_value
);
2200 dict
= FindNamePhase("event15", "X");
2202 dict
->GetDictionary("args", &args_dict
);
2203 ASSERT_TRUE(args_dict
);
2204 EXPECT_TRUE(args_dict
->GetInteger("timeticks_one", &int_value
));
2205 EXPECT_EQ(1, int_value
);
2210 bool IsTraceEventArgsWhitelisted(const char* category_group_name
,
2211 const char* event_name
) {
2212 if (MatchPattern(category_group_name
, "toplevel") &&
2213 MatchPattern(event_name
, "*")) {
2222 TEST_F(TraceEventTestFixture
, ArgsWhitelisting
) {
2223 TraceLog::GetInstance()->SetArgumentFilterPredicate(
2224 base::Bind(&IsTraceEventArgsWhitelisted
));
2226 TraceOptions trace_options
;
2227 trace_options
.enable_argument_filter
= true;
2228 TraceLog::GetInstance()->SetEnabled(CategoryFilter("*"),
2229 TraceLog::RECORDING_MODE
, trace_options
);
2231 TRACE_EVENT1("toplevel", "event1", "int_one", 1);
2232 TRACE_EVENT1("whitewashed", "event2", "int_two", 1);
2235 const DictionaryValue
* args_dict
= NULL
;
2236 DictionaryValue
* dict
= NULL
;
2239 dict
= FindNamePhase("event1", "X");
2241 dict
->GetDictionary("args", &args_dict
);
2242 ASSERT_TRUE(args_dict
);
2243 EXPECT_TRUE(args_dict
->GetInteger("int_one", &int_value
));
2244 EXPECT_EQ(1, int_value
);
2246 dict
= FindNamePhase("event2", "X");
2248 dict
->GetDictionary("args", &args_dict
);
2249 ASSERT_TRUE(args_dict
);
2250 EXPECT_FALSE(args_dict
->GetInteger("int_two", &int_value
));
2251 EXPECT_TRUE(args_dict
->GetInteger("stripped", &int_value
));
2254 class TraceEventCallbackTest
: public TraceEventTestFixture
{
2256 void SetUp() override
{
2257 TraceEventTestFixture::SetUp();
2258 ASSERT_EQ(NULL
, s_instance
);
2261 void TearDown() override
{
2262 TraceLog::GetInstance()->SetDisabled();
2263 ASSERT_TRUE(s_instance
);
2265 TraceEventTestFixture::TearDown();
2269 // For TraceEventCallbackAndRecordingX tests.
2270 void VerifyCallbackAndRecordedEvents(size_t expected_callback_count
,
2271 size_t expected_recorded_count
) {
2273 EXPECT_EQ(expected_callback_count
, collected_events_names_
.size());
2274 for (size_t i
= 0; i
< collected_events_names_
.size(); ++i
) {
2275 EXPECT_EQ("callback", collected_events_categories_
[i
]);
2276 EXPECT_EQ("yes", collected_events_names_
[i
]);
2280 EXPECT_EQ(expected_recorded_count
, trace_parsed_
.GetSize());
2281 EXPECT_TRUE(FindTraceEntry(trace_parsed_
, "recording"));
2282 EXPECT_FALSE(FindTraceEntry(trace_parsed_
, "callback"));
2283 EXPECT_TRUE(FindTraceEntry(trace_parsed_
, "yes"));
2284 EXPECT_FALSE(FindTraceEntry(trace_parsed_
, "no"));
2287 void VerifyCollectedEvent(size_t i
,
2289 const std::string
& category
,
2290 const std::string
& name
) {
2291 EXPECT_EQ(phase
, collected_events_phases_
[i
]);
2292 EXPECT_EQ(category
, collected_events_categories_
[i
]);
2293 EXPECT_EQ(name
, collected_events_names_
[i
]);
2296 std::vector
<std::string
> collected_events_categories_
;
2297 std::vector
<std::string
> collected_events_names_
;
2298 std::vector
<unsigned char> collected_events_phases_
;
2299 std::vector
<TraceTicks
> collected_events_timestamps_
;
2301 static TraceEventCallbackTest
* s_instance
;
2302 static void Callback(TraceTicks timestamp
,
2304 const unsigned char* category_group_enabled
,
2306 unsigned long long id
,
2308 const char* const arg_names
[],
2309 const unsigned char arg_types
[],
2310 const unsigned long long arg_values
[],
2311 unsigned char flags
) {
2312 s_instance
->collected_events_phases_
.push_back(phase
);
2313 s_instance
->collected_events_categories_
.push_back(
2314 TraceLog::GetCategoryGroupName(category_group_enabled
));
2315 s_instance
->collected_events_names_
.push_back(name
);
2316 s_instance
->collected_events_timestamps_
.push_back(timestamp
);
2320 TraceEventCallbackTest
* TraceEventCallbackTest::s_instance
;
2322 TEST_F(TraceEventCallbackTest
, TraceEventCallback
) {
2323 TRACE_EVENT_INSTANT0("all", "before enable", TRACE_EVENT_SCOPE_THREAD
);
2324 TraceLog::GetInstance()->SetEventCallbackEnabled(
2325 CategoryFilter("*"), Callback
);
2326 TRACE_EVENT_INSTANT0("all", "event1", TRACE_EVENT_SCOPE_GLOBAL
);
2327 TRACE_EVENT_INSTANT0("all", "event2", TRACE_EVENT_SCOPE_GLOBAL
);
2329 TRACE_EVENT0("all", "duration");
2330 TRACE_EVENT_INSTANT0("all", "event3", TRACE_EVENT_SCOPE_GLOBAL
);
2332 TraceLog::GetInstance()->SetEventCallbackDisabled();
2333 TRACE_EVENT_INSTANT0("all", "after callback removed",
2334 TRACE_EVENT_SCOPE_GLOBAL
);
2335 ASSERT_EQ(5u, collected_events_names_
.size());
2336 EXPECT_EQ("event1", collected_events_names_
[0]);
2337 EXPECT_EQ(TRACE_EVENT_PHASE_INSTANT
, collected_events_phases_
[0]);
2338 EXPECT_EQ("event2", collected_events_names_
[1]);
2339 EXPECT_EQ(TRACE_EVENT_PHASE_INSTANT
, collected_events_phases_
[1]);
2340 EXPECT_EQ("duration", collected_events_names_
[2]);
2341 EXPECT_EQ(TRACE_EVENT_PHASE_BEGIN
, collected_events_phases_
[2]);
2342 EXPECT_EQ("event3", collected_events_names_
[3]);
2343 EXPECT_EQ(TRACE_EVENT_PHASE_INSTANT
, collected_events_phases_
[3]);
2344 EXPECT_EQ("duration", collected_events_names_
[4]);
2345 EXPECT_EQ(TRACE_EVENT_PHASE_END
, collected_events_phases_
[4]);
2346 for (size_t i
= 1; i
< collected_events_timestamps_
.size(); i
++) {
2347 EXPECT_LE(collected_events_timestamps_
[i
- 1],
2348 collected_events_timestamps_
[i
]);
2352 TEST_F(TraceEventCallbackTest
, TraceEventCallbackWhileFull
) {
2353 TraceLog::GetInstance()->SetEnabled(
2354 CategoryFilter("*"),
2355 TraceLog::RECORDING_MODE
,
2358 TRACE_EVENT_INSTANT0("all", "badger badger", TRACE_EVENT_SCOPE_GLOBAL
);
2359 } while (!TraceLog::GetInstance()->BufferIsFull());
2360 TraceLog::GetInstance()->SetEventCallbackEnabled(CategoryFilter("*"),
2362 TRACE_EVENT_INSTANT0("all", "a snake", TRACE_EVENT_SCOPE_GLOBAL
);
2363 TraceLog::GetInstance()->SetEventCallbackDisabled();
2364 ASSERT_EQ(1u, collected_events_names_
.size());
2365 EXPECT_EQ("a snake", collected_events_names_
[0]);
2368 // 1: Enable callback, enable recording, disable callback, disable recording.
2369 TEST_F(TraceEventCallbackTest
, TraceEventCallbackAndRecording1
) {
2370 TRACE_EVENT_INSTANT0("recording", "no", TRACE_EVENT_SCOPE_GLOBAL
);
2371 TRACE_EVENT_INSTANT0("callback", "no", TRACE_EVENT_SCOPE_GLOBAL
);
2372 TraceLog::GetInstance()->SetEventCallbackEnabled(CategoryFilter("callback"),
2374 TRACE_EVENT_INSTANT0("recording", "no", TRACE_EVENT_SCOPE_GLOBAL
);
2375 TRACE_EVENT_INSTANT0("callback", "yes", TRACE_EVENT_SCOPE_GLOBAL
);
2376 TraceLog::GetInstance()->SetEnabled(
2377 CategoryFilter("recording"),
2378 TraceLog::RECORDING_MODE
,
2380 TRACE_EVENT_INSTANT0("recording", "yes", TRACE_EVENT_SCOPE_GLOBAL
);
2381 TRACE_EVENT_INSTANT0("callback", "yes", TRACE_EVENT_SCOPE_GLOBAL
);
2382 TraceLog::GetInstance()->SetEventCallbackDisabled();
2383 TRACE_EVENT_INSTANT0("recording", "yes", TRACE_EVENT_SCOPE_GLOBAL
);
2384 TRACE_EVENT_INSTANT0("callback", "no", TRACE_EVENT_SCOPE_GLOBAL
);
2386 TRACE_EVENT_INSTANT0("recording", "no", TRACE_EVENT_SCOPE_GLOBAL
);
2387 TRACE_EVENT_INSTANT0("callback", "no", TRACE_EVENT_SCOPE_GLOBAL
);
2389 DropTracedMetadataRecords();
2390 VerifyCallbackAndRecordedEvents(2, 2);
2393 // 2: Enable callback, enable recording, disable recording, disable callback.
2394 TEST_F(TraceEventCallbackTest
, TraceEventCallbackAndRecording2
) {
2395 TRACE_EVENT_INSTANT0("recording", "no", TRACE_EVENT_SCOPE_GLOBAL
);
2396 TRACE_EVENT_INSTANT0("callback", "no", TRACE_EVENT_SCOPE_GLOBAL
);
2397 TraceLog::GetInstance()->SetEventCallbackEnabled(CategoryFilter("callback"),
2399 TRACE_EVENT_INSTANT0("recording", "no", TRACE_EVENT_SCOPE_GLOBAL
);
2400 TRACE_EVENT_INSTANT0("callback", "yes", TRACE_EVENT_SCOPE_GLOBAL
);
2401 TraceLog::GetInstance()->SetEnabled(
2402 CategoryFilter("recording"),
2403 TraceLog::RECORDING_MODE
,
2405 TRACE_EVENT_INSTANT0("recording", "yes", TRACE_EVENT_SCOPE_GLOBAL
);
2406 TRACE_EVENT_INSTANT0("callback", "yes", TRACE_EVENT_SCOPE_GLOBAL
);
2408 TRACE_EVENT_INSTANT0("recording", "no", TRACE_EVENT_SCOPE_GLOBAL
);
2409 TRACE_EVENT_INSTANT0("callback", "yes", TRACE_EVENT_SCOPE_GLOBAL
);
2410 TraceLog::GetInstance()->SetEventCallbackDisabled();
2411 TRACE_EVENT_INSTANT0("recording", "no", TRACE_EVENT_SCOPE_GLOBAL
);
2412 TRACE_EVENT_INSTANT0("callback", "no", TRACE_EVENT_SCOPE_GLOBAL
);
2414 DropTracedMetadataRecords();
2415 VerifyCallbackAndRecordedEvents(3, 1);
2418 // 3: Enable recording, enable callback, disable callback, disable recording.
2419 TEST_F(TraceEventCallbackTest
, TraceEventCallbackAndRecording3
) {
2420 TRACE_EVENT_INSTANT0("recording", "no", TRACE_EVENT_SCOPE_GLOBAL
);
2421 TRACE_EVENT_INSTANT0("callback", "no", TRACE_EVENT_SCOPE_GLOBAL
);
2422 TraceLog::GetInstance()->SetEnabled(
2423 CategoryFilter("recording"),
2424 TraceLog::RECORDING_MODE
,
2426 TRACE_EVENT_INSTANT0("recording", "yes", TRACE_EVENT_SCOPE_GLOBAL
);
2427 TRACE_EVENT_INSTANT0("callback", "no", TRACE_EVENT_SCOPE_GLOBAL
);
2428 TraceLog::GetInstance()->SetEventCallbackEnabled(CategoryFilter("callback"),
2430 TRACE_EVENT_INSTANT0("recording", "yes", TRACE_EVENT_SCOPE_GLOBAL
);
2431 TRACE_EVENT_INSTANT0("callback", "yes", TRACE_EVENT_SCOPE_GLOBAL
);
2432 TraceLog::GetInstance()->SetEventCallbackDisabled();
2433 TRACE_EVENT_INSTANT0("recording", "yes", TRACE_EVENT_SCOPE_GLOBAL
);
2434 TRACE_EVENT_INSTANT0("callback", "no", TRACE_EVENT_SCOPE_GLOBAL
);
2436 TRACE_EVENT_INSTANT0("recording", "no", TRACE_EVENT_SCOPE_GLOBAL
);
2437 TRACE_EVENT_INSTANT0("callback", "no", TRACE_EVENT_SCOPE_GLOBAL
);
2439 DropTracedMetadataRecords();
2440 VerifyCallbackAndRecordedEvents(1, 3);
2443 // 4: Enable recording, enable callback, disable recording, disable callback.
2444 TEST_F(TraceEventCallbackTest
, TraceEventCallbackAndRecording4
) {
2445 TRACE_EVENT_INSTANT0("recording", "no", TRACE_EVENT_SCOPE_GLOBAL
);
2446 TRACE_EVENT_INSTANT0("callback", "no", TRACE_EVENT_SCOPE_GLOBAL
);
2447 TraceLog::GetInstance()->SetEnabled(
2448 CategoryFilter("recording"),
2449 TraceLog::RECORDING_MODE
,
2451 TRACE_EVENT_INSTANT0("recording", "yes", TRACE_EVENT_SCOPE_GLOBAL
);
2452 TRACE_EVENT_INSTANT0("callback", "no", TRACE_EVENT_SCOPE_GLOBAL
);
2453 TraceLog::GetInstance()->SetEventCallbackEnabled(CategoryFilter("callback"),
2455 TRACE_EVENT_INSTANT0("recording", "yes", TRACE_EVENT_SCOPE_GLOBAL
);
2456 TRACE_EVENT_INSTANT0("callback", "yes", TRACE_EVENT_SCOPE_GLOBAL
);
2458 TRACE_EVENT_INSTANT0("recording", "no", TRACE_EVENT_SCOPE_GLOBAL
);
2459 TRACE_EVENT_INSTANT0("callback", "yes", TRACE_EVENT_SCOPE_GLOBAL
);
2460 TraceLog::GetInstance()->SetEventCallbackDisabled();
2461 TRACE_EVENT_INSTANT0("recording", "no", TRACE_EVENT_SCOPE_GLOBAL
);
2462 TRACE_EVENT_INSTANT0("callback", "no", TRACE_EVENT_SCOPE_GLOBAL
);
2464 DropTracedMetadataRecords();
2465 VerifyCallbackAndRecordedEvents(2, 2);
2468 TEST_F(TraceEventCallbackTest
, TraceEventCallbackAndRecordingDuration
) {
2469 TraceLog::GetInstance()->SetEventCallbackEnabled(CategoryFilter("*"),
2472 TRACE_EVENT0("callback", "duration1");
2473 TraceLog::GetInstance()->SetEnabled(
2474 CategoryFilter("*"),
2475 TraceLog::RECORDING_MODE
,
2477 TRACE_EVENT0("callback", "duration2");
2479 TRACE_EVENT0("callback", "duration3");
2481 TraceLog::GetInstance()->SetEventCallbackDisabled();
2483 ASSERT_EQ(6u, collected_events_names_
.size());
2484 VerifyCollectedEvent(0, TRACE_EVENT_PHASE_BEGIN
, "callback", "duration1");
2485 VerifyCollectedEvent(1, TRACE_EVENT_PHASE_BEGIN
, "callback", "duration2");
2486 VerifyCollectedEvent(2, TRACE_EVENT_PHASE_BEGIN
, "callback", "duration3");
2487 VerifyCollectedEvent(3, TRACE_EVENT_PHASE_END
, "callback", "duration3");
2488 VerifyCollectedEvent(4, TRACE_EVENT_PHASE_END
, "callback", "duration2");
2489 VerifyCollectedEvent(5, TRACE_EVENT_PHASE_END
, "callback", "duration1");
2492 TEST_F(TraceEventTestFixture
, TraceBufferVectorReportFull
) {
2493 TraceLog
* trace_log
= TraceLog::GetInstance();
2494 trace_log
->SetEnabled(CategoryFilter("*"),
2495 TraceLog::RECORDING_MODE
,
2497 trace_log
->logged_events_
.reset(
2498 trace_log
->CreateTraceBufferVectorOfSize(100));
2500 TRACE_EVENT_BEGIN_WITH_ID_TID_AND_TIMESTAMP0(
2501 "all", "with_timestamp", 0, 0, TraceTicks::Now().ToInternalValue());
2502 TRACE_EVENT_END_WITH_ID_TID_AND_TIMESTAMP0(
2503 "all", "with_timestamp", 0, 0, TraceTicks::Now().ToInternalValue());
2504 } while (!trace_log
->BufferIsFull());
2508 const DictionaryValue
* trace_full_metadata
= NULL
;
2510 trace_full_metadata
= FindTraceEntry(trace_parsed_
,
2511 "overflowed_at_ts");
2513 double buffer_limit_reached_timestamp
= 0;
2515 EXPECT_TRUE(trace_full_metadata
);
2516 EXPECT_TRUE(trace_full_metadata
->GetString("ph", &phase
));
2517 EXPECT_EQ("M", phase
);
2518 EXPECT_TRUE(trace_full_metadata
->GetDouble(
2519 "args.overflowed_at_ts", &buffer_limit_reached_timestamp
));
2521 static_cast<double>(
2522 trace_log
->buffer_limit_reached_timestamp_
.ToInternalValue()),
2523 buffer_limit_reached_timestamp
);
2525 // Test that buffer_limit_reached_timestamp's value is between the timestamp
2526 // of the last trace event and current time.
2527 DropTracedMetadataRecords();
2528 const DictionaryValue
* last_trace_event
= NULL
;
2529 double last_trace_event_timestamp
= 0;
2530 EXPECT_TRUE(trace_parsed_
.GetDictionary(trace_parsed_
.GetSize() - 1,
2531 &last_trace_event
));
2532 EXPECT_TRUE(last_trace_event
->GetDouble("ts", &last_trace_event_timestamp
));
2533 EXPECT_LE(last_trace_event_timestamp
, buffer_limit_reached_timestamp
);
2534 EXPECT_LE(buffer_limit_reached_timestamp
,
2535 trace_log
->OffsetNow().ToInternalValue());
2538 TEST_F(TraceEventTestFixture
, TraceBufferRingBufferGetReturnChunk
) {
2539 TraceLog::GetInstance()->SetEnabled(CategoryFilter("*"),
2540 TraceLog::RECORDING_MODE
,
2541 TraceOptions(RECORD_CONTINUOUSLY
));
2542 TraceBuffer
* buffer
= TraceLog::GetInstance()->trace_buffer();
2543 size_t capacity
= buffer
->Capacity();
2544 size_t num_chunks
= capacity
/ TraceBufferChunk::kTraceBufferChunkSize
;
2545 uint32 last_seq
= 0;
2547 EXPECT_EQ(0u, buffer
->Size());
2549 scoped_ptr
<TraceBufferChunk
*[]> chunks(new TraceBufferChunk
*[num_chunks
]);
2550 for (size_t i
= 0; i
< num_chunks
; ++i
) {
2551 chunks
[i
] = buffer
->GetChunk(&chunk_index
).release();
2552 EXPECT_TRUE(chunks
[i
]);
2553 EXPECT_EQ(i
, chunk_index
);
2554 EXPECT_GT(chunks
[i
]->seq(), last_seq
);
2555 EXPECT_EQ((i
+ 1) * TraceBufferChunk::kTraceBufferChunkSize
,
2557 last_seq
= chunks
[i
]->seq();
2560 // Ring buffer is never full.
2561 EXPECT_FALSE(buffer
->IsFull());
2563 // Return all chunks in original order.
2564 for (size_t i
= 0; i
< num_chunks
; ++i
)
2565 buffer
->ReturnChunk(i
, scoped_ptr
<TraceBufferChunk
>(chunks
[i
]));
2567 // Should recycle the chunks in the returned order.
2568 for (size_t i
= 0; i
< num_chunks
; ++i
) {
2569 chunks
[i
] = buffer
->GetChunk(&chunk_index
).release();
2570 EXPECT_TRUE(chunks
[i
]);
2571 EXPECT_EQ(i
, chunk_index
);
2572 EXPECT_GT(chunks
[i
]->seq(), last_seq
);
2573 last_seq
= chunks
[i
]->seq();
2576 // Return all chunks in reverse order.
2577 for (size_t i
= 0; i
< num_chunks
; ++i
) {
2578 buffer
->ReturnChunk(
2580 scoped_ptr
<TraceBufferChunk
>(chunks
[num_chunks
- i
- 1]));
2583 // Should recycle the chunks in the returned order.
2584 for (size_t i
= 0; i
< num_chunks
; ++i
) {
2585 chunks
[i
] = buffer
->GetChunk(&chunk_index
).release();
2586 EXPECT_TRUE(chunks
[i
]);
2587 EXPECT_EQ(num_chunks
- i
- 1, chunk_index
);
2588 EXPECT_GT(chunks
[i
]->seq(), last_seq
);
2589 last_seq
= chunks
[i
]->seq();
2592 for (size_t i
= 0; i
< num_chunks
; ++i
)
2593 buffer
->ReturnChunk(i
, scoped_ptr
<TraceBufferChunk
>(chunks
[i
]));
2595 TraceLog::GetInstance()->SetDisabled();
2598 TEST_F(TraceEventTestFixture
, TraceBufferRingBufferHalfIteration
) {
2599 TraceLog::GetInstance()->SetEnabled(CategoryFilter("*"),
2600 TraceLog::RECORDING_MODE
,
2601 TraceOptions(RECORD_CONTINUOUSLY
));
2602 TraceBuffer
* buffer
= TraceLog::GetInstance()->trace_buffer();
2603 size_t capacity
= buffer
->Capacity();
2604 size_t num_chunks
= capacity
/ TraceBufferChunk::kTraceBufferChunkSize
;
2606 EXPECT_EQ(0u, buffer
->Size());
2607 EXPECT_FALSE(buffer
->NextChunk());
2609 size_t half_chunks
= num_chunks
/ 2;
2610 scoped_ptr
<TraceBufferChunk
*[]> chunks(new TraceBufferChunk
*[half_chunks
]);
2612 for (size_t i
= 0; i
< half_chunks
; ++i
) {
2613 chunks
[i
] = buffer
->GetChunk(&chunk_index
).release();
2614 EXPECT_TRUE(chunks
[i
]);
2615 EXPECT_EQ(i
, chunk_index
);
2617 for (size_t i
= 0; i
< half_chunks
; ++i
)
2618 buffer
->ReturnChunk(i
, scoped_ptr
<TraceBufferChunk
>(chunks
[i
]));
2620 for (size_t i
= 0; i
< half_chunks
; ++i
)
2621 EXPECT_EQ(chunks
[i
], buffer
->NextChunk());
2622 EXPECT_FALSE(buffer
->NextChunk());
2623 TraceLog::GetInstance()->SetDisabled();
2626 TEST_F(TraceEventTestFixture
, TraceBufferRingBufferFullIteration
) {
2627 TraceLog::GetInstance()->SetEnabled(CategoryFilter("*"),
2628 TraceLog::RECORDING_MODE
,
2629 TraceOptions(RECORD_CONTINUOUSLY
));
2630 TraceBuffer
* buffer
= TraceLog::GetInstance()->trace_buffer();
2631 size_t capacity
= buffer
->Capacity();
2632 size_t num_chunks
= capacity
/ TraceBufferChunk::kTraceBufferChunkSize
;
2634 EXPECT_EQ(0u, buffer
->Size());
2635 EXPECT_FALSE(buffer
->NextChunk());
2637 scoped_ptr
<TraceBufferChunk
*[]> chunks(new TraceBufferChunk
*[num_chunks
]);
2639 for (size_t i
= 0; i
< num_chunks
; ++i
) {
2640 chunks
[i
] = buffer
->GetChunk(&chunk_index
).release();
2641 EXPECT_TRUE(chunks
[i
]);
2642 EXPECT_EQ(i
, chunk_index
);
2644 for (size_t i
= 0; i
< num_chunks
; ++i
)
2645 buffer
->ReturnChunk(i
, scoped_ptr
<TraceBufferChunk
>(chunks
[i
]));
2647 for (size_t i
= 0; i
< num_chunks
; ++i
)
2648 EXPECT_TRUE(chunks
[i
] == buffer
->NextChunk());
2649 EXPECT_FALSE(buffer
->NextChunk());
2650 TraceLog::GetInstance()->SetDisabled();
2653 TEST_F(TraceEventTestFixture
, TraceRecordAsMuchAsPossibleMode
) {
2654 TraceLog::GetInstance()->SetEnabled(CategoryFilter("*"),
2655 TraceLog::RECORDING_MODE
,
2656 TraceOptions(RECORD_AS_MUCH_AS_POSSIBLE
));
2657 TraceBuffer
* buffer
= TraceLog::GetInstance()->trace_buffer();
2658 EXPECT_EQ(512000000UL, buffer
->Capacity());
2659 TraceLog::GetInstance()->SetDisabled();
2662 void BlockUntilStopped(WaitableEvent
* task_start_event
,
2663 WaitableEvent
* task_stop_event
) {
2664 task_start_event
->Signal();
2665 task_stop_event
->Wait();
2668 TEST_F(TraceEventTestFixture
, SetCurrentThreadBlocksMessageLoopBeforeTracing
) {
2672 WaitableEvent
task_complete_event(false, false);
2674 thread
.task_runner()->PostTask(
2675 FROM_HERE
, Bind(&TraceLog::SetCurrentThreadBlocksMessageLoop
,
2676 Unretained(TraceLog::GetInstance())));
2678 thread
.task_runner()->PostTask(
2679 FROM_HERE
, Bind(&TraceWithAllMacroVariants
, &task_complete_event
));
2680 task_complete_event
.Wait();
2682 WaitableEvent
task_start_event(false, false);
2683 WaitableEvent
task_stop_event(false, false);
2684 thread
.task_runner()->PostTask(
2685 FROM_HERE
, Bind(&BlockUntilStopped
, &task_start_event
, &task_stop_event
));
2686 task_start_event
.Wait();
2689 ValidateAllTraceMacrosCreatedData(trace_parsed_
);
2691 task_stop_event
.Signal();
2695 TEST_F(TraceEventTestFixture
, ConvertTraceOptionsToInternalOptions
) {
2696 TraceLog
* trace_log
= TraceLog::GetInstance();
2697 TraceOptions
options(RECORD_UNTIL_FULL
);
2698 EXPECT_EQ(TraceLog::kInternalRecordUntilFull
,
2699 trace_log
->GetInternalOptionsFromTraceOptions(options
));
2701 options
.record_mode
= RECORD_CONTINUOUSLY
;
2702 EXPECT_EQ(TraceLog::kInternalRecordContinuously
,
2703 trace_log
->GetInternalOptionsFromTraceOptions(options
));
2705 options
.record_mode
= ECHO_TO_CONSOLE
;
2706 EXPECT_EQ(TraceLog::kInternalEchoToConsole
,
2707 trace_log
->GetInternalOptionsFromTraceOptions(options
));
2709 options
.enable_sampling
= true;
2711 options
.record_mode
= RECORD_UNTIL_FULL
;
2713 TraceLog::kInternalRecordUntilFull
| TraceLog::kInternalEnableSampling
,
2714 trace_log
->GetInternalOptionsFromTraceOptions(options
));
2716 options
.record_mode
= RECORD_CONTINUOUSLY
;
2718 TraceLog::kInternalRecordContinuously
| TraceLog::kInternalEnableSampling
,
2719 trace_log
->GetInternalOptionsFromTraceOptions(options
));
2721 options
.record_mode
= ECHO_TO_CONSOLE
;
2723 TraceLog::kInternalEchoToConsole
| TraceLog::kInternalEnableSampling
,
2724 trace_log
->GetInternalOptionsFromTraceOptions(options
));
2726 options
.enable_systrace
= true;
2728 TraceLog::kInternalEchoToConsole
| TraceLog::kInternalEnableSampling
,
2729 trace_log
->GetInternalOptionsFromTraceOptions(options
));
2732 void SetBlockingFlagAndBlockUntilStopped(WaitableEvent
* task_start_event
,
2733 WaitableEvent
* task_stop_event
) {
2734 TraceLog::GetInstance()->SetCurrentThreadBlocksMessageLoop();
2735 BlockUntilStopped(task_start_event
, task_stop_event
);
2738 TEST_F(TraceEventTestFixture
, SetCurrentThreadBlocksMessageLoopAfterTracing
) {
2742 WaitableEvent
task_complete_event(false, false);
2745 thread
.task_runner()->PostTask(
2746 FROM_HERE
, Bind(&TraceWithAllMacroVariants
, &task_complete_event
));
2747 task_complete_event
.Wait();
2749 WaitableEvent
task_start_event(false, false);
2750 WaitableEvent
task_stop_event(false, false);
2751 thread
.task_runner()->PostTask(
2752 FROM_HERE
, Bind(&SetBlockingFlagAndBlockUntilStopped
, &task_start_event
,
2754 task_start_event
.Wait();
2757 ValidateAllTraceMacrosCreatedData(trace_parsed_
);
2759 task_stop_event
.Signal();
2763 TEST_F(TraceEventTestFixture
, ThreadOnceBlocking
) {
2767 WaitableEvent
task_complete_event(false, false);
2770 thread
.task_runner()->PostTask(
2771 FROM_HERE
, Bind(&TraceWithAllMacroVariants
, &task_complete_event
));
2772 task_complete_event
.Wait();
2773 task_complete_event
.Reset();
2775 WaitableEvent
task_start_event(false, false);
2776 WaitableEvent
task_stop_event(false, false);
2777 thread
.task_runner()->PostTask(
2778 FROM_HERE
, Bind(&BlockUntilStopped
, &task_start_event
, &task_stop_event
));
2779 task_start_event
.Wait();
2781 // The thread will timeout in this flush.
2782 EndTraceAndFlushInThreadWithMessageLoop();
2785 // Let the thread's message loop continue to spin.
2786 task_stop_event
.Signal();
2788 // The following sequence ensures that the FlushCurrentThread task has been
2789 // executed in the thread before continuing.
2790 task_start_event
.Reset();
2791 task_stop_event
.Reset();
2792 thread
.task_runner()->PostTask(
2793 FROM_HERE
, Bind(&BlockUntilStopped
, &task_start_event
, &task_stop_event
));
2794 task_start_event
.Wait();
2795 task_stop_event
.Signal();
2798 // TraceLog should discover the generation mismatch and recover the thread
2799 // local buffer for the thread without any error.
2801 thread
.task_runner()->PostTask(
2802 FROM_HERE
, Bind(&TraceWithAllMacroVariants
, &task_complete_event
));
2803 task_complete_event
.Wait();
2804 task_complete_event
.Reset();
2805 EndTraceAndFlushInThreadWithMessageLoop();
2806 ValidateAllTraceMacrosCreatedData(trace_parsed_
);
2809 std::string
* g_log_buffer
= NULL
;
2810 bool MockLogMessageHandler(int, const char*, int, size_t,
2811 const std::string
& str
) {
2813 g_log_buffer
= new std::string();
2814 g_log_buffer
->append(str
);
2818 TEST_F(TraceEventTestFixture
, EchoToConsole
) {
2819 logging::LogMessageHandlerFunction old_log_message_handler
=
2820 logging::GetLogMessageHandler();
2821 logging::SetLogMessageHandler(MockLogMessageHandler
);
2823 TraceLog::GetInstance()->SetEnabled(
2824 CategoryFilter("*"),
2825 TraceLog::RECORDING_MODE
,
2826 TraceOptions(ECHO_TO_CONSOLE
));
2827 TRACE_EVENT_BEGIN0("a", "begin_end");
2829 TRACE_EVENT0("b", "duration");
2830 TRACE_EVENT0("b1", "duration1");
2832 TRACE_EVENT_INSTANT0("c", "instant", TRACE_EVENT_SCOPE_GLOBAL
);
2833 TRACE_EVENT_END0("a", "begin_end");
2835 EXPECT_NE(std::string::npos
, g_log_buffer
->find("begin_end[a]\x1b"));
2836 EXPECT_NE(std::string::npos
, g_log_buffer
->find("| duration[b]\x1b"));
2837 EXPECT_NE(std::string::npos
, g_log_buffer
->find("| | duration1[b1]\x1b"));
2838 EXPECT_NE(std::string::npos
, g_log_buffer
->find("| | duration1[b1] ("));
2839 EXPECT_NE(std::string::npos
, g_log_buffer
->find("| duration[b] ("));
2840 EXPECT_NE(std::string::npos
, g_log_buffer
->find("| instant[c]\x1b"));
2841 EXPECT_NE(std::string::npos
, g_log_buffer
->find("begin_end[a] ("));
2844 delete g_log_buffer
;
2845 logging::SetLogMessageHandler(old_log_message_handler
);
2846 g_log_buffer
= NULL
;
2849 bool LogMessageHandlerWithTraceEvent(int, const char*, int, size_t,
2850 const std::string
&) {
2851 TRACE_EVENT0("log", "trace_event");
2855 TEST_F(TraceEventTestFixture
, EchoToConsoleTraceEventRecursion
) {
2856 logging::LogMessageHandlerFunction old_log_message_handler
=
2857 logging::GetLogMessageHandler();
2858 logging::SetLogMessageHandler(LogMessageHandlerWithTraceEvent
);
2860 TraceLog::GetInstance()->SetEnabled(
2861 CategoryFilter("*"),
2862 TraceLog::RECORDING_MODE
,
2863 TraceOptions(ECHO_TO_CONSOLE
));
2865 // This should not cause deadlock or infinite recursion.
2866 TRACE_EVENT0("b", "duration");
2870 logging::SetLogMessageHandler(old_log_message_handler
);
2873 TEST_F(TraceEventTestFixture
, TimeOffset
) {
2875 // Let TraceLog timer start from 0.
2876 TimeDelta time_offset
= TraceTicks::Now() - TraceTicks();
2877 TraceLog::GetInstance()->SetTimeOffset(time_offset
);
2880 TRACE_EVENT0("all", "duration1");
2881 TRACE_EVENT0("all", "duration2");
2883 TRACE_EVENT_BEGIN_WITH_ID_TID_AND_TIMESTAMP0(
2884 "all", "with_timestamp", 0, 0, TraceTicks::Now().ToInternalValue());
2885 TRACE_EVENT_END_WITH_ID_TID_AND_TIMESTAMP0(
2886 "all", "with_timestamp", 0, 0, TraceTicks::Now().ToInternalValue());
2889 DropTracedMetadataRecords();
2891 double end_time
= static_cast<double>(
2892 (TraceTicks::Now() - time_offset
).ToInternalValue());
2893 double last_timestamp
= 0;
2894 for (size_t i
= 0; i
< trace_parsed_
.GetSize(); ++i
) {
2895 const DictionaryValue
* item
;
2896 EXPECT_TRUE(trace_parsed_
.GetDictionary(i
, &item
));
2898 EXPECT_TRUE(item
->GetDouble("ts", ×tamp
));
2899 EXPECT_GE(timestamp
, last_timestamp
);
2900 EXPECT_LE(timestamp
, end_time
);
2901 last_timestamp
= timestamp
;
2905 TEST_F(TraceEventTestFixture
, ConfigureSyntheticDelays
) {
2906 BeginSpecificTrace("DELAY(test.Delay;0.05)");
2908 base::TimeTicks start
= base::TimeTicks::Now();
2910 TRACE_EVENT_SYNTHETIC_DELAY("test.Delay");
2912 base::TimeDelta duration
= base::TimeTicks::Now() - start
;
2913 EXPECT_GE(duration
.InMilliseconds(), 50);
2918 TEST_F(TraceEventTestFixture
, BadSyntheticDelayConfigurations
) {
2919 const char* const configs
[] = {
2924 "DELAY(test.Delay)",
2925 "DELAY(test.Delay;)"
2927 for (size_t i
= 0; i
< arraysize(configs
); i
++) {
2928 BeginSpecificTrace(configs
[i
]);
2930 CategoryFilter filter
= TraceLog::GetInstance()->GetCurrentCategoryFilter();
2931 EXPECT_EQ(0u, filter
.GetSyntheticDelayValues().size());
2935 TEST_F(TraceEventTestFixture
, SyntheticDelayConfigurationMerging
) {
2936 CategoryFilter
filter1("DELAY(test.Delay1;16)");
2937 CategoryFilter
filter2("DELAY(test.Delay2;32)");
2938 filter1
.Merge(filter2
);
2939 EXPECT_EQ(2u, filter1
.GetSyntheticDelayValues().size());
2942 TEST_F(TraceEventTestFixture
, SyntheticDelayConfigurationToString
) {
2943 const char config
[] = "DELAY(test.Delay;16;oneshot)";
2944 CategoryFilter
filter(config
);
2945 EXPECT_EQ(config
, filter
.ToString());
2948 } // namespace trace_event