Merge Chromium + Blink git repositories
[chromium-blink-merge.git] / chrome / test / logging / win / test_log_collector.cc
bloba218d602b32cbd5594cc7c3d9c5325f672d9419b
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.
5 #include "chrome/test/logging/win/test_log_collector.h"
7 #include <windows.h>
9 #include <algorithm>
10 #include <ios>
12 #include "base/command_line.h"
13 #include "base/compiler_specific.h"
14 #include "base/files/file_path.h"
15 #include "base/files/file_util.h"
16 #include "base/files/scoped_temp_dir.h"
17 #include "base/lazy_instance.h"
18 #include "base/logging.h"
19 #include "base/memory/scoped_ptr.h"
20 #include "base/strings/stringprintf.h"
21 #include "chrome/test/base/test_switches.h"
22 #include "chrome/test/logging/win/file_logger.h"
23 #include "chrome/test/logging/win/log_file_printer.h"
24 #include "testing/gtest/include/gtest/gtest.h"
26 namespace logging_win {
28 namespace {
30 const char kTraceLogExtension[] = ".etl";
32 class TestLogCollector {
33 public:
34 TestLogCollector();
35 ~TestLogCollector();
37 void Initialize(testing::UnitTest* unit_test);
39 void SetUp();
40 void StartSessionForTest(const testing::TestInfo& test_info);
41 bool LogTestPartResult(const testing::TestPartResult& test_part_result);
42 void ProcessSessionForTest(const testing::TestInfo& test_info);
43 void TearDown();
45 private:
46 // An EventListener that generally delegates to a given default result
47 // printer with a few exceptions; see individual method comments for details.
48 class EventListener : public testing::TestEventListener {
49 public:
50 // Ownership of |default_result_printer| is taken by the new instance.
51 EventListener(TestLogCollector* test_log_collector,
52 testing::TestEventListener* default_result_printer);
53 ~EventListener() override;
55 // Sets up the log collector.
56 void OnTestProgramStart(const testing::UnitTest& unit_test) override {
57 test_log_collector_->SetUp();
58 default_result_printer_->OnTestProgramStart(unit_test);
61 void OnTestIterationStart(const testing::UnitTest& unit_test,
62 int iteration) override {
63 default_result_printer_->OnTestIterationStart(unit_test, iteration);
66 void OnEnvironmentsSetUpStart(const testing::UnitTest& unit_test) override {
67 default_result_printer_->OnEnvironmentsSetUpStart(unit_test);
70 void OnEnvironmentsSetUpEnd(const testing::UnitTest& unit_test) override {
71 default_result_printer_->OnEnvironmentsSetUpEnd(unit_test);
74 void OnTestCaseStart(const testing::TestCase& test_case) override {
75 default_result_printer_->OnTestCaseStart(test_case);
78 // Calls back to the collector to start collecting logs for this test.
79 void OnTestStart(const testing::TestInfo& test_info) override {
80 default_result_printer_->OnTestStart(test_info);
81 test_log_collector_->StartSessionForTest(test_info);
84 // Calls back to the collector with the partial result. If the collector
85 // does not handle it, it is given to the default result printer.
86 void OnTestPartResult(
87 const testing::TestPartResult& test_part_result) override {
88 if (!test_log_collector_->LogTestPartResult(test_part_result))
89 default_result_printer_->OnTestPartResult(test_part_result);
92 // Calls back to the collector to handle the collected log for the test that
93 // has just ended.
94 void OnTestEnd(const testing::TestInfo& test_info) override {
95 test_log_collector_->ProcessSessionForTest(test_info);
96 default_result_printer_->OnTestEnd(test_info);
99 void OnTestCaseEnd(const testing::TestCase& test_case) override {
100 default_result_printer_->OnTestCaseEnd(test_case);
103 void OnEnvironmentsTearDownStart(
104 const testing::UnitTest& unit_test) override {
105 default_result_printer_->OnEnvironmentsTearDownStart(unit_test);
108 void OnEnvironmentsTearDownEnd(
109 const testing::UnitTest& unit_test) override {
110 default_result_printer_->OnEnvironmentsTearDownEnd(unit_test);
113 void OnTestIterationEnd(const testing::UnitTest& unit_test,
114 int iteration) override {
115 default_result_printer_->OnTestIterationEnd(unit_test, iteration);
118 // Tears down the log collector.
119 void OnTestProgramEnd(const testing::UnitTest& unit_test) override {
120 default_result_printer_->OnTestProgramEnd(unit_test);
121 test_log_collector_->TearDown();
124 private:
125 TestLogCollector* test_log_collector_;
126 scoped_ptr<testing::TestEventListener> default_result_printer_;
128 DISALLOW_COPY_AND_ASSIGN(EventListener);
131 // The Google Test unit test into which the collector has been installed.
132 testing::UnitTest* unit_test_;
134 // A temporary directory into which a log file is placed for the duration of
135 // each test. Created/destroyed at collector SetUp and TearDown.
136 base::ScopedTempDir log_temp_dir_;
138 // The test logger. Initialized/Unintitialized at collector SetUp and
139 // TearDown.
140 scoped_ptr<FileLogger> file_logger_;
142 // The current log file. Valid only during a test.
143 base::FilePath log_file_;
145 // True if --also-emit-success-logs was specified on the command line.
146 bool also_emit_success_logs_;
148 DISALLOW_COPY_AND_ASSIGN(TestLogCollector);
151 base::LazyInstance<TestLogCollector> g_test_log_collector =
152 LAZY_INSTANCE_INITIALIZER;
154 // TestLogCollector::EventListener implementation
156 TestLogCollector::EventListener::EventListener(
157 TestLogCollector* test_log_collector,
158 testing::TestEventListener* default_result_printer)
159 : test_log_collector_(test_log_collector),
160 default_result_printer_(default_result_printer) {
163 TestLogCollector::EventListener::~EventListener() {
166 // TestLogCollector implementation
168 TestLogCollector::TestLogCollector()
169 : unit_test_(NULL), also_emit_success_logs_(false) {
172 TestLogCollector::~TestLogCollector() {
175 void TestLogCollector::Initialize(testing::UnitTest* unit_test) {
176 if (unit_test_ != NULL) {
177 CHECK_EQ(unit_test, unit_test_)
178 << "Cannot install the test log collector in multiple unit tests.";
179 return; // Already initialized.
182 // Remove the default result printer and install the collector's listener
183 // which delegates to the printer. If the default result printer has already
184 // been released, log an error and move on.
185 testing::TestEventListeners& listeners = unit_test->listeners();
186 testing::TestEventListener* default_result_printer =
187 listeners.default_result_printer();
188 if (default_result_printer == NULL) {
189 LOG(ERROR) << "Failed to initialize the test log collector on account of "
190 "another component having released the default result "
191 "printer.";
192 } else {
193 // Ownership of |default_release_printer| is passed to the new listener, and
194 // ownership of the new listener is passed to the unit test.
195 listeners.Append(
196 new EventListener(this, listeners.Release(default_result_printer)));
198 also_emit_success_logs_ = base::CommandLine::ForCurrentProcess()->HasSwitch(
199 switches::kAlsoEmitSuccessLogs);
201 unit_test_ = unit_test;
205 // Invoked by the listener at test program start to create the temporary log
206 // directory and initialize the logger.
207 void TestLogCollector::SetUp() {
208 if (!log_temp_dir_.CreateUniqueTempDir()) {
209 LOG(ERROR) << "Failed to create temporary directory to hold log files.";
210 } else {
211 file_logger_.reset(new FileLogger());
212 file_logger_->Initialize();
216 // Invoked by the listener at test start to begin collecting logs in a file.
217 void TestLogCollector::StartSessionForTest(const testing::TestInfo& test_info) {
218 if (log_temp_dir_.IsValid()) {
219 std::string log_file_name(test_info.name());
220 std::replace(log_file_name.begin(), log_file_name.end(), '/', '_');
221 log_file_name.append(kTraceLogExtension);
222 log_file_ = log_temp_dir_.path().AppendASCII(log_file_name);
224 file_logger_->StartLogging(log_file_);
228 // Invoked by the listener when a test result is produced to log an event for
229 // the result.
230 bool TestLogCollector::LogTestPartResult(
231 const testing::TestPartResult& test_part_result) {
232 // Can't handle the event if no trace session.
233 if (!file_logger_.get() || !file_logger_->is_logging())
234 return false;
236 if (test_part_result.type() != testing::TestPartResult::kSuccess) {
237 // Approximate Google Test's message formatting.
238 LOG(ERROR)
239 << base::StringPrintf("%s(%d): error: %s", test_part_result.file_name(),
240 test_part_result.line_number(),
241 test_part_result.message());
243 return true;
246 // Invoked by the listener at test end to dump the collected log in case of
247 // error.
248 void TestLogCollector::ProcessSessionForTest(
249 const testing::TestInfo& test_info) {
250 if (file_logger_.get() != NULL && file_logger_->is_logging()) {
251 file_logger_->StopLogging();
253 if (also_emit_success_logs_ || test_info.result()->Failed()) {
254 std::cerr << "----- log messages for "
255 << test_info.test_case_name() << "." << test_info.name()
256 << " above this line are repeated below -----" << std::endl;
257 // Dump the log to stderr.
258 logging_win::PrintLogFile(log_file_, &std::cerr);
259 std::cerr.flush();
262 if (!base::DeleteFile(log_file_, false))
263 LOG(ERROR) << "Failed to delete log file " << log_file_.value();
266 log_file_.clear();
269 // Invoked by the listener at test program end to shut down the logger and
270 // delete the temporary log directory.
271 void TestLogCollector::TearDown() {
272 file_logger_.reset();
274 ignore_result(log_temp_dir_.Delete());
277 } // namespace
279 void InstallTestLogCollector(testing::UnitTest* unit_test) {
280 // Must be called before running any tests.
281 DCHECK(unit_test);
282 DCHECK(!unit_test->current_test_case());
284 g_test_log_collector.Get().Initialize(unit_test);
287 } // namespace logging_win