summaryrefslogtreecommitdiffstats
path: root/testing/gtest/mozilla/MozHelpers.cpp
blob: 78fe6149640b2a7799dec6104d63e108e9f20a10 (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
#include "MozHelpers.h"

#include <iostream>

#include "gtest/gtest-spi.h"
#include "mozilla/Mutex.h"
#include "nsDebug.h"

namespace mozilla::gtest {

void DisableCrashReporter() {
  nsCOMPtr<nsICrashReporter> crashreporter =
      do_GetService("@mozilla.org/toolkit/crash-reporter;1");
  if (crashreporter) {
    crashreporter->SetEnabled(false);
  }
}

class ScopedTestResultReporterImpl
    : public ScopedTestResultReporter,
      public testing::ScopedFakeTestPartResultReporter {
 public:
  explicit ScopedTestResultReporterImpl(ExitMode aExitMode)
      : testing::ScopedFakeTestPartResultReporter(INTERCEPT_ALL_THREADS,
                                                  nullptr),
        mExitMode(aExitMode) {}

  ~ScopedTestResultReporterImpl() {
    switch (mExitMode) {
      case ExitMode::ExitOnDtor:
        exit(ExitCode(Status()));
      case ExitMode::NoExit:
        break;
    }
  }

  void ReportTestPartResult(const testing::TestPartResult& aResult) override {
    {
      MutexAutoLock lock(mMutex);
      if (aResult.nonfatally_failed() &&
          mStatus < TestResultStatus::NonFatalFailure) {
        mStatus = TestResultStatus::NonFatalFailure;
      }

      if (aResult.fatally_failed() &&
          mStatus < TestResultStatus::FatalFailure) {
        mStatus = TestResultStatus::FatalFailure;
      }
    }

    std::ostringstream stream;
    stream << aResult;
    printf_stderr("%s\n", stream.str().c_str());
  }

  TestResultStatus Status() const override {
    MutexAutoLock lock(mMutex);
    return mStatus;
  }

 private:
  const ExitMode mExitMode;

  mutable Mutex mMutex{"ScopedTestResultReporterImpl::mMutex"};
  TestResultStatus mStatus MOZ_GUARDED_BY(mMutex) = TestResultStatus::Pass;
};

UniquePtr<ScopedTestResultReporter> ScopedTestResultReporter::Create(
    ExitMode aExitMode) {
  return MakeUnique<ScopedTestResultReporterImpl>(aExitMode);
}

}  // namespace mozilla::gtest