mock_log.cc 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  1. // Copyright 2015 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.
  4. #include "base/test/mock_log.h"
  5. namespace base {
  6. namespace test {
  7. // static
  8. MockLog* MockLog::g_instance_ = nullptr;
  9. Lock MockLog::g_lock;
  10. MockLog::MockLog() : is_capturing_logs_(false) {
  11. }
  12. MockLog::~MockLog() {
  13. if (is_capturing_logs_) {
  14. StopCapturingLogs();
  15. }
  16. }
  17. void MockLog::StartCapturingLogs() {
  18. AutoLock scoped_lock(g_lock);
  19. // We don't use CHECK(), which can generate a new LOG message, and
  20. // thus can confuse MockLog objects or other registered
  21. // LogSinks.
  22. RAW_CHECK(!is_capturing_logs_);
  23. RAW_CHECK(!g_instance_);
  24. is_capturing_logs_ = true;
  25. g_instance_ = this;
  26. previous_handler_ = logging::GetLogMessageHandler();
  27. logging::SetLogMessageHandler(LogMessageHandler);
  28. }
  29. void MockLog::StopCapturingLogs() {
  30. AutoLock scoped_lock(g_lock);
  31. // We don't use CHECK(), which can generate a new LOG message, and
  32. // thus can confuse MockLog objects or other registered
  33. // LogSinks.
  34. RAW_CHECK(is_capturing_logs_);
  35. RAW_CHECK(g_instance_ == this);
  36. is_capturing_logs_ = false;
  37. logging::SetLogMessageHandler(previous_handler_);
  38. g_instance_ = nullptr;
  39. }
  40. // static
  41. bool MockLog::LogMessageHandler(int severity,
  42. const char* file,
  43. int line,
  44. size_t message_start,
  45. const std::string& str) {
  46. // gMock guarantees thread-safety for calling a mocked method
  47. // (https://github.com/google/googlemock/blob/master/googlemock/docs/CookBook.md#using-google-mock-and-threads)
  48. // but we also need to make sure that Start/StopCapturingLogs are synchronized
  49. // with LogMessageHandler.
  50. AutoLock scoped_lock(g_lock);
  51. return g_instance_->Log(severity, file, line, message_start, str);
  52. }
  53. } // namespace test
  54. } // namespace base