summaryrefslogtreecommitdiffstats
path: root/chrome/test/logging/win/test_log_collector.cc
blob: a218d602b32cbd5594cc7c3d9c5325f672d9419b (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
// Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "chrome/test/logging/win/test_log_collector.h"

#include <windows.h>

#include <algorithm>
#include <ios>

#include "base/command_line.h"
#include "base/compiler_specific.h"
#include "base/files/file_path.h"
#include "base/files/file_util.h"
#include "base/files/scoped_temp_dir.h"
#include "base/lazy_instance.h"
#include "base/logging.h"
#include "base/memory/scoped_ptr.h"
#include "base/strings/stringprintf.h"
#include "chrome/test/base/test_switches.h"
#include "chrome/test/logging/win/file_logger.h"
#include "chrome/test/logging/win/log_file_printer.h"
#include "testing/gtest/include/gtest/gtest.h"

namespace logging_win {

namespace {

const char kTraceLogExtension[] = ".etl";

class TestLogCollector {
 public:
  TestLogCollector();
  ~TestLogCollector();

  void Initialize(testing::UnitTest* unit_test);

  void SetUp();
  void StartSessionForTest(const testing::TestInfo& test_info);
  bool LogTestPartResult(const testing::TestPartResult& test_part_result);
  void ProcessSessionForTest(const testing::TestInfo& test_info);
  void TearDown();

 private:
  // An EventListener that generally delegates to a given default result
  // printer with a few exceptions; see individual method comments for details.
  class EventListener : public testing::TestEventListener {
   public:
    // Ownership of |default_result_printer| is taken by the new instance.
    EventListener(TestLogCollector* test_log_collector,
                  testing::TestEventListener* default_result_printer);
    ~EventListener() override;

    // Sets up the log collector.
    void OnTestProgramStart(const testing::UnitTest& unit_test) override {
      test_log_collector_->SetUp();
      default_result_printer_->OnTestProgramStart(unit_test);
    }

    void OnTestIterationStart(const testing::UnitTest& unit_test,
                              int iteration) override {
      default_result_printer_->OnTestIterationStart(unit_test, iteration);
    }

    void OnEnvironmentsSetUpStart(const testing::UnitTest& unit_test) override {
      default_result_printer_->OnEnvironmentsSetUpStart(unit_test);
    }

    void OnEnvironmentsSetUpEnd(const testing::UnitTest& unit_test) override {
      default_result_printer_->OnEnvironmentsSetUpEnd(unit_test);
    }

    void OnTestCaseStart(const testing::TestCase& test_case) override {
      default_result_printer_->OnTestCaseStart(test_case);
    }

    // Calls back to the collector to start collecting logs for this test.
    void OnTestStart(const testing::TestInfo& test_info) override {
      default_result_printer_->OnTestStart(test_info);
      test_log_collector_->StartSessionForTest(test_info);
    }

    // Calls back to the collector with the partial result.  If the collector
    // does not handle it, it is given to the default result printer.
    void OnTestPartResult(
        const testing::TestPartResult& test_part_result) override {
      if (!test_log_collector_->LogTestPartResult(test_part_result))
        default_result_printer_->OnTestPartResult(test_part_result);
    }

    // Calls back to the collector to handle the collected log for the test that
    // has just ended.
    void OnTestEnd(const testing::TestInfo& test_info) override {
      test_log_collector_->ProcessSessionForTest(test_info);
      default_result_printer_->OnTestEnd(test_info);
    }

    void OnTestCaseEnd(const testing::TestCase& test_case) override {
      default_result_printer_->OnTestCaseEnd(test_case);
    }

    void OnEnvironmentsTearDownStart(
        const testing::UnitTest& unit_test) override {
      default_result_printer_->OnEnvironmentsTearDownStart(unit_test);
    }

    void OnEnvironmentsTearDownEnd(
        const testing::UnitTest& unit_test) override {
      default_result_printer_->OnEnvironmentsTearDownEnd(unit_test);
    }

    void OnTestIterationEnd(const testing::UnitTest& unit_test,
                            int iteration) override {
      default_result_printer_->OnTestIterationEnd(unit_test, iteration);
    }

    // Tears down the log collector.
    void OnTestProgramEnd(const testing::UnitTest& unit_test) override {
      default_result_printer_->OnTestProgramEnd(unit_test);
      test_log_collector_->TearDown();
    }

   private:
    TestLogCollector* test_log_collector_;
    scoped_ptr<testing::TestEventListener> default_result_printer_;

    DISALLOW_COPY_AND_ASSIGN(EventListener);
  };

  // The Google Test unit test into which the collector has been installed.
  testing::UnitTest* unit_test_;

  // A temporary directory into which a log file is placed for the duration of
  // each test.  Created/destroyed at collector SetUp and TearDown.
  base::ScopedTempDir log_temp_dir_;

  // The test logger.  Initialized/Unintitialized at collector SetUp and
  // TearDown.
  scoped_ptr<FileLogger> file_logger_;

  // The current log file.  Valid only during a test.
  base::FilePath log_file_;

  // True if --also-emit-success-logs was specified on the command line.
  bool also_emit_success_logs_;

  DISALLOW_COPY_AND_ASSIGN(TestLogCollector);
};

base::LazyInstance<TestLogCollector> g_test_log_collector =
    LAZY_INSTANCE_INITIALIZER;

// TestLogCollector::EventListener implementation

TestLogCollector::EventListener::EventListener(
    TestLogCollector* test_log_collector,
    testing::TestEventListener* default_result_printer)
    : test_log_collector_(test_log_collector),
      default_result_printer_(default_result_printer) {
}

TestLogCollector::EventListener::~EventListener() {
}

// TestLogCollector implementation

TestLogCollector::TestLogCollector()
    : unit_test_(NULL), also_emit_success_logs_(false) {
}

TestLogCollector::~TestLogCollector() {
}

void TestLogCollector::Initialize(testing::UnitTest* unit_test) {
  if (unit_test_ != NULL) {
    CHECK_EQ(unit_test, unit_test_)
        << "Cannot install the test log collector in multiple unit tests.";
    return;  // Already initialized.
  }

  // Remove the default result printer and install the collector's listener
  // which delegates to the printer.  If the default result printer has already
  // been released, log an error and move on.
  testing::TestEventListeners& listeners = unit_test->listeners();
  testing::TestEventListener* default_result_printer =
      listeners.default_result_printer();
  if (default_result_printer == NULL) {
    LOG(ERROR) << "Failed to initialize the test log collector on account of "
                  "another component having released the default result "
                  "printer.";
  } else {
    // Ownership of |default_release_printer| is passed to the new listener, and
    // ownership of the new listener is passed to the unit test.
    listeners.Append(
        new EventListener(this, listeners.Release(default_result_printer)));

    also_emit_success_logs_ = base::CommandLine::ForCurrentProcess()->HasSwitch(
        switches::kAlsoEmitSuccessLogs);

    unit_test_ = unit_test;
  }
}

// Invoked by the listener at test program start to create the temporary log
// directory and initialize the logger.
void TestLogCollector::SetUp() {
  if (!log_temp_dir_.CreateUniqueTempDir()) {
    LOG(ERROR) << "Failed to create temporary directory to hold log files.";
  } else {
    file_logger_.reset(new FileLogger());
    file_logger_->Initialize();
  }
}

// Invoked by the listener at test start to begin collecting logs in a file.
void TestLogCollector::StartSessionForTest(const testing::TestInfo& test_info) {
  if (log_temp_dir_.IsValid()) {
    std::string log_file_name(test_info.name());
    std::replace(log_file_name.begin(), log_file_name.end(), '/', '_');
    log_file_name.append(kTraceLogExtension);
    log_file_ = log_temp_dir_.path().AppendASCII(log_file_name);

    file_logger_->StartLogging(log_file_);
  }
}

// Invoked by the listener when a test result is produced to log an event for
// the result.
bool TestLogCollector::LogTestPartResult(
    const testing::TestPartResult& test_part_result) {
  // Can't handle the event if no trace session.
  if (!file_logger_.get() || !file_logger_->is_logging())
    return false;

  if (test_part_result.type() != testing::TestPartResult::kSuccess) {
    // Approximate Google Test's message formatting.
    LOG(ERROR)
        << base::StringPrintf("%s(%d): error: %s", test_part_result.file_name(),
                              test_part_result.line_number(),
                              test_part_result.message());
  }
  return true;
}

// Invoked by the listener at test end to dump the collected log in case of
// error.
void TestLogCollector::ProcessSessionForTest(
    const testing::TestInfo& test_info) {
  if (file_logger_.get() != NULL && file_logger_->is_logging()) {
    file_logger_->StopLogging();

    if (also_emit_success_logs_ || test_info.result()->Failed()) {
      std::cerr << "----- log messages for "
                << test_info.test_case_name() << "." << test_info.name()
                << " above this line are repeated below -----" << std::endl;
      // Dump the log to stderr.
      logging_win::PrintLogFile(log_file_, &std::cerr);
      std::cerr.flush();
    }

    if (!base::DeleteFile(log_file_, false))
      LOG(ERROR) << "Failed to delete log file " << log_file_.value();
  }

  log_file_.clear();
}

// Invoked by the listener at test program end to shut down the logger and
// delete the temporary log directory.
void TestLogCollector::TearDown() {
  file_logger_.reset();

  ignore_result(log_temp_dir_.Delete());
}

}  // namespace

void InstallTestLogCollector(testing::UnitTest* unit_test) {
  // Must be called before running any tests.
  DCHECK(unit_test);
  DCHECK(!unit_test->current_test_case());

  g_test_log_collector.Get().Initialize(unit_test);
}

}  // namespace logging_win