blob: 0cab07d1564bbf028331068626e708799a5b1513 [file] [log] [blame]
shiqian4b6829f2008-07-03 22:38:12 +00001// Copyright 2005, Google Inc.
2// All rights reserved.
3//
4// Redistribution and use in source and binary forms, with or without
5// modification, are permitted provided that the following conditions are
6// met:
7//
8// * Redistributions of source code must retain the above copyright
9// notice, this list of conditions and the following disclaimer.
10// * Redistributions in binary form must reproduce the above
11// copyright notice, this list of conditions and the following disclaimer
12// in the documentation and/or other materials provided with the
13// distribution.
14// * Neither the name of Google Inc. nor the names of its
15// contributors may be used to endorse or promote products derived from
16// this software without specific prior written permission.
17//
18// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
19// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
20// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
21// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
22// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
23// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
24// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
25// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
26// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
27// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
28// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
29//
30// Author: wan@google.com (Zhanyong Wan)
31//
32// Tests for Google Test itself. This verifies that the basic constructs of
33// Google Test work.
34
zhanyong.wan2620c792010-09-14 05:35:59 +000035#include "gtest/gtest.h"
zhanyong.wan0ebc16a2009-02-02 06:37:03 +000036
37// Verifies that the command line flag variables can be accessed
38// in code once <gtest/gtest.h> has been #included.
39// Do not move it after other #includes.
40TEST(CommandLineFlagsTest, CanBeAccessedInCodeOnceGTestHIsIncluded) {
41 bool dummy = testing::GTEST_FLAG(also_run_disabled_tests)
42 || testing::GTEST_FLAG(break_on_failure)
43 || testing::GTEST_FLAG(catch_exceptions)
44 || testing::GTEST_FLAG(color) != "unknown"
45 || testing::GTEST_FLAG(filter) != "unknown"
46 || testing::GTEST_FLAG(list_tests)
47 || testing::GTEST_FLAG(output) != "unknown"
48 || testing::GTEST_FLAG(print_time)
zhanyong.wan9b9794f2009-07-14 22:56:46 +000049 || testing::GTEST_FLAG(random_seed)
zhanyong.wan0ebc16a2009-02-02 06:37:03 +000050 || testing::GTEST_FLAG(repeat) > 0
51 || testing::GTEST_FLAG(show_internal_stack_frames)
zhanyong.wan9b9794f2009-07-14 22:56:46 +000052 || testing::GTEST_FLAG(shuffle)
zhanyong.wanb0fe69f2009-03-06 20:05:23 +000053 || testing::GTEST_FLAG(stack_trace_depth) > 0
zhanyong.wanc95489e2010-08-19 22:16:00 +000054 || testing::GTEST_FLAG(stream_result_to) != "unknown"
zhanyong.wanb0fe69f2009-03-06 20:05:23 +000055 || testing::GTEST_FLAG(throw_on_failure);
zhanyong.wan0ebc16a2009-02-02 06:37:03 +000056 EXPECT_TRUE(dummy || !dummy); // Suppresses warning that dummy is unused.
57}
58
vladlosev93fed472011-11-04 17:56:23 +000059#include <limits.h> // For INT_MAX.
60#include <stdlib.h>
61#include <string.h>
62#include <time.h>
63
64#include <map>
65#include <vector>
66#include <ostream>
67
zhanyong.wan2620c792010-09-14 05:35:59 +000068#include "gtest/gtest-spi.h"
shiqian4b6829f2008-07-03 22:38:12 +000069
70// Indicates that this translation unit is part of Google Test's
71// implementation. It must come before gtest-internal-inl.h is
72// included, or there will be a compiler error. This trick is to
73// prevent a user from accidentally including gtest-internal-inl.h in
74// his code.
zhanyong.wan4cd62602009-02-23 23:21:55 +000075#define GTEST_IMPLEMENTATION_ 1
shiqian4b6829f2008-07-03 22:38:12 +000076#include "src/gtest-internal-inl.h"
zhanyong.wan4cd62602009-02-23 23:21:55 +000077#undef GTEST_IMPLEMENTATION_
shiqian4b6829f2008-07-03 22:38:12 +000078
shiqian4b6829f2008-07-03 22:38:12 +000079namespace testing {
80namespace internal {
zhanyong.wanb7ec0f72009-07-01 04:58:05 +000081
kosak@google.coma032cff2013-02-22 20:25:42 +000082#if GTEST_CAN_STREAM_RESULTS_
83
84class StreamingListenerTest : public Test {
85 public:
86 class FakeSocketWriter : public StreamingListener::AbstractSocketWriter {
87 public:
88 // Sends a string to the socket.
89 virtual void Send(const string& message) { output_ += message; }
90
91 string output_;
92 };
93
94 StreamingListenerTest()
95 : fake_sock_writer_(new FakeSocketWriter),
96 streamer_(fake_sock_writer_),
97 test_info_obj_("FooTest", "Bar", NULL, NULL, 0, NULL) {}
98
99 protected:
100 string* output() { return &(fake_sock_writer_->output_); }
101
102 FakeSocketWriter* const fake_sock_writer_;
103 StreamingListener streamer_;
104 UnitTest unit_test_;
105 TestInfo test_info_obj_; // The name test_info_ was taken by testing::Test.
106};
107
108TEST_F(StreamingListenerTest, OnTestProgramEnd) {
109 *output() = "";
110 streamer_.OnTestProgramEnd(unit_test_);
111 EXPECT_EQ("event=TestProgramEnd&passed=1\n", *output());
112}
113
114TEST_F(StreamingListenerTest, OnTestIterationEnd) {
115 *output() = "";
116 streamer_.OnTestIterationEnd(unit_test_, 42);
117 EXPECT_EQ("event=TestIterationEnd&passed=1&elapsed_time=0ms\n", *output());
118}
119
120TEST_F(StreamingListenerTest, OnTestCaseStart) {
121 *output() = "";
122 streamer_.OnTestCaseStart(TestCase("FooTest", "Bar", NULL, NULL));
123 EXPECT_EQ("event=TestCaseStart&name=FooTest\n", *output());
124}
125
126TEST_F(StreamingListenerTest, OnTestCaseEnd) {
127 *output() = "";
128 streamer_.OnTestCaseEnd(TestCase("FooTest", "Bar", NULL, NULL));
129 EXPECT_EQ("event=TestCaseEnd&passed=1&elapsed_time=0ms\n", *output());
130}
131
132TEST_F(StreamingListenerTest, OnTestStart) {
133 *output() = "";
134 streamer_.OnTestStart(test_info_obj_);
135 EXPECT_EQ("event=TestStart&name=Bar\n", *output());
136}
137
138TEST_F(StreamingListenerTest, OnTestEnd) {
139 *output() = "";
140 streamer_.OnTestEnd(test_info_obj_);
141 EXPECT_EQ("event=TestEnd&passed=1&elapsed_time=0ms\n", *output());
142}
143
144TEST_F(StreamingListenerTest, OnTestPartResult) {
145 *output() = "";
146 streamer_.OnTestPartResult(TestPartResult(
147 TestPartResult::kFatalFailure, "foo.cc", 42, "failed=\n&%"));
148
149 // Meta characters in the failure message should be properly escaped.
150 EXPECT_EQ(
151 "event=TestPartResult&file=foo.cc&line=42&message=failed%3D%0A%26%25\n",
152 *output());
153}
154
155#endif // GTEST_CAN_STREAM_RESULTS_
156
zhanyong.wanf6d087b2009-09-30 20:23:50 +0000157// Provides access to otherwise private parts of the TestEventListeners class
zhanyong.wanf39160b2009-09-04 18:30:25 +0000158// that are needed to test it.
zhanyong.wanf6d087b2009-09-30 20:23:50 +0000159class TestEventListenersAccessor {
zhanyong.wanf39160b2009-09-04 18:30:25 +0000160 public:
zhanyong.wanf6d087b2009-09-30 20:23:50 +0000161 static TestEventListener* GetRepeater(TestEventListeners* listeners) {
zhanyong.wanfff03342009-09-24 21:15:59 +0000162 return listeners->repeater();
163 }
zhanyong.wanf39160b2009-09-04 18:30:25 +0000164
zhanyong.wanf6d087b2009-09-30 20:23:50 +0000165 static void SetDefaultResultPrinter(TestEventListeners* listeners,
zhanyong.wanfff03342009-09-24 21:15:59 +0000166 TestEventListener* listener) {
zhanyong.wanf39160b2009-09-04 18:30:25 +0000167 listeners->SetDefaultResultPrinter(listener);
168 }
zhanyong.wanf6d087b2009-09-30 20:23:50 +0000169 static void SetDefaultXmlGenerator(TestEventListeners* listeners,
zhanyong.wanfff03342009-09-24 21:15:59 +0000170 TestEventListener* listener) {
zhanyong.wanf39160b2009-09-04 18:30:25 +0000171 listeners->SetDefaultXmlGenerator(listener);
172 }
173
zhanyong.wanf6d087b2009-09-30 20:23:50 +0000174 static bool EventForwardingEnabled(const TestEventListeners& listeners) {
zhanyong.wanf39160b2009-09-04 18:30:25 +0000175 return listeners.EventForwardingEnabled();
176 }
177
zhanyong.wanf6d087b2009-09-30 20:23:50 +0000178 static void SuppressEventForwarding(TestEventListeners* listeners) {
zhanyong.wanf39160b2009-09-04 18:30:25 +0000179 listeners->SuppressEventForwarding();
180 }
181};
182
vladlosevdfbdf0b2013-04-05 20:50:46 +0000183class UnitTestRecordPropertyTestHelper : public Test {
184 protected:
185 UnitTestRecordPropertyTestHelper() {}
186
187 // Forwards to UnitTest::RecordProperty() to bypass access controls.
188 void UnitTestRecordProperty(const char* key, const std::string& value) {
189 unit_test_.RecordProperty(key, value);
190 }
191
192 UnitTest unit_test_;
193};
194
shiqian4b6829f2008-07-03 22:38:12 +0000195} // namespace internal
196} // namespace testing
197
shiqian760af5c2008-08-06 21:43:15 +0000198using testing::AssertionFailure;
199using testing::AssertionResult;
200using testing::AssertionSuccess;
201using testing::DoubleLE;
zhanyong.wanfff03342009-09-24 21:15:59 +0000202using testing::EmptyTestEventListener;
vladlosevdfbdf0b2013-04-05 20:50:46 +0000203using testing::Environment;
shiqian760af5c2008-08-06 21:43:15 +0000204using testing::FloatLE;
shiqianca6949f2009-01-10 01:16:33 +0000205using testing::GTEST_FLAG(also_run_disabled_tests);
shiqian760af5c2008-08-06 21:43:15 +0000206using testing::GTEST_FLAG(break_on_failure);
207using testing::GTEST_FLAG(catch_exceptions);
shiqian4b6829f2008-07-03 22:38:12 +0000208using testing::GTEST_FLAG(color);
zhanyong.wan1cdc7632009-07-16 00:36:55 +0000209using testing::GTEST_FLAG(death_test_use_fork);
shiqian760af5c2008-08-06 21:43:15 +0000210using testing::GTEST_FLAG(filter);
211using testing::GTEST_FLAG(list_tests);
212using testing::GTEST_FLAG(output);
213using testing::GTEST_FLAG(print_time);
zhanyong.wan9b9794f2009-07-14 22:56:46 +0000214using testing::GTEST_FLAG(random_seed);
shiqian760af5c2008-08-06 21:43:15 +0000215using testing::GTEST_FLAG(repeat);
216using testing::GTEST_FLAG(show_internal_stack_frames);
zhanyong.wan9b9794f2009-07-14 22:56:46 +0000217using testing::GTEST_FLAG(shuffle);
shiqian760af5c2008-08-06 21:43:15 +0000218using testing::GTEST_FLAG(stack_trace_depth);
zhanyong.wanc95489e2010-08-19 22:16:00 +0000219using testing::GTEST_FLAG(stream_result_to);
zhanyong.wanb0fe69f2009-03-06 20:05:23 +0000220using testing::GTEST_FLAG(throw_on_failure);
shiqian760af5c2008-08-06 21:43:15 +0000221using testing::IsNotSubstring;
222using testing::IsSubstring;
223using testing::Message;
shiqian4b6829f2008-07-03 22:38:12 +0000224using testing::ScopedFakeTestPartResultReporter;
shiqian21d43d12009-01-08 01:10:31 +0000225using testing::StaticAssertTypeEq;
zhanyong.wan1cdc7632009-07-16 00:36:55 +0000226using testing::Test;
zhanyong.wanfff03342009-09-24 21:15:59 +0000227using testing::TestCase;
zhanyong.wan678f92b2010-05-10 17:11:58 +0000228using testing::TestEventListeners;
vladlosevdfbdf0b2013-04-05 20:50:46 +0000229using testing::TestInfo;
zhanyong.wan1cdc7632009-07-16 00:36:55 +0000230using testing::TestPartResult;
231using testing::TestPartResultArray;
zhanyong.wanfff03342009-09-24 21:15:59 +0000232using testing::TestProperty;
233using testing::TestResult;
vladlosev8883b422011-10-05 05:52:34 +0000234using testing::TimeInMillis;
shiqian4b6829f2008-07-03 22:38:12 +0000235using testing::UnitTest;
vladlosevba015a92009-11-17 22:43:15 +0000236using testing::kMaxStackTraceDepth;
zhanyong.wan678f92b2010-05-10 17:11:58 +0000237using testing::internal::AddReference;
zhanyong.wanf6d087b2009-09-30 20:23:50 +0000238using testing::internal::AlwaysFalse;
239using testing::internal::AlwaysTrue;
shiqian4b6829f2008-07-03 22:38:12 +0000240using testing::internal::AppendUserMessage;
zhanyong.wan678f92b2010-05-10 17:11:58 +0000241using testing::internal::ArrayAwareFind;
242using testing::internal::ArrayEq;
vladloseve006e682008-08-25 23:11:54 +0000243using testing::internal::CodePointToUtf8;
zhanyong.wan678f92b2010-05-10 17:11:58 +0000244using testing::internal::CompileAssertTypesEqual;
245using testing::internal::CopyArray;
zhanyong.wan93d13a82010-02-25 01:09:07 +0000246using testing::internal::CountIf;
shiqian4b6829f2008-07-03 22:38:12 +0000247using testing::internal::EqFailure;
shiqian760af5c2008-08-06 21:43:15 +0000248using testing::internal::FloatingPoint;
zhanyong.wan93d13a82010-02-25 01:09:07 +0000249using testing::internal::ForEach;
vladlosev8883b422011-10-05 05:52:34 +0000250using testing::internal::FormatEpochTimeInMillisAsIso8601;
zhanyong.wan678f92b2010-05-10 17:11:58 +0000251using testing::internal::FormatTimeInMillisAsSeconds;
zhanyong.wan1cdc7632009-07-16 00:36:55 +0000252using testing::internal::GTestFlagSaver;
vladlosevf904a612008-11-20 01:40:35 +0000253using testing::internal::GetCurrentOsStackTraceExceptTop;
zhanyong.wan93d13a82010-02-25 01:09:07 +0000254using testing::internal::GetElementOr;
zhanyong.wan9b9794f2009-07-14 22:56:46 +0000255using testing::internal::GetNextRandomSeed;
256using testing::internal::GetRandomSeedFromFlag;
shiqianfe6a9a42008-11-24 20:13:22 +0000257using testing::internal::GetTestTypeId;
vladlosev8883b422011-10-05 05:52:34 +0000258using testing::internal::GetTimeInMillis;
shiqianfe6a9a42008-11-24 20:13:22 +0000259using testing::internal::GetTypeId;
zhanyong.wana80f23f2009-06-25 20:49:23 +0000260using testing::internal::GetUnitTestImpl;
zhanyong.wan678f92b2010-05-10 17:11:58 +0000261using testing::internal::ImplicitlyConvertible;
shiqian4b6829f2008-07-03 22:38:12 +0000262using testing::internal::Int32;
zhanyong.wan905074c2009-02-09 18:05:21 +0000263using testing::internal::Int32FromEnvOrDie;
zhanyong.wan678f92b2010-05-10 17:11:58 +0000264using testing::internal::IsAProtocolMessage;
265using testing::internal::IsContainer;
266using testing::internal::IsContainerTest;
267using testing::internal::IsNotContainer;
268using testing::internal::NativeArray;
zhanyong.wanf6d087b2009-09-30 20:23:50 +0000269using testing::internal::ParseInt32Flag;
zhanyong.wan678f92b2010-05-10 17:11:58 +0000270using testing::internal::RemoveConst;
271using testing::internal::RemoveReference;
zhanyong.wan905074c2009-02-09 18:05:21 +0000272using testing::internal::ShouldRunTestOnShard;
273using testing::internal::ShouldShard;
shiqian4b6829f2008-07-03 22:38:12 +0000274using testing::internal::ShouldUseColor;
zhanyong.wan93d13a82010-02-25 01:09:07 +0000275using testing::internal::Shuffle;
276using testing::internal::ShuffleRange;
zhanyong.wan9748de02010-06-08 22:51:46 +0000277using testing::internal::SkipPrefix;
shiqian4b6829f2008-07-03 22:38:12 +0000278using testing::internal::StreamableToString;
279using testing::internal::String;
zhanyong.wanf6d087b2009-09-30 20:23:50 +0000280using testing::internal::TestEventListenersAccessor;
zhanyong.wanb7ec0f72009-07-01 04:58:05 +0000281using testing::internal::TestResultAccessor;
zhanyong.wan85f555a2009-09-21 19:42:03 +0000282using testing::internal::UInt32;
vladloseve006e682008-08-25 23:11:54 +0000283using testing::internal::WideStringToUtf8;
zhanyong.wan678f92b2010-05-10 17:11:58 +0000284using testing::internal::kCopy;
zhanyong.wanfff03342009-09-24 21:15:59 +0000285using testing::internal::kMaxRandomSeed;
zhanyong.wan678f92b2010-05-10 17:11:58 +0000286using testing::internal::kReference;
zhanyong.wan1cdc7632009-07-16 00:36:55 +0000287using testing::internal::kTestTypeIdInGoogleTest;
zhanyong.wanf39160b2009-09-04 18:30:25 +0000288using testing::internal::scoped_ptr;
shiqian4b6829f2008-07-03 22:38:12 +0000289
zhanyong.wan5d0c3dc2010-08-31 18:21:13 +0000290#if GTEST_HAS_STREAM_REDIRECTION
zhanyong.wancf8a5842010-01-28 21:50:29 +0000291using testing::internal::CaptureStdout;
292using testing::internal::GetCapturedStdout;
zhanyong.wan5d0c3dc2010-08-31 18:21:13 +0000293#endif
zhanyong.wancf8a5842010-01-28 21:50:29 +0000294
zhanyong.wanf6fb5322010-03-04 22:15:53 +0000295#if GTEST_IS_THREADSAFE
296using testing::internal::ThreadWithParam;
297#endif
298
zhanyong.wan93d13a82010-02-25 01:09:07 +0000299class TestingVector : public std::vector<int> {
zhanyong.wanf19450f2009-09-30 23:46:28 +0000300};
301
302::std::ostream& operator<<(::std::ostream& os,
303 const TestingVector& vector) {
304 os << "{ ";
zhanyong.wan93d13a82010-02-25 01:09:07 +0000305 for (size_t i = 0; i < vector.size(); i++) {
306 os << vector[i] << " ";
zhanyong.wanf19450f2009-09-30 23:46:28 +0000307 }
308 os << "}";
309 return os;
310}
311
shiqian4b6829f2008-07-03 22:38:12 +0000312// This line tests that we can define tests in an unnamed namespace.
313namespace {
314
zhanyong.wan9b9794f2009-07-14 22:56:46 +0000315TEST(GetRandomSeedFromFlagTest, HandlesZero) {
316 const int seed = GetRandomSeedFromFlag(0);
317 EXPECT_LE(1, seed);
318 EXPECT_LE(seed, static_cast<int>(kMaxRandomSeed));
319}
320
321TEST(GetRandomSeedFromFlagTest, PreservesValidSeed) {
322 EXPECT_EQ(1, GetRandomSeedFromFlag(1));
323 EXPECT_EQ(2, GetRandomSeedFromFlag(2));
324 EXPECT_EQ(kMaxRandomSeed - 1, GetRandomSeedFromFlag(kMaxRandomSeed - 1));
325 EXPECT_EQ(static_cast<int>(kMaxRandomSeed),
326 GetRandomSeedFromFlag(kMaxRandomSeed));
327}
328
329TEST(GetRandomSeedFromFlagTest, NormalizesInvalidSeed) {
330 const int seed1 = GetRandomSeedFromFlag(-1);
331 EXPECT_LE(1, seed1);
332 EXPECT_LE(seed1, static_cast<int>(kMaxRandomSeed));
333
334 const int seed2 = GetRandomSeedFromFlag(kMaxRandomSeed + 1);
335 EXPECT_LE(1, seed2);
336 EXPECT_LE(seed2, static_cast<int>(kMaxRandomSeed));
337}
338
339TEST(GetNextRandomSeedTest, WorksForValidInput) {
340 EXPECT_EQ(2, GetNextRandomSeed(1));
341 EXPECT_EQ(3, GetNextRandomSeed(2));
342 EXPECT_EQ(static_cast<int>(kMaxRandomSeed),
343 GetNextRandomSeed(kMaxRandomSeed - 1));
344 EXPECT_EQ(1, GetNextRandomSeed(kMaxRandomSeed));
345
346 // We deliberately don't test GetNextRandomSeed() with invalid
347 // inputs, as that requires death tests, which are expensive. This
348 // is fine as GetNextRandomSeed() is internal and has a
349 // straightforward definition.
350}
351
zhanyong.wanb7ec0f72009-07-01 04:58:05 +0000352static void ClearCurrentTestPartResults() {
353 TestResultAccessor::ClearTestPartResults(
354 GetUnitTestImpl()->current_test_result());
355}
356
shiqianfe6a9a42008-11-24 20:13:22 +0000357// Tests GetTypeId.
358
359TEST(GetTypeIdTest, ReturnsSameValueForSameType) {
360 EXPECT_EQ(GetTypeId<int>(), GetTypeId<int>());
361 EXPECT_EQ(GetTypeId<Test>(), GetTypeId<Test>());
362}
363
364class SubClassOfTest : public Test {};
365class AnotherSubClassOfTest : public Test {};
366
367TEST(GetTypeIdTest, ReturnsDifferentValuesForDifferentTypes) {
368 EXPECT_NE(GetTypeId<int>(), GetTypeId<const int>());
369 EXPECT_NE(GetTypeId<int>(), GetTypeId<char>());
370 EXPECT_NE(GetTypeId<int>(), GetTestTypeId());
371 EXPECT_NE(GetTypeId<SubClassOfTest>(), GetTestTypeId());
372 EXPECT_NE(GetTypeId<AnotherSubClassOfTest>(), GetTestTypeId());
373 EXPECT_NE(GetTypeId<AnotherSubClassOfTest>(), GetTypeId<SubClassOfTest>());
374}
375
376// Verifies that GetTestTypeId() returns the same value, no matter it
377// is called from inside Google Test or outside of it.
378TEST(GetTestTypeIdTest, ReturnsTheSameValueInsideOrOutsideOfGoogleTest) {
379 EXPECT_EQ(kTestTypeIdInGoogleTest, GetTestTypeId());
380}
381
shiqianf0e809a2008-09-26 16:08:30 +0000382// Tests FormatTimeInMillisAsSeconds().
383
384TEST(FormatTimeInMillisAsSecondsTest, FormatsZero) {
zhanyong.wan65de7e02010-01-08 00:23:45 +0000385 EXPECT_EQ("0", FormatTimeInMillisAsSeconds(0));
shiqianf0e809a2008-09-26 16:08:30 +0000386}
387
388TEST(FormatTimeInMillisAsSecondsTest, FormatsPositiveNumber) {
zhanyong.wan65de7e02010-01-08 00:23:45 +0000389 EXPECT_EQ("0.003", FormatTimeInMillisAsSeconds(3));
390 EXPECT_EQ("0.01", FormatTimeInMillisAsSeconds(10));
391 EXPECT_EQ("0.2", FormatTimeInMillisAsSeconds(200));
392 EXPECT_EQ("1.2", FormatTimeInMillisAsSeconds(1200));
393 EXPECT_EQ("3", FormatTimeInMillisAsSeconds(3000));
shiqianf0e809a2008-09-26 16:08:30 +0000394}
395
396TEST(FormatTimeInMillisAsSecondsTest, FormatsNegativeNumber) {
zhanyong.wan65de7e02010-01-08 00:23:45 +0000397 EXPECT_EQ("-0.003", FormatTimeInMillisAsSeconds(-3));
398 EXPECT_EQ("-0.01", FormatTimeInMillisAsSeconds(-10));
399 EXPECT_EQ("-0.2", FormatTimeInMillisAsSeconds(-200));
400 EXPECT_EQ("-1.2", FormatTimeInMillisAsSeconds(-1200));
401 EXPECT_EQ("-3", FormatTimeInMillisAsSeconds(-3000));
shiqianf0e809a2008-09-26 16:08:30 +0000402}
403
vladlosev8883b422011-10-05 05:52:34 +0000404// Tests FormatEpochTimeInMillisAsIso8601(). The correctness of conversion
405// for particular dates below was verified in Python using
406// datetime.datetime.fromutctimestamp(<timetamp>/1000).
407
408// FormatEpochTimeInMillisAsIso8601 depends on the current timezone, so we
409// have to set up a particular timezone to obtain predictable results.
410class FormatEpochTimeInMillisAsIso8601Test : public Test {
411 public:
412 // On Cygwin, GCC doesn't allow unqualified integer literals to exceed
413 // 32 bits, even when 64-bit integer types are available. We have to
414 // force the constants to have a 64-bit type here.
415 static const TimeInMillis kMillisPerSec = 1000;
416
417 private:
418 virtual void SetUp() {
419 saved_tz_ = NULL;
420#if _MSC_VER
421# pragma warning(push) // Saves the current warning state.
422# pragma warning(disable:4996) // Temporarily disables warning 4996
423 // (function or variable may be unsafe
424 // for getenv, function is deprecated for
425 // strdup).
426 if (getenv("TZ"))
427 saved_tz_ = strdup(getenv("TZ"));
428# pragma warning(pop) // Restores the warning state again.
429#else
430 if (getenv("TZ"))
431 saved_tz_ = strdup(getenv("TZ"));
432#endif
433
434 // Set up the time zone for FormatEpochTimeInMillisAsIso8601 to use. We
435 // cannot use the local time zone because the function's output depends
436 // on the time zone.
437 SetTimeZone("UTC+00");
438 }
439
440 virtual void TearDown() {
441 SetTimeZone(saved_tz_);
442 free(const_cast<char*>(saved_tz_));
443 saved_tz_ = NULL;
444 }
445
446 static void SetTimeZone(const char* time_zone) {
447 // tzset() distinguishes between the TZ variable being present and empty
448 // and not being present, so we have to consider the case of time_zone
449 // being NULL.
450#if _MSC_VER
451 // ...Unless it's MSVC, whose standard library's _putenv doesn't
452 // distinguish between an empty and a missing variable.
453 const std::string env_var =
454 std::string("TZ=") + (time_zone ? time_zone : "");
455 _putenv(env_var.c_str());
456# pragma warning(push) // Saves the current warning state.
457# pragma warning(disable:4996) // Temporarily disables warning 4996
458 // (function is deprecated).
459 tzset();
460# pragma warning(pop) // Restores the warning state again.
461#else
462 if (time_zone) {
463 setenv(("TZ"), time_zone, 1);
464 } else {
465 unsetenv("TZ");
466 }
467 tzset();
468#endif
469 }
470
471 const char* saved_tz_;
472};
473
474const TimeInMillis FormatEpochTimeInMillisAsIso8601Test::kMillisPerSec;
475
476TEST_F(FormatEpochTimeInMillisAsIso8601Test, PrintsTwoDigitSegments) {
477 EXPECT_EQ("2011-10-31T18:52:42",
478 FormatEpochTimeInMillisAsIso8601(1320087162 * kMillisPerSec));
479}
480
481TEST_F(FormatEpochTimeInMillisAsIso8601Test, MillisecondsDoNotAffectResult) {
482 EXPECT_EQ(
483 "2011-10-31T18:52:42",
484 FormatEpochTimeInMillisAsIso8601(1320087162 * kMillisPerSec + 234));
485}
486
487TEST_F(FormatEpochTimeInMillisAsIso8601Test, PrintsLeadingZeroes) {
488 EXPECT_EQ("2011-09-03T05:07:02",
489 FormatEpochTimeInMillisAsIso8601(1315026422 * kMillisPerSec));
490}
491
492TEST_F(FormatEpochTimeInMillisAsIso8601Test, Prints24HourTime) {
493 EXPECT_EQ("2011-09-28T17:08:22",
494 FormatEpochTimeInMillisAsIso8601(1317229702 * kMillisPerSec));
495}
496
497TEST_F(FormatEpochTimeInMillisAsIso8601Test, PrintsEpochStart) {
498 EXPECT_EQ("1970-01-01T00:00:00", FormatEpochTimeInMillisAsIso8601(0));
499}
500
vladlosev5147b452010-03-17 18:22:59 +0000501#if GTEST_CAN_COMPARE_NULL
shiqian4b6829f2008-07-03 22:38:12 +0000502
zhanyong.wan733a54a2011-02-22 22:08:59 +0000503# ifdef __BORLANDC__
zhanyong.wan98efcc42009-04-28 00:28:09 +0000504// Silences warnings: "Condition is always true", "Unreachable code"
zhanyong.wan733a54a2011-02-22 22:08:59 +0000505# pragma option push -w-ccc -w-rch
506# endif
zhanyong.wan98efcc42009-04-28 00:28:09 +0000507
shiqiane44602e2008-10-11 07:20:02 +0000508// Tests that GTEST_IS_NULL_LITERAL_(x) is true when x is a null
shiqian4b6829f2008-07-03 22:38:12 +0000509// pointer literal.
510TEST(NullLiteralTest, IsTrueForNullLiterals) {
shiqiane44602e2008-10-11 07:20:02 +0000511 EXPECT_TRUE(GTEST_IS_NULL_LITERAL_(NULL));
512 EXPECT_TRUE(GTEST_IS_NULL_LITERAL_(0));
shiqiane44602e2008-10-11 07:20:02 +0000513 EXPECT_TRUE(GTEST_IS_NULL_LITERAL_(0U));
514 EXPECT_TRUE(GTEST_IS_NULL_LITERAL_(0L));
shiqian4b6829f2008-07-03 22:38:12 +0000515}
516
shiqiane44602e2008-10-11 07:20:02 +0000517// Tests that GTEST_IS_NULL_LITERAL_(x) is false when x is not a null
shiqian4b6829f2008-07-03 22:38:12 +0000518// pointer literal.
519TEST(NullLiteralTest, IsFalseForNonNullLiterals) {
shiqiane44602e2008-10-11 07:20:02 +0000520 EXPECT_FALSE(GTEST_IS_NULL_LITERAL_(1));
521 EXPECT_FALSE(GTEST_IS_NULL_LITERAL_(0.0));
522 EXPECT_FALSE(GTEST_IS_NULL_LITERAL_('a'));
523 EXPECT_FALSE(GTEST_IS_NULL_LITERAL_(static_cast<void*>(NULL)));
shiqian4b6829f2008-07-03 22:38:12 +0000524}
525
zhanyong.wan733a54a2011-02-22 22:08:59 +0000526# ifdef __BORLANDC__
vladlosevd6b49412010-04-07 05:32:34 +0000527// Restores warnings after previous "#pragma option push" suppressed them.
zhanyong.wan733a54a2011-02-22 22:08:59 +0000528# pragma option pop
529# endif
zhanyong.wan98efcc42009-04-28 00:28:09 +0000530
vladlosev5147b452010-03-17 18:22:59 +0000531#endif // GTEST_CAN_COMPARE_NULL
vladloseve006e682008-08-25 23:11:54 +0000532//
533// Tests CodePointToUtf8().
shiqian4b6829f2008-07-03 22:38:12 +0000534
535// Tests that the NUL character L'\0' is encoded correctly.
vladloseve006e682008-08-25 23:11:54 +0000536TEST(CodePointToUtf8Test, CanEncodeNul) {
kosak@google.com3b8388d2013-02-22 20:10:40 +0000537 EXPECT_EQ("", CodePointToUtf8(L'\0'));
shiqian4b6829f2008-07-03 22:38:12 +0000538}
539
540// Tests that ASCII characters are encoded correctly.
vladloseve006e682008-08-25 23:11:54 +0000541TEST(CodePointToUtf8Test, CanEncodeAscii) {
kosak@google.com3b8388d2013-02-22 20:10:40 +0000542 EXPECT_EQ("a", CodePointToUtf8(L'a'));
543 EXPECT_EQ("Z", CodePointToUtf8(L'Z'));
544 EXPECT_EQ("&", CodePointToUtf8(L'&'));
545 EXPECT_EQ("\x7F", CodePointToUtf8(L'\x7F'));
shiqian4b6829f2008-07-03 22:38:12 +0000546}
547
548// Tests that Unicode code-points that have 8 to 11 bits are encoded
549// as 110xxxxx 10xxxxxx.
vladloseve006e682008-08-25 23:11:54 +0000550TEST(CodePointToUtf8Test, CanEncode8To11Bits) {
shiqian4b6829f2008-07-03 22:38:12 +0000551 // 000 1101 0011 => 110-00011 10-010011
kosak@google.com3b8388d2013-02-22 20:10:40 +0000552 EXPECT_EQ("\xC3\x93", CodePointToUtf8(L'\xD3'));
shiqian4b6829f2008-07-03 22:38:12 +0000553
554 // 101 0111 0110 => 110-10101 10-110110
zhanyong.wanb499e7b2010-10-11 06:28:54 +0000555 // Some compilers (e.g., GCC on MinGW) cannot handle non-ASCII codepoints
556 // in wide strings and wide chars. In order to accomodate them, we have to
557 // introduce such character constants as integers.
kosak@google.com3b8388d2013-02-22 20:10:40 +0000558 EXPECT_EQ("\xD5\xB6",
559 CodePointToUtf8(static_cast<wchar_t>(0x576)));
shiqian4b6829f2008-07-03 22:38:12 +0000560}
561
562// Tests that Unicode code-points that have 12 to 16 bits are encoded
563// as 1110xxxx 10xxxxxx 10xxxxxx.
vladloseve006e682008-08-25 23:11:54 +0000564TEST(CodePointToUtf8Test, CanEncode12To16Bits) {
shiqian4b6829f2008-07-03 22:38:12 +0000565 // 0000 1000 1101 0011 => 1110-0000 10-100011 10-010011
kosak@google.com3b8388d2013-02-22 20:10:40 +0000566 EXPECT_EQ("\xE0\xA3\x93",
567 CodePointToUtf8(static_cast<wchar_t>(0x8D3)));
shiqian4b6829f2008-07-03 22:38:12 +0000568
569 // 1100 0111 0100 1101 => 1110-1100 10-011101 10-001101
kosak@google.com3b8388d2013-02-22 20:10:40 +0000570 EXPECT_EQ("\xEC\x9D\x8D",
571 CodePointToUtf8(static_cast<wchar_t>(0xC74D)));
shiqian4b6829f2008-07-03 22:38:12 +0000572}
573
zhanyong.wan4cd62602009-02-23 23:21:55 +0000574#if !GTEST_WIDE_STRING_USES_UTF16_
shiqian4b6829f2008-07-03 22:38:12 +0000575// Tests in this group require a wchar_t to hold > 16 bits, and thus
shiqian4f1d72e2008-07-09 20:58:26 +0000576// are skipped on Windows, Cygwin, and Symbian, where a wchar_t is
vladloseve006e682008-08-25 23:11:54 +0000577// 16-bit wide. This code may not compile on those systems.
shiqian4b6829f2008-07-03 22:38:12 +0000578
579// Tests that Unicode code-points that have 17 to 21 bits are encoded
580// as 11110xxx 10xxxxxx 10xxxxxx 10xxxxxx.
vladloseve006e682008-08-25 23:11:54 +0000581TEST(CodePointToUtf8Test, CanEncode17To21Bits) {
shiqian4b6829f2008-07-03 22:38:12 +0000582 // 0 0001 0000 1000 1101 0011 => 11110-000 10-010000 10-100011 10-010011
kosak@google.com3b8388d2013-02-22 20:10:40 +0000583 EXPECT_EQ("\xF0\x90\xA3\x93", CodePointToUtf8(L'\x108D3'));
shiqian4b6829f2008-07-03 22:38:12 +0000584
vladloseve006e682008-08-25 23:11:54 +0000585 // 0 0001 0000 0100 0000 0000 => 11110-000 10-010000 10-010000 10-000000
kosak@google.com3b8388d2013-02-22 20:10:40 +0000586 EXPECT_EQ("\xF0\x90\x90\x80", CodePointToUtf8(L'\x10400'));
vladloseve006e682008-08-25 23:11:54 +0000587
588 // 1 0000 1000 0110 0011 0100 => 11110-100 10-001000 10-011000 10-110100
kosak@google.com3b8388d2013-02-22 20:10:40 +0000589 EXPECT_EQ("\xF4\x88\x98\xB4", CodePointToUtf8(L'\x108634'));
shiqian4b6829f2008-07-03 22:38:12 +0000590}
591
592// Tests that encoding an invalid code-point generates the expected result.
vladloseve006e682008-08-25 23:11:54 +0000593TEST(CodePointToUtf8Test, CanEncodeInvalidCodePoint) {
kosak@google.com3b8388d2013-02-22 20:10:40 +0000594 EXPECT_EQ("(Invalid Unicode 0x1234ABCD)", CodePointToUtf8(L'\x1234ABCD'));
shiqian4b6829f2008-07-03 22:38:12 +0000595}
596
zhanyong.wan4cd62602009-02-23 23:21:55 +0000597#endif // !GTEST_WIDE_STRING_USES_UTF16_
vladloseve006e682008-08-25 23:11:54 +0000598
599// Tests WideStringToUtf8().
600
601// Tests that the NUL character L'\0' is encoded correctly.
602TEST(WideStringToUtf8Test, CanEncodeNul) {
603 EXPECT_STREQ("", WideStringToUtf8(L"", 0).c_str());
604 EXPECT_STREQ("", WideStringToUtf8(L"", -1).c_str());
605}
606
607// Tests that ASCII strings are encoded correctly.
608TEST(WideStringToUtf8Test, CanEncodeAscii) {
609 EXPECT_STREQ("a", WideStringToUtf8(L"a", 1).c_str());
610 EXPECT_STREQ("ab", WideStringToUtf8(L"ab", 2).c_str());
611 EXPECT_STREQ("a", WideStringToUtf8(L"a", -1).c_str());
612 EXPECT_STREQ("ab", WideStringToUtf8(L"ab", -1).c_str());
613}
614
615// Tests that Unicode code-points that have 8 to 11 bits are encoded
616// as 110xxxxx 10xxxxxx.
617TEST(WideStringToUtf8Test, CanEncode8To11Bits) {
618 // 000 1101 0011 => 110-00011 10-010011
619 EXPECT_STREQ("\xC3\x93", WideStringToUtf8(L"\xD3", 1).c_str());
620 EXPECT_STREQ("\xC3\x93", WideStringToUtf8(L"\xD3", -1).c_str());
621
622 // 101 0111 0110 => 110-10101 10-110110
zhanyong.wanb499e7b2010-10-11 06:28:54 +0000623 const wchar_t s[] = { 0x576, '\0' };
624 EXPECT_STREQ("\xD5\xB6", WideStringToUtf8(s, 1).c_str());
625 EXPECT_STREQ("\xD5\xB6", WideStringToUtf8(s, -1).c_str());
vladloseve006e682008-08-25 23:11:54 +0000626}
627
628// Tests that Unicode code-points that have 12 to 16 bits are encoded
629// as 1110xxxx 10xxxxxx 10xxxxxx.
630TEST(WideStringToUtf8Test, CanEncode12To16Bits) {
631 // 0000 1000 1101 0011 => 1110-0000 10-100011 10-010011
zhanyong.wanb499e7b2010-10-11 06:28:54 +0000632 const wchar_t s1[] = { 0x8D3, '\0' };
633 EXPECT_STREQ("\xE0\xA3\x93", WideStringToUtf8(s1, 1).c_str());
634 EXPECT_STREQ("\xE0\xA3\x93", WideStringToUtf8(s1, -1).c_str());
vladloseve006e682008-08-25 23:11:54 +0000635
636 // 1100 0111 0100 1101 => 1110-1100 10-011101 10-001101
zhanyong.wanb499e7b2010-10-11 06:28:54 +0000637 const wchar_t s2[] = { 0xC74D, '\0' };
638 EXPECT_STREQ("\xEC\x9D\x8D", WideStringToUtf8(s2, 1).c_str());
639 EXPECT_STREQ("\xEC\x9D\x8D", WideStringToUtf8(s2, -1).c_str());
vladloseve006e682008-08-25 23:11:54 +0000640}
641
642// Tests that the conversion stops when the function encounters \0 character.
643TEST(WideStringToUtf8Test, StopsOnNulCharacter) {
644 EXPECT_STREQ("ABC", WideStringToUtf8(L"ABC\0XYZ", 100).c_str());
645}
646
647// Tests that the conversion stops when the function reaches the limit
648// specified by the 'length' parameter.
649TEST(WideStringToUtf8Test, StopsWhenLengthLimitReached) {
650 EXPECT_STREQ("ABC", WideStringToUtf8(L"ABCDEF", 3).c_str());
651}
652
zhanyong.wan4cd62602009-02-23 23:21:55 +0000653#if !GTEST_WIDE_STRING_USES_UTF16_
vladloseve006e682008-08-25 23:11:54 +0000654// Tests that Unicode code-points that have 17 to 21 bits are encoded
655// as 11110xxx 10xxxxxx 10xxxxxx 10xxxxxx. This code may not compile
656// on the systems using UTF-16 encoding.
657TEST(WideStringToUtf8Test, CanEncode17To21Bits) {
658 // 0 0001 0000 1000 1101 0011 => 11110-000 10-010000 10-100011 10-010011
659 EXPECT_STREQ("\xF0\x90\xA3\x93", WideStringToUtf8(L"\x108D3", 1).c_str());
660 EXPECT_STREQ("\xF0\x90\xA3\x93", WideStringToUtf8(L"\x108D3", -1).c_str());
661
662 // 1 0000 1000 0110 0011 0100 => 11110-100 10-001000 10-011000 10-110100
663 EXPECT_STREQ("\xF4\x88\x98\xB4", WideStringToUtf8(L"\x108634", 1).c_str());
664 EXPECT_STREQ("\xF4\x88\x98\xB4", WideStringToUtf8(L"\x108634", -1).c_str());
665}
666
667// Tests that encoding an invalid code-point generates the expected result.
668TEST(WideStringToUtf8Test, CanEncodeInvalidCodePoint) {
669 EXPECT_STREQ("(Invalid Unicode 0xABCDFF)",
670 WideStringToUtf8(L"\xABCDFF", -1).c_str());
671}
zhanyong.wan4cd62602009-02-23 23:21:55 +0000672#else // !GTEST_WIDE_STRING_USES_UTF16_
vladloseve006e682008-08-25 23:11:54 +0000673// Tests that surrogate pairs are encoded correctly on the systems using
674// UTF-16 encoding in the wide strings.
675TEST(WideStringToUtf8Test, CanEncodeValidUtf16SUrrogatePairs) {
zhanyong.wanb499e7b2010-10-11 06:28:54 +0000676 const wchar_t s[] = { 0xD801, 0xDC00, '\0' };
677 EXPECT_STREQ("\xF0\x90\x90\x80", WideStringToUtf8(s, -1).c_str());
vladloseve006e682008-08-25 23:11:54 +0000678}
679
680// Tests that encoding an invalid UTF-16 surrogate pair
681// generates the expected result.
682TEST(WideStringToUtf8Test, CanEncodeInvalidUtf16SurrogatePair) {
683 // Leading surrogate is at the end of the string.
zhanyong.wanb499e7b2010-10-11 06:28:54 +0000684 const wchar_t s1[] = { 0xD800, '\0' };
685 EXPECT_STREQ("\xED\xA0\x80", WideStringToUtf8(s1, -1).c_str());
vladloseve006e682008-08-25 23:11:54 +0000686 // Leading surrogate is not followed by the trailing surrogate.
zhanyong.wanb499e7b2010-10-11 06:28:54 +0000687 const wchar_t s2[] = { 0xD800, 'M', '\0' };
688 EXPECT_STREQ("\xED\xA0\x80M", WideStringToUtf8(s2, -1).c_str());
vladloseve006e682008-08-25 23:11:54 +0000689 // Trailing surrogate appearas without a leading surrogate.
zhanyong.wanb499e7b2010-10-11 06:28:54 +0000690 const wchar_t s3[] = { 0xDC00, 'P', 'Q', 'R', '\0' };
691 EXPECT_STREQ("\xED\xB0\x80PQR", WideStringToUtf8(s3, -1).c_str());
vladloseve006e682008-08-25 23:11:54 +0000692}
zhanyong.wan4cd62602009-02-23 23:21:55 +0000693#endif // !GTEST_WIDE_STRING_USES_UTF16_
vladloseve006e682008-08-25 23:11:54 +0000694
695// Tests that codepoint concatenation works correctly.
zhanyong.wan4cd62602009-02-23 23:21:55 +0000696#if !GTEST_WIDE_STRING_USES_UTF16_
vladloseve006e682008-08-25 23:11:54 +0000697TEST(WideStringToUtf8Test, ConcatenatesCodepointsCorrectly) {
zhanyong.wanb499e7b2010-10-11 06:28:54 +0000698 const wchar_t s[] = { 0x108634, 0xC74D, '\n', 0x576, 0x8D3, 0x108634, '\0'};
vladloseve006e682008-08-25 23:11:54 +0000699 EXPECT_STREQ(
700 "\xF4\x88\x98\xB4"
701 "\xEC\x9D\x8D"
702 "\n"
703 "\xD5\xB6"
704 "\xE0\xA3\x93"
705 "\xF4\x88\x98\xB4",
zhanyong.wanb499e7b2010-10-11 06:28:54 +0000706 WideStringToUtf8(s, -1).c_str());
vladloseve006e682008-08-25 23:11:54 +0000707}
708#else
709TEST(WideStringToUtf8Test, ConcatenatesCodepointsCorrectly) {
zhanyong.wanb499e7b2010-10-11 06:28:54 +0000710 const wchar_t s[] = { 0xC74D, '\n', 0x576, 0x8D3, '\0'};
vladloseve006e682008-08-25 23:11:54 +0000711 EXPECT_STREQ(
712 "\xEC\x9D\x8D" "\n" "\xD5\xB6" "\xE0\xA3\x93",
zhanyong.wanb499e7b2010-10-11 06:28:54 +0000713 WideStringToUtf8(s, -1).c_str());
vladloseve006e682008-08-25 23:11:54 +0000714}
zhanyong.wan4cd62602009-02-23 23:21:55 +0000715#endif // !GTEST_WIDE_STRING_USES_UTF16_
shiqian4b6829f2008-07-03 22:38:12 +0000716
zhanyong.wan85f555a2009-09-21 19:42:03 +0000717// Tests the Random class.
718
719TEST(RandomDeathTest, GeneratesCrashesOnInvalidRange) {
720 testing::internal::Random random(42);
721 EXPECT_DEATH_IF_SUPPORTED(
722 random.Generate(0),
723 "Cannot generate a number in the range \\[0, 0\\)");
724 EXPECT_DEATH_IF_SUPPORTED(
725 random.Generate(testing::internal::Random::kMaxRange + 1),
726 "Generation of a number in \\[0, 2147483649\\) was requested, "
727 "but this can only generate numbers in \\[0, 2147483648\\)");
728}
729
730TEST(RandomTest, GeneratesNumbersWithinRange) {
731 const UInt32 kRange = 10000;
732 testing::internal::Random random(12345);
733 for (int i = 0; i < 10; i++) {
734 EXPECT_LT(random.Generate(kRange), kRange) << " for iteration " << i;
735 }
736
737 testing::internal::Random random2(testing::internal::Random::kMaxRange);
738 for (int i = 0; i < 10; i++) {
739 EXPECT_LT(random2.Generate(kRange), kRange) << " for iteration " << i;
740 }
741}
742
743TEST(RandomTest, RepeatsWhenReseeded) {
744 const int kSeed = 123;
745 const int kArraySize = 10;
746 const UInt32 kRange = 10000;
747 UInt32 values[kArraySize];
748
749 testing::internal::Random random(kSeed);
750 for (int i = 0; i < kArraySize; i++) {
751 values[i] = random.Generate(kRange);
752 }
753
754 random.Reseed(kSeed);
755 for (int i = 0; i < kArraySize; i++) {
756 EXPECT_EQ(values[i], random.Generate(kRange)) << " for iteration " << i;
757 }
758}
759
zhanyong.wan93d13a82010-02-25 01:09:07 +0000760// Tests STL container utilities.
zhanyong.wan449f84d2009-07-01 22:55:05 +0000761
zhanyong.wan93d13a82010-02-25 01:09:07 +0000762// Tests CountIf().
zhanyong.wan449f84d2009-07-01 22:55:05 +0000763
zhanyong.wan93d13a82010-02-25 01:09:07 +0000764static bool IsPositive(int n) { return n > 0; }
765
766TEST(ContainerUtilityTest, CountIf) {
767 std::vector<int> v;
768 EXPECT_EQ(0, CountIf(v, IsPositive)); // Works for an empty container.
769
770 v.push_back(-1);
771 v.push_back(0);
772 EXPECT_EQ(0, CountIf(v, IsPositive)); // Works when no value satisfies.
773
774 v.push_back(2);
775 v.push_back(-10);
776 v.push_back(10);
777 EXPECT_EQ(2, CountIf(v, IsPositive));
zhanyong.wan449f84d2009-07-01 22:55:05 +0000778}
779
zhanyong.wan93d13a82010-02-25 01:09:07 +0000780// Tests ForEach().
zhanyong.wan449f84d2009-07-01 22:55:05 +0000781
zhanyong.wan93d13a82010-02-25 01:09:07 +0000782static int g_sum = 0;
783static void Accumulate(int n) { g_sum += n; }
784
785TEST(ContainerUtilityTest, ForEach) {
786 std::vector<int> v;
787 g_sum = 0;
788 ForEach(v, Accumulate);
789 EXPECT_EQ(0, g_sum); // Works for an empty container;
790
791 g_sum = 0;
792 v.push_back(1);
793 ForEach(v, Accumulate);
794 EXPECT_EQ(1, g_sum); // Works for a container with one element.
795
796 g_sum = 0;
797 v.push_back(20);
798 v.push_back(300);
799 ForEach(v, Accumulate);
800 EXPECT_EQ(321, g_sum);
zhanyong.wan449f84d2009-07-01 22:55:05 +0000801}
shiqian4b6829f2008-07-03 22:38:12 +0000802
zhanyong.wan93d13a82010-02-25 01:09:07 +0000803// Tests GetElementOr().
804TEST(ContainerUtilityTest, GetElementOr) {
805 std::vector<char> a;
806 EXPECT_EQ('x', GetElementOr(a, 0, 'x'));
shiqian4b6829f2008-07-03 22:38:12 +0000807
zhanyong.wan93d13a82010-02-25 01:09:07 +0000808 a.push_back('a');
809 a.push_back('b');
810 EXPECT_EQ('a', GetElementOr(a, 0, 'x'));
811 EXPECT_EQ('b', GetElementOr(a, 1, 'x'));
812 EXPECT_EQ('x', GetElementOr(a, -2, 'x'));
813 EXPECT_EQ('x', GetElementOr(a, 2, 'x'));
shiqian4b6829f2008-07-03 22:38:12 +0000814}
815
zhanyong.wan93d13a82010-02-25 01:09:07 +0000816TEST(ContainerUtilityDeathTest, ShuffleRange) {
817 std::vector<int> a;
818 a.push_back(0);
819 a.push_back(1);
820 a.push_back(2);
zhanyong.wanf19450f2009-09-30 23:46:28 +0000821 testing::internal::Random random(1);
822
823 EXPECT_DEATH_IF_SUPPORTED(
zhanyong.wan93d13a82010-02-25 01:09:07 +0000824 ShuffleRange(&random, -1, 1, &a),
zhanyong.wanf19450f2009-09-30 23:46:28 +0000825 "Invalid shuffle range start -1: must be in range \\[0, 3\\]");
826 EXPECT_DEATH_IF_SUPPORTED(
zhanyong.wan93d13a82010-02-25 01:09:07 +0000827 ShuffleRange(&random, 4, 4, &a),
zhanyong.wanf19450f2009-09-30 23:46:28 +0000828 "Invalid shuffle range start 4: must be in range \\[0, 3\\]");
829 EXPECT_DEATH_IF_SUPPORTED(
zhanyong.wan93d13a82010-02-25 01:09:07 +0000830 ShuffleRange(&random, 3, 2, &a),
zhanyong.wanf19450f2009-09-30 23:46:28 +0000831 "Invalid shuffle range finish 2: must be in range \\[3, 3\\]");
832 EXPECT_DEATH_IF_SUPPORTED(
zhanyong.wan93d13a82010-02-25 01:09:07 +0000833 ShuffleRange(&random, 3, 4, &a),
zhanyong.wanf19450f2009-09-30 23:46:28 +0000834 "Invalid shuffle range finish 4: must be in range \\[3, 3\\]");
835}
836
837class VectorShuffleTest : public Test {
838 protected:
839 static const int kVectorSize = 20;
840
841 VectorShuffleTest() : random_(1) {
842 for (int i = 0; i < kVectorSize; i++) {
zhanyong.wan93d13a82010-02-25 01:09:07 +0000843 vector_.push_back(i);
zhanyong.wanf19450f2009-09-30 23:46:28 +0000844 }
845 }
846
847 static bool VectorIsCorrupt(const TestingVector& vector) {
zhanyong.wan93d13a82010-02-25 01:09:07 +0000848 if (kVectorSize != static_cast<int>(vector.size())) {
zhanyong.wanf19450f2009-09-30 23:46:28 +0000849 return true;
850 }
851
852 bool found_in_vector[kVectorSize] = { false };
zhanyong.wan93d13a82010-02-25 01:09:07 +0000853 for (size_t i = 0; i < vector.size(); i++) {
854 const int e = vector[i];
zhanyong.wanf19450f2009-09-30 23:46:28 +0000855 if (e < 0 || e >= kVectorSize || found_in_vector[e]) {
856 return true;
857 }
858 found_in_vector[e] = true;
859 }
860
861 // Vector size is correct, elements' range is correct, no
862 // duplicate elements. Therefore no corruption has occurred.
863 return false;
864 }
865
866 static bool VectorIsNotCorrupt(const TestingVector& vector) {
867 return !VectorIsCorrupt(vector);
868 }
869
870 static bool RangeIsShuffled(const TestingVector& vector, int begin, int end) {
871 for (int i = begin; i < end; i++) {
zhanyong.wan93d13a82010-02-25 01:09:07 +0000872 if (i != vector[i]) {
zhanyong.wanf19450f2009-09-30 23:46:28 +0000873 return true;
874 }
875 }
876 return false;
877 }
878
879 static bool RangeIsUnshuffled(
880 const TestingVector& vector, int begin, int end) {
881 return !RangeIsShuffled(vector, begin, end);
882 }
883
884 static bool VectorIsShuffled(const TestingVector& vector) {
zhanyong.wanb03ca472010-02-25 22:15:27 +0000885 return RangeIsShuffled(vector, 0, static_cast<int>(vector.size()));
zhanyong.wanf19450f2009-09-30 23:46:28 +0000886 }
887
888 static bool VectorIsUnshuffled(const TestingVector& vector) {
889 return !VectorIsShuffled(vector);
890 }
891
892 testing::internal::Random random_;
893 TestingVector vector_;
894}; // class VectorShuffleTest
895
896const int VectorShuffleTest::kVectorSize;
897
898TEST_F(VectorShuffleTest, HandlesEmptyRange) {
899 // Tests an empty range at the beginning...
zhanyong.wan93d13a82010-02-25 01:09:07 +0000900 ShuffleRange(&random_, 0, 0, &vector_);
zhanyong.wanf19450f2009-09-30 23:46:28 +0000901 ASSERT_PRED1(VectorIsNotCorrupt, vector_);
902 ASSERT_PRED1(VectorIsUnshuffled, vector_);
903
904 // ...in the middle...
zhanyong.wan93d13a82010-02-25 01:09:07 +0000905 ShuffleRange(&random_, kVectorSize/2, kVectorSize/2, &vector_);
zhanyong.wanf19450f2009-09-30 23:46:28 +0000906 ASSERT_PRED1(VectorIsNotCorrupt, vector_);
907 ASSERT_PRED1(VectorIsUnshuffled, vector_);
908
909 // ...at the end...
zhanyong.wan93d13a82010-02-25 01:09:07 +0000910 ShuffleRange(&random_, kVectorSize - 1, kVectorSize - 1, &vector_);
zhanyong.wanf19450f2009-09-30 23:46:28 +0000911 ASSERT_PRED1(VectorIsNotCorrupt, vector_);
912 ASSERT_PRED1(VectorIsUnshuffled, vector_);
913
914 // ...and past the end.
zhanyong.wan93d13a82010-02-25 01:09:07 +0000915 ShuffleRange(&random_, kVectorSize, kVectorSize, &vector_);
zhanyong.wanf19450f2009-09-30 23:46:28 +0000916 ASSERT_PRED1(VectorIsNotCorrupt, vector_);
917 ASSERT_PRED1(VectorIsUnshuffled, vector_);
918}
919
920TEST_F(VectorShuffleTest, HandlesRangeOfSizeOne) {
921 // Tests a size one range at the beginning...
zhanyong.wan93d13a82010-02-25 01:09:07 +0000922 ShuffleRange(&random_, 0, 1, &vector_);
zhanyong.wanf19450f2009-09-30 23:46:28 +0000923 ASSERT_PRED1(VectorIsNotCorrupt, vector_);
924 ASSERT_PRED1(VectorIsUnshuffled, vector_);
925
926 // ...in the middle...
zhanyong.wan93d13a82010-02-25 01:09:07 +0000927 ShuffleRange(&random_, kVectorSize/2, kVectorSize/2 + 1, &vector_);
zhanyong.wanf19450f2009-09-30 23:46:28 +0000928 ASSERT_PRED1(VectorIsNotCorrupt, vector_);
929 ASSERT_PRED1(VectorIsUnshuffled, vector_);
930
931 // ...and at the end.
zhanyong.wan93d13a82010-02-25 01:09:07 +0000932 ShuffleRange(&random_, kVectorSize - 1, kVectorSize, &vector_);
zhanyong.wanf19450f2009-09-30 23:46:28 +0000933 ASSERT_PRED1(VectorIsNotCorrupt, vector_);
934 ASSERT_PRED1(VectorIsUnshuffled, vector_);
935}
936
937// Because we use our own random number generator and a fixed seed,
938// we can guarantee that the following "random" tests will succeed.
939
940TEST_F(VectorShuffleTest, ShufflesEntireVector) {
zhanyong.wan93d13a82010-02-25 01:09:07 +0000941 Shuffle(&random_, &vector_);
zhanyong.wanf19450f2009-09-30 23:46:28 +0000942 ASSERT_PRED1(VectorIsNotCorrupt, vector_);
943 EXPECT_FALSE(VectorIsUnshuffled(vector_)) << vector_;
944
945 // Tests the first and last elements in particular to ensure that
946 // there are no off-by-one problems in our shuffle algorithm.
zhanyong.wan93d13a82010-02-25 01:09:07 +0000947 EXPECT_NE(0, vector_[0]);
948 EXPECT_NE(kVectorSize - 1, vector_[kVectorSize - 1]);
zhanyong.wanf19450f2009-09-30 23:46:28 +0000949}
950
951TEST_F(VectorShuffleTest, ShufflesStartOfVector) {
952 const int kRangeSize = kVectorSize/2;
953
zhanyong.wan93d13a82010-02-25 01:09:07 +0000954 ShuffleRange(&random_, 0, kRangeSize, &vector_);
zhanyong.wanf19450f2009-09-30 23:46:28 +0000955
956 ASSERT_PRED1(VectorIsNotCorrupt, vector_);
957 EXPECT_PRED3(RangeIsShuffled, vector_, 0, kRangeSize);
958 EXPECT_PRED3(RangeIsUnshuffled, vector_, kRangeSize, kVectorSize);
959}
960
961TEST_F(VectorShuffleTest, ShufflesEndOfVector) {
962 const int kRangeSize = kVectorSize / 2;
zhanyong.wan93d13a82010-02-25 01:09:07 +0000963 ShuffleRange(&random_, kRangeSize, kVectorSize, &vector_);
zhanyong.wanf19450f2009-09-30 23:46:28 +0000964
965 ASSERT_PRED1(VectorIsNotCorrupt, vector_);
966 EXPECT_PRED3(RangeIsUnshuffled, vector_, 0, kRangeSize);
967 EXPECT_PRED3(RangeIsShuffled, vector_, kRangeSize, kVectorSize);
968}
969
970TEST_F(VectorShuffleTest, ShufflesMiddleOfVector) {
971 int kRangeSize = kVectorSize/3;
zhanyong.wan93d13a82010-02-25 01:09:07 +0000972 ShuffleRange(&random_, kRangeSize, 2*kRangeSize, &vector_);
zhanyong.wanf19450f2009-09-30 23:46:28 +0000973
974 ASSERT_PRED1(VectorIsNotCorrupt, vector_);
975 EXPECT_PRED3(RangeIsUnshuffled, vector_, 0, kRangeSize);
976 EXPECT_PRED3(RangeIsShuffled, vector_, kRangeSize, 2*kRangeSize);
977 EXPECT_PRED3(RangeIsUnshuffled, vector_, 2*kRangeSize, kVectorSize);
978}
979
980TEST_F(VectorShuffleTest, ShufflesRepeatably) {
981 TestingVector vector2;
982 for (int i = 0; i < kVectorSize; i++) {
zhanyong.wan93d13a82010-02-25 01:09:07 +0000983 vector2.push_back(i);
zhanyong.wanf19450f2009-09-30 23:46:28 +0000984 }
985
986 random_.Reseed(1234);
zhanyong.wan93d13a82010-02-25 01:09:07 +0000987 Shuffle(&random_, &vector_);
zhanyong.wanf19450f2009-09-30 23:46:28 +0000988 random_.Reseed(1234);
zhanyong.wan93d13a82010-02-25 01:09:07 +0000989 Shuffle(&random_, &vector2);
zhanyong.wanf19450f2009-09-30 23:46:28 +0000990
991 ASSERT_PRED1(VectorIsNotCorrupt, vector_);
992 ASSERT_PRED1(VectorIsNotCorrupt, vector2);
993
994 for (int i = 0; i < kVectorSize; i++) {
zhanyong.wan93d13a82010-02-25 01:09:07 +0000995 EXPECT_EQ(vector_[i], vector2[i]) << " where i is " << i;
zhanyong.wanf19450f2009-09-30 23:46:28 +0000996 }
997}
998
zhanyong.wanf39160b2009-09-04 18:30:25 +0000999// Tests the size of the AssertHelper class.
shiqian4b6829f2008-07-03 22:38:12 +00001000
zhanyong.wanf39160b2009-09-04 18:30:25 +00001001TEST(AssertHelperTest, AssertHelperIsSmall) {
zhanyong.wan89be5762009-09-01 18:53:56 +00001002 // To avoid breaking clients that use lots of assertions in one
zhanyong.wanf39160b2009-09-04 18:30:25 +00001003 // function, we cannot grow the size of AssertHelper.
1004 EXPECT_LE(sizeof(testing::internal::AssertHelper), sizeof(void*));
zhanyong.wan89be5762009-09-01 18:53:56 +00001005}
1006
shiqian4b6829f2008-07-03 22:38:12 +00001007// Tests String::EndsWithCaseInsensitive().
1008TEST(StringTest, EndsWithCaseInsensitive) {
jgm@google.com03c31492012-11-15 15:47:38 +00001009 EXPECT_TRUE(String::EndsWithCaseInsensitive("foobar", "BAR"));
1010 EXPECT_TRUE(String::EndsWithCaseInsensitive("foobaR", "bar"));
1011 EXPECT_TRUE(String::EndsWithCaseInsensitive("foobar", ""));
1012 EXPECT_TRUE(String::EndsWithCaseInsensitive("", ""));
shiqian4b6829f2008-07-03 22:38:12 +00001013
jgm@google.com03c31492012-11-15 15:47:38 +00001014 EXPECT_FALSE(String::EndsWithCaseInsensitive("Foobar", "foo"));
1015 EXPECT_FALSE(String::EndsWithCaseInsensitive("foobar", "Foo"));
1016 EXPECT_FALSE(String::EndsWithCaseInsensitive("", "foo"));
shiqian4b6829f2008-07-03 22:38:12 +00001017}
1018
zhanyong.wan98efcc42009-04-28 00:28:09 +00001019// C++Builder's preprocessor is buggy; it fails to expand macros that
1020// appear in macro parameters after wide char literals. Provide an alias
1021// for NULL as a workaround.
1022static const wchar_t* const kNull = NULL;
1023
shiqiane8ff1482008-09-08 17:55:52 +00001024// Tests String::CaseInsensitiveWideCStringEquals
1025TEST(StringTest, CaseInsensitiveWideCStringEquals) {
1026 EXPECT_TRUE(String::CaseInsensitiveWideCStringEquals(NULL, NULL));
zhanyong.wan98efcc42009-04-28 00:28:09 +00001027 EXPECT_FALSE(String::CaseInsensitiveWideCStringEquals(kNull, L""));
1028 EXPECT_FALSE(String::CaseInsensitiveWideCStringEquals(L"", kNull));
1029 EXPECT_FALSE(String::CaseInsensitiveWideCStringEquals(kNull, L"foobar"));
1030 EXPECT_FALSE(String::CaseInsensitiveWideCStringEquals(L"foobar", kNull));
shiqiane8ff1482008-09-08 17:55:52 +00001031 EXPECT_TRUE(String::CaseInsensitiveWideCStringEquals(L"foobar", L"foobar"));
1032 EXPECT_TRUE(String::CaseInsensitiveWideCStringEquals(L"foobar", L"FOOBAR"));
1033 EXPECT_TRUE(String::CaseInsensitiveWideCStringEquals(L"FOOBAR", L"foobar"));
1034}
1035
zhanyong.wan4cd62602009-02-23 23:21:55 +00001036#if GTEST_OS_WINDOWS
shiqian4b6829f2008-07-03 22:38:12 +00001037
1038// Tests String::ShowWideCString().
1039TEST(StringTest, ShowWideCString) {
1040 EXPECT_STREQ("(null)",
1041 String::ShowWideCString(NULL).c_str());
1042 EXPECT_STREQ("", String::ShowWideCString(L"").c_str());
1043 EXPECT_STREQ("foo", String::ShowWideCString(L"foo").c_str());
1044}
1045
zhanyong.wan733a54a2011-02-22 22:08:59 +00001046# if GTEST_OS_WINDOWS_MOBILE
shiqiandd4a17b2008-07-31 18:34:08 +00001047TEST(StringTest, AnsiAndUtf16Null) {
1048 EXPECT_EQ(NULL, String::AnsiToUtf16(NULL));
1049 EXPECT_EQ(NULL, String::Utf16ToAnsi(NULL));
1050}
1051
1052TEST(StringTest, AnsiAndUtf16ConvertBasic) {
1053 const char* ansi = String::Utf16ToAnsi(L"str");
1054 EXPECT_STREQ("str", ansi);
1055 delete [] ansi;
1056 const WCHAR* utf16 = String::AnsiToUtf16("str");
zhanyong.wan4e7e2fc2009-06-19 00:24:28 +00001057 EXPECT_EQ(0, wcsncmp(L"str", utf16, 3));
shiqiandd4a17b2008-07-31 18:34:08 +00001058 delete [] utf16;
1059}
1060
1061TEST(StringTest, AnsiAndUtf16ConvertPathChars) {
1062 const char* ansi = String::Utf16ToAnsi(L".:\\ \"*?");
1063 EXPECT_STREQ(".:\\ \"*?", ansi);
1064 delete [] ansi;
1065 const WCHAR* utf16 = String::AnsiToUtf16(".:\\ \"*?");
zhanyong.wan4e7e2fc2009-06-19 00:24:28 +00001066 EXPECT_EQ(0, wcsncmp(L".:\\ \"*?", utf16, 3));
shiqiandd4a17b2008-07-31 18:34:08 +00001067 delete [] utf16;
1068}
zhanyong.wan733a54a2011-02-22 22:08:59 +00001069# endif // GTEST_OS_WINDOWS_MOBILE
shiqiandd4a17b2008-07-31 18:34:08 +00001070
shiqian4b6829f2008-07-03 22:38:12 +00001071#endif // GTEST_OS_WINDOWS
1072
1073// Tests TestProperty construction.
1074TEST(TestPropertyTest, StringValue) {
1075 TestProperty property("key", "1");
1076 EXPECT_STREQ("key", property.key());
1077 EXPECT_STREQ("1", property.value());
1078}
1079
1080// Tests TestProperty replacing a value.
1081TEST(TestPropertyTest, ReplaceStringValue) {
1082 TestProperty property("key", "1");
1083 EXPECT_STREQ("1", property.value());
1084 property.SetValue("2");
1085 EXPECT_STREQ("2", property.value());
1086}
1087
zhanyong.wan98efcc42009-04-28 00:28:09 +00001088// AddFatalFailure() and AddNonfatalFailure() must be stand-alone
1089// functions (i.e. their definitions cannot be inlined at the call
1090// sites), or C++Builder won't compile the code.
1091static void AddFatalFailure() {
1092 FAIL() << "Expected fatal failure.";
1093}
1094
1095static void AddNonfatalFailure() {
1096 ADD_FAILURE() << "Expected non-fatal failure.";
1097}
1098
shiqiane44602e2008-10-11 07:20:02 +00001099class ScopedFakeTestPartResultReporterTest : public Test {
tsunanetacd0f322009-05-18 20:53:57 +00001100 public: // Must be public and not protected due to a bug in g++ 3.4.2.
shiqiane44602e2008-10-11 07:20:02 +00001101 enum FailureMode {
1102 FATAL_FAILURE,
1103 NONFATAL_FAILURE
1104 };
1105 static void AddFailure(FailureMode failure) {
1106 if (failure == FATAL_FAILURE) {
zhanyong.wan98efcc42009-04-28 00:28:09 +00001107 AddFatalFailure();
shiqiane44602e2008-10-11 07:20:02 +00001108 } else {
zhanyong.wan98efcc42009-04-28 00:28:09 +00001109 AddNonfatalFailure();
shiqiane44602e2008-10-11 07:20:02 +00001110 }
1111 }
shiqian4b6829f2008-07-03 22:38:12 +00001112};
1113
shiqian4b6829f2008-07-03 22:38:12 +00001114// Tests that ScopedFakeTestPartResultReporter intercepts test
1115// failures.
shiqiane44602e2008-10-11 07:20:02 +00001116TEST_F(ScopedFakeTestPartResultReporterTest, InterceptsTestFailures) {
shiqian4b6829f2008-07-03 22:38:12 +00001117 TestPartResultArray results;
1118 {
shiqiane44602e2008-10-11 07:20:02 +00001119 ScopedFakeTestPartResultReporter reporter(
1120 ScopedFakeTestPartResultReporter::INTERCEPT_ONLY_CURRENT_THREAD,
1121 &results);
1122 AddFailure(NONFATAL_FAILURE);
1123 AddFailure(FATAL_FAILURE);
shiqian4b6829f2008-07-03 22:38:12 +00001124 }
1125
1126 EXPECT_EQ(2, results.size());
1127 EXPECT_TRUE(results.GetTestPartResult(0).nonfatally_failed());
1128 EXPECT_TRUE(results.GetTestPartResult(1).fatally_failed());
1129}
1130
shiqiane44602e2008-10-11 07:20:02 +00001131TEST_F(ScopedFakeTestPartResultReporterTest, DeprecatedConstructor) {
1132 TestPartResultArray results;
1133 {
1134 // Tests, that the deprecated constructor still works.
1135 ScopedFakeTestPartResultReporter reporter(&results);
1136 AddFailure(NONFATAL_FAILURE);
1137 }
1138 EXPECT_EQ(1, results.size());
1139}
1140
zhanyong.wanf6fb5322010-03-04 22:15:53 +00001141#if GTEST_IS_THREADSAFE
shiqiane44602e2008-10-11 07:20:02 +00001142
1143class ScopedFakeTestPartResultReporterWithThreadsTest
1144 : public ScopedFakeTestPartResultReporterTest {
1145 protected:
1146 static void AddFailureInOtherThread(FailureMode failure) {
zhanyong.wanf6fb5322010-03-04 22:15:53 +00001147 ThreadWithParam<FailureMode> thread(&AddFailure, failure, NULL);
1148 thread.Join();
shiqiane44602e2008-10-11 07:20:02 +00001149 }
1150};
1151
1152TEST_F(ScopedFakeTestPartResultReporterWithThreadsTest,
1153 InterceptsTestFailuresInAllThreads) {
1154 TestPartResultArray results;
1155 {
1156 ScopedFakeTestPartResultReporter reporter(
1157 ScopedFakeTestPartResultReporter::INTERCEPT_ALL_THREADS, &results);
1158 AddFailure(NONFATAL_FAILURE);
1159 AddFailure(FATAL_FAILURE);
1160 AddFailureInOtherThread(NONFATAL_FAILURE);
1161 AddFailureInOtherThread(FATAL_FAILURE);
1162 }
1163
1164 EXPECT_EQ(4, results.size());
1165 EXPECT_TRUE(results.GetTestPartResult(0).nonfatally_failed());
1166 EXPECT_TRUE(results.GetTestPartResult(1).fatally_failed());
1167 EXPECT_TRUE(results.GetTestPartResult(2).nonfatally_failed());
1168 EXPECT_TRUE(results.GetTestPartResult(3).fatally_failed());
1169}
1170
zhanyong.wanf6fb5322010-03-04 22:15:53 +00001171#endif // GTEST_IS_THREADSAFE
shiqiane44602e2008-10-11 07:20:02 +00001172
zhanyong.wan98efcc42009-04-28 00:28:09 +00001173// Tests EXPECT_FATAL_FAILURE{,ON_ALL_THREADS}. Makes sure that they
1174// work even if the failure is generated in a called function rather than
1175// the current context.
shiqiane44602e2008-10-11 07:20:02 +00001176
zhanyong.wane0ca02f2009-02-06 00:47:20 +00001177typedef ScopedFakeTestPartResultReporterTest ExpectFatalFailureTest;
shiqiane44602e2008-10-11 07:20:02 +00001178
zhanyong.wane0ca02f2009-02-06 00:47:20 +00001179TEST_F(ExpectFatalFailureTest, CatchesFatalFaliure) {
zhanyong.wan98efcc42009-04-28 00:28:09 +00001180 EXPECT_FATAL_FAILURE(AddFatalFailure(), "Expected fatal failure.");
shiqiane44602e2008-10-11 07:20:02 +00001181}
1182
zhanyong.wan375ce982010-09-27 17:42:52 +00001183#if GTEST_HAS_GLOBAL_STRING
1184TEST_F(ExpectFatalFailureTest, AcceptsStringObject) {
1185 EXPECT_FATAL_FAILURE(AddFatalFailure(), ::string("Expected fatal failure."));
1186}
1187#endif
1188
1189TEST_F(ExpectFatalFailureTest, AcceptsStdStringObject) {
1190 EXPECT_FATAL_FAILURE(AddFatalFailure(),
1191 ::std::string("Expected fatal failure."));
1192}
1193
zhanyong.wane0ca02f2009-02-06 00:47:20 +00001194TEST_F(ExpectFatalFailureTest, CatchesFatalFailureOnAllThreads) {
1195 // We have another test below to verify that the macro catches fatal
1196 // failures generated on another thread.
zhanyong.wan98efcc42009-04-28 00:28:09 +00001197 EXPECT_FATAL_FAILURE_ON_ALL_THREADS(AddFatalFailure(),
shiqiane44602e2008-10-11 07:20:02 +00001198 "Expected fatal failure.");
1199}
1200
zhanyong.wan98efcc42009-04-28 00:28:09 +00001201#ifdef __BORLANDC__
1202// Silences warnings: "Condition is always true"
zhanyong.wan733a54a2011-02-22 22:08:59 +00001203# pragma option push -w-ccc
zhanyong.wan98efcc42009-04-28 00:28:09 +00001204#endif
1205
zhanyong.wane0ca02f2009-02-06 00:47:20 +00001206// Tests that EXPECT_FATAL_FAILURE() can be used in a non-void
1207// function even when the statement in it contains ASSERT_*.
1208
1209int NonVoidFunction() {
1210 EXPECT_FATAL_FAILURE(ASSERT_TRUE(false), "");
1211 EXPECT_FATAL_FAILURE_ON_ALL_THREADS(FAIL(), "");
1212 return 0;
shiqiane44602e2008-10-11 07:20:02 +00001213}
1214
zhanyong.wane0ca02f2009-02-06 00:47:20 +00001215TEST_F(ExpectFatalFailureTest, CanBeUsedInNonVoidFunction) {
1216 NonVoidFunction();
1217}
1218
1219// Tests that EXPECT_FATAL_FAILURE(statement, ...) doesn't abort the
1220// current function even though 'statement' generates a fatal failure.
1221
1222void DoesNotAbortHelper(bool* aborted) {
1223 EXPECT_FATAL_FAILURE(ASSERT_TRUE(false), "");
1224 EXPECT_FATAL_FAILURE_ON_ALL_THREADS(FAIL(), "");
1225
1226 *aborted = false;
1227}
1228
zhanyong.wan98efcc42009-04-28 00:28:09 +00001229#ifdef __BORLANDC__
vladlosevd6b49412010-04-07 05:32:34 +00001230// Restores warnings after previous "#pragma option push" suppressed them.
zhanyong.wan733a54a2011-02-22 22:08:59 +00001231# pragma option pop
zhanyong.wan98efcc42009-04-28 00:28:09 +00001232#endif
1233
zhanyong.wane0ca02f2009-02-06 00:47:20 +00001234TEST_F(ExpectFatalFailureTest, DoesNotAbort) {
1235 bool aborted = true;
1236 DoesNotAbortHelper(&aborted);
1237 EXPECT_FALSE(aborted);
1238}
1239
1240// Tests that the EXPECT_FATAL_FAILURE{,_ON_ALL_THREADS} accepts a
1241// statement that contains a macro which expands to code containing an
1242// unprotected comma.
shiqiane44602e2008-10-11 07:20:02 +00001243
1244static int global_var = 0;
1245#define GTEST_USE_UNPROTECTED_COMMA_ global_var++, global_var++
1246
zhanyong.wane0ca02f2009-02-06 00:47:20 +00001247TEST_F(ExpectFatalFailureTest, AcceptsMacroThatExpandsToUnprotectedComma) {
zhanyong.waned1042b2011-03-05 08:04:01 +00001248#ifndef __BORLANDC__
1249 // ICE's in C++Builder.
shiqiane44602e2008-10-11 07:20:02 +00001250 EXPECT_FATAL_FAILURE({
1251 GTEST_USE_UNPROTECTED_COMMA_;
zhanyong.wan98efcc42009-04-28 00:28:09 +00001252 AddFatalFailure();
shiqiane44602e2008-10-11 07:20:02 +00001253 }, "");
zhanyong.wan98efcc42009-04-28 00:28:09 +00001254#endif
shiqiane44602e2008-10-11 07:20:02 +00001255
1256 EXPECT_FATAL_FAILURE_ON_ALL_THREADS({
1257 GTEST_USE_UNPROTECTED_COMMA_;
zhanyong.wan98efcc42009-04-28 00:28:09 +00001258 AddFatalFailure();
shiqiane44602e2008-10-11 07:20:02 +00001259 }, "");
zhanyong.wane0ca02f2009-02-06 00:47:20 +00001260}
shiqiane44602e2008-10-11 07:20:02 +00001261
zhanyong.wane0ca02f2009-02-06 00:47:20 +00001262// Tests EXPECT_NONFATAL_FAILURE{,ON_ALL_THREADS}.
1263
1264typedef ScopedFakeTestPartResultReporterTest ExpectNonfatalFailureTest;
1265
1266TEST_F(ExpectNonfatalFailureTest, CatchesNonfatalFailure) {
zhanyong.wan98efcc42009-04-28 00:28:09 +00001267 EXPECT_NONFATAL_FAILURE(AddNonfatalFailure(),
zhanyong.wane0ca02f2009-02-06 00:47:20 +00001268 "Expected non-fatal failure.");
1269}
1270
zhanyong.wan375ce982010-09-27 17:42:52 +00001271#if GTEST_HAS_GLOBAL_STRING
1272TEST_F(ExpectNonfatalFailureTest, AcceptsStringObject) {
1273 EXPECT_NONFATAL_FAILURE(AddNonfatalFailure(),
1274 ::string("Expected non-fatal failure."));
1275}
1276#endif
1277
1278TEST_F(ExpectNonfatalFailureTest, AcceptsStdStringObject) {
1279 EXPECT_NONFATAL_FAILURE(AddNonfatalFailure(),
1280 ::std::string("Expected non-fatal failure."));
1281}
1282
zhanyong.wane0ca02f2009-02-06 00:47:20 +00001283TEST_F(ExpectNonfatalFailureTest, CatchesNonfatalFailureOnAllThreads) {
1284 // We have another test below to verify that the macro catches
1285 // non-fatal failures generated on another thread.
zhanyong.wan98efcc42009-04-28 00:28:09 +00001286 EXPECT_NONFATAL_FAILURE_ON_ALL_THREADS(AddNonfatalFailure(),
zhanyong.wane0ca02f2009-02-06 00:47:20 +00001287 "Expected non-fatal failure.");
1288}
1289
1290// Tests that the EXPECT_NONFATAL_FAILURE{,_ON_ALL_THREADS} accepts a
1291// statement that contains a macro which expands to code containing an
1292// unprotected comma.
1293TEST_F(ExpectNonfatalFailureTest, AcceptsMacroThatExpandsToUnprotectedComma) {
shiqiane44602e2008-10-11 07:20:02 +00001294 EXPECT_NONFATAL_FAILURE({
1295 GTEST_USE_UNPROTECTED_COMMA_;
zhanyong.wan98efcc42009-04-28 00:28:09 +00001296 AddNonfatalFailure();
shiqiane44602e2008-10-11 07:20:02 +00001297 }, "");
1298
1299 EXPECT_NONFATAL_FAILURE_ON_ALL_THREADS({
1300 GTEST_USE_UNPROTECTED_COMMA_;
zhanyong.wan98efcc42009-04-28 00:28:09 +00001301 AddNonfatalFailure();
shiqiane44602e2008-10-11 07:20:02 +00001302 }, "");
1303}
1304
zhanyong.wanf6fb5322010-03-04 22:15:53 +00001305#if GTEST_IS_THREADSAFE
shiqiane44602e2008-10-11 07:20:02 +00001306
1307typedef ScopedFakeTestPartResultReporterWithThreadsTest
1308 ExpectFailureWithThreadsTest;
1309
1310TEST_F(ExpectFailureWithThreadsTest, ExpectFatalFailureOnAllThreads) {
1311 EXPECT_FATAL_FAILURE_ON_ALL_THREADS(AddFailureInOtherThread(FATAL_FAILURE),
1312 "Expected fatal failure.");
1313}
1314
1315TEST_F(ExpectFailureWithThreadsTest, ExpectNonFatalFailureOnAllThreads) {
1316 EXPECT_NONFATAL_FAILURE_ON_ALL_THREADS(
1317 AddFailureInOtherThread(NONFATAL_FAILURE), "Expected non-fatal failure.");
1318}
1319
zhanyong.wanf6fb5322010-03-04 22:15:53 +00001320#endif // GTEST_IS_THREADSAFE
shiqiane44602e2008-10-11 07:20:02 +00001321
zhanyong.wan1cdc7632009-07-16 00:36:55 +00001322// Tests the TestProperty class.
1323
1324TEST(TestPropertyTest, ConstructorWorks) {
1325 const TestProperty property("key", "value");
1326 EXPECT_STREQ("key", property.key());
1327 EXPECT_STREQ("value", property.value());
1328}
1329
1330TEST(TestPropertyTest, SetValue) {
1331 TestProperty property("key", "value_1");
1332 EXPECT_STREQ("key", property.key());
1333 property.SetValue("value_2");
1334 EXPECT_STREQ("key", property.key());
1335 EXPECT_STREQ("value_2", property.value());
1336}
1337
shiqian4b6829f2008-07-03 22:38:12 +00001338// Tests the TestResult class
1339
1340// The test fixture for testing TestResult.
shiqian760af5c2008-08-06 21:43:15 +00001341class TestResultTest : public Test {
shiqian4b6829f2008-07-03 22:38:12 +00001342 protected:
zhanyong.wan93d13a82010-02-25 01:09:07 +00001343 typedef std::vector<TestPartResult> TPRVector;
shiqian4b6829f2008-07-03 22:38:12 +00001344
1345 // We make use of 2 TestPartResult objects,
1346 TestPartResult * pr1, * pr2;
1347
1348 // ... and 3 TestResult objects.
1349 TestResult * r0, * r1, * r2;
1350
1351 virtual void SetUp() {
1352 // pr1 is for success.
zhanyong.wan334aaea2009-09-18 18:16:20 +00001353 pr1 = new TestPartResult(TestPartResult::kSuccess,
1354 "foo/bar.cc",
1355 10,
1356 "Success!");
shiqian4b6829f2008-07-03 22:38:12 +00001357
1358 // pr2 is for fatal failure.
zhanyong.wan334aaea2009-09-18 18:16:20 +00001359 pr2 = new TestPartResult(TestPartResult::kFatalFailure,
1360 "foo/bar.cc",
shiqian760af5c2008-08-06 21:43:15 +00001361 -1, // This line number means "unknown"
1362 "Failure!");
shiqian4b6829f2008-07-03 22:38:12 +00001363
1364 // Creates the TestResult objects.
1365 r0 = new TestResult();
1366 r1 = new TestResult();
1367 r2 = new TestResult();
1368
1369 // In order to test TestResult, we need to modify its internal
zhanyong.wan93d13a82010-02-25 01:09:07 +00001370 // state, in particular the TestPartResult vector it holds.
1371 // test_part_results() returns a const reference to this vector.
shiqian4b6829f2008-07-03 22:38:12 +00001372 // We cast it to a non-const object s.t. it can be modified (yes,
1373 // this is a hack).
zhanyong.wan93d13a82010-02-25 01:09:07 +00001374 TPRVector* results1 = const_cast<TPRVector*>(
zhanyong.wanb7ec0f72009-07-01 04:58:05 +00001375 &TestResultAccessor::test_part_results(*r1));
zhanyong.wan93d13a82010-02-25 01:09:07 +00001376 TPRVector* results2 = const_cast<TPRVector*>(
zhanyong.wanb7ec0f72009-07-01 04:58:05 +00001377 &TestResultAccessor::test_part_results(*r2));
shiqian4b6829f2008-07-03 22:38:12 +00001378
1379 // r0 is an empty TestResult.
1380
1381 // r1 contains a single SUCCESS TestPartResult.
zhanyong.wan93d13a82010-02-25 01:09:07 +00001382 results1->push_back(*pr1);
shiqian4b6829f2008-07-03 22:38:12 +00001383
1384 // r2 contains a SUCCESS, and a FAILURE.
zhanyong.wan93d13a82010-02-25 01:09:07 +00001385 results2->push_back(*pr1);
1386 results2->push_back(*pr2);
shiqian4b6829f2008-07-03 22:38:12 +00001387 }
1388
1389 virtual void TearDown() {
1390 delete pr1;
1391 delete pr2;
1392
1393 delete r0;
1394 delete r1;
1395 delete r2;
1396 }
zhanyong.wan9644db82009-06-24 23:02:50 +00001397
1398 // Helper that compares two two TestPartResults.
zhanyong.wan449f84d2009-07-01 22:55:05 +00001399 static void CompareTestPartResult(const TestPartResult& expected,
1400 const TestPartResult& actual) {
1401 EXPECT_EQ(expected.type(), actual.type());
1402 EXPECT_STREQ(expected.file_name(), actual.file_name());
1403 EXPECT_EQ(expected.line_number(), actual.line_number());
1404 EXPECT_STREQ(expected.summary(), actual.summary());
1405 EXPECT_STREQ(expected.message(), actual.message());
1406 EXPECT_EQ(expected.passed(), actual.passed());
1407 EXPECT_EQ(expected.failed(), actual.failed());
1408 EXPECT_EQ(expected.nonfatally_failed(), actual.nonfatally_failed());
1409 EXPECT_EQ(expected.fatally_failed(), actual.fatally_failed());
zhanyong.wan9644db82009-06-24 23:02:50 +00001410 }
shiqian4b6829f2008-07-03 22:38:12 +00001411};
1412
zhanyong.wanb7ec0f72009-07-01 04:58:05 +00001413// Tests TestResult::total_part_count().
shiqian4b6829f2008-07-03 22:38:12 +00001414TEST_F(TestResultTest, total_part_count) {
zhanyong.wanb7ec0f72009-07-01 04:58:05 +00001415 ASSERT_EQ(0, r0->total_part_count());
1416 ASSERT_EQ(1, r1->total_part_count());
1417 ASSERT_EQ(2, r2->total_part_count());
shiqian4b6829f2008-07-03 22:38:12 +00001418}
1419
zhanyong.wan9644db82009-06-24 23:02:50 +00001420// Tests TestResult::Passed().
shiqian4b6829f2008-07-03 22:38:12 +00001421TEST_F(TestResultTest, Passed) {
1422 ASSERT_TRUE(r0->Passed());
1423 ASSERT_TRUE(r1->Passed());
1424 ASSERT_FALSE(r2->Passed());
1425}
1426
zhanyong.wan9644db82009-06-24 23:02:50 +00001427// Tests TestResult::Failed().
shiqian4b6829f2008-07-03 22:38:12 +00001428TEST_F(TestResultTest, Failed) {
1429 ASSERT_FALSE(r0->Failed());
1430 ASSERT_FALSE(r1->Failed());
1431 ASSERT_TRUE(r2->Failed());
1432}
1433
zhanyong.wan9644db82009-06-24 23:02:50 +00001434// Tests TestResult::GetTestPartResult().
zhanyong.wan449f84d2009-07-01 22:55:05 +00001435
1436typedef TestResultTest TestResultDeathTest;
1437
1438TEST_F(TestResultDeathTest, GetTestPartResult) {
1439 CompareTestPartResult(*pr1, r2->GetTestPartResult(0));
1440 CompareTestPartResult(*pr2, r2->GetTestPartResult(1));
zhanyong.wan93d13a82010-02-25 01:09:07 +00001441 EXPECT_DEATH_IF_SUPPORTED(r2->GetTestPartResult(2), "");
1442 EXPECT_DEATH_IF_SUPPORTED(r2->GetTestPartResult(-1), "");
zhanyong.wan9644db82009-06-24 23:02:50 +00001443}
1444
zhanyong.wanb7ec0f72009-07-01 04:58:05 +00001445// Tests TestResult has no properties when none are added.
shiqian4b6829f2008-07-03 22:38:12 +00001446TEST(TestResultPropertyTest, NoPropertiesFoundWhenNoneAreAdded) {
1447 TestResult test_result;
zhanyong.wanb7ec0f72009-07-01 04:58:05 +00001448 ASSERT_EQ(0, test_result.test_property_count());
shiqian4b6829f2008-07-03 22:38:12 +00001449}
1450
zhanyong.wanb7ec0f72009-07-01 04:58:05 +00001451// Tests TestResult has the expected property when added.
shiqian4b6829f2008-07-03 22:38:12 +00001452TEST(TestResultPropertyTest, OnePropertyFoundWhenAdded) {
1453 TestResult test_result;
1454 TestProperty property("key_1", "1");
vladlosevdfbdf0b2013-04-05 20:50:46 +00001455 TestResultAccessor::RecordProperty(&test_result, "testcase", property);
zhanyong.wanb7ec0f72009-07-01 04:58:05 +00001456 ASSERT_EQ(1, test_result.test_property_count());
zhanyong.wan449f84d2009-07-01 22:55:05 +00001457 const TestProperty& actual_property = test_result.GetTestProperty(0);
1458 EXPECT_STREQ("key_1", actual_property.key());
1459 EXPECT_STREQ("1", actual_property.value());
shiqian4b6829f2008-07-03 22:38:12 +00001460}
1461
zhanyong.wanb7ec0f72009-07-01 04:58:05 +00001462// Tests TestResult has multiple properties when added.
shiqian4b6829f2008-07-03 22:38:12 +00001463TEST(TestResultPropertyTest, MultiplePropertiesFoundWhenAdded) {
1464 TestResult test_result;
1465 TestProperty property_1("key_1", "1");
1466 TestProperty property_2("key_2", "2");
vladlosevdfbdf0b2013-04-05 20:50:46 +00001467 TestResultAccessor::RecordProperty(&test_result, "testcase", property_1);
1468 TestResultAccessor::RecordProperty(&test_result, "testcase", property_2);
zhanyong.wanb7ec0f72009-07-01 04:58:05 +00001469 ASSERT_EQ(2, test_result.test_property_count());
zhanyong.wan449f84d2009-07-01 22:55:05 +00001470 const TestProperty& actual_property_1 = test_result.GetTestProperty(0);
1471 EXPECT_STREQ("key_1", actual_property_1.key());
1472 EXPECT_STREQ("1", actual_property_1.value());
shiqian4b6829f2008-07-03 22:38:12 +00001473
zhanyong.wan449f84d2009-07-01 22:55:05 +00001474 const TestProperty& actual_property_2 = test_result.GetTestProperty(1);
1475 EXPECT_STREQ("key_2", actual_property_2.key());
1476 EXPECT_STREQ("2", actual_property_2.value());
shiqian4b6829f2008-07-03 22:38:12 +00001477}
1478
zhanyong.wanb7ec0f72009-07-01 04:58:05 +00001479// Tests TestResult::RecordProperty() overrides values for duplicate keys.
shiqian4b6829f2008-07-03 22:38:12 +00001480TEST(TestResultPropertyTest, OverridesValuesForDuplicateKeys) {
1481 TestResult test_result;
1482 TestProperty property_1_1("key_1", "1");
1483 TestProperty property_2_1("key_2", "2");
1484 TestProperty property_1_2("key_1", "12");
1485 TestProperty property_2_2("key_2", "22");
vladlosevdfbdf0b2013-04-05 20:50:46 +00001486 TestResultAccessor::RecordProperty(&test_result, "testcase", property_1_1);
1487 TestResultAccessor::RecordProperty(&test_result, "testcase", property_2_1);
1488 TestResultAccessor::RecordProperty(&test_result, "testcase", property_1_2);
1489 TestResultAccessor::RecordProperty(&test_result, "testcase", property_2_2);
shiqian4b6829f2008-07-03 22:38:12 +00001490
zhanyong.wan9644db82009-06-24 23:02:50 +00001491 ASSERT_EQ(2, test_result.test_property_count());
zhanyong.wan449f84d2009-07-01 22:55:05 +00001492 const TestProperty& actual_property_1 = test_result.GetTestProperty(0);
1493 EXPECT_STREQ("key_1", actual_property_1.key());
1494 EXPECT_STREQ("12", actual_property_1.value());
zhanyong.wanb7ec0f72009-07-01 04:58:05 +00001495
zhanyong.wan449f84d2009-07-01 22:55:05 +00001496 const TestProperty& actual_property_2 = test_result.GetTestProperty(1);
1497 EXPECT_STREQ("key_2", actual_property_2.key());
1498 EXPECT_STREQ("22", actual_property_2.value());
zhanyong.wan9644db82009-06-24 23:02:50 +00001499}
1500
1501// Tests TestResult::GetTestProperty().
vladlosevdfbdf0b2013-04-05 20:50:46 +00001502TEST(TestResultPropertyTest, GetTestProperty) {
zhanyong.wan9644db82009-06-24 23:02:50 +00001503 TestResult test_result;
1504 TestProperty property_1("key_1", "1");
1505 TestProperty property_2("key_2", "2");
1506 TestProperty property_3("key_3", "3");
vladlosevdfbdf0b2013-04-05 20:50:46 +00001507 TestResultAccessor::RecordProperty(&test_result, "testcase", property_1);
1508 TestResultAccessor::RecordProperty(&test_result, "testcase", property_2);
1509 TestResultAccessor::RecordProperty(&test_result, "testcase", property_3);
zhanyong.wan9644db82009-06-24 23:02:50 +00001510
zhanyong.wan449f84d2009-07-01 22:55:05 +00001511 const TestProperty& fetched_property_1 = test_result.GetTestProperty(0);
1512 const TestProperty& fetched_property_2 = test_result.GetTestProperty(1);
1513 const TestProperty& fetched_property_3 = test_result.GetTestProperty(2);
zhanyong.wan9644db82009-06-24 23:02:50 +00001514
zhanyong.wan449f84d2009-07-01 22:55:05 +00001515 EXPECT_STREQ("key_1", fetched_property_1.key());
1516 EXPECT_STREQ("1", fetched_property_1.value());
zhanyong.wan9644db82009-06-24 23:02:50 +00001517
zhanyong.wan449f84d2009-07-01 22:55:05 +00001518 EXPECT_STREQ("key_2", fetched_property_2.key());
1519 EXPECT_STREQ("2", fetched_property_2.value());
zhanyong.wan9644db82009-06-24 23:02:50 +00001520
zhanyong.wan449f84d2009-07-01 22:55:05 +00001521 EXPECT_STREQ("key_3", fetched_property_3.key());
1522 EXPECT_STREQ("3", fetched_property_3.value());
zhanyong.wan9644db82009-06-24 23:02:50 +00001523
zhanyong.wan93d13a82010-02-25 01:09:07 +00001524 EXPECT_DEATH_IF_SUPPORTED(test_result.GetTestProperty(3), "");
1525 EXPECT_DEATH_IF_SUPPORTED(test_result.GetTestProperty(-1), "");
zhanyong.wan9644db82009-06-24 23:02:50 +00001526}
1527
shiqian4b6829f2008-07-03 22:38:12 +00001528// Tests that GTestFlagSaver works on Windows and Mac.
1529
shiqian760af5c2008-08-06 21:43:15 +00001530class GTestFlagSaverTest : public Test {
shiqian4b6829f2008-07-03 22:38:12 +00001531 protected:
1532 // Saves the Google Test flags such that we can restore them later, and
1533 // then sets them to their default values. This will be called
1534 // before the first test in this test case is run.
1535 static void SetUpTestCase() {
shiqian760af5c2008-08-06 21:43:15 +00001536 saver_ = new GTestFlagSaver;
shiqian4b6829f2008-07-03 22:38:12 +00001537
shiqianca6949f2009-01-10 01:16:33 +00001538 GTEST_FLAG(also_run_disabled_tests) = false;
shiqian760af5c2008-08-06 21:43:15 +00001539 GTEST_FLAG(break_on_failure) = false;
1540 GTEST_FLAG(catch_exceptions) = false;
shiqian21d43d12009-01-08 01:10:31 +00001541 GTEST_FLAG(death_test_use_fork) = false;
shiqian760af5c2008-08-06 21:43:15 +00001542 GTEST_FLAG(color) = "auto";
1543 GTEST_FLAG(filter) = "";
1544 GTEST_FLAG(list_tests) = false;
1545 GTEST_FLAG(output) = "";
zhanyong.wan73ad5a32009-04-14 23:19:22 +00001546 GTEST_FLAG(print_time) = true;
zhanyong.wan9b9794f2009-07-14 22:56:46 +00001547 GTEST_FLAG(random_seed) = 0;
shiqian760af5c2008-08-06 21:43:15 +00001548 GTEST_FLAG(repeat) = 1;
zhanyong.wan9b9794f2009-07-14 22:56:46 +00001549 GTEST_FLAG(shuffle) = false;
vladlosevba015a92009-11-17 22:43:15 +00001550 GTEST_FLAG(stack_trace_depth) = kMaxStackTraceDepth;
zhanyong.wanc95489e2010-08-19 22:16:00 +00001551 GTEST_FLAG(stream_result_to) = "";
zhanyong.wanb0fe69f2009-03-06 20:05:23 +00001552 GTEST_FLAG(throw_on_failure) = false;
shiqian4b6829f2008-07-03 22:38:12 +00001553 }
1554
1555 // Restores the Google Test flags that the tests have modified. This will
1556 // be called after the last test in this test case is run.
1557 static void TearDownTestCase() {
1558 delete saver_;
1559 saver_ = NULL;
1560 }
1561
1562 // Verifies that the Google Test flags have their default values, and then
1563 // modifies each of them.
1564 void VerifyAndModifyFlags() {
shiqianca6949f2009-01-10 01:16:33 +00001565 EXPECT_FALSE(GTEST_FLAG(also_run_disabled_tests));
shiqian760af5c2008-08-06 21:43:15 +00001566 EXPECT_FALSE(GTEST_FLAG(break_on_failure));
1567 EXPECT_FALSE(GTEST_FLAG(catch_exceptions));
1568 EXPECT_STREQ("auto", GTEST_FLAG(color).c_str());
shiqian21d43d12009-01-08 01:10:31 +00001569 EXPECT_FALSE(GTEST_FLAG(death_test_use_fork));
shiqian760af5c2008-08-06 21:43:15 +00001570 EXPECT_STREQ("", GTEST_FLAG(filter).c_str());
1571 EXPECT_FALSE(GTEST_FLAG(list_tests));
1572 EXPECT_STREQ("", GTEST_FLAG(output).c_str());
zhanyong.wan73ad5a32009-04-14 23:19:22 +00001573 EXPECT_TRUE(GTEST_FLAG(print_time));
zhanyong.wan9b9794f2009-07-14 22:56:46 +00001574 EXPECT_EQ(0, GTEST_FLAG(random_seed));
shiqian760af5c2008-08-06 21:43:15 +00001575 EXPECT_EQ(1, GTEST_FLAG(repeat));
zhanyong.wan9b9794f2009-07-14 22:56:46 +00001576 EXPECT_FALSE(GTEST_FLAG(shuffle));
vladlosevba015a92009-11-17 22:43:15 +00001577 EXPECT_EQ(kMaxStackTraceDepth, GTEST_FLAG(stack_trace_depth));
zhanyong.wanc95489e2010-08-19 22:16:00 +00001578 EXPECT_STREQ("", GTEST_FLAG(stream_result_to).c_str());
zhanyong.wanb0fe69f2009-03-06 20:05:23 +00001579 EXPECT_FALSE(GTEST_FLAG(throw_on_failure));
shiqian4b6829f2008-07-03 22:38:12 +00001580
shiqianca6949f2009-01-10 01:16:33 +00001581 GTEST_FLAG(also_run_disabled_tests) = true;
shiqian760af5c2008-08-06 21:43:15 +00001582 GTEST_FLAG(break_on_failure) = true;
1583 GTEST_FLAG(catch_exceptions) = true;
1584 GTEST_FLAG(color) = "no";
shiqian21d43d12009-01-08 01:10:31 +00001585 GTEST_FLAG(death_test_use_fork) = true;
shiqian760af5c2008-08-06 21:43:15 +00001586 GTEST_FLAG(filter) = "abc";
1587 GTEST_FLAG(list_tests) = true;
1588 GTEST_FLAG(output) = "xml:foo.xml";
zhanyong.wan73ad5a32009-04-14 23:19:22 +00001589 GTEST_FLAG(print_time) = false;
zhanyong.wan9b9794f2009-07-14 22:56:46 +00001590 GTEST_FLAG(random_seed) = 1;
shiqian760af5c2008-08-06 21:43:15 +00001591 GTEST_FLAG(repeat) = 100;
zhanyong.wan9b9794f2009-07-14 22:56:46 +00001592 GTEST_FLAG(shuffle) = true;
vladlosevba015a92009-11-17 22:43:15 +00001593 GTEST_FLAG(stack_trace_depth) = 1;
zhanyong.wanc95489e2010-08-19 22:16:00 +00001594 GTEST_FLAG(stream_result_to) = "localhost:1234";
zhanyong.wanb0fe69f2009-03-06 20:05:23 +00001595 GTEST_FLAG(throw_on_failure) = true;
shiqian4b6829f2008-07-03 22:38:12 +00001596 }
vladlosev93fed472011-11-04 17:56:23 +00001597
shiqian4b6829f2008-07-03 22:38:12 +00001598 private:
1599 // For saving Google Test flags during this test case.
shiqian760af5c2008-08-06 21:43:15 +00001600 static GTestFlagSaver* saver_;
shiqian4b6829f2008-07-03 22:38:12 +00001601};
1602
shiqian760af5c2008-08-06 21:43:15 +00001603GTestFlagSaver* GTestFlagSaverTest::saver_ = NULL;
shiqian4b6829f2008-07-03 22:38:12 +00001604
1605// Google Test doesn't guarantee the order of tests. The following two
1606// tests are designed to work regardless of their order.
1607
1608// Modifies the Google Test flags in the test body.
1609TEST_F(GTestFlagSaverTest, ModifyGTestFlags) {
1610 VerifyAndModifyFlags();
1611}
1612
1613// Verifies that the Google Test flags in the body of the previous test were
1614// restored to their original values.
1615TEST_F(GTestFlagSaverTest, VerifyGTestFlags) {
1616 VerifyAndModifyFlags();
1617}
1618
1619// Sets an environment variable with the given name to the given
1620// value. If the value argument is "", unsets the environment
1621// variable. The caller must ensure that both arguments are not NULL.
1622static void SetEnv(const char* name, const char* value) {
zhanyong.wanfff03342009-09-24 21:15:59 +00001623#if GTEST_OS_WINDOWS_MOBILE
shiqian4b6829f2008-07-03 22:38:12 +00001624 // Environment variables are not supported on Windows CE.
1625 return;
vladlosev673a0cb2010-02-03 02:27:02 +00001626#elif defined(__BORLANDC__) || defined(__SunOS_5_8) || defined(__SunOS_5_9)
zhanyong.wan98efcc42009-04-28 00:28:09 +00001627 // C++Builder's putenv only stores a pointer to its parameter; we have to
1628 // ensure that the string remains valid as long as it might be needed.
1629 // We use an std::map to do so.
jgm@google.com03c31492012-11-15 15:47:38 +00001630 static std::map<std::string, std::string*> added_env;
zhanyong.wan98efcc42009-04-28 00:28:09 +00001631
1632 // Because putenv stores a pointer to the string buffer, we can't delete the
1633 // previous string (if present) until after it's replaced.
jgm@google.com03c31492012-11-15 15:47:38 +00001634 std::string *prev_env = NULL;
zhanyong.wan98efcc42009-04-28 00:28:09 +00001635 if (added_env.find(name) != added_env.end()) {
1636 prev_env = added_env[name];
1637 }
jgm@google.com03c31492012-11-15 15:47:38 +00001638 added_env[name] = new std::string(
1639 (Message() << name << "=" << value).GetString());
vladlosev673a0cb2010-02-03 02:27:02 +00001640
1641 // The standard signature of putenv accepts a 'char*' argument. Other
1642 // implementations, like C++Builder's, accept a 'const char*'.
1643 // We cast away the 'const' since that would work for both variants.
1644 putenv(const_cast<char*>(added_env[name]->c_str()));
zhanyong.wan98efcc42009-04-28 00:28:09 +00001645 delete prev_env;
zhanyong.wan4cd62602009-02-23 23:21:55 +00001646#elif GTEST_OS_WINDOWS // If we are on Windows proper.
shiqian760af5c2008-08-06 21:43:15 +00001647 _putenv((Message() << name << "=" << value).GetString().c_str());
shiqian4b6829f2008-07-03 22:38:12 +00001648#else
1649 if (*value == '\0') {
1650 unsetenv(name);
1651 } else {
1652 setenv(name, value, 1);
1653 }
zhanyong.wanfff03342009-09-24 21:15:59 +00001654#endif // GTEST_OS_WINDOWS_MOBILE
shiqian4b6829f2008-07-03 22:38:12 +00001655}
1656
zhanyong.wanfff03342009-09-24 21:15:59 +00001657#if !GTEST_OS_WINDOWS_MOBILE
shiqian4b6829f2008-07-03 22:38:12 +00001658// Environment variables are not supported on Windows CE.
1659
shiqian760af5c2008-08-06 21:43:15 +00001660using testing::internal::Int32FromGTestEnv;
shiqian4b6829f2008-07-03 22:38:12 +00001661
1662// Tests Int32FromGTestEnv().
1663
1664// Tests that Int32FromGTestEnv() returns the default value when the
1665// environment variable is not set.
1666TEST(Int32FromGTestEnvTest, ReturnsDefaultWhenVariableIsNotSet) {
zhanyong.wan4cd62602009-02-23 23:21:55 +00001667 SetEnv(GTEST_FLAG_PREFIX_UPPER_ "TEMP", "");
shiqian4b6829f2008-07-03 22:38:12 +00001668 EXPECT_EQ(10, Int32FromGTestEnv("temp", 10));
1669}
1670
1671// Tests that Int32FromGTestEnv() returns the default value when the
1672// environment variable overflows as an Int32.
1673TEST(Int32FromGTestEnvTest, ReturnsDefaultWhenValueOverflows) {
1674 printf("(expecting 2 warnings)\n");
1675
zhanyong.wan4cd62602009-02-23 23:21:55 +00001676 SetEnv(GTEST_FLAG_PREFIX_UPPER_ "TEMP", "12345678987654321");
shiqian4b6829f2008-07-03 22:38:12 +00001677 EXPECT_EQ(20, Int32FromGTestEnv("temp", 20));
1678
zhanyong.wan4cd62602009-02-23 23:21:55 +00001679 SetEnv(GTEST_FLAG_PREFIX_UPPER_ "TEMP", "-12345678987654321");
shiqian4b6829f2008-07-03 22:38:12 +00001680 EXPECT_EQ(30, Int32FromGTestEnv("temp", 30));
1681}
1682
1683// Tests that Int32FromGTestEnv() returns the default value when the
1684// environment variable does not represent a valid decimal integer.
1685TEST(Int32FromGTestEnvTest, ReturnsDefaultWhenValueIsInvalid) {
1686 printf("(expecting 2 warnings)\n");
1687
zhanyong.wan4cd62602009-02-23 23:21:55 +00001688 SetEnv(GTEST_FLAG_PREFIX_UPPER_ "TEMP", "A1");
shiqian4b6829f2008-07-03 22:38:12 +00001689 EXPECT_EQ(40, Int32FromGTestEnv("temp", 40));
1690
zhanyong.wan4cd62602009-02-23 23:21:55 +00001691 SetEnv(GTEST_FLAG_PREFIX_UPPER_ "TEMP", "12X");
shiqian4b6829f2008-07-03 22:38:12 +00001692 EXPECT_EQ(50, Int32FromGTestEnv("temp", 50));
1693}
1694
1695// Tests that Int32FromGTestEnv() parses and returns the value of the
1696// environment variable when it represents a valid decimal integer in
1697// the range of an Int32.
1698TEST(Int32FromGTestEnvTest, ParsesAndReturnsValidValue) {
zhanyong.wan4cd62602009-02-23 23:21:55 +00001699 SetEnv(GTEST_FLAG_PREFIX_UPPER_ "TEMP", "123");
shiqian4b6829f2008-07-03 22:38:12 +00001700 EXPECT_EQ(123, Int32FromGTestEnv("temp", 0));
1701
zhanyong.wan4cd62602009-02-23 23:21:55 +00001702 SetEnv(GTEST_FLAG_PREFIX_UPPER_ "TEMP", "-321");
shiqian4b6829f2008-07-03 22:38:12 +00001703 EXPECT_EQ(-321, Int32FromGTestEnv("temp", 0));
1704}
zhanyong.wanfff03342009-09-24 21:15:59 +00001705#endif // !GTEST_OS_WINDOWS_MOBILE
shiqian4b6829f2008-07-03 22:38:12 +00001706
1707// Tests ParseInt32Flag().
1708
1709// Tests that ParseInt32Flag() returns false and doesn't change the
1710// output value when the flag has wrong format
1711TEST(ParseInt32FlagTest, ReturnsFalseForInvalidFlag) {
1712 Int32 value = 123;
1713 EXPECT_FALSE(ParseInt32Flag("--a=100", "b", &value));
1714 EXPECT_EQ(123, value);
1715
1716 EXPECT_FALSE(ParseInt32Flag("a=100", "a", &value));
1717 EXPECT_EQ(123, value);
1718}
1719
1720// Tests that ParseInt32Flag() returns false and doesn't change the
1721// output value when the flag overflows as an Int32.
1722TEST(ParseInt32FlagTest, ReturnsDefaultWhenValueOverflows) {
1723 printf("(expecting 2 warnings)\n");
1724
1725 Int32 value = 123;
1726 EXPECT_FALSE(ParseInt32Flag("--abc=12345678987654321", "abc", &value));
1727 EXPECT_EQ(123, value);
1728
1729 EXPECT_FALSE(ParseInt32Flag("--abc=-12345678987654321", "abc", &value));
1730 EXPECT_EQ(123, value);
1731}
1732
1733// Tests that ParseInt32Flag() returns false and doesn't change the
1734// output value when the flag does not represent a valid decimal
1735// integer.
1736TEST(ParseInt32FlagTest, ReturnsDefaultWhenValueIsInvalid) {
1737 printf("(expecting 2 warnings)\n");
1738
1739 Int32 value = 123;
1740 EXPECT_FALSE(ParseInt32Flag("--abc=A1", "abc", &value));
1741 EXPECT_EQ(123, value);
1742
1743 EXPECT_FALSE(ParseInt32Flag("--abc=12X", "abc", &value));
1744 EXPECT_EQ(123, value);
1745}
1746
1747// Tests that ParseInt32Flag() parses the value of the flag and
1748// returns true when the flag represents a valid decimal integer in
1749// the range of an Int32.
1750TEST(ParseInt32FlagTest, ParsesAndReturnsValidValue) {
1751 Int32 value = 123;
zhanyong.wan4cd62602009-02-23 23:21:55 +00001752 EXPECT_TRUE(ParseInt32Flag("--" GTEST_FLAG_PREFIX_ "abc=456", "abc", &value));
shiqian4b6829f2008-07-03 22:38:12 +00001753 EXPECT_EQ(456, value);
1754
zhanyong.wan98efcc42009-04-28 00:28:09 +00001755 EXPECT_TRUE(ParseInt32Flag("--" GTEST_FLAG_PREFIX_ "abc=-789",
1756 "abc", &value));
shiqian4b6829f2008-07-03 22:38:12 +00001757 EXPECT_EQ(-789, value);
1758}
1759
zhanyong.wan905074c2009-02-09 18:05:21 +00001760// Tests that Int32FromEnvOrDie() parses the value of the var or
1761// returns the correct default.
zhanyong.wanc427f5e2009-06-19 17:23:54 +00001762// Environment variables are not supported on Windows CE.
zhanyong.wanfff03342009-09-24 21:15:59 +00001763#if !GTEST_OS_WINDOWS_MOBILE
zhanyong.wan905074c2009-02-09 18:05:21 +00001764TEST(Int32FromEnvOrDieTest, ParsesAndReturnsValidValue) {
zhanyong.wan4cd62602009-02-23 23:21:55 +00001765 EXPECT_EQ(333, Int32FromEnvOrDie(GTEST_FLAG_PREFIX_UPPER_ "UnsetVar", 333));
1766 SetEnv(GTEST_FLAG_PREFIX_UPPER_ "UnsetVar", "123");
1767 EXPECT_EQ(123, Int32FromEnvOrDie(GTEST_FLAG_PREFIX_UPPER_ "UnsetVar", 333));
1768 SetEnv(GTEST_FLAG_PREFIX_UPPER_ "UnsetVar", "-123");
1769 EXPECT_EQ(-123, Int32FromEnvOrDie(GTEST_FLAG_PREFIX_UPPER_ "UnsetVar", 333));
zhanyong.wan905074c2009-02-09 18:05:21 +00001770}
zhanyong.wanfff03342009-09-24 21:15:59 +00001771#endif // !GTEST_OS_WINDOWS_MOBILE
zhanyong.wan905074c2009-02-09 18:05:21 +00001772
1773// Tests that Int32FromEnvOrDie() aborts with an error message
1774// if the variable is not an Int32.
1775TEST(Int32FromEnvOrDieDeathTest, AbortsOnFailure) {
zhanyong.wan4cd62602009-02-23 23:21:55 +00001776 SetEnv(GTEST_FLAG_PREFIX_UPPER_ "VAR", "xxx");
zhanyong.wan535de532009-08-07 06:47:47 +00001777 EXPECT_DEATH_IF_SUPPORTED(
zhanyong.wan449f84d2009-07-01 22:55:05 +00001778 Int32FromEnvOrDie(GTEST_FLAG_PREFIX_UPPER_ "VAR", 123),
1779 ".*");
zhanyong.wan905074c2009-02-09 18:05:21 +00001780}
1781
1782// Tests that Int32FromEnvOrDie() aborts with an error message
1783// if the variable cannot be represnted by an Int32.
1784TEST(Int32FromEnvOrDieDeathTest, AbortsOnInt32Overflow) {
zhanyong.wan4cd62602009-02-23 23:21:55 +00001785 SetEnv(GTEST_FLAG_PREFIX_UPPER_ "VAR", "1234567891234567891234");
zhanyong.wan535de532009-08-07 06:47:47 +00001786 EXPECT_DEATH_IF_SUPPORTED(
zhanyong.wan449f84d2009-07-01 22:55:05 +00001787 Int32FromEnvOrDie(GTEST_FLAG_PREFIX_UPPER_ "VAR", 123),
1788 ".*");
zhanyong.wan905074c2009-02-09 18:05:21 +00001789}
1790
zhanyong.wan905074c2009-02-09 18:05:21 +00001791// Tests that ShouldRunTestOnShard() selects all tests
1792// where there is 1 shard.
1793TEST(ShouldRunTestOnShardTest, IsPartitionWhenThereIsOneShard) {
1794 EXPECT_TRUE(ShouldRunTestOnShard(1, 0, 0));
1795 EXPECT_TRUE(ShouldRunTestOnShard(1, 0, 1));
1796 EXPECT_TRUE(ShouldRunTestOnShard(1, 0, 2));
1797 EXPECT_TRUE(ShouldRunTestOnShard(1, 0, 3));
1798 EXPECT_TRUE(ShouldRunTestOnShard(1, 0, 4));
1799}
1800
1801class ShouldShardTest : public testing::Test {
1802 protected:
1803 virtual void SetUp() {
zhanyong.wan4cd62602009-02-23 23:21:55 +00001804 index_var_ = GTEST_FLAG_PREFIX_UPPER_ "INDEX";
1805 total_var_ = GTEST_FLAG_PREFIX_UPPER_ "TOTAL";
zhanyong.wan905074c2009-02-09 18:05:21 +00001806 }
1807
1808 virtual void TearDown() {
1809 SetEnv(index_var_, "");
1810 SetEnv(total_var_, "");
1811 }
1812
1813 const char* index_var_;
1814 const char* total_var_;
1815};
1816
1817// Tests that sharding is disabled if neither of the environment variables
1818// are set.
1819TEST_F(ShouldShardTest, ReturnsFalseWhenNeitherEnvVarIsSet) {
1820 SetEnv(index_var_, "");
1821 SetEnv(total_var_, "");
1822
1823 EXPECT_FALSE(ShouldShard(total_var_, index_var_, false));
1824 EXPECT_FALSE(ShouldShard(total_var_, index_var_, true));
1825}
1826
1827// Tests that sharding is not enabled if total_shards == 1.
1828TEST_F(ShouldShardTest, ReturnsFalseWhenTotalShardIsOne) {
1829 SetEnv(index_var_, "0");
1830 SetEnv(total_var_, "1");
1831 EXPECT_FALSE(ShouldShard(total_var_, index_var_, false));
1832 EXPECT_FALSE(ShouldShard(total_var_, index_var_, true));
1833}
1834
1835// Tests that sharding is enabled if total_shards > 1 and
1836// we are not in a death test subprocess.
zhanyong.wanc427f5e2009-06-19 17:23:54 +00001837// Environment variables are not supported on Windows CE.
zhanyong.wanfff03342009-09-24 21:15:59 +00001838#if !GTEST_OS_WINDOWS_MOBILE
zhanyong.wan905074c2009-02-09 18:05:21 +00001839TEST_F(ShouldShardTest, WorksWhenShardEnvVarsAreValid) {
1840 SetEnv(index_var_, "4");
1841 SetEnv(total_var_, "22");
1842 EXPECT_TRUE(ShouldShard(total_var_, index_var_, false));
1843 EXPECT_FALSE(ShouldShard(total_var_, index_var_, true));
1844
1845 SetEnv(index_var_, "8");
1846 SetEnv(total_var_, "9");
1847 EXPECT_TRUE(ShouldShard(total_var_, index_var_, false));
1848 EXPECT_FALSE(ShouldShard(total_var_, index_var_, true));
1849
1850 SetEnv(index_var_, "0");
1851 SetEnv(total_var_, "9");
1852 EXPECT_TRUE(ShouldShard(total_var_, index_var_, false));
1853 EXPECT_FALSE(ShouldShard(total_var_, index_var_, true));
1854}
zhanyong.wanfff03342009-09-24 21:15:59 +00001855#endif // !GTEST_OS_WINDOWS_MOBILE
zhanyong.wan905074c2009-02-09 18:05:21 +00001856
1857// Tests that we exit in error if the sharding values are not valid.
zhanyong.wan449f84d2009-07-01 22:55:05 +00001858
1859typedef ShouldShardTest ShouldShardDeathTest;
1860
1861TEST_F(ShouldShardDeathTest, AbortsWhenShardingEnvVarsAreInvalid) {
zhanyong.wan905074c2009-02-09 18:05:21 +00001862 SetEnv(index_var_, "4");
1863 SetEnv(total_var_, "4");
zhanyong.wan535de532009-08-07 06:47:47 +00001864 EXPECT_DEATH_IF_SUPPORTED(ShouldShard(total_var_, index_var_, false), ".*");
zhanyong.wan905074c2009-02-09 18:05:21 +00001865
1866 SetEnv(index_var_, "4");
1867 SetEnv(total_var_, "-2");
zhanyong.wan535de532009-08-07 06:47:47 +00001868 EXPECT_DEATH_IF_SUPPORTED(ShouldShard(total_var_, index_var_, false), ".*");
zhanyong.wan905074c2009-02-09 18:05:21 +00001869
1870 SetEnv(index_var_, "5");
1871 SetEnv(total_var_, "");
zhanyong.wan535de532009-08-07 06:47:47 +00001872 EXPECT_DEATH_IF_SUPPORTED(ShouldShard(total_var_, index_var_, false), ".*");
zhanyong.wan905074c2009-02-09 18:05:21 +00001873
1874 SetEnv(index_var_, "");
1875 SetEnv(total_var_, "5");
zhanyong.wan535de532009-08-07 06:47:47 +00001876 EXPECT_DEATH_IF_SUPPORTED(ShouldShard(total_var_, index_var_, false), ".*");
zhanyong.wan905074c2009-02-09 18:05:21 +00001877}
1878
zhanyong.wan905074c2009-02-09 18:05:21 +00001879// Tests that ShouldRunTestOnShard is a partition when 5
1880// shards are used.
1881TEST(ShouldRunTestOnShardTest, IsPartitionWhenThereAreFiveShards) {
1882 // Choose an arbitrary number of tests and shards.
1883 const int num_tests = 17;
1884 const int num_shards = 5;
1885
1886 // Check partitioning: each test should be on exactly 1 shard.
1887 for (int test_id = 0; test_id < num_tests; test_id++) {
1888 int prev_selected_shard_index = -1;
1889 for (int shard_index = 0; shard_index < num_shards; shard_index++) {
1890 if (ShouldRunTestOnShard(num_shards, shard_index, test_id)) {
1891 if (prev_selected_shard_index < 0) {
1892 prev_selected_shard_index = shard_index;
1893 } else {
1894 ADD_FAILURE() << "Shard " << prev_selected_shard_index << " and "
1895 << shard_index << " are both selected to run test " << test_id;
1896 }
1897 }
1898 }
1899 }
1900
1901 // Check balance: This is not required by the sharding protocol, but is a
1902 // desirable property for performance.
1903 for (int shard_index = 0; shard_index < num_shards; shard_index++) {
1904 int num_tests_on_shard = 0;
1905 for (int test_id = 0; test_id < num_tests; test_id++) {
1906 num_tests_on_shard +=
1907 ShouldRunTestOnShard(num_shards, shard_index, test_id);
1908 }
1909 EXPECT_GE(num_tests_on_shard, num_tests / num_shards);
1910 }
1911}
1912
shiqian4b6829f2008-07-03 22:38:12 +00001913// For the same reason we are not explicitly testing everything in the
shiqianc3b4de32008-09-12 04:01:37 +00001914// Test class, there are no separate tests for the following classes
1915// (except for some trivial cases):
shiqian4b6829f2008-07-03 22:38:12 +00001916//
1917// TestCase, UnitTest, UnitTestResultPrinter.
1918//
1919// Similarly, there are no separate tests for the following macros:
1920//
1921// TEST, TEST_F, RUN_ALL_TESTS
1922
shiqianc3b4de32008-09-12 04:01:37 +00001923TEST(UnitTestTest, CanGetOriginalWorkingDir) {
1924 ASSERT_TRUE(UnitTest::GetInstance()->original_working_dir() != NULL);
1925 EXPECT_STRNE(UnitTest::GetInstance()->original_working_dir(), "");
1926}
1927
vladlosev8883b422011-10-05 05:52:34 +00001928TEST(UnitTestTest, ReturnsPlausibleTimestamp) {
1929 EXPECT_LT(0, UnitTest::GetInstance()->start_timestamp());
1930 EXPECT_LE(UnitTest::GetInstance()->start_timestamp(), GetTimeInMillis());
1931}
1932
vladlosevdfbdf0b2013-04-05 20:50:46 +00001933// When a property using a reserved key is supplied to this function, it
1934// tests that a non-fatal failure is added, a fatal failure is not added,
1935// and that the property is not recorded.
1936void ExpectNonFatalFailureRecordingPropertyWithReservedKey(
1937 const TestResult& test_result, const char* key) {
1938 EXPECT_NONFATAL_FAILURE(Test::RecordProperty(key, "1"), "Reserved key");
1939 ASSERT_EQ(0, test_result.test_property_count()) << "Property for key '" << key
1940 << "' recorded unexpectedly.";
1941}
1942
1943void ExpectNonFatalFailureRecordingPropertyWithReservedKeyForCurrentTest(
1944 const char* key) {
1945 const TestInfo* test_info = UnitTest::GetInstance()->current_test_info();
1946 ASSERT_TRUE(test_info != NULL);
1947 ExpectNonFatalFailureRecordingPropertyWithReservedKey(*test_info->result(),
1948 key);
1949}
1950
1951void ExpectNonFatalFailureRecordingPropertyWithReservedKeyForCurrentTestCase(
1952 const char* key) {
1953 const TestCase* test_case = UnitTest::GetInstance()->current_test_case();
1954 ASSERT_TRUE(test_case != NULL);
1955 ExpectNonFatalFailureRecordingPropertyWithReservedKey(
1956 test_case->ad_hoc_test_result(), key);
1957}
1958
1959void ExpectNonFatalFailureRecordingPropertyWithReservedKeyOutsideOfTestCase(
1960 const char* key) {
1961 ExpectNonFatalFailureRecordingPropertyWithReservedKey(
1962 UnitTest::GetInstance()->ad_hoc_test_result(), key);
1963}
1964
1965// Tests that property recording functions in UnitTest outside of tests
1966// functions correcly. Creating a separate instance of UnitTest ensures it
1967// is in a state similar to the UnitTest's singleton's between tests.
1968class UnitTestRecordPropertyTest :
1969 public testing::internal::UnitTestRecordPropertyTestHelper {
1970 public:
1971 static void SetUpTestCase() {
1972 ExpectNonFatalFailureRecordingPropertyWithReservedKeyForCurrentTestCase(
1973 "disabled");
1974 ExpectNonFatalFailureRecordingPropertyWithReservedKeyForCurrentTestCase(
1975 "errors");
1976 ExpectNonFatalFailureRecordingPropertyWithReservedKeyForCurrentTestCase(
1977 "failures");
1978 ExpectNonFatalFailureRecordingPropertyWithReservedKeyForCurrentTestCase(
1979 "name");
1980 ExpectNonFatalFailureRecordingPropertyWithReservedKeyForCurrentTestCase(
1981 "tests");
1982 ExpectNonFatalFailureRecordingPropertyWithReservedKeyForCurrentTestCase(
1983 "time");
1984
1985 Test::RecordProperty("test_case_key_1", "1");
1986 const TestCase* test_case = UnitTest::GetInstance()->current_test_case();
1987 ASSERT_TRUE(test_case != NULL);
1988
1989 ASSERT_EQ(1, test_case->ad_hoc_test_result().test_property_count());
1990 EXPECT_STREQ("test_case_key_1",
1991 test_case->ad_hoc_test_result().GetTestProperty(0).key());
1992 EXPECT_STREQ("1",
1993 test_case->ad_hoc_test_result().GetTestProperty(0).value());
1994 }
1995};
1996
1997// Tests TestResult has the expected property when added.
1998TEST_F(UnitTestRecordPropertyTest, OnePropertyFoundWhenAdded) {
1999 UnitTestRecordProperty("key_1", "1");
2000
2001 ASSERT_EQ(1, unit_test_.ad_hoc_test_result().test_property_count());
2002
2003 EXPECT_STREQ("key_1",
2004 unit_test_.ad_hoc_test_result().GetTestProperty(0).key());
2005 EXPECT_STREQ("1",
2006 unit_test_.ad_hoc_test_result().GetTestProperty(0).value());
2007}
2008
2009// Tests TestResult has multiple properties when added.
2010TEST_F(UnitTestRecordPropertyTest, MultiplePropertiesFoundWhenAdded) {
2011 UnitTestRecordProperty("key_1", "1");
2012 UnitTestRecordProperty("key_2", "2");
2013
2014 ASSERT_EQ(2, unit_test_.ad_hoc_test_result().test_property_count());
2015
2016 EXPECT_STREQ("key_1",
2017 unit_test_.ad_hoc_test_result().GetTestProperty(0).key());
2018 EXPECT_STREQ("1", unit_test_.ad_hoc_test_result().GetTestProperty(0).value());
2019
2020 EXPECT_STREQ("key_2",
2021 unit_test_.ad_hoc_test_result().GetTestProperty(1).key());
2022 EXPECT_STREQ("2", unit_test_.ad_hoc_test_result().GetTestProperty(1).value());
2023}
2024
2025// Tests TestResult::RecordProperty() overrides values for duplicate keys.
2026TEST_F(UnitTestRecordPropertyTest, OverridesValuesForDuplicateKeys) {
2027 UnitTestRecordProperty("key_1", "1");
2028 UnitTestRecordProperty("key_2", "2");
2029 UnitTestRecordProperty("key_1", "12");
2030 UnitTestRecordProperty("key_2", "22");
2031
2032 ASSERT_EQ(2, unit_test_.ad_hoc_test_result().test_property_count());
2033
2034 EXPECT_STREQ("key_1",
2035 unit_test_.ad_hoc_test_result().GetTestProperty(0).key());
2036 EXPECT_STREQ("12",
2037 unit_test_.ad_hoc_test_result().GetTestProperty(0).value());
2038
2039 EXPECT_STREQ("key_2",
2040 unit_test_.ad_hoc_test_result().GetTestProperty(1).key());
2041 EXPECT_STREQ("22",
2042 unit_test_.ad_hoc_test_result().GetTestProperty(1).value());
2043}
2044
2045TEST_F(UnitTestRecordPropertyTest,
2046 AddFailureInsideTestsWhenUsingTestCaseReservedKeys) {
2047 ExpectNonFatalFailureRecordingPropertyWithReservedKeyForCurrentTest(
2048 "name");
2049 ExpectNonFatalFailureRecordingPropertyWithReservedKeyForCurrentTest(
2050 "value_param");
2051 ExpectNonFatalFailureRecordingPropertyWithReservedKeyForCurrentTest(
2052 "type_param");
2053 ExpectNonFatalFailureRecordingPropertyWithReservedKeyForCurrentTest(
2054 "status");
2055 ExpectNonFatalFailureRecordingPropertyWithReservedKeyForCurrentTest(
2056 "time");
2057 ExpectNonFatalFailureRecordingPropertyWithReservedKeyForCurrentTest(
2058 "classname");
2059}
2060
2061TEST_F(UnitTestRecordPropertyTest,
2062 AddRecordWithReservedKeysGeneratesCorrectPropertyList) {
2063 EXPECT_NONFATAL_FAILURE(
2064 Test::RecordProperty("name", "1"),
2065 "'classname', 'name', 'status', 'time', 'type_param', and 'value_param'"
2066 " are reserved");
2067}
2068
2069class UnitTestRecordPropertyTestEnvironment : public Environment {
2070 public:
2071 virtual void TearDown() {
2072 ExpectNonFatalFailureRecordingPropertyWithReservedKeyOutsideOfTestCase(
2073 "tests");
2074 ExpectNonFatalFailureRecordingPropertyWithReservedKeyOutsideOfTestCase(
2075 "failures");
2076 ExpectNonFatalFailureRecordingPropertyWithReservedKeyOutsideOfTestCase(
2077 "disabled");
2078 ExpectNonFatalFailureRecordingPropertyWithReservedKeyOutsideOfTestCase(
2079 "errors");
2080 ExpectNonFatalFailureRecordingPropertyWithReservedKeyOutsideOfTestCase(
2081 "name");
2082 ExpectNonFatalFailureRecordingPropertyWithReservedKeyOutsideOfTestCase(
2083 "timestamp");
2084 ExpectNonFatalFailureRecordingPropertyWithReservedKeyOutsideOfTestCase(
2085 "time");
2086 ExpectNonFatalFailureRecordingPropertyWithReservedKeyOutsideOfTestCase(
2087 "random_seed");
2088 }
2089};
2090
2091// This will test property recording outside of any test or test case.
2092static Environment* record_property_env =
2093 AddGlobalTestEnvironment(new UnitTestRecordPropertyTestEnvironment);
2094
shiqian4b6829f2008-07-03 22:38:12 +00002095// This group of tests is for predicate assertions (ASSERT_PRED*, etc)
2096// of various arities. They do not attempt to be exhaustive. Rather,
2097// view them as smoke tests that can be easily reviewed and verified.
2098// A more complete set of tests for predicate assertions can be found
2099// in gtest_pred_impl_unittest.cc.
2100
2101// First, some predicates and predicate-formatters needed by the tests.
2102
2103// Returns true iff the argument is an even number.
2104bool IsEven(int n) {
2105 return (n % 2) == 0;
2106}
2107
2108// A functor that returns true iff the argument is an even number.
2109struct IsEvenFunctor {
2110 bool operator()(int n) { return IsEven(n); }
2111};
2112
2113// A predicate-formatter function that asserts the argument is an even
2114// number.
shiqian760af5c2008-08-06 21:43:15 +00002115AssertionResult AssertIsEven(const char* expr, int n) {
shiqian4b6829f2008-07-03 22:38:12 +00002116 if (IsEven(n)) {
shiqian760af5c2008-08-06 21:43:15 +00002117 return AssertionSuccess();
shiqian4b6829f2008-07-03 22:38:12 +00002118 }
2119
shiqian760af5c2008-08-06 21:43:15 +00002120 Message msg;
shiqian4b6829f2008-07-03 22:38:12 +00002121 msg << expr << " evaluates to " << n << ", which is not even.";
shiqian760af5c2008-08-06 21:43:15 +00002122 return AssertionFailure(msg);
shiqian4b6829f2008-07-03 22:38:12 +00002123}
2124
vladlosevfbd53a52009-10-20 21:03:10 +00002125// A predicate function that returns AssertionResult for use in
2126// EXPECT/ASSERT_TRUE/FALSE.
2127AssertionResult ResultIsEven(int n) {
2128 if (IsEven(n))
2129 return AssertionSuccess() << n << " is even";
2130 else
2131 return AssertionFailure() << n << " is odd";
2132}
2133
2134// A predicate function that returns AssertionResult but gives no
2135// explanation why it succeeds. Needed for testing that
2136// EXPECT/ASSERT_FALSE handles such functions correctly.
2137AssertionResult ResultIsEvenNoExplanation(int n) {
2138 if (IsEven(n))
2139 return AssertionSuccess();
2140 else
2141 return AssertionFailure() << n << " is odd";
2142}
2143
shiqian4b6829f2008-07-03 22:38:12 +00002144// A predicate-formatter functor that asserts the argument is an even
2145// number.
2146struct AssertIsEvenFunctor {
shiqian760af5c2008-08-06 21:43:15 +00002147 AssertionResult operator()(const char* expr, int n) {
shiqian4b6829f2008-07-03 22:38:12 +00002148 return AssertIsEven(expr, n);
2149 }
2150};
2151
2152// Returns true iff the sum of the arguments is an even number.
2153bool SumIsEven2(int n1, int n2) {
2154 return IsEven(n1 + n2);
2155}
2156
2157// A functor that returns true iff the sum of the arguments is an even
2158// number.
2159struct SumIsEven3Functor {
2160 bool operator()(int n1, int n2, int n3) {
2161 return IsEven(n1 + n2 + n3);
2162 }
2163};
2164
2165// A predicate-formatter function that asserts the sum of the
2166// arguments is an even number.
shiqian760af5c2008-08-06 21:43:15 +00002167AssertionResult AssertSumIsEven4(
2168 const char* e1, const char* e2, const char* e3, const char* e4,
2169 int n1, int n2, int n3, int n4) {
shiqian4b6829f2008-07-03 22:38:12 +00002170 const int sum = n1 + n2 + n3 + n4;
2171 if (IsEven(sum)) {
shiqian760af5c2008-08-06 21:43:15 +00002172 return AssertionSuccess();
shiqian4b6829f2008-07-03 22:38:12 +00002173 }
2174
shiqian760af5c2008-08-06 21:43:15 +00002175 Message msg;
shiqian4b6829f2008-07-03 22:38:12 +00002176 msg << e1 << " + " << e2 << " + " << e3 << " + " << e4
2177 << " (" << n1 << " + " << n2 << " + " << n3 << " + " << n4
2178 << ") evaluates to " << sum << ", which is not even.";
shiqian760af5c2008-08-06 21:43:15 +00002179 return AssertionFailure(msg);
shiqian4b6829f2008-07-03 22:38:12 +00002180}
2181
2182// A predicate-formatter functor that asserts the sum of the arguments
2183// is an even number.
2184struct AssertSumIsEven5Functor {
shiqian760af5c2008-08-06 21:43:15 +00002185 AssertionResult operator()(
2186 const char* e1, const char* e2, const char* e3, const char* e4,
2187 const char* e5, int n1, int n2, int n3, int n4, int n5) {
shiqian4b6829f2008-07-03 22:38:12 +00002188 const int sum = n1 + n2 + n3 + n4 + n5;
2189 if (IsEven(sum)) {
shiqian760af5c2008-08-06 21:43:15 +00002190 return AssertionSuccess();
shiqian4b6829f2008-07-03 22:38:12 +00002191 }
2192
shiqian760af5c2008-08-06 21:43:15 +00002193 Message msg;
shiqian4b6829f2008-07-03 22:38:12 +00002194 msg << e1 << " + " << e2 << " + " << e3 << " + " << e4 << " + " << e5
2195 << " ("
2196 << n1 << " + " << n2 << " + " << n3 << " + " << n4 << " + " << n5
2197 << ") evaluates to " << sum << ", which is not even.";
shiqian760af5c2008-08-06 21:43:15 +00002198 return AssertionFailure(msg);
shiqian4b6829f2008-07-03 22:38:12 +00002199 }
2200};
2201
2202
2203// Tests unary predicate assertions.
2204
2205// Tests unary predicate assertions that don't use a custom formatter.
2206TEST(Pred1Test, WithoutFormat) {
2207 // Success cases.
2208 EXPECT_PRED1(IsEvenFunctor(), 2) << "This failure is UNEXPECTED!";
2209 ASSERT_PRED1(IsEven, 4);
2210
2211 // Failure cases.
2212 EXPECT_NONFATAL_FAILURE({ // NOLINT
2213 EXPECT_PRED1(IsEven, 5) << "This failure is expected.";
2214 }, "This failure is expected.");
2215 EXPECT_FATAL_FAILURE(ASSERT_PRED1(IsEvenFunctor(), 5),
2216 "evaluates to false");
2217}
2218
2219// Tests unary predicate assertions that use a custom formatter.
2220TEST(Pred1Test, WithFormat) {
2221 // Success cases.
2222 EXPECT_PRED_FORMAT1(AssertIsEven, 2);
2223 ASSERT_PRED_FORMAT1(AssertIsEvenFunctor(), 4)
2224 << "This failure is UNEXPECTED!";
2225
2226 // Failure cases.
2227 const int n = 5;
2228 EXPECT_NONFATAL_FAILURE(EXPECT_PRED_FORMAT1(AssertIsEvenFunctor(), n),
2229 "n evaluates to 5, which is not even.");
2230 EXPECT_FATAL_FAILURE({ // NOLINT
2231 ASSERT_PRED_FORMAT1(AssertIsEven, 5) << "This failure is expected.";
2232 }, "This failure is expected.");
2233}
2234
2235// Tests that unary predicate assertions evaluates their arguments
2236// exactly once.
2237TEST(Pred1Test, SingleEvaluationOnFailure) {
2238 // A success case.
2239 static int n = 0;
2240 EXPECT_PRED1(IsEven, n++);
2241 EXPECT_EQ(1, n) << "The argument is not evaluated exactly once.";
2242
2243 // A failure case.
2244 EXPECT_FATAL_FAILURE({ // NOLINT
2245 ASSERT_PRED_FORMAT1(AssertIsEvenFunctor(), n++)
2246 << "This failure is expected.";
2247 }, "This failure is expected.");
2248 EXPECT_EQ(2, n) << "The argument is not evaluated exactly once.";
2249}
2250
2251
2252// Tests predicate assertions whose arity is >= 2.
2253
2254// Tests predicate assertions that don't use a custom formatter.
2255TEST(PredTest, WithoutFormat) {
2256 // Success cases.
2257 ASSERT_PRED2(SumIsEven2, 2, 4) << "This failure is UNEXPECTED!";
2258 EXPECT_PRED3(SumIsEven3Functor(), 4, 6, 8);
2259
2260 // Failure cases.
2261 const int n1 = 1;
2262 const int n2 = 2;
2263 EXPECT_NONFATAL_FAILURE({ // NOLINT
2264 EXPECT_PRED2(SumIsEven2, n1, n2) << "This failure is expected.";
2265 }, "This failure is expected.");
2266 EXPECT_FATAL_FAILURE({ // NOLINT
2267 ASSERT_PRED3(SumIsEven3Functor(), 1, 2, 4);
2268 }, "evaluates to false");
2269}
2270
2271// Tests predicate assertions that use a custom formatter.
2272TEST(PredTest, WithFormat) {
2273 // Success cases.
2274 ASSERT_PRED_FORMAT4(AssertSumIsEven4, 4, 6, 8, 10) <<
2275 "This failure is UNEXPECTED!";
2276 EXPECT_PRED_FORMAT5(AssertSumIsEven5Functor(), 2, 4, 6, 8, 10);
2277
2278 // Failure cases.
2279 const int n1 = 1;
2280 const int n2 = 2;
2281 const int n3 = 4;
2282 const int n4 = 6;
2283 EXPECT_NONFATAL_FAILURE({ // NOLINT
2284 EXPECT_PRED_FORMAT4(AssertSumIsEven4, n1, n2, n3, n4);
2285 }, "evaluates to 13, which is not even.");
2286 EXPECT_FATAL_FAILURE({ // NOLINT
2287 ASSERT_PRED_FORMAT5(AssertSumIsEven5Functor(), 1, 2, 4, 6, 8)
2288 << "This failure is expected.";
2289 }, "This failure is expected.");
2290}
2291
2292// Tests that predicate assertions evaluates their arguments
2293// exactly once.
2294TEST(PredTest, SingleEvaluationOnFailure) {
2295 // A success case.
2296 int n1 = 0;
2297 int n2 = 0;
2298 EXPECT_PRED2(SumIsEven2, n1++, n2++);
2299 EXPECT_EQ(1, n1) << "Argument 1 is not evaluated exactly once.";
2300 EXPECT_EQ(1, n2) << "Argument 2 is not evaluated exactly once.";
2301
2302 // Another success case.
2303 n1 = n2 = 0;
2304 int n3 = 0;
2305 int n4 = 0;
2306 int n5 = 0;
2307 ASSERT_PRED_FORMAT5(AssertSumIsEven5Functor(),
2308 n1++, n2++, n3++, n4++, n5++)
2309 << "This failure is UNEXPECTED!";
2310 EXPECT_EQ(1, n1) << "Argument 1 is not evaluated exactly once.";
2311 EXPECT_EQ(1, n2) << "Argument 2 is not evaluated exactly once.";
2312 EXPECT_EQ(1, n3) << "Argument 3 is not evaluated exactly once.";
2313 EXPECT_EQ(1, n4) << "Argument 4 is not evaluated exactly once.";
2314 EXPECT_EQ(1, n5) << "Argument 5 is not evaluated exactly once.";
2315
2316 // A failure case.
2317 n1 = n2 = n3 = 0;
2318 EXPECT_NONFATAL_FAILURE({ // NOLINT
2319 EXPECT_PRED3(SumIsEven3Functor(), ++n1, n2++, n3++)
2320 << "This failure is expected.";
2321 }, "This failure is expected.");
2322 EXPECT_EQ(1, n1) << "Argument 1 is not evaluated exactly once.";
2323 EXPECT_EQ(1, n2) << "Argument 2 is not evaluated exactly once.";
2324 EXPECT_EQ(1, n3) << "Argument 3 is not evaluated exactly once.";
2325
2326 // Another failure case.
2327 n1 = n2 = n3 = n4 = 0;
2328 EXPECT_NONFATAL_FAILURE({ // NOLINT
2329 EXPECT_PRED_FORMAT4(AssertSumIsEven4, ++n1, n2++, n3++, n4++);
2330 }, "evaluates to 1, which is not even.");
2331 EXPECT_EQ(1, n1) << "Argument 1 is not evaluated exactly once.";
2332 EXPECT_EQ(1, n2) << "Argument 2 is not evaluated exactly once.";
2333 EXPECT_EQ(1, n3) << "Argument 3 is not evaluated exactly once.";
2334 EXPECT_EQ(1, n4) << "Argument 4 is not evaluated exactly once.";
2335}
2336
2337
2338// Some helper functions for testing using overloaded/template
2339// functions with ASSERT_PREDn and EXPECT_PREDn.
2340
shiqian4b6829f2008-07-03 22:38:12 +00002341bool IsPositive(double x) {
2342 return x > 0;
2343}
2344
2345template <typename T>
2346bool IsNegative(T x) {
2347 return x < 0;
2348}
2349
2350template <typename T1, typename T2>
2351bool GreaterThan(T1 x1, T2 x2) {
2352 return x1 > x2;
2353}
2354
2355// Tests that overloaded functions can be used in *_PRED* as long as
2356// their types are explicitly specified.
2357TEST(PredicateAssertionTest, AcceptsOverloadedFunction) {
zhanyong.wan98efcc42009-04-28 00:28:09 +00002358 // C++Builder requires C-style casts rather than static_cast.
2359 EXPECT_PRED1((bool (*)(int))(IsPositive), 5); // NOLINT
2360 ASSERT_PRED1((bool (*)(double))(IsPositive), 6.0); // NOLINT
shiqian4b6829f2008-07-03 22:38:12 +00002361}
2362
2363// Tests that template functions can be used in *_PRED* as long as
2364// their types are explicitly specified.
2365TEST(PredicateAssertionTest, AcceptsTemplateFunction) {
2366 EXPECT_PRED1(IsNegative<int>, -5);
2367 // Makes sure that we can handle templates with more than one
2368 // parameter.
2369 ASSERT_PRED2((GreaterThan<int, int>), 5, 0);
2370}
2371
2372
2373// Some helper functions for testing using overloaded/template
2374// functions with ASSERT_PRED_FORMATn and EXPECT_PRED_FORMATn.
2375
zhanyong.wanb0a12f72009-01-29 06:49:00 +00002376AssertionResult IsPositiveFormat(const char* /* expr */, int n) {
shiqian760af5c2008-08-06 21:43:15 +00002377 return n > 0 ? AssertionSuccess() :
2378 AssertionFailure(Message() << "Failure");
shiqian4b6829f2008-07-03 22:38:12 +00002379}
2380
zhanyong.wanb0a12f72009-01-29 06:49:00 +00002381AssertionResult IsPositiveFormat(const char* /* expr */, double x) {
shiqian760af5c2008-08-06 21:43:15 +00002382 return x > 0 ? AssertionSuccess() :
2383 AssertionFailure(Message() << "Failure");
shiqian4b6829f2008-07-03 22:38:12 +00002384}
2385
2386template <typename T>
zhanyong.wanb0a12f72009-01-29 06:49:00 +00002387AssertionResult IsNegativeFormat(const char* /* expr */, T x) {
shiqian760af5c2008-08-06 21:43:15 +00002388 return x < 0 ? AssertionSuccess() :
2389 AssertionFailure(Message() << "Failure");
shiqian4b6829f2008-07-03 22:38:12 +00002390}
2391
2392template <typename T1, typename T2>
zhanyong.wanb0a12f72009-01-29 06:49:00 +00002393AssertionResult EqualsFormat(const char* /* expr1 */, const char* /* expr2 */,
shiqian760af5c2008-08-06 21:43:15 +00002394 const T1& x1, const T2& x2) {
2395 return x1 == x2 ? AssertionSuccess() :
2396 AssertionFailure(Message() << "Failure");
shiqian4b6829f2008-07-03 22:38:12 +00002397}
2398
2399// Tests that overloaded functions can be used in *_PRED_FORMAT*
zhanyong.wanb0a12f72009-01-29 06:49:00 +00002400// without explicitly specifying their types.
shiqian4b6829f2008-07-03 22:38:12 +00002401TEST(PredicateFormatAssertionTest, AcceptsOverloadedFunction) {
2402 EXPECT_PRED_FORMAT1(IsPositiveFormat, 5);
2403 ASSERT_PRED_FORMAT1(IsPositiveFormat, 6.0);
2404}
2405
2406// Tests that template functions can be used in *_PRED_FORMAT* without
2407// explicitly specifying their types.
2408TEST(PredicateFormatAssertionTest, AcceptsTemplateFunction) {
2409 EXPECT_PRED_FORMAT1(IsNegativeFormat, -5);
2410 ASSERT_PRED_FORMAT2(EqualsFormat, 3, 3);
2411}
2412
2413
2414// Tests string assertions.
2415
2416// Tests ASSERT_STREQ with non-NULL arguments.
2417TEST(StringAssertionTest, ASSERT_STREQ) {
2418 const char * const p1 = "good";
2419 ASSERT_STREQ(p1, p1);
2420
2421 // Let p2 have the same content as p1, but be at a different address.
2422 const char p2[] = "good";
2423 ASSERT_STREQ(p1, p2);
2424
2425 EXPECT_FATAL_FAILURE(ASSERT_STREQ("bad", "good"),
2426 "Expected: \"bad\"");
2427}
2428
2429// Tests ASSERT_STREQ with NULL arguments.
2430TEST(StringAssertionTest, ASSERT_STREQ_Null) {
2431 ASSERT_STREQ(static_cast<const char *>(NULL), NULL);
2432 EXPECT_FATAL_FAILURE(ASSERT_STREQ(NULL, "non-null"),
2433 "non-null");
2434}
2435
2436// Tests ASSERT_STREQ with NULL arguments.
2437TEST(StringAssertionTest, ASSERT_STREQ_Null2) {
2438 EXPECT_FATAL_FAILURE(ASSERT_STREQ("non-null", NULL),
2439 "non-null");
2440}
2441
2442// Tests ASSERT_STRNE.
2443TEST(StringAssertionTest, ASSERT_STRNE) {
2444 ASSERT_STRNE("hi", "Hi");
2445 ASSERT_STRNE("Hi", NULL);
2446 ASSERT_STRNE(NULL, "Hi");
2447 ASSERT_STRNE("", NULL);
2448 ASSERT_STRNE(NULL, "");
2449 ASSERT_STRNE("", "Hi");
2450 ASSERT_STRNE("Hi", "");
2451 EXPECT_FATAL_FAILURE(ASSERT_STRNE("Hi", "Hi"),
2452 "\"Hi\" vs \"Hi\"");
2453}
2454
2455// Tests ASSERT_STRCASEEQ.
2456TEST(StringAssertionTest, ASSERT_STRCASEEQ) {
2457 ASSERT_STRCASEEQ("hi", "Hi");
2458 ASSERT_STRCASEEQ(static_cast<const char *>(NULL), NULL);
2459
2460 ASSERT_STRCASEEQ("", "");
2461 EXPECT_FATAL_FAILURE(ASSERT_STRCASEEQ("Hi", "hi2"),
2462 "(ignoring case)");
2463}
2464
2465// Tests ASSERT_STRCASENE.
2466TEST(StringAssertionTest, ASSERT_STRCASENE) {
2467 ASSERT_STRCASENE("hi1", "Hi2");
2468 ASSERT_STRCASENE("Hi", NULL);
2469 ASSERT_STRCASENE(NULL, "Hi");
2470 ASSERT_STRCASENE("", NULL);
2471 ASSERT_STRCASENE(NULL, "");
2472 ASSERT_STRCASENE("", "Hi");
2473 ASSERT_STRCASENE("Hi", "");
2474 EXPECT_FATAL_FAILURE(ASSERT_STRCASENE("Hi", "hi"),
2475 "(ignoring case)");
2476}
2477
2478// Tests *_STREQ on wide strings.
2479TEST(StringAssertionTest, STREQ_Wide) {
2480 // NULL strings.
2481 ASSERT_STREQ(static_cast<const wchar_t *>(NULL), NULL);
2482
2483 // Empty strings.
2484 ASSERT_STREQ(L"", L"");
2485
2486 // Non-null vs NULL.
2487 EXPECT_NONFATAL_FAILURE(EXPECT_STREQ(L"non-null", NULL),
2488 "non-null");
2489
2490 // Equal strings.
2491 EXPECT_STREQ(L"Hi", L"Hi");
2492
2493 // Unequal strings.
2494 EXPECT_NONFATAL_FAILURE(EXPECT_STREQ(L"abc", L"Abc"),
2495 "Abc");
2496
2497 // Strings containing wide characters.
2498 EXPECT_NONFATAL_FAILURE(EXPECT_STREQ(L"abc\x8119", L"abc\x8120"),
2499 "abc");
jgm@google.com7a574c92012-03-09 17:12:39 +00002500
2501 // The streaming variation.
2502 EXPECT_NONFATAL_FAILURE({ // NOLINT
2503 EXPECT_STREQ(L"abc\x8119", L"abc\x8121") << "Expected failure";
2504 }, "Expected failure");
shiqian4b6829f2008-07-03 22:38:12 +00002505}
2506
2507// Tests *_STRNE on wide strings.
2508TEST(StringAssertionTest, STRNE_Wide) {
2509 // NULL strings.
2510 EXPECT_NONFATAL_FAILURE({ // NOLINT
2511 EXPECT_STRNE(static_cast<const wchar_t *>(NULL), NULL);
2512 }, "");
2513
2514 // Empty strings.
2515 EXPECT_NONFATAL_FAILURE(EXPECT_STRNE(L"", L""),
2516 "L\"\"");
2517
2518 // Non-null vs NULL.
2519 ASSERT_STRNE(L"non-null", NULL);
2520
2521 // Equal strings.
2522 EXPECT_NONFATAL_FAILURE(EXPECT_STRNE(L"Hi", L"Hi"),
2523 "L\"Hi\"");
2524
2525 // Unequal strings.
2526 EXPECT_STRNE(L"abc", L"Abc");
2527
2528 // Strings containing wide characters.
2529 EXPECT_NONFATAL_FAILURE(EXPECT_STRNE(L"abc\x8119", L"abc\x8119"),
2530 "abc");
jgm@google.com7a574c92012-03-09 17:12:39 +00002531
2532 // The streaming variation.
2533 ASSERT_STRNE(L"abc\x8119", L"abc\x8120") << "This shouldn't happen";
shiqian4b6829f2008-07-03 22:38:12 +00002534}
2535
2536// Tests for ::testing::IsSubstring().
2537
2538// Tests that IsSubstring() returns the correct result when the input
2539// argument type is const char*.
2540TEST(IsSubstringTest, ReturnsCorrectResultForCString) {
shiqian4b6829f2008-07-03 22:38:12 +00002541 EXPECT_FALSE(IsSubstring("", "", NULL, "a"));
2542 EXPECT_FALSE(IsSubstring("", "", "b", NULL));
2543 EXPECT_FALSE(IsSubstring("", "", "needle", "haystack"));
2544
2545 EXPECT_TRUE(IsSubstring("", "", static_cast<const char*>(NULL), NULL));
2546 EXPECT_TRUE(IsSubstring("", "", "needle", "two needles"));
2547}
2548
2549// Tests that IsSubstring() returns the correct result when the input
2550// argument type is const wchar_t*.
2551TEST(IsSubstringTest, ReturnsCorrectResultForWideCString) {
zhanyong.wan98efcc42009-04-28 00:28:09 +00002552 EXPECT_FALSE(IsSubstring("", "", kNull, L"a"));
2553 EXPECT_FALSE(IsSubstring("", "", L"b", kNull));
shiqian4b6829f2008-07-03 22:38:12 +00002554 EXPECT_FALSE(IsSubstring("", "", L"needle", L"haystack"));
2555
2556 EXPECT_TRUE(IsSubstring("", "", static_cast<const wchar_t*>(NULL), NULL));
2557 EXPECT_TRUE(IsSubstring("", "", L"needle", L"two needles"));
2558}
2559
2560// Tests that IsSubstring() generates the correct message when the input
2561// argument type is const char*.
2562TEST(IsSubstringTest, GeneratesCorrectMessageForCString) {
2563 EXPECT_STREQ("Value of: needle_expr\n"
2564 " Actual: \"needle\"\n"
2565 "Expected: a substring of haystack_expr\n"
2566 "Which is: \"haystack\"",
shiqian760af5c2008-08-06 21:43:15 +00002567 IsSubstring("needle_expr", "haystack_expr",
2568 "needle", "haystack").failure_message());
shiqian4b6829f2008-07-03 22:38:12 +00002569}
2570
shiqian4b6829f2008-07-03 22:38:12 +00002571// Tests that IsSubstring returns the correct result when the input
2572// argument type is ::std::string.
2573TEST(IsSubstringTest, ReturnsCorrectResultsForStdString) {
shiqian760af5c2008-08-06 21:43:15 +00002574 EXPECT_TRUE(IsSubstring("", "", std::string("hello"), "ahellob"));
2575 EXPECT_FALSE(IsSubstring("", "", "hello", std::string("world")));
shiqian4b6829f2008-07-03 22:38:12 +00002576}
2577
shiqian4b6829f2008-07-03 22:38:12 +00002578#if GTEST_HAS_STD_WSTRING
2579// Tests that IsSubstring returns the correct result when the input
2580// argument type is ::std::wstring.
2581TEST(IsSubstringTest, ReturnsCorrectResultForStdWstring) {
shiqian4b6829f2008-07-03 22:38:12 +00002582 EXPECT_TRUE(IsSubstring("", "", ::std::wstring(L"needle"), L"two needles"));
2583 EXPECT_FALSE(IsSubstring("", "", L"needle", ::std::wstring(L"haystack")));
2584}
2585
2586// Tests that IsSubstring() generates the correct message when the input
2587// argument type is ::std::wstring.
2588TEST(IsSubstringTest, GeneratesCorrectMessageForWstring) {
2589 EXPECT_STREQ("Value of: needle_expr\n"
2590 " Actual: L\"needle\"\n"
2591 "Expected: a substring of haystack_expr\n"
2592 "Which is: L\"haystack\"",
shiqian760af5c2008-08-06 21:43:15 +00002593 IsSubstring(
shiqian4b6829f2008-07-03 22:38:12 +00002594 "needle_expr", "haystack_expr",
2595 ::std::wstring(L"needle"), L"haystack").failure_message());
2596}
2597
2598#endif // GTEST_HAS_STD_WSTRING
2599
2600// Tests for ::testing::IsNotSubstring().
2601
2602// Tests that IsNotSubstring() returns the correct result when the input
2603// argument type is const char*.
2604TEST(IsNotSubstringTest, ReturnsCorrectResultForCString) {
shiqian4b6829f2008-07-03 22:38:12 +00002605 EXPECT_TRUE(IsNotSubstring("", "", "needle", "haystack"));
2606 EXPECT_FALSE(IsNotSubstring("", "", "needle", "two needles"));
2607}
2608
2609// Tests that IsNotSubstring() returns the correct result when the input
2610// argument type is const wchar_t*.
2611TEST(IsNotSubstringTest, ReturnsCorrectResultForWideCString) {
shiqian4b6829f2008-07-03 22:38:12 +00002612 EXPECT_TRUE(IsNotSubstring("", "", L"needle", L"haystack"));
2613 EXPECT_FALSE(IsNotSubstring("", "", L"needle", L"two needles"));
2614}
2615
2616// Tests that IsNotSubstring() generates the correct message when the input
2617// argument type is const wchar_t*.
2618TEST(IsNotSubstringTest, GeneratesCorrectMessageForWideCString) {
2619 EXPECT_STREQ("Value of: needle_expr\n"
2620 " Actual: L\"needle\"\n"
2621 "Expected: not a substring of haystack_expr\n"
2622 "Which is: L\"two needles\"",
shiqian760af5c2008-08-06 21:43:15 +00002623 IsNotSubstring(
shiqian4b6829f2008-07-03 22:38:12 +00002624 "needle_expr", "haystack_expr",
2625 L"needle", L"two needles").failure_message());
2626}
2627
shiqian4b6829f2008-07-03 22:38:12 +00002628// Tests that IsNotSubstring returns the correct result when the input
2629// argument type is ::std::string.
2630TEST(IsNotSubstringTest, ReturnsCorrectResultsForStdString) {
shiqian4b6829f2008-07-03 22:38:12 +00002631 EXPECT_FALSE(IsNotSubstring("", "", std::string("hello"), "ahellob"));
2632 EXPECT_TRUE(IsNotSubstring("", "", "hello", std::string("world")));
2633}
2634
2635// Tests that IsNotSubstring() generates the correct message when the input
2636// argument type is ::std::string.
2637TEST(IsNotSubstringTest, GeneratesCorrectMessageForStdString) {
2638 EXPECT_STREQ("Value of: needle_expr\n"
2639 " Actual: \"needle\"\n"
2640 "Expected: not a substring of haystack_expr\n"
2641 "Which is: \"two needles\"",
shiqian760af5c2008-08-06 21:43:15 +00002642 IsNotSubstring(
shiqian4b6829f2008-07-03 22:38:12 +00002643 "needle_expr", "haystack_expr",
2644 ::std::string("needle"), "two needles").failure_message());
2645}
2646
shiqian4b6829f2008-07-03 22:38:12 +00002647#if GTEST_HAS_STD_WSTRING
2648
2649// Tests that IsNotSubstring returns the correct result when the input
2650// argument type is ::std::wstring.
2651TEST(IsNotSubstringTest, ReturnsCorrectResultForStdWstring) {
shiqian4b6829f2008-07-03 22:38:12 +00002652 EXPECT_FALSE(
2653 IsNotSubstring("", "", ::std::wstring(L"needle"), L"two needles"));
2654 EXPECT_TRUE(IsNotSubstring("", "", L"needle", ::std::wstring(L"haystack")));
2655}
2656
2657#endif // GTEST_HAS_STD_WSTRING
2658
2659// Tests floating-point assertions.
2660
2661template <typename RawType>
shiqian760af5c2008-08-06 21:43:15 +00002662class FloatingPointTest : public Test {
shiqian4b6829f2008-07-03 22:38:12 +00002663 protected:
zhanyong.wan98efcc42009-04-28 00:28:09 +00002664 // Pre-calculated numbers to be used by the tests.
2665 struct TestValues {
2666 RawType close_to_positive_zero;
2667 RawType close_to_negative_zero;
2668 RawType further_from_negative_zero;
2669
2670 RawType close_to_one;
2671 RawType further_from_one;
2672
2673 RawType infinity;
2674 RawType close_to_infinity;
2675 RawType further_from_infinity;
2676
2677 RawType nan1;
2678 RawType nan2;
2679 };
2680
shiqian4b6829f2008-07-03 22:38:12 +00002681 typedef typename testing::internal::FloatingPoint<RawType> Floating;
2682 typedef typename Floating::Bits Bits;
2683
2684 virtual void SetUp() {
2685 const size_t max_ulps = Floating::kMaxUlps;
2686
2687 // The bits that represent 0.0.
2688 const Bits zero_bits = Floating(0).bits();
2689
2690 // Makes some numbers close to 0.0.
zhanyong.wan98efcc42009-04-28 00:28:09 +00002691 values_.close_to_positive_zero = Floating::ReinterpretBits(
2692 zero_bits + max_ulps/2);
2693 values_.close_to_negative_zero = -Floating::ReinterpretBits(
shiqian4b6829f2008-07-03 22:38:12 +00002694 zero_bits + max_ulps - max_ulps/2);
zhanyong.wan98efcc42009-04-28 00:28:09 +00002695 values_.further_from_negative_zero = -Floating::ReinterpretBits(
shiqian4b6829f2008-07-03 22:38:12 +00002696 zero_bits + max_ulps + 1 - max_ulps/2);
2697
2698 // The bits that represent 1.0.
2699 const Bits one_bits = Floating(1).bits();
2700
2701 // Makes some numbers close to 1.0.
zhanyong.wan98efcc42009-04-28 00:28:09 +00002702 values_.close_to_one = Floating::ReinterpretBits(one_bits + max_ulps);
2703 values_.further_from_one = Floating::ReinterpretBits(
2704 one_bits + max_ulps + 1);
shiqian4b6829f2008-07-03 22:38:12 +00002705
2706 // +infinity.
zhanyong.wan98efcc42009-04-28 00:28:09 +00002707 values_.infinity = Floating::Infinity();
shiqian4b6829f2008-07-03 22:38:12 +00002708
2709 // The bits that represent +infinity.
zhanyong.wan98efcc42009-04-28 00:28:09 +00002710 const Bits infinity_bits = Floating(values_.infinity).bits();
shiqian4b6829f2008-07-03 22:38:12 +00002711
2712 // Makes some numbers close to infinity.
zhanyong.wan98efcc42009-04-28 00:28:09 +00002713 values_.close_to_infinity = Floating::ReinterpretBits(
2714 infinity_bits - max_ulps);
2715 values_.further_from_infinity = Floating::ReinterpretBits(
shiqian4b6829f2008-07-03 22:38:12 +00002716 infinity_bits - max_ulps - 1);
2717
zhanyong.wan98efcc42009-04-28 00:28:09 +00002718 // Makes some NAN's. Sets the most significant bit of the fraction so that
2719 // our NaN's are quiet; trying to process a signaling NaN would raise an
2720 // exception if our environment enables floating point exceptions.
2721 values_.nan1 = Floating::ReinterpretBits(Floating::kExponentBitMask
2722 | (static_cast<Bits>(1) << (Floating::kFractionBitCount - 1)) | 1);
2723 values_.nan2 = Floating::ReinterpretBits(Floating::kExponentBitMask
2724 | (static_cast<Bits>(1) << (Floating::kFractionBitCount - 1)) | 200);
shiqian4b6829f2008-07-03 22:38:12 +00002725 }
2726
2727 void TestSize() {
2728 EXPECT_EQ(sizeof(RawType), sizeof(Bits));
2729 }
2730
zhanyong.wan98efcc42009-04-28 00:28:09 +00002731 static TestValues values_;
shiqian4b6829f2008-07-03 22:38:12 +00002732};
2733
2734template <typename RawType>
zhanyong.wan98efcc42009-04-28 00:28:09 +00002735typename FloatingPointTest<RawType>::TestValues
2736 FloatingPointTest<RawType>::values_;
shiqian4b6829f2008-07-03 22:38:12 +00002737
2738// Instantiates FloatingPointTest for testing *_FLOAT_EQ.
2739typedef FloatingPointTest<float> FloatTest;
2740
2741// Tests that the size of Float::Bits matches the size of float.
2742TEST_F(FloatTest, Size) {
2743 TestSize();
2744}
2745
2746// Tests comparing with +0 and -0.
2747TEST_F(FloatTest, Zeros) {
2748 EXPECT_FLOAT_EQ(0.0, -0.0);
2749 EXPECT_NONFATAL_FAILURE(EXPECT_FLOAT_EQ(-0.0, 1.0),
2750 "1.0");
2751 EXPECT_FATAL_FAILURE(ASSERT_FLOAT_EQ(0.0, 1.5),
2752 "1.5");
2753}
2754
2755// Tests comparing numbers close to 0.
2756//
2757// This ensures that *_FLOAT_EQ handles the sign correctly and no
2758// overflow occurs when comparing numbers whose absolute value is very
2759// small.
2760TEST_F(FloatTest, AlmostZeros) {
zhanyong.wan98efcc42009-04-28 00:28:09 +00002761 // In C++Builder, names within local classes (such as used by
2762 // EXPECT_FATAL_FAILURE) cannot be resolved against static members of the
2763 // scoping class. Use a static local alias as a workaround.
vladlosev673a0cb2010-02-03 02:27:02 +00002764 // We use the assignment syntax since some compilers, like Sun Studio,
2765 // don't allow initializing references using construction syntax
2766 // (parentheses).
2767 static const FloatTest::TestValues& v = this->values_;
zhanyong.wan98efcc42009-04-28 00:28:09 +00002768
2769 EXPECT_FLOAT_EQ(0.0, v.close_to_positive_zero);
2770 EXPECT_FLOAT_EQ(-0.0, v.close_to_negative_zero);
2771 EXPECT_FLOAT_EQ(v.close_to_positive_zero, v.close_to_negative_zero);
shiqian4b6829f2008-07-03 22:38:12 +00002772
2773 EXPECT_FATAL_FAILURE({ // NOLINT
zhanyong.wan98efcc42009-04-28 00:28:09 +00002774 ASSERT_FLOAT_EQ(v.close_to_positive_zero,
2775 v.further_from_negative_zero);
2776 }, "v.further_from_negative_zero");
shiqian4b6829f2008-07-03 22:38:12 +00002777}
2778
2779// Tests comparing numbers close to each other.
2780TEST_F(FloatTest, SmallDiff) {
zhanyong.wan98efcc42009-04-28 00:28:09 +00002781 EXPECT_FLOAT_EQ(1.0, values_.close_to_one);
2782 EXPECT_NONFATAL_FAILURE(EXPECT_FLOAT_EQ(1.0, values_.further_from_one),
2783 "values_.further_from_one");
shiqian4b6829f2008-07-03 22:38:12 +00002784}
2785
2786// Tests comparing numbers far apart.
2787TEST_F(FloatTest, LargeDiff) {
2788 EXPECT_NONFATAL_FAILURE(EXPECT_FLOAT_EQ(2.5, 3.0),
2789 "3.0");
2790}
2791
2792// Tests comparing with infinity.
2793//
2794// This ensures that no overflow occurs when comparing numbers whose
2795// absolute value is very large.
2796TEST_F(FloatTest, Infinity) {
zhanyong.wan98efcc42009-04-28 00:28:09 +00002797 EXPECT_FLOAT_EQ(values_.infinity, values_.close_to_infinity);
2798 EXPECT_FLOAT_EQ(-values_.infinity, -values_.close_to_infinity);
zhanyong.wan4cd62602009-02-23 23:21:55 +00002799#if !GTEST_OS_SYMBIAN
shiqiane44602e2008-10-11 07:20:02 +00002800 // Nokia's STLport crashes if we try to output infinity or NaN.
zhanyong.wan98efcc42009-04-28 00:28:09 +00002801 EXPECT_NONFATAL_FAILURE(EXPECT_FLOAT_EQ(values_.infinity, -values_.infinity),
2802 "-values_.infinity");
shiqian4b6829f2008-07-03 22:38:12 +00002803
zhanyong.wan98efcc42009-04-28 00:28:09 +00002804 // This is interesting as the representations of infinity and nan1
shiqian4b6829f2008-07-03 22:38:12 +00002805 // are only 1 DLP apart.
zhanyong.wan98efcc42009-04-28 00:28:09 +00002806 EXPECT_NONFATAL_FAILURE(EXPECT_FLOAT_EQ(values_.infinity, values_.nan1),
2807 "values_.nan1");
zhanyong.wan4cd62602009-02-23 23:21:55 +00002808#endif // !GTEST_OS_SYMBIAN
shiqian4b6829f2008-07-03 22:38:12 +00002809}
2810
2811// Tests that comparing with NAN always returns false.
2812TEST_F(FloatTest, NaN) {
zhanyong.wan4cd62602009-02-23 23:21:55 +00002813#if !GTEST_OS_SYMBIAN
shiqiane44602e2008-10-11 07:20:02 +00002814// Nokia's STLport crashes if we try to output infinity or NaN.
shiqian4b6829f2008-07-03 22:38:12 +00002815
zhanyong.wan98efcc42009-04-28 00:28:09 +00002816 // In C++Builder, names within local classes (such as used by
2817 // EXPECT_FATAL_FAILURE) cannot be resolved against static members of the
2818 // scoping class. Use a static local alias as a workaround.
vladlosev673a0cb2010-02-03 02:27:02 +00002819 // We use the assignment syntax since some compilers, like Sun Studio,
2820 // don't allow initializing references using construction syntax
2821 // (parentheses).
2822 static const FloatTest::TestValues& v = this->values_;
zhanyong.wan98efcc42009-04-28 00:28:09 +00002823
2824 EXPECT_NONFATAL_FAILURE(EXPECT_FLOAT_EQ(v.nan1, v.nan1),
2825 "v.nan1");
2826 EXPECT_NONFATAL_FAILURE(EXPECT_FLOAT_EQ(v.nan1, v.nan2),
2827 "v.nan2");
2828 EXPECT_NONFATAL_FAILURE(EXPECT_FLOAT_EQ(1.0, v.nan1),
2829 "v.nan1");
2830
2831 EXPECT_FATAL_FAILURE(ASSERT_FLOAT_EQ(v.nan1, v.infinity),
2832 "v.infinity");
zhanyong.wan4cd62602009-02-23 23:21:55 +00002833#endif // !GTEST_OS_SYMBIAN
shiqian4b6829f2008-07-03 22:38:12 +00002834}
2835
2836// Tests that *_FLOAT_EQ are reflexive.
2837TEST_F(FloatTest, Reflexive) {
2838 EXPECT_FLOAT_EQ(0.0, 0.0);
2839 EXPECT_FLOAT_EQ(1.0, 1.0);
zhanyong.wan98efcc42009-04-28 00:28:09 +00002840 ASSERT_FLOAT_EQ(values_.infinity, values_.infinity);
shiqian4b6829f2008-07-03 22:38:12 +00002841}
2842
2843// Tests that *_FLOAT_EQ are commutative.
2844TEST_F(FloatTest, Commutative) {
zhanyong.wan98efcc42009-04-28 00:28:09 +00002845 // We already tested EXPECT_FLOAT_EQ(1.0, values_.close_to_one).
2846 EXPECT_FLOAT_EQ(values_.close_to_one, 1.0);
shiqian4b6829f2008-07-03 22:38:12 +00002847
zhanyong.wan98efcc42009-04-28 00:28:09 +00002848 // We already tested EXPECT_FLOAT_EQ(1.0, values_.further_from_one).
2849 EXPECT_NONFATAL_FAILURE(EXPECT_FLOAT_EQ(values_.further_from_one, 1.0),
shiqian4b6829f2008-07-03 22:38:12 +00002850 "1.0");
2851}
2852
2853// Tests EXPECT_NEAR.
2854TEST_F(FloatTest, EXPECT_NEAR) {
2855 EXPECT_NEAR(-1.0f, -1.1f, 0.2f);
2856 EXPECT_NEAR(2.0f, 3.0f, 1.0f);
zhanyong.wan65de7e02010-01-08 00:23:45 +00002857 EXPECT_NONFATAL_FAILURE(EXPECT_NEAR(1.0f,1.5f, 0.25f), // NOLINT
2858 "The difference between 1.0f and 1.5f is 0.5, "
2859 "which exceeds 0.25f");
shiqian4b6829f2008-07-03 22:38:12 +00002860 // To work around a bug in gcc 2.95.0, there is intentionally no
2861 // space after the first comma in the previous line.
2862}
2863
2864// Tests ASSERT_NEAR.
2865TEST_F(FloatTest, ASSERT_NEAR) {
2866 ASSERT_NEAR(-1.0f, -1.1f, 0.2f);
2867 ASSERT_NEAR(2.0f, 3.0f, 1.0f);
zhanyong.wan65de7e02010-01-08 00:23:45 +00002868 EXPECT_FATAL_FAILURE(ASSERT_NEAR(1.0f,1.5f, 0.25f), // NOLINT
2869 "The difference between 1.0f and 1.5f is 0.5, "
2870 "which exceeds 0.25f");
shiqian4b6829f2008-07-03 22:38:12 +00002871 // To work around a bug in gcc 2.95.0, there is intentionally no
2872 // space after the first comma in the previous line.
2873}
2874
2875// Tests the cases where FloatLE() should succeed.
2876TEST_F(FloatTest, FloatLESucceeds) {
shiqian760af5c2008-08-06 21:43:15 +00002877 EXPECT_PRED_FORMAT2(FloatLE, 1.0f, 2.0f); // When val1 < val2,
2878 ASSERT_PRED_FORMAT2(FloatLE, 1.0f, 1.0f); // val1 == val2,
shiqian4b6829f2008-07-03 22:38:12 +00002879
2880 // or when val1 is greater than, but almost equals to, val2.
zhanyong.wan98efcc42009-04-28 00:28:09 +00002881 EXPECT_PRED_FORMAT2(FloatLE, values_.close_to_positive_zero, 0.0f);
shiqian4b6829f2008-07-03 22:38:12 +00002882}
2883
2884// Tests the cases where FloatLE() should fail.
2885TEST_F(FloatTest, FloatLEFails) {
2886 // When val1 is greater than val2 by a large margin,
shiqian760af5c2008-08-06 21:43:15 +00002887 EXPECT_NONFATAL_FAILURE(EXPECT_PRED_FORMAT2(FloatLE, 2.0f, 1.0f),
shiqian4b6829f2008-07-03 22:38:12 +00002888 "(2.0f) <= (1.0f)");
2889
2890 // or by a small yet non-negligible margin,
2891 EXPECT_NONFATAL_FAILURE({ // NOLINT
zhanyong.wan98efcc42009-04-28 00:28:09 +00002892 EXPECT_PRED_FORMAT2(FloatLE, values_.further_from_one, 1.0f);
2893 }, "(values_.further_from_one) <= (1.0f)");
shiqian4b6829f2008-07-03 22:38:12 +00002894
zhanyong.wan98efcc42009-04-28 00:28:09 +00002895#if !GTEST_OS_SYMBIAN && !defined(__BORLANDC__)
shiqiane44602e2008-10-11 07:20:02 +00002896 // Nokia's STLport crashes if we try to output infinity or NaN.
zhanyong.wan98efcc42009-04-28 00:28:09 +00002897 // C++Builder gives bad results for ordered comparisons involving NaNs
2898 // due to compiler bugs.
shiqian4b6829f2008-07-03 22:38:12 +00002899 EXPECT_NONFATAL_FAILURE({ // NOLINT
zhanyong.wan98efcc42009-04-28 00:28:09 +00002900 EXPECT_PRED_FORMAT2(FloatLE, values_.nan1, values_.infinity);
2901 }, "(values_.nan1) <= (values_.infinity)");
shiqian4b6829f2008-07-03 22:38:12 +00002902 EXPECT_NONFATAL_FAILURE({ // NOLINT
zhanyong.wan98efcc42009-04-28 00:28:09 +00002903 EXPECT_PRED_FORMAT2(FloatLE, -values_.infinity, values_.nan1);
2904 }, "(-values_.infinity) <= (values_.nan1)");
shiqian4b6829f2008-07-03 22:38:12 +00002905 EXPECT_FATAL_FAILURE({ // NOLINT
zhanyong.wan98efcc42009-04-28 00:28:09 +00002906 ASSERT_PRED_FORMAT2(FloatLE, values_.nan1, values_.nan1);
2907 }, "(values_.nan1) <= (values_.nan1)");
2908#endif // !GTEST_OS_SYMBIAN && !defined(__BORLANDC__)
shiqian4b6829f2008-07-03 22:38:12 +00002909}
2910
2911// Instantiates FloatingPointTest for testing *_DOUBLE_EQ.
2912typedef FloatingPointTest<double> DoubleTest;
2913
2914// Tests that the size of Double::Bits matches the size of double.
2915TEST_F(DoubleTest, Size) {
2916 TestSize();
2917}
2918
2919// Tests comparing with +0 and -0.
2920TEST_F(DoubleTest, Zeros) {
2921 EXPECT_DOUBLE_EQ(0.0, -0.0);
2922 EXPECT_NONFATAL_FAILURE(EXPECT_DOUBLE_EQ(-0.0, 1.0),
2923 "1.0");
2924 EXPECT_FATAL_FAILURE(ASSERT_DOUBLE_EQ(0.0, 1.0),
2925 "1.0");
2926}
2927
2928// Tests comparing numbers close to 0.
2929//
2930// This ensures that *_DOUBLE_EQ handles the sign correctly and no
2931// overflow occurs when comparing numbers whose absolute value is very
2932// small.
2933TEST_F(DoubleTest, AlmostZeros) {
zhanyong.wan98efcc42009-04-28 00:28:09 +00002934 // In C++Builder, names within local classes (such as used by
2935 // EXPECT_FATAL_FAILURE) cannot be resolved against static members of the
2936 // scoping class. Use a static local alias as a workaround.
vladlosev673a0cb2010-02-03 02:27:02 +00002937 // We use the assignment syntax since some compilers, like Sun Studio,
2938 // don't allow initializing references using construction syntax
2939 // (parentheses).
2940 static const DoubleTest::TestValues& v = this->values_;
zhanyong.wan98efcc42009-04-28 00:28:09 +00002941
2942 EXPECT_DOUBLE_EQ(0.0, v.close_to_positive_zero);
2943 EXPECT_DOUBLE_EQ(-0.0, v.close_to_negative_zero);
2944 EXPECT_DOUBLE_EQ(v.close_to_positive_zero, v.close_to_negative_zero);
shiqian4b6829f2008-07-03 22:38:12 +00002945
2946 EXPECT_FATAL_FAILURE({ // NOLINT
zhanyong.wan98efcc42009-04-28 00:28:09 +00002947 ASSERT_DOUBLE_EQ(v.close_to_positive_zero,
2948 v.further_from_negative_zero);
2949 }, "v.further_from_negative_zero");
shiqian4b6829f2008-07-03 22:38:12 +00002950}
2951
2952// Tests comparing numbers close to each other.
2953TEST_F(DoubleTest, SmallDiff) {
zhanyong.wan98efcc42009-04-28 00:28:09 +00002954 EXPECT_DOUBLE_EQ(1.0, values_.close_to_one);
2955 EXPECT_NONFATAL_FAILURE(EXPECT_DOUBLE_EQ(1.0, values_.further_from_one),
2956 "values_.further_from_one");
shiqian4b6829f2008-07-03 22:38:12 +00002957}
2958
2959// Tests comparing numbers far apart.
2960TEST_F(DoubleTest, LargeDiff) {
2961 EXPECT_NONFATAL_FAILURE(EXPECT_DOUBLE_EQ(2.0, 3.0),
2962 "3.0");
2963}
2964
2965// Tests comparing with infinity.
2966//
2967// This ensures that no overflow occurs when comparing numbers whose
2968// absolute value is very large.
2969TEST_F(DoubleTest, Infinity) {
zhanyong.wan98efcc42009-04-28 00:28:09 +00002970 EXPECT_DOUBLE_EQ(values_.infinity, values_.close_to_infinity);
2971 EXPECT_DOUBLE_EQ(-values_.infinity, -values_.close_to_infinity);
zhanyong.wan4cd62602009-02-23 23:21:55 +00002972#if !GTEST_OS_SYMBIAN
shiqiane44602e2008-10-11 07:20:02 +00002973 // Nokia's STLport crashes if we try to output infinity or NaN.
zhanyong.wan98efcc42009-04-28 00:28:09 +00002974 EXPECT_NONFATAL_FAILURE(EXPECT_DOUBLE_EQ(values_.infinity, -values_.infinity),
2975 "-values_.infinity");
shiqian4b6829f2008-07-03 22:38:12 +00002976
2977 // This is interesting as the representations of infinity_ and nan1_
2978 // are only 1 DLP apart.
zhanyong.wan98efcc42009-04-28 00:28:09 +00002979 EXPECT_NONFATAL_FAILURE(EXPECT_DOUBLE_EQ(values_.infinity, values_.nan1),
2980 "values_.nan1");
zhanyong.wan4cd62602009-02-23 23:21:55 +00002981#endif // !GTEST_OS_SYMBIAN
shiqian4b6829f2008-07-03 22:38:12 +00002982}
2983
2984// Tests that comparing with NAN always returns false.
2985TEST_F(DoubleTest, NaN) {
zhanyong.wan4cd62602009-02-23 23:21:55 +00002986#if !GTEST_OS_SYMBIAN
zhanyong.wan98efcc42009-04-28 00:28:09 +00002987 // In C++Builder, names within local classes (such as used by
2988 // EXPECT_FATAL_FAILURE) cannot be resolved against static members of the
2989 // scoping class. Use a static local alias as a workaround.
vladlosev673a0cb2010-02-03 02:27:02 +00002990 // We use the assignment syntax since some compilers, like Sun Studio,
2991 // don't allow initializing references using construction syntax
2992 // (parentheses).
2993 static const DoubleTest::TestValues& v = this->values_;
zhanyong.wan98efcc42009-04-28 00:28:09 +00002994
shiqiane44602e2008-10-11 07:20:02 +00002995 // Nokia's STLport crashes if we try to output infinity or NaN.
zhanyong.wan98efcc42009-04-28 00:28:09 +00002996 EXPECT_NONFATAL_FAILURE(EXPECT_DOUBLE_EQ(v.nan1, v.nan1),
2997 "v.nan1");
2998 EXPECT_NONFATAL_FAILURE(EXPECT_DOUBLE_EQ(v.nan1, v.nan2), "v.nan2");
2999 EXPECT_NONFATAL_FAILURE(EXPECT_DOUBLE_EQ(1.0, v.nan1), "v.nan1");
3000 EXPECT_FATAL_FAILURE(ASSERT_DOUBLE_EQ(v.nan1, v.infinity),
3001 "v.infinity");
zhanyong.wan4cd62602009-02-23 23:21:55 +00003002#endif // !GTEST_OS_SYMBIAN
shiqian4b6829f2008-07-03 22:38:12 +00003003}
3004
3005// Tests that *_DOUBLE_EQ are reflexive.
3006TEST_F(DoubleTest, Reflexive) {
3007 EXPECT_DOUBLE_EQ(0.0, 0.0);
3008 EXPECT_DOUBLE_EQ(1.0, 1.0);
zhanyong.wan4cd62602009-02-23 23:21:55 +00003009#if !GTEST_OS_SYMBIAN
shiqiane44602e2008-10-11 07:20:02 +00003010 // Nokia's STLport crashes if we try to output infinity or NaN.
zhanyong.wan98efcc42009-04-28 00:28:09 +00003011 ASSERT_DOUBLE_EQ(values_.infinity, values_.infinity);
zhanyong.wan4cd62602009-02-23 23:21:55 +00003012#endif // !GTEST_OS_SYMBIAN
shiqian4b6829f2008-07-03 22:38:12 +00003013}
3014
3015// Tests that *_DOUBLE_EQ are commutative.
3016TEST_F(DoubleTest, Commutative) {
zhanyong.wan98efcc42009-04-28 00:28:09 +00003017 // We already tested EXPECT_DOUBLE_EQ(1.0, values_.close_to_one).
3018 EXPECT_DOUBLE_EQ(values_.close_to_one, 1.0);
shiqian4b6829f2008-07-03 22:38:12 +00003019
zhanyong.wan98efcc42009-04-28 00:28:09 +00003020 // We already tested EXPECT_DOUBLE_EQ(1.0, values_.further_from_one).
3021 EXPECT_NONFATAL_FAILURE(EXPECT_DOUBLE_EQ(values_.further_from_one, 1.0),
3022 "1.0");
shiqian4b6829f2008-07-03 22:38:12 +00003023}
3024
3025// Tests EXPECT_NEAR.
3026TEST_F(DoubleTest, EXPECT_NEAR) {
3027 EXPECT_NEAR(-1.0, -1.1, 0.2);
3028 EXPECT_NEAR(2.0, 3.0, 1.0);
zhanyong.wan65de7e02010-01-08 00:23:45 +00003029 EXPECT_NONFATAL_FAILURE(EXPECT_NEAR(1.0, 1.5, 0.25), // NOLINT
3030 "The difference between 1.0 and 1.5 is 0.5, "
3031 "which exceeds 0.25");
shiqian4b6829f2008-07-03 22:38:12 +00003032 // To work around a bug in gcc 2.95.0, there is intentionally no
3033 // space after the first comma in the previous statement.
shiqian4b6829f2008-07-03 22:38:12 +00003034}
3035
3036// Tests ASSERT_NEAR.
3037TEST_F(DoubleTest, ASSERT_NEAR) {
3038 ASSERT_NEAR(-1.0, -1.1, 0.2);
3039 ASSERT_NEAR(2.0, 3.0, 1.0);
zhanyong.wan65de7e02010-01-08 00:23:45 +00003040 EXPECT_FATAL_FAILURE(ASSERT_NEAR(1.0, 1.5, 0.25), // NOLINT
3041 "The difference between 1.0 and 1.5 is 0.5, "
3042 "which exceeds 0.25");
shiqian4b6829f2008-07-03 22:38:12 +00003043 // To work around a bug in gcc 2.95.0, there is intentionally no
3044 // space after the first comma in the previous statement.
shiqian4b6829f2008-07-03 22:38:12 +00003045}
3046
3047// Tests the cases where DoubleLE() should succeed.
3048TEST_F(DoubleTest, DoubleLESucceeds) {
shiqian760af5c2008-08-06 21:43:15 +00003049 EXPECT_PRED_FORMAT2(DoubleLE, 1.0, 2.0); // When val1 < val2,
3050 ASSERT_PRED_FORMAT2(DoubleLE, 1.0, 1.0); // val1 == val2,
shiqian4b6829f2008-07-03 22:38:12 +00003051
3052 // or when val1 is greater than, but almost equals to, val2.
zhanyong.wan98efcc42009-04-28 00:28:09 +00003053 EXPECT_PRED_FORMAT2(DoubleLE, values_.close_to_positive_zero, 0.0);
shiqian4b6829f2008-07-03 22:38:12 +00003054}
3055
3056// Tests the cases where DoubleLE() should fail.
3057TEST_F(DoubleTest, DoubleLEFails) {
3058 // When val1 is greater than val2 by a large margin,
shiqian760af5c2008-08-06 21:43:15 +00003059 EXPECT_NONFATAL_FAILURE(EXPECT_PRED_FORMAT2(DoubleLE, 2.0, 1.0),
shiqian4b6829f2008-07-03 22:38:12 +00003060 "(2.0) <= (1.0)");
3061
3062 // or by a small yet non-negligible margin,
3063 EXPECT_NONFATAL_FAILURE({ // NOLINT
zhanyong.wan98efcc42009-04-28 00:28:09 +00003064 EXPECT_PRED_FORMAT2(DoubleLE, values_.further_from_one, 1.0);
3065 }, "(values_.further_from_one) <= (1.0)");
shiqian4b6829f2008-07-03 22:38:12 +00003066
zhanyong.wan98efcc42009-04-28 00:28:09 +00003067#if !GTEST_OS_SYMBIAN && !defined(__BORLANDC__)
shiqiane44602e2008-10-11 07:20:02 +00003068 // Nokia's STLport crashes if we try to output infinity or NaN.
zhanyong.wan98efcc42009-04-28 00:28:09 +00003069 // C++Builder gives bad results for ordered comparisons involving NaNs
3070 // due to compiler bugs.
shiqian4b6829f2008-07-03 22:38:12 +00003071 EXPECT_NONFATAL_FAILURE({ // NOLINT
zhanyong.wan98efcc42009-04-28 00:28:09 +00003072 EXPECT_PRED_FORMAT2(DoubleLE, values_.nan1, values_.infinity);
3073 }, "(values_.nan1) <= (values_.infinity)");
shiqian4b6829f2008-07-03 22:38:12 +00003074 EXPECT_NONFATAL_FAILURE({ // NOLINT
zhanyong.wan98efcc42009-04-28 00:28:09 +00003075 EXPECT_PRED_FORMAT2(DoubleLE, -values_.infinity, values_.nan1);
3076 }, " (-values_.infinity) <= (values_.nan1)");
shiqian4b6829f2008-07-03 22:38:12 +00003077 EXPECT_FATAL_FAILURE({ // NOLINT
zhanyong.wan98efcc42009-04-28 00:28:09 +00003078 ASSERT_PRED_FORMAT2(DoubleLE, values_.nan1, values_.nan1);
3079 }, "(values_.nan1) <= (values_.nan1)");
3080#endif // !GTEST_OS_SYMBIAN && !defined(__BORLANDC__)
shiqian4b6829f2008-07-03 22:38:12 +00003081}
3082
3083
3084// Verifies that a test or test case whose name starts with DISABLED_ is
3085// not run.
3086
3087// A test whose name starts with DISABLED_.
3088// Should not run.
3089TEST(DisabledTest, DISABLED_TestShouldNotRun) {
3090 FAIL() << "Unexpected failure: Disabled test should not be run.";
3091}
3092
3093// A test whose name does not start with DISABLED_.
3094// Should run.
3095TEST(DisabledTest, NotDISABLED_TestShouldRun) {
3096 EXPECT_EQ(1, 1);
3097}
3098
3099// A test case whose name starts with DISABLED_.
3100// Should not run.
3101TEST(DISABLED_TestCase, TestShouldNotRun) {
3102 FAIL() << "Unexpected failure: Test in disabled test case should not be run.";
3103}
3104
3105// A test case and test whose names start with DISABLED_.
3106// Should not run.
3107TEST(DISABLED_TestCase, DISABLED_TestShouldNotRun) {
3108 FAIL() << "Unexpected failure: Test in disabled test case should not be run.";
3109}
3110
3111// Check that when all tests in a test case are disabled, SetupTestCase() and
3112// TearDownTestCase() are not called.
shiqian760af5c2008-08-06 21:43:15 +00003113class DisabledTestsTest : public Test {
shiqian4b6829f2008-07-03 22:38:12 +00003114 protected:
3115 static void SetUpTestCase() {
3116 FAIL() << "Unexpected failure: All tests disabled in test case. "
3117 "SetupTestCase() should not be called.";
3118 }
3119
3120 static void TearDownTestCase() {
3121 FAIL() << "Unexpected failure: All tests disabled in test case. "
3122 "TearDownTestCase() should not be called.";
3123 }
3124};
3125
3126TEST_F(DisabledTestsTest, DISABLED_TestShouldNotRun_1) {
3127 FAIL() << "Unexpected failure: Disabled test should not be run.";
3128}
3129
3130TEST_F(DisabledTestsTest, DISABLED_TestShouldNotRun_2) {
3131 FAIL() << "Unexpected failure: Disabled test should not be run.";
3132}
3133
shiqiane8ff1482008-09-08 17:55:52 +00003134// Tests that disabled typed tests aren't run.
3135
zhanyong.wan4cd62602009-02-23 23:21:55 +00003136#if GTEST_HAS_TYPED_TEST
shiqiane8ff1482008-09-08 17:55:52 +00003137
3138template <typename T>
3139class TypedTest : public Test {
3140};
3141
3142typedef testing::Types<int, double> NumericTypes;
3143TYPED_TEST_CASE(TypedTest, NumericTypes);
3144
3145TYPED_TEST(TypedTest, DISABLED_ShouldNotRun) {
3146 FAIL() << "Unexpected failure: Disabled typed test should not run.";
3147}
3148
3149template <typename T>
3150class DISABLED_TypedTest : public Test {
3151};
3152
3153TYPED_TEST_CASE(DISABLED_TypedTest, NumericTypes);
3154
3155TYPED_TEST(DISABLED_TypedTest, ShouldNotRun) {
3156 FAIL() << "Unexpected failure: Disabled typed test should not run.";
3157}
3158
3159#endif // GTEST_HAS_TYPED_TEST
3160
3161// Tests that disabled type-parameterized tests aren't run.
3162
zhanyong.wan4cd62602009-02-23 23:21:55 +00003163#if GTEST_HAS_TYPED_TEST_P
shiqiane8ff1482008-09-08 17:55:52 +00003164
3165template <typename T>
3166class TypedTestP : public Test {
3167};
3168
3169TYPED_TEST_CASE_P(TypedTestP);
3170
3171TYPED_TEST_P(TypedTestP, DISABLED_ShouldNotRun) {
3172 FAIL() << "Unexpected failure: "
3173 << "Disabled type-parameterized test should not run.";
3174}
3175
3176REGISTER_TYPED_TEST_CASE_P(TypedTestP, DISABLED_ShouldNotRun);
3177
3178INSTANTIATE_TYPED_TEST_CASE_P(My, TypedTestP, NumericTypes);
3179
3180template <typename T>
3181class DISABLED_TypedTestP : public Test {
3182};
3183
3184TYPED_TEST_CASE_P(DISABLED_TypedTestP);
3185
3186TYPED_TEST_P(DISABLED_TypedTestP, ShouldNotRun) {
3187 FAIL() << "Unexpected failure: "
3188 << "Disabled type-parameterized test should not run.";
3189}
3190
3191REGISTER_TYPED_TEST_CASE_P(DISABLED_TypedTestP, ShouldNotRun);
3192
3193INSTANTIATE_TYPED_TEST_CASE_P(My, DISABLED_TypedTestP, NumericTypes);
3194
3195#endif // GTEST_HAS_TYPED_TEST_P
shiqian4b6829f2008-07-03 22:38:12 +00003196
3197// Tests that assertion macros evaluate their arguments exactly once.
3198
shiqian760af5c2008-08-06 21:43:15 +00003199class SingleEvaluationTest : public Test {
tsunanetacd0f322009-05-18 20:53:57 +00003200 public: // Must be public and not protected due to a bug in g++ 3.4.2.
zhanyong.wan98efcc42009-04-28 00:28:09 +00003201 // This helper function is needed by the FailedASSERT_STREQ test
3202 // below. It's public to work around C++Builder's bug with scoping local
3203 // classes.
3204 static void CompareAndIncrementCharPtrs() {
3205 ASSERT_STREQ(p1_++, p2_++);
3206 }
3207
3208 // This helper function is needed by the FailedASSERT_NE test below. It's
3209 // public to work around C++Builder's bug with scoping local classes.
3210 static void CompareAndIncrementInts() {
3211 ASSERT_NE(a_++, b_++);
3212 }
3213
shiqian4b6829f2008-07-03 22:38:12 +00003214 protected:
3215 SingleEvaluationTest() {
3216 p1_ = s1_;
3217 p2_ = s2_;
3218 a_ = 0;
3219 b_ = 0;
3220 }
3221
shiqian4b6829f2008-07-03 22:38:12 +00003222 static const char* const s1_;
3223 static const char* const s2_;
3224 static const char* p1_;
3225 static const char* p2_;
3226
3227 static int a_;
3228 static int b_;
3229};
3230
3231const char* const SingleEvaluationTest::s1_ = "01234";
3232const char* const SingleEvaluationTest::s2_ = "abcde";
3233const char* SingleEvaluationTest::p1_;
3234const char* SingleEvaluationTest::p2_;
3235int SingleEvaluationTest::a_;
3236int SingleEvaluationTest::b_;
3237
3238// Tests that when ASSERT_STREQ fails, it evaluates its arguments
3239// exactly once.
3240TEST_F(SingleEvaluationTest, FailedASSERT_STREQ) {
zhanyong.wan98efcc42009-04-28 00:28:09 +00003241 EXPECT_FATAL_FAILURE(SingleEvaluationTest::CompareAndIncrementCharPtrs(),
shiqian4b6829f2008-07-03 22:38:12 +00003242 "p2_++");
3243 EXPECT_EQ(s1_ + 1, p1_);
3244 EXPECT_EQ(s2_ + 1, p2_);
3245}
3246
3247// Tests that string assertion arguments are evaluated exactly once.
3248TEST_F(SingleEvaluationTest, ASSERT_STR) {
3249 // successful EXPECT_STRNE
3250 EXPECT_STRNE(p1_++, p2_++);
3251 EXPECT_EQ(s1_ + 1, p1_);
3252 EXPECT_EQ(s2_ + 1, p2_);
3253
3254 // failed EXPECT_STRCASEEQ
3255 EXPECT_NONFATAL_FAILURE(EXPECT_STRCASEEQ(p1_++, p2_++),
3256 "ignoring case");
3257 EXPECT_EQ(s1_ + 2, p1_);
3258 EXPECT_EQ(s2_ + 2, p2_);
3259}
3260
3261// Tests that when ASSERT_NE fails, it evaluates its arguments exactly
3262// once.
3263TEST_F(SingleEvaluationTest, FailedASSERT_NE) {
zhanyong.wan98efcc42009-04-28 00:28:09 +00003264 EXPECT_FATAL_FAILURE(SingleEvaluationTest::CompareAndIncrementInts(),
3265 "(a_++) != (b_++)");
shiqian4b6829f2008-07-03 22:38:12 +00003266 EXPECT_EQ(1, a_);
3267 EXPECT_EQ(1, b_);
3268}
3269
3270// Tests that assertion arguments are evaluated exactly once.
3271TEST_F(SingleEvaluationTest, OtherCases) {
3272 // successful EXPECT_TRUE
3273 EXPECT_TRUE(0 == a_++); // NOLINT
3274 EXPECT_EQ(1, a_);
3275
3276 // failed EXPECT_TRUE
3277 EXPECT_NONFATAL_FAILURE(EXPECT_TRUE(-1 == a_++), "-1 == a_++");
3278 EXPECT_EQ(2, a_);
3279
3280 // successful EXPECT_GT
3281 EXPECT_GT(a_++, b_++);
3282 EXPECT_EQ(3, a_);
3283 EXPECT_EQ(1, b_);
3284
3285 // failed EXPECT_LT
3286 EXPECT_NONFATAL_FAILURE(EXPECT_LT(a_++, b_++), "(a_++) < (b_++)");
3287 EXPECT_EQ(4, a_);
3288 EXPECT_EQ(2, b_);
3289
3290 // successful ASSERT_TRUE
3291 ASSERT_TRUE(0 < a_++); // NOLINT
3292 EXPECT_EQ(5, a_);
3293
3294 // successful ASSERT_GT
3295 ASSERT_GT(a_++, b_++);
3296 EXPECT_EQ(6, a_);
3297 EXPECT_EQ(3, b_);
3298}
3299
shiqian9204c8e2008-09-12 20:57:22 +00003300#if GTEST_HAS_EXCEPTIONS
3301
3302void ThrowAnInteger() {
3303 throw 1;
3304}
3305
3306// Tests that assertion arguments are evaluated exactly once.
3307TEST_F(SingleEvaluationTest, ExceptionTests) {
3308 // successful EXPECT_THROW
3309 EXPECT_THROW({ // NOLINT
3310 a_++;
3311 ThrowAnInteger();
3312 }, int);
3313 EXPECT_EQ(1, a_);
3314
3315 // failed EXPECT_THROW, throws different
3316 EXPECT_NONFATAL_FAILURE(EXPECT_THROW({ // NOLINT
3317 a_++;
3318 ThrowAnInteger();
3319 }, bool), "throws a different type");
3320 EXPECT_EQ(2, a_);
3321
3322 // failed EXPECT_THROW, throws nothing
3323 EXPECT_NONFATAL_FAILURE(EXPECT_THROW(a_++, bool), "throws nothing");
3324 EXPECT_EQ(3, a_);
3325
3326 // successful EXPECT_NO_THROW
3327 EXPECT_NO_THROW(a_++);
3328 EXPECT_EQ(4, a_);
3329
3330 // failed EXPECT_NO_THROW
3331 EXPECT_NONFATAL_FAILURE(EXPECT_NO_THROW({ // NOLINT
3332 a_++;
3333 ThrowAnInteger();
3334 }), "it throws");
3335 EXPECT_EQ(5, a_);
3336
3337 // successful EXPECT_ANY_THROW
3338 EXPECT_ANY_THROW({ // NOLINT
3339 a_++;
3340 ThrowAnInteger();
3341 });
3342 EXPECT_EQ(6, a_);
3343
3344 // failed EXPECT_ANY_THROW
3345 EXPECT_NONFATAL_FAILURE(EXPECT_ANY_THROW(a_++), "it doesn't");
3346 EXPECT_EQ(7, a_);
3347}
3348
3349#endif // GTEST_HAS_EXCEPTIONS
shiqian4b6829f2008-07-03 22:38:12 +00003350
shiqiane44602e2008-10-11 07:20:02 +00003351// Tests {ASSERT|EXPECT}_NO_FATAL_FAILURE.
3352class NoFatalFailureTest : public Test {
3353 protected:
3354 void Succeeds() {}
3355 void FailsNonFatal() {
3356 ADD_FAILURE() << "some non-fatal failure";
3357 }
3358 void Fails() {
3359 FAIL() << "some fatal failure";
3360 }
3361
3362 void DoAssertNoFatalFailureOnFails() {
3363 ASSERT_NO_FATAL_FAILURE(Fails());
3364 ADD_FAILURE() << "shold not reach here.";
3365 }
3366
3367 void DoExpectNoFatalFailureOnFails() {
3368 EXPECT_NO_FATAL_FAILURE(Fails());
3369 ADD_FAILURE() << "other failure";
3370 }
3371};
3372
3373TEST_F(NoFatalFailureTest, NoFailure) {
3374 EXPECT_NO_FATAL_FAILURE(Succeeds());
3375 ASSERT_NO_FATAL_FAILURE(Succeeds());
3376}
3377
3378TEST_F(NoFatalFailureTest, NonFatalIsNoFailure) {
3379 EXPECT_NONFATAL_FAILURE(
3380 EXPECT_NO_FATAL_FAILURE(FailsNonFatal()),
3381 "some non-fatal failure");
3382 EXPECT_NONFATAL_FAILURE(
3383 ASSERT_NO_FATAL_FAILURE(FailsNonFatal()),
3384 "some non-fatal failure");
3385}
3386
3387TEST_F(NoFatalFailureTest, AssertNoFatalFailureOnFatalFailure) {
3388 TestPartResultArray gtest_failures;
3389 {
3390 ScopedFakeTestPartResultReporter gtest_reporter(&gtest_failures);
3391 DoAssertNoFatalFailureOnFails();
3392 }
3393 ASSERT_EQ(2, gtest_failures.size());
zhanyong.wan334aaea2009-09-18 18:16:20 +00003394 EXPECT_EQ(TestPartResult::kFatalFailure,
shiqiane44602e2008-10-11 07:20:02 +00003395 gtest_failures.GetTestPartResult(0).type());
zhanyong.wan334aaea2009-09-18 18:16:20 +00003396 EXPECT_EQ(TestPartResult::kFatalFailure,
shiqiane44602e2008-10-11 07:20:02 +00003397 gtest_failures.GetTestPartResult(1).type());
3398 EXPECT_PRED_FORMAT2(testing::IsSubstring, "some fatal failure",
3399 gtest_failures.GetTestPartResult(0).message());
3400 EXPECT_PRED_FORMAT2(testing::IsSubstring, "it does",
3401 gtest_failures.GetTestPartResult(1).message());
3402}
3403
3404TEST_F(NoFatalFailureTest, ExpectNoFatalFailureOnFatalFailure) {
3405 TestPartResultArray gtest_failures;
3406 {
3407 ScopedFakeTestPartResultReporter gtest_reporter(&gtest_failures);
3408 DoExpectNoFatalFailureOnFails();
3409 }
3410 ASSERT_EQ(3, gtest_failures.size());
zhanyong.wan334aaea2009-09-18 18:16:20 +00003411 EXPECT_EQ(TestPartResult::kFatalFailure,
shiqiane44602e2008-10-11 07:20:02 +00003412 gtest_failures.GetTestPartResult(0).type());
zhanyong.wan334aaea2009-09-18 18:16:20 +00003413 EXPECT_EQ(TestPartResult::kNonFatalFailure,
shiqiane44602e2008-10-11 07:20:02 +00003414 gtest_failures.GetTestPartResult(1).type());
zhanyong.wan334aaea2009-09-18 18:16:20 +00003415 EXPECT_EQ(TestPartResult::kNonFatalFailure,
shiqiane44602e2008-10-11 07:20:02 +00003416 gtest_failures.GetTestPartResult(2).type());
3417 EXPECT_PRED_FORMAT2(testing::IsSubstring, "some fatal failure",
3418 gtest_failures.GetTestPartResult(0).message());
3419 EXPECT_PRED_FORMAT2(testing::IsSubstring, "it does",
3420 gtest_failures.GetTestPartResult(1).message());
3421 EXPECT_PRED_FORMAT2(testing::IsSubstring, "other failure",
3422 gtest_failures.GetTestPartResult(2).message());
3423}
3424
3425TEST_F(NoFatalFailureTest, MessageIsStreamable) {
3426 TestPartResultArray gtest_failures;
3427 {
3428 ScopedFakeTestPartResultReporter gtest_reporter(&gtest_failures);
3429 EXPECT_NO_FATAL_FAILURE(FAIL() << "foo") << "my message";
3430 }
3431 ASSERT_EQ(2, gtest_failures.size());
zhanyong.wan334aaea2009-09-18 18:16:20 +00003432 EXPECT_EQ(TestPartResult::kNonFatalFailure,
shiqiane44602e2008-10-11 07:20:02 +00003433 gtest_failures.GetTestPartResult(0).type());
zhanyong.wan334aaea2009-09-18 18:16:20 +00003434 EXPECT_EQ(TestPartResult::kNonFatalFailure,
shiqiane44602e2008-10-11 07:20:02 +00003435 gtest_failures.GetTestPartResult(1).type());
3436 EXPECT_PRED_FORMAT2(testing::IsSubstring, "foo",
3437 gtest_failures.GetTestPartResult(0).message());
3438 EXPECT_PRED_FORMAT2(testing::IsSubstring, "my message",
3439 gtest_failures.GetTestPartResult(1).message());
3440}
3441
shiqian4b6829f2008-07-03 22:38:12 +00003442// Tests non-string assertions.
3443
3444// Tests EqFailure(), used for implementing *EQ* assertions.
3445TEST(AssertionTest, EqFailure) {
jgm@google.com03c31492012-11-15 15:47:38 +00003446 const std::string foo_val("5"), bar_val("6");
3447 const std::string msg1(
shiqian4b6829f2008-07-03 22:38:12 +00003448 EqFailure("foo", "bar", foo_val, bar_val, false)
3449 .failure_message());
3450 EXPECT_STREQ(
3451 "Value of: bar\n"
3452 " Actual: 6\n"
3453 "Expected: foo\n"
3454 "Which is: 5",
3455 msg1.c_str());
3456
jgm@google.com03c31492012-11-15 15:47:38 +00003457 const std::string msg2(
shiqian4b6829f2008-07-03 22:38:12 +00003458 EqFailure("foo", "6", foo_val, bar_val, false)
3459 .failure_message());
3460 EXPECT_STREQ(
3461 "Value of: 6\n"
3462 "Expected: foo\n"
3463 "Which is: 5",
3464 msg2.c_str());
3465
jgm@google.com03c31492012-11-15 15:47:38 +00003466 const std::string msg3(
shiqian4b6829f2008-07-03 22:38:12 +00003467 EqFailure("5", "bar", foo_val, bar_val, false)
3468 .failure_message());
3469 EXPECT_STREQ(
3470 "Value of: bar\n"
3471 " Actual: 6\n"
3472 "Expected: 5",
3473 msg3.c_str());
3474
jgm@google.com03c31492012-11-15 15:47:38 +00003475 const std::string msg4(
shiqian4b6829f2008-07-03 22:38:12 +00003476 EqFailure("5", "6", foo_val, bar_val, false).failure_message());
3477 EXPECT_STREQ(
3478 "Value of: 6\n"
3479 "Expected: 5",
3480 msg4.c_str());
3481
jgm@google.com03c31492012-11-15 15:47:38 +00003482 const std::string msg5(
shiqian4b6829f2008-07-03 22:38:12 +00003483 EqFailure("foo", "bar",
jgm@google.com03c31492012-11-15 15:47:38 +00003484 std::string("\"x\""), std::string("\"y\""),
shiqian4b6829f2008-07-03 22:38:12 +00003485 true).failure_message());
3486 EXPECT_STREQ(
3487 "Value of: bar\n"
3488 " Actual: \"y\"\n"
3489 "Expected: foo (ignoring case)\n"
3490 "Which is: \"x\"",
3491 msg5.c_str());
3492}
3493
3494// Tests AppendUserMessage(), used for implementing the *EQ* macros.
3495TEST(AssertionTest, AppendUserMessage) {
jgm@google.com03c31492012-11-15 15:47:38 +00003496 const std::string foo("foo");
shiqian4b6829f2008-07-03 22:38:12 +00003497
shiqian760af5c2008-08-06 21:43:15 +00003498 Message msg;
shiqian4b6829f2008-07-03 22:38:12 +00003499 EXPECT_STREQ("foo",
3500 AppendUserMessage(foo, msg).c_str());
3501
3502 msg << "bar";
3503 EXPECT_STREQ("foo\nbar",
3504 AppendUserMessage(foo, msg).c_str());
3505}
3506
zhanyong.wan98efcc42009-04-28 00:28:09 +00003507#ifdef __BORLANDC__
3508// Silences warnings: "Condition is always true", "Unreachable code"
zhanyong.wan733a54a2011-02-22 22:08:59 +00003509# pragma option push -w-ccc -w-rch
zhanyong.wan98efcc42009-04-28 00:28:09 +00003510#endif
3511
shiqian4b6829f2008-07-03 22:38:12 +00003512// Tests ASSERT_TRUE.
3513TEST(AssertionTest, ASSERT_TRUE) {
3514 ASSERT_TRUE(2 > 1); // NOLINT
3515 EXPECT_FATAL_FAILURE(ASSERT_TRUE(2 < 1),
3516 "2 < 1");
3517}
3518
vladlosevfbd53a52009-10-20 21:03:10 +00003519// Tests ASSERT_TRUE(predicate) for predicates returning AssertionResult.
3520TEST(AssertionTest, AssertTrueWithAssertionResult) {
3521 ASSERT_TRUE(ResultIsEven(2));
zhanyong.waned1042b2011-03-05 08:04:01 +00003522#ifndef __BORLANDC__
3523 // ICE's in C++Builder.
vladlosevfbd53a52009-10-20 21:03:10 +00003524 EXPECT_FATAL_FAILURE(ASSERT_TRUE(ResultIsEven(3)),
3525 "Value of: ResultIsEven(3)\n"
3526 " Actual: false (3 is odd)\n"
3527 "Expected: true");
vladlosevd6b49412010-04-07 05:32:34 +00003528#endif
vladlosevfbd53a52009-10-20 21:03:10 +00003529 ASSERT_TRUE(ResultIsEvenNoExplanation(2));
3530 EXPECT_FATAL_FAILURE(ASSERT_TRUE(ResultIsEvenNoExplanation(3)),
3531 "Value of: ResultIsEvenNoExplanation(3)\n"
3532 " Actual: false (3 is odd)\n"
3533 "Expected: true");
3534}
3535
shiqian4b6829f2008-07-03 22:38:12 +00003536// Tests ASSERT_FALSE.
3537TEST(AssertionTest, ASSERT_FALSE) {
3538 ASSERT_FALSE(2 < 1); // NOLINT
3539 EXPECT_FATAL_FAILURE(ASSERT_FALSE(2 > 1),
3540 "Value of: 2 > 1\n"
3541 " Actual: true\n"
3542 "Expected: false");
3543}
3544
vladlosevfbd53a52009-10-20 21:03:10 +00003545// Tests ASSERT_FALSE(predicate) for predicates returning AssertionResult.
3546TEST(AssertionTest, AssertFalseWithAssertionResult) {
3547 ASSERT_FALSE(ResultIsEven(3));
zhanyong.waned1042b2011-03-05 08:04:01 +00003548#ifndef __BORLANDC__
3549 // ICE's in C++Builder.
vladlosevfbd53a52009-10-20 21:03:10 +00003550 EXPECT_FATAL_FAILURE(ASSERT_FALSE(ResultIsEven(2)),
3551 "Value of: ResultIsEven(2)\n"
3552 " Actual: true (2 is even)\n"
3553 "Expected: false");
vladlosevd6b49412010-04-07 05:32:34 +00003554#endif
vladlosevfbd53a52009-10-20 21:03:10 +00003555 ASSERT_FALSE(ResultIsEvenNoExplanation(3));
3556 EXPECT_FATAL_FAILURE(ASSERT_FALSE(ResultIsEvenNoExplanation(2)),
3557 "Value of: ResultIsEvenNoExplanation(2)\n"
3558 " Actual: true\n"
3559 "Expected: false");
3560}
3561
zhanyong.wan98efcc42009-04-28 00:28:09 +00003562#ifdef __BORLANDC__
3563// Restores warnings after previous "#pragma option push" supressed them
zhanyong.wan733a54a2011-02-22 22:08:59 +00003564# pragma option pop
zhanyong.wan98efcc42009-04-28 00:28:09 +00003565#endif
3566
shiqian4b6829f2008-07-03 22:38:12 +00003567// Tests using ASSERT_EQ on double values. The purpose is to make
3568// sure that the specialization we did for integer and anonymous enums
3569// isn't used for double arguments.
3570TEST(ExpectTest, ASSERT_EQ_Double) {
3571 // A success.
3572 ASSERT_EQ(5.6, 5.6);
3573
3574 // A failure.
3575 EXPECT_FATAL_FAILURE(ASSERT_EQ(5.1, 5.2),
3576 "5.1");
3577}
3578
3579// Tests ASSERT_EQ.
3580TEST(AssertionTest, ASSERT_EQ) {
3581 ASSERT_EQ(5, 2 + 3);
3582 EXPECT_FATAL_FAILURE(ASSERT_EQ(5, 2*3),
3583 "Value of: 2*3\n"
3584 " Actual: 6\n"
3585 "Expected: 5");
3586}
3587
3588// Tests ASSERT_EQ(NULL, pointer).
vladlosev5147b452010-03-17 18:22:59 +00003589#if GTEST_CAN_COMPARE_NULL
shiqian4b6829f2008-07-03 22:38:12 +00003590TEST(AssertionTest, ASSERT_EQ_NULL) {
3591 // A success.
3592 const char* p = NULL;
zhanyong.wan9644db82009-06-24 23:02:50 +00003593 // Some older GCC versions may issue a spurious waring in this or the next
3594 // assertion statement. This warning should not be suppressed with
3595 // static_cast since the test verifies the ability to use bare NULL as the
3596 // expected parameter to the macro.
shiqian4b6829f2008-07-03 22:38:12 +00003597 ASSERT_EQ(NULL, p);
3598
3599 // A failure.
3600 static int n = 0;
3601 EXPECT_FATAL_FAILURE(ASSERT_EQ(NULL, &n),
3602 "Value of: &n\n");
3603}
vladlosev5147b452010-03-17 18:22:59 +00003604#endif // GTEST_CAN_COMPARE_NULL
shiqian4b6829f2008-07-03 22:38:12 +00003605
3606// Tests ASSERT_EQ(0, non_pointer). Since the literal 0 can be
3607// treated as a null pointer by the compiler, we need to make sure
3608// that ASSERT_EQ(0, non_pointer) isn't interpreted by Google Test as
3609// ASSERT_EQ(static_cast<void*>(NULL), non_pointer).
3610TEST(ExpectTest, ASSERT_EQ_0) {
3611 int n = 0;
3612
3613 // A success.
3614 ASSERT_EQ(0, n);
3615
3616 // A failure.
3617 EXPECT_FATAL_FAILURE(ASSERT_EQ(0, 5.6),
3618 "Expected: 0");
3619}
3620
3621// Tests ASSERT_NE.
3622TEST(AssertionTest, ASSERT_NE) {
3623 ASSERT_NE(6, 7);
3624 EXPECT_FATAL_FAILURE(ASSERT_NE('a', 'a'),
3625 "Expected: ('a') != ('a'), "
3626 "actual: 'a' (97, 0x61) vs 'a' (97, 0x61)");
3627}
3628
3629// Tests ASSERT_LE.
3630TEST(AssertionTest, ASSERT_LE) {
3631 ASSERT_LE(2, 3);
3632 ASSERT_LE(2, 2);
3633 EXPECT_FATAL_FAILURE(ASSERT_LE(2, 0),
3634 "Expected: (2) <= (0), actual: 2 vs 0");
3635}
3636
3637// Tests ASSERT_LT.
3638TEST(AssertionTest, ASSERT_LT) {
3639 ASSERT_LT(2, 3);
3640 EXPECT_FATAL_FAILURE(ASSERT_LT(2, 2),
3641 "Expected: (2) < (2), actual: 2 vs 2");
3642}
3643
3644// Tests ASSERT_GE.
3645TEST(AssertionTest, ASSERT_GE) {
3646 ASSERT_GE(2, 1);
3647 ASSERT_GE(2, 2);
3648 EXPECT_FATAL_FAILURE(ASSERT_GE(2, 3),
3649 "Expected: (2) >= (3), actual: 2 vs 3");
3650}
3651
3652// Tests ASSERT_GT.
3653TEST(AssertionTest, ASSERT_GT) {
3654 ASSERT_GT(2, 1);
3655 EXPECT_FATAL_FAILURE(ASSERT_GT(2, 2),
3656 "Expected: (2) > (2), actual: 2 vs 2");
3657}
3658
shiqian9204c8e2008-09-12 20:57:22 +00003659#if GTEST_HAS_EXCEPTIONS
3660
zhanyong.wanac60cef2009-02-08 04:53:35 +00003661void ThrowNothing() {}
3662
shiqian9204c8e2008-09-12 20:57:22 +00003663// Tests ASSERT_THROW.
3664TEST(AssertionTest, ASSERT_THROW) {
3665 ASSERT_THROW(ThrowAnInteger(), int);
vladlosevd6b49412010-04-07 05:32:34 +00003666
zhanyong.wan733a54a2011-02-22 22:08:59 +00003667# ifndef __BORLANDC__
3668
vladlosevd6b49412010-04-07 05:32:34 +00003669 // ICE's in C++Builder 2007 and 2009.
zhanyong.wanac60cef2009-02-08 04:53:35 +00003670 EXPECT_FATAL_FAILURE(
3671 ASSERT_THROW(ThrowAnInteger(), bool),
3672 "Expected: ThrowAnInteger() throws an exception of type bool.\n"
3673 " Actual: it throws a different type.");
zhanyong.wan733a54a2011-02-22 22:08:59 +00003674# endif
vladlosevd6b49412010-04-07 05:32:34 +00003675
zhanyong.wanac60cef2009-02-08 04:53:35 +00003676 EXPECT_FATAL_FAILURE(
3677 ASSERT_THROW(ThrowNothing(), bool),
3678 "Expected: ThrowNothing() throws an exception of type bool.\n"
3679 " Actual: it throws nothing.");
shiqian9204c8e2008-09-12 20:57:22 +00003680}
3681
3682// Tests ASSERT_NO_THROW.
3683TEST(AssertionTest, ASSERT_NO_THROW) {
zhanyong.wanac60cef2009-02-08 04:53:35 +00003684 ASSERT_NO_THROW(ThrowNothing());
shiqian9204c8e2008-09-12 20:57:22 +00003685 EXPECT_FATAL_FAILURE(ASSERT_NO_THROW(ThrowAnInteger()),
zhanyong.wanac60cef2009-02-08 04:53:35 +00003686 "Expected: ThrowAnInteger() doesn't throw an exception."
shiqian9204c8e2008-09-12 20:57:22 +00003687 "\n Actual: it throws.");
3688}
3689
3690// Tests ASSERT_ANY_THROW.
3691TEST(AssertionTest, ASSERT_ANY_THROW) {
3692 ASSERT_ANY_THROW(ThrowAnInteger());
zhanyong.wanac60cef2009-02-08 04:53:35 +00003693 EXPECT_FATAL_FAILURE(
3694 ASSERT_ANY_THROW(ThrowNothing()),
3695 "Expected: ThrowNothing() throws an exception.\n"
3696 " Actual: it doesn't.");
shiqian9204c8e2008-09-12 20:57:22 +00003697}
3698
3699#endif // GTEST_HAS_EXCEPTIONS
3700
shiqian4b6829f2008-07-03 22:38:12 +00003701// Makes sure we deal with the precedence of <<. This test should
3702// compile.
3703TEST(AssertionTest, AssertPrecedence) {
3704 ASSERT_EQ(1 < 2, true);
zhanyong.wan5e255e02011-01-10 18:17:59 +00003705 bool false_value = false;
3706 ASSERT_EQ(true && false_value, false);
shiqian4b6829f2008-07-03 22:38:12 +00003707}
3708
3709// A subroutine used by the following test.
3710void TestEq1(int x) {
3711 ASSERT_EQ(1, x);
3712}
3713
3714// Tests calling a test subroutine that's not part of a fixture.
3715TEST(AssertionTest, NonFixtureSubroutine) {
3716 EXPECT_FATAL_FAILURE(TestEq1(2),
3717 "Value of: x");
3718}
3719
3720// An uncopyable class.
3721class Uncopyable {
3722 public:
zhanyong.wan7de34012009-12-16 19:54:05 +00003723 explicit Uncopyable(int a_value) : value_(a_value) {}
shiqian4b6829f2008-07-03 22:38:12 +00003724
3725 int value() const { return value_; }
3726 bool operator==(const Uncopyable& rhs) const {
3727 return value() == rhs.value();
3728 }
3729 private:
3730 // This constructor deliberately has no implementation, as we don't
3731 // want this class to be copyable.
3732 Uncopyable(const Uncopyable&); // NOLINT
3733
3734 int value_;
3735};
3736
3737::std::ostream& operator<<(::std::ostream& os, const Uncopyable& value) {
3738 return os << value.value();
3739}
3740
3741
3742bool IsPositiveUncopyable(const Uncopyable& x) {
3743 return x.value() > 0;
3744}
3745
3746// A subroutine used by the following test.
3747void TestAssertNonPositive() {
3748 Uncopyable y(-1);
3749 ASSERT_PRED1(IsPositiveUncopyable, y);
3750}
3751// A subroutine used by the following test.
3752void TestAssertEqualsUncopyable() {
3753 Uncopyable x(5);
3754 Uncopyable y(-1);
3755 ASSERT_EQ(x, y);
3756}
3757
3758// Tests that uncopyable objects can be used in assertions.
3759TEST(AssertionTest, AssertWorksWithUncopyableObject) {
3760 Uncopyable x(5);
3761 ASSERT_PRED1(IsPositiveUncopyable, x);
3762 ASSERT_EQ(x, x);
3763 EXPECT_FATAL_FAILURE(TestAssertNonPositive(),
3764 "IsPositiveUncopyable(y) evaluates to false, where\ny evaluates to -1");
3765 EXPECT_FATAL_FAILURE(TestAssertEqualsUncopyable(),
3766 "Value of: y\n Actual: -1\nExpected: x\nWhich is: 5");
3767}
3768
3769// Tests that uncopyable objects can be used in expects.
3770TEST(AssertionTest, ExpectWorksWithUncopyableObject) {
3771 Uncopyable x(5);
3772 EXPECT_PRED1(IsPositiveUncopyable, x);
3773 Uncopyable y(-1);
3774 EXPECT_NONFATAL_FAILURE(EXPECT_PRED1(IsPositiveUncopyable, y),
3775 "IsPositiveUncopyable(y) evaluates to false, where\ny evaluates to -1");
3776 EXPECT_EQ(x, x);
3777 EXPECT_NONFATAL_FAILURE(EXPECT_EQ(x, y),
3778 "Value of: y\n Actual: -1\nExpected: x\nWhich is: 5");
3779}
3780
zhanyong.wan739d3042010-08-09 18:19:15 +00003781enum NamedEnum {
3782 kE1 = 0,
zhanyong.wan66d8d6b2011-03-05 01:16:12 +00003783 kE2 = 1
zhanyong.wan739d3042010-08-09 18:19:15 +00003784};
3785
3786TEST(AssertionTest, NamedEnum) {
3787 EXPECT_EQ(kE1, kE1);
3788 EXPECT_LT(kE1, kE2);
3789 EXPECT_NONFATAL_FAILURE(EXPECT_EQ(kE1, kE2), "Which is: 0");
3790 EXPECT_NONFATAL_FAILURE(EXPECT_EQ(kE1, kE2), "Actual: 1");
3791}
shiqian4b6829f2008-07-03 22:38:12 +00003792
3793// The version of gcc used in XCode 2.2 has a bug and doesn't allow
zhanyong.wanefa2fc72009-03-31 16:27:55 +00003794// anonymous enums in assertions. Therefore the following test is not
3795// done on Mac.
zhanyong.wanc2df1522011-04-07 18:36:50 +00003796// Sun Studio and HP aCC also reject this code.
3797#if !GTEST_OS_MAC && !defined(__SUNPRO_CC) && !defined(__HP_aCC)
shiqian4b6829f2008-07-03 22:38:12 +00003798
3799// Tests using assertions with anonymous enums.
3800enum {
zhanyong.wan739d3042010-08-09 18:19:15 +00003801 kCaseA = -1,
zhanyong.wan733a54a2011-02-22 22:08:59 +00003802
3803# if GTEST_OS_LINUX
3804
shiqian4b6829f2008-07-03 22:38:12 +00003805 // We want to test the case where the size of the anonymous enum is
3806 // larger than sizeof(int), to make sure our implementation of the
3807 // assertions doesn't truncate the enums. However, MSVC
3808 // (incorrectly) doesn't allow an enum value to exceed the range of
3809 // an int, so this has to be conditionally compiled.
3810 //
zhanyong.wan739d3042010-08-09 18:19:15 +00003811 // On Linux, kCaseB and kCaseA have the same value when truncated to
shiqian4b6829f2008-07-03 22:38:12 +00003812 // int size. We want to test whether this will confuse the
3813 // assertions.
zhanyong.wan739d3042010-08-09 18:19:15 +00003814 kCaseB = testing::internal::kMaxBiggestInt,
zhanyong.wan733a54a2011-02-22 22:08:59 +00003815
3816# else
3817
zhanyong.wan739d3042010-08-09 18:19:15 +00003818 kCaseB = INT_MAX,
zhanyong.wan733a54a2011-02-22 22:08:59 +00003819
3820# endif // GTEST_OS_LINUX
3821
vladloseve5c59712011-04-08 00:29:12 +00003822 kCaseC = 42
shiqian4b6829f2008-07-03 22:38:12 +00003823};
3824
3825TEST(AssertionTest, AnonymousEnum) {
zhanyong.wan733a54a2011-02-22 22:08:59 +00003826# if GTEST_OS_LINUX
3827
zhanyong.wan739d3042010-08-09 18:19:15 +00003828 EXPECT_EQ(static_cast<int>(kCaseA), static_cast<int>(kCaseB));
zhanyong.wan733a54a2011-02-22 22:08:59 +00003829
3830# endif // GTEST_OS_LINUX
shiqian4b6829f2008-07-03 22:38:12 +00003831
zhanyong.wan739d3042010-08-09 18:19:15 +00003832 EXPECT_EQ(kCaseA, kCaseA);
3833 EXPECT_NE(kCaseA, kCaseB);
3834 EXPECT_LT(kCaseA, kCaseB);
3835 EXPECT_LE(kCaseA, kCaseB);
3836 EXPECT_GT(kCaseB, kCaseA);
3837 EXPECT_GE(kCaseA, kCaseA);
3838 EXPECT_NONFATAL_FAILURE(EXPECT_GE(kCaseA, kCaseB),
3839 "(kCaseA) >= (kCaseB)");
3840 EXPECT_NONFATAL_FAILURE(EXPECT_GE(kCaseA, kCaseC),
3841 "-1 vs 42");
shiqian4b6829f2008-07-03 22:38:12 +00003842
zhanyong.wan739d3042010-08-09 18:19:15 +00003843 ASSERT_EQ(kCaseA, kCaseA);
3844 ASSERT_NE(kCaseA, kCaseB);
3845 ASSERT_LT(kCaseA, kCaseB);
3846 ASSERT_LE(kCaseA, kCaseB);
3847 ASSERT_GT(kCaseB, kCaseA);
3848 ASSERT_GE(kCaseA, kCaseA);
zhanyong.waned1042b2011-03-05 08:04:01 +00003849
3850# ifndef __BORLANDC__
3851
3852 // ICE's in C++Builder.
zhanyong.wan739d3042010-08-09 18:19:15 +00003853 EXPECT_FATAL_FAILURE(ASSERT_EQ(kCaseA, kCaseB),
3854 "Value of: kCaseB");
3855 EXPECT_FATAL_FAILURE(ASSERT_EQ(kCaseA, kCaseC),
3856 "Actual: 42");
zhanyong.waned1042b2011-03-05 08:04:01 +00003857# endif
3858
zhanyong.wan739d3042010-08-09 18:19:15 +00003859 EXPECT_FATAL_FAILURE(ASSERT_EQ(kCaseA, kCaseC),
3860 "Which is: -1");
shiqian4b6829f2008-07-03 22:38:12 +00003861}
3862
vladlosev673a0cb2010-02-03 02:27:02 +00003863#endif // !GTEST_OS_MAC && !defined(__SUNPRO_CC)
shiqian4b6829f2008-07-03 22:38:12 +00003864
zhanyong.wan4cd62602009-02-23 23:21:55 +00003865#if GTEST_OS_WINDOWS
shiqian4b6829f2008-07-03 22:38:12 +00003866
3867static HRESULT UnexpectedHRESULTFailure() {
3868 return E_UNEXPECTED;
3869}
3870
3871static HRESULT OkHRESULTSuccess() {
3872 return S_OK;
3873}
3874
3875static HRESULT FalseHRESULTSuccess() {
3876 return S_FALSE;
3877}
3878
3879// HRESULT assertion tests test both zero and non-zero
3880// success codes as well as failure message for each.
3881//
3882// Windows CE doesn't support message texts.
3883TEST(HRESULTAssertionTest, EXPECT_HRESULT_SUCCEEDED) {
3884 EXPECT_HRESULT_SUCCEEDED(S_OK);
3885 EXPECT_HRESULT_SUCCEEDED(S_FALSE);
3886
shiqian4b6829f2008-07-03 22:38:12 +00003887 EXPECT_NONFATAL_FAILURE(EXPECT_HRESULT_SUCCEEDED(UnexpectedHRESULTFailure()),
shiqianafebcbd2008-09-13 00:49:59 +00003888 "Expected: (UnexpectedHRESULTFailure()) succeeds.\n"
3889 " Actual: 0x8000FFFF");
shiqian4b6829f2008-07-03 22:38:12 +00003890}
3891
3892TEST(HRESULTAssertionTest, ASSERT_HRESULT_SUCCEEDED) {
3893 ASSERT_HRESULT_SUCCEEDED(S_OK);
3894 ASSERT_HRESULT_SUCCEEDED(S_FALSE);
3895
shiqian4b6829f2008-07-03 22:38:12 +00003896 EXPECT_FATAL_FAILURE(ASSERT_HRESULT_SUCCEEDED(UnexpectedHRESULTFailure()),
shiqianafebcbd2008-09-13 00:49:59 +00003897 "Expected: (UnexpectedHRESULTFailure()) succeeds.\n"
3898 " Actual: 0x8000FFFF");
shiqian4b6829f2008-07-03 22:38:12 +00003899}
3900
3901TEST(HRESULTAssertionTest, EXPECT_HRESULT_FAILED) {
3902 EXPECT_HRESULT_FAILED(E_UNEXPECTED);
3903
shiqian4b6829f2008-07-03 22:38:12 +00003904 EXPECT_NONFATAL_FAILURE(EXPECT_HRESULT_FAILED(OkHRESULTSuccess()),
shiqianafebcbd2008-09-13 00:49:59 +00003905 "Expected: (OkHRESULTSuccess()) fails.\n"
kosak@google.com3b8388d2013-02-22 20:10:40 +00003906 " Actual: 0x0");
shiqian4b6829f2008-07-03 22:38:12 +00003907 EXPECT_NONFATAL_FAILURE(EXPECT_HRESULT_FAILED(FalseHRESULTSuccess()),
shiqianafebcbd2008-09-13 00:49:59 +00003908 "Expected: (FalseHRESULTSuccess()) fails.\n"
kosak@google.com3b8388d2013-02-22 20:10:40 +00003909 " Actual: 0x1");
shiqian4b6829f2008-07-03 22:38:12 +00003910}
3911
3912TEST(HRESULTAssertionTest, ASSERT_HRESULT_FAILED) {
3913 ASSERT_HRESULT_FAILED(E_UNEXPECTED);
3914
zhanyong.wan733a54a2011-02-22 22:08:59 +00003915# ifndef __BORLANDC__
3916
zhanyong.wan98efcc42009-04-28 00:28:09 +00003917 // ICE's in C++Builder 2007 and 2009.
shiqian4b6829f2008-07-03 22:38:12 +00003918 EXPECT_FATAL_FAILURE(ASSERT_HRESULT_FAILED(OkHRESULTSuccess()),
shiqianafebcbd2008-09-13 00:49:59 +00003919 "Expected: (OkHRESULTSuccess()) fails.\n"
kosak@google.com3b8388d2013-02-22 20:10:40 +00003920 " Actual: 0x0");
zhanyong.wan733a54a2011-02-22 22:08:59 +00003921# endif
3922
shiqian4b6829f2008-07-03 22:38:12 +00003923 EXPECT_FATAL_FAILURE(ASSERT_HRESULT_FAILED(FalseHRESULTSuccess()),
shiqianafebcbd2008-09-13 00:49:59 +00003924 "Expected: (FalseHRESULTSuccess()) fails.\n"
kosak@google.com3b8388d2013-02-22 20:10:40 +00003925 " Actual: 0x1");
shiqian4b6829f2008-07-03 22:38:12 +00003926}
3927
3928// Tests that streaming to the HRESULT macros works.
3929TEST(HRESULTAssertionTest, Streaming) {
3930 EXPECT_HRESULT_SUCCEEDED(S_OK) << "unexpected failure";
3931 ASSERT_HRESULT_SUCCEEDED(S_OK) << "unexpected failure";
3932 EXPECT_HRESULT_FAILED(E_UNEXPECTED) << "unexpected failure";
3933 ASSERT_HRESULT_FAILED(E_UNEXPECTED) << "unexpected failure";
3934
3935 EXPECT_NONFATAL_FAILURE(
3936 EXPECT_HRESULT_SUCCEEDED(E_UNEXPECTED) << "expected failure",
3937 "expected failure");
3938
zhanyong.wan733a54a2011-02-22 22:08:59 +00003939# ifndef __BORLANDC__
3940
zhanyong.wan98efcc42009-04-28 00:28:09 +00003941 // ICE's in C++Builder 2007 and 2009.
shiqian4b6829f2008-07-03 22:38:12 +00003942 EXPECT_FATAL_FAILURE(
3943 ASSERT_HRESULT_SUCCEEDED(E_UNEXPECTED) << "expected failure",
3944 "expected failure");
zhanyong.wan733a54a2011-02-22 22:08:59 +00003945# endif
shiqian4b6829f2008-07-03 22:38:12 +00003946
3947 EXPECT_NONFATAL_FAILURE(
3948 EXPECT_HRESULT_FAILED(S_OK) << "expected failure",
3949 "expected failure");
3950
3951 EXPECT_FATAL_FAILURE(
3952 ASSERT_HRESULT_FAILED(S_OK) << "expected failure",
3953 "expected failure");
3954}
3955
zhanyong.wan4cd62602009-02-23 23:21:55 +00003956#endif // GTEST_OS_WINDOWS
shiqian4b6829f2008-07-03 22:38:12 +00003957
zhanyong.wan98efcc42009-04-28 00:28:09 +00003958#ifdef __BORLANDC__
3959// Silences warnings: "Condition is always true", "Unreachable code"
zhanyong.wan733a54a2011-02-22 22:08:59 +00003960# pragma option push -w-ccc -w-rch
zhanyong.wan98efcc42009-04-28 00:28:09 +00003961#endif
3962
shiqian4b6829f2008-07-03 22:38:12 +00003963// Tests that the assertion macros behave like single statements.
shiqiane44602e2008-10-11 07:20:02 +00003964TEST(AssertionSyntaxTest, BasicAssertionsBehavesLikeSingleStatement) {
zhanyong.wanf6d087b2009-09-30 20:23:50 +00003965 if (AlwaysFalse())
shiqian4b6829f2008-07-03 22:38:12 +00003966 ASSERT_TRUE(false) << "This should never be executed; "
3967 "It's a compilation test only.";
3968
zhanyong.wanf6d087b2009-09-30 20:23:50 +00003969 if (AlwaysTrue())
shiqian4b6829f2008-07-03 22:38:12 +00003970 EXPECT_FALSE(false);
3971 else
zhanyong.wan4e7e2fc2009-06-19 00:24:28 +00003972 ; // NOLINT
shiqian4b6829f2008-07-03 22:38:12 +00003973
zhanyong.wanf6d087b2009-09-30 20:23:50 +00003974 if (AlwaysFalse())
shiqian4b6829f2008-07-03 22:38:12 +00003975 ASSERT_LT(1, 3);
3976
zhanyong.wanf6d087b2009-09-30 20:23:50 +00003977 if (AlwaysFalse())
zhanyong.wan4e7e2fc2009-06-19 00:24:28 +00003978 ; // NOLINT
shiqian4b6829f2008-07-03 22:38:12 +00003979 else
3980 EXPECT_GT(3, 2) << "";
shiqiane44602e2008-10-11 07:20:02 +00003981}
shiqian9204c8e2008-09-12 20:57:22 +00003982
3983#if GTEST_HAS_EXCEPTIONS
zhanyong.wane0ca02f2009-02-06 00:47:20 +00003984// Tests that the compiler will not complain about unreachable code in the
3985// EXPECT_THROW/EXPECT_ANY_THROW/EXPECT_NO_THROW macros.
3986TEST(ExpectThrowTest, DoesNotGenerateUnreachableCodeWarning) {
3987 int n = 0;
3988
3989 EXPECT_THROW(throw 1, int);
3990 EXPECT_NONFATAL_FAILURE(EXPECT_THROW(n++, int), "");
3991 EXPECT_NONFATAL_FAILURE(EXPECT_THROW(throw 1, const char*), "");
3992 EXPECT_NO_THROW(n++);
3993 EXPECT_NONFATAL_FAILURE(EXPECT_NO_THROW(throw 1), "");
3994 EXPECT_ANY_THROW(throw 1);
3995 EXPECT_NONFATAL_FAILURE(EXPECT_ANY_THROW(n++), "");
3996}
3997
shiqiane44602e2008-10-11 07:20:02 +00003998TEST(AssertionSyntaxTest, ExceptionAssertionsBehavesLikeSingleStatement) {
zhanyong.wanf6d087b2009-09-30 20:23:50 +00003999 if (AlwaysFalse())
zhanyong.wanac60cef2009-02-08 04:53:35 +00004000 EXPECT_THROW(ThrowNothing(), bool);
shiqian9204c8e2008-09-12 20:57:22 +00004001
zhanyong.wanf6d087b2009-09-30 20:23:50 +00004002 if (AlwaysTrue())
shiqian9204c8e2008-09-12 20:57:22 +00004003 EXPECT_THROW(ThrowAnInteger(), int);
4004 else
zhanyong.wan4e7e2fc2009-06-19 00:24:28 +00004005 ; // NOLINT
shiqian9204c8e2008-09-12 20:57:22 +00004006
zhanyong.wanf6d087b2009-09-30 20:23:50 +00004007 if (AlwaysFalse())
shiqian9204c8e2008-09-12 20:57:22 +00004008 EXPECT_NO_THROW(ThrowAnInteger());
4009
zhanyong.wanf6d087b2009-09-30 20:23:50 +00004010 if (AlwaysTrue())
zhanyong.wanac60cef2009-02-08 04:53:35 +00004011 EXPECT_NO_THROW(ThrowNothing());
shiqian9204c8e2008-09-12 20:57:22 +00004012 else
zhanyong.wan4e7e2fc2009-06-19 00:24:28 +00004013 ; // NOLINT
shiqian9204c8e2008-09-12 20:57:22 +00004014
zhanyong.wanf6d087b2009-09-30 20:23:50 +00004015 if (AlwaysFalse())
zhanyong.wanac60cef2009-02-08 04:53:35 +00004016 EXPECT_ANY_THROW(ThrowNothing());
shiqian9204c8e2008-09-12 20:57:22 +00004017
zhanyong.wanf6d087b2009-09-30 20:23:50 +00004018 if (AlwaysTrue())
shiqian9204c8e2008-09-12 20:57:22 +00004019 EXPECT_ANY_THROW(ThrowAnInteger());
4020 else
zhanyong.wan4e7e2fc2009-06-19 00:24:28 +00004021 ; // NOLINT
shiqiane44602e2008-10-11 07:20:02 +00004022}
shiqian9204c8e2008-09-12 20:57:22 +00004023#endif // GTEST_HAS_EXCEPTIONS
shiqiane44602e2008-10-11 07:20:02 +00004024
4025TEST(AssertionSyntaxTest, NoFatalFailureAssertionsBehavesLikeSingleStatement) {
zhanyong.wanf6d087b2009-09-30 20:23:50 +00004026 if (AlwaysFalse())
shiqiane44602e2008-10-11 07:20:02 +00004027 EXPECT_NO_FATAL_FAILURE(FAIL()) << "This should never be executed. "
4028 << "It's a compilation test only.";
4029 else
zhanyong.wan4e7e2fc2009-06-19 00:24:28 +00004030 ; // NOLINT
shiqiane44602e2008-10-11 07:20:02 +00004031
zhanyong.wanf6d087b2009-09-30 20:23:50 +00004032 if (AlwaysFalse())
shiqiane44602e2008-10-11 07:20:02 +00004033 ASSERT_NO_FATAL_FAILURE(FAIL()) << "";
4034 else
zhanyong.wan4e7e2fc2009-06-19 00:24:28 +00004035 ; // NOLINT
shiqiane44602e2008-10-11 07:20:02 +00004036
zhanyong.wanf6d087b2009-09-30 20:23:50 +00004037 if (AlwaysTrue())
shiqiane44602e2008-10-11 07:20:02 +00004038 EXPECT_NO_FATAL_FAILURE(SUCCEED());
4039 else
zhanyong.wan4e7e2fc2009-06-19 00:24:28 +00004040 ; // NOLINT
shiqiane44602e2008-10-11 07:20:02 +00004041
zhanyong.wanf6d087b2009-09-30 20:23:50 +00004042 if (AlwaysFalse())
zhanyong.wan4e7e2fc2009-06-19 00:24:28 +00004043 ; // NOLINT
shiqiane44602e2008-10-11 07:20:02 +00004044 else
4045 ASSERT_NO_FATAL_FAILURE(SUCCEED());
shiqian4b6829f2008-07-03 22:38:12 +00004046}
4047
4048// Tests that the assertion macros work well with switch statements.
4049TEST(AssertionSyntaxTest, WorksWithSwitch) {
4050 switch (0) {
4051 case 1:
4052 break;
4053 default:
4054 ASSERT_TRUE(true);
4055 }
4056
4057 switch (0)
4058 case 0:
4059 EXPECT_FALSE(false) << "EXPECT_FALSE failed in switch case";
4060
4061 // Binary assertions are implemented using a different code path
4062 // than the Boolean assertions. Hence we test them separately.
4063 switch (0) {
4064 case 1:
4065 default:
4066 ASSERT_EQ(1, 1) << "ASSERT_EQ failed in default switch handler";
4067 }
4068
4069 switch (0)
4070 case 0:
4071 EXPECT_NE(1, 2);
4072}
4073
shiqian9204c8e2008-09-12 20:57:22 +00004074#if GTEST_HAS_EXCEPTIONS
4075
4076void ThrowAString() {
jgm@google.com03c31492012-11-15 15:47:38 +00004077 throw "std::string";
shiqian9204c8e2008-09-12 20:57:22 +00004078}
4079
4080// Test that the exception assertion macros compile and work with const
4081// type qualifier.
4082TEST(AssertionSyntaxTest, WorksWithConst) {
4083 ASSERT_THROW(ThrowAString(), const char*);
4084
4085 EXPECT_THROW(ThrowAString(), const char*);
4086}
4087
4088#endif // GTEST_HAS_EXCEPTIONS
4089
shiqian4b6829f2008-07-03 22:38:12 +00004090} // namespace
4091
shiqian4b6829f2008-07-03 22:38:12 +00004092namespace testing {
4093
4094// Tests that Google Test tracks SUCCEED*.
4095TEST(SuccessfulAssertionTest, SUCCEED) {
4096 SUCCEED();
4097 SUCCEED() << "OK";
zhanyong.wan1cdc7632009-07-16 00:36:55 +00004098 EXPECT_EQ(2, GetUnitTestImpl()->current_test_result()->total_part_count());
shiqian4b6829f2008-07-03 22:38:12 +00004099}
4100
4101// Tests that Google Test doesn't track successful EXPECT_*.
4102TEST(SuccessfulAssertionTest, EXPECT) {
4103 EXPECT_TRUE(true);
zhanyong.wan1cdc7632009-07-16 00:36:55 +00004104 EXPECT_EQ(0, GetUnitTestImpl()->current_test_result()->total_part_count());
shiqian4b6829f2008-07-03 22:38:12 +00004105}
4106
4107// Tests that Google Test doesn't track successful EXPECT_STR*.
4108TEST(SuccessfulAssertionTest, EXPECT_STR) {
4109 EXPECT_STREQ("", "");
zhanyong.wan1cdc7632009-07-16 00:36:55 +00004110 EXPECT_EQ(0, GetUnitTestImpl()->current_test_result()->total_part_count());
shiqian4b6829f2008-07-03 22:38:12 +00004111}
4112
4113// Tests that Google Test doesn't track successful ASSERT_*.
4114TEST(SuccessfulAssertionTest, ASSERT) {
4115 ASSERT_TRUE(true);
zhanyong.wan1cdc7632009-07-16 00:36:55 +00004116 EXPECT_EQ(0, GetUnitTestImpl()->current_test_result()->total_part_count());
shiqian4b6829f2008-07-03 22:38:12 +00004117}
4118
4119// Tests that Google Test doesn't track successful ASSERT_STR*.
4120TEST(SuccessfulAssertionTest, ASSERT_STR) {
4121 ASSERT_STREQ("", "");
zhanyong.wan1cdc7632009-07-16 00:36:55 +00004122 EXPECT_EQ(0, GetUnitTestImpl()->current_test_result()->total_part_count());
shiqian4b6829f2008-07-03 22:38:12 +00004123}
4124
4125} // namespace testing
4126
4127namespace {
4128
jgm@google.com7a574c92012-03-09 17:12:39 +00004129// Tests the message streaming variation of assertions.
4130
4131TEST(AssertionWithMessageTest, EXPECT) {
4132 EXPECT_EQ(1, 1) << "This should succeed.";
4133 EXPECT_NONFATAL_FAILURE(EXPECT_NE(1, 1) << "Expected failure #1.",
4134 "Expected failure #1");
4135 EXPECT_LE(1, 2) << "This should succeed.";
4136 EXPECT_NONFATAL_FAILURE(EXPECT_LT(1, 0) << "Expected failure #2.",
4137 "Expected failure #2.");
4138 EXPECT_GE(1, 0) << "This should succeed.";
4139 EXPECT_NONFATAL_FAILURE(EXPECT_GT(1, 2) << "Expected failure #3.",
4140 "Expected failure #3.");
4141
4142 EXPECT_STREQ("1", "1") << "This should succeed.";
4143 EXPECT_NONFATAL_FAILURE(EXPECT_STRNE("1", "1") << "Expected failure #4.",
4144 "Expected failure #4.");
4145 EXPECT_STRCASEEQ("a", "A") << "This should succeed.";
4146 EXPECT_NONFATAL_FAILURE(EXPECT_STRCASENE("a", "A") << "Expected failure #5.",
4147 "Expected failure #5.");
4148
4149 EXPECT_FLOAT_EQ(1, 1) << "This should succeed.";
4150 EXPECT_NONFATAL_FAILURE(EXPECT_DOUBLE_EQ(1, 1.2) << "Expected failure #6.",
4151 "Expected failure #6.");
4152 EXPECT_NEAR(1, 1.1, 0.2) << "This should succeed.";
4153}
4154
4155TEST(AssertionWithMessageTest, ASSERT) {
4156 ASSERT_EQ(1, 1) << "This should succeed.";
4157 ASSERT_NE(1, 2) << "This should succeed.";
4158 ASSERT_LE(1, 2) << "This should succeed.";
4159 ASSERT_LT(1, 2) << "This should succeed.";
4160 ASSERT_GE(1, 0) << "This should succeed.";
4161 EXPECT_FATAL_FAILURE(ASSERT_GT(1, 2) << "Expected failure.",
4162 "Expected failure.");
4163}
4164
4165TEST(AssertionWithMessageTest, ASSERT_STR) {
4166 ASSERT_STREQ("1", "1") << "This should succeed.";
4167 ASSERT_STRNE("1", "2") << "This should succeed.";
4168 ASSERT_STRCASEEQ("a", "A") << "This should succeed.";
4169 EXPECT_FATAL_FAILURE(ASSERT_STRCASENE("a", "A") << "Expected failure.",
4170 "Expected failure.");
4171}
4172
4173TEST(AssertionWithMessageTest, ASSERT_FLOATING) {
4174 ASSERT_FLOAT_EQ(1, 1) << "This should succeed.";
4175 ASSERT_DOUBLE_EQ(1, 1) << "This should succeed.";
4176 EXPECT_FATAL_FAILURE(ASSERT_NEAR(1,1.2, 0.1) << "Expect failure.", // NOLINT
4177 "Expect failure.");
4178 // To work around a bug in gcc 2.95.0, there is intentionally no
4179 // space after the first comma in the previous statement.
4180}
4181
4182// Tests using ASSERT_FALSE with a streamed message.
4183TEST(AssertionWithMessageTest, ASSERT_FALSE) {
4184 ASSERT_FALSE(false) << "This shouldn't fail.";
4185 EXPECT_FATAL_FAILURE({ // NOLINT
4186 ASSERT_FALSE(true) << "Expected failure: " << 2 << " > " << 1
4187 << " evaluates to " << true;
4188 }, "Expected failure");
4189}
4190
4191// Tests using FAIL with a streamed message.
4192TEST(AssertionWithMessageTest, FAIL) {
4193 EXPECT_FATAL_FAILURE(FAIL() << 0,
4194 "0");
4195}
4196
4197// Tests using SUCCEED with a streamed message.
4198TEST(AssertionWithMessageTest, SUCCEED) {
4199 SUCCEED() << "Success == " << 1;
4200}
4201
4202// Tests using ASSERT_TRUE with a streamed message.
4203TEST(AssertionWithMessageTest, ASSERT_TRUE) {
4204 ASSERT_TRUE(true) << "This should succeed.";
4205 ASSERT_TRUE(true) << true;
4206 EXPECT_FATAL_FAILURE({ // NOLINT
4207 ASSERT_TRUE(false) << static_cast<const char *>(NULL)
4208 << static_cast<char *>(NULL);
4209 }, "(null)(null)");
4210}
4211
4212#if GTEST_OS_WINDOWS
4213// Tests using wide strings in assertion messages.
4214TEST(AssertionWithMessageTest, WideStringMessage) {
4215 EXPECT_NONFATAL_FAILURE({ // NOLINT
4216 EXPECT_TRUE(false) << L"This failure is expected.\x8119";
4217 }, "This failure is expected.");
4218 EXPECT_FATAL_FAILURE({ // NOLINT
4219 ASSERT_EQ(1, 2) << "This failure is "
4220 << L"expected too.\x8120";
4221 }, "This failure is expected too.");
4222}
4223#endif // GTEST_OS_WINDOWS
4224
shiqian4b6829f2008-07-03 22:38:12 +00004225// Tests EXPECT_TRUE.
4226TEST(ExpectTest, EXPECT_TRUE) {
jgm@google.com7a574c92012-03-09 17:12:39 +00004227 EXPECT_TRUE(true) << "Intentional success";
4228 EXPECT_NONFATAL_FAILURE(EXPECT_TRUE(false) << "Intentional failure #1.",
4229 "Intentional failure #1.");
4230 EXPECT_NONFATAL_FAILURE(EXPECT_TRUE(false) << "Intentional failure #2.",
4231 "Intentional failure #2.");
shiqian4b6829f2008-07-03 22:38:12 +00004232 EXPECT_TRUE(2 > 1); // NOLINT
4233 EXPECT_NONFATAL_FAILURE(EXPECT_TRUE(2 < 1),
4234 "Value of: 2 < 1\n"
4235 " Actual: false\n"
4236 "Expected: true");
4237 EXPECT_NONFATAL_FAILURE(EXPECT_TRUE(2 > 3),
4238 "2 > 3");
4239}
4240
vladlosevfbd53a52009-10-20 21:03:10 +00004241// Tests EXPECT_TRUE(predicate) for predicates returning AssertionResult.
4242TEST(ExpectTest, ExpectTrueWithAssertionResult) {
4243 EXPECT_TRUE(ResultIsEven(2));
4244 EXPECT_NONFATAL_FAILURE(EXPECT_TRUE(ResultIsEven(3)),
4245 "Value of: ResultIsEven(3)\n"
4246 " Actual: false (3 is odd)\n"
4247 "Expected: true");
4248 EXPECT_TRUE(ResultIsEvenNoExplanation(2));
4249 EXPECT_NONFATAL_FAILURE(EXPECT_TRUE(ResultIsEvenNoExplanation(3)),
4250 "Value of: ResultIsEvenNoExplanation(3)\n"
4251 " Actual: false (3 is odd)\n"
4252 "Expected: true");
4253}
4254
jgm@google.com7a574c92012-03-09 17:12:39 +00004255// Tests EXPECT_FALSE with a streamed message.
shiqian4b6829f2008-07-03 22:38:12 +00004256TEST(ExpectTest, EXPECT_FALSE) {
4257 EXPECT_FALSE(2 < 1); // NOLINT
jgm@google.com7a574c92012-03-09 17:12:39 +00004258 EXPECT_FALSE(false) << "Intentional success";
4259 EXPECT_NONFATAL_FAILURE(EXPECT_FALSE(true) << "Intentional failure #1.",
4260 "Intentional failure #1.");
4261 EXPECT_NONFATAL_FAILURE(EXPECT_FALSE(true) << "Intentional failure #2.",
4262 "Intentional failure #2.");
shiqian4b6829f2008-07-03 22:38:12 +00004263 EXPECT_NONFATAL_FAILURE(EXPECT_FALSE(2 > 1),
4264 "Value of: 2 > 1\n"
4265 " Actual: true\n"
4266 "Expected: false");
4267 EXPECT_NONFATAL_FAILURE(EXPECT_FALSE(2 < 3),
4268 "2 < 3");
4269}
4270
vladlosevfbd53a52009-10-20 21:03:10 +00004271// Tests EXPECT_FALSE(predicate) for predicates returning AssertionResult.
4272TEST(ExpectTest, ExpectFalseWithAssertionResult) {
4273 EXPECT_FALSE(ResultIsEven(3));
4274 EXPECT_NONFATAL_FAILURE(EXPECT_FALSE(ResultIsEven(2)),
4275 "Value of: ResultIsEven(2)\n"
4276 " Actual: true (2 is even)\n"
4277 "Expected: false");
4278 EXPECT_FALSE(ResultIsEvenNoExplanation(3));
4279 EXPECT_NONFATAL_FAILURE(EXPECT_FALSE(ResultIsEvenNoExplanation(2)),
4280 "Value of: ResultIsEvenNoExplanation(2)\n"
4281 " Actual: true\n"
4282 "Expected: false");
4283}
4284
zhanyong.wan98efcc42009-04-28 00:28:09 +00004285#ifdef __BORLANDC__
4286// Restores warnings after previous "#pragma option push" supressed them
zhanyong.wan733a54a2011-02-22 22:08:59 +00004287# pragma option pop
zhanyong.wan98efcc42009-04-28 00:28:09 +00004288#endif
4289
shiqian4b6829f2008-07-03 22:38:12 +00004290// Tests EXPECT_EQ.
4291TEST(ExpectTest, EXPECT_EQ) {
4292 EXPECT_EQ(5, 2 + 3);
4293 EXPECT_NONFATAL_FAILURE(EXPECT_EQ(5, 2*3),
4294 "Value of: 2*3\n"
4295 " Actual: 6\n"
4296 "Expected: 5");
4297 EXPECT_NONFATAL_FAILURE(EXPECT_EQ(5, 2 - 3),
4298 "2 - 3");
4299}
4300
4301// Tests using EXPECT_EQ on double values. The purpose is to make
4302// sure that the specialization we did for integer and anonymous enums
4303// isn't used for double arguments.
4304TEST(ExpectTest, EXPECT_EQ_Double) {
4305 // A success.
4306 EXPECT_EQ(5.6, 5.6);
4307
4308 // A failure.
4309 EXPECT_NONFATAL_FAILURE(EXPECT_EQ(5.1, 5.2),
4310 "5.1");
4311}
4312
vladlosev5147b452010-03-17 18:22:59 +00004313#if GTEST_CAN_COMPARE_NULL
shiqian4b6829f2008-07-03 22:38:12 +00004314// Tests EXPECT_EQ(NULL, pointer).
4315TEST(ExpectTest, EXPECT_EQ_NULL) {
4316 // A success.
4317 const char* p = NULL;
zhanyong.wan5e255e02011-01-10 18:17:59 +00004318 // Some older GCC versions may issue a spurious warning in this or the next
zhanyong.wan9644db82009-06-24 23:02:50 +00004319 // assertion statement. This warning should not be suppressed with
4320 // static_cast since the test verifies the ability to use bare NULL as the
4321 // expected parameter to the macro.
shiqian4b6829f2008-07-03 22:38:12 +00004322 EXPECT_EQ(NULL, p);
4323
4324 // A failure.
4325 int n = 0;
4326 EXPECT_NONFATAL_FAILURE(EXPECT_EQ(NULL, &n),
4327 "Value of: &n\n");
4328}
vladlosev5147b452010-03-17 18:22:59 +00004329#endif // GTEST_CAN_COMPARE_NULL
shiqian4b6829f2008-07-03 22:38:12 +00004330
4331// Tests EXPECT_EQ(0, non_pointer). Since the literal 0 can be
4332// treated as a null pointer by the compiler, we need to make sure
4333// that EXPECT_EQ(0, non_pointer) isn't interpreted by Google Test as
4334// EXPECT_EQ(static_cast<void*>(NULL), non_pointer).
4335TEST(ExpectTest, EXPECT_EQ_0) {
4336 int n = 0;
4337
4338 // A success.
4339 EXPECT_EQ(0, n);
4340
4341 // A failure.
4342 EXPECT_NONFATAL_FAILURE(EXPECT_EQ(0, 5.6),
4343 "Expected: 0");
4344}
4345
4346// Tests EXPECT_NE.
4347TEST(ExpectTest, EXPECT_NE) {
4348 EXPECT_NE(6, 7);
4349
4350 EXPECT_NONFATAL_FAILURE(EXPECT_NE('a', 'a'),
4351 "Expected: ('a') != ('a'), "
4352 "actual: 'a' (97, 0x61) vs 'a' (97, 0x61)");
4353 EXPECT_NONFATAL_FAILURE(EXPECT_NE(2, 2),
4354 "2");
4355 char* const p0 = NULL;
4356 EXPECT_NONFATAL_FAILURE(EXPECT_NE(p0, p0),
4357 "p0");
4358 // Only way to get the Nokia compiler to compile the cast
4359 // is to have a separate void* variable first. Putting
4360 // the two casts on the same line doesn't work, neither does
4361 // a direct C-style to char*.
4362 void* pv1 = (void*)0x1234; // NOLINT
4363 char* const p1 = reinterpret_cast<char*>(pv1);
4364 EXPECT_NONFATAL_FAILURE(EXPECT_NE(p1, p1),
4365 "p1");
4366}
4367
4368// Tests EXPECT_LE.
4369TEST(ExpectTest, EXPECT_LE) {
4370 EXPECT_LE(2, 3);
4371 EXPECT_LE(2, 2);
4372 EXPECT_NONFATAL_FAILURE(EXPECT_LE(2, 0),
4373 "Expected: (2) <= (0), actual: 2 vs 0");
4374 EXPECT_NONFATAL_FAILURE(EXPECT_LE(1.1, 0.9),
4375 "(1.1) <= (0.9)");
4376}
4377
4378// Tests EXPECT_LT.
4379TEST(ExpectTest, EXPECT_LT) {
4380 EXPECT_LT(2, 3);
4381 EXPECT_NONFATAL_FAILURE(EXPECT_LT(2, 2),
4382 "Expected: (2) < (2), actual: 2 vs 2");
4383 EXPECT_NONFATAL_FAILURE(EXPECT_LT(2, 1),
4384 "(2) < (1)");
4385}
4386
4387// Tests EXPECT_GE.
4388TEST(ExpectTest, EXPECT_GE) {
4389 EXPECT_GE(2, 1);
4390 EXPECT_GE(2, 2);
4391 EXPECT_NONFATAL_FAILURE(EXPECT_GE(2, 3),
4392 "Expected: (2) >= (3), actual: 2 vs 3");
4393 EXPECT_NONFATAL_FAILURE(EXPECT_GE(0.9, 1.1),
4394 "(0.9) >= (1.1)");
4395}
4396
4397// Tests EXPECT_GT.
4398TEST(ExpectTest, EXPECT_GT) {
4399 EXPECT_GT(2, 1);
4400 EXPECT_NONFATAL_FAILURE(EXPECT_GT(2, 2),
4401 "Expected: (2) > (2), actual: 2 vs 2");
4402 EXPECT_NONFATAL_FAILURE(EXPECT_GT(2, 3),
4403 "(2) > (3)");
4404}
4405
shiqian9204c8e2008-09-12 20:57:22 +00004406#if GTEST_HAS_EXCEPTIONS
4407
4408// Tests EXPECT_THROW.
4409TEST(ExpectTest, EXPECT_THROW) {
4410 EXPECT_THROW(ThrowAnInteger(), int);
4411 EXPECT_NONFATAL_FAILURE(EXPECT_THROW(ThrowAnInteger(), bool),
zhanyong.wanac60cef2009-02-08 04:53:35 +00004412 "Expected: ThrowAnInteger() throws an exception of "
shiqian9204c8e2008-09-12 20:57:22 +00004413 "type bool.\n Actual: it throws a different type.");
zhanyong.wanac60cef2009-02-08 04:53:35 +00004414 EXPECT_NONFATAL_FAILURE(
4415 EXPECT_THROW(ThrowNothing(), bool),
4416 "Expected: ThrowNothing() throws an exception of type bool.\n"
4417 " Actual: it throws nothing.");
shiqian9204c8e2008-09-12 20:57:22 +00004418}
4419
4420// Tests EXPECT_NO_THROW.
4421TEST(ExpectTest, EXPECT_NO_THROW) {
zhanyong.wanac60cef2009-02-08 04:53:35 +00004422 EXPECT_NO_THROW(ThrowNothing());
shiqian9204c8e2008-09-12 20:57:22 +00004423 EXPECT_NONFATAL_FAILURE(EXPECT_NO_THROW(ThrowAnInteger()),
zhanyong.wanac60cef2009-02-08 04:53:35 +00004424 "Expected: ThrowAnInteger() doesn't throw an "
shiqian9204c8e2008-09-12 20:57:22 +00004425 "exception.\n Actual: it throws.");
4426}
4427
4428// Tests EXPECT_ANY_THROW.
4429TEST(ExpectTest, EXPECT_ANY_THROW) {
4430 EXPECT_ANY_THROW(ThrowAnInteger());
zhanyong.wanac60cef2009-02-08 04:53:35 +00004431 EXPECT_NONFATAL_FAILURE(
4432 EXPECT_ANY_THROW(ThrowNothing()),
4433 "Expected: ThrowNothing() throws an exception.\n"
4434 " Actual: it doesn't.");
shiqian9204c8e2008-09-12 20:57:22 +00004435}
4436
4437#endif // GTEST_HAS_EXCEPTIONS
4438
shiqian4b6829f2008-07-03 22:38:12 +00004439// Make sure we deal with the precedence of <<.
4440TEST(ExpectTest, ExpectPrecedence) {
4441 EXPECT_EQ(1 < 2, true);
4442 EXPECT_NONFATAL_FAILURE(EXPECT_EQ(true, true && false),
4443 "Value of: true && false");
4444}
4445
4446
4447// Tests the StreamableToString() function.
4448
4449// Tests using StreamableToString() on a scalar.
4450TEST(StreamableToStringTest, Scalar) {
4451 EXPECT_STREQ("5", StreamableToString(5).c_str());
4452}
4453
4454// Tests using StreamableToString() on a non-char pointer.
4455TEST(StreamableToStringTest, Pointer) {
4456 int n = 0;
4457 int* p = &n;
4458 EXPECT_STRNE("(null)", StreamableToString(p).c_str());
4459}
4460
4461// Tests using StreamableToString() on a NULL non-char pointer.
4462TEST(StreamableToStringTest, NullPointer) {
4463 int* p = NULL;
4464 EXPECT_STREQ("(null)", StreamableToString(p).c_str());
4465}
4466
4467// Tests using StreamableToString() on a C string.
4468TEST(StreamableToStringTest, CString) {
4469 EXPECT_STREQ("Foo", StreamableToString("Foo").c_str());
4470}
4471
4472// Tests using StreamableToString() on a NULL C string.
4473TEST(StreamableToStringTest, NullCString) {
4474 char* p = NULL;
4475 EXPECT_STREQ("(null)", StreamableToString(p).c_str());
4476}
4477
4478// Tests using streamable values as assertion messages.
4479
shiqian4b6829f2008-07-03 22:38:12 +00004480// Tests using std::string as an assertion message.
4481TEST(StreamableTest, string) {
4482 static const std::string str(
4483 "This failure message is a std::string, and is expected.");
4484 EXPECT_FATAL_FAILURE(FAIL() << str,
4485 str.c_str());
4486}
4487
4488// Tests that we can output strings containing embedded NULs.
4489// Limited to Linux because we can only do this with std::string's.
4490TEST(StreamableTest, stringWithEmbeddedNUL) {
4491 static const char char_array_with_nul[] =
4492 "Here's a NUL\0 and some more string";
4493 static const std::string string_with_nul(char_array_with_nul,
4494 sizeof(char_array_with_nul)
4495 - 1); // drops the trailing NUL
4496 EXPECT_FATAL_FAILURE(FAIL() << string_with_nul,
4497 "Here's a NUL\\0 and some more string");
4498}
4499
shiqian4b6829f2008-07-03 22:38:12 +00004500// Tests that we can output a NUL char.
4501TEST(StreamableTest, NULChar) {
4502 EXPECT_FATAL_FAILURE({ // NOLINT
4503 FAIL() << "A NUL" << '\0' << " and some more string";
4504 }, "A NUL\\0 and some more string");
4505}
4506
4507// Tests using int as an assertion message.
4508TEST(StreamableTest, int) {
4509 EXPECT_FATAL_FAILURE(FAIL() << 900913,
4510 "900913");
4511}
4512
4513// Tests using NULL char pointer as an assertion message.
4514//
4515// In MSVC, streaming a NULL char * causes access violation. Google Test
4516// implemented a workaround (substituting "(null)" for NULL). This
4517// tests whether the workaround works.
4518TEST(StreamableTest, NullCharPtr) {
4519 EXPECT_FATAL_FAILURE(FAIL() << static_cast<const char*>(NULL),
4520 "(null)");
4521}
4522
4523// Tests that basic IO manipulators (endl, ends, and flush) can be
4524// streamed to testing::Message.
4525TEST(StreamableTest, BasicIoManip) {
4526 EXPECT_FATAL_FAILURE({ // NOLINT
4527 FAIL() << "Line 1." << std::endl
4528 << "A NUL char " << std::ends << std::flush << " in line 2.";
4529 }, "Line 1.\nA NUL char \\0 in line 2.");
4530}
4531
shiqian4b6829f2008-07-03 22:38:12 +00004532// Tests the macros that haven't been covered so far.
4533
4534void AddFailureHelper(bool* aborted) {
4535 *aborted = true;
jgm@google.com7a574c92012-03-09 17:12:39 +00004536 ADD_FAILURE() << "Intentional failure.";
shiqian4b6829f2008-07-03 22:38:12 +00004537 *aborted = false;
4538}
4539
4540// Tests ADD_FAILURE.
4541TEST(MacroTest, ADD_FAILURE) {
4542 bool aborted = true;
4543 EXPECT_NONFATAL_FAILURE(AddFailureHelper(&aborted),
jgm@google.com7a574c92012-03-09 17:12:39 +00004544 "Intentional failure.");
shiqian4b6829f2008-07-03 22:38:12 +00004545 EXPECT_FALSE(aborted);
4546}
4547
zhanyong.wand5ad2ca2010-07-26 21:59:50 +00004548// Tests ADD_FAILURE_AT.
4549TEST(MacroTest, ADD_FAILURE_AT) {
4550 // Verifies that ADD_FAILURE_AT does generate a nonfatal failure and
4551 // the failure message contains the user-streamed part.
4552 EXPECT_NONFATAL_FAILURE(ADD_FAILURE_AT("foo.cc", 42) << "Wrong!", "Wrong!");
4553
4554 // Verifies that the user-streamed part is optional.
4555 EXPECT_NONFATAL_FAILURE(ADD_FAILURE_AT("foo.cc", 42), "Failed");
4556
4557 // Unfortunately, we cannot verify that the failure message contains
4558 // the right file path and line number the same way, as
4559 // EXPECT_NONFATAL_FAILURE() doesn't get to see the file path and
4560 // line number. Instead, we do that in gtest_output_test_.cc.
4561}
4562
shiqian4b6829f2008-07-03 22:38:12 +00004563// Tests FAIL.
4564TEST(MacroTest, FAIL) {
4565 EXPECT_FATAL_FAILURE(FAIL(),
4566 "Failed");
4567 EXPECT_FATAL_FAILURE(FAIL() << "Intentional failure.",
4568 "Intentional failure.");
4569}
4570
4571// Tests SUCCEED
4572TEST(MacroTest, SUCCEED) {
4573 SUCCEED();
4574 SUCCEED() << "Explicit success.";
4575}
4576
shiqian4b6829f2008-07-03 22:38:12 +00004577// Tests for EXPECT_EQ() and ASSERT_EQ().
4578//
4579// These tests fail *intentionally*, s.t. the failure messages can be
4580// generated and tested.
4581//
4582// We have different tests for different argument types.
4583
4584// Tests using bool values in {EXPECT|ASSERT}_EQ.
4585TEST(EqAssertionTest, Bool) {
4586 EXPECT_EQ(true, true);
zhanyong.wan5e255e02011-01-10 18:17:59 +00004587 EXPECT_FATAL_FAILURE({
4588 bool false_value = false;
4589 ASSERT_EQ(false_value, true);
4590 }, "Value of: true");
shiqian4b6829f2008-07-03 22:38:12 +00004591}
4592
4593// Tests using int values in {EXPECT|ASSERT}_EQ.
4594TEST(EqAssertionTest, Int) {
4595 ASSERT_EQ(32, 32);
4596 EXPECT_NONFATAL_FAILURE(EXPECT_EQ(32, 33),
4597 "33");
4598}
4599
4600// Tests using time_t values in {EXPECT|ASSERT}_EQ.
4601TEST(EqAssertionTest, Time_T) {
4602 EXPECT_EQ(static_cast<time_t>(0),
4603 static_cast<time_t>(0));
4604 EXPECT_FATAL_FAILURE(ASSERT_EQ(static_cast<time_t>(0),
4605 static_cast<time_t>(1234)),
4606 "1234");
4607}
4608
4609// Tests using char values in {EXPECT|ASSERT}_EQ.
4610TEST(EqAssertionTest, Char) {
4611 ASSERT_EQ('z', 'z');
4612 const char ch = 'b';
4613 EXPECT_NONFATAL_FAILURE(EXPECT_EQ('\0', ch),
4614 "ch");
4615 EXPECT_NONFATAL_FAILURE(EXPECT_EQ('a', ch),
4616 "ch");
4617}
4618
4619// Tests using wchar_t values in {EXPECT|ASSERT}_EQ.
4620TEST(EqAssertionTest, WideChar) {
4621 EXPECT_EQ(L'b', L'b');
4622
4623 EXPECT_NONFATAL_FAILURE(EXPECT_EQ(L'\0', L'x'),
4624 "Value of: L'x'\n"
4625 " Actual: L'x' (120, 0x78)\n"
4626 "Expected: L'\0'\n"
4627 "Which is: L'\0' (0, 0x0)");
4628
4629 static wchar_t wchar;
4630 wchar = L'b';
4631 EXPECT_NONFATAL_FAILURE(EXPECT_EQ(L'a', wchar),
4632 "wchar");
zhanyong.wanb499e7b2010-10-11 06:28:54 +00004633 wchar = 0x8119;
4634 EXPECT_FATAL_FAILURE(ASSERT_EQ(static_cast<wchar_t>(0x8120), wchar),
shiqian4b6829f2008-07-03 22:38:12 +00004635 "Value of: wchar");
4636}
4637
shiqian4b6829f2008-07-03 22:38:12 +00004638// Tests using ::std::string values in {EXPECT|ASSERT}_EQ.
4639TEST(EqAssertionTest, StdString) {
4640 // Compares a const char* to an std::string that has identical
4641 // content.
4642 ASSERT_EQ("Test", ::std::string("Test"));
4643
4644 // Compares two identical std::strings.
4645 static const ::std::string str1("A * in the middle");
4646 static const ::std::string str2(str1);
4647 EXPECT_EQ(str1, str2);
4648
4649 // Compares a const char* to an std::string that has different
4650 // content
4651 EXPECT_NONFATAL_FAILURE(EXPECT_EQ("Test", ::std::string("test")),
zhanyong.wanf2ac1ec2013-04-04 22:44:57 +00004652 "\"test\"");
shiqian4b6829f2008-07-03 22:38:12 +00004653
4654 // Compares an std::string to a char* that has different content.
4655 char* const p1 = const_cast<char*>("foo");
4656 EXPECT_NONFATAL_FAILURE(EXPECT_EQ(::std::string("bar"), p1),
4657 "p1");
4658
4659 // Compares two std::strings that have different contents, one of
4660 // which having a NUL character in the middle. This should fail.
4661 static ::std::string str3(str1);
4662 str3.at(2) = '\0';
4663 EXPECT_FATAL_FAILURE(ASSERT_EQ(str1, str3),
4664 "Value of: str3\n"
4665 " Actual: \"A \\0 in the middle\"");
4666}
4667
shiqian4b6829f2008-07-03 22:38:12 +00004668#if GTEST_HAS_STD_WSTRING
4669
4670// Tests using ::std::wstring values in {EXPECT|ASSERT}_EQ.
4671TEST(EqAssertionTest, StdWideString) {
shiqian4b6829f2008-07-03 22:38:12 +00004672 // Compares two identical std::wstrings.
4673 const ::std::wstring wstr1(L"A * in the middle");
4674 const ::std::wstring wstr2(wstr1);
4675 ASSERT_EQ(wstr1, wstr2);
4676
zhanyong.wanb499e7b2010-10-11 06:28:54 +00004677 // Compares an std::wstring to a const wchar_t* that has identical
4678 // content.
4679 const wchar_t kTestX8119[] = { 'T', 'e', 's', 't', 0x8119, '\0' };
4680 EXPECT_EQ(::std::wstring(kTestX8119), kTestX8119);
4681
shiqian4b6829f2008-07-03 22:38:12 +00004682 // Compares an std::wstring to a const wchar_t* that has different
4683 // content.
zhanyong.wanb499e7b2010-10-11 06:28:54 +00004684 const wchar_t kTestX8120[] = { 'T', 'e', 's', 't', 0x8120, '\0' };
shiqian4b6829f2008-07-03 22:38:12 +00004685 EXPECT_NONFATAL_FAILURE({ // NOLINT
zhanyong.wanb499e7b2010-10-11 06:28:54 +00004686 EXPECT_EQ(::std::wstring(kTestX8119), kTestX8120);
4687 }, "kTestX8120");
shiqian4b6829f2008-07-03 22:38:12 +00004688
4689 // Compares two std::wstrings that have different contents, one of
4690 // which having a NUL character in the middle.
4691 ::std::wstring wstr3(wstr1);
4692 wstr3.at(2) = L'\0';
4693 EXPECT_NONFATAL_FAILURE(EXPECT_EQ(wstr1, wstr3),
4694 "wstr3");
4695
4696 // Compares a wchar_t* to an std::wstring that has different
4697 // content.
4698 EXPECT_FATAL_FAILURE({ // NOLINT
4699 ASSERT_EQ(const_cast<wchar_t*>(L"foo"), ::std::wstring(L"bar"));
4700 }, "");
4701}
4702
4703#endif // GTEST_HAS_STD_WSTRING
4704
4705#if GTEST_HAS_GLOBAL_STRING
4706// Tests using ::string values in {EXPECT|ASSERT}_EQ.
4707TEST(EqAssertionTest, GlobalString) {
4708 // Compares a const char* to a ::string that has identical content.
4709 EXPECT_EQ("Test", ::string("Test"));
4710
4711 // Compares two identical ::strings.
4712 const ::string str1("A * in the middle");
4713 const ::string str2(str1);
4714 ASSERT_EQ(str1, str2);
4715
4716 // Compares a ::string to a const char* that has different content.
4717 EXPECT_NONFATAL_FAILURE(EXPECT_EQ(::string("Test"), "test"),
4718 "test");
4719
4720 // Compares two ::strings that have different contents, one of which
4721 // having a NUL character in the middle.
4722 ::string str3(str1);
4723 str3.at(2) = '\0';
4724 EXPECT_NONFATAL_FAILURE(EXPECT_EQ(str1, str3),
4725 "str3");
4726
4727 // Compares a ::string to a char* that has different content.
4728 EXPECT_FATAL_FAILURE({ // NOLINT
4729 ASSERT_EQ(::string("bar"), const_cast<char*>("foo"));
4730 }, "");
4731}
4732
4733#endif // GTEST_HAS_GLOBAL_STRING
4734
4735#if GTEST_HAS_GLOBAL_WSTRING
4736
4737// Tests using ::wstring values in {EXPECT|ASSERT}_EQ.
4738TEST(EqAssertionTest, GlobalWideString) {
shiqian4b6829f2008-07-03 22:38:12 +00004739 // Compares two identical ::wstrings.
4740 static const ::wstring wstr1(L"A * in the middle");
4741 static const ::wstring wstr2(wstr1);
4742 EXPECT_EQ(wstr1, wstr2);
4743
zhanyong.wanb499e7b2010-10-11 06:28:54 +00004744 // Compares a const wchar_t* to a ::wstring that has identical content.
4745 const wchar_t kTestX8119[] = { 'T', 'e', 's', 't', 0x8119, '\0' };
4746 ASSERT_EQ(kTestX8119, ::wstring(kTestX8119));
4747
shiqian4b6829f2008-07-03 22:38:12 +00004748 // Compares a const wchar_t* to a ::wstring that has different
4749 // content.
zhanyong.wanb499e7b2010-10-11 06:28:54 +00004750 const wchar_t kTestX8120[] = { 'T', 'e', 's', 't', 0x8120, '\0' };
shiqian4b6829f2008-07-03 22:38:12 +00004751 EXPECT_NONFATAL_FAILURE({ // NOLINT
zhanyong.wanb499e7b2010-10-11 06:28:54 +00004752 EXPECT_EQ(kTestX8120, ::wstring(kTestX8119));
shiqian4b6829f2008-07-03 22:38:12 +00004753 }, "Test\\x8119");
4754
4755 // Compares a wchar_t* to a ::wstring that has different content.
4756 wchar_t* const p1 = const_cast<wchar_t*>(L"foo");
4757 EXPECT_NONFATAL_FAILURE(EXPECT_EQ(p1, ::wstring(L"bar")),
4758 "bar");
4759
4760 // Compares two ::wstrings that have different contents, one of which
4761 // having a NUL character in the middle.
4762 static ::wstring wstr3;
4763 wstr3 = wstr1;
4764 wstr3.at(2) = L'\0';
4765 EXPECT_FATAL_FAILURE(ASSERT_EQ(wstr1, wstr3),
4766 "wstr3");
4767}
4768
4769#endif // GTEST_HAS_GLOBAL_WSTRING
4770
4771// Tests using char pointers in {EXPECT|ASSERT}_EQ.
4772TEST(EqAssertionTest, CharPointer) {
4773 char* const p0 = NULL;
4774 // Only way to get the Nokia compiler to compile the cast
4775 // is to have a separate void* variable first. Putting
4776 // the two casts on the same line doesn't work, neither does
4777 // a direct C-style to char*.
4778 void* pv1 = (void*)0x1234; // NOLINT
4779 void* pv2 = (void*)0xABC0; // NOLINT
4780 char* const p1 = reinterpret_cast<char*>(pv1);
4781 char* const p2 = reinterpret_cast<char*>(pv2);
4782 ASSERT_EQ(p1, p1);
4783
4784 EXPECT_NONFATAL_FAILURE(EXPECT_EQ(p0, p2),
4785 "Value of: p2");
4786 EXPECT_NONFATAL_FAILURE(EXPECT_EQ(p1, p2),
4787 "p2");
4788 EXPECT_FATAL_FAILURE(ASSERT_EQ(reinterpret_cast<char*>(0x1234),
4789 reinterpret_cast<char*>(0xABC0)),
4790 "ABC0");
4791}
4792
4793// Tests using wchar_t pointers in {EXPECT|ASSERT}_EQ.
4794TEST(EqAssertionTest, WideCharPointer) {
4795 wchar_t* const p0 = NULL;
4796 // Only way to get the Nokia compiler to compile the cast
4797 // is to have a separate void* variable first. Putting
4798 // the two casts on the same line doesn't work, neither does
4799 // a direct C-style to char*.
4800 void* pv1 = (void*)0x1234; // NOLINT
4801 void* pv2 = (void*)0xABC0; // NOLINT
4802 wchar_t* const p1 = reinterpret_cast<wchar_t*>(pv1);
4803 wchar_t* const p2 = reinterpret_cast<wchar_t*>(pv2);
4804 EXPECT_EQ(p0, p0);
4805
4806 EXPECT_NONFATAL_FAILURE(EXPECT_EQ(p0, p2),
4807 "Value of: p2");
4808 EXPECT_NONFATAL_FAILURE(EXPECT_EQ(p1, p2),
4809 "p2");
4810 void* pv3 = (void*)0x1234; // NOLINT
4811 void* pv4 = (void*)0xABC0; // NOLINT
4812 const wchar_t* p3 = reinterpret_cast<const wchar_t*>(pv3);
4813 const wchar_t* p4 = reinterpret_cast<const wchar_t*>(pv4);
4814 EXPECT_NONFATAL_FAILURE(EXPECT_EQ(p3, p4),
4815 "p4");
4816}
4817
4818// Tests using other types of pointers in {EXPECT|ASSERT}_EQ.
4819TEST(EqAssertionTest, OtherPointer) {
4820 ASSERT_EQ(static_cast<const int*>(NULL),
4821 static_cast<const int*>(NULL));
4822 EXPECT_FATAL_FAILURE(ASSERT_EQ(static_cast<const int*>(NULL),
4823 reinterpret_cast<const int*>(0x1234)),
4824 "0x1234");
4825}
4826
zhanyong.wan39dc95e2010-07-21 22:15:17 +00004827// A class that supports binary comparison operators but not streaming.
4828class UnprintableChar {
4829 public:
4830 explicit UnprintableChar(char ch) : char_(ch) {}
4831
4832 bool operator==(const UnprintableChar& rhs) const {
4833 return char_ == rhs.char_;
4834 }
4835 bool operator!=(const UnprintableChar& rhs) const {
4836 return char_ != rhs.char_;
4837 }
4838 bool operator<(const UnprintableChar& rhs) const {
4839 return char_ < rhs.char_;
4840 }
4841 bool operator<=(const UnprintableChar& rhs) const {
4842 return char_ <= rhs.char_;
4843 }
4844 bool operator>(const UnprintableChar& rhs) const {
4845 return char_ > rhs.char_;
4846 }
4847 bool operator>=(const UnprintableChar& rhs) const {
4848 return char_ >= rhs.char_;
4849 }
4850
4851 private:
4852 char char_;
4853};
4854
4855// Tests that ASSERT_EQ() and friends don't require the arguments to
4856// be printable.
4857TEST(ComparisonAssertionTest, AcceptsUnprintableArgs) {
4858 const UnprintableChar x('x'), y('y');
4859 ASSERT_EQ(x, x);
4860 EXPECT_NE(x, y);
4861 ASSERT_LT(x, y);
4862 EXPECT_LE(x, y);
4863 ASSERT_GT(y, x);
4864 EXPECT_GE(x, x);
4865
4866 EXPECT_NONFATAL_FAILURE(EXPECT_EQ(x, y), "1-byte object <78>");
4867 EXPECT_NONFATAL_FAILURE(EXPECT_EQ(x, y), "1-byte object <79>");
4868 EXPECT_NONFATAL_FAILURE(EXPECT_LT(y, y), "1-byte object <79>");
4869 EXPECT_NONFATAL_FAILURE(EXPECT_GT(x, y), "1-byte object <78>");
4870 EXPECT_NONFATAL_FAILURE(EXPECT_GT(x, y), "1-byte object <79>");
4871
4872 // Code tested by EXPECT_FATAL_FAILURE cannot reference local
4873 // variables, so we have to write UnprintableChar('x') instead of x.
zhanyong.waned1042b2011-03-05 08:04:01 +00004874#ifndef __BORLANDC__
4875 // ICE's in C++Builder.
zhanyong.wan39dc95e2010-07-21 22:15:17 +00004876 EXPECT_FATAL_FAILURE(ASSERT_NE(UnprintableChar('x'), UnprintableChar('x')),
4877 "1-byte object <78>");
4878 EXPECT_FATAL_FAILURE(ASSERT_LE(UnprintableChar('y'), UnprintableChar('x')),
4879 "1-byte object <78>");
zhanyong.waned1042b2011-03-05 08:04:01 +00004880#endif
zhanyong.wan39dc95e2010-07-21 22:15:17 +00004881 EXPECT_FATAL_FAILURE(ASSERT_LE(UnprintableChar('y'), UnprintableChar('x')),
4882 "1-byte object <79>");
4883 EXPECT_FATAL_FAILURE(ASSERT_GE(UnprintableChar('x'), UnprintableChar('y')),
4884 "1-byte object <78>");
4885 EXPECT_FATAL_FAILURE(ASSERT_GE(UnprintableChar('x'), UnprintableChar('y')),
4886 "1-byte object <79>");
4887}
4888
shiqian4b6829f2008-07-03 22:38:12 +00004889// Tests the FRIEND_TEST macro.
4890
4891// This class has a private member we want to test. We will test it
4892// both in a TEST and in a TEST_F.
4893class Foo {
4894 public:
4895 Foo() {}
4896
4897 private:
4898 int Bar() const { return 1; }
4899
4900 // Declares the friend tests that can access the private member
4901 // Bar().
4902 FRIEND_TEST(FRIEND_TEST_Test, TEST);
4903 FRIEND_TEST(FRIEND_TEST_Test2, TEST_F);
4904};
4905
4906// Tests that the FRIEND_TEST declaration allows a TEST to access a
4907// class's private members. This should compile.
4908TEST(FRIEND_TEST_Test, TEST) {
4909 ASSERT_EQ(1, Foo().Bar());
4910}
4911
4912// The fixture needed to test using FRIEND_TEST with TEST_F.
shiqian760af5c2008-08-06 21:43:15 +00004913class FRIEND_TEST_Test2 : public Test {
shiqian4b6829f2008-07-03 22:38:12 +00004914 protected:
4915 Foo foo;
4916};
4917
4918// Tests that the FRIEND_TEST declaration allows a TEST_F to access a
4919// class's private members. This should compile.
4920TEST_F(FRIEND_TEST_Test2, TEST_F) {
4921 ASSERT_EQ(1, foo.Bar());
4922}
4923
4924// Tests the life cycle of Test objects.
4925
4926// The test fixture for testing the life cycle of Test objects.
4927//
4928// This class counts the number of live test objects that uses this
4929// fixture.
shiqian760af5c2008-08-06 21:43:15 +00004930class TestLifeCycleTest : public Test {
shiqian4b6829f2008-07-03 22:38:12 +00004931 protected:
4932 // Constructor. Increments the number of test objects that uses
4933 // this fixture.
4934 TestLifeCycleTest() { count_++; }
4935
4936 // Destructor. Decrements the number of test objects that uses this
4937 // fixture.
4938 ~TestLifeCycleTest() { count_--; }
4939
4940 // Returns the number of live test objects that uses this fixture.
4941 int count() const { return count_; }
4942
4943 private:
4944 static int count_;
4945};
4946
4947int TestLifeCycleTest::count_ = 0;
4948
4949// Tests the life cycle of test objects.
4950TEST_F(TestLifeCycleTest, Test1) {
4951 // There should be only one test object in this test case that's
4952 // currently alive.
4953 ASSERT_EQ(1, count());
4954}
4955
4956// Tests the life cycle of test objects.
4957TEST_F(TestLifeCycleTest, Test2) {
4958 // After Test1 is done and Test2 is started, there should still be
4959 // only one live test object, as the object for Test1 should've been
4960 // deleted.
4961 ASSERT_EQ(1, count());
4962}
4963
4964} // namespace
4965
vladlosevfbd53a52009-10-20 21:03:10 +00004966// Tests that the copy constructor works when it is NOT optimized away by
4967// the compiler.
4968TEST(AssertionResultTest, CopyConstructorWorksWhenNotOptimied) {
4969 // Checks that the copy constructor doesn't try to dereference NULL pointers
4970 // in the source object.
4971 AssertionResult r1 = AssertionSuccess();
4972 AssertionResult r2 = r1;
4973 // The following line is added to prevent the compiler from optimizing
4974 // away the constructor call.
4975 r1 << "abc";
4976
4977 AssertionResult r3 = r1;
4978 EXPECT_EQ(static_cast<bool>(r3), static_cast<bool>(r1));
4979 EXPECT_STREQ("abc", r1.message());
4980}
4981
4982// Tests that AssertionSuccess and AssertionFailure construct
4983// AssertionResult objects as expected.
4984TEST(AssertionResultTest, ConstructionWorks) {
4985 AssertionResult r1 = AssertionSuccess();
4986 EXPECT_TRUE(r1);
4987 EXPECT_STREQ("", r1.message());
4988
4989 AssertionResult r2 = AssertionSuccess() << "abc";
4990 EXPECT_TRUE(r2);
4991 EXPECT_STREQ("abc", r2.message());
4992
4993 AssertionResult r3 = AssertionFailure();
4994 EXPECT_FALSE(r3);
4995 EXPECT_STREQ("", r3.message());
4996
4997 AssertionResult r4 = AssertionFailure() << "def";
4998 EXPECT_FALSE(r4);
4999 EXPECT_STREQ("def", r4.message());
5000
5001 AssertionResult r5 = AssertionFailure(Message() << "ghi");
5002 EXPECT_FALSE(r5);
5003 EXPECT_STREQ("ghi", r5.message());
5004}
5005
vladlosev12878402010-10-22 01:33:11 +00005006// Tests that the negation flips the predicate result but keeps the message.
vladlosevfbd53a52009-10-20 21:03:10 +00005007TEST(AssertionResultTest, NegationWorks) {
5008 AssertionResult r1 = AssertionSuccess() << "abc";
5009 EXPECT_FALSE(!r1);
5010 EXPECT_STREQ("abc", (!r1).message());
5011
5012 AssertionResult r2 = AssertionFailure() << "def";
5013 EXPECT_TRUE(!r2);
5014 EXPECT_STREQ("def", (!r2).message());
5015}
5016
5017TEST(AssertionResultTest, StreamingWorks) {
5018 AssertionResult r = AssertionSuccess();
5019 r << "abc" << 'd' << 0 << true;
5020 EXPECT_STREQ("abcd0true", r.message());
5021}
5022
vladlosev12878402010-10-22 01:33:11 +00005023TEST(AssertionResultTest, CanStreamOstreamManipulators) {
5024 AssertionResult r = AssertionSuccess();
5025 r << "Data" << std::endl << std::flush << std::ends << "Will be visible";
5026 EXPECT_STREQ("Data\n\\0Will be visible", r.message());
5027}
5028
shiqian4b6829f2008-07-03 22:38:12 +00005029// Tests streaming a user type whose definition and operator << are
5030// both in the global namespace.
5031class Base {
5032 public:
zhanyong.wan7de34012009-12-16 19:54:05 +00005033 explicit Base(int an_x) : x_(an_x) {}
shiqian4b6829f2008-07-03 22:38:12 +00005034 int x() const { return x_; }
5035 private:
5036 int x_;
5037};
5038std::ostream& operator<<(std::ostream& os,
5039 const Base& val) {
5040 return os << val.x();
5041}
5042std::ostream& operator<<(std::ostream& os,
5043 const Base* pointer) {
5044 return os << "(" << pointer->x() << ")";
5045}
5046
5047TEST(MessageTest, CanStreamUserTypeInGlobalNameSpace) {
shiqian760af5c2008-08-06 21:43:15 +00005048 Message msg;
shiqian4b6829f2008-07-03 22:38:12 +00005049 Base a(1);
5050
5051 msg << a << &a; // Uses ::operator<<.
5052 EXPECT_STREQ("1(1)", msg.GetString().c_str());
5053}
5054
5055// Tests streaming a user type whose definition and operator<< are
5056// both in an unnamed namespace.
5057namespace {
5058class MyTypeInUnnamedNameSpace : public Base {
5059 public:
zhanyong.wan7de34012009-12-16 19:54:05 +00005060 explicit MyTypeInUnnamedNameSpace(int an_x): Base(an_x) {}
shiqian4b6829f2008-07-03 22:38:12 +00005061};
5062std::ostream& operator<<(std::ostream& os,
5063 const MyTypeInUnnamedNameSpace& val) {
5064 return os << val.x();
5065}
5066std::ostream& operator<<(std::ostream& os,
5067 const MyTypeInUnnamedNameSpace* pointer) {
5068 return os << "(" << pointer->x() << ")";
5069}
5070} // namespace
5071
5072TEST(MessageTest, CanStreamUserTypeInUnnamedNameSpace) {
shiqian760af5c2008-08-06 21:43:15 +00005073 Message msg;
shiqian4b6829f2008-07-03 22:38:12 +00005074 MyTypeInUnnamedNameSpace a(1);
5075
5076 msg << a << &a; // Uses <unnamed_namespace>::operator<<.
5077 EXPECT_STREQ("1(1)", msg.GetString().c_str());
5078}
5079
5080// Tests streaming a user type whose definition and operator<< are
5081// both in a user namespace.
5082namespace namespace1 {
5083class MyTypeInNameSpace1 : public Base {
5084 public:
zhanyong.wan7de34012009-12-16 19:54:05 +00005085 explicit MyTypeInNameSpace1(int an_x): Base(an_x) {}
shiqian4b6829f2008-07-03 22:38:12 +00005086};
5087std::ostream& operator<<(std::ostream& os,
5088 const MyTypeInNameSpace1& val) {
5089 return os << val.x();
5090}
5091std::ostream& operator<<(std::ostream& os,
5092 const MyTypeInNameSpace1* pointer) {
5093 return os << "(" << pointer->x() << ")";
5094}
5095} // namespace namespace1
5096
5097TEST(MessageTest, CanStreamUserTypeInUserNameSpace) {
shiqian760af5c2008-08-06 21:43:15 +00005098 Message msg;
shiqian4b6829f2008-07-03 22:38:12 +00005099 namespace1::MyTypeInNameSpace1 a(1);
5100
5101 msg << a << &a; // Uses namespace1::operator<<.
5102 EXPECT_STREQ("1(1)", msg.GetString().c_str());
5103}
5104
5105// Tests streaming a user type whose definition is in a user namespace
5106// but whose operator<< is in the global namespace.
5107namespace namespace2 {
5108class MyTypeInNameSpace2 : public ::Base {
5109 public:
zhanyong.wan7de34012009-12-16 19:54:05 +00005110 explicit MyTypeInNameSpace2(int an_x): Base(an_x) {}
shiqian4b6829f2008-07-03 22:38:12 +00005111};
5112} // namespace namespace2
5113std::ostream& operator<<(std::ostream& os,
5114 const namespace2::MyTypeInNameSpace2& val) {
5115 return os << val.x();
5116}
5117std::ostream& operator<<(std::ostream& os,
5118 const namespace2::MyTypeInNameSpace2* pointer) {
5119 return os << "(" << pointer->x() << ")";
5120}
5121
5122TEST(MessageTest, CanStreamUserTypeInUserNameSpaceWithStreamOperatorInGlobal) {
shiqian760af5c2008-08-06 21:43:15 +00005123 Message msg;
shiqian4b6829f2008-07-03 22:38:12 +00005124 namespace2::MyTypeInNameSpace2 a(1);
5125
5126 msg << a << &a; // Uses ::operator<<.
5127 EXPECT_STREQ("1(1)", msg.GetString().c_str());
5128}
5129
5130// Tests streaming NULL pointers to testing::Message.
5131TEST(MessageTest, NullPointers) {
shiqian760af5c2008-08-06 21:43:15 +00005132 Message msg;
shiqian4b6829f2008-07-03 22:38:12 +00005133 char* const p1 = NULL;
5134 unsigned char* const p2 = NULL;
5135 int* p3 = NULL;
5136 double* p4 = NULL;
5137 bool* p5 = NULL;
shiqian760af5c2008-08-06 21:43:15 +00005138 Message* p6 = NULL;
shiqian4b6829f2008-07-03 22:38:12 +00005139
5140 msg << p1 << p2 << p3 << p4 << p5 << p6;
5141 ASSERT_STREQ("(null)(null)(null)(null)(null)(null)",
5142 msg.GetString().c_str());
5143}
5144
5145// Tests streaming wide strings to testing::Message.
5146TEST(MessageTest, WideStrings) {
shiqian4b6829f2008-07-03 22:38:12 +00005147 // Streams a NULL of type const wchar_t*.
5148 const wchar_t* const_wstr = NULL;
5149 EXPECT_STREQ("(null)",
5150 (Message() << const_wstr).GetString().c_str());
5151
5152 // Streams a NULL of type wchar_t*.
5153 wchar_t* wstr = NULL;
5154 EXPECT_STREQ("(null)",
5155 (Message() << wstr).GetString().c_str());
5156
5157 // Streams a non-NULL of type const wchar_t*.
5158 const_wstr = L"abc\x8119";
5159 EXPECT_STREQ("abc\xe8\x84\x99",
5160 (Message() << const_wstr).GetString().c_str());
5161
5162 // Streams a non-NULL of type wchar_t*.
5163 wstr = const_cast<wchar_t*>(const_wstr);
5164 EXPECT_STREQ("abc\xe8\x84\x99",
5165 (Message() << wstr).GetString().c_str());
5166}
5167
5168
5169// This line tests that we can define tests in the testing namespace.
5170namespace testing {
5171
5172// Tests the TestInfo class.
5173
shiqian760af5c2008-08-06 21:43:15 +00005174class TestInfoTest : public Test {
shiqian4b6829f2008-07-03 22:38:12 +00005175 protected:
zhanyong.wanb7ec0f72009-07-01 04:58:05 +00005176 static const TestInfo* GetTestInfo(const char* test_name) {
5177 const TestCase* const test_case = GetUnitTestImpl()->
5178 GetTestCase("TestInfoTest", "", NULL, NULL);
5179
5180 for (int i = 0; i < test_case->total_test_count(); ++i) {
5181 const TestInfo* const test_info = test_case->GetTestInfo(i);
5182 if (strcmp(test_name, test_info->name()) == 0)
5183 return test_info;
5184 }
5185 return NULL;
shiqian4b6829f2008-07-03 22:38:12 +00005186 }
5187
5188 static const TestResult* GetTestResult(
shiqian760af5c2008-08-06 21:43:15 +00005189 const TestInfo* test_info) {
shiqian4b6829f2008-07-03 22:38:12 +00005190 return test_info->result();
5191 }
5192};
5193
5194// Tests TestInfo::test_case_name() and TestInfo::name().
5195TEST_F(TestInfoTest, Names) {
zhanyong.wanb7ec0f72009-07-01 04:58:05 +00005196 const TestInfo* const test_info = GetTestInfo("Names");
shiqian4b6829f2008-07-03 22:38:12 +00005197
5198 ASSERT_STREQ("TestInfoTest", test_info->test_case_name());
5199 ASSERT_STREQ("Names", test_info->name());
5200}
5201
5202// Tests TestInfo::result().
5203TEST_F(TestInfoTest, result) {
zhanyong.wanb7ec0f72009-07-01 04:58:05 +00005204 const TestInfo* const test_info = GetTestInfo("result");
shiqian4b6829f2008-07-03 22:38:12 +00005205
5206 // Initially, there is no TestPartResult for this test.
zhanyong.wanb7ec0f72009-07-01 04:58:05 +00005207 ASSERT_EQ(0, GetTestResult(test_info)->total_part_count());
shiqian4b6829f2008-07-03 22:38:12 +00005208
5209 // After the previous assertion, there is still none.
zhanyong.wanb7ec0f72009-07-01 04:58:05 +00005210 ASSERT_EQ(0, GetTestResult(test_info)->total_part_count());
shiqian4b6829f2008-07-03 22:38:12 +00005211}
5212
5213// Tests setting up and tearing down a test case.
5214
shiqian760af5c2008-08-06 21:43:15 +00005215class SetUpTestCaseTest : public Test {
shiqian4b6829f2008-07-03 22:38:12 +00005216 protected:
5217 // This will be called once before the first test in this test case
5218 // is run.
5219 static void SetUpTestCase() {
5220 printf("Setting up the test case . . .\n");
5221
5222 // Initializes some shared resource. In this simple example, we
5223 // just create a C string. More complex stuff can be done if
5224 // desired.
5225 shared_resource_ = "123";
5226
5227 // Increments the number of test cases that have been set up.
5228 counter_++;
5229
5230 // SetUpTestCase() should be called only once.
5231 EXPECT_EQ(1, counter_);
5232 }
5233
5234 // This will be called once after the last test in this test case is
5235 // run.
5236 static void TearDownTestCase() {
5237 printf("Tearing down the test case . . .\n");
5238
5239 // Decrements the number of test cases that have been set up.
5240 counter_--;
5241
5242 // TearDownTestCase() should be called only once.
5243 EXPECT_EQ(0, counter_);
5244
5245 // Cleans up the shared resource.
5246 shared_resource_ = NULL;
5247 }
5248
5249 // This will be called before each test in this test case.
5250 virtual void SetUp() {
5251 // SetUpTestCase() should be called only once, so counter_ should
5252 // always be 1.
5253 EXPECT_EQ(1, counter_);
5254 }
5255
5256 // Number of test cases that have been set up.
5257 static int counter_;
5258
5259 // Some resource to be shared by all tests in this test case.
5260 static const char* shared_resource_;
5261};
5262
5263int SetUpTestCaseTest::counter_ = 0;
5264const char* SetUpTestCaseTest::shared_resource_ = NULL;
5265
5266// A test that uses the shared resource.
5267TEST_F(SetUpTestCaseTest, Test1) {
5268 EXPECT_STRNE(NULL, shared_resource_);
5269}
5270
5271// Another test that uses the shared resource.
5272TEST_F(SetUpTestCaseTest, Test2) {
5273 EXPECT_STREQ("123", shared_resource_);
5274}
5275
5276// The InitGoogleTestTest test case tests testing::InitGoogleTest().
5277
5278// The Flags struct stores a copy of all Google Test flags.
5279struct Flags {
5280 // Constructs a Flags struct where each flag has its default value.
shiqianca6949f2009-01-10 01:16:33 +00005281 Flags() : also_run_disabled_tests(false),
5282 break_on_failure(false),
shiqian4b6829f2008-07-03 22:38:12 +00005283 catch_exceptions(false),
shiqian21d43d12009-01-08 01:10:31 +00005284 death_test_use_fork(false),
shiqian4b6829f2008-07-03 22:38:12 +00005285 filter(""),
5286 list_tests(false),
5287 output(""),
zhanyong.wan73ad5a32009-04-14 23:19:22 +00005288 print_time(true),
zhanyong.wan9b9794f2009-07-14 22:56:46 +00005289 random_seed(0),
zhanyong.wanb0fe69f2009-03-06 20:05:23 +00005290 repeat(1),
zhanyong.wan9b9794f2009-07-14 22:56:46 +00005291 shuffle(false),
vladlosevba015a92009-11-17 22:43:15 +00005292 stack_trace_depth(kMaxStackTraceDepth),
zhanyong.wanc95489e2010-08-19 22:16:00 +00005293 stream_result_to(""),
zhanyong.wanb0fe69f2009-03-06 20:05:23 +00005294 throw_on_failure(false) {}
shiqian4b6829f2008-07-03 22:38:12 +00005295
5296 // Factory methods.
5297
shiqianca6949f2009-01-10 01:16:33 +00005298 // Creates a Flags struct where the gtest_also_run_disabled_tests flag has
5299 // the given value.
5300 static Flags AlsoRunDisabledTests(bool also_run_disabled_tests) {
5301 Flags flags;
5302 flags.also_run_disabled_tests = also_run_disabled_tests;
5303 return flags;
5304 }
5305
shiqian4b6829f2008-07-03 22:38:12 +00005306 // Creates a Flags struct where the gtest_break_on_failure flag has
5307 // the given value.
5308 static Flags BreakOnFailure(bool break_on_failure) {
5309 Flags flags;
5310 flags.break_on_failure = break_on_failure;
5311 return flags;
5312 }
5313
5314 // Creates a Flags struct where the gtest_catch_exceptions flag has
5315 // the given value.
5316 static Flags CatchExceptions(bool catch_exceptions) {
5317 Flags flags;
5318 flags.catch_exceptions = catch_exceptions;
5319 return flags;
5320 }
5321
shiqian21d43d12009-01-08 01:10:31 +00005322 // Creates a Flags struct where the gtest_death_test_use_fork flag has
5323 // the given value.
5324 static Flags DeathTestUseFork(bool death_test_use_fork) {
5325 Flags flags;
5326 flags.death_test_use_fork = death_test_use_fork;
5327 return flags;
5328 }
5329
shiqian4b6829f2008-07-03 22:38:12 +00005330 // Creates a Flags struct where the gtest_filter flag has the given
5331 // value.
5332 static Flags Filter(const char* filter) {
5333 Flags flags;
5334 flags.filter = filter;
5335 return flags;
5336 }
5337
5338 // Creates a Flags struct where the gtest_list_tests flag has the
5339 // given value.
5340 static Flags ListTests(bool list_tests) {
5341 Flags flags;
5342 flags.list_tests = list_tests;
5343 return flags;
5344 }
5345
5346 // Creates a Flags struct where the gtest_output flag has the given
5347 // value.
5348 static Flags Output(const char* output) {
5349 Flags flags;
5350 flags.output = output;
5351 return flags;
5352 }
5353
shiqiand981cee2008-07-25 04:06:16 +00005354 // Creates a Flags struct where the gtest_print_time flag has the given
5355 // value.
5356 static Flags PrintTime(bool print_time) {
5357 Flags flags;
5358 flags.print_time = print_time;
5359 return flags;
5360 }
5361
zhanyong.wan9b9794f2009-07-14 22:56:46 +00005362 // Creates a Flags struct where the gtest_random_seed flag has
5363 // the given value.
5364 static Flags RandomSeed(Int32 random_seed) {
5365 Flags flags;
5366 flags.random_seed = random_seed;
5367 return flags;
5368 }
5369
shiqian4b6829f2008-07-03 22:38:12 +00005370 // Creates a Flags struct where the gtest_repeat flag has the given
5371 // value.
5372 static Flags Repeat(Int32 repeat) {
5373 Flags flags;
5374 flags.repeat = repeat;
5375 return flags;
5376 }
5377
zhanyong.wan9b9794f2009-07-14 22:56:46 +00005378 // Creates a Flags struct where the gtest_shuffle flag has
5379 // the given value.
5380 static Flags Shuffle(bool shuffle) {
5381 Flags flags;
5382 flags.shuffle = shuffle;
5383 return flags;
5384 }
5385
vladlosevba015a92009-11-17 22:43:15 +00005386 // Creates a Flags struct where the GTEST_FLAG(stack_trace_depth) flag has
5387 // the given value.
5388 static Flags StackTraceDepth(Int32 stack_trace_depth) {
5389 Flags flags;
5390 flags.stack_trace_depth = stack_trace_depth;
5391 return flags;
5392 }
5393
zhanyong.wanc95489e2010-08-19 22:16:00 +00005394 // Creates a Flags struct where the GTEST_FLAG(stream_result_to) flag has
5395 // the given value.
5396 static Flags StreamResultTo(const char* stream_result_to) {
5397 Flags flags;
5398 flags.stream_result_to = stream_result_to;
5399 return flags;
5400 }
5401
zhanyong.wanb0fe69f2009-03-06 20:05:23 +00005402 // Creates a Flags struct where the gtest_throw_on_failure flag has
5403 // the given value.
5404 static Flags ThrowOnFailure(bool throw_on_failure) {
5405 Flags flags;
5406 flags.throw_on_failure = throw_on_failure;
5407 return flags;
5408 }
5409
shiqian4b6829f2008-07-03 22:38:12 +00005410 // These fields store the flag values.
shiqianca6949f2009-01-10 01:16:33 +00005411 bool also_run_disabled_tests;
shiqian4b6829f2008-07-03 22:38:12 +00005412 bool break_on_failure;
5413 bool catch_exceptions;
shiqian21d43d12009-01-08 01:10:31 +00005414 bool death_test_use_fork;
shiqian4b6829f2008-07-03 22:38:12 +00005415 const char* filter;
5416 bool list_tests;
5417 const char* output;
shiqiand981cee2008-07-25 04:06:16 +00005418 bool print_time;
zhanyong.wan9b9794f2009-07-14 22:56:46 +00005419 Int32 random_seed;
shiqian4b6829f2008-07-03 22:38:12 +00005420 Int32 repeat;
zhanyong.wan9b9794f2009-07-14 22:56:46 +00005421 bool shuffle;
vladlosevba015a92009-11-17 22:43:15 +00005422 Int32 stack_trace_depth;
zhanyong.wanc95489e2010-08-19 22:16:00 +00005423 const char* stream_result_to;
zhanyong.wanb0fe69f2009-03-06 20:05:23 +00005424 bool throw_on_failure;
shiqian4b6829f2008-07-03 22:38:12 +00005425};
5426
5427// Fixture for testing InitGoogleTest().
shiqian760af5c2008-08-06 21:43:15 +00005428class InitGoogleTestTest : public Test {
shiqian4b6829f2008-07-03 22:38:12 +00005429 protected:
5430 // Clears the flags before each test.
5431 virtual void SetUp() {
shiqianca6949f2009-01-10 01:16:33 +00005432 GTEST_FLAG(also_run_disabled_tests) = false;
shiqian4b6829f2008-07-03 22:38:12 +00005433 GTEST_FLAG(break_on_failure) = false;
5434 GTEST_FLAG(catch_exceptions) = false;
shiqian21d43d12009-01-08 01:10:31 +00005435 GTEST_FLAG(death_test_use_fork) = false;
shiqian4b6829f2008-07-03 22:38:12 +00005436 GTEST_FLAG(filter) = "";
5437 GTEST_FLAG(list_tests) = false;
5438 GTEST_FLAG(output) = "";
zhanyong.wan73ad5a32009-04-14 23:19:22 +00005439 GTEST_FLAG(print_time) = true;
zhanyong.wan9b9794f2009-07-14 22:56:46 +00005440 GTEST_FLAG(random_seed) = 0;
shiqian4b6829f2008-07-03 22:38:12 +00005441 GTEST_FLAG(repeat) = 1;
zhanyong.wan9b9794f2009-07-14 22:56:46 +00005442 GTEST_FLAG(shuffle) = false;
vladlosevba015a92009-11-17 22:43:15 +00005443 GTEST_FLAG(stack_trace_depth) = kMaxStackTraceDepth;
zhanyong.wanc95489e2010-08-19 22:16:00 +00005444 GTEST_FLAG(stream_result_to) = "";
zhanyong.wanb0fe69f2009-03-06 20:05:23 +00005445 GTEST_FLAG(throw_on_failure) = false;
shiqian4b6829f2008-07-03 22:38:12 +00005446 }
5447
5448 // Asserts that two narrow or wide string arrays are equal.
5449 template <typename CharType>
5450 static void AssertStringArrayEq(size_t size1, CharType** array1,
5451 size_t size2, CharType** array2) {
5452 ASSERT_EQ(size1, size2) << " Array sizes different.";
5453
5454 for (size_t i = 0; i != size1; i++) {
5455 ASSERT_STREQ(array1[i], array2[i]) << " where i == " << i;
5456 }
5457 }
5458
5459 // Verifies that the flag values match the expected values.
5460 static void CheckFlags(const Flags& expected) {
shiqianca6949f2009-01-10 01:16:33 +00005461 EXPECT_EQ(expected.also_run_disabled_tests,
5462 GTEST_FLAG(also_run_disabled_tests));
shiqian4b6829f2008-07-03 22:38:12 +00005463 EXPECT_EQ(expected.break_on_failure, GTEST_FLAG(break_on_failure));
5464 EXPECT_EQ(expected.catch_exceptions, GTEST_FLAG(catch_exceptions));
shiqian21d43d12009-01-08 01:10:31 +00005465 EXPECT_EQ(expected.death_test_use_fork, GTEST_FLAG(death_test_use_fork));
shiqian4b6829f2008-07-03 22:38:12 +00005466 EXPECT_STREQ(expected.filter, GTEST_FLAG(filter).c_str());
5467 EXPECT_EQ(expected.list_tests, GTEST_FLAG(list_tests));
5468 EXPECT_STREQ(expected.output, GTEST_FLAG(output).c_str());
shiqiand981cee2008-07-25 04:06:16 +00005469 EXPECT_EQ(expected.print_time, GTEST_FLAG(print_time));
zhanyong.wan9b9794f2009-07-14 22:56:46 +00005470 EXPECT_EQ(expected.random_seed, GTEST_FLAG(random_seed));
shiqian4b6829f2008-07-03 22:38:12 +00005471 EXPECT_EQ(expected.repeat, GTEST_FLAG(repeat));
zhanyong.wan9b9794f2009-07-14 22:56:46 +00005472 EXPECT_EQ(expected.shuffle, GTEST_FLAG(shuffle));
vladlosevba015a92009-11-17 22:43:15 +00005473 EXPECT_EQ(expected.stack_trace_depth, GTEST_FLAG(stack_trace_depth));
zhanyong.wanc95489e2010-08-19 22:16:00 +00005474 EXPECT_STREQ(expected.stream_result_to,
5475 GTEST_FLAG(stream_result_to).c_str());
5476 EXPECT_EQ(expected.throw_on_failure, GTEST_FLAG(throw_on_failure));
shiqian4b6829f2008-07-03 22:38:12 +00005477 }
5478
5479 // Parses a command line (specified by argc1 and argv1), then
5480 // verifies that the flag values are expected and that the
5481 // recognized flags are removed from the command line.
5482 template <typename CharType>
5483 static void TestParsingFlags(int argc1, const CharType** argv1,
5484 int argc2, const CharType** argv2,
vladlosevba015a92009-11-17 22:43:15 +00005485 const Flags& expected, bool should_print_help) {
5486 const bool saved_help_flag = ::testing::internal::g_help_flag;
5487 ::testing::internal::g_help_flag = false;
5488
zhanyong.wan5d0c3dc2010-08-31 18:21:13 +00005489#if GTEST_HAS_STREAM_REDIRECTION
zhanyong.wancf8a5842010-01-28 21:50:29 +00005490 CaptureStdout();
zhanyong.wan5d0c3dc2010-08-31 18:21:13 +00005491#endif
zhanyong.wancf8a5842010-01-28 21:50:29 +00005492
shiqian4b6829f2008-07-03 22:38:12 +00005493 // Parses the command line.
vladlosevf179f4e2008-11-26 20:48:45 +00005494 internal::ParseGoogleTestFlagsOnly(&argc1, const_cast<CharType**>(argv1));
shiqian4b6829f2008-07-03 22:38:12 +00005495
zhanyong.wan5d0c3dc2010-08-31 18:21:13 +00005496#if GTEST_HAS_STREAM_REDIRECTION
jgm@google.com03c31492012-11-15 15:47:38 +00005497 const std::string captured_stdout = GetCapturedStdout();
zhanyong.wan5d0c3dc2010-08-31 18:21:13 +00005498#endif
zhanyong.wancf8a5842010-01-28 21:50:29 +00005499
shiqian4b6829f2008-07-03 22:38:12 +00005500 // Verifies the flag values.
5501 CheckFlags(expected);
5502
5503 // Verifies that the recognized flags are removed from the command
5504 // line.
5505 AssertStringArrayEq(argc1 + 1, argv1, argc2 + 1, argv2);
vladlosevba015a92009-11-17 22:43:15 +00005506
5507 // ParseGoogleTestFlagsOnly should neither set g_help_flag nor print the
5508 // help message for the flags it recognizes.
5509 EXPECT_EQ(should_print_help, ::testing::internal::g_help_flag);
5510
zhanyong.wan5d0c3dc2010-08-31 18:21:13 +00005511#if GTEST_HAS_STREAM_REDIRECTION
zhanyong.wancf8a5842010-01-28 21:50:29 +00005512 const char* const expected_help_fragment =
5513 "This program contains tests written using";
5514 if (should_print_help) {
5515 EXPECT_PRED_FORMAT2(IsSubstring, expected_help_fragment, captured_stdout);
5516 } else {
5517 EXPECT_PRED_FORMAT2(IsNotSubstring,
5518 expected_help_fragment, captured_stdout);
5519 }
zhanyong.wan5d0c3dc2010-08-31 18:21:13 +00005520#endif // GTEST_HAS_STREAM_REDIRECTION
vladlosevba015a92009-11-17 22:43:15 +00005521
5522 ::testing::internal::g_help_flag = saved_help_flag;
shiqian4b6829f2008-07-03 22:38:12 +00005523 }
5524
5525 // This macro wraps TestParsingFlags s.t. the user doesn't need
5526 // to specify the array sizes.
zhanyong.wan733a54a2011-02-22 22:08:59 +00005527
vladlosevba015a92009-11-17 22:43:15 +00005528#define GTEST_TEST_PARSING_FLAGS_(argv1, argv2, expected, should_print_help) \
shiqian4b6829f2008-07-03 22:38:12 +00005529 TestParsingFlags(sizeof(argv1)/sizeof(*argv1) - 1, argv1, \
vladlosevba015a92009-11-17 22:43:15 +00005530 sizeof(argv2)/sizeof(*argv2) - 1, argv2, \
5531 expected, should_print_help)
shiqian4b6829f2008-07-03 22:38:12 +00005532};
5533
5534// Tests parsing an empty command line.
5535TEST_F(InitGoogleTestTest, Empty) {
5536 const char* argv[] = {
5537 NULL
5538 };
5539
5540 const char* argv2[] = {
5541 NULL
5542 };
5543
vladlosevba015a92009-11-17 22:43:15 +00005544 GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags(), false);
shiqian4b6829f2008-07-03 22:38:12 +00005545}
5546
5547// Tests parsing a command line that has no flag.
5548TEST_F(InitGoogleTestTest, NoFlag) {
5549 const char* argv[] = {
5550 "foo.exe",
5551 NULL
5552 };
5553
5554 const char* argv2[] = {
5555 "foo.exe",
5556 NULL
5557 };
5558
vladlosevba015a92009-11-17 22:43:15 +00005559 GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags(), false);
shiqian4b6829f2008-07-03 22:38:12 +00005560}
5561
5562// Tests parsing a bad --gtest_filter flag.
5563TEST_F(InitGoogleTestTest, FilterBad) {
5564 const char* argv[] = {
5565 "foo.exe",
5566 "--gtest_filter",
5567 NULL
5568 };
5569
5570 const char* argv2[] = {
5571 "foo.exe",
5572 "--gtest_filter",
5573 NULL
5574 };
5575
vladlosevba015a92009-11-17 22:43:15 +00005576 GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::Filter(""), true);
shiqian4b6829f2008-07-03 22:38:12 +00005577}
5578
5579// Tests parsing an empty --gtest_filter flag.
5580TEST_F(InitGoogleTestTest, FilterEmpty) {
5581 const char* argv[] = {
5582 "foo.exe",
5583 "--gtest_filter=",
5584 NULL
5585 };
5586
5587 const char* argv2[] = {
5588 "foo.exe",
5589 NULL
5590 };
5591
vladlosevba015a92009-11-17 22:43:15 +00005592 GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::Filter(""), false);
shiqian4b6829f2008-07-03 22:38:12 +00005593}
5594
5595// Tests parsing a non-empty --gtest_filter flag.
5596TEST_F(InitGoogleTestTest, FilterNonEmpty) {
5597 const char* argv[] = {
5598 "foo.exe",
5599 "--gtest_filter=abc",
5600 NULL
5601 };
5602
5603 const char* argv2[] = {
5604 "foo.exe",
5605 NULL
5606 };
5607
vladlosevba015a92009-11-17 22:43:15 +00005608 GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::Filter("abc"), false);
shiqian4b6829f2008-07-03 22:38:12 +00005609}
5610
5611// Tests parsing --gtest_break_on_failure.
zhanyong.wan9b9794f2009-07-14 22:56:46 +00005612TEST_F(InitGoogleTestTest, BreakOnFailureWithoutValue) {
shiqian4b6829f2008-07-03 22:38:12 +00005613 const char* argv[] = {
5614 "foo.exe",
5615 "--gtest_break_on_failure",
5616 NULL
5617};
5618
5619 const char* argv2[] = {
5620 "foo.exe",
5621 NULL
5622 };
5623
vladlosevba015a92009-11-17 22:43:15 +00005624 GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::BreakOnFailure(true), false);
shiqian4b6829f2008-07-03 22:38:12 +00005625}
5626
5627// Tests parsing --gtest_break_on_failure=0.
5628TEST_F(InitGoogleTestTest, BreakOnFailureFalse_0) {
5629 const char* argv[] = {
5630 "foo.exe",
5631 "--gtest_break_on_failure=0",
5632 NULL
5633 };
5634
5635 const char* argv2[] = {
5636 "foo.exe",
5637 NULL
5638 };
5639
vladlosevba015a92009-11-17 22:43:15 +00005640 GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::BreakOnFailure(false), false);
shiqian4b6829f2008-07-03 22:38:12 +00005641}
5642
5643// Tests parsing --gtest_break_on_failure=f.
5644TEST_F(InitGoogleTestTest, BreakOnFailureFalse_f) {
5645 const char* argv[] = {
5646 "foo.exe",
5647 "--gtest_break_on_failure=f",
5648 NULL
5649 };
5650
5651 const char* argv2[] = {
5652 "foo.exe",
5653 NULL
5654 };
5655
vladlosevba015a92009-11-17 22:43:15 +00005656 GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::BreakOnFailure(false), false);
shiqian4b6829f2008-07-03 22:38:12 +00005657}
5658
5659// Tests parsing --gtest_break_on_failure=F.
5660TEST_F(InitGoogleTestTest, BreakOnFailureFalse_F) {
5661 const char* argv[] = {
5662 "foo.exe",
5663 "--gtest_break_on_failure=F",
5664 NULL
5665 };
5666
5667 const char* argv2[] = {
5668 "foo.exe",
5669 NULL
5670 };
5671
vladlosevba015a92009-11-17 22:43:15 +00005672 GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::BreakOnFailure(false), false);
shiqian4b6829f2008-07-03 22:38:12 +00005673}
5674
5675// Tests parsing a --gtest_break_on_failure flag that has a "true"
5676// definition.
5677TEST_F(InitGoogleTestTest, BreakOnFailureTrue) {
5678 const char* argv[] = {
5679 "foo.exe",
5680 "--gtest_break_on_failure=1",
5681 NULL
5682 };
5683
5684 const char* argv2[] = {
5685 "foo.exe",
5686 NULL
5687 };
5688
vladlosevba015a92009-11-17 22:43:15 +00005689 GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::BreakOnFailure(true), false);
shiqian4b6829f2008-07-03 22:38:12 +00005690}
5691
5692// Tests parsing --gtest_catch_exceptions.
5693TEST_F(InitGoogleTestTest, CatchExceptions) {
5694 const char* argv[] = {
5695 "foo.exe",
5696 "--gtest_catch_exceptions",
5697 NULL
5698 };
5699
5700 const char* argv2[] = {
5701 "foo.exe",
5702 NULL
5703 };
5704
vladlosevba015a92009-11-17 22:43:15 +00005705 GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::CatchExceptions(true), false);
shiqian4b6829f2008-07-03 22:38:12 +00005706}
5707
shiqian21d43d12009-01-08 01:10:31 +00005708// Tests parsing --gtest_death_test_use_fork.
5709TEST_F(InitGoogleTestTest, DeathTestUseFork) {
5710 const char* argv[] = {
5711 "foo.exe",
5712 "--gtest_death_test_use_fork",
5713 NULL
5714 };
5715
5716 const char* argv2[] = {
5717 "foo.exe",
5718 NULL
5719 };
5720
vladlosevba015a92009-11-17 22:43:15 +00005721 GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::DeathTestUseFork(true), false);
shiqian21d43d12009-01-08 01:10:31 +00005722}
5723
shiqian4b6829f2008-07-03 22:38:12 +00005724// Tests having the same flag twice with different values. The
5725// expected behavior is that the one coming last takes precedence.
5726TEST_F(InitGoogleTestTest, DuplicatedFlags) {
5727 const char* argv[] = {
5728 "foo.exe",
5729 "--gtest_filter=a",
5730 "--gtest_filter=b",
5731 NULL
5732 };
5733
5734 const char* argv2[] = {
5735 "foo.exe",
5736 NULL
5737 };
5738
vladlosevba015a92009-11-17 22:43:15 +00005739 GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::Filter("b"), false);
shiqian4b6829f2008-07-03 22:38:12 +00005740}
5741
5742// Tests having an unrecognized flag on the command line.
5743TEST_F(InitGoogleTestTest, UnrecognizedFlag) {
5744 const char* argv[] = {
5745 "foo.exe",
5746 "--gtest_break_on_failure",
5747 "bar", // Unrecognized by Google Test.
5748 "--gtest_filter=b",
5749 NULL
5750 };
5751
5752 const char* argv2[] = {
5753 "foo.exe",
5754 "bar",
5755 NULL
5756 };
5757
5758 Flags flags;
5759 flags.break_on_failure = true;
5760 flags.filter = "b";
vladlosevba015a92009-11-17 22:43:15 +00005761 GTEST_TEST_PARSING_FLAGS_(argv, argv2, flags, false);
shiqian4b6829f2008-07-03 22:38:12 +00005762}
5763
5764// Tests having a --gtest_list_tests flag
5765TEST_F(InitGoogleTestTest, ListTestsFlag) {
5766 const char* argv[] = {
5767 "foo.exe",
5768 "--gtest_list_tests",
5769 NULL
5770 };
5771
5772 const char* argv2[] = {
5773 "foo.exe",
5774 NULL
5775 };
5776
vladlosevba015a92009-11-17 22:43:15 +00005777 GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::ListTests(true), false);
shiqian4b6829f2008-07-03 22:38:12 +00005778}
5779
5780// Tests having a --gtest_list_tests flag with a "true" value
5781TEST_F(InitGoogleTestTest, ListTestsTrue) {
5782 const char* argv[] = {
5783 "foo.exe",
5784 "--gtest_list_tests=1",
5785 NULL
5786 };
5787
5788 const char* argv2[] = {
5789 "foo.exe",
5790 NULL
5791 };
5792
vladlosevba015a92009-11-17 22:43:15 +00005793 GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::ListTests(true), false);
shiqian4b6829f2008-07-03 22:38:12 +00005794}
5795
5796// Tests having a --gtest_list_tests flag with a "false" value
5797TEST_F(InitGoogleTestTest, ListTestsFalse) {
5798 const char* argv[] = {
5799 "foo.exe",
5800 "--gtest_list_tests=0",
5801 NULL
5802 };
5803
5804 const char* argv2[] = {
5805 "foo.exe",
5806 NULL
5807 };
5808
vladlosevba015a92009-11-17 22:43:15 +00005809 GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::ListTests(false), false);
shiqian4b6829f2008-07-03 22:38:12 +00005810}
5811
5812// Tests parsing --gtest_list_tests=f.
5813TEST_F(InitGoogleTestTest, ListTestsFalse_f) {
5814 const char* argv[] = {
5815 "foo.exe",
5816 "--gtest_list_tests=f",
5817 NULL
5818 };
5819
5820 const char* argv2[] = {
5821 "foo.exe",
5822 NULL
5823 };
5824
vladlosevba015a92009-11-17 22:43:15 +00005825 GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::ListTests(false), false);
shiqian4b6829f2008-07-03 22:38:12 +00005826}
5827
zhanyong.wan9b9794f2009-07-14 22:56:46 +00005828// Tests parsing --gtest_list_tests=F.
shiqian4b6829f2008-07-03 22:38:12 +00005829TEST_F(InitGoogleTestTest, ListTestsFalse_F) {
5830 const char* argv[] = {
5831 "foo.exe",
5832 "--gtest_list_tests=F",
5833 NULL
5834 };
5835
5836 const char* argv2[] = {
5837 "foo.exe",
5838 NULL
5839 };
5840
vladlosevba015a92009-11-17 22:43:15 +00005841 GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::ListTests(false), false);
shiqian4b6829f2008-07-03 22:38:12 +00005842}
5843
5844// Tests parsing --gtest_output (invalid).
5845TEST_F(InitGoogleTestTest, OutputEmpty) {
5846 const char* argv[] = {
5847 "foo.exe",
5848 "--gtest_output",
5849 NULL
5850 };
5851
5852 const char* argv2[] = {
5853 "foo.exe",
5854 "--gtest_output",
5855 NULL
5856 };
5857
vladlosevba015a92009-11-17 22:43:15 +00005858 GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags(), true);
shiqian4b6829f2008-07-03 22:38:12 +00005859}
5860
5861// Tests parsing --gtest_output=xml
5862TEST_F(InitGoogleTestTest, OutputXml) {
5863 const char* argv[] = {
5864 "foo.exe",
5865 "--gtest_output=xml",
5866 NULL
5867 };
5868
5869 const char* argv2[] = {
5870 "foo.exe",
5871 NULL
5872 };
5873
vladlosevba015a92009-11-17 22:43:15 +00005874 GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::Output("xml"), false);
shiqian4b6829f2008-07-03 22:38:12 +00005875}
5876
5877// Tests parsing --gtest_output=xml:file
5878TEST_F(InitGoogleTestTest, OutputXmlFile) {
5879 const char* argv[] = {
5880 "foo.exe",
5881 "--gtest_output=xml:file",
5882 NULL
5883 };
5884
5885 const char* argv2[] = {
5886 "foo.exe",
5887 NULL
5888 };
5889
vladlosevba015a92009-11-17 22:43:15 +00005890 GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::Output("xml:file"), false);
shiqian4b6829f2008-07-03 22:38:12 +00005891}
5892
5893// Tests parsing --gtest_output=xml:directory/path/
5894TEST_F(InitGoogleTestTest, OutputXmlDirectory) {
5895 const char* argv[] = {
5896 "foo.exe",
5897 "--gtest_output=xml:directory/path/",
5898 NULL
5899 };
5900
5901 const char* argv2[] = {
5902 "foo.exe",
5903 NULL
5904 };
5905
vladlosevba015a92009-11-17 22:43:15 +00005906 GTEST_TEST_PARSING_FLAGS_(argv, argv2,
5907 Flags::Output("xml:directory/path/"), false);
shiqian4b6829f2008-07-03 22:38:12 +00005908}
5909
shiqiand981cee2008-07-25 04:06:16 +00005910// Tests having a --gtest_print_time flag
5911TEST_F(InitGoogleTestTest, PrintTimeFlag) {
5912 const char* argv[] = {
5913 "foo.exe",
5914 "--gtest_print_time",
5915 NULL
5916 };
5917
5918 const char* argv2[] = {
5919 "foo.exe",
5920 NULL
5921 };
5922
vladlosevba015a92009-11-17 22:43:15 +00005923 GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::PrintTime(true), false);
shiqiand981cee2008-07-25 04:06:16 +00005924}
5925
5926// Tests having a --gtest_print_time flag with a "true" value
5927TEST_F(InitGoogleTestTest, PrintTimeTrue) {
5928 const char* argv[] = {
5929 "foo.exe",
5930 "--gtest_print_time=1",
5931 NULL
5932 };
5933
5934 const char* argv2[] = {
5935 "foo.exe",
5936 NULL
5937 };
5938
vladlosevba015a92009-11-17 22:43:15 +00005939 GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::PrintTime(true), false);
shiqiand981cee2008-07-25 04:06:16 +00005940}
5941
5942// Tests having a --gtest_print_time flag with a "false" value
5943TEST_F(InitGoogleTestTest, PrintTimeFalse) {
5944 const char* argv[] = {
5945 "foo.exe",
5946 "--gtest_print_time=0",
5947 NULL
5948 };
5949
5950 const char* argv2[] = {
5951 "foo.exe",
5952 NULL
5953 };
5954
vladlosevba015a92009-11-17 22:43:15 +00005955 GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::PrintTime(false), false);
shiqiand981cee2008-07-25 04:06:16 +00005956}
5957
5958// Tests parsing --gtest_print_time=f.
5959TEST_F(InitGoogleTestTest, PrintTimeFalse_f) {
5960 const char* argv[] = {
5961 "foo.exe",
5962 "--gtest_print_time=f",
5963 NULL
5964 };
5965
5966 const char* argv2[] = {
5967 "foo.exe",
5968 NULL
5969 };
5970
vladlosevba015a92009-11-17 22:43:15 +00005971 GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::PrintTime(false), false);
shiqiand981cee2008-07-25 04:06:16 +00005972}
5973
5974// Tests parsing --gtest_print_time=F.
5975TEST_F(InitGoogleTestTest, PrintTimeFalse_F) {
5976 const char* argv[] = {
5977 "foo.exe",
5978 "--gtest_print_time=F",
5979 NULL
5980 };
5981
5982 const char* argv2[] = {
5983 "foo.exe",
5984 NULL
5985 };
5986
vladlosevba015a92009-11-17 22:43:15 +00005987 GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::PrintTime(false), false);
shiqiand981cee2008-07-25 04:06:16 +00005988}
5989
zhanyong.wan9b9794f2009-07-14 22:56:46 +00005990// Tests parsing --gtest_random_seed=number
5991TEST_F(InitGoogleTestTest, RandomSeed) {
5992 const char* argv[] = {
5993 "foo.exe",
5994 "--gtest_random_seed=1000",
5995 NULL
5996 };
5997
5998 const char* argv2[] = {
5999 "foo.exe",
6000 NULL
6001 };
6002
vladlosevba015a92009-11-17 22:43:15 +00006003 GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::RandomSeed(1000), false);
zhanyong.wan9b9794f2009-07-14 22:56:46 +00006004}
6005
shiqian4b6829f2008-07-03 22:38:12 +00006006// Tests parsing --gtest_repeat=number
6007TEST_F(InitGoogleTestTest, Repeat) {
6008 const char* argv[] = {
6009 "foo.exe",
6010 "--gtest_repeat=1000",
6011 NULL
6012 };
6013
6014 const char* argv2[] = {
6015 "foo.exe",
6016 NULL
6017 };
6018
vladlosevba015a92009-11-17 22:43:15 +00006019 GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::Repeat(1000), false);
shiqian4b6829f2008-07-03 22:38:12 +00006020}
6021
shiqianca6949f2009-01-10 01:16:33 +00006022// Tests having a --gtest_also_run_disabled_tests flag
6023TEST_F(InitGoogleTestTest, AlsoRunDisabledTestsFlag) {
6024 const char* argv[] = {
6025 "foo.exe",
6026 "--gtest_also_run_disabled_tests",
6027 NULL
6028 };
6029
6030 const char* argv2[] = {
6031 "foo.exe",
6032 NULL
6033 };
6034
vladlosevba015a92009-11-17 22:43:15 +00006035 GTEST_TEST_PARSING_FLAGS_(argv, argv2,
6036 Flags::AlsoRunDisabledTests(true), false);
shiqianca6949f2009-01-10 01:16:33 +00006037}
6038
6039// Tests having a --gtest_also_run_disabled_tests flag with a "true" value
6040TEST_F(InitGoogleTestTest, AlsoRunDisabledTestsTrue) {
6041 const char* argv[] = {
6042 "foo.exe",
6043 "--gtest_also_run_disabled_tests=1",
6044 NULL
6045 };
6046
6047 const char* argv2[] = {
6048 "foo.exe",
6049 NULL
6050 };
6051
vladlosevba015a92009-11-17 22:43:15 +00006052 GTEST_TEST_PARSING_FLAGS_(argv, argv2,
6053 Flags::AlsoRunDisabledTests(true), false);
shiqianca6949f2009-01-10 01:16:33 +00006054}
6055
6056// Tests having a --gtest_also_run_disabled_tests flag with a "false" value
6057TEST_F(InitGoogleTestTest, AlsoRunDisabledTestsFalse) {
6058 const char* argv[] = {
6059 "foo.exe",
6060 "--gtest_also_run_disabled_tests=0",
6061 NULL
6062 };
6063
6064 const char* argv2[] = {
6065 "foo.exe",
6066 NULL
6067 };
6068
vladlosevba015a92009-11-17 22:43:15 +00006069 GTEST_TEST_PARSING_FLAGS_(argv, argv2,
6070 Flags::AlsoRunDisabledTests(false), false);
shiqianca6949f2009-01-10 01:16:33 +00006071}
6072
zhanyong.wan9b9794f2009-07-14 22:56:46 +00006073// Tests parsing --gtest_shuffle.
6074TEST_F(InitGoogleTestTest, ShuffleWithoutValue) {
6075 const char* argv[] = {
6076 "foo.exe",
6077 "--gtest_shuffle",
6078 NULL
6079};
6080
6081 const char* argv2[] = {
6082 "foo.exe",
6083 NULL
6084 };
6085
vladlosevba015a92009-11-17 22:43:15 +00006086 GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::Shuffle(true), false);
zhanyong.wan9b9794f2009-07-14 22:56:46 +00006087}
6088
6089// Tests parsing --gtest_shuffle=0.
6090TEST_F(InitGoogleTestTest, ShuffleFalse_0) {
6091 const char* argv[] = {
6092 "foo.exe",
6093 "--gtest_shuffle=0",
6094 NULL
6095 };
6096
6097 const char* argv2[] = {
6098 "foo.exe",
6099 NULL
6100 };
6101
vladlosevba015a92009-11-17 22:43:15 +00006102 GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::Shuffle(false), false);
zhanyong.wan9b9794f2009-07-14 22:56:46 +00006103}
6104
6105// Tests parsing a --gtest_shuffle flag that has a "true"
6106// definition.
6107TEST_F(InitGoogleTestTest, ShuffleTrue) {
6108 const char* argv[] = {
6109 "foo.exe",
6110 "--gtest_shuffle=1",
6111 NULL
6112 };
6113
6114 const char* argv2[] = {
6115 "foo.exe",
6116 NULL
6117 };
6118
vladlosevba015a92009-11-17 22:43:15 +00006119 GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::Shuffle(true), false);
6120}
6121
6122// Tests parsing --gtest_stack_trace_depth=number.
6123TEST_F(InitGoogleTestTest, StackTraceDepth) {
6124 const char* argv[] = {
6125 "foo.exe",
6126 "--gtest_stack_trace_depth=5",
6127 NULL
6128 };
6129
6130 const char* argv2[] = {
6131 "foo.exe",
6132 NULL
6133 };
6134
6135 GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::StackTraceDepth(5), false);
zhanyong.wan9b9794f2009-07-14 22:56:46 +00006136}
zhanyong.wanb0fe69f2009-03-06 20:05:23 +00006137
zhanyong.wanc95489e2010-08-19 22:16:00 +00006138TEST_F(InitGoogleTestTest, StreamResultTo) {
6139 const char* argv[] = {
6140 "foo.exe",
6141 "--gtest_stream_result_to=localhost:1234",
6142 NULL
6143 };
6144
6145 const char* argv2[] = {
6146 "foo.exe",
6147 NULL
6148 };
6149
6150 GTEST_TEST_PARSING_FLAGS_(
6151 argv, argv2, Flags::StreamResultTo("localhost:1234"), false);
6152}
6153
zhanyong.wanb0fe69f2009-03-06 20:05:23 +00006154// Tests parsing --gtest_throw_on_failure.
zhanyong.wan9b9794f2009-07-14 22:56:46 +00006155TEST_F(InitGoogleTestTest, ThrowOnFailureWithoutValue) {
zhanyong.wanb0fe69f2009-03-06 20:05:23 +00006156 const char* argv[] = {
6157 "foo.exe",
6158 "--gtest_throw_on_failure",
6159 NULL
6160};
6161
6162 const char* argv2[] = {
6163 "foo.exe",
6164 NULL
6165 };
6166
vladlosevba015a92009-11-17 22:43:15 +00006167 GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::ThrowOnFailure(true), false);
zhanyong.wanb0fe69f2009-03-06 20:05:23 +00006168}
6169
6170// Tests parsing --gtest_throw_on_failure=0.
6171TEST_F(InitGoogleTestTest, ThrowOnFailureFalse_0) {
6172 const char* argv[] = {
6173 "foo.exe",
6174 "--gtest_throw_on_failure=0",
6175 NULL
6176 };
6177
6178 const char* argv2[] = {
6179 "foo.exe",
6180 NULL
6181 };
6182
vladlosevba015a92009-11-17 22:43:15 +00006183 GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::ThrowOnFailure(false), false);
zhanyong.wanb0fe69f2009-03-06 20:05:23 +00006184}
6185
6186// Tests parsing a --gtest_throw_on_failure flag that has a "true"
6187// definition.
6188TEST_F(InitGoogleTestTest, ThrowOnFailureTrue) {
6189 const char* argv[] = {
6190 "foo.exe",
6191 "--gtest_throw_on_failure=1",
6192 NULL
6193 };
6194
6195 const char* argv2[] = {
6196 "foo.exe",
6197 NULL
6198 };
6199
vladlosevba015a92009-11-17 22:43:15 +00006200 GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::ThrowOnFailure(true), false);
zhanyong.wanb0fe69f2009-03-06 20:05:23 +00006201}
6202
zhanyong.wan4cd62602009-02-23 23:21:55 +00006203#if GTEST_OS_WINDOWS
shiqian4b6829f2008-07-03 22:38:12 +00006204// Tests parsing wide strings.
6205TEST_F(InitGoogleTestTest, WideStrings) {
6206 const wchar_t* argv[] = {
6207 L"foo.exe",
6208 L"--gtest_filter=Foo*",
6209 L"--gtest_list_tests=1",
6210 L"--gtest_break_on_failure",
6211 L"--non_gtest_flag",
6212 NULL
6213 };
6214
6215 const wchar_t* argv2[] = {
6216 L"foo.exe",
6217 L"--non_gtest_flag",
6218 NULL
6219 };
6220
6221 Flags expected_flags;
6222 expected_flags.break_on_failure = true;
6223 expected_flags.filter = "Foo*";
6224 expected_flags.list_tests = true;
6225
vladlosevba015a92009-11-17 22:43:15 +00006226 GTEST_TEST_PARSING_FLAGS_(argv, argv2, expected_flags, false);
shiqian4b6829f2008-07-03 22:38:12 +00006227}
6228#endif // GTEST_OS_WINDOWS
6229
6230// Tests current_test_info() in UnitTest.
6231class CurrentTestInfoTest : public Test {
6232 protected:
6233 // Tests that current_test_info() returns NULL before the first test in
6234 // the test case is run.
6235 static void SetUpTestCase() {
6236 // There should be no tests running at this point.
6237 const TestInfo* test_info =
6238 UnitTest::GetInstance()->current_test_info();
zhanyong.wan9644db82009-06-24 23:02:50 +00006239 EXPECT_TRUE(test_info == NULL)
shiqian4b6829f2008-07-03 22:38:12 +00006240 << "There should be no tests running at this point.";
6241 }
6242
6243 // Tests that current_test_info() returns NULL after the last test in
6244 // the test case has run.
6245 static void TearDownTestCase() {
6246 const TestInfo* test_info =
6247 UnitTest::GetInstance()->current_test_info();
zhanyong.wan9644db82009-06-24 23:02:50 +00006248 EXPECT_TRUE(test_info == NULL)
shiqian4b6829f2008-07-03 22:38:12 +00006249 << "There should be no tests running at this point.";
6250 }
6251};
6252
6253// Tests that current_test_info() returns TestInfo for currently running
6254// test by checking the expected test name against the actual one.
6255TEST_F(CurrentTestInfoTest, WorksForFirstTestInATestCase) {
6256 const TestInfo* test_info =
6257 UnitTest::GetInstance()->current_test_info();
6258 ASSERT_TRUE(NULL != test_info)
6259 << "There is a test running so we should have a valid TestInfo.";
6260 EXPECT_STREQ("CurrentTestInfoTest", test_info->test_case_name())
6261 << "Expected the name of the currently running test case.";
6262 EXPECT_STREQ("WorksForFirstTestInATestCase", test_info->name())
6263 << "Expected the name of the currently running test.";
6264}
6265
6266// Tests that current_test_info() returns TestInfo for currently running
6267// test by checking the expected test name against the actual one. We
6268// use this test to see that the TestInfo object actually changed from
6269// the previous invocation.
6270TEST_F(CurrentTestInfoTest, WorksForSecondTestInATestCase) {
6271 const TestInfo* test_info =
6272 UnitTest::GetInstance()->current_test_info();
6273 ASSERT_TRUE(NULL != test_info)
6274 << "There is a test running so we should have a valid TestInfo.";
6275 EXPECT_STREQ("CurrentTestInfoTest", test_info->test_case_name())
6276 << "Expected the name of the currently running test case.";
6277 EXPECT_STREQ("WorksForSecondTestInATestCase", test_info->name())
6278 << "Expected the name of the currently running test.";
6279}
6280
6281} // namespace testing
6282
6283// These two lines test that we can define tests in a namespace that
6284// has the name "testing" and is nested in another namespace.
6285namespace my_namespace {
6286namespace testing {
6287
6288// Makes sure that TEST knows to use ::testing::Test instead of
6289// ::my_namespace::testing::Test.
6290class Test {};
6291
6292// Makes sure that an assertion knows to use ::testing::Message instead of
6293// ::my_namespace::testing::Message.
6294class Message {};
6295
6296// Makes sure that an assertion knows to use
6297// ::testing::AssertionResult instead of
6298// ::my_namespace::testing::AssertionResult.
6299class AssertionResult {};
6300
6301// Tests that an assertion that should succeed works as expected.
6302TEST(NestedTestingNamespaceTest, Success) {
6303 EXPECT_EQ(1, 1) << "This shouldn't fail.";
6304}
6305
6306// Tests that an assertion that should fail works as expected.
6307TEST(NestedTestingNamespaceTest, Failure) {
6308 EXPECT_FATAL_FAILURE(FAIL() << "This failure is expected.",
6309 "This failure is expected.");
6310}
6311
6312} // namespace testing
6313} // namespace my_namespace
6314
6315// Tests that one can call superclass SetUp and TearDown methods--
6316// that is, that they are not private.
6317// No tests are based on this fixture; the test "passes" if it compiles
6318// successfully.
shiqian760af5c2008-08-06 21:43:15 +00006319class ProtectedFixtureMethodsTest : public Test {
shiqian4b6829f2008-07-03 22:38:12 +00006320 protected:
6321 virtual void SetUp() {
shiqian760af5c2008-08-06 21:43:15 +00006322 Test::SetUp();
shiqian4b6829f2008-07-03 22:38:12 +00006323 }
6324 virtual void TearDown() {
shiqian760af5c2008-08-06 21:43:15 +00006325 Test::TearDown();
shiqian4b6829f2008-07-03 22:38:12 +00006326 }
6327};
6328
6329// StreamingAssertionsTest tests the streaming versions of a representative
6330// sample of assertions.
6331TEST(StreamingAssertionsTest, Unconditional) {
6332 SUCCEED() << "expected success";
6333 EXPECT_NONFATAL_FAILURE(ADD_FAILURE() << "expected failure",
6334 "expected failure");
6335 EXPECT_FATAL_FAILURE(FAIL() << "expected failure",
6336 "expected failure");
6337}
6338
zhanyong.wan98efcc42009-04-28 00:28:09 +00006339#ifdef __BORLANDC__
6340// Silences warnings: "Condition is always true", "Unreachable code"
zhanyong.wan733a54a2011-02-22 22:08:59 +00006341# pragma option push -w-ccc -w-rch
zhanyong.wan98efcc42009-04-28 00:28:09 +00006342#endif
6343
shiqian4b6829f2008-07-03 22:38:12 +00006344TEST(StreamingAssertionsTest, Truth) {
6345 EXPECT_TRUE(true) << "unexpected failure";
6346 ASSERT_TRUE(true) << "unexpected failure";
6347 EXPECT_NONFATAL_FAILURE(EXPECT_TRUE(false) << "expected failure",
6348 "expected failure");
6349 EXPECT_FATAL_FAILURE(ASSERT_TRUE(false) << "expected failure",
6350 "expected failure");
6351}
6352
6353TEST(StreamingAssertionsTest, Truth2) {
6354 EXPECT_FALSE(false) << "unexpected failure";
6355 ASSERT_FALSE(false) << "unexpected failure";
6356 EXPECT_NONFATAL_FAILURE(EXPECT_FALSE(true) << "expected failure",
6357 "expected failure");
6358 EXPECT_FATAL_FAILURE(ASSERT_FALSE(true) << "expected failure",
6359 "expected failure");
6360}
6361
zhanyong.wan98efcc42009-04-28 00:28:09 +00006362#ifdef __BORLANDC__
6363// Restores warnings after previous "#pragma option push" supressed them
zhanyong.wan733a54a2011-02-22 22:08:59 +00006364# pragma option pop
zhanyong.wan98efcc42009-04-28 00:28:09 +00006365#endif
6366
shiqian4b6829f2008-07-03 22:38:12 +00006367TEST(StreamingAssertionsTest, IntegerEquals) {
6368 EXPECT_EQ(1, 1) << "unexpected failure";
6369 ASSERT_EQ(1, 1) << "unexpected failure";
6370 EXPECT_NONFATAL_FAILURE(EXPECT_EQ(1, 2) << "expected failure",
6371 "expected failure");
6372 EXPECT_FATAL_FAILURE(ASSERT_EQ(1, 2) << "expected failure",
6373 "expected failure");
6374}
6375
6376TEST(StreamingAssertionsTest, IntegerLessThan) {
6377 EXPECT_LT(1, 2) << "unexpected failure";
6378 ASSERT_LT(1, 2) << "unexpected failure";
6379 EXPECT_NONFATAL_FAILURE(EXPECT_LT(2, 1) << "expected failure",
6380 "expected failure");
6381 EXPECT_FATAL_FAILURE(ASSERT_LT(2, 1) << "expected failure",
6382 "expected failure");
6383}
6384
6385TEST(StreamingAssertionsTest, StringsEqual) {
6386 EXPECT_STREQ("foo", "foo") << "unexpected failure";
6387 ASSERT_STREQ("foo", "foo") << "unexpected failure";
6388 EXPECT_NONFATAL_FAILURE(EXPECT_STREQ("foo", "bar") << "expected failure",
6389 "expected failure");
6390 EXPECT_FATAL_FAILURE(ASSERT_STREQ("foo", "bar") << "expected failure",
6391 "expected failure");
6392}
6393
6394TEST(StreamingAssertionsTest, StringsNotEqual) {
6395 EXPECT_STRNE("foo", "bar") << "unexpected failure";
6396 ASSERT_STRNE("foo", "bar") << "unexpected failure";
6397 EXPECT_NONFATAL_FAILURE(EXPECT_STRNE("foo", "foo") << "expected failure",
6398 "expected failure");
6399 EXPECT_FATAL_FAILURE(ASSERT_STRNE("foo", "foo") << "expected failure",
6400 "expected failure");
6401}
6402
6403TEST(StreamingAssertionsTest, StringsEqualIgnoringCase) {
6404 EXPECT_STRCASEEQ("foo", "FOO") << "unexpected failure";
6405 ASSERT_STRCASEEQ("foo", "FOO") << "unexpected failure";
6406 EXPECT_NONFATAL_FAILURE(EXPECT_STRCASEEQ("foo", "bar") << "expected failure",
6407 "expected failure");
6408 EXPECT_FATAL_FAILURE(ASSERT_STRCASEEQ("foo", "bar") << "expected failure",
6409 "expected failure");
6410}
6411
6412TEST(StreamingAssertionsTest, StringNotEqualIgnoringCase) {
6413 EXPECT_STRCASENE("foo", "bar") << "unexpected failure";
6414 ASSERT_STRCASENE("foo", "bar") << "unexpected failure";
6415 EXPECT_NONFATAL_FAILURE(EXPECT_STRCASENE("foo", "FOO") << "expected failure",
6416 "expected failure");
6417 EXPECT_FATAL_FAILURE(ASSERT_STRCASENE("bar", "BAR") << "expected failure",
6418 "expected failure");
6419}
6420
6421TEST(StreamingAssertionsTest, FloatingPointEquals) {
6422 EXPECT_FLOAT_EQ(1.0, 1.0) << "unexpected failure";
6423 ASSERT_FLOAT_EQ(1.0, 1.0) << "unexpected failure";
6424 EXPECT_NONFATAL_FAILURE(EXPECT_FLOAT_EQ(0.0, 1.0) << "expected failure",
6425 "expected failure");
6426 EXPECT_FATAL_FAILURE(ASSERT_FLOAT_EQ(0.0, 1.0) << "expected failure",
6427 "expected failure");
6428}
6429
shiqian9204c8e2008-09-12 20:57:22 +00006430#if GTEST_HAS_EXCEPTIONS
6431
6432TEST(StreamingAssertionsTest, Throw) {
6433 EXPECT_THROW(ThrowAnInteger(), int) << "unexpected failure";
6434 ASSERT_THROW(ThrowAnInteger(), int) << "unexpected failure";
6435 EXPECT_NONFATAL_FAILURE(EXPECT_THROW(ThrowAnInteger(), bool) <<
6436 "expected failure", "expected failure");
6437 EXPECT_FATAL_FAILURE(ASSERT_THROW(ThrowAnInteger(), bool) <<
6438 "expected failure", "expected failure");
6439}
6440
6441TEST(StreamingAssertionsTest, NoThrow) {
zhanyong.wanac60cef2009-02-08 04:53:35 +00006442 EXPECT_NO_THROW(ThrowNothing()) << "unexpected failure";
6443 ASSERT_NO_THROW(ThrowNothing()) << "unexpected failure";
shiqian9204c8e2008-09-12 20:57:22 +00006444 EXPECT_NONFATAL_FAILURE(EXPECT_NO_THROW(ThrowAnInteger()) <<
6445 "expected failure", "expected failure");
6446 EXPECT_FATAL_FAILURE(ASSERT_NO_THROW(ThrowAnInteger()) <<
6447 "expected failure", "expected failure");
6448}
6449
6450TEST(StreamingAssertionsTest, AnyThrow) {
6451 EXPECT_ANY_THROW(ThrowAnInteger()) << "unexpected failure";
6452 ASSERT_ANY_THROW(ThrowAnInteger()) << "unexpected failure";
zhanyong.wanac60cef2009-02-08 04:53:35 +00006453 EXPECT_NONFATAL_FAILURE(EXPECT_ANY_THROW(ThrowNothing()) <<
shiqian9204c8e2008-09-12 20:57:22 +00006454 "expected failure", "expected failure");
zhanyong.wanac60cef2009-02-08 04:53:35 +00006455 EXPECT_FATAL_FAILURE(ASSERT_ANY_THROW(ThrowNothing()) <<
shiqian9204c8e2008-09-12 20:57:22 +00006456 "expected failure", "expected failure");
6457}
6458
6459#endif // GTEST_HAS_EXCEPTIONS
6460
shiqian4b6829f2008-07-03 22:38:12 +00006461// Tests that Google Test correctly decides whether to use colors in the output.
6462
6463TEST(ColoredOutputTest, UsesColorsWhenGTestColorFlagIsYes) {
6464 GTEST_FLAG(color) = "yes";
6465
6466 SetEnv("TERM", "xterm"); // TERM supports colors.
6467 EXPECT_TRUE(ShouldUseColor(true)); // Stdout is a TTY.
6468 EXPECT_TRUE(ShouldUseColor(false)); // Stdout is not a TTY.
6469
6470 SetEnv("TERM", "dumb"); // TERM doesn't support colors.
6471 EXPECT_TRUE(ShouldUseColor(true)); // Stdout is a TTY.
6472 EXPECT_TRUE(ShouldUseColor(false)); // Stdout is not a TTY.
6473}
6474
6475TEST(ColoredOutputTest, UsesColorsWhenGTestColorFlagIsAliasOfYes) {
6476 SetEnv("TERM", "dumb"); // TERM doesn't support colors.
6477
6478 GTEST_FLAG(color) = "True";
6479 EXPECT_TRUE(ShouldUseColor(false)); // Stdout is not a TTY.
6480
6481 GTEST_FLAG(color) = "t";
6482 EXPECT_TRUE(ShouldUseColor(false)); // Stdout is not a TTY.
6483
6484 GTEST_FLAG(color) = "1";
6485 EXPECT_TRUE(ShouldUseColor(false)); // Stdout is not a TTY.
6486}
6487
6488TEST(ColoredOutputTest, UsesNoColorWhenGTestColorFlagIsNo) {
6489 GTEST_FLAG(color) = "no";
6490
6491 SetEnv("TERM", "xterm"); // TERM supports colors.
6492 EXPECT_FALSE(ShouldUseColor(true)); // Stdout is a TTY.
6493 EXPECT_FALSE(ShouldUseColor(false)); // Stdout is not a TTY.
6494
6495 SetEnv("TERM", "dumb"); // TERM doesn't support colors.
6496 EXPECT_FALSE(ShouldUseColor(true)); // Stdout is a TTY.
6497 EXPECT_FALSE(ShouldUseColor(false)); // Stdout is not a TTY.
6498}
6499
6500TEST(ColoredOutputTest, UsesNoColorWhenGTestColorFlagIsInvalid) {
6501 SetEnv("TERM", "xterm"); // TERM supports colors.
6502
6503 GTEST_FLAG(color) = "F";
6504 EXPECT_FALSE(ShouldUseColor(true)); // Stdout is a TTY.
6505
6506 GTEST_FLAG(color) = "0";
6507 EXPECT_FALSE(ShouldUseColor(true)); // Stdout is a TTY.
6508
6509 GTEST_FLAG(color) = "unknown";
6510 EXPECT_FALSE(ShouldUseColor(true)); // Stdout is a TTY.
6511}
6512
6513TEST(ColoredOutputTest, UsesColorsWhenStdoutIsTty) {
6514 GTEST_FLAG(color) = "auto";
6515
6516 SetEnv("TERM", "xterm"); // TERM supports colors.
6517 EXPECT_FALSE(ShouldUseColor(false)); // Stdout is not a TTY.
6518 EXPECT_TRUE(ShouldUseColor(true)); // Stdout is a TTY.
6519}
6520
6521TEST(ColoredOutputTest, UsesColorsWhenTermSupportsColors) {
6522 GTEST_FLAG(color) = "auto";
6523
zhanyong.wan4cd62602009-02-23 23:21:55 +00006524#if GTEST_OS_WINDOWS
shiqian4b6829f2008-07-03 22:38:12 +00006525 // On Windows, we ignore the TERM variable as it's usually not set.
6526
6527 SetEnv("TERM", "dumb");
6528 EXPECT_TRUE(ShouldUseColor(true)); // Stdout is a TTY.
6529
6530 SetEnv("TERM", "");
6531 EXPECT_TRUE(ShouldUseColor(true)); // Stdout is a TTY.
6532
6533 SetEnv("TERM", "xterm");
6534 EXPECT_TRUE(ShouldUseColor(true)); // Stdout is a TTY.
6535#else
6536 // On non-Windows platforms, we rely on TERM to determine if the
6537 // terminal supports colors.
6538
6539 SetEnv("TERM", "dumb"); // TERM doesn't support colors.
6540 EXPECT_FALSE(ShouldUseColor(true)); // Stdout is a TTY.
6541
6542 SetEnv("TERM", "emacs"); // TERM doesn't support colors.
6543 EXPECT_FALSE(ShouldUseColor(true)); // Stdout is a TTY.
6544
6545 SetEnv("TERM", "vt100"); // TERM doesn't support colors.
6546 EXPECT_FALSE(ShouldUseColor(true)); // Stdout is a TTY.
6547
6548 SetEnv("TERM", "xterm-mono"); // TERM doesn't support colors.
6549 EXPECT_FALSE(ShouldUseColor(true)); // Stdout is a TTY.
6550
6551 SetEnv("TERM", "xterm"); // TERM supports colors.
6552 EXPECT_TRUE(ShouldUseColor(true)); // Stdout is a TTY.
6553
6554 SetEnv("TERM", "xterm-color"); // TERM supports colors.
6555 EXPECT_TRUE(ShouldUseColor(true)); // Stdout is a TTY.
zhanyong.wana8a582f2009-07-13 19:25:02 +00006556
vladlosev9f254912010-04-22 11:44:59 +00006557 SetEnv("TERM", "xterm-256color"); // TERM supports colors.
6558 EXPECT_TRUE(ShouldUseColor(true)); // Stdout is a TTY.
6559
6560 SetEnv("TERM", "screen"); // TERM supports colors.
6561 EXPECT_TRUE(ShouldUseColor(true)); // Stdout is a TTY.
6562
zhanyong.wan4036e7d2013-03-11 17:52:13 +00006563 SetEnv("TERM", "screen-256color"); // TERM supports colors.
6564 EXPECT_TRUE(ShouldUseColor(true)); // Stdout is a TTY.
6565
zhanyong.wana8a582f2009-07-13 19:25:02 +00006566 SetEnv("TERM", "linux"); // TERM supports colors.
6567 EXPECT_TRUE(ShouldUseColor(true)); // Stdout is a TTY.
vladlosev9f254912010-04-22 11:44:59 +00006568
6569 SetEnv("TERM", "cygwin"); // TERM supports colors.
6570 EXPECT_TRUE(ShouldUseColor(true)); // Stdout is a TTY.
shiqian4b6829f2008-07-03 22:38:12 +00006571#endif // GTEST_OS_WINDOWS
6572}
6573
shiqian21d43d12009-01-08 01:10:31 +00006574// Verifies that StaticAssertTypeEq works in a namespace scope.
6575
zhanyong.wan5e255e02011-01-10 18:17:59 +00006576static bool dummy1 GTEST_ATTRIBUTE_UNUSED_ = StaticAssertTypeEq<bool, bool>();
6577static bool dummy2 GTEST_ATTRIBUTE_UNUSED_ =
6578 StaticAssertTypeEq<const int, const int>();
shiqian21d43d12009-01-08 01:10:31 +00006579
6580// Verifies that StaticAssertTypeEq works in a class.
6581
6582template <typename T>
6583class StaticAssertTypeEqTestHelper {
6584 public:
6585 StaticAssertTypeEqTestHelper() { StaticAssertTypeEq<bool, T>(); }
6586};
6587
6588TEST(StaticAssertTypeEqTest, WorksInClass) {
6589 StaticAssertTypeEqTestHelper<bool>();
6590}
6591
6592// Verifies that StaticAssertTypeEq works inside a function.
6593
6594typedef int IntAlias;
6595
6596TEST(StaticAssertTypeEqTest, CompilesForEqualTypes) {
6597 StaticAssertTypeEq<int, IntAlias>();
6598 StaticAssertTypeEq<int*, IntAlias*>();
6599}
6600
vladlosevf904a612008-11-20 01:40:35 +00006601TEST(GetCurrentOsStackTraceExceptTopTest, ReturnsTheStackTrace) {
6602 testing::UnitTest* const unit_test = testing::UnitTest::GetInstance();
6603
6604 // We don't have a stack walker in Google Test yet.
6605 EXPECT_STREQ("", GetCurrentOsStackTraceExceptTop(unit_test, 0).c_str());
6606 EXPECT_STREQ("", GetCurrentOsStackTraceExceptTop(unit_test, 1).c_str());
6607}
zhanyong.wan1b171102009-04-07 21:03:22 +00006608
6609TEST(HasNonfatalFailureTest, ReturnsFalseWhenThereIsNoFailure) {
6610 EXPECT_FALSE(HasNonfatalFailure());
6611}
6612
6613static void FailFatally() { FAIL(); }
6614
6615TEST(HasNonfatalFailureTest, ReturnsFalseWhenThereIsOnlyFatalFailure) {
6616 FailFatally();
6617 const bool has_nonfatal_failure = HasNonfatalFailure();
6618 ClearCurrentTestPartResults();
6619 EXPECT_FALSE(has_nonfatal_failure);
6620}
6621
6622TEST(HasNonfatalFailureTest, ReturnsTrueWhenThereIsNonfatalFailure) {
6623 ADD_FAILURE();
6624 const bool has_nonfatal_failure = HasNonfatalFailure();
6625 ClearCurrentTestPartResults();
6626 EXPECT_TRUE(has_nonfatal_failure);
6627}
6628
6629TEST(HasNonfatalFailureTest, ReturnsTrueWhenThereAreFatalAndNonfatalFailures) {
6630 FailFatally();
6631 ADD_FAILURE();
6632 const bool has_nonfatal_failure = HasNonfatalFailure();
6633 ClearCurrentTestPartResults();
6634 EXPECT_TRUE(has_nonfatal_failure);
6635}
6636
6637// A wrapper for calling HasNonfatalFailure outside of a test body.
6638static bool HasNonfatalFailureHelper() {
6639 return testing::Test::HasNonfatalFailure();
6640}
6641
6642TEST(HasNonfatalFailureTest, WorksOutsideOfTestBody) {
6643 EXPECT_FALSE(HasNonfatalFailureHelper());
6644}
6645
6646TEST(HasNonfatalFailureTest, WorksOutsideOfTestBody2) {
6647 ADD_FAILURE();
6648 const bool has_nonfatal_failure = HasNonfatalFailureHelper();
6649 ClearCurrentTestPartResults();
6650 EXPECT_TRUE(has_nonfatal_failure);
6651}
6652
6653TEST(HasFailureTest, ReturnsFalseWhenThereIsNoFailure) {
6654 EXPECT_FALSE(HasFailure());
6655}
6656
6657TEST(HasFailureTest, ReturnsTrueWhenThereIsFatalFailure) {
6658 FailFatally();
6659 const bool has_failure = HasFailure();
6660 ClearCurrentTestPartResults();
6661 EXPECT_TRUE(has_failure);
6662}
6663
6664TEST(HasFailureTest, ReturnsTrueWhenThereIsNonfatalFailure) {
6665 ADD_FAILURE();
6666 const bool has_failure = HasFailure();
6667 ClearCurrentTestPartResults();
6668 EXPECT_TRUE(has_failure);
6669}
6670
6671TEST(HasFailureTest, ReturnsTrueWhenThereAreFatalAndNonfatalFailures) {
6672 FailFatally();
6673 ADD_FAILURE();
6674 const bool has_failure = HasFailure();
6675 ClearCurrentTestPartResults();
6676 EXPECT_TRUE(has_failure);
6677}
6678
6679// A wrapper for calling HasFailure outside of a test body.
6680static bool HasFailureHelper() { return testing::Test::HasFailure(); }
6681
6682TEST(HasFailureTest, WorksOutsideOfTestBody) {
6683 EXPECT_FALSE(HasFailureHelper());
6684}
6685
6686TEST(HasFailureTest, WorksOutsideOfTestBody2) {
6687 ADD_FAILURE();
6688 const bool has_failure = HasFailureHelper();
6689 ClearCurrentTestPartResults();
6690 EXPECT_TRUE(has_failure);
6691}
zhanyong.wanf39160b2009-09-04 18:30:25 +00006692
6693class TestListener : public EmptyTestEventListener {
6694 public:
6695 TestListener() : on_start_counter_(NULL), is_destroyed_(NULL) {}
6696 TestListener(int* on_start_counter, bool* is_destroyed)
6697 : on_start_counter_(on_start_counter),
6698 is_destroyed_(is_destroyed) {}
6699
6700 virtual ~TestListener() {
6701 if (is_destroyed_)
6702 *is_destroyed_ = true;
6703 }
6704
6705 protected:
zhanyong.wan7dcfb6b2009-09-17 19:12:30 +00006706 virtual void OnTestProgramStart(const UnitTest& /*unit_test*/) {
zhanyong.wanf39160b2009-09-04 18:30:25 +00006707 if (on_start_counter_ != NULL)
6708 (*on_start_counter_)++;
6709 }
6710
6711 private:
6712 int* on_start_counter_;
6713 bool* is_destroyed_;
6714};
6715
6716// Tests the constructor.
zhanyong.wanf6d087b2009-09-30 20:23:50 +00006717TEST(TestEventListenersTest, ConstructionWorks) {
6718 TestEventListeners listeners;
zhanyong.wanf39160b2009-09-04 18:30:25 +00006719
zhanyong.wanf6d087b2009-09-30 20:23:50 +00006720 EXPECT_TRUE(TestEventListenersAccessor::GetRepeater(&listeners) != NULL);
zhanyong.wanf39160b2009-09-04 18:30:25 +00006721 EXPECT_TRUE(listeners.default_result_printer() == NULL);
6722 EXPECT_TRUE(listeners.default_xml_generator() == NULL);
6723}
6724
zhanyong.wanf6d087b2009-09-30 20:23:50 +00006725// Tests that the TestEventListeners destructor deletes all the listeners it
zhanyong.wanf39160b2009-09-04 18:30:25 +00006726// owns.
zhanyong.wanf6d087b2009-09-30 20:23:50 +00006727TEST(TestEventListenersTest, DestructionWorks) {
zhanyong.wanf39160b2009-09-04 18:30:25 +00006728 bool default_result_printer_is_destroyed = false;
6729 bool default_xml_printer_is_destroyed = false;
6730 bool extra_listener_is_destroyed = false;
6731 TestListener* default_result_printer = new TestListener(
6732 NULL, &default_result_printer_is_destroyed);
6733 TestListener* default_xml_printer = new TestListener(
6734 NULL, &default_xml_printer_is_destroyed);
6735 TestListener* extra_listener = new TestListener(
6736 NULL, &extra_listener_is_destroyed);
6737
6738 {
zhanyong.wanf6d087b2009-09-30 20:23:50 +00006739 TestEventListeners listeners;
6740 TestEventListenersAccessor::SetDefaultResultPrinter(&listeners,
6741 default_result_printer);
6742 TestEventListenersAccessor::SetDefaultXmlGenerator(&listeners,
6743 default_xml_printer);
zhanyong.wanf39160b2009-09-04 18:30:25 +00006744 listeners.Append(extra_listener);
6745 }
6746 EXPECT_TRUE(default_result_printer_is_destroyed);
6747 EXPECT_TRUE(default_xml_printer_is_destroyed);
6748 EXPECT_TRUE(extra_listener_is_destroyed);
6749}
6750
zhanyong.wanf6d087b2009-09-30 20:23:50 +00006751// Tests that a listener Append'ed to a TestEventListeners list starts
zhanyong.wanf39160b2009-09-04 18:30:25 +00006752// receiving events.
zhanyong.wanf6d087b2009-09-30 20:23:50 +00006753TEST(TestEventListenersTest, Append) {
zhanyong.wanf39160b2009-09-04 18:30:25 +00006754 int on_start_counter = 0;
6755 bool is_destroyed = false;
6756 TestListener* listener = new TestListener(&on_start_counter, &is_destroyed);
6757 {
zhanyong.wanf6d087b2009-09-30 20:23:50 +00006758 TestEventListeners listeners;
zhanyong.wanf39160b2009-09-04 18:30:25 +00006759 listeners.Append(listener);
zhanyong.wanf6d087b2009-09-30 20:23:50 +00006760 TestEventListenersAccessor::GetRepeater(&listeners)->OnTestProgramStart(
zhanyong.wanf39160b2009-09-04 18:30:25 +00006761 *UnitTest::GetInstance());
6762 EXPECT_EQ(1, on_start_counter);
6763 }
6764 EXPECT_TRUE(is_destroyed);
6765}
6766
zhanyong.wan7dcfb6b2009-09-17 19:12:30 +00006767// Tests that listeners receive events in the order they were appended to
6768// the list, except for *End requests, which must be received in the reverse
6769// order.
zhanyong.wanf39160b2009-09-04 18:30:25 +00006770class SequenceTestingListener : public EmptyTestEventListener {
6771 public:
jgm@google.com03c31492012-11-15 15:47:38 +00006772 SequenceTestingListener(std::vector<std::string>* vector, const char* id)
zhanyong.wan7dcfb6b2009-09-17 19:12:30 +00006773 : vector_(vector), id_(id) {}
zhanyong.wanf39160b2009-09-04 18:30:25 +00006774
6775 protected:
zhanyong.wan7dcfb6b2009-09-17 19:12:30 +00006776 virtual void OnTestProgramStart(const UnitTest& /*unit_test*/) {
zhanyong.wan93d13a82010-02-25 01:09:07 +00006777 vector_->push_back(GetEventDescription("OnTestProgramStart"));
zhanyong.wan7dcfb6b2009-09-17 19:12:30 +00006778 }
6779
6780 virtual void OnTestProgramEnd(const UnitTest& /*unit_test*/) {
zhanyong.wan93d13a82010-02-25 01:09:07 +00006781 vector_->push_back(GetEventDescription("OnTestProgramEnd"));
zhanyong.wan7dcfb6b2009-09-17 19:12:30 +00006782 }
6783
6784 virtual void OnTestIterationStart(const UnitTest& /*unit_test*/,
6785 int /*iteration*/) {
zhanyong.wan93d13a82010-02-25 01:09:07 +00006786 vector_->push_back(GetEventDescription("OnTestIterationStart"));
zhanyong.wan7dcfb6b2009-09-17 19:12:30 +00006787 }
6788
6789 virtual void OnTestIterationEnd(const UnitTest& /*unit_test*/,
6790 int /*iteration*/) {
zhanyong.wan93d13a82010-02-25 01:09:07 +00006791 vector_->push_back(GetEventDescription("OnTestIterationEnd"));
zhanyong.wanf39160b2009-09-04 18:30:25 +00006792 }
6793
6794 private:
jgm@google.com03c31492012-11-15 15:47:38 +00006795 std::string GetEventDescription(const char* method) {
zhanyong.wan7dcfb6b2009-09-17 19:12:30 +00006796 Message message;
6797 message << id_ << "." << method;
6798 return message.GetString();
6799 }
6800
jgm@google.com03c31492012-11-15 15:47:38 +00006801 std::vector<std::string>* vector_;
zhanyong.wan7dcfb6b2009-09-17 19:12:30 +00006802 const char* const id_;
zhanyong.wand586f9f2009-09-18 16:35:15 +00006803
6804 GTEST_DISALLOW_COPY_AND_ASSIGN_(SequenceTestingListener);
zhanyong.wanf39160b2009-09-04 18:30:25 +00006805};
6806
6807TEST(EventListenerTest, AppendKeepsOrder) {
jgm@google.com03c31492012-11-15 15:47:38 +00006808 std::vector<std::string> vec;
zhanyong.wanf6d087b2009-09-30 20:23:50 +00006809 TestEventListeners listeners;
zhanyong.wan7dcfb6b2009-09-17 19:12:30 +00006810 listeners.Append(new SequenceTestingListener(&vec, "1st"));
6811 listeners.Append(new SequenceTestingListener(&vec, "2nd"));
6812 listeners.Append(new SequenceTestingListener(&vec, "3rd"));
6813
zhanyong.wanf6d087b2009-09-30 20:23:50 +00006814 TestEventListenersAccessor::GetRepeater(&listeners)->OnTestProgramStart(
zhanyong.wanf39160b2009-09-04 18:30:25 +00006815 *UnitTest::GetInstance());
zhanyong.wan93d13a82010-02-25 01:09:07 +00006816 ASSERT_EQ(3U, vec.size());
6817 EXPECT_STREQ("1st.OnTestProgramStart", vec[0].c_str());
6818 EXPECT_STREQ("2nd.OnTestProgramStart", vec[1].c_str());
6819 EXPECT_STREQ("3rd.OnTestProgramStart", vec[2].c_str());
zhanyong.wan7dcfb6b2009-09-17 19:12:30 +00006820
zhanyong.wan93d13a82010-02-25 01:09:07 +00006821 vec.clear();
zhanyong.wanf6d087b2009-09-30 20:23:50 +00006822 TestEventListenersAccessor::GetRepeater(&listeners)->OnTestProgramEnd(
zhanyong.wan7dcfb6b2009-09-17 19:12:30 +00006823 *UnitTest::GetInstance());
zhanyong.wan93d13a82010-02-25 01:09:07 +00006824 ASSERT_EQ(3U, vec.size());
6825 EXPECT_STREQ("3rd.OnTestProgramEnd", vec[0].c_str());
6826 EXPECT_STREQ("2nd.OnTestProgramEnd", vec[1].c_str());
6827 EXPECT_STREQ("1st.OnTestProgramEnd", vec[2].c_str());
zhanyong.wan7dcfb6b2009-09-17 19:12:30 +00006828
zhanyong.wan93d13a82010-02-25 01:09:07 +00006829 vec.clear();
zhanyong.wanf6d087b2009-09-30 20:23:50 +00006830 TestEventListenersAccessor::GetRepeater(&listeners)->OnTestIterationStart(
zhanyong.wan7dcfb6b2009-09-17 19:12:30 +00006831 *UnitTest::GetInstance(), 0);
zhanyong.wan93d13a82010-02-25 01:09:07 +00006832 ASSERT_EQ(3U, vec.size());
6833 EXPECT_STREQ("1st.OnTestIterationStart", vec[0].c_str());
6834 EXPECT_STREQ("2nd.OnTestIterationStart", vec[1].c_str());
6835 EXPECT_STREQ("3rd.OnTestIterationStart", vec[2].c_str());
zhanyong.wan7dcfb6b2009-09-17 19:12:30 +00006836
zhanyong.wan93d13a82010-02-25 01:09:07 +00006837 vec.clear();
zhanyong.wanf6d087b2009-09-30 20:23:50 +00006838 TestEventListenersAccessor::GetRepeater(&listeners)->OnTestIterationEnd(
zhanyong.wan7dcfb6b2009-09-17 19:12:30 +00006839 *UnitTest::GetInstance(), 0);
zhanyong.wan93d13a82010-02-25 01:09:07 +00006840 ASSERT_EQ(3U, vec.size());
6841 EXPECT_STREQ("3rd.OnTestIterationEnd", vec[0].c_str());
6842 EXPECT_STREQ("2nd.OnTestIterationEnd", vec[1].c_str());
6843 EXPECT_STREQ("1st.OnTestIterationEnd", vec[2].c_str());
zhanyong.wanf39160b2009-09-04 18:30:25 +00006844}
6845
zhanyong.wanf6d087b2009-09-30 20:23:50 +00006846// Tests that a listener removed from a TestEventListeners list stops receiving
zhanyong.wanf39160b2009-09-04 18:30:25 +00006847// events and is not deleted when the list is destroyed.
zhanyong.wanf6d087b2009-09-30 20:23:50 +00006848TEST(TestEventListenersTest, Release) {
zhanyong.wanf39160b2009-09-04 18:30:25 +00006849 int on_start_counter = 0;
6850 bool is_destroyed = false;
6851 // Although Append passes the ownership of this object to the list,
6852 // the following calls release it, and we need to delete it before the
6853 // test ends.
6854 TestListener* listener = new TestListener(&on_start_counter, &is_destroyed);
6855 {
zhanyong.wanf6d087b2009-09-30 20:23:50 +00006856 TestEventListeners listeners;
zhanyong.wanf39160b2009-09-04 18:30:25 +00006857 listeners.Append(listener);
6858 EXPECT_EQ(listener, listeners.Release(listener));
zhanyong.wanf6d087b2009-09-30 20:23:50 +00006859 TestEventListenersAccessor::GetRepeater(&listeners)->OnTestProgramStart(
zhanyong.wanf39160b2009-09-04 18:30:25 +00006860 *UnitTest::GetInstance());
6861 EXPECT_TRUE(listeners.Release(listener) == NULL);
6862 }
6863 EXPECT_EQ(0, on_start_counter);
6864 EXPECT_FALSE(is_destroyed);
6865 delete listener;
6866}
6867
6868// Tests that no events are forwarded when event forwarding is disabled.
6869TEST(EventListenerTest, SuppressEventForwarding) {
6870 int on_start_counter = 0;
6871 TestListener* listener = new TestListener(&on_start_counter, NULL);
6872
zhanyong.wanf6d087b2009-09-30 20:23:50 +00006873 TestEventListeners listeners;
zhanyong.wanf39160b2009-09-04 18:30:25 +00006874 listeners.Append(listener);
zhanyong.wanf6d087b2009-09-30 20:23:50 +00006875 ASSERT_TRUE(TestEventListenersAccessor::EventForwardingEnabled(listeners));
6876 TestEventListenersAccessor::SuppressEventForwarding(&listeners);
6877 ASSERT_FALSE(TestEventListenersAccessor::EventForwardingEnabled(listeners));
6878 TestEventListenersAccessor::GetRepeater(&listeners)->OnTestProgramStart(
zhanyong.wanf39160b2009-09-04 18:30:25 +00006879 *UnitTest::GetInstance());
6880 EXPECT_EQ(0, on_start_counter);
6881}
6882
zhanyong.wanf39160b2009-09-04 18:30:25 +00006883// Tests that events generated by Google Test are not forwarded in
6884// death test subprocesses.
6885TEST(EventListenerDeathTest, EventsNotForwardedInDeathTestSubprecesses) {
zhanyong.wand541f022009-09-11 06:59:42 +00006886 EXPECT_DEATH_IF_SUPPORTED({
zhanyong.wanf6d087b2009-09-30 20:23:50 +00006887 GTEST_CHECK_(TestEventListenersAccessor::EventForwardingEnabled(
zhanyong.wanf39160b2009-09-04 18:30:25 +00006888 *GetUnitTestImpl()->listeners())) << "expected failure";},
6889 "expected failure");
6890}
zhanyong.wanf39160b2009-09-04 18:30:25 +00006891
6892// Tests that a listener installed via SetDefaultResultPrinter() starts
6893// receiving events and is returned via default_result_printer() and that
6894// the previous default_result_printer is removed from the list and deleted.
6895TEST(EventListenerTest, default_result_printer) {
6896 int on_start_counter = 0;
6897 bool is_destroyed = false;
6898 TestListener* listener = new TestListener(&on_start_counter, &is_destroyed);
6899
zhanyong.wanf6d087b2009-09-30 20:23:50 +00006900 TestEventListeners listeners;
6901 TestEventListenersAccessor::SetDefaultResultPrinter(&listeners, listener);
zhanyong.wanf39160b2009-09-04 18:30:25 +00006902
6903 EXPECT_EQ(listener, listeners.default_result_printer());
6904
zhanyong.wanf6d087b2009-09-30 20:23:50 +00006905 TestEventListenersAccessor::GetRepeater(&listeners)->OnTestProgramStart(
zhanyong.wanf39160b2009-09-04 18:30:25 +00006906 *UnitTest::GetInstance());
6907
6908 EXPECT_EQ(1, on_start_counter);
6909
6910 // Replacing default_result_printer with something else should remove it
6911 // from the list and destroy it.
zhanyong.wanf6d087b2009-09-30 20:23:50 +00006912 TestEventListenersAccessor::SetDefaultResultPrinter(&listeners, NULL);
zhanyong.wanf39160b2009-09-04 18:30:25 +00006913
6914 EXPECT_TRUE(listeners.default_result_printer() == NULL);
6915 EXPECT_TRUE(is_destroyed);
6916
6917 // After broadcasting an event the counter is still the same, indicating
6918 // the listener is not in the list anymore.
zhanyong.wanf6d087b2009-09-30 20:23:50 +00006919 TestEventListenersAccessor::GetRepeater(&listeners)->OnTestProgramStart(
zhanyong.wanf39160b2009-09-04 18:30:25 +00006920 *UnitTest::GetInstance());
6921 EXPECT_EQ(1, on_start_counter);
6922}
6923
6924// Tests that the default_result_printer listener stops receiving events
6925// when removed via Release and that is not owned by the list anymore.
6926TEST(EventListenerTest, RemovingDefaultResultPrinterWorks) {
6927 int on_start_counter = 0;
6928 bool is_destroyed = false;
6929 // Although Append passes the ownership of this object to the list,
6930 // the following calls release it, and we need to delete it before the
6931 // test ends.
6932 TestListener* listener = new TestListener(&on_start_counter, &is_destroyed);
6933 {
zhanyong.wanf6d087b2009-09-30 20:23:50 +00006934 TestEventListeners listeners;
6935 TestEventListenersAccessor::SetDefaultResultPrinter(&listeners, listener);
zhanyong.wanf39160b2009-09-04 18:30:25 +00006936
6937 EXPECT_EQ(listener, listeners.Release(listener));
6938 EXPECT_TRUE(listeners.default_result_printer() == NULL);
6939 EXPECT_FALSE(is_destroyed);
6940
6941 // Broadcasting events now should not affect default_result_printer.
zhanyong.wanf6d087b2009-09-30 20:23:50 +00006942 TestEventListenersAccessor::GetRepeater(&listeners)->OnTestProgramStart(
zhanyong.wanf39160b2009-09-04 18:30:25 +00006943 *UnitTest::GetInstance());
6944 EXPECT_EQ(0, on_start_counter);
6945 }
6946 // Destroying the list should not affect the listener now, too.
6947 EXPECT_FALSE(is_destroyed);
6948 delete listener;
6949}
6950
6951// Tests that a listener installed via SetDefaultXmlGenerator() starts
6952// receiving events and is returned via default_xml_generator() and that
6953// the previous default_xml_generator is removed from the list and deleted.
6954TEST(EventListenerTest, default_xml_generator) {
6955 int on_start_counter = 0;
6956 bool is_destroyed = false;
6957 TestListener* listener = new TestListener(&on_start_counter, &is_destroyed);
6958
zhanyong.wanf6d087b2009-09-30 20:23:50 +00006959 TestEventListeners listeners;
6960 TestEventListenersAccessor::SetDefaultXmlGenerator(&listeners, listener);
zhanyong.wanf39160b2009-09-04 18:30:25 +00006961
6962 EXPECT_EQ(listener, listeners.default_xml_generator());
6963
zhanyong.wanf6d087b2009-09-30 20:23:50 +00006964 TestEventListenersAccessor::GetRepeater(&listeners)->OnTestProgramStart(
zhanyong.wanf39160b2009-09-04 18:30:25 +00006965 *UnitTest::GetInstance());
6966
6967 EXPECT_EQ(1, on_start_counter);
6968
6969 // Replacing default_xml_generator with something else should remove it
6970 // from the list and destroy it.
zhanyong.wanf6d087b2009-09-30 20:23:50 +00006971 TestEventListenersAccessor::SetDefaultXmlGenerator(&listeners, NULL);
zhanyong.wanf39160b2009-09-04 18:30:25 +00006972
6973 EXPECT_TRUE(listeners.default_xml_generator() == NULL);
6974 EXPECT_TRUE(is_destroyed);
6975
6976 // After broadcasting an event the counter is still the same, indicating
6977 // the listener is not in the list anymore.
zhanyong.wanf6d087b2009-09-30 20:23:50 +00006978 TestEventListenersAccessor::GetRepeater(&listeners)->OnTestProgramStart(
zhanyong.wanf39160b2009-09-04 18:30:25 +00006979 *UnitTest::GetInstance());
6980 EXPECT_EQ(1, on_start_counter);
6981}
6982
6983// Tests that the default_xml_generator listener stops receiving events
6984// when removed via Release and that is not owned by the list anymore.
6985TEST(EventListenerTest, RemovingDefaultXmlGeneratorWorks) {
6986 int on_start_counter = 0;
6987 bool is_destroyed = false;
6988 // Although Append passes the ownership of this object to the list,
6989 // the following calls release it, and we need to delete it before the
6990 // test ends.
6991 TestListener* listener = new TestListener(&on_start_counter, &is_destroyed);
6992 {
zhanyong.wanf6d087b2009-09-30 20:23:50 +00006993 TestEventListeners listeners;
6994 TestEventListenersAccessor::SetDefaultXmlGenerator(&listeners, listener);
zhanyong.wanf39160b2009-09-04 18:30:25 +00006995
6996 EXPECT_EQ(listener, listeners.Release(listener));
6997 EXPECT_TRUE(listeners.default_xml_generator() == NULL);
6998 EXPECT_FALSE(is_destroyed);
6999
7000 // Broadcasting events now should not affect default_xml_generator.
zhanyong.wanf6d087b2009-09-30 20:23:50 +00007001 TestEventListenersAccessor::GetRepeater(&listeners)->OnTestProgramStart(
zhanyong.wanf39160b2009-09-04 18:30:25 +00007002 *UnitTest::GetInstance());
7003 EXPECT_EQ(0, on_start_counter);
7004 }
7005 // Destroying the list should not affect the listener now, too.
7006 EXPECT_FALSE(is_destroyed);
7007 delete listener;
7008}
zhanyong.wan1618bb42010-04-13 04:40:32 +00007009
7010// Sanity tests to ensure that the alternative, verbose spellings of
7011// some of the macros work. We don't test them thoroughly as that
7012// would be quite involved. Since their implementations are
7013// straightforward, and they are rarely used, we'll just rely on the
7014// users to tell us when they are broken.
7015GTEST_TEST(AlternativeNameTest, Works) { // GTEST_TEST is the same as TEST.
7016 GTEST_SUCCEED() << "OK"; // GTEST_SUCCEED is the same as SUCCEED.
7017
7018 // GTEST_FAIL is the same as FAIL.
7019 EXPECT_FATAL_FAILURE(GTEST_FAIL() << "An expected failure",
7020 "An expected failure");
zhanyong.wan0bfb5632010-09-15 04:56:58 +00007021
7022 // GTEST_ASSERT_XY is the same as ASSERT_XY.
7023
7024 GTEST_ASSERT_EQ(0, 0);
7025 EXPECT_FATAL_FAILURE(GTEST_ASSERT_EQ(0, 1) << "An expected failure",
7026 "An expected failure");
7027 EXPECT_FATAL_FAILURE(GTEST_ASSERT_EQ(1, 0) << "An expected failure",
7028 "An expected failure");
7029
7030 GTEST_ASSERT_NE(0, 1);
7031 GTEST_ASSERT_NE(1, 0);
7032 EXPECT_FATAL_FAILURE(GTEST_ASSERT_NE(0, 0) << "An expected failure",
7033 "An expected failure");
7034
7035 GTEST_ASSERT_LE(0, 0);
7036 GTEST_ASSERT_LE(0, 1);
7037 EXPECT_FATAL_FAILURE(GTEST_ASSERT_LE(1, 0) << "An expected failure",
7038 "An expected failure");
7039
7040 GTEST_ASSERT_LT(0, 1);
7041 EXPECT_FATAL_FAILURE(GTEST_ASSERT_LT(0, 0) << "An expected failure",
7042 "An expected failure");
7043 EXPECT_FATAL_FAILURE(GTEST_ASSERT_LT(1, 0) << "An expected failure",
7044 "An expected failure");
7045
7046 GTEST_ASSERT_GE(0, 0);
7047 GTEST_ASSERT_GE(1, 0);
7048 EXPECT_FATAL_FAILURE(GTEST_ASSERT_GE(0, 1) << "An expected failure",
7049 "An expected failure");
7050
7051 GTEST_ASSERT_GT(1, 0);
7052 EXPECT_FATAL_FAILURE(GTEST_ASSERT_GT(0, 1) << "An expected failure",
7053 "An expected failure");
7054 EXPECT_FATAL_FAILURE(GTEST_ASSERT_GT(1, 1) << "An expected failure",
7055 "An expected failure");
zhanyong.wan1618bb42010-04-13 04:40:32 +00007056}
zhanyong.wan678f92b2010-05-10 17:11:58 +00007057
7058// Tests for internal utilities necessary for implementation of the universal
7059// printing.
7060// TODO(vladl@google.com): Find a better home for them.
7061
7062class ConversionHelperBase {};
7063class ConversionHelperDerived : public ConversionHelperBase {};
7064
7065// Tests that IsAProtocolMessage<T>::value is a compile-time constant.
7066TEST(IsAProtocolMessageTest, ValueIsCompileTimeConstant) {
7067 GTEST_COMPILE_ASSERT_(IsAProtocolMessage<ProtocolMessage>::value,
7068 const_true);
7069 GTEST_COMPILE_ASSERT_(!IsAProtocolMessage<int>::value, const_false);
7070}
7071
7072// Tests that IsAProtocolMessage<T>::value is true when T is
zhanyong.wan5d0c3dc2010-08-31 18:21:13 +00007073// proto2::Message or a sub-class of it.
zhanyong.wan678f92b2010-05-10 17:11:58 +00007074TEST(IsAProtocolMessageTest, ValueIsTrueWhenTypeIsAProtocolMessage) {
7075 EXPECT_TRUE(IsAProtocolMessage< ::proto2::Message>::value);
7076 EXPECT_TRUE(IsAProtocolMessage<ProtocolMessage>::value);
zhanyong.wan678f92b2010-05-10 17:11:58 +00007077}
7078
7079// Tests that IsAProtocolMessage<T>::value is false when T is neither
7080// ProtocolMessage nor a sub-class of it.
7081TEST(IsAProtocolMessageTest, ValueIsFalseWhenTypeIsNotAProtocolMessage) {
7082 EXPECT_FALSE(IsAProtocolMessage<int>::value);
7083 EXPECT_FALSE(IsAProtocolMessage<const ConversionHelperBase>::value);
7084}
7085
7086// Tests that CompileAssertTypesEqual compiles when the type arguments are
7087// equal.
7088TEST(CompileAssertTypesEqual, CompilesWhenTypesAreEqual) {
7089 CompileAssertTypesEqual<void, void>();
7090 CompileAssertTypesEqual<int*, int*>();
7091}
7092
7093// Tests that RemoveReference does not affect non-reference types.
7094TEST(RemoveReferenceTest, DoesNotAffectNonReferenceType) {
7095 CompileAssertTypesEqual<int, RemoveReference<int>::type>();
7096 CompileAssertTypesEqual<const char, RemoveReference<const char>::type>();
7097}
7098
7099// Tests that RemoveReference removes reference from reference types.
7100TEST(RemoveReferenceTest, RemovesReference) {
7101 CompileAssertTypesEqual<int, RemoveReference<int&>::type>();
7102 CompileAssertTypesEqual<const char, RemoveReference<const char&>::type>();
7103}
7104
7105// Tests GTEST_REMOVE_REFERENCE_.
7106
7107template <typename T1, typename T2>
7108void TestGTestRemoveReference() {
7109 CompileAssertTypesEqual<T1, GTEST_REMOVE_REFERENCE_(T2)>();
7110}
7111
7112TEST(RemoveReferenceTest, MacroVersion) {
7113 TestGTestRemoveReference<int, int>();
7114 TestGTestRemoveReference<const char, const char&>();
7115}
7116
7117
7118// Tests that RemoveConst does not affect non-const types.
7119TEST(RemoveConstTest, DoesNotAffectNonConstType) {
7120 CompileAssertTypesEqual<int, RemoveConst<int>::type>();
7121 CompileAssertTypesEqual<char&, RemoveConst<char&>::type>();
7122}
7123
7124// Tests that RemoveConst removes const from const types.
7125TEST(RemoveConstTest, RemovesConst) {
7126 CompileAssertTypesEqual<int, RemoveConst<const int>::type>();
7127 CompileAssertTypesEqual<char[2], RemoveConst<const char[2]>::type>();
7128 CompileAssertTypesEqual<char[2][3], RemoveConst<const char[2][3]>::type>();
7129}
7130
7131// Tests GTEST_REMOVE_CONST_.
7132
7133template <typename T1, typename T2>
7134void TestGTestRemoveConst() {
7135 CompileAssertTypesEqual<T1, GTEST_REMOVE_CONST_(T2)>();
7136}
7137
7138TEST(RemoveConstTest, MacroVersion) {
7139 TestGTestRemoveConst<int, int>();
7140 TestGTestRemoveConst<double&, double&>();
7141 TestGTestRemoveConst<char, const char>();
7142}
7143
zhanyong.wanc3ad6902010-05-17 19:31:00 +00007144// Tests GTEST_REMOVE_REFERENCE_AND_CONST_.
7145
7146template <typename T1, typename T2>
7147void TestGTestRemoveReferenceAndConst() {
7148 CompileAssertTypesEqual<T1, GTEST_REMOVE_REFERENCE_AND_CONST_(T2)>();
7149}
7150
7151TEST(RemoveReferenceToConstTest, Works) {
7152 TestGTestRemoveReferenceAndConst<int, int>();
7153 TestGTestRemoveReferenceAndConst<double, double&>();
7154 TestGTestRemoveReferenceAndConst<char, const char>();
7155 TestGTestRemoveReferenceAndConst<char, const char&>();
7156 TestGTestRemoveReferenceAndConst<const char*, const char*>();
7157}
7158
zhanyong.wan678f92b2010-05-10 17:11:58 +00007159// Tests that AddReference does not affect reference types.
7160TEST(AddReferenceTest, DoesNotAffectReferenceType) {
7161 CompileAssertTypesEqual<int&, AddReference<int&>::type>();
7162 CompileAssertTypesEqual<const char&, AddReference<const char&>::type>();
7163}
7164
7165// Tests that AddReference adds reference to non-reference types.
7166TEST(AddReferenceTest, AddsReference) {
7167 CompileAssertTypesEqual<int&, AddReference<int>::type>();
7168 CompileAssertTypesEqual<const char&, AddReference<const char>::type>();
7169}
7170
7171// Tests GTEST_ADD_REFERENCE_.
7172
7173template <typename T1, typename T2>
7174void TestGTestAddReference() {
7175 CompileAssertTypesEqual<T1, GTEST_ADD_REFERENCE_(T2)>();
7176}
7177
7178TEST(AddReferenceTest, MacroVersion) {
7179 TestGTestAddReference<int&, int>();
7180 TestGTestAddReference<const char&, const char&>();
7181}
7182
7183// Tests GTEST_REFERENCE_TO_CONST_.
7184
7185template <typename T1, typename T2>
7186void TestGTestReferenceToConst() {
7187 CompileAssertTypesEqual<T1, GTEST_REFERENCE_TO_CONST_(T2)>();
7188}
7189
7190TEST(GTestReferenceToConstTest, Works) {
7191 TestGTestReferenceToConst<const char&, char>();
7192 TestGTestReferenceToConst<const int&, const int>();
7193 TestGTestReferenceToConst<const double&, double>();
jgm@google.com03c31492012-11-15 15:47:38 +00007194 TestGTestReferenceToConst<const std::string&, const std::string&>();
zhanyong.wan678f92b2010-05-10 17:11:58 +00007195}
7196
7197// Tests that ImplicitlyConvertible<T1, T2>::value is a compile-time constant.
7198TEST(ImplicitlyConvertibleTest, ValueIsCompileTimeConstant) {
7199 GTEST_COMPILE_ASSERT_((ImplicitlyConvertible<int, int>::value), const_true);
7200 GTEST_COMPILE_ASSERT_((!ImplicitlyConvertible<void*, int*>::value),
7201 const_false);
7202}
7203
7204// Tests that ImplicitlyConvertible<T1, T2>::value is true when T1 can
7205// be implicitly converted to T2.
7206TEST(ImplicitlyConvertibleTest, ValueIsTrueWhenConvertible) {
7207 EXPECT_TRUE((ImplicitlyConvertible<int, double>::value));
7208 EXPECT_TRUE((ImplicitlyConvertible<double, int>::value));
7209 EXPECT_TRUE((ImplicitlyConvertible<int*, void*>::value));
7210 EXPECT_TRUE((ImplicitlyConvertible<int*, const int*>::value));
7211 EXPECT_TRUE((ImplicitlyConvertible<ConversionHelperDerived&,
7212 const ConversionHelperBase&>::value));
7213 EXPECT_TRUE((ImplicitlyConvertible<const ConversionHelperBase,
7214 ConversionHelperBase>::value));
7215}
7216
7217// Tests that ImplicitlyConvertible<T1, T2>::value is false when T1
7218// cannot be implicitly converted to T2.
7219TEST(ImplicitlyConvertibleTest, ValueIsFalseWhenNotConvertible) {
7220 EXPECT_FALSE((ImplicitlyConvertible<double, int*>::value));
7221 EXPECT_FALSE((ImplicitlyConvertible<void*, int*>::value));
7222 EXPECT_FALSE((ImplicitlyConvertible<const int*, int*>::value));
7223 EXPECT_FALSE((ImplicitlyConvertible<ConversionHelperBase&,
7224 ConversionHelperDerived&>::value));
7225}
7226
7227// Tests IsContainerTest.
7228
7229class NonContainer {};
7230
7231TEST(IsContainerTestTest, WorksForNonContainer) {
7232 EXPECT_EQ(sizeof(IsNotContainer), sizeof(IsContainerTest<int>(0)));
7233 EXPECT_EQ(sizeof(IsNotContainer), sizeof(IsContainerTest<char[5]>(0)));
7234 EXPECT_EQ(sizeof(IsNotContainer), sizeof(IsContainerTest<NonContainer>(0)));
7235}
7236
7237TEST(IsContainerTestTest, WorksForContainer) {
7238 EXPECT_EQ(sizeof(IsContainer),
7239 sizeof(IsContainerTest<std::vector<bool> >(0)));
7240 EXPECT_EQ(sizeof(IsContainer),
7241 sizeof(IsContainerTest<std::map<int, double> >(0)));
7242}
7243
7244// Tests ArrayEq().
7245
7246TEST(ArrayEqTest, WorksForDegeneratedArrays) {
7247 EXPECT_TRUE(ArrayEq(5, 5L));
7248 EXPECT_FALSE(ArrayEq('a', 0));
7249}
7250
7251TEST(ArrayEqTest, WorksForOneDimensionalArrays) {
vladlosev93fed472011-11-04 17:56:23 +00007252 // Note that a and b are distinct but compatible types.
zhanyong.wan678f92b2010-05-10 17:11:58 +00007253 const int a[] = { 0, 1 };
7254 long b[] = { 0, 1 };
7255 EXPECT_TRUE(ArrayEq(a, b));
7256 EXPECT_TRUE(ArrayEq(a, 2, b));
7257
7258 b[0] = 2;
7259 EXPECT_FALSE(ArrayEq(a, b));
7260 EXPECT_FALSE(ArrayEq(a, 1, b));
7261}
7262
7263TEST(ArrayEqTest, WorksForTwoDimensionalArrays) {
7264 const char a[][3] = { "hi", "lo" };
7265 const char b[][3] = { "hi", "lo" };
7266 const char c[][3] = { "hi", "li" };
7267
7268 EXPECT_TRUE(ArrayEq(a, b));
7269 EXPECT_TRUE(ArrayEq(a, 2, b));
7270
7271 EXPECT_FALSE(ArrayEq(a, c));
7272 EXPECT_FALSE(ArrayEq(a, 2, c));
7273}
7274
7275// Tests ArrayAwareFind().
7276
7277TEST(ArrayAwareFindTest, WorksForOneDimensionalArray) {
7278 const char a[] = "hello";
7279 EXPECT_EQ(a + 4, ArrayAwareFind(a, a + 5, 'o'));
7280 EXPECT_EQ(a + 5, ArrayAwareFind(a, a + 5, 'x'));
7281}
7282
7283TEST(ArrayAwareFindTest, WorksForTwoDimensionalArray) {
7284 int a[][2] = { { 0, 1 }, { 2, 3 }, { 4, 5 } };
7285 const int b[2] = { 2, 3 };
7286 EXPECT_EQ(a + 1, ArrayAwareFind(a, a + 3, b));
7287
7288 const int c[2] = { 6, 7 };
7289 EXPECT_EQ(a + 3, ArrayAwareFind(a, a + 3, c));
7290}
7291
7292// Tests CopyArray().
7293
7294TEST(CopyArrayTest, WorksForDegeneratedArrays) {
7295 int n = 0;
7296 CopyArray('a', &n);
7297 EXPECT_EQ('a', n);
7298}
7299
7300TEST(CopyArrayTest, WorksForOneDimensionalArrays) {
7301 const char a[3] = "hi";
7302 int b[3];
zhanyong.waned1042b2011-03-05 08:04:01 +00007303#ifndef __BORLANDC__ // C++Builder cannot compile some array size deductions.
zhanyong.wan678f92b2010-05-10 17:11:58 +00007304 CopyArray(a, &b);
7305 EXPECT_TRUE(ArrayEq(a, b));
zhanyong.waned1042b2011-03-05 08:04:01 +00007306#endif
zhanyong.wan678f92b2010-05-10 17:11:58 +00007307
7308 int c[3];
7309 CopyArray(a, 3, c);
7310 EXPECT_TRUE(ArrayEq(a, c));
7311}
7312
7313TEST(CopyArrayTest, WorksForTwoDimensionalArrays) {
7314 const int a[2][3] = { { 0, 1, 2 }, { 3, 4, 5 } };
7315 int b[2][3];
zhanyong.waned1042b2011-03-05 08:04:01 +00007316#ifndef __BORLANDC__ // C++Builder cannot compile some array size deductions.
zhanyong.wan678f92b2010-05-10 17:11:58 +00007317 CopyArray(a, &b);
7318 EXPECT_TRUE(ArrayEq(a, b));
zhanyong.waned1042b2011-03-05 08:04:01 +00007319#endif
zhanyong.wan678f92b2010-05-10 17:11:58 +00007320
7321 int c[2][3];
7322 CopyArray(a, 2, c);
7323 EXPECT_TRUE(ArrayEq(a, c));
7324}
7325
7326// Tests NativeArray.
7327
7328TEST(NativeArrayTest, ConstructorFromArrayWorks) {
7329 const int a[3] = { 0, 1, 2 };
7330 NativeArray<int> na(a, 3, kReference);
7331 EXPECT_EQ(3U, na.size());
7332 EXPECT_EQ(a, na.begin());
7333}
7334
7335TEST(NativeArrayTest, CreatesAndDeletesCopyOfArrayWhenAskedTo) {
7336 typedef int Array[2];
7337 Array* a = new Array[1];
7338 (*a)[0] = 0;
7339 (*a)[1] = 1;
7340 NativeArray<int> na(*a, 2, kCopy);
7341 EXPECT_NE(*a, na.begin());
7342 delete[] a;
7343 EXPECT_EQ(0, na.begin()[0]);
7344 EXPECT_EQ(1, na.begin()[1]);
7345
7346 // We rely on the heap checker to verify that na deletes the copy of
7347 // array.
7348}
7349
7350TEST(NativeArrayTest, TypeMembersAreCorrect) {
7351 StaticAssertTypeEq<char, NativeArray<char>::value_type>();
7352 StaticAssertTypeEq<int[2], NativeArray<int[2]>::value_type>();
7353
7354 StaticAssertTypeEq<const char*, NativeArray<char>::const_iterator>();
7355 StaticAssertTypeEq<const bool(*)[2], NativeArray<bool[2]>::const_iterator>();
7356}
7357
7358TEST(NativeArrayTest, MethodsWork) {
7359 const int a[3] = { 0, 1, 2 };
7360 NativeArray<int> na(a, 3, kCopy);
7361 ASSERT_EQ(3U, na.size());
7362 EXPECT_EQ(3, na.end() - na.begin());
7363
7364 NativeArray<int>::const_iterator it = na.begin();
7365 EXPECT_EQ(0, *it);
7366 ++it;
7367 EXPECT_EQ(1, *it);
7368 it++;
7369 EXPECT_EQ(2, *it);
7370 ++it;
7371 EXPECT_EQ(na.end(), it);
7372
7373 EXPECT_TRUE(na == na);
7374
7375 NativeArray<int> na2(a, 3, kReference);
7376 EXPECT_TRUE(na == na2);
7377
7378 const int b1[3] = { 0, 1, 1 };
7379 const int b2[4] = { 0, 1, 2, 3 };
7380 EXPECT_FALSE(na == NativeArray<int>(b1, 3, kReference));
7381 EXPECT_FALSE(na == NativeArray<int>(b2, 4, kCopy));
7382}
7383
7384TEST(NativeArrayTest, WorksForTwoDimensionalArray) {
7385 const char a[2][3] = { "hi", "lo" };
7386 NativeArray<char[3]> na(a, 2, kReference);
7387 ASSERT_EQ(2U, na.size());
7388 EXPECT_EQ(a, na.begin());
7389}
zhanyong.wan9748de02010-06-08 22:51:46 +00007390
7391// Tests SkipPrefix().
7392
7393TEST(SkipPrefixTest, SkipsWhenPrefixMatches) {
7394 const char* const str = "hello";
7395
7396 const char* p = str;
7397 EXPECT_TRUE(SkipPrefix("", &p));
7398 EXPECT_EQ(str, p);
7399
7400 p = str;
7401 EXPECT_TRUE(SkipPrefix("hell", &p));
7402 EXPECT_EQ(str + 4, p);
7403}
7404
7405TEST(SkipPrefixTest, DoesNotSkipWhenPrefixDoesNotMatch) {
7406 const char* const str = "world";
7407
7408 const char* p = str;
7409 EXPECT_FALSE(SkipPrefix("W", &p));
7410 EXPECT_EQ(str, p);
7411
7412 p = str;
7413 EXPECT_FALSE(SkipPrefix("world!", &p));
7414 EXPECT_EQ(str, p);
7415}