stderr_log_sink_test.cc (2868B)
1 // 2 // Copyright 2022 The Abseil Authors. 3 // 4 // Licensed under the Apache License, Version 2.0 (the "License"); 5 // you may not use this file except in compliance with the License. 6 // You may obtain a copy of the License at 7 // 8 // https://www.apache.org/licenses/LICENSE-2.0 9 // 10 // Unless required by applicable law or agreed to in writing, software 11 // distributed under the License is distributed on an "AS IS" BASIS, 12 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 // See the License for the specific language governing permissions and 14 // limitations under the License. 15 16 #include <stdlib.h> 17 18 #include <string> 19 20 #include "gmock/gmock.h" 21 #include "gtest/gtest.h" 22 #include "absl/base/attributes.h" 23 #include "absl/base/log_severity.h" 24 #include "absl/log/globals.h" 25 #include "absl/log/internal/test_helpers.h" 26 #include "absl/log/log.h" 27 28 namespace { 29 using ::testing::AllOf; 30 using ::testing::HasSubstr; 31 32 auto* test_env ABSL_ATTRIBUTE_UNUSED = ::testing::AddGlobalTestEnvironment( 33 new absl::log_internal::LogTestEnvironment); 34 35 MATCHER_P2(HasSubstrTimes, substr, expected_count, "") { 36 int count = 0; 37 std::string::size_type pos = 0; 38 std::string needle(substr); 39 while ((pos = arg.find(needle, pos)) != std::string::npos) { 40 ++count; 41 pos += needle.size(); 42 } 43 44 return count == expected_count; 45 } 46 47 TEST(StderrLogSinkDeathTest, InfoMessagesInStderr) { 48 EXPECT_DEATH_IF_SUPPORTED( 49 { 50 absl::SetStderrThreshold(absl::LogSeverityAtLeast::kInfo); 51 LOG(INFO) << "INFO message"; 52 exit(1); 53 }, 54 "INFO message"); 55 } 56 57 TEST(StderrLogSinkDeathTest, WarningMessagesInStderr) { 58 EXPECT_DEATH_IF_SUPPORTED( 59 { 60 absl::SetStderrThreshold(absl::LogSeverityAtLeast::kInfo); 61 LOG(WARNING) << "WARNING message"; 62 exit(1); 63 }, 64 "WARNING message"); 65 } 66 67 TEST(StderrLogSinkDeathTest, ErrorMessagesInStderr) { 68 EXPECT_DEATH_IF_SUPPORTED( 69 { 70 absl::SetStderrThreshold(absl::LogSeverityAtLeast::kInfo); 71 LOG(ERROR) << "ERROR message"; 72 exit(1); 73 }, 74 "ERROR message"); 75 } 76 77 TEST(StderrLogSinkDeathTest, FatalMessagesInStderr) { 78 char message[] = "FATAL message"; 79 char stacktrace[] = "*** Check failure stack trace: ***"; 80 81 int expected_count = 1; 82 83 EXPECT_DEATH_IF_SUPPORTED( 84 { 85 absl::SetStderrThreshold(absl::LogSeverityAtLeast::kInfo); 86 LOG(FATAL) << message; 87 }, 88 AllOf(HasSubstrTimes(message, expected_count), HasSubstr(stacktrace))); 89 } 90 91 TEST(StderrLogSinkDeathTest, SecondaryFatalMessagesInStderr) { 92 auto MessageGen = []() -> std::string { 93 LOG(FATAL) << "Internal failure"; 94 return "External failure"; 95 }; 96 97 EXPECT_DEATH_IF_SUPPORTED( 98 { 99 absl::SetStderrThreshold(absl::LogSeverityAtLeast::kInfo); 100 LOG(FATAL) << MessageGen(); 101 }, 102 "Internal failure"); 103 } 104 105 } // namespace