1/*
2 *  Copyright (c) 2012 The WebRTC project authors. All Rights Reserved.
3 *
4 *  Use of this source code is governed by a BSD-style license
5 *  that can be found in the LICENSE file in the root of the source
6 *  tree. An additional intellectual property rights grant can be found
7 *  in the file PATENTS.  All contributing project authors may
8 *  be found in the AUTHORS file in the root of the source tree.
9 */
10
11#ifndef WEBRTC_SYSTEM_WRAPPERS_SOURCE_UNITTEST_UTILITIES_H_
12#define WEBRTC_SYSTEM_WRAPPERS_SOURCE_UNITTEST_UTILITIES_H_
13
14// This file contains utilities that make it simpler to write unittests
15// that are appropriate for the system_wrappers classes.
16
17#include <stdio.h>
18#include <string.h>
19
20#include "system_wrappers/interface/trace.h"
21
22namespace webrtc {
23
24class TestTraceCallback : public TraceCallback {
25 public:
26  virtual void Print(const TraceLevel level,
27                     const char* traceString,
28                     const int length) {
29    if (traceString) {
30      char* cmd_print = new char[length+1];
31      memcpy(cmd_print, traceString, length);
32      cmd_print[length] = '\0';
33      printf("%s\n", cmd_print);
34      fflush(stdout);
35      delete[] cmd_print;
36    }
37  }
38};
39
40// A class that turns on tracing to stdout at the beginning of the test,
41// and turns it off once the test is finished.
42// Intended usage:
43// class SomeTest : public ::testing::Test {
44//  protected:
45//   SomeTest()
46//     : trace_(false) {}  // Change to true to turn on tracing.
47//  private:
48//   ScopedTracing trace_;
49// }
50class ScopedTracing {
51 public:
52  explicit ScopedTracing(bool logOn) {
53    logging_ = logOn;
54    StartTrace();
55  }
56
57  ~ScopedTracing() {
58    StopTrace();
59  }
60
61 private:
62  void StartTrace() {
63    if (logging_) {
64      Trace::CreateTrace();
65      Trace::SetLevelFilter(webrtc::kTraceAll);
66      Trace::SetTraceCallback(&trace_);
67    }
68  }
69
70  void StopTrace() {
71    if (logging_) {
72      Trace::ReturnTrace();
73    }
74  }
75
76 private:
77  bool logging_;
78  TestTraceCallback trace_;
79};
80
81}  // namespace webrtc
82
83#endif  // WEBRTC_SYSTEM_WRAPPERS_SOURCE_UNITTEST_UTILITIES_H_
84