blob: 9a64a13e45e19fd014fa25ab5377ae931ff5a405 [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
35#include <gtest/gtest.h>
36#include <gtest/gtest-spi.h>
37
38// Indicates that this translation unit is part of Google Test's
39// implementation. It must come before gtest-internal-inl.h is
40// included, or there will be a compiler error. This trick is to
41// prevent a user from accidentally including gtest-internal-inl.h in
42// his code.
43#define GTEST_IMPLEMENTATION
44#include "src/gtest-internal-inl.h"
45#undef GTEST_IMPLEMENTATION
46
47#include <stdlib.h>
48
49#ifdef GTEST_OS_LINUX
50#include <string.h>
51#include <signal.h>
52#include <sys/stat.h>
53#include <pthread.h>
54#include <unistd.h>
55#include <string>
56#include <vector>
57#endif // GTEST_OS_LINUX
58
59namespace testing {
60namespace internal {
61bool ParseInt32Flag(const char* str, const char* flag, Int32* value);
62} // namespace internal
63} // namespace testing
64
65using testing::internal::ParseInt32Flag;
66
67namespace testing {
68
69GTEST_DECLARE_string(output);
70GTEST_DECLARE_string(color);
71
72namespace internal {
73bool ShouldUseColor(bool stdout_is_tty);
74} // namespace internal
75} // namespace testing
76
77using testing::GTEST_FLAG(color);
78using testing::ScopedFakeTestPartResultReporter;
79using testing::TestPartResult;
80using testing::TestPartResultArray;
81using testing::UnitTest;
82using testing::internal::AppendUserMessage;
83using testing::internal::EqFailure;
84using testing::internal::Int32;
85using testing::internal::List;
86using testing::internal::OsStackTraceGetter;
87using testing::internal::OsStackTraceGetterInterface;
88using testing::internal::ShouldUseColor;
89using testing::internal::StreamableToString;
90using testing::internal::String;
91using testing::internal::TestProperty;
92using testing::internal::TestResult;
93using testing::internal::ToUtf8String;
94using testing::internal::UnitTestImpl;
95using testing::internal::UnitTestOptions;
96
97// This line tests that we can define tests in an unnamed namespace.
98namespace {
99
100#ifndef __SYMBIAN32__
101// NULL testing does not work with Symbian compilers.
102
103// Tests that GTEST_IS_NULL_LITERAL(x) is true when x is a null
104// pointer literal.
105TEST(NullLiteralTest, IsTrueForNullLiterals) {
106 EXPECT_TRUE(GTEST_IS_NULL_LITERAL(NULL));
107 EXPECT_TRUE(GTEST_IS_NULL_LITERAL(0));
108 EXPECT_TRUE(GTEST_IS_NULL_LITERAL(1 - 1));
109 EXPECT_TRUE(GTEST_IS_NULL_LITERAL(0U));
110 EXPECT_TRUE(GTEST_IS_NULL_LITERAL(0L));
111 EXPECT_TRUE(GTEST_IS_NULL_LITERAL(false));
112 EXPECT_TRUE(GTEST_IS_NULL_LITERAL(true && false));
113}
114
115// Tests that GTEST_IS_NULL_LITERAL(x) is false when x is not a null
116// pointer literal.
117TEST(NullLiteralTest, IsFalseForNonNullLiterals) {
118 EXPECT_FALSE(GTEST_IS_NULL_LITERAL(1));
119 EXPECT_FALSE(GTEST_IS_NULL_LITERAL(0.0));
120 EXPECT_FALSE(GTEST_IS_NULL_LITERAL('a'));
121 EXPECT_FALSE(GTEST_IS_NULL_LITERAL(static_cast<void*>(NULL)));
122}
123
124#endif // __SYMBIAN32__
125// Tests ToUtf8String().
126
127// Tests that the NUL character L'\0' is encoded correctly.
128TEST(ToUtf8StringTest, CanEncodeNul) {
129 EXPECT_STREQ("", ToUtf8String(L'\0').c_str());
130}
131
132// Tests that ASCII characters are encoded correctly.
133TEST(ToUtf8StringTest, CanEncodeAscii) {
134 EXPECT_STREQ("a", ToUtf8String(L'a').c_str());
135 EXPECT_STREQ("Z", ToUtf8String(L'Z').c_str());
136 EXPECT_STREQ("&", ToUtf8String(L'&').c_str());
137 EXPECT_STREQ("\x7F", ToUtf8String(L'\x7F').c_str());
138}
139
140// Tests that Unicode code-points that have 8 to 11 bits are encoded
141// as 110xxxxx 10xxxxxx.
142TEST(ToUtf8StringTest, CanEncode8To11Bits) {
143 // 000 1101 0011 => 110-00011 10-010011
144 EXPECT_STREQ("\xC3\x93", ToUtf8String(L'\xD3').c_str());
145
146 // 101 0111 0110 => 110-10101 10-110110
147 EXPECT_STREQ("\xD5\xB6", ToUtf8String(L'\x576').c_str());
148}
149
150// Tests that Unicode code-points that have 12 to 16 bits are encoded
151// as 1110xxxx 10xxxxxx 10xxxxxx.
152TEST(ToUtf8StringTest, CanEncode12To16Bits) {
153 // 0000 1000 1101 0011 => 1110-0000 10-100011 10-010011
154 EXPECT_STREQ("\xE0\xA3\x93", ToUtf8String(L'\x8D3').c_str());
155
156 // 1100 0111 0100 1101 => 1110-1100 10-011101 10-001101
157 EXPECT_STREQ("\xEC\x9D\x8D", ToUtf8String(L'\xC74D').c_str());
158}
159
160#if !defined(GTEST_OS_WINDOWS) && !defined(__SYMBIAN32__)
161
162// Tests in this group require a wchar_t to hold > 16 bits, and thus
163// are skipped on Windows and Symbian, where a wchar_t is 16-bit wide.
164
165// Tests that Unicode code-points that have 17 to 21 bits are encoded
166// as 11110xxx 10xxxxxx 10xxxxxx 10xxxxxx.
167TEST(ToUtf8StringTest, CanEncode17To21Bits) {
168 // 0 0001 0000 1000 1101 0011 => 11110-000 10-010000 10-100011 10-010011
169 EXPECT_STREQ("\xF0\x90\xA3\x93", ToUtf8String(L'\x108D3').c_str());
170
171 // 1 0111 1000 0110 0011 0100 => 11110-101 10-111000 10-011000 10-110100
172 EXPECT_STREQ("\xF5\xB8\x98\xB4", ToUtf8String(L'\x178634').c_str());
173}
174
175// Tests that encoding an invalid code-point generates the expected result.
176TEST(ToUtf8StringTest, CanEncodeInvalidCodePoint) {
177 EXPECT_STREQ("(Invalid Unicode 0x1234ABCD)",
178 ToUtf8String(L'\x1234ABCD').c_str());
179}
180
181#endif // Windows or Symbian
182
183// Tests the List template class.
184
185// Tests List::PushFront().
186TEST(ListTest, PushFront) {
187 List<int> a;
188 ASSERT_EQ(0u, a.size());
189
190 // Calls PushFront() on an empty list.
191 a.PushFront(1);
192 ASSERT_EQ(1u, a.size());
193 EXPECT_EQ(1, a.Head()->element());
194 ASSERT_EQ(a.Head(), a.Last());
195
196 // Calls PushFront() on a singleton list.
197 a.PushFront(2);
198 ASSERT_EQ(2u, a.size());
199 EXPECT_EQ(2, a.Head()->element());
200 EXPECT_EQ(1, a.Last()->element());
201
202 // Calls PushFront() on a list with more than one elements.
203 a.PushFront(3);
204 ASSERT_EQ(3u, a.size());
205 EXPECT_EQ(3, a.Head()->element());
206 EXPECT_EQ(2, a.Head()->next()->element());
207 EXPECT_EQ(1, a.Last()->element());
208}
209
210// Tests List::PopFront().
211TEST(ListTest, PopFront) {
212 List<int> a;
213
214 // Popping on an empty list should fail.
215 EXPECT_FALSE(a.PopFront(NULL));
216
217 // Popping again on an empty list should fail, and the result element
218 // shouldn't be overwritten.
219 int element = 1;
220 EXPECT_FALSE(a.PopFront(&element));
221 EXPECT_EQ(1, element);
222
223 a.PushFront(2);
224 a.PushFront(3);
225
226 // PopFront() should pop the element in the front of the list.
227 EXPECT_TRUE(a.PopFront(&element));
228 EXPECT_EQ(3, element);
229
230 // After popping the last element, the list should be empty.
231 EXPECT_TRUE(a.PopFront(NULL));
232 EXPECT_EQ(0u, a.size());
233}
234
235// Tests inserting at the beginning using List::InsertAfter().
236TEST(ListTest, InsertAfterAtBeginning) {
237 List<int> a;
238 ASSERT_EQ(0u, a.size());
239
240 // Inserts into an empty list.
241 a.InsertAfter(NULL, 1);
242 ASSERT_EQ(1u, a.size());
243 EXPECT_EQ(1, a.Head()->element());
244 ASSERT_EQ(a.Head(), a.Last());
245
246 // Inserts at the beginning of a singleton list.
247 a.InsertAfter(NULL, 2);
248 ASSERT_EQ(2u, a.size());
249 EXPECT_EQ(2, a.Head()->element());
250 EXPECT_EQ(1, a.Last()->element());
251
252 // Inserts at the beginning of a list with more than one elements.
253 a.InsertAfter(NULL, 3);
254 ASSERT_EQ(3u, a.size());
255 EXPECT_EQ(3, a.Head()->element());
256 EXPECT_EQ(2, a.Head()->next()->element());
257 EXPECT_EQ(1, a.Last()->element());
258}
259
260// Tests inserting at a location other than the beginning using
261// List::InsertAfter().
262TEST(ListTest, InsertAfterNotAtBeginning) {
263 // Prepares a singleton list.
264 List<int> a;
265 a.PushBack(1);
266
267 // Inserts at the end of a singleton list.
268 a.InsertAfter(a.Last(), 2);
269 ASSERT_EQ(2u, a.size());
270 EXPECT_EQ(1, a.Head()->element());
271 EXPECT_EQ(2, a.Last()->element());
272
273 // Inserts at the end of a list with more than one elements.
274 a.InsertAfter(a.Last(), 3);
275 ASSERT_EQ(3u, a.size());
276 EXPECT_EQ(1, a.Head()->element());
277 EXPECT_EQ(2, a.Head()->next()->element());
278 EXPECT_EQ(3, a.Last()->element());
279
280 // Inserts in the middle of a list.
281 a.InsertAfter(a.Head(), 4);
282 ASSERT_EQ(4u, a.size());
283 EXPECT_EQ(1, a.Head()->element());
284 EXPECT_EQ(4, a.Head()->next()->element());
285 EXPECT_EQ(2, a.Head()->next()->next()->element());
286 EXPECT_EQ(3, a.Last()->element());
287}
288
289
290// Tests the String class.
291
292// Tests String's constructors.
293TEST(StringTest, Constructors) {
294 // Default ctor.
295 String s1;
296 EXPECT_EQ(NULL, s1.c_str());
297
298 // Implicitly constructs from a C-string.
299 String s2 = "Hi";
300 EXPECT_STREQ("Hi", s2.c_str());
301
302 // Constructs from a C-string and a length.
303 String s3("hello", 3);
304 EXPECT_STREQ("hel", s3.c_str());
305
306 // Copy ctor.
307 String s4 = s3;
308 EXPECT_STREQ("hel", s4.c_str());
309}
310
311// Tests String::ShowCString().
312TEST(StringTest, ShowCString) {
313 EXPECT_STREQ("(null)", String::ShowCString(NULL));
314 EXPECT_STREQ("", String::ShowCString(""));
315 EXPECT_STREQ("foo", String::ShowCString("foo"));
316}
317
318// Tests String::ShowCStringQuoted().
319TEST(StringTest, ShowCStringQuoted) {
320 EXPECT_STREQ("(null)",
321 String::ShowCStringQuoted(NULL).c_str());
322 EXPECT_STREQ("\"\"",
323 String::ShowCStringQuoted("").c_str());
324 EXPECT_STREQ("\"foo\"",
325 String::ShowCStringQuoted("foo").c_str());
326}
327
328// Tests String::operator==().
329TEST(StringTest, Equals) {
330 const String null(NULL);
331 EXPECT_TRUE(null == NULL); // NOLINT
332 EXPECT_FALSE(null == ""); // NOLINT
333 EXPECT_FALSE(null == "bar"); // NOLINT
334
335 const String empty("");
336 EXPECT_FALSE(empty == NULL); // NOLINT
337 EXPECT_TRUE(empty == ""); // NOLINT
338 EXPECT_FALSE(empty == "bar"); // NOLINT
339
340 const String foo("foo");
341 EXPECT_FALSE(foo == NULL); // NOLINT
342 EXPECT_FALSE(foo == ""); // NOLINT
343 EXPECT_FALSE(foo == "bar"); // NOLINT
344 EXPECT_TRUE(foo == "foo"); // NOLINT
345}
346
347// Tests String::operator!=().
348TEST(StringTest, NotEquals) {
349 const String null(NULL);
350 EXPECT_FALSE(null != NULL); // NOLINT
351 EXPECT_TRUE(null != ""); // NOLINT
352 EXPECT_TRUE(null != "bar"); // NOLINT
353
354 const String empty("");
355 EXPECT_TRUE(empty != NULL); // NOLINT
356 EXPECT_FALSE(empty != ""); // NOLINT
357 EXPECT_TRUE(empty != "bar"); // NOLINT
358
359 const String foo("foo");
360 EXPECT_TRUE(foo != NULL); // NOLINT
361 EXPECT_TRUE(foo != ""); // NOLINT
362 EXPECT_TRUE(foo != "bar"); // NOLINT
363 EXPECT_FALSE(foo != "foo"); // NOLINT
364}
365
366// Tests String::EndsWith().
367TEST(StringTest, EndsWith) {
368 EXPECT_TRUE(String("foobar").EndsWith("bar"));
369 EXPECT_TRUE(String("foobar").EndsWith(""));
370 EXPECT_TRUE(String("").EndsWith(""));
371
372 EXPECT_FALSE(String("foobar").EndsWith("foo"));
373 EXPECT_FALSE(String("").EndsWith("foo"));
374}
375
376// Tests String::EndsWithCaseInsensitive().
377TEST(StringTest, EndsWithCaseInsensitive) {
378 EXPECT_TRUE(String("foobar").EndsWithCaseInsensitive("BAR"));
379 EXPECT_TRUE(String("foobaR").EndsWithCaseInsensitive("bar"));
380 EXPECT_TRUE(String("foobar").EndsWithCaseInsensitive(""));
381 EXPECT_TRUE(String("").EndsWithCaseInsensitive(""));
382
383 EXPECT_FALSE(String("Foobar").EndsWithCaseInsensitive("foo"));
384 EXPECT_FALSE(String("foobar").EndsWithCaseInsensitive("Foo"));
385 EXPECT_FALSE(String("").EndsWithCaseInsensitive("foo"));
386}
387
388// Tests that NULL can be assigned to a String.
389TEST(StringTest, CanBeAssignedNULL) {
390 const String src(NULL);
391 String dest;
392
393 dest = src;
394 EXPECT_STREQ(NULL, dest.c_str());
395}
396
397// Tests that the empty string "" can be assigned to a String.
398TEST(StringTest, CanBeAssignedEmpty) {
399 const String src("");
400 String dest;
401
402 dest = src;
403 EXPECT_STREQ("", dest.c_str());
404}
405
406// Tests that a non-empty string can be assigned to a String.
407TEST(StringTest, CanBeAssignedNonEmpty) {
408 const String src("hello");
409 String dest;
410
411 dest = src;
412 EXPECT_STREQ("hello", dest.c_str());
413}
414
415// Tests that a String can be assigned to itself.
416TEST(StringTest, CanBeAssignedSelf) {
417 String dest("hello");
418
419 dest = dest;
420 EXPECT_STREQ("hello", dest.c_str());
421}
422
423#ifdef GTEST_OS_WINDOWS
424
425// Tests String::ShowWideCString().
426TEST(StringTest, ShowWideCString) {
427 EXPECT_STREQ("(null)",
428 String::ShowWideCString(NULL).c_str());
429 EXPECT_STREQ("", String::ShowWideCString(L"").c_str());
430 EXPECT_STREQ("foo", String::ShowWideCString(L"foo").c_str());
431}
432
433// Tests String::ShowWideCStringQuoted().
434TEST(StringTest, ShowWideCStringQuoted) {
435 EXPECT_STREQ("(null)",
436 String::ShowWideCStringQuoted(NULL).c_str());
437 EXPECT_STREQ("L\"\"",
438 String::ShowWideCStringQuoted(L"").c_str());
439 EXPECT_STREQ("L\"foo\"",
440 String::ShowWideCStringQuoted(L"foo").c_str());
441}
442
443#endif // GTEST_OS_WINDOWS
444
445// Tests TestProperty construction.
446TEST(TestPropertyTest, StringValue) {
447 TestProperty property("key", "1");
448 EXPECT_STREQ("key", property.key());
449 EXPECT_STREQ("1", property.value());
450}
451
452// Tests TestProperty replacing a value.
453TEST(TestPropertyTest, ReplaceStringValue) {
454 TestProperty property("key", "1");
455 EXPECT_STREQ("1", property.value());
456 property.SetValue("2");
457 EXPECT_STREQ("2", property.value());
458}
459
460// Tests the TestPartResult class.
461
462// The test fixture for testing TestPartResult.
463class TestPartResultTest : public testing::Test {
464 protected:
465 TestPartResultTest()
466 : r1_(testing::TPRT_SUCCESS,
467 "foo/bar.cc",
468 10,
469 "Success!"),
470 r2_(testing::TPRT_NONFATAL_FAILURE,
471 "foo/bar.cc",
472 -1,
473 "Failure!"),
474 r3_(testing::TPRT_FATAL_FAILURE,
475 NULL,
476 -1,
477 "Failure!") {}
478
479 TestPartResult r1_, r2_, r3_;
480};
481
482// Tests TestPartResult::type()
483TEST_F(TestPartResultTest, type) {
484 EXPECT_EQ(testing::TPRT_SUCCESS, r1_.type());
485 EXPECT_EQ(testing::TPRT_NONFATAL_FAILURE, r2_.type());
486 EXPECT_EQ(testing::TPRT_FATAL_FAILURE, r3_.type());
487}
488
489// Tests TestPartResult::file_name()
490TEST_F(TestPartResultTest, file_name) {
491 EXPECT_STREQ("foo/bar.cc", r1_.file_name());
492 EXPECT_STREQ(NULL, r3_.file_name());
493}
494
495// Tests TestPartResult::line_number()
496TEST_F(TestPartResultTest, line_number) {
497 EXPECT_EQ(10, r1_.line_number());
498 EXPECT_EQ(-1, r2_.line_number());
499}
500
501// Tests TestPartResult::message()
502TEST_F(TestPartResultTest, message) {
503 EXPECT_STREQ("Success!", r1_.message());
504}
505
506// Tests TestPartResult::passed()
507TEST_F(TestPartResultTest, Passed) {
508 EXPECT_TRUE(r1_.passed());
509 EXPECT_FALSE(r2_.passed());
510 EXPECT_FALSE(r3_.passed());
511}
512
513// Tests TestPartResult::failed()
514TEST_F(TestPartResultTest, Failed) {
515 EXPECT_FALSE(r1_.failed());
516 EXPECT_TRUE(r2_.failed());
517 EXPECT_TRUE(r3_.failed());
518}
519
520// Tests TestPartResult::fatally_failed()
521TEST_F(TestPartResultTest, FatallyFailed) {
522 EXPECT_FALSE(r1_.fatally_failed());
523 EXPECT_FALSE(r2_.fatally_failed());
524 EXPECT_TRUE(r3_.fatally_failed());
525}
526
527// Tests TestPartResult::nonfatally_failed()
528TEST_F(TestPartResultTest, NonfatallyFailed) {
529 EXPECT_FALSE(r1_.nonfatally_failed());
530 EXPECT_TRUE(r2_.nonfatally_failed());
531 EXPECT_FALSE(r3_.nonfatally_failed());
532}
533
534// Tests the TestPartResultArray class.
535
536class TestPartResultArrayTest : public testing::Test {
537 protected:
538 TestPartResultArrayTest()
539 : r1_(testing::TPRT_NONFATAL_FAILURE,
540 "foo/bar.cc",
541 -1,
542 "Failure 1"),
543 r2_(testing::TPRT_FATAL_FAILURE,
544 "foo/bar.cc",
545 -1,
546 "Failure 2") {}
547
548 const TestPartResult r1_, r2_;
549};
550
551// Tests that TestPartResultArray initially has size 0.
552TEST_F(TestPartResultArrayTest, InitialSizeIsZero) {
553 TestPartResultArray results;
554 EXPECT_EQ(0, results.size());
555}
556
557// Tests that TestPartResultArray contains the given TestPartResult
558// after one Append() operation.
559TEST_F(TestPartResultArrayTest, ContainsGivenResultAfterAppend) {
560 TestPartResultArray results;
561 results.Append(r1_);
562 EXPECT_EQ(1, results.size());
563 EXPECT_STREQ("Failure 1", results.GetTestPartResult(0).message());
564}
565
566// Tests that TestPartResultArray contains the given TestPartResults
567// after two Append() operations.
568TEST_F(TestPartResultArrayTest, ContainsGivenResultsAfterTwoAppends) {
569 TestPartResultArray results;
570 results.Append(r1_);
571 results.Append(r2_);
572 EXPECT_EQ(2, results.size());
573 EXPECT_STREQ("Failure 1", results.GetTestPartResult(0).message());
574 EXPECT_STREQ("Failure 2", results.GetTestPartResult(1).message());
575}
576
577void ScopedFakeTestPartResultReporterTestHelper() {
578 FAIL() << "Expected fatal failure.";
579}
580
581// Tests that ScopedFakeTestPartResultReporter intercepts test
582// failures.
583TEST(ScopedFakeTestPartResultReporterTest, InterceptsTestFailures) {
584 TestPartResultArray results;
585 {
586 ScopedFakeTestPartResultReporter reporter(&results);
587 ADD_FAILURE() << "Expected non-fatal failure.";
588 ScopedFakeTestPartResultReporterTestHelper();
589 }
590
591 EXPECT_EQ(2, results.size());
592 EXPECT_TRUE(results.GetTestPartResult(0).nonfatally_failed());
593 EXPECT_TRUE(results.GetTestPartResult(1).fatally_failed());
594}
595
596// Tests the TestResult class
597
598// The test fixture for testing TestResult.
599class TestResultTest : public testing::Test {
600 protected:
601 typedef List<TestPartResult> TPRList;
602
603 // We make use of 2 TestPartResult objects,
604 TestPartResult * pr1, * pr2;
605
606 // ... and 3 TestResult objects.
607 TestResult * r0, * r1, * r2;
608
609 virtual void SetUp() {
610 // pr1 is for success.
611 pr1 = new TestPartResult(testing::TPRT_SUCCESS,
612 "foo/bar.cc",
613 10,
614 "Success!");
615
616 // pr2 is for fatal failure.
617 pr2 = new TestPartResult(testing::TPRT_FATAL_FAILURE,
618 "foo/bar.cc",
619 -1, // This line number means "unknown"
620 "Failure!");
621
622 // Creates the TestResult objects.
623 r0 = new TestResult();
624 r1 = new TestResult();
625 r2 = new TestResult();
626
627 // In order to test TestResult, we need to modify its internal
628 // state, in particular the TestPartResult list it holds.
629 // test_part_results() returns a const reference to this list.
630 // We cast it to a non-const object s.t. it can be modified (yes,
631 // this is a hack).
632 TPRList * list1, * list2;
633 list1 = const_cast<List<TestPartResult> *>(
634 & r1->test_part_results());
635 list2 = const_cast<List<TestPartResult> *>(
636 & r2->test_part_results());
637
638 // r0 is an empty TestResult.
639
640 // r1 contains a single SUCCESS TestPartResult.
641 list1->PushBack(*pr1);
642
643 // r2 contains a SUCCESS, and a FAILURE.
644 list2->PushBack(*pr1);
645 list2->PushBack(*pr2);
646 }
647
648 virtual void TearDown() {
649 delete pr1;
650 delete pr2;
651
652 delete r0;
653 delete r1;
654 delete r2;
655 }
656};
657
658// Tests TestResult::test_part_results()
659TEST_F(TestResultTest, test_part_results) {
660 ASSERT_EQ(0u, r0->test_part_results().size());
661 ASSERT_EQ(1u, r1->test_part_results().size());
662 ASSERT_EQ(2u, r2->test_part_results().size());
663}
664
665// Tests TestResult::successful_part_count()
666TEST_F(TestResultTest, successful_part_count) {
667 ASSERT_EQ(0u, r0->successful_part_count());
668 ASSERT_EQ(1u, r1->successful_part_count());
669 ASSERT_EQ(1u, r2->successful_part_count());
670}
671
672// Tests TestResult::failed_part_count()
673TEST_F(TestResultTest, failed_part_count) {
674 ASSERT_EQ(0u, r0->failed_part_count());
675 ASSERT_EQ(0u, r1->failed_part_count());
676 ASSERT_EQ(1u, r2->failed_part_count());
677}
678
679// Tests TestResult::total_part_count()
680TEST_F(TestResultTest, total_part_count) {
681 ASSERT_EQ(0u, r0->total_part_count());
682 ASSERT_EQ(1u, r1->total_part_count());
683 ASSERT_EQ(2u, r2->total_part_count());
684}
685
686// Tests TestResult::Passed()
687TEST_F(TestResultTest, Passed) {
688 ASSERT_TRUE(r0->Passed());
689 ASSERT_TRUE(r1->Passed());
690 ASSERT_FALSE(r2->Passed());
691}
692
693// Tests TestResult::Failed()
694TEST_F(TestResultTest, Failed) {
695 ASSERT_FALSE(r0->Failed());
696 ASSERT_FALSE(r1->Failed());
697 ASSERT_TRUE(r2->Failed());
698}
699
700// Tests TestResult::test_properties() has no properties when none are added.
701TEST(TestResultPropertyTest, NoPropertiesFoundWhenNoneAreAdded) {
702 TestResult test_result;
703 ASSERT_EQ(0u, test_result.test_properties().size());
704}
705
706// Tests TestResult::test_properties() has the expected property when added.
707TEST(TestResultPropertyTest, OnePropertyFoundWhenAdded) {
708 TestResult test_result;
709 TestProperty property("key_1", "1");
710 test_result.RecordProperty(property);
711 const List<TestProperty>& properties = test_result.test_properties();
712 ASSERT_EQ(1u, properties.size());
713 TestProperty actual_property = properties.Head()->element();
714 EXPECT_STREQ("key_1", actual_property.key());
715 EXPECT_STREQ("1", actual_property.value());
716}
717
718// Tests TestResult::test_properties() has multiple properties when added.
719TEST(TestResultPropertyTest, MultiplePropertiesFoundWhenAdded) {
720 TestResult test_result;
721 TestProperty property_1("key_1", "1");
722 TestProperty property_2("key_2", "2");
723 test_result.RecordProperty(property_1);
724 test_result.RecordProperty(property_2);
725 const List<TestProperty>& properties = test_result.test_properties();
726 ASSERT_EQ(2u, properties.size());
727 TestProperty actual_property_1 = properties.Head()->element();
728 EXPECT_STREQ("key_1", actual_property_1.key());
729 EXPECT_STREQ("1", actual_property_1.value());
730
731 TestProperty actual_property_2 = properties.Last()->element();
732 EXPECT_STREQ("key_2", actual_property_2.key());
733 EXPECT_STREQ("2", actual_property_2.value());
734}
735
736// Tests TestResult::test_properties() overrides values for duplicate keys.
737TEST(TestResultPropertyTest, OverridesValuesForDuplicateKeys) {
738 TestResult test_result;
739 TestProperty property_1_1("key_1", "1");
740 TestProperty property_2_1("key_2", "2");
741 TestProperty property_1_2("key_1", "12");
742 TestProperty property_2_2("key_2", "22");
743 test_result.RecordProperty(property_1_1);
744 test_result.RecordProperty(property_2_1);
745 test_result.RecordProperty(property_1_2);
746 test_result.RecordProperty(property_2_2);
747
748 const List<TestProperty>& properties = test_result.test_properties();
749 ASSERT_EQ(2u, properties.size());
750 TestProperty actual_property_1 = properties.Head()->element();
751 EXPECT_STREQ("key_1", actual_property_1.key());
752 EXPECT_STREQ("12", actual_property_1.value());
753
754 TestProperty actual_property_2 = properties.Last()->element();
755 EXPECT_STREQ("key_2", actual_property_2.key());
756 EXPECT_STREQ("22", actual_property_2.value());
757}
758
759// When a property using a reserved key is supplied to this function, it tests
760// that a non-fatal failure is added, a fatal failure is not added, and that the
761// property is not recorded.
762void ExpectNonFatalFailureRecordingPropertyWithReservedKey(const char* key) {
763 TestResult test_result;
764 TestProperty property("name", "1");
765 EXPECT_NONFATAL_FAILURE(test_result.RecordProperty(property), "Reserved key");
766 ASSERT_TRUE(test_result.test_properties().IsEmpty()) << "Not recorded";
767}
768
769// Attempting to recording a property with the Reserved literal "name"
770// should add a non-fatal failure and the property should not be recorded.
771TEST(TestResultPropertyTest, AddFailureWhenUsingReservedKeyCalledName) {
772 ExpectNonFatalFailureRecordingPropertyWithReservedKey("name");
773}
774
775// Attempting to recording a property with the Reserved literal "status"
776// should add a non-fatal failure and the property should not be recorded.
777TEST(TestResultPropertyTest, AddFailureWhenUsingReservedKeyCalledStatus) {
778 ExpectNonFatalFailureRecordingPropertyWithReservedKey("status");
779}
780
781// Attempting to recording a property with the Reserved literal "time"
782// should add a non-fatal failure and the property should not be recorded.
783TEST(TestResultPropertyTest, AddFailureWhenUsingReservedKeyCalledTime) {
784 ExpectNonFatalFailureRecordingPropertyWithReservedKey("time");
785}
786
787// Attempting to recording a property with the Reserved literal "classname"
788// should add a non-fatal failure and the property should not be recorded.
789TEST(TestResultPropertyTest, AddFailureWhenUsingReservedKeyCalledClassname) {
790 ExpectNonFatalFailureRecordingPropertyWithReservedKey("classname");
791}
792
793// Tests that GTestFlagSaver works on Windows and Mac.
794
795class GTestFlagSaverTest : public testing::Test {
796 protected:
797 // Saves the Google Test flags such that we can restore them later, and
798 // then sets them to their default values. This will be called
799 // before the first test in this test case is run.
800 static void SetUpTestCase() {
801 saver_ = new testing::internal::GTestFlagSaver;
802
803 testing::GTEST_FLAG(break_on_failure) = false;
804 testing::GTEST_FLAG(catch_exceptions) = false;
805 testing::GTEST_FLAG(color) = "auto";
806 testing::GTEST_FLAG(filter) = "";
807 testing::GTEST_FLAG(list_tests) = false;
808 testing::GTEST_FLAG(output) = "";
809 testing::GTEST_FLAG(repeat) = 1;
810 }
811
812 // Restores the Google Test flags that the tests have modified. This will
813 // be called after the last test in this test case is run.
814 static void TearDownTestCase() {
815 delete saver_;
816 saver_ = NULL;
817 }
818
819 // Verifies that the Google Test flags have their default values, and then
820 // modifies each of them.
821 void VerifyAndModifyFlags() {
822 EXPECT_FALSE(testing::GTEST_FLAG(break_on_failure));
823 EXPECT_FALSE(testing::GTEST_FLAG(catch_exceptions));
824 EXPECT_STREQ("auto", testing::GTEST_FLAG(color).c_str());
825 EXPECT_STREQ("", testing::GTEST_FLAG(filter).c_str());
826 EXPECT_FALSE(testing::GTEST_FLAG(list_tests));
827 EXPECT_STREQ("", testing::GTEST_FLAG(output).c_str());
828 EXPECT_EQ(1, testing::GTEST_FLAG(repeat));
829
830 testing::GTEST_FLAG(break_on_failure) = true;
831 testing::GTEST_FLAG(catch_exceptions) = true;
832 testing::GTEST_FLAG(color) = "no";
833 testing::GTEST_FLAG(filter) = "abc";
834 testing::GTEST_FLAG(list_tests) = true;
835 testing::GTEST_FLAG(output) = "xml:foo.xml";
836 testing::GTEST_FLAG(repeat) = 100;
837 }
838 private:
839 // For saving Google Test flags during this test case.
840 static testing::internal::GTestFlagSaver* saver_;
841};
842
843testing::internal::GTestFlagSaver* GTestFlagSaverTest::saver_ = NULL;
844
845// Google Test doesn't guarantee the order of tests. The following two
846// tests are designed to work regardless of their order.
847
848// Modifies the Google Test flags in the test body.
849TEST_F(GTestFlagSaverTest, ModifyGTestFlags) {
850 VerifyAndModifyFlags();
851}
852
853// Verifies that the Google Test flags in the body of the previous test were
854// restored to their original values.
855TEST_F(GTestFlagSaverTest, VerifyGTestFlags) {
856 VerifyAndModifyFlags();
857}
858
859// Sets an environment variable with the given name to the given
860// value. If the value argument is "", unsets the environment
861// variable. The caller must ensure that both arguments are not NULL.
862static void SetEnv(const char* name, const char* value) {
863#ifdef _WIN32_WCE
864 // Environment variables are not supported on Windows CE.
865 return;
866#elif defined(GTEST_OS_WINDOWS) // If we are on Windows proper.
867 _putenv((testing::Message() << name << "=" << value).GetString().c_str());
868#else
869 if (*value == '\0') {
870 unsetenv(name);
871 } else {
872 setenv(name, value, 1);
873 }
874#endif
875}
876
877#ifndef _WIN32_WCE
878// Environment variables are not supported on Windows CE.
879
880using ::testing::internal::Int32FromGTestEnv;
881
882// Tests Int32FromGTestEnv().
883
884// Tests that Int32FromGTestEnv() returns the default value when the
885// environment variable is not set.
886TEST(Int32FromGTestEnvTest, ReturnsDefaultWhenVariableIsNotSet) {
887 SetEnv(GTEST_FLAG_PREFIX_UPPER "TEMP", "");
888 EXPECT_EQ(10, Int32FromGTestEnv("temp", 10));
889}
890
891// Tests that Int32FromGTestEnv() returns the default value when the
892// environment variable overflows as an Int32.
893TEST(Int32FromGTestEnvTest, ReturnsDefaultWhenValueOverflows) {
894 printf("(expecting 2 warnings)\n");
895
896 SetEnv(GTEST_FLAG_PREFIX_UPPER "TEMP", "12345678987654321");
897 EXPECT_EQ(20, Int32FromGTestEnv("temp", 20));
898
899 SetEnv(GTEST_FLAG_PREFIX_UPPER "TEMP", "-12345678987654321");
900 EXPECT_EQ(30, Int32FromGTestEnv("temp", 30));
901}
902
903// Tests that Int32FromGTestEnv() returns the default value when the
904// environment variable does not represent a valid decimal integer.
905TEST(Int32FromGTestEnvTest, ReturnsDefaultWhenValueIsInvalid) {
906 printf("(expecting 2 warnings)\n");
907
908 SetEnv(GTEST_FLAG_PREFIX_UPPER "TEMP", "A1");
909 EXPECT_EQ(40, Int32FromGTestEnv("temp", 40));
910
911 SetEnv(GTEST_FLAG_PREFIX_UPPER "TEMP", "12X");
912 EXPECT_EQ(50, Int32FromGTestEnv("temp", 50));
913}
914
915// Tests that Int32FromGTestEnv() parses and returns the value of the
916// environment variable when it represents a valid decimal integer in
917// the range of an Int32.
918TEST(Int32FromGTestEnvTest, ParsesAndReturnsValidValue) {
919 SetEnv(GTEST_FLAG_PREFIX_UPPER "TEMP", "123");
920 EXPECT_EQ(123, Int32FromGTestEnv("temp", 0));
921
922 SetEnv(GTEST_FLAG_PREFIX_UPPER "TEMP", "-321");
923 EXPECT_EQ(-321, Int32FromGTestEnv("temp", 0));
924}
925#endif // !defined(_WIN32_WCE)
926
927// Tests ParseInt32Flag().
928
929// Tests that ParseInt32Flag() returns false and doesn't change the
930// output value when the flag has wrong format
931TEST(ParseInt32FlagTest, ReturnsFalseForInvalidFlag) {
932 Int32 value = 123;
933 EXPECT_FALSE(ParseInt32Flag("--a=100", "b", &value));
934 EXPECT_EQ(123, value);
935
936 EXPECT_FALSE(ParseInt32Flag("a=100", "a", &value));
937 EXPECT_EQ(123, value);
938}
939
940// Tests that ParseInt32Flag() returns false and doesn't change the
941// output value when the flag overflows as an Int32.
942TEST(ParseInt32FlagTest, ReturnsDefaultWhenValueOverflows) {
943 printf("(expecting 2 warnings)\n");
944
945 Int32 value = 123;
946 EXPECT_FALSE(ParseInt32Flag("--abc=12345678987654321", "abc", &value));
947 EXPECT_EQ(123, value);
948
949 EXPECT_FALSE(ParseInt32Flag("--abc=-12345678987654321", "abc", &value));
950 EXPECT_EQ(123, value);
951}
952
953// Tests that ParseInt32Flag() returns false and doesn't change the
954// output value when the flag does not represent a valid decimal
955// integer.
956TEST(ParseInt32FlagTest, ReturnsDefaultWhenValueIsInvalid) {
957 printf("(expecting 2 warnings)\n");
958
959 Int32 value = 123;
960 EXPECT_FALSE(ParseInt32Flag("--abc=A1", "abc", &value));
961 EXPECT_EQ(123, value);
962
963 EXPECT_FALSE(ParseInt32Flag("--abc=12X", "abc", &value));
964 EXPECT_EQ(123, value);
965}
966
967// Tests that ParseInt32Flag() parses the value of the flag and
968// returns true when the flag represents a valid decimal integer in
969// the range of an Int32.
970TEST(ParseInt32FlagTest, ParsesAndReturnsValidValue) {
971 Int32 value = 123;
972 EXPECT_TRUE(ParseInt32Flag("--" GTEST_FLAG_PREFIX "abc=456", "abc", &value));
973 EXPECT_EQ(456, value);
974
975 EXPECT_TRUE(ParseInt32Flag("--" GTEST_FLAG_PREFIX "abc=-789", "abc", &value));
976 EXPECT_EQ(-789, value);
977}
978
979// For the same reason we are not explicitly testing everything in the
980// Test class, there are no separate tests for the following classes:
981//
982// TestCase, UnitTest, UnitTestResultPrinter.
983//
984// Similarly, there are no separate tests for the following macros:
985//
986// TEST, TEST_F, RUN_ALL_TESTS
987
988// This group of tests is for predicate assertions (ASSERT_PRED*, etc)
989// of various arities. They do not attempt to be exhaustive. Rather,
990// view them as smoke tests that can be easily reviewed and verified.
991// A more complete set of tests for predicate assertions can be found
992// in gtest_pred_impl_unittest.cc.
993
994// First, some predicates and predicate-formatters needed by the tests.
995
996// Returns true iff the argument is an even number.
997bool IsEven(int n) {
998 return (n % 2) == 0;
999}
1000
1001// A functor that returns true iff the argument is an even number.
1002struct IsEvenFunctor {
1003 bool operator()(int n) { return IsEven(n); }
1004};
1005
1006// A predicate-formatter function that asserts the argument is an even
1007// number.
1008testing::AssertionResult AssertIsEven(const char* expr, int n) {
1009 if (IsEven(n)) {
1010 return testing::AssertionSuccess();
1011 }
1012
1013 testing::Message msg;
1014 msg << expr << " evaluates to " << n << ", which is not even.";
1015 return testing::AssertionFailure(msg);
1016}
1017
1018// A predicate-formatter functor that asserts the argument is an even
1019// number.
1020struct AssertIsEvenFunctor {
1021 testing::AssertionResult operator()(const char* expr, int n) {
1022 return AssertIsEven(expr, n);
1023 }
1024};
1025
1026// Returns true iff the sum of the arguments is an even number.
1027bool SumIsEven2(int n1, int n2) {
1028 return IsEven(n1 + n2);
1029}
1030
1031// A functor that returns true iff the sum of the arguments is an even
1032// number.
1033struct SumIsEven3Functor {
1034 bool operator()(int n1, int n2, int n3) {
1035 return IsEven(n1 + n2 + n3);
1036 }
1037};
1038
1039// A predicate-formatter function that asserts the sum of the
1040// arguments is an even number.
1041testing::AssertionResult AssertSumIsEven4(const char* e1,
1042 const char* e2,
1043 const char* e3,
1044 const char* e4,
1045 int n1,
1046 int n2,
1047 int n3,
1048 int n4) {
1049 const int sum = n1 + n2 + n3 + n4;
1050 if (IsEven(sum)) {
1051 return testing::AssertionSuccess();
1052 }
1053
1054 testing::Message msg;
1055 msg << e1 << " + " << e2 << " + " << e3 << " + " << e4
1056 << " (" << n1 << " + " << n2 << " + " << n3 << " + " << n4
1057 << ") evaluates to " << sum << ", which is not even.";
1058 return testing::AssertionFailure(msg);
1059}
1060
1061// A predicate-formatter functor that asserts the sum of the arguments
1062// is an even number.
1063struct AssertSumIsEven5Functor {
1064 testing::AssertionResult operator()(const char* e1,
1065 const char* e2,
1066 const char* e3,
1067 const char* e4,
1068 const char* e5,
1069 int n1,
1070 int n2,
1071 int n3,
1072 int n4,
1073 int n5) {
1074 const int sum = n1 + n2 + n3 + n4 + n5;
1075 if (IsEven(sum)) {
1076 return testing::AssertionSuccess();
1077 }
1078
1079 testing::Message msg;
1080 msg << e1 << " + " << e2 << " + " << e3 << " + " << e4 << " + " << e5
1081 << " ("
1082 << n1 << " + " << n2 << " + " << n3 << " + " << n4 << " + " << n5
1083 << ") evaluates to " << sum << ", which is not even.";
1084 return testing::AssertionFailure(msg);
1085 }
1086};
1087
1088
1089// Tests unary predicate assertions.
1090
1091// Tests unary predicate assertions that don't use a custom formatter.
1092TEST(Pred1Test, WithoutFormat) {
1093 // Success cases.
1094 EXPECT_PRED1(IsEvenFunctor(), 2) << "This failure is UNEXPECTED!";
1095 ASSERT_PRED1(IsEven, 4);
1096
1097 // Failure cases.
1098 EXPECT_NONFATAL_FAILURE({ // NOLINT
1099 EXPECT_PRED1(IsEven, 5) << "This failure is expected.";
1100 }, "This failure is expected.");
1101 EXPECT_FATAL_FAILURE(ASSERT_PRED1(IsEvenFunctor(), 5),
1102 "evaluates to false");
1103}
1104
1105// Tests unary predicate assertions that use a custom formatter.
1106TEST(Pred1Test, WithFormat) {
1107 // Success cases.
1108 EXPECT_PRED_FORMAT1(AssertIsEven, 2);
1109 ASSERT_PRED_FORMAT1(AssertIsEvenFunctor(), 4)
1110 << "This failure is UNEXPECTED!";
1111
1112 // Failure cases.
1113 const int n = 5;
1114 EXPECT_NONFATAL_FAILURE(EXPECT_PRED_FORMAT1(AssertIsEvenFunctor(), n),
1115 "n evaluates to 5, which is not even.");
1116 EXPECT_FATAL_FAILURE({ // NOLINT
1117 ASSERT_PRED_FORMAT1(AssertIsEven, 5) << "This failure is expected.";
1118 }, "This failure is expected.");
1119}
1120
1121// Tests that unary predicate assertions evaluates their arguments
1122// exactly once.
1123TEST(Pred1Test, SingleEvaluationOnFailure) {
1124 // A success case.
1125 static int n = 0;
1126 EXPECT_PRED1(IsEven, n++);
1127 EXPECT_EQ(1, n) << "The argument is not evaluated exactly once.";
1128
1129 // A failure case.
1130 EXPECT_FATAL_FAILURE({ // NOLINT
1131 ASSERT_PRED_FORMAT1(AssertIsEvenFunctor(), n++)
1132 << "This failure is expected.";
1133 }, "This failure is expected.");
1134 EXPECT_EQ(2, n) << "The argument is not evaluated exactly once.";
1135}
1136
1137
1138// Tests predicate assertions whose arity is >= 2.
1139
1140// Tests predicate assertions that don't use a custom formatter.
1141TEST(PredTest, WithoutFormat) {
1142 // Success cases.
1143 ASSERT_PRED2(SumIsEven2, 2, 4) << "This failure is UNEXPECTED!";
1144 EXPECT_PRED3(SumIsEven3Functor(), 4, 6, 8);
1145
1146 // Failure cases.
1147 const int n1 = 1;
1148 const int n2 = 2;
1149 EXPECT_NONFATAL_FAILURE({ // NOLINT
1150 EXPECT_PRED2(SumIsEven2, n1, n2) << "This failure is expected.";
1151 }, "This failure is expected.");
1152 EXPECT_FATAL_FAILURE({ // NOLINT
1153 ASSERT_PRED3(SumIsEven3Functor(), 1, 2, 4);
1154 }, "evaluates to false");
1155}
1156
1157// Tests predicate assertions that use a custom formatter.
1158TEST(PredTest, WithFormat) {
1159 // Success cases.
1160 ASSERT_PRED_FORMAT4(AssertSumIsEven4, 4, 6, 8, 10) <<
1161 "This failure is UNEXPECTED!";
1162 EXPECT_PRED_FORMAT5(AssertSumIsEven5Functor(), 2, 4, 6, 8, 10);
1163
1164 // Failure cases.
1165 const int n1 = 1;
1166 const int n2 = 2;
1167 const int n3 = 4;
1168 const int n4 = 6;
1169 EXPECT_NONFATAL_FAILURE({ // NOLINT
1170 EXPECT_PRED_FORMAT4(AssertSumIsEven4, n1, n2, n3, n4);
1171 }, "evaluates to 13, which is not even.");
1172 EXPECT_FATAL_FAILURE({ // NOLINT
1173 ASSERT_PRED_FORMAT5(AssertSumIsEven5Functor(), 1, 2, 4, 6, 8)
1174 << "This failure is expected.";
1175 }, "This failure is expected.");
1176}
1177
1178// Tests that predicate assertions evaluates their arguments
1179// exactly once.
1180TEST(PredTest, SingleEvaluationOnFailure) {
1181 // A success case.
1182 int n1 = 0;
1183 int n2 = 0;
1184 EXPECT_PRED2(SumIsEven2, n1++, n2++);
1185 EXPECT_EQ(1, n1) << "Argument 1 is not evaluated exactly once.";
1186 EXPECT_EQ(1, n2) << "Argument 2 is not evaluated exactly once.";
1187
1188 // Another success case.
1189 n1 = n2 = 0;
1190 int n3 = 0;
1191 int n4 = 0;
1192 int n5 = 0;
1193 ASSERT_PRED_FORMAT5(AssertSumIsEven5Functor(),
1194 n1++, n2++, n3++, n4++, n5++)
1195 << "This failure is UNEXPECTED!";
1196 EXPECT_EQ(1, n1) << "Argument 1 is not evaluated exactly once.";
1197 EXPECT_EQ(1, n2) << "Argument 2 is not evaluated exactly once.";
1198 EXPECT_EQ(1, n3) << "Argument 3 is not evaluated exactly once.";
1199 EXPECT_EQ(1, n4) << "Argument 4 is not evaluated exactly once.";
1200 EXPECT_EQ(1, n5) << "Argument 5 is not evaluated exactly once.";
1201
1202 // A failure case.
1203 n1 = n2 = n3 = 0;
1204 EXPECT_NONFATAL_FAILURE({ // NOLINT
1205 EXPECT_PRED3(SumIsEven3Functor(), ++n1, n2++, n3++)
1206 << "This failure is expected.";
1207 }, "This failure is expected.");
1208 EXPECT_EQ(1, n1) << "Argument 1 is not evaluated exactly once.";
1209 EXPECT_EQ(1, n2) << "Argument 2 is not evaluated exactly once.";
1210 EXPECT_EQ(1, n3) << "Argument 3 is not evaluated exactly once.";
1211
1212 // Another failure case.
1213 n1 = n2 = n3 = n4 = 0;
1214 EXPECT_NONFATAL_FAILURE({ // NOLINT
1215 EXPECT_PRED_FORMAT4(AssertSumIsEven4, ++n1, n2++, n3++, n4++);
1216 }, "evaluates to 1, which is not even.");
1217 EXPECT_EQ(1, n1) << "Argument 1 is not evaluated exactly once.";
1218 EXPECT_EQ(1, n2) << "Argument 2 is not evaluated exactly once.";
1219 EXPECT_EQ(1, n3) << "Argument 3 is not evaluated exactly once.";
1220 EXPECT_EQ(1, n4) << "Argument 4 is not evaluated exactly once.";
1221}
1222
1223
1224// Some helper functions for testing using overloaded/template
1225// functions with ASSERT_PREDn and EXPECT_PREDn.
1226
1227bool IsPositive(int n) {
1228 return n > 0;
1229}
1230
1231bool IsPositive(double x) {
1232 return x > 0;
1233}
1234
1235template <typename T>
1236bool IsNegative(T x) {
1237 return x < 0;
1238}
1239
1240template <typename T1, typename T2>
1241bool GreaterThan(T1 x1, T2 x2) {
1242 return x1 > x2;
1243}
1244
1245// Tests that overloaded functions can be used in *_PRED* as long as
1246// their types are explicitly specified.
1247TEST(PredicateAssertionTest, AcceptsOverloadedFunction) {
1248 EXPECT_PRED1(static_cast<bool (*)(int)>(IsPositive), 5); // NOLINT
1249 ASSERT_PRED1(static_cast<bool (*)(double)>(IsPositive), 6.0); // NOLINT
1250}
1251
1252// Tests that template functions can be used in *_PRED* as long as
1253// their types are explicitly specified.
1254TEST(PredicateAssertionTest, AcceptsTemplateFunction) {
1255 EXPECT_PRED1(IsNegative<int>, -5);
1256 // Makes sure that we can handle templates with more than one
1257 // parameter.
1258 ASSERT_PRED2((GreaterThan<int, int>), 5, 0);
1259}
1260
1261
1262// Some helper functions for testing using overloaded/template
1263// functions with ASSERT_PRED_FORMATn and EXPECT_PRED_FORMATn.
1264
1265testing::AssertionResult IsPositiveFormat(const char* expr, int n) {
1266 return n > 0 ? testing::AssertionSuccess() :
1267 testing::AssertionFailure(testing::Message() << "Failure");
1268}
1269
1270testing::AssertionResult IsPositiveFormat(const char* expr, double x) {
1271 return x > 0 ? testing::AssertionSuccess() :
1272 testing::AssertionFailure(testing::Message() << "Failure");
1273}
1274
1275template <typename T>
1276testing::AssertionResult IsNegativeFormat(const char* expr, T x) {
1277 return x < 0 ? testing::AssertionSuccess() :
1278 testing::AssertionFailure(testing::Message() << "Failure");
1279}
1280
1281template <typename T1, typename T2>
1282testing::AssertionResult EqualsFormat(const char* expr1, const char* expr2,
1283 const T1& x1, const T2& x2) {
1284 return x1 == x2 ? testing::AssertionSuccess() :
1285 testing::AssertionFailure(testing::Message() << "Failure");
1286}
1287
1288// Tests that overloaded functions can be used in *_PRED_FORMAT*
1289// without explictly specifying their types.
1290TEST(PredicateFormatAssertionTest, AcceptsOverloadedFunction) {
1291 EXPECT_PRED_FORMAT1(IsPositiveFormat, 5);
1292 ASSERT_PRED_FORMAT1(IsPositiveFormat, 6.0);
1293}
1294
1295// Tests that template functions can be used in *_PRED_FORMAT* without
1296// explicitly specifying their types.
1297TEST(PredicateFormatAssertionTest, AcceptsTemplateFunction) {
1298 EXPECT_PRED_FORMAT1(IsNegativeFormat, -5);
1299 ASSERT_PRED_FORMAT2(EqualsFormat, 3, 3);
1300}
1301
1302
1303// Tests string assertions.
1304
1305// Tests ASSERT_STREQ with non-NULL arguments.
1306TEST(StringAssertionTest, ASSERT_STREQ) {
1307 const char * const p1 = "good";
1308 ASSERT_STREQ(p1, p1);
1309
1310 // Let p2 have the same content as p1, but be at a different address.
1311 const char p2[] = "good";
1312 ASSERT_STREQ(p1, p2);
1313
1314 EXPECT_FATAL_FAILURE(ASSERT_STREQ("bad", "good"),
1315 "Expected: \"bad\"");
1316}
1317
1318// Tests ASSERT_STREQ with NULL arguments.
1319TEST(StringAssertionTest, ASSERT_STREQ_Null) {
1320 ASSERT_STREQ(static_cast<const char *>(NULL), NULL);
1321 EXPECT_FATAL_FAILURE(ASSERT_STREQ(NULL, "non-null"),
1322 "non-null");
1323}
1324
1325// Tests ASSERT_STREQ with NULL arguments.
1326TEST(StringAssertionTest, ASSERT_STREQ_Null2) {
1327 EXPECT_FATAL_FAILURE(ASSERT_STREQ("non-null", NULL),
1328 "non-null");
1329}
1330
1331// Tests ASSERT_STRNE.
1332TEST(StringAssertionTest, ASSERT_STRNE) {
1333 ASSERT_STRNE("hi", "Hi");
1334 ASSERT_STRNE("Hi", NULL);
1335 ASSERT_STRNE(NULL, "Hi");
1336 ASSERT_STRNE("", NULL);
1337 ASSERT_STRNE(NULL, "");
1338 ASSERT_STRNE("", "Hi");
1339 ASSERT_STRNE("Hi", "");
1340 EXPECT_FATAL_FAILURE(ASSERT_STRNE("Hi", "Hi"),
1341 "\"Hi\" vs \"Hi\"");
1342}
1343
1344// Tests ASSERT_STRCASEEQ.
1345TEST(StringAssertionTest, ASSERT_STRCASEEQ) {
1346 ASSERT_STRCASEEQ("hi", "Hi");
1347 ASSERT_STRCASEEQ(static_cast<const char *>(NULL), NULL);
1348
1349 ASSERT_STRCASEEQ("", "");
1350 EXPECT_FATAL_FAILURE(ASSERT_STRCASEEQ("Hi", "hi2"),
1351 "(ignoring case)");
1352}
1353
1354// Tests ASSERT_STRCASENE.
1355TEST(StringAssertionTest, ASSERT_STRCASENE) {
1356 ASSERT_STRCASENE("hi1", "Hi2");
1357 ASSERT_STRCASENE("Hi", NULL);
1358 ASSERT_STRCASENE(NULL, "Hi");
1359 ASSERT_STRCASENE("", NULL);
1360 ASSERT_STRCASENE(NULL, "");
1361 ASSERT_STRCASENE("", "Hi");
1362 ASSERT_STRCASENE("Hi", "");
1363 EXPECT_FATAL_FAILURE(ASSERT_STRCASENE("Hi", "hi"),
1364 "(ignoring case)");
1365}
1366
1367// Tests *_STREQ on wide strings.
1368TEST(StringAssertionTest, STREQ_Wide) {
1369 // NULL strings.
1370 ASSERT_STREQ(static_cast<const wchar_t *>(NULL), NULL);
1371
1372 // Empty strings.
1373 ASSERT_STREQ(L"", L"");
1374
1375 // Non-null vs NULL.
1376 EXPECT_NONFATAL_FAILURE(EXPECT_STREQ(L"non-null", NULL),
1377 "non-null");
1378
1379 // Equal strings.
1380 EXPECT_STREQ(L"Hi", L"Hi");
1381
1382 // Unequal strings.
1383 EXPECT_NONFATAL_FAILURE(EXPECT_STREQ(L"abc", L"Abc"),
1384 "Abc");
1385
1386 // Strings containing wide characters.
1387 EXPECT_NONFATAL_FAILURE(EXPECT_STREQ(L"abc\x8119", L"abc\x8120"),
1388 "abc");
1389}
1390
1391// Tests *_STRNE on wide strings.
1392TEST(StringAssertionTest, STRNE_Wide) {
1393 // NULL strings.
1394 EXPECT_NONFATAL_FAILURE({ // NOLINT
1395 EXPECT_STRNE(static_cast<const wchar_t *>(NULL), NULL);
1396 }, "");
1397
1398 // Empty strings.
1399 EXPECT_NONFATAL_FAILURE(EXPECT_STRNE(L"", L""),
1400 "L\"\"");
1401
1402 // Non-null vs NULL.
1403 ASSERT_STRNE(L"non-null", NULL);
1404
1405 // Equal strings.
1406 EXPECT_NONFATAL_FAILURE(EXPECT_STRNE(L"Hi", L"Hi"),
1407 "L\"Hi\"");
1408
1409 // Unequal strings.
1410 EXPECT_STRNE(L"abc", L"Abc");
1411
1412 // Strings containing wide characters.
1413 EXPECT_NONFATAL_FAILURE(EXPECT_STRNE(L"abc\x8119", L"abc\x8119"),
1414 "abc");
1415}
1416
1417// Tests for ::testing::IsSubstring().
1418
1419// Tests that IsSubstring() returns the correct result when the input
1420// argument type is const char*.
1421TEST(IsSubstringTest, ReturnsCorrectResultForCString) {
1422 using ::testing::IsSubstring;
1423
1424 EXPECT_FALSE(IsSubstring("", "", NULL, "a"));
1425 EXPECT_FALSE(IsSubstring("", "", "b", NULL));
1426 EXPECT_FALSE(IsSubstring("", "", "needle", "haystack"));
1427
1428 EXPECT_TRUE(IsSubstring("", "", static_cast<const char*>(NULL), NULL));
1429 EXPECT_TRUE(IsSubstring("", "", "needle", "two needles"));
1430}
1431
1432// Tests that IsSubstring() returns the correct result when the input
1433// argument type is const wchar_t*.
1434TEST(IsSubstringTest, ReturnsCorrectResultForWideCString) {
1435 using ::testing::IsSubstring;
1436
1437 EXPECT_FALSE(IsSubstring("", "", NULL, L"a"));
1438 EXPECT_FALSE(IsSubstring("", "", L"b", NULL));
1439 EXPECT_FALSE(IsSubstring("", "", L"needle", L"haystack"));
1440
1441 EXPECT_TRUE(IsSubstring("", "", static_cast<const wchar_t*>(NULL), NULL));
1442 EXPECT_TRUE(IsSubstring("", "", L"needle", L"two needles"));
1443}
1444
1445// Tests that IsSubstring() generates the correct message when the input
1446// argument type is const char*.
1447TEST(IsSubstringTest, GeneratesCorrectMessageForCString) {
1448 EXPECT_STREQ("Value of: needle_expr\n"
1449 " Actual: \"needle\"\n"
1450 "Expected: a substring of haystack_expr\n"
1451 "Which is: \"haystack\"",
1452 ::testing::IsSubstring("needle_expr", "haystack_expr",
1453 "needle", "haystack").failure_message());
1454}
1455
1456#if GTEST_HAS_STD_STRING
1457
1458// Tests that IsSubstring returns the correct result when the input
1459// argument type is ::std::string.
1460TEST(IsSubstringTest, ReturnsCorrectResultsForStdString) {
1461 EXPECT_TRUE(::testing::IsSubstring("", "", std::string("hello"), "ahellob"));
1462 EXPECT_FALSE(::testing::IsSubstring("", "", "hello", std::string("world")));
1463}
1464
1465#endif // GTEST_HAS_STD_STRING
1466
1467#if GTEST_HAS_STD_WSTRING
1468// Tests that IsSubstring returns the correct result when the input
1469// argument type is ::std::wstring.
1470TEST(IsSubstringTest, ReturnsCorrectResultForStdWstring) {
1471 using ::testing::IsSubstring;
1472
1473 EXPECT_TRUE(IsSubstring("", "", ::std::wstring(L"needle"), L"two needles"));
1474 EXPECT_FALSE(IsSubstring("", "", L"needle", ::std::wstring(L"haystack")));
1475}
1476
1477// Tests that IsSubstring() generates the correct message when the input
1478// argument type is ::std::wstring.
1479TEST(IsSubstringTest, GeneratesCorrectMessageForWstring) {
1480 EXPECT_STREQ("Value of: needle_expr\n"
1481 " Actual: L\"needle\"\n"
1482 "Expected: a substring of haystack_expr\n"
1483 "Which is: L\"haystack\"",
1484 ::testing::IsSubstring(
1485 "needle_expr", "haystack_expr",
1486 ::std::wstring(L"needle"), L"haystack").failure_message());
1487}
1488
1489#endif // GTEST_HAS_STD_WSTRING
1490
1491// Tests for ::testing::IsNotSubstring().
1492
1493// Tests that IsNotSubstring() returns the correct result when the input
1494// argument type is const char*.
1495TEST(IsNotSubstringTest, ReturnsCorrectResultForCString) {
1496 using ::testing::IsNotSubstring;
1497
1498 EXPECT_TRUE(IsNotSubstring("", "", "needle", "haystack"));
1499 EXPECT_FALSE(IsNotSubstring("", "", "needle", "two needles"));
1500}
1501
1502// Tests that IsNotSubstring() returns the correct result when the input
1503// argument type is const wchar_t*.
1504TEST(IsNotSubstringTest, ReturnsCorrectResultForWideCString) {
1505 using ::testing::IsNotSubstring;
1506
1507 EXPECT_TRUE(IsNotSubstring("", "", L"needle", L"haystack"));
1508 EXPECT_FALSE(IsNotSubstring("", "", L"needle", L"two needles"));
1509}
1510
1511// Tests that IsNotSubstring() generates the correct message when the input
1512// argument type is const wchar_t*.
1513TEST(IsNotSubstringTest, GeneratesCorrectMessageForWideCString) {
1514 EXPECT_STREQ("Value of: needle_expr\n"
1515 " Actual: L\"needle\"\n"
1516 "Expected: not a substring of haystack_expr\n"
1517 "Which is: L\"two needles\"",
1518 ::testing::IsNotSubstring(
1519 "needle_expr", "haystack_expr",
1520 L"needle", L"two needles").failure_message());
1521}
1522
1523#if GTEST_HAS_STD_STRING
1524
1525// Tests that IsNotSubstring returns the correct result when the input
1526// argument type is ::std::string.
1527TEST(IsNotSubstringTest, ReturnsCorrectResultsForStdString) {
1528 using ::testing::IsNotSubstring;
1529
1530 EXPECT_FALSE(IsNotSubstring("", "", std::string("hello"), "ahellob"));
1531 EXPECT_TRUE(IsNotSubstring("", "", "hello", std::string("world")));
1532}
1533
1534// Tests that IsNotSubstring() generates the correct message when the input
1535// argument type is ::std::string.
1536TEST(IsNotSubstringTest, GeneratesCorrectMessageForStdString) {
1537 EXPECT_STREQ("Value of: needle_expr\n"
1538 " Actual: \"needle\"\n"
1539 "Expected: not a substring of haystack_expr\n"
1540 "Which is: \"two needles\"",
1541 ::testing::IsNotSubstring(
1542 "needle_expr", "haystack_expr",
1543 ::std::string("needle"), "two needles").failure_message());
1544}
1545
1546#endif // GTEST_HAS_STD_STRING
1547
1548#if GTEST_HAS_STD_WSTRING
1549
1550// Tests that IsNotSubstring returns the correct result when the input
1551// argument type is ::std::wstring.
1552TEST(IsNotSubstringTest, ReturnsCorrectResultForStdWstring) {
1553 using ::testing::IsNotSubstring;
1554
1555 EXPECT_FALSE(
1556 IsNotSubstring("", "", ::std::wstring(L"needle"), L"two needles"));
1557 EXPECT_TRUE(IsNotSubstring("", "", L"needle", ::std::wstring(L"haystack")));
1558}
1559
1560#endif // GTEST_HAS_STD_WSTRING
1561
1562// Tests floating-point assertions.
1563
1564template <typename RawType>
1565class FloatingPointTest : public testing::Test {
1566 protected:
1567 typedef typename testing::internal::FloatingPoint<RawType> Floating;
1568 typedef typename Floating::Bits Bits;
1569
1570 virtual void SetUp() {
1571 const size_t max_ulps = Floating::kMaxUlps;
1572
1573 // The bits that represent 0.0.
1574 const Bits zero_bits = Floating(0).bits();
1575
1576 // Makes some numbers close to 0.0.
1577 close_to_positive_zero_ = Floating::ReinterpretBits(zero_bits + max_ulps/2);
1578 close_to_negative_zero_ = -Floating::ReinterpretBits(
1579 zero_bits + max_ulps - max_ulps/2);
1580 further_from_negative_zero_ = -Floating::ReinterpretBits(
1581 zero_bits + max_ulps + 1 - max_ulps/2);
1582
1583 // The bits that represent 1.0.
1584 const Bits one_bits = Floating(1).bits();
1585
1586 // Makes some numbers close to 1.0.
1587 close_to_one_ = Floating::ReinterpretBits(one_bits + max_ulps);
1588 further_from_one_ = Floating::ReinterpretBits(one_bits + max_ulps + 1);
1589
1590 // +infinity.
1591 infinity_ = Floating::Infinity();
1592
1593 // The bits that represent +infinity.
1594 const Bits infinity_bits = Floating(infinity_).bits();
1595
1596 // Makes some numbers close to infinity.
1597 close_to_infinity_ = Floating::ReinterpretBits(infinity_bits - max_ulps);
1598 further_from_infinity_ = Floating::ReinterpretBits(
1599 infinity_bits - max_ulps - 1);
1600
1601 // Makes some NAN's.
1602 nan1_ = Floating::ReinterpretBits(Floating::kExponentBitMask | 1);
1603 nan2_ = Floating::ReinterpretBits(Floating::kExponentBitMask | 200);
1604 }
1605
1606 void TestSize() {
1607 EXPECT_EQ(sizeof(RawType), sizeof(Bits));
1608 }
1609
1610 // Pre-calculated numbers to be used by the tests.
1611
1612 static RawType close_to_positive_zero_;
1613 static RawType close_to_negative_zero_;
1614 static RawType further_from_negative_zero_;
1615
1616 static RawType close_to_one_;
1617 static RawType further_from_one_;
1618
1619 static RawType infinity_;
1620 static RawType close_to_infinity_;
1621 static RawType further_from_infinity_;
1622
1623 static RawType nan1_;
1624 static RawType nan2_;
1625};
1626
1627template <typename RawType>
1628RawType FloatingPointTest<RawType>::close_to_positive_zero_;
1629
1630template <typename RawType>
1631RawType FloatingPointTest<RawType>::close_to_negative_zero_;
1632
1633template <typename RawType>
1634RawType FloatingPointTest<RawType>::further_from_negative_zero_;
1635
1636template <typename RawType>
1637RawType FloatingPointTest<RawType>::close_to_one_;
1638
1639template <typename RawType>
1640RawType FloatingPointTest<RawType>::further_from_one_;
1641
1642template <typename RawType>
1643RawType FloatingPointTest<RawType>::infinity_;
1644
1645template <typename RawType>
1646RawType FloatingPointTest<RawType>::close_to_infinity_;
1647
1648template <typename RawType>
1649RawType FloatingPointTest<RawType>::further_from_infinity_;
1650
1651template <typename RawType>
1652RawType FloatingPointTest<RawType>::nan1_;
1653
1654template <typename RawType>
1655RawType FloatingPointTest<RawType>::nan2_;
1656
1657// Instantiates FloatingPointTest for testing *_FLOAT_EQ.
1658typedef FloatingPointTest<float> FloatTest;
1659
1660// Tests that the size of Float::Bits matches the size of float.
1661TEST_F(FloatTest, Size) {
1662 TestSize();
1663}
1664
1665// Tests comparing with +0 and -0.
1666TEST_F(FloatTest, Zeros) {
1667 EXPECT_FLOAT_EQ(0.0, -0.0);
1668 EXPECT_NONFATAL_FAILURE(EXPECT_FLOAT_EQ(-0.0, 1.0),
1669 "1.0");
1670 EXPECT_FATAL_FAILURE(ASSERT_FLOAT_EQ(0.0, 1.5),
1671 "1.5");
1672}
1673
1674// Tests comparing numbers close to 0.
1675//
1676// This ensures that *_FLOAT_EQ handles the sign correctly and no
1677// overflow occurs when comparing numbers whose absolute value is very
1678// small.
1679TEST_F(FloatTest, AlmostZeros) {
1680 EXPECT_FLOAT_EQ(0.0, close_to_positive_zero_);
1681 EXPECT_FLOAT_EQ(-0.0, close_to_negative_zero_);
1682 EXPECT_FLOAT_EQ(close_to_positive_zero_, close_to_negative_zero_);
1683
1684 EXPECT_FATAL_FAILURE({ // NOLINT
1685 ASSERT_FLOAT_EQ(close_to_positive_zero_, further_from_negative_zero_);
1686 }, "further_from_negative_zero_");
1687}
1688
1689// Tests comparing numbers close to each other.
1690TEST_F(FloatTest, SmallDiff) {
1691 EXPECT_FLOAT_EQ(1.0, close_to_one_);
1692 EXPECT_NONFATAL_FAILURE(EXPECT_FLOAT_EQ(1.0, further_from_one_),
1693 "further_from_one_");
1694}
1695
1696// Tests comparing numbers far apart.
1697TEST_F(FloatTest, LargeDiff) {
1698 EXPECT_NONFATAL_FAILURE(EXPECT_FLOAT_EQ(2.5, 3.0),
1699 "3.0");
1700}
1701
1702// Tests comparing with infinity.
1703//
1704// This ensures that no overflow occurs when comparing numbers whose
1705// absolute value is very large.
1706TEST_F(FloatTest, Infinity) {
1707 EXPECT_FLOAT_EQ(infinity_, close_to_infinity_);
1708 EXPECT_FLOAT_EQ(-infinity_, -close_to_infinity_);
1709 EXPECT_NONFATAL_FAILURE(EXPECT_FLOAT_EQ(infinity_, -infinity_),
1710 "-infinity_");
1711
1712 // This is interesting as the representations of infinity_ and nan1_
1713 // are only 1 DLP apart.
1714 EXPECT_NONFATAL_FAILURE(EXPECT_FLOAT_EQ(infinity_, nan1_),
1715 "nan1_");
1716}
1717
1718// Tests that comparing with NAN always returns false.
1719TEST_F(FloatTest, NaN) {
1720 EXPECT_NONFATAL_FAILURE(EXPECT_FLOAT_EQ(nan1_, nan1_),
1721 "nan1_");
1722 EXPECT_NONFATAL_FAILURE(EXPECT_FLOAT_EQ(nan1_, nan2_),
1723 "nan2_");
1724 EXPECT_NONFATAL_FAILURE(EXPECT_FLOAT_EQ(1.0, nan1_),
1725 "nan1_");
1726
1727 EXPECT_FATAL_FAILURE(ASSERT_FLOAT_EQ(nan1_, infinity_),
1728 "infinity_");
1729}
1730
1731// Tests that *_FLOAT_EQ are reflexive.
1732TEST_F(FloatTest, Reflexive) {
1733 EXPECT_FLOAT_EQ(0.0, 0.0);
1734 EXPECT_FLOAT_EQ(1.0, 1.0);
1735 ASSERT_FLOAT_EQ(infinity_, infinity_);
1736}
1737
1738// Tests that *_FLOAT_EQ are commutative.
1739TEST_F(FloatTest, Commutative) {
1740 // We already tested EXPECT_FLOAT_EQ(1.0, close_to_one_).
1741 EXPECT_FLOAT_EQ(close_to_one_, 1.0);
1742
1743 // We already tested EXPECT_FLOAT_EQ(1.0, further_from_one_).
1744 EXPECT_NONFATAL_FAILURE(EXPECT_FLOAT_EQ(further_from_one_, 1.0),
1745 "1.0");
1746}
1747
1748// Tests EXPECT_NEAR.
1749TEST_F(FloatTest, EXPECT_NEAR) {
1750 EXPECT_NEAR(-1.0f, -1.1f, 0.2f);
1751 EXPECT_NEAR(2.0f, 3.0f, 1.0f);
1752 EXPECT_NONFATAL_FAILURE(EXPECT_NEAR(1.0f,1.2f, 0.1f), // NOLINT
1753 "The difference between 1.0f and 1.2f is 0.2, "
1754 "which exceeds 0.1f");
1755 // To work around a bug in gcc 2.95.0, there is intentionally no
1756 // space after the first comma in the previous line.
1757}
1758
1759// Tests ASSERT_NEAR.
1760TEST_F(FloatTest, ASSERT_NEAR) {
1761 ASSERT_NEAR(-1.0f, -1.1f, 0.2f);
1762 ASSERT_NEAR(2.0f, 3.0f, 1.0f);
1763 EXPECT_FATAL_FAILURE(ASSERT_NEAR(1.0f,1.2f, 0.1f), // NOLINT
1764 "The difference between 1.0f and 1.2f is 0.2, "
1765 "which exceeds 0.1f");
1766 // To work around a bug in gcc 2.95.0, there is intentionally no
1767 // space after the first comma in the previous line.
1768}
1769
1770// Tests the cases where FloatLE() should succeed.
1771TEST_F(FloatTest, FloatLESucceeds) {
1772 EXPECT_PRED_FORMAT2(testing::FloatLE, 1.0f, 2.0f); // When val1 < val2,
1773 ASSERT_PRED_FORMAT2(testing::FloatLE, 1.0f, 1.0f); // val1 == val2,
1774
1775 // or when val1 is greater than, but almost equals to, val2.
1776 EXPECT_PRED_FORMAT2(testing::FloatLE, close_to_positive_zero_, 0.0f);
1777}
1778
1779// Tests the cases where FloatLE() should fail.
1780TEST_F(FloatTest, FloatLEFails) {
1781 // When val1 is greater than val2 by a large margin,
1782 EXPECT_NONFATAL_FAILURE(EXPECT_PRED_FORMAT2(testing::FloatLE, 2.0f, 1.0f),
1783 "(2.0f) <= (1.0f)");
1784
1785 // or by a small yet non-negligible margin,
1786 EXPECT_NONFATAL_FAILURE({ // NOLINT
1787 EXPECT_PRED_FORMAT2(testing::FloatLE, further_from_one_, 1.0f);
1788 }, "(further_from_one_) <= (1.0f)");
1789
1790 // or when either val1 or val2 is NaN.
1791 EXPECT_NONFATAL_FAILURE({ // NOLINT
1792 EXPECT_PRED_FORMAT2(testing::FloatLE, nan1_, infinity_);
1793 }, "(nan1_) <= (infinity_)");
1794 EXPECT_NONFATAL_FAILURE({ // NOLINT
1795 EXPECT_PRED_FORMAT2(testing::FloatLE, -infinity_, nan1_);
1796 }, "(-infinity_) <= (nan1_)");
1797
1798 EXPECT_FATAL_FAILURE({ // NOLINT
1799 ASSERT_PRED_FORMAT2(testing::FloatLE, nan1_, nan1_);
1800 }, "(nan1_) <= (nan1_)");
1801}
1802
1803// Instantiates FloatingPointTest for testing *_DOUBLE_EQ.
1804typedef FloatingPointTest<double> DoubleTest;
1805
1806// Tests that the size of Double::Bits matches the size of double.
1807TEST_F(DoubleTest, Size) {
1808 TestSize();
1809}
1810
1811// Tests comparing with +0 and -0.
1812TEST_F(DoubleTest, Zeros) {
1813 EXPECT_DOUBLE_EQ(0.0, -0.0);
1814 EXPECT_NONFATAL_FAILURE(EXPECT_DOUBLE_EQ(-0.0, 1.0),
1815 "1.0");
1816 EXPECT_FATAL_FAILURE(ASSERT_DOUBLE_EQ(0.0, 1.0),
1817 "1.0");
1818}
1819
1820// Tests comparing numbers close to 0.
1821//
1822// This ensures that *_DOUBLE_EQ handles the sign correctly and no
1823// overflow occurs when comparing numbers whose absolute value is very
1824// small.
1825TEST_F(DoubleTest, AlmostZeros) {
1826 EXPECT_DOUBLE_EQ(0.0, close_to_positive_zero_);
1827 EXPECT_DOUBLE_EQ(-0.0, close_to_negative_zero_);
1828 EXPECT_DOUBLE_EQ(close_to_positive_zero_, close_to_negative_zero_);
1829
1830 EXPECT_FATAL_FAILURE({ // NOLINT
1831 ASSERT_DOUBLE_EQ(close_to_positive_zero_, further_from_negative_zero_);
1832 }, "further_from_negative_zero_");
1833}
1834
1835// Tests comparing numbers close to each other.
1836TEST_F(DoubleTest, SmallDiff) {
1837 EXPECT_DOUBLE_EQ(1.0, close_to_one_);
1838 EXPECT_NONFATAL_FAILURE(EXPECT_DOUBLE_EQ(1.0, further_from_one_),
1839 "further_from_one_");
1840}
1841
1842// Tests comparing numbers far apart.
1843TEST_F(DoubleTest, LargeDiff) {
1844 EXPECT_NONFATAL_FAILURE(EXPECT_DOUBLE_EQ(2.0, 3.0),
1845 "3.0");
1846}
1847
1848// Tests comparing with infinity.
1849//
1850// This ensures that no overflow occurs when comparing numbers whose
1851// absolute value is very large.
1852TEST_F(DoubleTest, Infinity) {
1853 EXPECT_DOUBLE_EQ(infinity_, close_to_infinity_);
1854 EXPECT_DOUBLE_EQ(-infinity_, -close_to_infinity_);
1855 EXPECT_NONFATAL_FAILURE(EXPECT_DOUBLE_EQ(infinity_, -infinity_),
1856 "-infinity_");
1857
1858 // This is interesting as the representations of infinity_ and nan1_
1859 // are only 1 DLP apart.
1860 EXPECT_NONFATAL_FAILURE(EXPECT_DOUBLE_EQ(infinity_, nan1_),
1861 "nan1_");
1862}
1863
1864// Tests that comparing with NAN always returns false.
1865TEST_F(DoubleTest, NaN) {
1866 EXPECT_NONFATAL_FAILURE(EXPECT_DOUBLE_EQ(nan1_, nan1_),
1867 "nan1_");
1868 EXPECT_NONFATAL_FAILURE(EXPECT_DOUBLE_EQ(nan1_, nan2_), "nan2_");
1869 EXPECT_NONFATAL_FAILURE(EXPECT_DOUBLE_EQ(1.0, nan1_), "nan1_");
1870 EXPECT_FATAL_FAILURE(ASSERT_DOUBLE_EQ(nan1_, infinity_), "infinity_");
1871}
1872
1873// Tests that *_DOUBLE_EQ are reflexive.
1874TEST_F(DoubleTest, Reflexive) {
1875 EXPECT_DOUBLE_EQ(0.0, 0.0);
1876 EXPECT_DOUBLE_EQ(1.0, 1.0);
1877 ASSERT_DOUBLE_EQ(infinity_, infinity_);
1878}
1879
1880// Tests that *_DOUBLE_EQ are commutative.
1881TEST_F(DoubleTest, Commutative) {
1882 // We already tested EXPECT_DOUBLE_EQ(1.0, close_to_one_).
1883 EXPECT_DOUBLE_EQ(close_to_one_, 1.0);
1884
1885 // We already tested EXPECT_DOUBLE_EQ(1.0, further_from_one_).
1886 EXPECT_NONFATAL_FAILURE(EXPECT_DOUBLE_EQ(further_from_one_, 1.0), "1.0");
1887}
1888
1889// Tests EXPECT_NEAR.
1890TEST_F(DoubleTest, EXPECT_NEAR) {
1891 EXPECT_NEAR(-1.0, -1.1, 0.2);
1892 EXPECT_NEAR(2.0, 3.0, 1.0);
1893#ifdef __SYMBIAN32__
1894 // Symbian STLport has currently a buggy floating point output.
1895 // TODO(mikie): fix STLport.
1896 EXPECT_NONFATAL_FAILURE(EXPECT_NEAR(1.0, 1.2, 0.1), // NOLINT
1897 "The difference between 1.0 and 1.2 is 0.19999:, "
1898 "which exceeds 0.1");
1899#else // !__SYMBIAN32__
1900 EXPECT_NONFATAL_FAILURE(EXPECT_NEAR(1.0, 1.2, 0.1), // NOLINT
1901 "The difference between 1.0 and 1.2 is 0.2, "
1902 "which exceeds 0.1");
1903 // To work around a bug in gcc 2.95.0, there is intentionally no
1904 // space after the first comma in the previous statement.
1905#endif // __SYMBIAN32__
1906}
1907
1908// Tests ASSERT_NEAR.
1909TEST_F(DoubleTest, ASSERT_NEAR) {
1910 ASSERT_NEAR(-1.0, -1.1, 0.2);
1911 ASSERT_NEAR(2.0, 3.0, 1.0);
1912#ifdef __SYMBIAN32__
1913 // Symbian STLport has currently a buggy floating point output.
1914 // TODO(mikie): fix STLport.
1915 EXPECT_FATAL_FAILURE(ASSERT_NEAR(1.0, 1.2, 0.1), // NOLINT
1916 "The difference between 1.0 and 1.2 is 0.19999:, "
1917 "which exceeds 0.1");
1918#else // ! __SYMBIAN32__
1919 EXPECT_FATAL_FAILURE(ASSERT_NEAR(1.0, 1.2, 0.1), // NOLINT
1920 "The difference between 1.0 and 1.2 is 0.2, "
1921 "which exceeds 0.1");
1922 // To work around a bug in gcc 2.95.0, there is intentionally no
1923 // space after the first comma in the previous statement.
1924#endif // __SYMBIAN32__
1925}
1926
1927// Tests the cases where DoubleLE() should succeed.
1928TEST_F(DoubleTest, DoubleLESucceeds) {
1929 EXPECT_PRED_FORMAT2(testing::DoubleLE, 1.0, 2.0); // When val1 < val2,
1930 ASSERT_PRED_FORMAT2(testing::DoubleLE, 1.0, 1.0); // val1 == val2,
1931
1932 // or when val1 is greater than, but almost equals to, val2.
1933 EXPECT_PRED_FORMAT2(testing::DoubleLE, close_to_positive_zero_, 0.0);
1934}
1935
1936// Tests the cases where DoubleLE() should fail.
1937TEST_F(DoubleTest, DoubleLEFails) {
1938 // When val1 is greater than val2 by a large margin,
1939 EXPECT_NONFATAL_FAILURE(EXPECT_PRED_FORMAT2(testing::DoubleLE, 2.0, 1.0),
1940 "(2.0) <= (1.0)");
1941
1942 // or by a small yet non-negligible margin,
1943 EXPECT_NONFATAL_FAILURE({ // NOLINT
1944 EXPECT_PRED_FORMAT2(testing::DoubleLE, further_from_one_, 1.0);
1945 }, "(further_from_one_) <= (1.0)");
1946
1947 // or when either val1 or val2 is NaN.
1948 EXPECT_NONFATAL_FAILURE({ // NOLINT
1949 EXPECT_PRED_FORMAT2(testing::DoubleLE, nan1_, infinity_);
1950 }, "(nan1_) <= (infinity_)");
1951 EXPECT_NONFATAL_FAILURE({ // NOLINT
1952 EXPECT_PRED_FORMAT2(testing::DoubleLE, -infinity_, nan1_);
1953 }, " (-infinity_) <= (nan1_)");
1954 EXPECT_FATAL_FAILURE({ // NOLINT
1955 ASSERT_PRED_FORMAT2(testing::DoubleLE, nan1_, nan1_);
1956 }, "(nan1_) <= (nan1_)");
1957}
1958
1959
1960// Verifies that a test or test case whose name starts with DISABLED_ is
1961// not run.
1962
1963// A test whose name starts with DISABLED_.
1964// Should not run.
1965TEST(DisabledTest, DISABLED_TestShouldNotRun) {
1966 FAIL() << "Unexpected failure: Disabled test should not be run.";
1967}
1968
1969// A test whose name does not start with DISABLED_.
1970// Should run.
1971TEST(DisabledTest, NotDISABLED_TestShouldRun) {
1972 EXPECT_EQ(1, 1);
1973}
1974
1975// A test case whose name starts with DISABLED_.
1976// Should not run.
1977TEST(DISABLED_TestCase, TestShouldNotRun) {
1978 FAIL() << "Unexpected failure: Test in disabled test case should not be run.";
1979}
1980
1981// A test case and test whose names start with DISABLED_.
1982// Should not run.
1983TEST(DISABLED_TestCase, DISABLED_TestShouldNotRun) {
1984 FAIL() << "Unexpected failure: Test in disabled test case should not be run.";
1985}
1986
1987// Check that when all tests in a test case are disabled, SetupTestCase() and
1988// TearDownTestCase() are not called.
1989class DisabledTestsTest : public testing::Test {
1990 protected:
1991 static void SetUpTestCase() {
1992 FAIL() << "Unexpected failure: All tests disabled in test case. "
1993 "SetupTestCase() should not be called.";
1994 }
1995
1996 static void TearDownTestCase() {
1997 FAIL() << "Unexpected failure: All tests disabled in test case. "
1998 "TearDownTestCase() should not be called.";
1999 }
2000};
2001
2002TEST_F(DisabledTestsTest, DISABLED_TestShouldNotRun_1) {
2003 FAIL() << "Unexpected failure: Disabled test should not be run.";
2004}
2005
2006TEST_F(DisabledTestsTest, DISABLED_TestShouldNotRun_2) {
2007 FAIL() << "Unexpected failure: Disabled test should not be run.";
2008}
2009
2010
2011// Tests that assertion macros evaluate their arguments exactly once.
2012
2013class SingleEvaluationTest : public testing::Test {
2014 protected:
2015 SingleEvaluationTest() {
2016 p1_ = s1_;
2017 p2_ = s2_;
2018 a_ = 0;
2019 b_ = 0;
2020 }
2021
2022 // This helper function is needed by the FailedASSERT_STREQ test
2023 // below.
2024 static void CompareAndIncrementCharPtrs() {
2025 ASSERT_STREQ(p1_++, p2_++);
2026 }
2027
2028 // This helper function is needed by the FailedASSERT_NE test below.
2029 static void CompareAndIncrementInts() {
2030 ASSERT_NE(a_++, b_++);
2031 }
2032
2033 static const char* const s1_;
2034 static const char* const s2_;
2035 static const char* p1_;
2036 static const char* p2_;
2037
2038 static int a_;
2039 static int b_;
2040};
2041
2042const char* const SingleEvaluationTest::s1_ = "01234";
2043const char* const SingleEvaluationTest::s2_ = "abcde";
2044const char* SingleEvaluationTest::p1_;
2045const char* SingleEvaluationTest::p2_;
2046int SingleEvaluationTest::a_;
2047int SingleEvaluationTest::b_;
2048
2049// Tests that when ASSERT_STREQ fails, it evaluates its arguments
2050// exactly once.
2051TEST_F(SingleEvaluationTest, FailedASSERT_STREQ) {
2052 EXPECT_FATAL_FAILURE(CompareAndIncrementCharPtrs(),
2053 "p2_++");
2054 EXPECT_EQ(s1_ + 1, p1_);
2055 EXPECT_EQ(s2_ + 1, p2_);
2056}
2057
2058// Tests that string assertion arguments are evaluated exactly once.
2059TEST_F(SingleEvaluationTest, ASSERT_STR) {
2060 // successful EXPECT_STRNE
2061 EXPECT_STRNE(p1_++, p2_++);
2062 EXPECT_EQ(s1_ + 1, p1_);
2063 EXPECT_EQ(s2_ + 1, p2_);
2064
2065 // failed EXPECT_STRCASEEQ
2066 EXPECT_NONFATAL_FAILURE(EXPECT_STRCASEEQ(p1_++, p2_++),
2067 "ignoring case");
2068 EXPECT_EQ(s1_ + 2, p1_);
2069 EXPECT_EQ(s2_ + 2, p2_);
2070}
2071
2072// Tests that when ASSERT_NE fails, it evaluates its arguments exactly
2073// once.
2074TEST_F(SingleEvaluationTest, FailedASSERT_NE) {
2075 EXPECT_FATAL_FAILURE(CompareAndIncrementInts(), "(a_++) != (b_++)");
2076 EXPECT_EQ(1, a_);
2077 EXPECT_EQ(1, b_);
2078}
2079
2080// Tests that assertion arguments are evaluated exactly once.
2081TEST_F(SingleEvaluationTest, OtherCases) {
2082 // successful EXPECT_TRUE
2083 EXPECT_TRUE(0 == a_++); // NOLINT
2084 EXPECT_EQ(1, a_);
2085
2086 // failed EXPECT_TRUE
2087 EXPECT_NONFATAL_FAILURE(EXPECT_TRUE(-1 == a_++), "-1 == a_++");
2088 EXPECT_EQ(2, a_);
2089
2090 // successful EXPECT_GT
2091 EXPECT_GT(a_++, b_++);
2092 EXPECT_EQ(3, a_);
2093 EXPECT_EQ(1, b_);
2094
2095 // failed EXPECT_LT
2096 EXPECT_NONFATAL_FAILURE(EXPECT_LT(a_++, b_++), "(a_++) < (b_++)");
2097 EXPECT_EQ(4, a_);
2098 EXPECT_EQ(2, b_);
2099
2100 // successful ASSERT_TRUE
2101 ASSERT_TRUE(0 < a_++); // NOLINT
2102 EXPECT_EQ(5, a_);
2103
2104 // successful ASSERT_GT
2105 ASSERT_GT(a_++, b_++);
2106 EXPECT_EQ(6, a_);
2107 EXPECT_EQ(3, b_);
2108}
2109
2110
2111// Tests non-string assertions.
2112
2113// Tests EqFailure(), used for implementing *EQ* assertions.
2114TEST(AssertionTest, EqFailure) {
2115 const String foo_val("5"), bar_val("6");
2116 const String msg1(
2117 EqFailure("foo", "bar", foo_val, bar_val, false)
2118 .failure_message());
2119 EXPECT_STREQ(
2120 "Value of: bar\n"
2121 " Actual: 6\n"
2122 "Expected: foo\n"
2123 "Which is: 5",
2124 msg1.c_str());
2125
2126 const String msg2(
2127 EqFailure("foo", "6", foo_val, bar_val, false)
2128 .failure_message());
2129 EXPECT_STREQ(
2130 "Value of: 6\n"
2131 "Expected: foo\n"
2132 "Which is: 5",
2133 msg2.c_str());
2134
2135 const String msg3(
2136 EqFailure("5", "bar", foo_val, bar_val, false)
2137 .failure_message());
2138 EXPECT_STREQ(
2139 "Value of: bar\n"
2140 " Actual: 6\n"
2141 "Expected: 5",
2142 msg3.c_str());
2143
2144 const String msg4(
2145 EqFailure("5", "6", foo_val, bar_val, false).failure_message());
2146 EXPECT_STREQ(
2147 "Value of: 6\n"
2148 "Expected: 5",
2149 msg4.c_str());
2150
2151 const String msg5(
2152 EqFailure("foo", "bar",
2153 String("\"x\""), String("\"y\""),
2154 true).failure_message());
2155 EXPECT_STREQ(
2156 "Value of: bar\n"
2157 " Actual: \"y\"\n"
2158 "Expected: foo (ignoring case)\n"
2159 "Which is: \"x\"",
2160 msg5.c_str());
2161}
2162
2163// Tests AppendUserMessage(), used for implementing the *EQ* macros.
2164TEST(AssertionTest, AppendUserMessage) {
2165 const String foo("foo");
2166
2167 testing::Message msg;
2168 EXPECT_STREQ("foo",
2169 AppendUserMessage(foo, msg).c_str());
2170
2171 msg << "bar";
2172 EXPECT_STREQ("foo\nbar",
2173 AppendUserMessage(foo, msg).c_str());
2174}
2175
2176// Tests ASSERT_TRUE.
2177TEST(AssertionTest, ASSERT_TRUE) {
2178 ASSERT_TRUE(2 > 1); // NOLINT
2179 EXPECT_FATAL_FAILURE(ASSERT_TRUE(2 < 1),
2180 "2 < 1");
2181}
2182
2183// Tests ASSERT_FALSE.
2184TEST(AssertionTest, ASSERT_FALSE) {
2185 ASSERT_FALSE(2 < 1); // NOLINT
2186 EXPECT_FATAL_FAILURE(ASSERT_FALSE(2 > 1),
2187 "Value of: 2 > 1\n"
2188 " Actual: true\n"
2189 "Expected: false");
2190}
2191
2192// Tests using ASSERT_EQ on double values. The purpose is to make
2193// sure that the specialization we did for integer and anonymous enums
2194// isn't used for double arguments.
2195TEST(ExpectTest, ASSERT_EQ_Double) {
2196 // A success.
2197 ASSERT_EQ(5.6, 5.6);
2198
2199 // A failure.
2200 EXPECT_FATAL_FAILURE(ASSERT_EQ(5.1, 5.2),
2201 "5.1");
2202}
2203
2204// Tests ASSERT_EQ.
2205TEST(AssertionTest, ASSERT_EQ) {
2206 ASSERT_EQ(5, 2 + 3);
2207 EXPECT_FATAL_FAILURE(ASSERT_EQ(5, 2*3),
2208 "Value of: 2*3\n"
2209 " Actual: 6\n"
2210 "Expected: 5");
2211}
2212
2213// Tests ASSERT_EQ(NULL, pointer).
2214#ifndef __SYMBIAN32__
2215// The NULL-detection template magic fails to compile with
2216// the Nokia compiler and crashes the ARM compiler, hence
2217// not testing on Symbian.
2218TEST(AssertionTest, ASSERT_EQ_NULL) {
2219 // A success.
2220 const char* p = NULL;
2221 ASSERT_EQ(NULL, p);
2222
2223 // A failure.
2224 static int n = 0;
2225 EXPECT_FATAL_FAILURE(ASSERT_EQ(NULL, &n),
2226 "Value of: &n\n");
2227}
2228#endif // __SYMBIAN32__
2229
2230// Tests ASSERT_EQ(0, non_pointer). Since the literal 0 can be
2231// treated as a null pointer by the compiler, we need to make sure
2232// that ASSERT_EQ(0, non_pointer) isn't interpreted by Google Test as
2233// ASSERT_EQ(static_cast<void*>(NULL), non_pointer).
2234TEST(ExpectTest, ASSERT_EQ_0) {
2235 int n = 0;
2236
2237 // A success.
2238 ASSERT_EQ(0, n);
2239
2240 // A failure.
2241 EXPECT_FATAL_FAILURE(ASSERT_EQ(0, 5.6),
2242 "Expected: 0");
2243}
2244
2245// Tests ASSERT_NE.
2246TEST(AssertionTest, ASSERT_NE) {
2247 ASSERT_NE(6, 7);
2248 EXPECT_FATAL_FAILURE(ASSERT_NE('a', 'a'),
2249 "Expected: ('a') != ('a'), "
2250 "actual: 'a' (97, 0x61) vs 'a' (97, 0x61)");
2251}
2252
2253// Tests ASSERT_LE.
2254TEST(AssertionTest, ASSERT_LE) {
2255 ASSERT_LE(2, 3);
2256 ASSERT_LE(2, 2);
2257 EXPECT_FATAL_FAILURE(ASSERT_LE(2, 0),
2258 "Expected: (2) <= (0), actual: 2 vs 0");
2259}
2260
2261// Tests ASSERT_LT.
2262TEST(AssertionTest, ASSERT_LT) {
2263 ASSERT_LT(2, 3);
2264 EXPECT_FATAL_FAILURE(ASSERT_LT(2, 2),
2265 "Expected: (2) < (2), actual: 2 vs 2");
2266}
2267
2268// Tests ASSERT_GE.
2269TEST(AssertionTest, ASSERT_GE) {
2270 ASSERT_GE(2, 1);
2271 ASSERT_GE(2, 2);
2272 EXPECT_FATAL_FAILURE(ASSERT_GE(2, 3),
2273 "Expected: (2) >= (3), actual: 2 vs 3");
2274}
2275
2276// Tests ASSERT_GT.
2277TEST(AssertionTest, ASSERT_GT) {
2278 ASSERT_GT(2, 1);
2279 EXPECT_FATAL_FAILURE(ASSERT_GT(2, 2),
2280 "Expected: (2) > (2), actual: 2 vs 2");
2281}
2282
2283// Makes sure we deal with the precedence of <<. This test should
2284// compile.
2285TEST(AssertionTest, AssertPrecedence) {
2286 ASSERT_EQ(1 < 2, true);
2287 ASSERT_EQ(true && false, false);
2288}
2289
2290// A subroutine used by the following test.
2291void TestEq1(int x) {
2292 ASSERT_EQ(1, x);
2293}
2294
2295// Tests calling a test subroutine that's not part of a fixture.
2296TEST(AssertionTest, NonFixtureSubroutine) {
2297 EXPECT_FATAL_FAILURE(TestEq1(2),
2298 "Value of: x");
2299}
2300
2301// An uncopyable class.
2302class Uncopyable {
2303 public:
2304 explicit Uncopyable(int value) : value_(value) {}
2305
2306 int value() const { return value_; }
2307 bool operator==(const Uncopyable& rhs) const {
2308 return value() == rhs.value();
2309 }
2310 private:
2311 // This constructor deliberately has no implementation, as we don't
2312 // want this class to be copyable.
2313 Uncopyable(const Uncopyable&); // NOLINT
2314
2315 int value_;
2316};
2317
2318::std::ostream& operator<<(::std::ostream& os, const Uncopyable& value) {
2319 return os << value.value();
2320}
2321
2322
2323bool IsPositiveUncopyable(const Uncopyable& x) {
2324 return x.value() > 0;
2325}
2326
2327// A subroutine used by the following test.
2328void TestAssertNonPositive() {
2329 Uncopyable y(-1);
2330 ASSERT_PRED1(IsPositiveUncopyable, y);
2331}
2332// A subroutine used by the following test.
2333void TestAssertEqualsUncopyable() {
2334 Uncopyable x(5);
2335 Uncopyable y(-1);
2336 ASSERT_EQ(x, y);
2337}
2338
2339// Tests that uncopyable objects can be used in assertions.
2340TEST(AssertionTest, AssertWorksWithUncopyableObject) {
2341 Uncopyable x(5);
2342 ASSERT_PRED1(IsPositiveUncopyable, x);
2343 ASSERT_EQ(x, x);
2344 EXPECT_FATAL_FAILURE(TestAssertNonPositive(),
2345 "IsPositiveUncopyable(y) evaluates to false, where\ny evaluates to -1");
2346 EXPECT_FATAL_FAILURE(TestAssertEqualsUncopyable(),
2347 "Value of: y\n Actual: -1\nExpected: x\nWhich is: 5");
2348}
2349
2350// Tests that uncopyable objects can be used in expects.
2351TEST(AssertionTest, ExpectWorksWithUncopyableObject) {
2352 Uncopyable x(5);
2353 EXPECT_PRED1(IsPositiveUncopyable, x);
2354 Uncopyable y(-1);
2355 EXPECT_NONFATAL_FAILURE(EXPECT_PRED1(IsPositiveUncopyable, y),
2356 "IsPositiveUncopyable(y) evaluates to false, where\ny evaluates to -1");
2357 EXPECT_EQ(x, x);
2358 EXPECT_NONFATAL_FAILURE(EXPECT_EQ(x, y),
2359 "Value of: y\n Actual: -1\nExpected: x\nWhich is: 5");
2360}
2361
2362
2363// The version of gcc used in XCode 2.2 has a bug and doesn't allow
2364// anonymous enums in assertions. Therefore the following test is
2365// done only on Linux and Windows.
2366#if defined(GTEST_OS_LINUX) || defined(GTEST_OS_WINDOWS)
2367
2368// Tests using assertions with anonymous enums.
2369enum {
2370 CASE_A = -1,
2371#ifdef GTEST_OS_LINUX
2372 // We want to test the case where the size of the anonymous enum is
2373 // larger than sizeof(int), to make sure our implementation of the
2374 // assertions doesn't truncate the enums. However, MSVC
2375 // (incorrectly) doesn't allow an enum value to exceed the range of
2376 // an int, so this has to be conditionally compiled.
2377 //
2378 // On Linux, CASE_B and CASE_A have the same value when truncated to
2379 // int size. We want to test whether this will confuse the
2380 // assertions.
2381 CASE_B = ::testing::internal::kMaxBiggestInt,
2382#else
2383 CASE_B = INT_MAX,
2384#endif // GTEST_OS_LINUX
2385};
2386
2387TEST(AssertionTest, AnonymousEnum) {
2388#ifdef GTEST_OS_LINUX
2389 EXPECT_EQ(static_cast<int>(CASE_A), static_cast<int>(CASE_B));
2390#endif // GTEST_OS_LINUX
2391
2392 EXPECT_EQ(CASE_A, CASE_A);
2393 EXPECT_NE(CASE_A, CASE_B);
2394 EXPECT_LT(CASE_A, CASE_B);
2395 EXPECT_LE(CASE_A, CASE_B);
2396 EXPECT_GT(CASE_B, CASE_A);
2397 EXPECT_GE(CASE_A, CASE_A);
2398 EXPECT_NONFATAL_FAILURE(EXPECT_GE(CASE_A, CASE_B),
2399 "(CASE_A) >= (CASE_B)");
2400
2401 ASSERT_EQ(CASE_A, CASE_A);
2402 ASSERT_NE(CASE_A, CASE_B);
2403 ASSERT_LT(CASE_A, CASE_B);
2404 ASSERT_LE(CASE_A, CASE_B);
2405 ASSERT_GT(CASE_B, CASE_A);
2406 ASSERT_GE(CASE_A, CASE_A);
2407 EXPECT_FATAL_FAILURE(ASSERT_EQ(CASE_A, CASE_B),
2408 "Value of: CASE_B");
2409}
2410
2411#endif // defined(GTEST_OS_LINUX) || defined(GTEST_OS_WINDOWS)
2412
2413#if defined(GTEST_OS_WINDOWS)
2414
2415static HRESULT UnexpectedHRESULTFailure() {
2416 return E_UNEXPECTED;
2417}
2418
2419static HRESULT OkHRESULTSuccess() {
2420 return S_OK;
2421}
2422
2423static HRESULT FalseHRESULTSuccess() {
2424 return S_FALSE;
2425}
2426
2427// HRESULT assertion tests test both zero and non-zero
2428// success codes as well as failure message for each.
2429//
2430// Windows CE doesn't support message texts.
2431TEST(HRESULTAssertionTest, EXPECT_HRESULT_SUCCEEDED) {
2432 EXPECT_HRESULT_SUCCEEDED(S_OK);
2433 EXPECT_HRESULT_SUCCEEDED(S_FALSE);
2434
2435#ifdef _WIN32_WCE
2436 const char* expected =
2437 "Expected: (UnexpectedHRESULTFailure()) succeeds.\n"
2438 " Actual: 0x8000FFFF";
2439#else // Windows proper
2440 const char* expected =
2441 "Expected: (UnexpectedHRESULTFailure()) succeeds.\n"
2442 " Actual: 0x8000FFFF Catastrophic failure";
2443#endif // _WIN32_WCE
2444 EXPECT_NONFATAL_FAILURE(EXPECT_HRESULT_SUCCEEDED(UnexpectedHRESULTFailure()),
2445 expected);
2446}
2447
2448TEST(HRESULTAssertionTest, ASSERT_HRESULT_SUCCEEDED) {
2449 ASSERT_HRESULT_SUCCEEDED(S_OK);
2450 ASSERT_HRESULT_SUCCEEDED(S_FALSE);
2451
2452#ifdef _WIN32_WCE
2453 const char* expected =
2454 "Expected: (UnexpectedHRESULTFailure()) succeeds.\n"
2455 " Actual: 0x8000FFFF";
2456#else // Windows proper
2457 const char* expected =
2458 "Expected: (UnexpectedHRESULTFailure()) succeeds.\n"
2459 " Actual: 0x8000FFFF Catastrophic failure";
2460#endif // _WIN32_WCE
2461
2462 EXPECT_FATAL_FAILURE(ASSERT_HRESULT_SUCCEEDED(UnexpectedHRESULTFailure()),
2463 expected);
2464}
2465
2466TEST(HRESULTAssertionTest, EXPECT_HRESULT_FAILED) {
2467 EXPECT_HRESULT_FAILED(E_UNEXPECTED);
2468
2469#ifdef _WIN32_WCE
2470 const char* expected_success =
2471 "Expected: (OkHRESULTSuccess()) fails.\n"
2472 " Actual: 0x00000000";
2473 const char* expected_incorrect_function =
2474 "Expected: (FalseHRESULTSuccess()) fails.\n"
2475 " Actual: 0x00000001";
2476#else // Windows proper
2477 const char* expected_success =
2478 "Expected: (OkHRESULTSuccess()) fails.\n"
2479 " Actual: 0x00000000 The operation completed successfully";
2480 const char* expected_incorrect_function =
2481 "Expected: (FalseHRESULTSuccess()) fails.\n"
2482 " Actual: 0x00000001 Incorrect function.";
2483#endif // _WIN32_WCE
2484
2485 EXPECT_NONFATAL_FAILURE(EXPECT_HRESULT_FAILED(OkHRESULTSuccess()),
2486 expected_success);
2487 EXPECT_NONFATAL_FAILURE(EXPECT_HRESULT_FAILED(FalseHRESULTSuccess()),
2488 expected_incorrect_function);
2489}
2490
2491TEST(HRESULTAssertionTest, ASSERT_HRESULT_FAILED) {
2492 ASSERT_HRESULT_FAILED(E_UNEXPECTED);
2493
2494#ifdef _WIN32_WCE
2495 const char* expected_success =
2496 "Expected: (OkHRESULTSuccess()) fails.\n"
2497 " Actual: 0x00000000";
2498 const char* expected_incorrect_function =
2499 "Expected: (FalseHRESULTSuccess()) fails.\n"
2500 " Actual: 0x00000001";
2501#else // Windows proper
2502 const char* expected_success =
2503 "Expected: (OkHRESULTSuccess()) fails.\n"
2504 " Actual: 0x00000000 The operation completed successfully";
2505 const char* expected_incorrect_function =
2506 "Expected: (FalseHRESULTSuccess()) fails.\n"
2507 " Actual: 0x00000001 Incorrect function.";
2508#endif // _WIN32_WCE
2509
2510 EXPECT_FATAL_FAILURE(ASSERT_HRESULT_FAILED(OkHRESULTSuccess()),
2511 expected_success);
2512 EXPECT_FATAL_FAILURE(ASSERT_HRESULT_FAILED(FalseHRESULTSuccess()),
2513 expected_incorrect_function);
2514}
2515
2516// Tests that streaming to the HRESULT macros works.
2517TEST(HRESULTAssertionTest, Streaming) {
2518 EXPECT_HRESULT_SUCCEEDED(S_OK) << "unexpected failure";
2519 ASSERT_HRESULT_SUCCEEDED(S_OK) << "unexpected failure";
2520 EXPECT_HRESULT_FAILED(E_UNEXPECTED) << "unexpected failure";
2521 ASSERT_HRESULT_FAILED(E_UNEXPECTED) << "unexpected failure";
2522
2523 EXPECT_NONFATAL_FAILURE(
2524 EXPECT_HRESULT_SUCCEEDED(E_UNEXPECTED) << "expected failure",
2525 "expected failure");
2526
2527 EXPECT_FATAL_FAILURE(
2528 ASSERT_HRESULT_SUCCEEDED(E_UNEXPECTED) << "expected failure",
2529 "expected failure");
2530
2531 EXPECT_NONFATAL_FAILURE(
2532 EXPECT_HRESULT_FAILED(S_OK) << "expected failure",
2533 "expected failure");
2534
2535 EXPECT_FATAL_FAILURE(
2536 ASSERT_HRESULT_FAILED(S_OK) << "expected failure",
2537 "expected failure");
2538}
2539
2540#endif // defined(GTEST_OS_WINDOWS)
2541
2542// Tests that the assertion macros behave like single statements.
2543TEST(AssertionSyntaxTest, BehavesLikeSingleStatement) {
2544 if (false)
2545 ASSERT_TRUE(false) << "This should never be executed; "
2546 "It's a compilation test only.";
2547
2548 if (true)
2549 EXPECT_FALSE(false);
2550 else
2551 ;
2552
2553 if (false)
2554 ASSERT_LT(1, 3);
2555
2556 if (false)
2557 ;
2558 else
2559 EXPECT_GT(3, 2) << "";
2560}
2561
2562// Tests that the assertion macros work well with switch statements.
2563TEST(AssertionSyntaxTest, WorksWithSwitch) {
2564 switch (0) {
2565 case 1:
2566 break;
2567 default:
2568 ASSERT_TRUE(true);
2569 }
2570
2571 switch (0)
2572 case 0:
2573 EXPECT_FALSE(false) << "EXPECT_FALSE failed in switch case";
2574
2575 // Binary assertions are implemented using a different code path
2576 // than the Boolean assertions. Hence we test them separately.
2577 switch (0) {
2578 case 1:
2579 default:
2580 ASSERT_EQ(1, 1) << "ASSERT_EQ failed in default switch handler";
2581 }
2582
2583 switch (0)
2584 case 0:
2585 EXPECT_NE(1, 2);
2586}
2587
2588} // namespace
2589
2590// Returns the number of successful parts in the current test.
2591static size_t GetSuccessfulPartCount() {
2592 return UnitTest::GetInstance()->impl()->current_test_result()->
2593 successful_part_count();
2594}
2595
2596namespace testing {
2597
2598// Tests that Google Test tracks SUCCEED*.
2599TEST(SuccessfulAssertionTest, SUCCEED) {
2600 SUCCEED();
2601 SUCCEED() << "OK";
2602 EXPECT_EQ(2u, GetSuccessfulPartCount());
2603}
2604
2605// Tests that Google Test doesn't track successful EXPECT_*.
2606TEST(SuccessfulAssertionTest, EXPECT) {
2607 EXPECT_TRUE(true);
2608 EXPECT_EQ(0u, GetSuccessfulPartCount());
2609}
2610
2611// Tests that Google Test doesn't track successful EXPECT_STR*.
2612TEST(SuccessfulAssertionTest, EXPECT_STR) {
2613 EXPECT_STREQ("", "");
2614 EXPECT_EQ(0u, GetSuccessfulPartCount());
2615}
2616
2617// Tests that Google Test doesn't track successful ASSERT_*.
2618TEST(SuccessfulAssertionTest, ASSERT) {
2619 ASSERT_TRUE(true);
2620 EXPECT_EQ(0u, GetSuccessfulPartCount());
2621}
2622
2623// Tests that Google Test doesn't track successful ASSERT_STR*.
2624TEST(SuccessfulAssertionTest, ASSERT_STR) {
2625 ASSERT_STREQ("", "");
2626 EXPECT_EQ(0u, GetSuccessfulPartCount());
2627}
2628
2629} // namespace testing
2630
2631namespace {
2632
2633// Tests EXPECT_TRUE.
2634TEST(ExpectTest, EXPECT_TRUE) {
2635 EXPECT_TRUE(2 > 1); // NOLINT
2636 EXPECT_NONFATAL_FAILURE(EXPECT_TRUE(2 < 1),
2637 "Value of: 2 < 1\n"
2638 " Actual: false\n"
2639 "Expected: true");
2640 EXPECT_NONFATAL_FAILURE(EXPECT_TRUE(2 > 3),
2641 "2 > 3");
2642}
2643
2644// Tests EXPECT_FALSE.
2645TEST(ExpectTest, EXPECT_FALSE) {
2646 EXPECT_FALSE(2 < 1); // NOLINT
2647 EXPECT_NONFATAL_FAILURE(EXPECT_FALSE(2 > 1),
2648 "Value of: 2 > 1\n"
2649 " Actual: true\n"
2650 "Expected: false");
2651 EXPECT_NONFATAL_FAILURE(EXPECT_FALSE(2 < 3),
2652 "2 < 3");
2653}
2654
2655// Tests EXPECT_EQ.
2656TEST(ExpectTest, EXPECT_EQ) {
2657 EXPECT_EQ(5, 2 + 3);
2658 EXPECT_NONFATAL_FAILURE(EXPECT_EQ(5, 2*3),
2659 "Value of: 2*3\n"
2660 " Actual: 6\n"
2661 "Expected: 5");
2662 EXPECT_NONFATAL_FAILURE(EXPECT_EQ(5, 2 - 3),
2663 "2 - 3");
2664}
2665
2666// Tests using EXPECT_EQ on double values. The purpose is to make
2667// sure that the specialization we did for integer and anonymous enums
2668// isn't used for double arguments.
2669TEST(ExpectTest, EXPECT_EQ_Double) {
2670 // A success.
2671 EXPECT_EQ(5.6, 5.6);
2672
2673 // A failure.
2674 EXPECT_NONFATAL_FAILURE(EXPECT_EQ(5.1, 5.2),
2675 "5.1");
2676}
2677
2678#ifndef __SYMBIAN32__
2679// Tests EXPECT_EQ(NULL, pointer).
2680TEST(ExpectTest, EXPECT_EQ_NULL) {
2681 // A success.
2682 const char* p = NULL;
2683 EXPECT_EQ(NULL, p);
2684
2685 // A failure.
2686 int n = 0;
2687 EXPECT_NONFATAL_FAILURE(EXPECT_EQ(NULL, &n),
2688 "Value of: &n\n");
2689}
2690#endif // __SYMBIAN32__
2691
2692// Tests EXPECT_EQ(0, non_pointer). Since the literal 0 can be
2693// treated as a null pointer by the compiler, we need to make sure
2694// that EXPECT_EQ(0, non_pointer) isn't interpreted by Google Test as
2695// EXPECT_EQ(static_cast<void*>(NULL), non_pointer).
2696TEST(ExpectTest, EXPECT_EQ_0) {
2697 int n = 0;
2698
2699 // A success.
2700 EXPECT_EQ(0, n);
2701
2702 // A failure.
2703 EXPECT_NONFATAL_FAILURE(EXPECT_EQ(0, 5.6),
2704 "Expected: 0");
2705}
2706
2707// Tests EXPECT_NE.
2708TEST(ExpectTest, EXPECT_NE) {
2709 EXPECT_NE(6, 7);
2710
2711 EXPECT_NONFATAL_FAILURE(EXPECT_NE('a', 'a'),
2712 "Expected: ('a') != ('a'), "
2713 "actual: 'a' (97, 0x61) vs 'a' (97, 0x61)");
2714 EXPECT_NONFATAL_FAILURE(EXPECT_NE(2, 2),
2715 "2");
2716 char* const p0 = NULL;
2717 EXPECT_NONFATAL_FAILURE(EXPECT_NE(p0, p0),
2718 "p0");
2719 // Only way to get the Nokia compiler to compile the cast
2720 // is to have a separate void* variable first. Putting
2721 // the two casts on the same line doesn't work, neither does
2722 // a direct C-style to char*.
2723 void* pv1 = (void*)0x1234; // NOLINT
2724 char* const p1 = reinterpret_cast<char*>(pv1);
2725 EXPECT_NONFATAL_FAILURE(EXPECT_NE(p1, p1),
2726 "p1");
2727}
2728
2729// Tests EXPECT_LE.
2730TEST(ExpectTest, EXPECT_LE) {
2731 EXPECT_LE(2, 3);
2732 EXPECT_LE(2, 2);
2733 EXPECT_NONFATAL_FAILURE(EXPECT_LE(2, 0),
2734 "Expected: (2) <= (0), actual: 2 vs 0");
2735 EXPECT_NONFATAL_FAILURE(EXPECT_LE(1.1, 0.9),
2736 "(1.1) <= (0.9)");
2737}
2738
2739// Tests EXPECT_LT.
2740TEST(ExpectTest, EXPECT_LT) {
2741 EXPECT_LT(2, 3);
2742 EXPECT_NONFATAL_FAILURE(EXPECT_LT(2, 2),
2743 "Expected: (2) < (2), actual: 2 vs 2");
2744 EXPECT_NONFATAL_FAILURE(EXPECT_LT(2, 1),
2745 "(2) < (1)");
2746}
2747
2748// Tests EXPECT_GE.
2749TEST(ExpectTest, EXPECT_GE) {
2750 EXPECT_GE(2, 1);
2751 EXPECT_GE(2, 2);
2752 EXPECT_NONFATAL_FAILURE(EXPECT_GE(2, 3),
2753 "Expected: (2) >= (3), actual: 2 vs 3");
2754 EXPECT_NONFATAL_FAILURE(EXPECT_GE(0.9, 1.1),
2755 "(0.9) >= (1.1)");
2756}
2757
2758// Tests EXPECT_GT.
2759TEST(ExpectTest, EXPECT_GT) {
2760 EXPECT_GT(2, 1);
2761 EXPECT_NONFATAL_FAILURE(EXPECT_GT(2, 2),
2762 "Expected: (2) > (2), actual: 2 vs 2");
2763 EXPECT_NONFATAL_FAILURE(EXPECT_GT(2, 3),
2764 "(2) > (3)");
2765}
2766
2767// Make sure we deal with the precedence of <<.
2768TEST(ExpectTest, ExpectPrecedence) {
2769 EXPECT_EQ(1 < 2, true);
2770 EXPECT_NONFATAL_FAILURE(EXPECT_EQ(true, true && false),
2771 "Value of: true && false");
2772}
2773
2774
2775// Tests the StreamableToString() function.
2776
2777// Tests using StreamableToString() on a scalar.
2778TEST(StreamableToStringTest, Scalar) {
2779 EXPECT_STREQ("5", StreamableToString(5).c_str());
2780}
2781
2782// Tests using StreamableToString() on a non-char pointer.
2783TEST(StreamableToStringTest, Pointer) {
2784 int n = 0;
2785 int* p = &n;
2786 EXPECT_STRNE("(null)", StreamableToString(p).c_str());
2787}
2788
2789// Tests using StreamableToString() on a NULL non-char pointer.
2790TEST(StreamableToStringTest, NullPointer) {
2791 int* p = NULL;
2792 EXPECT_STREQ("(null)", StreamableToString(p).c_str());
2793}
2794
2795// Tests using StreamableToString() on a C string.
2796TEST(StreamableToStringTest, CString) {
2797 EXPECT_STREQ("Foo", StreamableToString("Foo").c_str());
2798}
2799
2800// Tests using StreamableToString() on a NULL C string.
2801TEST(StreamableToStringTest, NullCString) {
2802 char* p = NULL;
2803 EXPECT_STREQ("(null)", StreamableToString(p).c_str());
2804}
2805
2806// Tests using streamable values as assertion messages.
2807
2808#if GTEST_HAS_STD_STRING
2809// Tests using std::string as an assertion message.
2810TEST(StreamableTest, string) {
2811 static const std::string str(
2812 "This failure message is a std::string, and is expected.");
2813 EXPECT_FATAL_FAILURE(FAIL() << str,
2814 str.c_str());
2815}
2816
2817// Tests that we can output strings containing embedded NULs.
2818// Limited to Linux because we can only do this with std::string's.
2819TEST(StreamableTest, stringWithEmbeddedNUL) {
2820 static const char char_array_with_nul[] =
2821 "Here's a NUL\0 and some more string";
2822 static const std::string string_with_nul(char_array_with_nul,
2823 sizeof(char_array_with_nul)
2824 - 1); // drops the trailing NUL
2825 EXPECT_FATAL_FAILURE(FAIL() << string_with_nul,
2826 "Here's a NUL\\0 and some more string");
2827}
2828
2829#endif // GTEST_HAS_STD_STRING
2830
2831// Tests that we can output a NUL char.
2832TEST(StreamableTest, NULChar) {
2833 EXPECT_FATAL_FAILURE({ // NOLINT
2834 FAIL() << "A NUL" << '\0' << " and some more string";
2835 }, "A NUL\\0 and some more string");
2836}
2837
2838// Tests using int as an assertion message.
2839TEST(StreamableTest, int) {
2840 EXPECT_FATAL_FAILURE(FAIL() << 900913,
2841 "900913");
2842}
2843
2844// Tests using NULL char pointer as an assertion message.
2845//
2846// In MSVC, streaming a NULL char * causes access violation. Google Test
2847// implemented a workaround (substituting "(null)" for NULL). This
2848// tests whether the workaround works.
2849TEST(StreamableTest, NullCharPtr) {
2850 EXPECT_FATAL_FAILURE(FAIL() << static_cast<const char*>(NULL),
2851 "(null)");
2852}
2853
2854// Tests that basic IO manipulators (endl, ends, and flush) can be
2855// streamed to testing::Message.
2856TEST(StreamableTest, BasicIoManip) {
2857 EXPECT_FATAL_FAILURE({ // NOLINT
2858 FAIL() << "Line 1." << std::endl
2859 << "A NUL char " << std::ends << std::flush << " in line 2.";
2860 }, "Line 1.\nA NUL char \\0 in line 2.");
2861}
2862
2863
2864// Tests the macros that haven't been covered so far.
2865
2866void AddFailureHelper(bool* aborted) {
2867 *aborted = true;
2868 ADD_FAILURE() << "Failure";
2869 *aborted = false;
2870}
2871
2872// Tests ADD_FAILURE.
2873TEST(MacroTest, ADD_FAILURE) {
2874 bool aborted = true;
2875 EXPECT_NONFATAL_FAILURE(AddFailureHelper(&aborted),
2876 "Failure");
2877 EXPECT_FALSE(aborted);
2878}
2879
2880// Tests FAIL.
2881TEST(MacroTest, FAIL) {
2882 EXPECT_FATAL_FAILURE(FAIL(),
2883 "Failed");
2884 EXPECT_FATAL_FAILURE(FAIL() << "Intentional failure.",
2885 "Intentional failure.");
2886}
2887
2888// Tests SUCCEED
2889TEST(MacroTest, SUCCEED) {
2890 SUCCEED();
2891 SUCCEED() << "Explicit success.";
2892}
2893
2894
2895// Tests for EXPECT_EQ() and ASSERT_EQ().
2896//
2897// These tests fail *intentionally*, s.t. the failure messages can be
2898// generated and tested.
2899//
2900// We have different tests for different argument types.
2901
2902// Tests using bool values in {EXPECT|ASSERT}_EQ.
2903TEST(EqAssertionTest, Bool) {
2904 EXPECT_EQ(true, true);
2905 EXPECT_FATAL_FAILURE(ASSERT_EQ(false, true),
2906 "Value of: true");
2907}
2908
2909// Tests using int values in {EXPECT|ASSERT}_EQ.
2910TEST(EqAssertionTest, Int) {
2911 ASSERT_EQ(32, 32);
2912 EXPECT_NONFATAL_FAILURE(EXPECT_EQ(32, 33),
2913 "33");
2914}
2915
2916// Tests using time_t values in {EXPECT|ASSERT}_EQ.
2917TEST(EqAssertionTest, Time_T) {
2918 EXPECT_EQ(static_cast<time_t>(0),
2919 static_cast<time_t>(0));
2920 EXPECT_FATAL_FAILURE(ASSERT_EQ(static_cast<time_t>(0),
2921 static_cast<time_t>(1234)),
2922 "1234");
2923}
2924
2925// Tests using char values in {EXPECT|ASSERT}_EQ.
2926TEST(EqAssertionTest, Char) {
2927 ASSERT_EQ('z', 'z');
2928 const char ch = 'b';
2929 EXPECT_NONFATAL_FAILURE(EXPECT_EQ('\0', ch),
2930 "ch");
2931 EXPECT_NONFATAL_FAILURE(EXPECT_EQ('a', ch),
2932 "ch");
2933}
2934
2935// Tests using wchar_t values in {EXPECT|ASSERT}_EQ.
2936TEST(EqAssertionTest, WideChar) {
2937 EXPECT_EQ(L'b', L'b');
2938
2939 EXPECT_NONFATAL_FAILURE(EXPECT_EQ(L'\0', L'x'),
2940 "Value of: L'x'\n"
2941 " Actual: L'x' (120, 0x78)\n"
2942 "Expected: L'\0'\n"
2943 "Which is: L'\0' (0, 0x0)");
2944
2945 static wchar_t wchar;
2946 wchar = L'b';
2947 EXPECT_NONFATAL_FAILURE(EXPECT_EQ(L'a', wchar),
2948 "wchar");
2949 wchar = L'\x8119';
2950 EXPECT_FATAL_FAILURE(ASSERT_EQ(L'\x8120', wchar),
2951 "Value of: wchar");
2952}
2953
2954#if GTEST_HAS_STD_STRING
2955// Tests using ::std::string values in {EXPECT|ASSERT}_EQ.
2956TEST(EqAssertionTest, StdString) {
2957 // Compares a const char* to an std::string that has identical
2958 // content.
2959 ASSERT_EQ("Test", ::std::string("Test"));
2960
2961 // Compares two identical std::strings.
2962 static const ::std::string str1("A * in the middle");
2963 static const ::std::string str2(str1);
2964 EXPECT_EQ(str1, str2);
2965
2966 // Compares a const char* to an std::string that has different
2967 // content
2968 EXPECT_NONFATAL_FAILURE(EXPECT_EQ("Test", ::std::string("test")),
2969 "::std::string(\"test\")");
2970
2971 // Compares an std::string to a char* that has different content.
2972 char* const p1 = const_cast<char*>("foo");
2973 EXPECT_NONFATAL_FAILURE(EXPECT_EQ(::std::string("bar"), p1),
2974 "p1");
2975
2976 // Compares two std::strings that have different contents, one of
2977 // which having a NUL character in the middle. This should fail.
2978 static ::std::string str3(str1);
2979 str3.at(2) = '\0';
2980 EXPECT_FATAL_FAILURE(ASSERT_EQ(str1, str3),
2981 "Value of: str3\n"
2982 " Actual: \"A \\0 in the middle\"");
2983}
2984
2985#endif // GTEST_HAS_STD_STRING
2986
2987#if GTEST_HAS_STD_WSTRING
2988
2989// Tests using ::std::wstring values in {EXPECT|ASSERT}_EQ.
2990TEST(EqAssertionTest, StdWideString) {
2991 // Compares an std::wstring to a const wchar_t* that has identical
2992 // content.
2993 EXPECT_EQ(::std::wstring(L"Test\x8119"), L"Test\x8119");
2994
2995 // Compares two identical std::wstrings.
2996 const ::std::wstring wstr1(L"A * in the middle");
2997 const ::std::wstring wstr2(wstr1);
2998 ASSERT_EQ(wstr1, wstr2);
2999
3000 // Compares an std::wstring to a const wchar_t* that has different
3001 // content.
3002 EXPECT_NONFATAL_FAILURE({ // NOLINT
3003 EXPECT_EQ(::std::wstring(L"Test\x8119"), L"Test\x8120");
3004 }, "L\"Test\\x8120\"");
3005
3006 // Compares two std::wstrings that have different contents, one of
3007 // which having a NUL character in the middle.
3008 ::std::wstring wstr3(wstr1);
3009 wstr3.at(2) = L'\0';
3010 EXPECT_NONFATAL_FAILURE(EXPECT_EQ(wstr1, wstr3),
3011 "wstr3");
3012
3013 // Compares a wchar_t* to an std::wstring that has different
3014 // content.
3015 EXPECT_FATAL_FAILURE({ // NOLINT
3016 ASSERT_EQ(const_cast<wchar_t*>(L"foo"), ::std::wstring(L"bar"));
3017 }, "");
3018}
3019
3020#endif // GTEST_HAS_STD_WSTRING
3021
3022#if GTEST_HAS_GLOBAL_STRING
3023// Tests using ::string values in {EXPECT|ASSERT}_EQ.
3024TEST(EqAssertionTest, GlobalString) {
3025 // Compares a const char* to a ::string that has identical content.
3026 EXPECT_EQ("Test", ::string("Test"));
3027
3028 // Compares two identical ::strings.
3029 const ::string str1("A * in the middle");
3030 const ::string str2(str1);
3031 ASSERT_EQ(str1, str2);
3032
3033 // Compares a ::string to a const char* that has different content.
3034 EXPECT_NONFATAL_FAILURE(EXPECT_EQ(::string("Test"), "test"),
3035 "test");
3036
3037 // Compares two ::strings that have different contents, one of which
3038 // having a NUL character in the middle.
3039 ::string str3(str1);
3040 str3.at(2) = '\0';
3041 EXPECT_NONFATAL_FAILURE(EXPECT_EQ(str1, str3),
3042 "str3");
3043
3044 // Compares a ::string to a char* that has different content.
3045 EXPECT_FATAL_FAILURE({ // NOLINT
3046 ASSERT_EQ(::string("bar"), const_cast<char*>("foo"));
3047 }, "");
3048}
3049
3050#endif // GTEST_HAS_GLOBAL_STRING
3051
3052#if GTEST_HAS_GLOBAL_WSTRING
3053
3054// Tests using ::wstring values in {EXPECT|ASSERT}_EQ.
3055TEST(EqAssertionTest, GlobalWideString) {
3056 // Compares a const wchar_t* to a ::wstring that has identical content.
3057 ASSERT_EQ(L"Test\x8119", ::wstring(L"Test\x8119"));
3058
3059 // Compares two identical ::wstrings.
3060 static const ::wstring wstr1(L"A * in the middle");
3061 static const ::wstring wstr2(wstr1);
3062 EXPECT_EQ(wstr1, wstr2);
3063
3064 // Compares a const wchar_t* to a ::wstring that has different
3065 // content.
3066 EXPECT_NONFATAL_FAILURE({ // NOLINT
3067 EXPECT_EQ(L"Test\x8120", ::wstring(L"Test\x8119"));
3068 }, "Test\\x8119");
3069
3070 // Compares a wchar_t* to a ::wstring that has different content.
3071 wchar_t* const p1 = const_cast<wchar_t*>(L"foo");
3072 EXPECT_NONFATAL_FAILURE(EXPECT_EQ(p1, ::wstring(L"bar")),
3073 "bar");
3074
3075 // Compares two ::wstrings that have different contents, one of which
3076 // having a NUL character in the middle.
3077 static ::wstring wstr3;
3078 wstr3 = wstr1;
3079 wstr3.at(2) = L'\0';
3080 EXPECT_FATAL_FAILURE(ASSERT_EQ(wstr1, wstr3),
3081 "wstr3");
3082}
3083
3084#endif // GTEST_HAS_GLOBAL_WSTRING
3085
3086// Tests using char pointers in {EXPECT|ASSERT}_EQ.
3087TEST(EqAssertionTest, CharPointer) {
3088 char* const p0 = NULL;
3089 // Only way to get the Nokia compiler to compile the cast
3090 // is to have a separate void* variable first. Putting
3091 // the two casts on the same line doesn't work, neither does
3092 // a direct C-style to char*.
3093 void* pv1 = (void*)0x1234; // NOLINT
3094 void* pv2 = (void*)0xABC0; // NOLINT
3095 char* const p1 = reinterpret_cast<char*>(pv1);
3096 char* const p2 = reinterpret_cast<char*>(pv2);
3097 ASSERT_EQ(p1, p1);
3098
3099 EXPECT_NONFATAL_FAILURE(EXPECT_EQ(p0, p2),
3100 "Value of: p2");
3101 EXPECT_NONFATAL_FAILURE(EXPECT_EQ(p1, p2),
3102 "p2");
3103 EXPECT_FATAL_FAILURE(ASSERT_EQ(reinterpret_cast<char*>(0x1234),
3104 reinterpret_cast<char*>(0xABC0)),
3105 "ABC0");
3106}
3107
3108// Tests using wchar_t pointers in {EXPECT|ASSERT}_EQ.
3109TEST(EqAssertionTest, WideCharPointer) {
3110 wchar_t* const p0 = NULL;
3111 // Only way to get the Nokia compiler to compile the cast
3112 // is to have a separate void* variable first. Putting
3113 // the two casts on the same line doesn't work, neither does
3114 // a direct C-style to char*.
3115 void* pv1 = (void*)0x1234; // NOLINT
3116 void* pv2 = (void*)0xABC0; // NOLINT
3117 wchar_t* const p1 = reinterpret_cast<wchar_t*>(pv1);
3118 wchar_t* const p2 = reinterpret_cast<wchar_t*>(pv2);
3119 EXPECT_EQ(p0, p0);
3120
3121 EXPECT_NONFATAL_FAILURE(EXPECT_EQ(p0, p2),
3122 "Value of: p2");
3123 EXPECT_NONFATAL_FAILURE(EXPECT_EQ(p1, p2),
3124 "p2");
3125 void* pv3 = (void*)0x1234; // NOLINT
3126 void* pv4 = (void*)0xABC0; // NOLINT
3127 const wchar_t* p3 = reinterpret_cast<const wchar_t*>(pv3);
3128 const wchar_t* p4 = reinterpret_cast<const wchar_t*>(pv4);
3129 EXPECT_NONFATAL_FAILURE(EXPECT_EQ(p3, p4),
3130 "p4");
3131}
3132
3133// Tests using other types of pointers in {EXPECT|ASSERT}_EQ.
3134TEST(EqAssertionTest, OtherPointer) {
3135 ASSERT_EQ(static_cast<const int*>(NULL),
3136 static_cast<const int*>(NULL));
3137 EXPECT_FATAL_FAILURE(ASSERT_EQ(static_cast<const int*>(NULL),
3138 reinterpret_cast<const int*>(0x1234)),
3139 "0x1234");
3140}
3141
3142// Tests the FRIEND_TEST macro.
3143
3144// This class has a private member we want to test. We will test it
3145// both in a TEST and in a TEST_F.
3146class Foo {
3147 public:
3148 Foo() {}
3149
3150 private:
3151 int Bar() const { return 1; }
3152
3153 // Declares the friend tests that can access the private member
3154 // Bar().
3155 FRIEND_TEST(FRIEND_TEST_Test, TEST);
3156 FRIEND_TEST(FRIEND_TEST_Test2, TEST_F);
3157};
3158
3159// Tests that the FRIEND_TEST declaration allows a TEST to access a
3160// class's private members. This should compile.
3161TEST(FRIEND_TEST_Test, TEST) {
3162 ASSERT_EQ(1, Foo().Bar());
3163}
3164
3165// The fixture needed to test using FRIEND_TEST with TEST_F.
3166class FRIEND_TEST_Test2 : public testing::Test {
3167 protected:
3168 Foo foo;
3169};
3170
3171// Tests that the FRIEND_TEST declaration allows a TEST_F to access a
3172// class's private members. This should compile.
3173TEST_F(FRIEND_TEST_Test2, TEST_F) {
3174 ASSERT_EQ(1, foo.Bar());
3175}
3176
3177// Tests the life cycle of Test objects.
3178
3179// The test fixture for testing the life cycle of Test objects.
3180//
3181// This class counts the number of live test objects that uses this
3182// fixture.
3183class TestLifeCycleTest : public testing::Test {
3184 protected:
3185 // Constructor. Increments the number of test objects that uses
3186 // this fixture.
3187 TestLifeCycleTest() { count_++; }
3188
3189 // Destructor. Decrements the number of test objects that uses this
3190 // fixture.
3191 ~TestLifeCycleTest() { count_--; }
3192
3193 // Returns the number of live test objects that uses this fixture.
3194 int count() const { return count_; }
3195
3196 private:
3197 static int count_;
3198};
3199
3200int TestLifeCycleTest::count_ = 0;
3201
3202// Tests the life cycle of test objects.
3203TEST_F(TestLifeCycleTest, Test1) {
3204 // There should be only one test object in this test case that's
3205 // currently alive.
3206 ASSERT_EQ(1, count());
3207}
3208
3209// Tests the life cycle of test objects.
3210TEST_F(TestLifeCycleTest, Test2) {
3211 // After Test1 is done and Test2 is started, there should still be
3212 // only one live test object, as the object for Test1 should've been
3213 // deleted.
3214 ASSERT_EQ(1, count());
3215}
3216
3217} // namespace
3218
3219// Tests streaming a user type whose definition and operator << are
3220// both in the global namespace.
3221class Base {
3222 public:
3223 explicit Base(int x) : x_(x) {}
3224 int x() const { return x_; }
3225 private:
3226 int x_;
3227};
3228std::ostream& operator<<(std::ostream& os,
3229 const Base& val) {
3230 return os << val.x();
3231}
3232std::ostream& operator<<(std::ostream& os,
3233 const Base* pointer) {
3234 return os << "(" << pointer->x() << ")";
3235}
3236
3237TEST(MessageTest, CanStreamUserTypeInGlobalNameSpace) {
3238 testing::Message msg;
3239 Base a(1);
3240
3241 msg << a << &a; // Uses ::operator<<.
3242 EXPECT_STREQ("1(1)", msg.GetString().c_str());
3243}
3244
3245// Tests streaming a user type whose definition and operator<< are
3246// both in an unnamed namespace.
3247namespace {
3248class MyTypeInUnnamedNameSpace : public Base {
3249 public:
3250 explicit MyTypeInUnnamedNameSpace(int x): Base(x) {}
3251};
3252std::ostream& operator<<(std::ostream& os,
3253 const MyTypeInUnnamedNameSpace& val) {
3254 return os << val.x();
3255}
3256std::ostream& operator<<(std::ostream& os,
3257 const MyTypeInUnnamedNameSpace* pointer) {
3258 return os << "(" << pointer->x() << ")";
3259}
3260} // namespace
3261
3262TEST(MessageTest, CanStreamUserTypeInUnnamedNameSpace) {
3263 testing::Message msg;
3264 MyTypeInUnnamedNameSpace a(1);
3265
3266 msg << a << &a; // Uses <unnamed_namespace>::operator<<.
3267 EXPECT_STREQ("1(1)", msg.GetString().c_str());
3268}
3269
3270// Tests streaming a user type whose definition and operator<< are
3271// both in a user namespace.
3272namespace namespace1 {
3273class MyTypeInNameSpace1 : public Base {
3274 public:
3275 explicit MyTypeInNameSpace1(int x): Base(x) {}
3276};
3277std::ostream& operator<<(std::ostream& os,
3278 const MyTypeInNameSpace1& val) {
3279 return os << val.x();
3280}
3281std::ostream& operator<<(std::ostream& os,
3282 const MyTypeInNameSpace1* pointer) {
3283 return os << "(" << pointer->x() << ")";
3284}
3285} // namespace namespace1
3286
3287TEST(MessageTest, CanStreamUserTypeInUserNameSpace) {
3288 testing::Message msg;
3289 namespace1::MyTypeInNameSpace1 a(1);
3290
3291 msg << a << &a; // Uses namespace1::operator<<.
3292 EXPECT_STREQ("1(1)", msg.GetString().c_str());
3293}
3294
3295// Tests streaming a user type whose definition is in a user namespace
3296// but whose operator<< is in the global namespace.
3297namespace namespace2 {
3298class MyTypeInNameSpace2 : public ::Base {
3299 public:
3300 explicit MyTypeInNameSpace2(int x): Base(x) {}
3301};
3302} // namespace namespace2
3303std::ostream& operator<<(std::ostream& os,
3304 const namespace2::MyTypeInNameSpace2& val) {
3305 return os << val.x();
3306}
3307std::ostream& operator<<(std::ostream& os,
3308 const namespace2::MyTypeInNameSpace2* pointer) {
3309 return os << "(" << pointer->x() << ")";
3310}
3311
3312TEST(MessageTest, CanStreamUserTypeInUserNameSpaceWithStreamOperatorInGlobal) {
3313 testing::Message msg;
3314 namespace2::MyTypeInNameSpace2 a(1);
3315
3316 msg << a << &a; // Uses ::operator<<.
3317 EXPECT_STREQ("1(1)", msg.GetString().c_str());
3318}
3319
3320// Tests streaming NULL pointers to testing::Message.
3321TEST(MessageTest, NullPointers) {
3322 testing::Message msg;
3323 char* const p1 = NULL;
3324 unsigned char* const p2 = NULL;
3325 int* p3 = NULL;
3326 double* p4 = NULL;
3327 bool* p5 = NULL;
3328 testing::Message* p6 = NULL;
3329
3330 msg << p1 << p2 << p3 << p4 << p5 << p6;
3331 ASSERT_STREQ("(null)(null)(null)(null)(null)(null)",
3332 msg.GetString().c_str());
3333}
3334
3335// Tests streaming wide strings to testing::Message.
3336TEST(MessageTest, WideStrings) {
3337 using testing::Message;
3338
3339 // Streams a NULL of type const wchar_t*.
3340 const wchar_t* const_wstr = NULL;
3341 EXPECT_STREQ("(null)",
3342 (Message() << const_wstr).GetString().c_str());
3343
3344 // Streams a NULL of type wchar_t*.
3345 wchar_t* wstr = NULL;
3346 EXPECT_STREQ("(null)",
3347 (Message() << wstr).GetString().c_str());
3348
3349 // Streams a non-NULL of type const wchar_t*.
3350 const_wstr = L"abc\x8119";
3351 EXPECT_STREQ("abc\xe8\x84\x99",
3352 (Message() << const_wstr).GetString().c_str());
3353
3354 // Streams a non-NULL of type wchar_t*.
3355 wstr = const_cast<wchar_t*>(const_wstr);
3356 EXPECT_STREQ("abc\xe8\x84\x99",
3357 (Message() << wstr).GetString().c_str());
3358}
3359
3360
3361// This line tests that we can define tests in the testing namespace.
3362namespace testing {
3363
3364// Tests the TestInfo class.
3365
3366class TestInfoTest : public testing::Test {
3367 protected:
3368 static TestInfo * GetTestInfo(const char* test_name) {
3369 return UnitTest::GetInstance()->impl()->
3370 GetTestCase("TestInfoTest", NULL, NULL)->
3371 GetTestInfo(test_name);
3372 }
3373
3374 static const TestResult* GetTestResult(
3375 const testing::TestInfo* test_info) {
3376 return test_info->result();
3377 }
3378};
3379
3380// Tests TestInfo::test_case_name() and TestInfo::name().
3381TEST_F(TestInfoTest, Names) {
3382 TestInfo * const test_info = GetTestInfo("Names");
3383
3384 ASSERT_STREQ("TestInfoTest", test_info->test_case_name());
3385 ASSERT_STREQ("Names", test_info->name());
3386}
3387
3388// Tests TestInfo::result().
3389TEST_F(TestInfoTest, result) {
3390 TestInfo * const test_info = GetTestInfo("result");
3391
3392 // Initially, there is no TestPartResult for this test.
3393 ASSERT_EQ(0u, GetTestResult(test_info)->total_part_count());
3394
3395 // After the previous assertion, there is still none.
3396 ASSERT_EQ(0u, GetTestResult(test_info)->total_part_count());
3397}
3398
3399// Tests setting up and tearing down a test case.
3400
3401class SetUpTestCaseTest : public testing::Test {
3402 protected:
3403 // This will be called once before the first test in this test case
3404 // is run.
3405 static void SetUpTestCase() {
3406 printf("Setting up the test case . . .\n");
3407
3408 // Initializes some shared resource. In this simple example, we
3409 // just create a C string. More complex stuff can be done if
3410 // desired.
3411 shared_resource_ = "123";
3412
3413 // Increments the number of test cases that have been set up.
3414 counter_++;
3415
3416 // SetUpTestCase() should be called only once.
3417 EXPECT_EQ(1, counter_);
3418 }
3419
3420 // This will be called once after the last test in this test case is
3421 // run.
3422 static void TearDownTestCase() {
3423 printf("Tearing down the test case . . .\n");
3424
3425 // Decrements the number of test cases that have been set up.
3426 counter_--;
3427
3428 // TearDownTestCase() should be called only once.
3429 EXPECT_EQ(0, counter_);
3430
3431 // Cleans up the shared resource.
3432 shared_resource_ = NULL;
3433 }
3434
3435 // This will be called before each test in this test case.
3436 virtual void SetUp() {
3437 // SetUpTestCase() should be called only once, so counter_ should
3438 // always be 1.
3439 EXPECT_EQ(1, counter_);
3440 }
3441
3442 // Number of test cases that have been set up.
3443 static int counter_;
3444
3445 // Some resource to be shared by all tests in this test case.
3446 static const char* shared_resource_;
3447};
3448
3449int SetUpTestCaseTest::counter_ = 0;
3450const char* SetUpTestCaseTest::shared_resource_ = NULL;
3451
3452// A test that uses the shared resource.
3453TEST_F(SetUpTestCaseTest, Test1) {
3454 EXPECT_STRNE(NULL, shared_resource_);
3455}
3456
3457// Another test that uses the shared resource.
3458TEST_F(SetUpTestCaseTest, Test2) {
3459 EXPECT_STREQ("123", shared_resource_);
3460}
3461
3462// The InitGoogleTestTest test case tests testing::InitGoogleTest().
3463
3464// The Flags struct stores a copy of all Google Test flags.
3465struct Flags {
3466 // Constructs a Flags struct where each flag has its default value.
3467 Flags() : break_on_failure(false),
3468 catch_exceptions(false),
3469 filter(""),
3470 list_tests(false),
3471 output(""),
3472 repeat(1) {}
3473
3474 // Factory methods.
3475
3476 // Creates a Flags struct where the gtest_break_on_failure flag has
3477 // the given value.
3478 static Flags BreakOnFailure(bool break_on_failure) {
3479 Flags flags;
3480 flags.break_on_failure = break_on_failure;
3481 return flags;
3482 }
3483
3484 // Creates a Flags struct where the gtest_catch_exceptions flag has
3485 // the given value.
3486 static Flags CatchExceptions(bool catch_exceptions) {
3487 Flags flags;
3488 flags.catch_exceptions = catch_exceptions;
3489 return flags;
3490 }
3491
3492 // Creates a Flags struct where the gtest_filter flag has the given
3493 // value.
3494 static Flags Filter(const char* filter) {
3495 Flags flags;
3496 flags.filter = filter;
3497 return flags;
3498 }
3499
3500 // Creates a Flags struct where the gtest_list_tests flag has the
3501 // given value.
3502 static Flags ListTests(bool list_tests) {
3503 Flags flags;
3504 flags.list_tests = list_tests;
3505 return flags;
3506 }
3507
3508 // Creates a Flags struct where the gtest_output flag has the given
3509 // value.
3510 static Flags Output(const char* output) {
3511 Flags flags;
3512 flags.output = output;
3513 return flags;
3514 }
3515
3516 // Creates a Flags struct where the gtest_repeat flag has the given
3517 // value.
3518 static Flags Repeat(Int32 repeat) {
3519 Flags flags;
3520 flags.repeat = repeat;
3521 return flags;
3522 }
3523
3524 // These fields store the flag values.
3525 bool break_on_failure;
3526 bool catch_exceptions;
3527 const char* filter;
3528 bool list_tests;
3529 const char* output;
3530 Int32 repeat;
3531};
3532
3533// Fixture for testing InitGoogleTest().
3534class InitGoogleTestTest : public testing::Test {
3535 protected:
3536 // Clears the flags before each test.
3537 virtual void SetUp() {
3538 GTEST_FLAG(break_on_failure) = false;
3539 GTEST_FLAG(catch_exceptions) = false;
3540 GTEST_FLAG(filter) = "";
3541 GTEST_FLAG(list_tests) = false;
3542 GTEST_FLAG(output) = "";
3543 GTEST_FLAG(repeat) = 1;
3544 }
3545
3546 // Asserts that two narrow or wide string arrays are equal.
3547 template <typename CharType>
3548 static void AssertStringArrayEq(size_t size1, CharType** array1,
3549 size_t size2, CharType** array2) {
3550 ASSERT_EQ(size1, size2) << " Array sizes different.";
3551
3552 for (size_t i = 0; i != size1; i++) {
3553 ASSERT_STREQ(array1[i], array2[i]) << " where i == " << i;
3554 }
3555 }
3556
3557 // Verifies that the flag values match the expected values.
3558 static void CheckFlags(const Flags& expected) {
3559 EXPECT_EQ(expected.break_on_failure, GTEST_FLAG(break_on_failure));
3560 EXPECT_EQ(expected.catch_exceptions, GTEST_FLAG(catch_exceptions));
3561 EXPECT_STREQ(expected.filter, GTEST_FLAG(filter).c_str());
3562 EXPECT_EQ(expected.list_tests, GTEST_FLAG(list_tests));
3563 EXPECT_STREQ(expected.output, GTEST_FLAG(output).c_str());
3564 EXPECT_EQ(expected.repeat, GTEST_FLAG(repeat));
3565 }
3566
3567 // Parses a command line (specified by argc1 and argv1), then
3568 // verifies that the flag values are expected and that the
3569 // recognized flags are removed from the command line.
3570 template <typename CharType>
3571 static void TestParsingFlags(int argc1, const CharType** argv1,
3572 int argc2, const CharType** argv2,
3573 const Flags& expected) {
3574 // Parses the command line.
3575 InitGoogleTest(&argc1, const_cast<CharType**>(argv1));
3576
3577 // Verifies the flag values.
3578 CheckFlags(expected);
3579
3580 // Verifies that the recognized flags are removed from the command
3581 // line.
3582 AssertStringArrayEq(argc1 + 1, argv1, argc2 + 1, argv2);
3583 }
3584
3585 // This macro wraps TestParsingFlags s.t. the user doesn't need
3586 // to specify the array sizes.
3587#define TEST_PARSING_FLAGS(argv1, argv2, expected) \
3588 TestParsingFlags(sizeof(argv1)/sizeof(*argv1) - 1, argv1, \
3589 sizeof(argv2)/sizeof(*argv2) - 1, argv2, expected)
3590};
3591
3592// Tests parsing an empty command line.
3593TEST_F(InitGoogleTestTest, Empty) {
3594 const char* argv[] = {
3595 NULL
3596 };
3597
3598 const char* argv2[] = {
3599 NULL
3600 };
3601
3602 TEST_PARSING_FLAGS(argv, argv2, Flags());
3603}
3604
3605// Tests parsing a command line that has no flag.
3606TEST_F(InitGoogleTestTest, NoFlag) {
3607 const char* argv[] = {
3608 "foo.exe",
3609 NULL
3610 };
3611
3612 const char* argv2[] = {
3613 "foo.exe",
3614 NULL
3615 };
3616
3617 TEST_PARSING_FLAGS(argv, argv2, Flags());
3618}
3619
3620// Tests parsing a bad --gtest_filter flag.
3621TEST_F(InitGoogleTestTest, FilterBad) {
3622 const char* argv[] = {
3623 "foo.exe",
3624 "--gtest_filter",
3625 NULL
3626 };
3627
3628 const char* argv2[] = {
3629 "foo.exe",
3630 "--gtest_filter",
3631 NULL
3632 };
3633
3634 TEST_PARSING_FLAGS(argv, argv2, Flags::Filter(""));
3635}
3636
3637// Tests parsing an empty --gtest_filter flag.
3638TEST_F(InitGoogleTestTest, FilterEmpty) {
3639 const char* argv[] = {
3640 "foo.exe",
3641 "--gtest_filter=",
3642 NULL
3643 };
3644
3645 const char* argv2[] = {
3646 "foo.exe",
3647 NULL
3648 };
3649
3650 TEST_PARSING_FLAGS(argv, argv2, Flags::Filter(""));
3651}
3652
3653// Tests parsing a non-empty --gtest_filter flag.
3654TEST_F(InitGoogleTestTest, FilterNonEmpty) {
3655 const char* argv[] = {
3656 "foo.exe",
3657 "--gtest_filter=abc",
3658 NULL
3659 };
3660
3661 const char* argv2[] = {
3662 "foo.exe",
3663 NULL
3664 };
3665
3666 TEST_PARSING_FLAGS(argv, argv2, Flags::Filter("abc"));
3667}
3668
3669// Tests parsing --gtest_break_on_failure.
3670TEST_F(InitGoogleTestTest, BreakOnFailureNoDef) {
3671 const char* argv[] = {
3672 "foo.exe",
3673 "--gtest_break_on_failure",
3674 NULL
3675};
3676
3677 const char* argv2[] = {
3678 "foo.exe",
3679 NULL
3680 };
3681
3682 TEST_PARSING_FLAGS(argv, argv2, Flags::BreakOnFailure(true));
3683}
3684
3685// Tests parsing --gtest_break_on_failure=0.
3686TEST_F(InitGoogleTestTest, BreakOnFailureFalse_0) {
3687 const char* argv[] = {
3688 "foo.exe",
3689 "--gtest_break_on_failure=0",
3690 NULL
3691 };
3692
3693 const char* argv2[] = {
3694 "foo.exe",
3695 NULL
3696 };
3697
3698 TEST_PARSING_FLAGS(argv, argv2, Flags::BreakOnFailure(false));
3699}
3700
3701// Tests parsing --gtest_break_on_failure=f.
3702TEST_F(InitGoogleTestTest, BreakOnFailureFalse_f) {
3703 const char* argv[] = {
3704 "foo.exe",
3705 "--gtest_break_on_failure=f",
3706 NULL
3707 };
3708
3709 const char* argv2[] = {
3710 "foo.exe",
3711 NULL
3712 };
3713
3714 TEST_PARSING_FLAGS(argv, argv2, Flags::BreakOnFailure(false));
3715}
3716
3717// Tests parsing --gtest_break_on_failure=F.
3718TEST_F(InitGoogleTestTest, BreakOnFailureFalse_F) {
3719 const char* argv[] = {
3720 "foo.exe",
3721 "--gtest_break_on_failure=F",
3722 NULL
3723 };
3724
3725 const char* argv2[] = {
3726 "foo.exe",
3727 NULL
3728 };
3729
3730 TEST_PARSING_FLAGS(argv, argv2, Flags::BreakOnFailure(false));
3731}
3732
3733// Tests parsing a --gtest_break_on_failure flag that has a "true"
3734// definition.
3735TEST_F(InitGoogleTestTest, BreakOnFailureTrue) {
3736 const char* argv[] = {
3737 "foo.exe",
3738 "--gtest_break_on_failure=1",
3739 NULL
3740 };
3741
3742 const char* argv2[] = {
3743 "foo.exe",
3744 NULL
3745 };
3746
3747 TEST_PARSING_FLAGS(argv, argv2, Flags::BreakOnFailure(true));
3748}
3749
3750// Tests parsing --gtest_catch_exceptions.
3751TEST_F(InitGoogleTestTest, CatchExceptions) {
3752 const char* argv[] = {
3753 "foo.exe",
3754 "--gtest_catch_exceptions",
3755 NULL
3756 };
3757
3758 const char* argv2[] = {
3759 "foo.exe",
3760 NULL
3761 };
3762
3763 TEST_PARSING_FLAGS(argv, argv2, Flags::CatchExceptions(true));
3764}
3765
3766// Tests having the same flag twice with different values. The
3767// expected behavior is that the one coming last takes precedence.
3768TEST_F(InitGoogleTestTest, DuplicatedFlags) {
3769 const char* argv[] = {
3770 "foo.exe",
3771 "--gtest_filter=a",
3772 "--gtest_filter=b",
3773 NULL
3774 };
3775
3776 const char* argv2[] = {
3777 "foo.exe",
3778 NULL
3779 };
3780
3781 TEST_PARSING_FLAGS(argv, argv2, Flags::Filter("b"));
3782}
3783
3784// Tests having an unrecognized flag on the command line.
3785TEST_F(InitGoogleTestTest, UnrecognizedFlag) {
3786 const char* argv[] = {
3787 "foo.exe",
3788 "--gtest_break_on_failure",
3789 "bar", // Unrecognized by Google Test.
3790 "--gtest_filter=b",
3791 NULL
3792 };
3793
3794 const char* argv2[] = {
3795 "foo.exe",
3796 "bar",
3797 NULL
3798 };
3799
3800 Flags flags;
3801 flags.break_on_failure = true;
3802 flags.filter = "b";
3803 TEST_PARSING_FLAGS(argv, argv2, flags);
3804}
3805
3806// Tests having a --gtest_list_tests flag
3807TEST_F(InitGoogleTestTest, ListTestsFlag) {
3808 const char* argv[] = {
3809 "foo.exe",
3810 "--gtest_list_tests",
3811 NULL
3812 };
3813
3814 const char* argv2[] = {
3815 "foo.exe",
3816 NULL
3817 };
3818
3819 TEST_PARSING_FLAGS(argv, argv2, Flags::ListTests(true));
3820}
3821
3822// Tests having a --gtest_list_tests flag with a "true" value
3823TEST_F(InitGoogleTestTest, ListTestsTrue) {
3824 const char* argv[] = {
3825 "foo.exe",
3826 "--gtest_list_tests=1",
3827 NULL
3828 };
3829
3830 const char* argv2[] = {
3831 "foo.exe",
3832 NULL
3833 };
3834
3835 TEST_PARSING_FLAGS(argv, argv2, Flags::ListTests(true));
3836}
3837
3838// Tests having a --gtest_list_tests flag with a "false" value
3839TEST_F(InitGoogleTestTest, ListTestsFalse) {
3840 const char* argv[] = {
3841 "foo.exe",
3842 "--gtest_list_tests=0",
3843 NULL
3844 };
3845
3846 const char* argv2[] = {
3847 "foo.exe",
3848 NULL
3849 };
3850
3851 TEST_PARSING_FLAGS(argv, argv2, Flags::ListTests(false));
3852}
3853
3854// Tests parsing --gtest_list_tests=f.
3855TEST_F(InitGoogleTestTest, ListTestsFalse_f) {
3856 const char* argv[] = {
3857 "foo.exe",
3858 "--gtest_list_tests=f",
3859 NULL
3860 };
3861
3862 const char* argv2[] = {
3863 "foo.exe",
3864 NULL
3865 };
3866
3867 TEST_PARSING_FLAGS(argv, argv2, Flags::ListTests(false));
3868}
3869
3870// Tests parsing --gtest_break_on_failure=F.
3871TEST_F(InitGoogleTestTest, ListTestsFalse_F) {
3872 const char* argv[] = {
3873 "foo.exe",
3874 "--gtest_list_tests=F",
3875 NULL
3876 };
3877
3878 const char* argv2[] = {
3879 "foo.exe",
3880 NULL
3881 };
3882
3883 TEST_PARSING_FLAGS(argv, argv2, Flags::ListTests(false));
3884}
3885
3886// Tests parsing --gtest_output (invalid).
3887TEST_F(InitGoogleTestTest, OutputEmpty) {
3888 const char* argv[] = {
3889 "foo.exe",
3890 "--gtest_output",
3891 NULL
3892 };
3893
3894 const char* argv2[] = {
3895 "foo.exe",
3896 "--gtest_output",
3897 NULL
3898 };
3899
3900 TEST_PARSING_FLAGS(argv, argv2, Flags());
3901}
3902
3903// Tests parsing --gtest_output=xml
3904TEST_F(InitGoogleTestTest, OutputXml) {
3905 const char* argv[] = {
3906 "foo.exe",
3907 "--gtest_output=xml",
3908 NULL
3909 };
3910
3911 const char* argv2[] = {
3912 "foo.exe",
3913 NULL
3914 };
3915
3916 TEST_PARSING_FLAGS(argv, argv2, Flags::Output("xml"));
3917}
3918
3919// Tests parsing --gtest_output=xml:file
3920TEST_F(InitGoogleTestTest, OutputXmlFile) {
3921 const char* argv[] = {
3922 "foo.exe",
3923 "--gtest_output=xml:file",
3924 NULL
3925 };
3926
3927 const char* argv2[] = {
3928 "foo.exe",
3929 NULL
3930 };
3931
3932 TEST_PARSING_FLAGS(argv, argv2, Flags::Output("xml:file"));
3933}
3934
3935// Tests parsing --gtest_output=xml:directory/path/
3936TEST_F(InitGoogleTestTest, OutputXmlDirectory) {
3937 const char* argv[] = {
3938 "foo.exe",
3939 "--gtest_output=xml:directory/path/",
3940 NULL
3941 };
3942
3943 const char* argv2[] = {
3944 "foo.exe",
3945 NULL
3946 };
3947
3948 TEST_PARSING_FLAGS(argv, argv2, Flags::Output("xml:directory/path/"));
3949}
3950
3951// Tests parsing --gtest_repeat=number
3952TEST_F(InitGoogleTestTest, Repeat) {
3953 const char* argv[] = {
3954 "foo.exe",
3955 "--gtest_repeat=1000",
3956 NULL
3957 };
3958
3959 const char* argv2[] = {
3960 "foo.exe",
3961 NULL
3962 };
3963
3964 TEST_PARSING_FLAGS(argv, argv2, Flags::Repeat(1000));
3965}
3966
3967#ifdef GTEST_OS_WINDOWS
3968// Tests parsing wide strings.
3969TEST_F(InitGoogleTestTest, WideStrings) {
3970 const wchar_t* argv[] = {
3971 L"foo.exe",
3972 L"--gtest_filter=Foo*",
3973 L"--gtest_list_tests=1",
3974 L"--gtest_break_on_failure",
3975 L"--non_gtest_flag",
3976 NULL
3977 };
3978
3979 const wchar_t* argv2[] = {
3980 L"foo.exe",
3981 L"--non_gtest_flag",
3982 NULL
3983 };
3984
3985 Flags expected_flags;
3986 expected_flags.break_on_failure = true;
3987 expected_flags.filter = "Foo*";
3988 expected_flags.list_tests = true;
3989
3990 TEST_PARSING_FLAGS(argv, argv2, expected_flags);
3991}
3992#endif // GTEST_OS_WINDOWS
3993
3994// Tests current_test_info() in UnitTest.
3995class CurrentTestInfoTest : public Test {
3996 protected:
3997 // Tests that current_test_info() returns NULL before the first test in
3998 // the test case is run.
3999 static void SetUpTestCase() {
4000 // There should be no tests running at this point.
4001 const TestInfo* test_info =
4002 UnitTest::GetInstance()->current_test_info();
4003 EXPECT_EQ(NULL, test_info)
4004 << "There should be no tests running at this point.";
4005 }
4006
4007 // Tests that current_test_info() returns NULL after the last test in
4008 // the test case has run.
4009 static void TearDownTestCase() {
4010 const TestInfo* test_info =
4011 UnitTest::GetInstance()->current_test_info();
4012 EXPECT_EQ(NULL, test_info)
4013 << "There should be no tests running at this point.";
4014 }
4015};
4016
4017// Tests that current_test_info() returns TestInfo for currently running
4018// test by checking the expected test name against the actual one.
4019TEST_F(CurrentTestInfoTest, WorksForFirstTestInATestCase) {
4020 const TestInfo* test_info =
4021 UnitTest::GetInstance()->current_test_info();
4022 ASSERT_TRUE(NULL != test_info)
4023 << "There is a test running so we should have a valid TestInfo.";
4024 EXPECT_STREQ("CurrentTestInfoTest", test_info->test_case_name())
4025 << "Expected the name of the currently running test case.";
4026 EXPECT_STREQ("WorksForFirstTestInATestCase", test_info->name())
4027 << "Expected the name of the currently running test.";
4028}
4029
4030// Tests that current_test_info() returns TestInfo for currently running
4031// test by checking the expected test name against the actual one. We
4032// use this test to see that the TestInfo object actually changed from
4033// the previous invocation.
4034TEST_F(CurrentTestInfoTest, WorksForSecondTestInATestCase) {
4035 const TestInfo* test_info =
4036 UnitTest::GetInstance()->current_test_info();
4037 ASSERT_TRUE(NULL != test_info)
4038 << "There is a test running so we should have a valid TestInfo.";
4039 EXPECT_STREQ("CurrentTestInfoTest", test_info->test_case_name())
4040 << "Expected the name of the currently running test case.";
4041 EXPECT_STREQ("WorksForSecondTestInATestCase", test_info->name())
4042 << "Expected the name of the currently running test.";
4043}
4044
4045} // namespace testing
4046
4047// These two lines test that we can define tests in a namespace that
4048// has the name "testing" and is nested in another namespace.
4049namespace my_namespace {
4050namespace testing {
4051
4052// Makes sure that TEST knows to use ::testing::Test instead of
4053// ::my_namespace::testing::Test.
4054class Test {};
4055
4056// Makes sure that an assertion knows to use ::testing::Message instead of
4057// ::my_namespace::testing::Message.
4058class Message {};
4059
4060// Makes sure that an assertion knows to use
4061// ::testing::AssertionResult instead of
4062// ::my_namespace::testing::AssertionResult.
4063class AssertionResult {};
4064
4065// Tests that an assertion that should succeed works as expected.
4066TEST(NestedTestingNamespaceTest, Success) {
4067 EXPECT_EQ(1, 1) << "This shouldn't fail.";
4068}
4069
4070// Tests that an assertion that should fail works as expected.
4071TEST(NestedTestingNamespaceTest, Failure) {
4072 EXPECT_FATAL_FAILURE(FAIL() << "This failure is expected.",
4073 "This failure is expected.");
4074}
4075
4076} // namespace testing
4077} // namespace my_namespace
4078
4079// Tests that one can call superclass SetUp and TearDown methods--
4080// that is, that they are not private.
4081// No tests are based on this fixture; the test "passes" if it compiles
4082// successfully.
4083class ProtectedFixtureMethodsTest : public testing::Test {
4084 protected:
4085 virtual void SetUp() {
4086 testing::Test::SetUp();
4087 }
4088 virtual void TearDown() {
4089 testing::Test::TearDown();
4090 }
4091};
4092
4093// StreamingAssertionsTest tests the streaming versions of a representative
4094// sample of assertions.
4095TEST(StreamingAssertionsTest, Unconditional) {
4096 SUCCEED() << "expected success";
4097 EXPECT_NONFATAL_FAILURE(ADD_FAILURE() << "expected failure",
4098 "expected failure");
4099 EXPECT_FATAL_FAILURE(FAIL() << "expected failure",
4100 "expected failure");
4101}
4102
4103TEST(StreamingAssertionsTest, Truth) {
4104 EXPECT_TRUE(true) << "unexpected failure";
4105 ASSERT_TRUE(true) << "unexpected failure";
4106 EXPECT_NONFATAL_FAILURE(EXPECT_TRUE(false) << "expected failure",
4107 "expected failure");
4108 EXPECT_FATAL_FAILURE(ASSERT_TRUE(false) << "expected failure",
4109 "expected failure");
4110}
4111
4112TEST(StreamingAssertionsTest, Truth2) {
4113 EXPECT_FALSE(false) << "unexpected failure";
4114 ASSERT_FALSE(false) << "unexpected failure";
4115 EXPECT_NONFATAL_FAILURE(EXPECT_FALSE(true) << "expected failure",
4116 "expected failure");
4117 EXPECT_FATAL_FAILURE(ASSERT_FALSE(true) << "expected failure",
4118 "expected failure");
4119}
4120
4121TEST(StreamingAssertionsTest, IntegerEquals) {
4122 EXPECT_EQ(1, 1) << "unexpected failure";
4123 ASSERT_EQ(1, 1) << "unexpected failure";
4124 EXPECT_NONFATAL_FAILURE(EXPECT_EQ(1, 2) << "expected failure",
4125 "expected failure");
4126 EXPECT_FATAL_FAILURE(ASSERT_EQ(1, 2) << "expected failure",
4127 "expected failure");
4128}
4129
4130TEST(StreamingAssertionsTest, IntegerLessThan) {
4131 EXPECT_LT(1, 2) << "unexpected failure";
4132 ASSERT_LT(1, 2) << "unexpected failure";
4133 EXPECT_NONFATAL_FAILURE(EXPECT_LT(2, 1) << "expected failure",
4134 "expected failure");
4135 EXPECT_FATAL_FAILURE(ASSERT_LT(2, 1) << "expected failure",
4136 "expected failure");
4137}
4138
4139TEST(StreamingAssertionsTest, StringsEqual) {
4140 EXPECT_STREQ("foo", "foo") << "unexpected failure";
4141 ASSERT_STREQ("foo", "foo") << "unexpected failure";
4142 EXPECT_NONFATAL_FAILURE(EXPECT_STREQ("foo", "bar") << "expected failure",
4143 "expected failure");
4144 EXPECT_FATAL_FAILURE(ASSERT_STREQ("foo", "bar") << "expected failure",
4145 "expected failure");
4146}
4147
4148TEST(StreamingAssertionsTest, StringsNotEqual) {
4149 EXPECT_STRNE("foo", "bar") << "unexpected failure";
4150 ASSERT_STRNE("foo", "bar") << "unexpected failure";
4151 EXPECT_NONFATAL_FAILURE(EXPECT_STRNE("foo", "foo") << "expected failure",
4152 "expected failure");
4153 EXPECT_FATAL_FAILURE(ASSERT_STRNE("foo", "foo") << "expected failure",
4154 "expected failure");
4155}
4156
4157TEST(StreamingAssertionsTest, StringsEqualIgnoringCase) {
4158 EXPECT_STRCASEEQ("foo", "FOO") << "unexpected failure";
4159 ASSERT_STRCASEEQ("foo", "FOO") << "unexpected failure";
4160 EXPECT_NONFATAL_FAILURE(EXPECT_STRCASEEQ("foo", "bar") << "expected failure",
4161 "expected failure");
4162 EXPECT_FATAL_FAILURE(ASSERT_STRCASEEQ("foo", "bar") << "expected failure",
4163 "expected failure");
4164}
4165
4166TEST(StreamingAssertionsTest, StringNotEqualIgnoringCase) {
4167 EXPECT_STRCASENE("foo", "bar") << "unexpected failure";
4168 ASSERT_STRCASENE("foo", "bar") << "unexpected failure";
4169 EXPECT_NONFATAL_FAILURE(EXPECT_STRCASENE("foo", "FOO") << "expected failure",
4170 "expected failure");
4171 EXPECT_FATAL_FAILURE(ASSERT_STRCASENE("bar", "BAR") << "expected failure",
4172 "expected failure");
4173}
4174
4175TEST(StreamingAssertionsTest, FloatingPointEquals) {
4176 EXPECT_FLOAT_EQ(1.0, 1.0) << "unexpected failure";
4177 ASSERT_FLOAT_EQ(1.0, 1.0) << "unexpected failure";
4178 EXPECT_NONFATAL_FAILURE(EXPECT_FLOAT_EQ(0.0, 1.0) << "expected failure",
4179 "expected failure");
4180 EXPECT_FATAL_FAILURE(ASSERT_FLOAT_EQ(0.0, 1.0) << "expected failure",
4181 "expected failure");
4182}
4183
4184// Tests that Google Test correctly decides whether to use colors in the output.
4185
4186TEST(ColoredOutputTest, UsesColorsWhenGTestColorFlagIsYes) {
4187 GTEST_FLAG(color) = "yes";
4188
4189 SetEnv("TERM", "xterm"); // TERM supports colors.
4190 EXPECT_TRUE(ShouldUseColor(true)); // Stdout is a TTY.
4191 EXPECT_TRUE(ShouldUseColor(false)); // Stdout is not a TTY.
4192
4193 SetEnv("TERM", "dumb"); // TERM doesn't support colors.
4194 EXPECT_TRUE(ShouldUseColor(true)); // Stdout is a TTY.
4195 EXPECT_TRUE(ShouldUseColor(false)); // Stdout is not a TTY.
4196}
4197
4198TEST(ColoredOutputTest, UsesColorsWhenGTestColorFlagIsAliasOfYes) {
4199 SetEnv("TERM", "dumb"); // TERM doesn't support colors.
4200
4201 GTEST_FLAG(color) = "True";
4202 EXPECT_TRUE(ShouldUseColor(false)); // Stdout is not a TTY.
4203
4204 GTEST_FLAG(color) = "t";
4205 EXPECT_TRUE(ShouldUseColor(false)); // Stdout is not a TTY.
4206
4207 GTEST_FLAG(color) = "1";
4208 EXPECT_TRUE(ShouldUseColor(false)); // Stdout is not a TTY.
4209}
4210
4211TEST(ColoredOutputTest, UsesNoColorWhenGTestColorFlagIsNo) {
4212 GTEST_FLAG(color) = "no";
4213
4214 SetEnv("TERM", "xterm"); // TERM supports colors.
4215 EXPECT_FALSE(ShouldUseColor(true)); // Stdout is a TTY.
4216 EXPECT_FALSE(ShouldUseColor(false)); // Stdout is not a TTY.
4217
4218 SetEnv("TERM", "dumb"); // TERM doesn't support colors.
4219 EXPECT_FALSE(ShouldUseColor(true)); // Stdout is a TTY.
4220 EXPECT_FALSE(ShouldUseColor(false)); // Stdout is not a TTY.
4221}
4222
4223TEST(ColoredOutputTest, UsesNoColorWhenGTestColorFlagIsInvalid) {
4224 SetEnv("TERM", "xterm"); // TERM supports colors.
4225
4226 GTEST_FLAG(color) = "F";
4227 EXPECT_FALSE(ShouldUseColor(true)); // Stdout is a TTY.
4228
4229 GTEST_FLAG(color) = "0";
4230 EXPECT_FALSE(ShouldUseColor(true)); // Stdout is a TTY.
4231
4232 GTEST_FLAG(color) = "unknown";
4233 EXPECT_FALSE(ShouldUseColor(true)); // Stdout is a TTY.
4234}
4235
4236TEST(ColoredOutputTest, UsesColorsWhenStdoutIsTty) {
4237 GTEST_FLAG(color) = "auto";
4238
4239 SetEnv("TERM", "xterm"); // TERM supports colors.
4240 EXPECT_FALSE(ShouldUseColor(false)); // Stdout is not a TTY.
4241 EXPECT_TRUE(ShouldUseColor(true)); // Stdout is a TTY.
4242}
4243
4244TEST(ColoredOutputTest, UsesColorsWhenTermSupportsColors) {
4245 GTEST_FLAG(color) = "auto";
4246
4247#ifdef GTEST_OS_WINDOWS
4248 // On Windows, we ignore the TERM variable as it's usually not set.
4249
4250 SetEnv("TERM", "dumb");
4251 EXPECT_TRUE(ShouldUseColor(true)); // Stdout is a TTY.
4252
4253 SetEnv("TERM", "");
4254 EXPECT_TRUE(ShouldUseColor(true)); // Stdout is a TTY.
4255
4256 SetEnv("TERM", "xterm");
4257 EXPECT_TRUE(ShouldUseColor(true)); // Stdout is a TTY.
4258#else
4259 // On non-Windows platforms, we rely on TERM to determine if the
4260 // terminal supports colors.
4261
4262 SetEnv("TERM", "dumb"); // TERM doesn't support colors.
4263 EXPECT_FALSE(ShouldUseColor(true)); // Stdout is a TTY.
4264
4265 SetEnv("TERM", "emacs"); // TERM doesn't support colors.
4266 EXPECT_FALSE(ShouldUseColor(true)); // Stdout is a TTY.
4267
4268 SetEnv("TERM", "vt100"); // TERM doesn't support colors.
4269 EXPECT_FALSE(ShouldUseColor(true)); // Stdout is a TTY.
4270
4271 SetEnv("TERM", "xterm-mono"); // TERM doesn't support colors.
4272 EXPECT_FALSE(ShouldUseColor(true)); // Stdout is a TTY.
4273
4274 SetEnv("TERM", "xterm"); // TERM supports colors.
4275 EXPECT_TRUE(ShouldUseColor(true)); // Stdout is a TTY.
4276
4277 SetEnv("TERM", "xterm-color"); // TERM supports colors.
4278 EXPECT_TRUE(ShouldUseColor(true)); // Stdout is a TTY.
4279#endif // GTEST_OS_WINDOWS
4280}
4281
4282#ifndef __SYMBIAN32__
4283// We will want to integrate running the unittests to a different
4284// main application on Symbian.
4285int main(int argc, char** argv) {
4286 testing::InitGoogleTest(&argc, argv);
4287
4288#ifdef GTEST_HAS_DEATH_TEST
4289 if (!testing::internal::GTEST_FLAG(internal_run_death_test).empty()) {
4290 // Skip the usual output capturing if we're running as the child
4291 // process of an threadsafe-style death test.
4292 freopen("/dev/null", "w", stdout);
4293 }
4294#endif // GTEST_HAS_DEATH_TEST
4295
4296 // Runs all tests using Google Test.
4297 return RUN_ALL_TESTS();
4298}
4299#endif // __SYMBIAN32_