1 // 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
37 // Verifies that the command line flag variables can be accessed
38 // in code once <gtest/gtest.h> has been #included.
39 // Do not move it after other #includes.
TEST(CommandLineFlagsTest,CanBeAccessedInCodeOnceGTestHIsIncluded)40 TEST(CommandLineFlagsTest, CanBeAccessedInCodeOnceGTestHIsIncluded) {
41 bool dummy = testing::GTEST_FLAG(also_run_disabled_tests)
42 || testing::GTEST_FLAG(break_on_failure)
43 || testing::GTEST_FLAG(catch_exceptions)
44 || testing::GTEST_FLAG(color) != "unknown"
45 || testing::GTEST_FLAG(filter) != "unknown"
46 || testing::GTEST_FLAG(list_tests)
47 || testing::GTEST_FLAG(output) != "unknown"
48 || testing::GTEST_FLAG(print_time)
49 || testing::GTEST_FLAG(repeat) > 0
50 || testing::GTEST_FLAG(show_internal_stack_frames)
51 || testing::GTEST_FLAG(stack_trace_depth) > 0
52 || testing::GTEST_FLAG(throw_on_failure);
53 EXPECT_TRUE(dummy || !dummy); // Suppresses warning that dummy is unused.
54 }
55
56 #include <gtest/gtest-spi.h>
57
58 // Indicates that this translation unit is part of Google Test's
59 // implementation. It must come before gtest-internal-inl.h is
60 // included, or there will be a compiler error. This trick is to
61 // prevent a user from accidentally including gtest-internal-inl.h in
62 // his code.
63 #define GTEST_IMPLEMENTATION_ 1
64 #include "src/gtest-internal-inl.h"
65 #undef GTEST_IMPLEMENTATION_
66
67 #include <stdlib.h>
68
69 #if GTEST_HAS_PTHREAD
70 #include <pthread.h>
71 #endif // GTEST_HAS_PTHREAD
72
73 #if GTEST_OS_LINUX
74 #include <string.h>
75 #include <signal.h>
76 #include <sys/stat.h>
77 #include <unistd.h>
78 #include <string>
79 #include <vector>
80 #endif // GTEST_OS_LINUX
81
82 namespace testing {
83 namespace internal {
84 const char* FormatTimeInMillisAsSeconds(TimeInMillis ms);
85 bool ParseInt32Flag(const char* str, const char* flag, Int32* value);
86 } // namespace internal
87 } // namespace testing
88
89 using testing::internal::FormatTimeInMillisAsSeconds;
90 using testing::internal::ParseInt32Flag;
91
92 namespace testing {
93
94 GTEST_DECLARE_string_(output);
95 GTEST_DECLARE_string_(color);
96
97 namespace internal {
98 bool ShouldUseColor(bool stdout_is_tty);
99 } // namespace internal
100 } // namespace testing
101
102 using testing::AssertionFailure;
103 using testing::AssertionResult;
104 using testing::AssertionSuccess;
105 using testing::DoubleLE;
106 using testing::FloatLE;
107 using testing::GTEST_FLAG(also_run_disabled_tests);
108 using testing::GTEST_FLAG(break_on_failure);
109 using testing::GTEST_FLAG(catch_exceptions);
110 using testing::GTEST_FLAG(death_test_use_fork);
111 using testing::GTEST_FLAG(color);
112 using testing::GTEST_FLAG(filter);
113 using testing::GTEST_FLAG(list_tests);
114 using testing::GTEST_FLAG(output);
115 using testing::GTEST_FLAG(print_time);
116 using testing::GTEST_FLAG(repeat);
117 using testing::GTEST_FLAG(show_internal_stack_frames);
118 using testing::GTEST_FLAG(stack_trace_depth);
119 using testing::GTEST_FLAG(throw_on_failure);
120 using testing::IsNotSubstring;
121 using testing::IsSubstring;
122 using testing::Message;
123 using testing::ScopedFakeTestPartResultReporter;
124 using testing::StaticAssertTypeEq;
125 using testing::Test;
126 using testing::TestPartResult;
127 using testing::TestPartResultArray;
128 using testing::TPRT_FATAL_FAILURE;
129 using testing::TPRT_NONFATAL_FAILURE;
130 using testing::TPRT_SUCCESS;
131 using testing::UnitTest;
132 using testing::internal::kTestTypeIdInGoogleTest;
133 using testing::internal::AppendUserMessage;
134 using testing::internal::CodePointToUtf8;
135 using testing::internal::EqFailure;
136 using testing::internal::FloatingPoint;
137 using testing::internal::GetCurrentOsStackTraceExceptTop;
138 using testing::internal::GetFailedPartCount;
139 using testing::internal::GetTestTypeId;
140 using testing::internal::GetTypeId;
141 using testing::internal::GTestFlagSaver;
142 using testing::internal::Int32;
143 using testing::internal::Int32FromEnvOrDie;
144 using testing::internal::List;
145 using testing::internal::ShouldRunTestOnShard;
146 using testing::internal::ShouldShard;
147 using testing::internal::ShouldUseColor;
148 using testing::internal::StreamableToString;
149 using testing::internal::String;
150 using testing::internal::TestProperty;
151 using testing::internal::TestResult;
152 using testing::internal::ThreadLocal;
153 using testing::internal::UnitTestImpl;
154 using testing::internal::WideStringToUtf8;
155
156 // This line tests that we can define tests in an unnamed namespace.
157 namespace {
158
159 // Tests GetTypeId.
160
TEST(GetTypeIdTest,ReturnsSameValueForSameType)161 TEST(GetTypeIdTest, ReturnsSameValueForSameType) {
162 EXPECT_EQ(GetTypeId<int>(), GetTypeId<int>());
163 EXPECT_EQ(GetTypeId<Test>(), GetTypeId<Test>());
164 }
165
166 class SubClassOfTest : public Test {};
167 class AnotherSubClassOfTest : public Test {};
168
TEST(GetTypeIdTest,ReturnsDifferentValuesForDifferentTypes)169 TEST(GetTypeIdTest, ReturnsDifferentValuesForDifferentTypes) {
170 EXPECT_NE(GetTypeId<int>(), GetTypeId<const int>());
171 EXPECT_NE(GetTypeId<int>(), GetTypeId<char>());
172 EXPECT_NE(GetTypeId<int>(), GetTestTypeId());
173 EXPECT_NE(GetTypeId<SubClassOfTest>(), GetTestTypeId());
174 EXPECT_NE(GetTypeId<AnotherSubClassOfTest>(), GetTestTypeId());
175 EXPECT_NE(GetTypeId<AnotherSubClassOfTest>(), GetTypeId<SubClassOfTest>());
176 }
177
178 // Verifies that GetTestTypeId() returns the same value, no matter it
179 // is called from inside Google Test or outside of it.
TEST(GetTestTypeIdTest,ReturnsTheSameValueInsideOrOutsideOfGoogleTest)180 TEST(GetTestTypeIdTest, ReturnsTheSameValueInsideOrOutsideOfGoogleTest) {
181 EXPECT_EQ(kTestTypeIdInGoogleTest, GetTestTypeId());
182 }
183
184 // Tests FormatTimeInMillisAsSeconds().
185
TEST(FormatTimeInMillisAsSecondsTest,FormatsZero)186 TEST(FormatTimeInMillisAsSecondsTest, FormatsZero) {
187 EXPECT_STREQ("0", FormatTimeInMillisAsSeconds(0));
188 }
189
TEST(FormatTimeInMillisAsSecondsTest,FormatsPositiveNumber)190 TEST(FormatTimeInMillisAsSecondsTest, FormatsPositiveNumber) {
191 EXPECT_STREQ("0.003", FormatTimeInMillisAsSeconds(3));
192 EXPECT_STREQ("0.01", FormatTimeInMillisAsSeconds(10));
193 EXPECT_STREQ("0.2", FormatTimeInMillisAsSeconds(200));
194 EXPECT_STREQ("1.2", FormatTimeInMillisAsSeconds(1200));
195 EXPECT_STREQ("3", FormatTimeInMillisAsSeconds(3000));
196 }
197
TEST(FormatTimeInMillisAsSecondsTest,FormatsNegativeNumber)198 TEST(FormatTimeInMillisAsSecondsTest, FormatsNegativeNumber) {
199 EXPECT_STREQ("-0.003", FormatTimeInMillisAsSeconds(-3));
200 EXPECT_STREQ("-0.01", FormatTimeInMillisAsSeconds(-10));
201 EXPECT_STREQ("-0.2", FormatTimeInMillisAsSeconds(-200));
202 EXPECT_STREQ("-1.2", FormatTimeInMillisAsSeconds(-1200));
203 EXPECT_STREQ("-3", FormatTimeInMillisAsSeconds(-3000));
204 }
205
206 #if !GTEST_OS_SYMBIAN
207 // NULL testing does not work with Symbian compilers.
208
209 // Tests that GTEST_IS_NULL_LITERAL_(x) is true when x is a null
210 // pointer literal.
TEST(NullLiteralTest,IsTrueForNullLiterals)211 TEST(NullLiteralTest, IsTrueForNullLiterals) {
212 EXPECT_TRUE(GTEST_IS_NULL_LITERAL_(NULL));
213 EXPECT_TRUE(GTEST_IS_NULL_LITERAL_(0));
214 EXPECT_TRUE(GTEST_IS_NULL_LITERAL_(1 - 1));
215 EXPECT_TRUE(GTEST_IS_NULL_LITERAL_(0U));
216 EXPECT_TRUE(GTEST_IS_NULL_LITERAL_(0L));
217 EXPECT_TRUE(GTEST_IS_NULL_LITERAL_(false));
218 EXPECT_TRUE(GTEST_IS_NULL_LITERAL_(true && false));
219 }
220
221 // Tests that GTEST_IS_NULL_LITERAL_(x) is false when x is not a null
222 // pointer literal.
TEST(NullLiteralTest,IsFalseForNonNullLiterals)223 TEST(NullLiteralTest, IsFalseForNonNullLiterals) {
224 EXPECT_FALSE(GTEST_IS_NULL_LITERAL_(1));
225 EXPECT_FALSE(GTEST_IS_NULL_LITERAL_(0.0));
226 EXPECT_FALSE(GTEST_IS_NULL_LITERAL_('a'));
227 EXPECT_FALSE(GTEST_IS_NULL_LITERAL_(static_cast<void*>(NULL)));
228 }
229
230 #endif // !GTEST_OS_SYMBIAN
231 //
232 // Tests CodePointToUtf8().
233
234 // Tests that the NUL character L'\0' is encoded correctly.
TEST(CodePointToUtf8Test,CanEncodeNul)235 TEST(CodePointToUtf8Test, CanEncodeNul) {
236 char buffer[32];
237 EXPECT_STREQ("", CodePointToUtf8(L'\0', buffer));
238 }
239
240 // Tests that ASCII characters are encoded correctly.
TEST(CodePointToUtf8Test,CanEncodeAscii)241 TEST(CodePointToUtf8Test, CanEncodeAscii) {
242 char buffer[32];
243 EXPECT_STREQ("a", CodePointToUtf8(L'a', buffer));
244 EXPECT_STREQ("Z", CodePointToUtf8(L'Z', buffer));
245 EXPECT_STREQ("&", CodePointToUtf8(L'&', buffer));
246 EXPECT_STREQ("\x7F", CodePointToUtf8(L'\x7F', buffer));
247 }
248
249 // Tests that Unicode code-points that have 8 to 11 bits are encoded
250 // as 110xxxxx 10xxxxxx.
TEST(CodePointToUtf8Test,CanEncode8To11Bits)251 TEST(CodePointToUtf8Test, CanEncode8To11Bits) {
252 char buffer[32];
253 // 000 1101 0011 => 110-00011 10-010011
254 EXPECT_STREQ("\xC3\x93", CodePointToUtf8(L'\xD3', buffer));
255
256 // 101 0111 0110 => 110-10101 10-110110
257 EXPECT_STREQ("\xD5\xB6", CodePointToUtf8(L'\x576', buffer));
258 }
259
260 // Tests that Unicode code-points that have 12 to 16 bits are encoded
261 // as 1110xxxx 10xxxxxx 10xxxxxx.
TEST(CodePointToUtf8Test,CanEncode12To16Bits)262 TEST(CodePointToUtf8Test, CanEncode12To16Bits) {
263 char buffer[32];
264 // 0000 1000 1101 0011 => 1110-0000 10-100011 10-010011
265 EXPECT_STREQ("\xE0\xA3\x93", CodePointToUtf8(L'\x8D3', buffer));
266
267 // 1100 0111 0100 1101 => 1110-1100 10-011101 10-001101
268 EXPECT_STREQ("\xEC\x9D\x8D", CodePointToUtf8(L'\xC74D', buffer));
269 }
270
271 #if !GTEST_WIDE_STRING_USES_UTF16_
272 // Tests in this group require a wchar_t to hold > 16 bits, and thus
273 // are skipped on Windows, Cygwin, and Symbian, where a wchar_t is
274 // 16-bit wide. This code may not compile on those systems.
275
276 // Tests that Unicode code-points that have 17 to 21 bits are encoded
277 // as 11110xxx 10xxxxxx 10xxxxxx 10xxxxxx.
TEST(CodePointToUtf8Test,CanEncode17To21Bits)278 TEST(CodePointToUtf8Test, CanEncode17To21Bits) {
279 char buffer[32];
280 // 0 0001 0000 1000 1101 0011 => 11110-000 10-010000 10-100011 10-010011
281 EXPECT_STREQ("\xF0\x90\xA3\x93", CodePointToUtf8(L'\x108D3', buffer));
282
283 // 0 0001 0000 0100 0000 0000 => 11110-000 10-010000 10-010000 10-000000
284 EXPECT_STREQ("\xF0\x90\x90\x80", CodePointToUtf8(L'\x10400', buffer));
285
286 // 1 0000 1000 0110 0011 0100 => 11110-100 10-001000 10-011000 10-110100
287 EXPECT_STREQ("\xF4\x88\x98\xB4", CodePointToUtf8(L'\x108634', buffer));
288 }
289
290 // Tests that encoding an invalid code-point generates the expected result.
TEST(CodePointToUtf8Test,CanEncodeInvalidCodePoint)291 TEST(CodePointToUtf8Test, CanEncodeInvalidCodePoint) {
292 char buffer[32];
293 EXPECT_STREQ("(Invalid Unicode 0x1234ABCD)",
294 CodePointToUtf8(L'\x1234ABCD', buffer));
295 }
296
297 #endif // !GTEST_WIDE_STRING_USES_UTF16_
298
299 // Tests WideStringToUtf8().
300
301 // Tests that the NUL character L'\0' is encoded correctly.
TEST(WideStringToUtf8Test,CanEncodeNul)302 TEST(WideStringToUtf8Test, CanEncodeNul) {
303 EXPECT_STREQ("", WideStringToUtf8(L"", 0).c_str());
304 EXPECT_STREQ("", WideStringToUtf8(L"", -1).c_str());
305 }
306
307 // Tests that ASCII strings are encoded correctly.
TEST(WideStringToUtf8Test,CanEncodeAscii)308 TEST(WideStringToUtf8Test, CanEncodeAscii) {
309 EXPECT_STREQ("a", WideStringToUtf8(L"a", 1).c_str());
310 EXPECT_STREQ("ab", WideStringToUtf8(L"ab", 2).c_str());
311 EXPECT_STREQ("a", WideStringToUtf8(L"a", -1).c_str());
312 EXPECT_STREQ("ab", WideStringToUtf8(L"ab", -1).c_str());
313 }
314
315 // Tests that Unicode code-points that have 8 to 11 bits are encoded
316 // as 110xxxxx 10xxxxxx.
TEST(WideStringToUtf8Test,CanEncode8To11Bits)317 TEST(WideStringToUtf8Test, CanEncode8To11Bits) {
318 // 000 1101 0011 => 110-00011 10-010011
319 EXPECT_STREQ("\xC3\x93", WideStringToUtf8(L"\xD3", 1).c_str());
320 EXPECT_STREQ("\xC3\x93", WideStringToUtf8(L"\xD3", -1).c_str());
321
322 // 101 0111 0110 => 110-10101 10-110110
323 EXPECT_STREQ("\xD5\xB6", WideStringToUtf8(L"\x576", 1).c_str());
324 EXPECT_STREQ("\xD5\xB6", WideStringToUtf8(L"\x576", -1).c_str());
325 }
326
327 // Tests that Unicode code-points that have 12 to 16 bits are encoded
328 // as 1110xxxx 10xxxxxx 10xxxxxx.
TEST(WideStringToUtf8Test,CanEncode12To16Bits)329 TEST(WideStringToUtf8Test, CanEncode12To16Bits) {
330 // 0000 1000 1101 0011 => 1110-0000 10-100011 10-010011
331 EXPECT_STREQ("\xE0\xA3\x93", WideStringToUtf8(L"\x8D3", 1).c_str());
332 EXPECT_STREQ("\xE0\xA3\x93", WideStringToUtf8(L"\x8D3", -1).c_str());
333
334 // 1100 0111 0100 1101 => 1110-1100 10-011101 10-001101
335 EXPECT_STREQ("\xEC\x9D\x8D", WideStringToUtf8(L"\xC74D", 1).c_str());
336 EXPECT_STREQ("\xEC\x9D\x8D", WideStringToUtf8(L"\xC74D", -1).c_str());
337 }
338
339 // Tests that the conversion stops when the function encounters \0 character.
TEST(WideStringToUtf8Test,StopsOnNulCharacter)340 TEST(WideStringToUtf8Test, StopsOnNulCharacter) {
341 EXPECT_STREQ("ABC", WideStringToUtf8(L"ABC\0XYZ", 100).c_str());
342 }
343
344 // Tests that the conversion stops when the function reaches the limit
345 // specified by the 'length' parameter.
TEST(WideStringToUtf8Test,StopsWhenLengthLimitReached)346 TEST(WideStringToUtf8Test, StopsWhenLengthLimitReached) {
347 EXPECT_STREQ("ABC", WideStringToUtf8(L"ABCDEF", 3).c_str());
348 }
349
350
351 #if !GTEST_WIDE_STRING_USES_UTF16_
352 // Tests that Unicode code-points that have 17 to 21 bits are encoded
353 // as 11110xxx 10xxxxxx 10xxxxxx 10xxxxxx. This code may not compile
354 // on the systems using UTF-16 encoding.
TEST(WideStringToUtf8Test,CanEncode17To21Bits)355 TEST(WideStringToUtf8Test, CanEncode17To21Bits) {
356 // 0 0001 0000 1000 1101 0011 => 11110-000 10-010000 10-100011 10-010011
357 EXPECT_STREQ("\xF0\x90\xA3\x93", WideStringToUtf8(L"\x108D3", 1).c_str());
358 EXPECT_STREQ("\xF0\x90\xA3\x93", WideStringToUtf8(L"\x108D3", -1).c_str());
359
360 // 1 0000 1000 0110 0011 0100 => 11110-100 10-001000 10-011000 10-110100
361 EXPECT_STREQ("\xF4\x88\x98\xB4", WideStringToUtf8(L"\x108634", 1).c_str());
362 EXPECT_STREQ("\xF4\x88\x98\xB4", WideStringToUtf8(L"\x108634", -1).c_str());
363 }
364
365 // Tests that encoding an invalid code-point generates the expected result.
TEST(WideStringToUtf8Test,CanEncodeInvalidCodePoint)366 TEST(WideStringToUtf8Test, CanEncodeInvalidCodePoint) {
367 EXPECT_STREQ("(Invalid Unicode 0xABCDFF)",
368 WideStringToUtf8(L"\xABCDFF", -1).c_str());
369 }
370 #else // !GTEST_WIDE_STRING_USES_UTF16_
371 // Tests that surrogate pairs are encoded correctly on the systems using
372 // UTF-16 encoding in the wide strings.
TEST(WideStringToUtf8Test,CanEncodeValidUtf16SUrrogatePairs)373 TEST(WideStringToUtf8Test, CanEncodeValidUtf16SUrrogatePairs) {
374 EXPECT_STREQ("\xF0\x90\x90\x80",
375 WideStringToUtf8(L"\xD801\xDC00", -1).c_str());
376 }
377
378 // Tests that encoding an invalid UTF-16 surrogate pair
379 // generates the expected result.
TEST(WideStringToUtf8Test,CanEncodeInvalidUtf16SurrogatePair)380 TEST(WideStringToUtf8Test, CanEncodeInvalidUtf16SurrogatePair) {
381 // Leading surrogate is at the end of the string.
382 EXPECT_STREQ("\xED\xA0\x80", WideStringToUtf8(L"\xD800", -1).c_str());
383 // Leading surrogate is not followed by the trailing surrogate.
384 EXPECT_STREQ("\xED\xA0\x80$", WideStringToUtf8(L"\xD800$", -1).c_str());
385 // Trailing surrogate appearas without a leading surrogate.
386 EXPECT_STREQ("\xED\xB0\x80PQR", WideStringToUtf8(L"\xDC00PQR", -1).c_str());
387 }
388 #endif // !GTEST_WIDE_STRING_USES_UTF16_
389
390 // Tests that codepoint concatenation works correctly.
391 #if !GTEST_WIDE_STRING_USES_UTF16_
TEST(WideStringToUtf8Test,ConcatenatesCodepointsCorrectly)392 TEST(WideStringToUtf8Test, ConcatenatesCodepointsCorrectly) {
393 EXPECT_STREQ(
394 "\xF4\x88\x98\xB4"
395 "\xEC\x9D\x8D"
396 "\n"
397 "\xD5\xB6"
398 "\xE0\xA3\x93"
399 "\xF4\x88\x98\xB4",
400 WideStringToUtf8(L"\x108634\xC74D\n\x576\x8D3\x108634", -1).c_str());
401 }
402 #else
TEST(WideStringToUtf8Test,ConcatenatesCodepointsCorrectly)403 TEST(WideStringToUtf8Test, ConcatenatesCodepointsCorrectly) {
404 EXPECT_STREQ(
405 "\xEC\x9D\x8D" "\n" "\xD5\xB6" "\xE0\xA3\x93",
406 WideStringToUtf8(L"\xC74D\n\x576\x8D3", -1).c_str());
407 }
408 #endif // !GTEST_WIDE_STRING_USES_UTF16_
409
410 // Tests the List template class.
411
412 // Tests List::PushFront().
TEST(ListTest,PushFront)413 TEST(ListTest, PushFront) {
414 List<int> a;
415 ASSERT_EQ(0u, a.size());
416
417 // Calls PushFront() on an empty list.
418 a.PushFront(1);
419 ASSERT_EQ(1u, a.size());
420 EXPECT_EQ(1, a.Head()->element());
421 ASSERT_EQ(a.Head(), a.Last());
422
423 // Calls PushFront() on a singleton list.
424 a.PushFront(2);
425 ASSERT_EQ(2u, a.size());
426 EXPECT_EQ(2, a.Head()->element());
427 EXPECT_EQ(1, a.Last()->element());
428
429 // Calls PushFront() on a list with more than one elements.
430 a.PushFront(3);
431 ASSERT_EQ(3u, a.size());
432 EXPECT_EQ(3, a.Head()->element());
433 EXPECT_EQ(2, a.Head()->next()->element());
434 EXPECT_EQ(1, a.Last()->element());
435 }
436
437 // Tests List::PopFront().
TEST(ListTest,PopFront)438 TEST(ListTest, PopFront) {
439 List<int> a;
440
441 // Popping on an empty list should fail.
442 EXPECT_FALSE(a.PopFront(NULL));
443
444 // Popping again on an empty list should fail, and the result element
445 // shouldn't be overwritten.
446 int element = 1;
447 EXPECT_FALSE(a.PopFront(&element));
448 EXPECT_EQ(1, element);
449
450 a.PushFront(2);
451 a.PushFront(3);
452
453 // PopFront() should pop the element in the front of the list.
454 EXPECT_TRUE(a.PopFront(&element));
455 EXPECT_EQ(3, element);
456
457 // After popping the last element, the list should be empty.
458 EXPECT_TRUE(a.PopFront(NULL));
459 EXPECT_EQ(0u, a.size());
460 }
461
462 // Tests inserting at the beginning using List::InsertAfter().
TEST(ListTest,InsertAfterAtBeginning)463 TEST(ListTest, InsertAfterAtBeginning) {
464 List<int> a;
465 ASSERT_EQ(0u, a.size());
466
467 // Inserts into an empty list.
468 a.InsertAfter(NULL, 1);
469 ASSERT_EQ(1u, a.size());
470 EXPECT_EQ(1, a.Head()->element());
471 ASSERT_EQ(a.Head(), a.Last());
472
473 // Inserts at the beginning of a singleton list.
474 a.InsertAfter(NULL, 2);
475 ASSERT_EQ(2u, a.size());
476 EXPECT_EQ(2, a.Head()->element());
477 EXPECT_EQ(1, a.Last()->element());
478
479 // Inserts at the beginning of a list with more than one elements.
480 a.InsertAfter(NULL, 3);
481 ASSERT_EQ(3u, a.size());
482 EXPECT_EQ(3, a.Head()->element());
483 EXPECT_EQ(2, a.Head()->next()->element());
484 EXPECT_EQ(1, a.Last()->element());
485 }
486
487 // Tests inserting at a location other than the beginning using
488 // List::InsertAfter().
TEST(ListTest,InsertAfterNotAtBeginning)489 TEST(ListTest, InsertAfterNotAtBeginning) {
490 // Prepares a singleton list.
491 List<int> a;
492 a.PushBack(1);
493
494 // Inserts at the end of a singleton list.
495 a.InsertAfter(a.Last(), 2);
496 ASSERT_EQ(2u, a.size());
497 EXPECT_EQ(1, a.Head()->element());
498 EXPECT_EQ(2, a.Last()->element());
499
500 // Inserts at the end of a list with more than one elements.
501 a.InsertAfter(a.Last(), 3);
502 ASSERT_EQ(3u, a.size());
503 EXPECT_EQ(1, a.Head()->element());
504 EXPECT_EQ(2, a.Head()->next()->element());
505 EXPECT_EQ(3, a.Last()->element());
506
507 // Inserts in the middle of a list.
508 a.InsertAfter(a.Head(), 4);
509 ASSERT_EQ(4u, a.size());
510 EXPECT_EQ(1, a.Head()->element());
511 EXPECT_EQ(4, a.Head()->next()->element());
512 EXPECT_EQ(2, a.Head()->next()->next()->element());
513 EXPECT_EQ(3, a.Last()->element());
514 }
515
516
517 // Tests the String class.
518
519 // Tests String's constructors.
TEST(StringTest,Constructors)520 TEST(StringTest, Constructors) {
521 // Default ctor.
522 String s1;
523 // We aren't using EXPECT_EQ(NULL, s1.c_str()) because comparing
524 // pointers with NULL isn't supported on all platforms.
525 EXPECT_TRUE(NULL == s1.c_str());
526
527 // Implicitly constructs from a C-string.
528 String s2 = "Hi";
529 EXPECT_STREQ("Hi", s2.c_str());
530
531 // Constructs from a C-string and a length.
532 String s3("hello", 3);
533 EXPECT_STREQ("hel", s3.c_str());
534
535 // Copy ctor.
536 String s4 = s3;
537 EXPECT_STREQ("hel", s4.c_str());
538 }
539
540 #if GTEST_HAS_STD_STRING
541
TEST(StringTest,ConvertsFromStdString)542 TEST(StringTest, ConvertsFromStdString) {
543 // An empty std::string.
544 const std::string src1("");
545 const String dest1 = src1;
546 EXPECT_STREQ("", dest1.c_str());
547
548 // A normal std::string.
549 const std::string src2("Hi");
550 const String dest2 = src2;
551 EXPECT_STREQ("Hi", dest2.c_str());
552
553 // An std::string with an embedded NUL character.
554 const char src3[] = "Hello\0world.";
555 const String dest3 = std::string(src3, sizeof(src3));
556 EXPECT_STREQ("Hello", dest3.c_str());
557 }
558
TEST(StringTest,ConvertsToStdString)559 TEST(StringTest, ConvertsToStdString) {
560 // An empty String.
561 const String src1("");
562 const std::string dest1 = src1;
563 EXPECT_EQ("", dest1);
564
565 // A normal String.
566 const String src2("Hi");
567 const std::string dest2 = src2;
568 EXPECT_EQ("Hi", dest2);
569 }
570
571 #endif // GTEST_HAS_STD_STRING
572
573 #if GTEST_HAS_GLOBAL_STRING
574
TEST(StringTest,ConvertsFromGlobalString)575 TEST(StringTest, ConvertsFromGlobalString) {
576 // An empty ::string.
577 const ::string src1("");
578 const String dest1 = src1;
579 EXPECT_STREQ("", dest1.c_str());
580
581 // A normal ::string.
582 const ::string src2("Hi");
583 const String dest2 = src2;
584 EXPECT_STREQ("Hi", dest2.c_str());
585
586 // An ::string with an embedded NUL character.
587 const char src3[] = "Hello\0world.";
588 const String dest3 = ::string(src3, sizeof(src3));
589 EXPECT_STREQ("Hello", dest3.c_str());
590 }
591
TEST(StringTest,ConvertsToGlobalString)592 TEST(StringTest, ConvertsToGlobalString) {
593 // An empty String.
594 const String src1("");
595 const ::string dest1 = src1;
596 EXPECT_EQ("", dest1);
597
598 // A normal String.
599 const String src2("Hi");
600 const ::string dest2 = src2;
601 EXPECT_EQ("Hi", dest2);
602 }
603
604 #endif // GTEST_HAS_GLOBAL_STRING
605
606 // Tests String::ShowCString().
TEST(StringTest,ShowCString)607 TEST(StringTest, ShowCString) {
608 EXPECT_STREQ("(null)", String::ShowCString(NULL));
609 EXPECT_STREQ("", String::ShowCString(""));
610 EXPECT_STREQ("foo", String::ShowCString("foo"));
611 }
612
613 // Tests String::ShowCStringQuoted().
TEST(StringTest,ShowCStringQuoted)614 TEST(StringTest, ShowCStringQuoted) {
615 EXPECT_STREQ("(null)",
616 String::ShowCStringQuoted(NULL).c_str());
617 EXPECT_STREQ("\"\"",
618 String::ShowCStringQuoted("").c_str());
619 EXPECT_STREQ("\"foo\"",
620 String::ShowCStringQuoted("foo").c_str());
621 }
622
623 // Tests String::operator==().
TEST(StringTest,Equals)624 TEST(StringTest, Equals) {
625 const String null(NULL);
626 EXPECT_TRUE(null == NULL); // NOLINT
627 EXPECT_FALSE(null == ""); // NOLINT
628 EXPECT_FALSE(null == "bar"); // NOLINT
629
630 const String empty("");
631 EXPECT_FALSE(empty == NULL); // NOLINT
632 EXPECT_TRUE(empty == ""); // NOLINT
633 EXPECT_FALSE(empty == "bar"); // NOLINT
634
635 const String foo("foo");
636 EXPECT_FALSE(foo == NULL); // NOLINT
637 EXPECT_FALSE(foo == ""); // NOLINT
638 EXPECT_FALSE(foo == "bar"); // NOLINT
639 EXPECT_TRUE(foo == "foo"); // NOLINT
640 }
641
642 // Tests String::operator!=().
TEST(StringTest,NotEquals)643 TEST(StringTest, NotEquals) {
644 const String null(NULL);
645 EXPECT_FALSE(null != NULL); // NOLINT
646 EXPECT_TRUE(null != ""); // NOLINT
647 EXPECT_TRUE(null != "bar"); // NOLINT
648
649 const String empty("");
650 EXPECT_TRUE(empty != NULL); // NOLINT
651 EXPECT_FALSE(empty != ""); // NOLINT
652 EXPECT_TRUE(empty != "bar"); // NOLINT
653
654 const String foo("foo");
655 EXPECT_TRUE(foo != NULL); // NOLINT
656 EXPECT_TRUE(foo != ""); // NOLINT
657 EXPECT_TRUE(foo != "bar"); // NOLINT
658 EXPECT_FALSE(foo != "foo"); // NOLINT
659 }
660
661 // Tests String::EndsWith().
TEST(StringTest,EndsWith)662 TEST(StringTest, EndsWith) {
663 EXPECT_TRUE(String("foobar").EndsWith("bar"));
664 EXPECT_TRUE(String("foobar").EndsWith(""));
665 EXPECT_TRUE(String("").EndsWith(""));
666
667 EXPECT_FALSE(String("foobar").EndsWith("foo"));
668 EXPECT_FALSE(String("").EndsWith("foo"));
669 }
670
671 // Tests String::EndsWithCaseInsensitive().
TEST(StringTest,EndsWithCaseInsensitive)672 TEST(StringTest, EndsWithCaseInsensitive) {
673 EXPECT_TRUE(String("foobar").EndsWithCaseInsensitive("BAR"));
674 EXPECT_TRUE(String("foobaR").EndsWithCaseInsensitive("bar"));
675 EXPECT_TRUE(String("foobar").EndsWithCaseInsensitive(""));
676 EXPECT_TRUE(String("").EndsWithCaseInsensitive(""));
677
678 EXPECT_FALSE(String("Foobar").EndsWithCaseInsensitive("foo"));
679 EXPECT_FALSE(String("foobar").EndsWithCaseInsensitive("Foo"));
680 EXPECT_FALSE(String("").EndsWithCaseInsensitive("foo"));
681 }
682
683 // Tests String::CaseInsensitiveWideCStringEquals
TEST(StringTest,CaseInsensitiveWideCStringEquals)684 TEST(StringTest, CaseInsensitiveWideCStringEquals) {
685 EXPECT_TRUE(String::CaseInsensitiveWideCStringEquals(NULL, NULL));
686 EXPECT_FALSE(String::CaseInsensitiveWideCStringEquals(NULL, L""));
687 EXPECT_FALSE(String::CaseInsensitiveWideCStringEquals(L"", NULL));
688 EXPECT_FALSE(String::CaseInsensitiveWideCStringEquals(NULL, L"foobar"));
689 EXPECT_FALSE(String::CaseInsensitiveWideCStringEquals(L"foobar", NULL));
690 EXPECT_TRUE(String::CaseInsensitiveWideCStringEquals(L"foobar", L"foobar"));
691 EXPECT_TRUE(String::CaseInsensitiveWideCStringEquals(L"foobar", L"FOOBAR"));
692 EXPECT_TRUE(String::CaseInsensitiveWideCStringEquals(L"FOOBAR", L"foobar"));
693 }
694
695 // Tests that NULL can be assigned to a String.
TEST(StringTest,CanBeAssignedNULL)696 TEST(StringTest, CanBeAssignedNULL) {
697 const String src(NULL);
698 String dest;
699
700 dest = src;
701 EXPECT_STREQ(NULL, dest.c_str());
702 }
703
704 // Tests that the empty string "" can be assigned to a String.
TEST(StringTest,CanBeAssignedEmpty)705 TEST(StringTest, CanBeAssignedEmpty) {
706 const String src("");
707 String dest;
708
709 dest = src;
710 EXPECT_STREQ("", dest.c_str());
711 }
712
713 // Tests that a non-empty string can be assigned to a String.
TEST(StringTest,CanBeAssignedNonEmpty)714 TEST(StringTest, CanBeAssignedNonEmpty) {
715 const String src("hello");
716 String dest;
717
718 dest = src;
719 EXPECT_STREQ("hello", dest.c_str());
720 }
721
722 // Tests that a String can be assigned to itself.
TEST(StringTest,CanBeAssignedSelf)723 TEST(StringTest, CanBeAssignedSelf) {
724 String dest("hello");
725
726 dest = dest;
727 EXPECT_STREQ("hello", dest.c_str());
728 }
729
730 #if GTEST_OS_WINDOWS
731
732 // Tests String::ShowWideCString().
TEST(StringTest,ShowWideCString)733 TEST(StringTest, ShowWideCString) {
734 EXPECT_STREQ("(null)",
735 String::ShowWideCString(NULL).c_str());
736 EXPECT_STREQ("", String::ShowWideCString(L"").c_str());
737 EXPECT_STREQ("foo", String::ShowWideCString(L"foo").c_str());
738 }
739
740 // Tests String::ShowWideCStringQuoted().
TEST(StringTest,ShowWideCStringQuoted)741 TEST(StringTest, ShowWideCStringQuoted) {
742 EXPECT_STREQ("(null)",
743 String::ShowWideCStringQuoted(NULL).c_str());
744 EXPECT_STREQ("L\"\"",
745 String::ShowWideCStringQuoted(L"").c_str());
746 EXPECT_STREQ("L\"foo\"",
747 String::ShowWideCStringQuoted(L"foo").c_str());
748 }
749
750 #ifdef _WIN32_WCE
TEST(StringTest,AnsiAndUtf16Null)751 TEST(StringTest, AnsiAndUtf16Null) {
752 EXPECT_EQ(NULL, String::AnsiToUtf16(NULL));
753 EXPECT_EQ(NULL, String::Utf16ToAnsi(NULL));
754 }
755
TEST(StringTest,AnsiAndUtf16ConvertBasic)756 TEST(StringTest, AnsiAndUtf16ConvertBasic) {
757 const char* ansi = String::Utf16ToAnsi(L"str");
758 EXPECT_STREQ("str", ansi);
759 delete [] ansi;
760 const WCHAR* utf16 = String::AnsiToUtf16("str");
761 EXPECT_TRUE(wcsncmp(L"str", utf16, 3) == 0);
762 delete [] utf16;
763 }
764
TEST(StringTest,AnsiAndUtf16ConvertPathChars)765 TEST(StringTest, AnsiAndUtf16ConvertPathChars) {
766 const char* ansi = String::Utf16ToAnsi(L".:\\ \"*?");
767 EXPECT_STREQ(".:\\ \"*?", ansi);
768 delete [] ansi;
769 const WCHAR* utf16 = String::AnsiToUtf16(".:\\ \"*?");
770 EXPECT_TRUE(wcsncmp(L".:\\ \"*?", utf16, 3) == 0);
771 delete [] utf16;
772 }
773 #endif // _WIN32_WCE
774
775 #endif // GTEST_OS_WINDOWS
776
777 // Tests TestProperty construction.
TEST(TestPropertyTest,StringValue)778 TEST(TestPropertyTest, StringValue) {
779 TestProperty property("key", "1");
780 EXPECT_STREQ("key", property.key());
781 EXPECT_STREQ("1", property.value());
782 }
783
784 // Tests TestProperty replacing a value.
TEST(TestPropertyTest,ReplaceStringValue)785 TEST(TestPropertyTest, ReplaceStringValue) {
786 TestProperty property("key", "1");
787 EXPECT_STREQ("1", property.value());
788 property.SetValue("2");
789 EXPECT_STREQ("2", property.value());
790 }
791
792 class ScopedFakeTestPartResultReporterTest : public Test {
793 protected:
794 enum FailureMode {
795 FATAL_FAILURE,
796 NONFATAL_FAILURE
797 };
AddFailure(FailureMode failure)798 static void AddFailure(FailureMode failure) {
799 if (failure == FATAL_FAILURE) {
800 FAIL() << "Expected fatal failure.";
801 } else {
802 ADD_FAILURE() << "Expected non-fatal failure.";
803 }
804 }
805 };
806
807 // Tests that ScopedFakeTestPartResultReporter intercepts test
808 // failures.
TEST_F(ScopedFakeTestPartResultReporterTest,InterceptsTestFailures)809 TEST_F(ScopedFakeTestPartResultReporterTest, InterceptsTestFailures) {
810 TestPartResultArray results;
811 {
812 ScopedFakeTestPartResultReporter reporter(
813 ScopedFakeTestPartResultReporter::INTERCEPT_ONLY_CURRENT_THREAD,
814 &results);
815 AddFailure(NONFATAL_FAILURE);
816 AddFailure(FATAL_FAILURE);
817 }
818
819 EXPECT_EQ(2, results.size());
820 EXPECT_TRUE(results.GetTestPartResult(0).nonfatally_failed());
821 EXPECT_TRUE(results.GetTestPartResult(1).fatally_failed());
822 }
823
TEST_F(ScopedFakeTestPartResultReporterTest,DeprecatedConstructor)824 TEST_F(ScopedFakeTestPartResultReporterTest, DeprecatedConstructor) {
825 TestPartResultArray results;
826 {
827 // Tests, that the deprecated constructor still works.
828 ScopedFakeTestPartResultReporter reporter(&results);
829 AddFailure(NONFATAL_FAILURE);
830 }
831 EXPECT_EQ(1, results.size());
832 }
833
834 #if GTEST_IS_THREADSAFE && GTEST_HAS_PTHREAD
835
836 class ScopedFakeTestPartResultReporterWithThreadsTest
837 : public ScopedFakeTestPartResultReporterTest {
838 protected:
AddFailureInOtherThread(FailureMode failure)839 static void AddFailureInOtherThread(FailureMode failure) {
840 pthread_t tid;
841 pthread_create(&tid,
842 NULL,
843 ScopedFakeTestPartResultReporterWithThreadsTest::
844 FailureThread,
845 &failure);
846 pthread_join(tid, NULL);
847 }
848 private:
FailureThread(void * attr)849 static void* FailureThread(void* attr) {
850 FailureMode* failure = static_cast<FailureMode*>(attr);
851 AddFailure(*failure);
852 return NULL;
853 }
854 };
855
TEST_F(ScopedFakeTestPartResultReporterWithThreadsTest,InterceptsTestFailuresInAllThreads)856 TEST_F(ScopedFakeTestPartResultReporterWithThreadsTest,
857 InterceptsTestFailuresInAllThreads) {
858 TestPartResultArray results;
859 {
860 ScopedFakeTestPartResultReporter reporter(
861 ScopedFakeTestPartResultReporter::INTERCEPT_ALL_THREADS, &results);
862 AddFailure(NONFATAL_FAILURE);
863 AddFailure(FATAL_FAILURE);
864 AddFailureInOtherThread(NONFATAL_FAILURE);
865 AddFailureInOtherThread(FATAL_FAILURE);
866 }
867
868 EXPECT_EQ(4, results.size());
869 EXPECT_TRUE(results.GetTestPartResult(0).nonfatally_failed());
870 EXPECT_TRUE(results.GetTestPartResult(1).fatally_failed());
871 EXPECT_TRUE(results.GetTestPartResult(2).nonfatally_failed());
872 EXPECT_TRUE(results.GetTestPartResult(3).fatally_failed());
873 }
874
875 #endif // GTEST_IS_THREADSAFE && GTEST_HAS_PTHREAD
876
877 // Tests EXPECT_FATAL_FAILURE{,ON_ALL_THREADS}.
878
879 typedef ScopedFakeTestPartResultReporterTest ExpectFatalFailureTest;
880
TEST_F(ExpectFatalFailureTest,CatchesFatalFaliure)881 TEST_F(ExpectFatalFailureTest, CatchesFatalFaliure) {
882 EXPECT_FATAL_FAILURE(AddFailure(FATAL_FAILURE), "Expected fatal failure.");
883 }
884
TEST_F(ExpectFatalFailureTest,CatchesFatalFailureOnAllThreads)885 TEST_F(ExpectFatalFailureTest, CatchesFatalFailureOnAllThreads) {
886 // We have another test below to verify that the macro catches fatal
887 // failures generated on another thread.
888 EXPECT_FATAL_FAILURE_ON_ALL_THREADS(AddFailure(FATAL_FAILURE),
889 "Expected fatal failure.");
890 }
891
892 // Tests that EXPECT_FATAL_FAILURE() can be used in a non-void
893 // function even when the statement in it contains ASSERT_*.
894
NonVoidFunction()895 int NonVoidFunction() {
896 EXPECT_FATAL_FAILURE(ASSERT_TRUE(false), "");
897 EXPECT_FATAL_FAILURE_ON_ALL_THREADS(FAIL(), "");
898 return 0;
899 }
900
TEST_F(ExpectFatalFailureTest,CanBeUsedInNonVoidFunction)901 TEST_F(ExpectFatalFailureTest, CanBeUsedInNonVoidFunction) {
902 NonVoidFunction();
903 }
904
905 // Tests that EXPECT_FATAL_FAILURE(statement, ...) doesn't abort the
906 // current function even though 'statement' generates a fatal failure.
907
DoesNotAbortHelper(bool * aborted)908 void DoesNotAbortHelper(bool* aborted) {
909 EXPECT_FATAL_FAILURE(ASSERT_TRUE(false), "");
910 EXPECT_FATAL_FAILURE_ON_ALL_THREADS(FAIL(), "");
911
912 *aborted = false;
913 }
914
TEST_F(ExpectFatalFailureTest,DoesNotAbort)915 TEST_F(ExpectFatalFailureTest, DoesNotAbort) {
916 bool aborted = true;
917 DoesNotAbortHelper(&aborted);
918 EXPECT_FALSE(aborted);
919 }
920
921 // Tests that the EXPECT_FATAL_FAILURE{,_ON_ALL_THREADS} accepts a
922 // statement that contains a macro which expands to code containing an
923 // unprotected comma.
924
925 static int global_var = 0;
926 #define GTEST_USE_UNPROTECTED_COMMA_ global_var++, global_var++
927
TEST_F(ExpectFatalFailureTest,AcceptsMacroThatExpandsToUnprotectedComma)928 TEST_F(ExpectFatalFailureTest, AcceptsMacroThatExpandsToUnprotectedComma) {
929 EXPECT_FATAL_FAILURE({
930 GTEST_USE_UNPROTECTED_COMMA_;
931 AddFailure(FATAL_FAILURE);
932 }, "");
933
934 EXPECT_FATAL_FAILURE_ON_ALL_THREADS({
935 GTEST_USE_UNPROTECTED_COMMA_;
936 AddFailure(FATAL_FAILURE);
937 }, "");
938 }
939
940 // Tests EXPECT_NONFATAL_FAILURE{,ON_ALL_THREADS}.
941
942 typedef ScopedFakeTestPartResultReporterTest ExpectNonfatalFailureTest;
943
TEST_F(ExpectNonfatalFailureTest,CatchesNonfatalFailure)944 TEST_F(ExpectNonfatalFailureTest, CatchesNonfatalFailure) {
945 EXPECT_NONFATAL_FAILURE(AddFailure(NONFATAL_FAILURE),
946 "Expected non-fatal failure.");
947 }
948
TEST_F(ExpectNonfatalFailureTest,CatchesNonfatalFailureOnAllThreads)949 TEST_F(ExpectNonfatalFailureTest, CatchesNonfatalFailureOnAllThreads) {
950 // We have another test below to verify that the macro catches
951 // non-fatal failures generated on another thread.
952 EXPECT_NONFATAL_FAILURE_ON_ALL_THREADS(AddFailure(NONFATAL_FAILURE),
953 "Expected non-fatal failure.");
954 }
955
956 // Tests that the EXPECT_NONFATAL_FAILURE{,_ON_ALL_THREADS} accepts a
957 // statement that contains a macro which expands to code containing an
958 // unprotected comma.
TEST_F(ExpectNonfatalFailureTest,AcceptsMacroThatExpandsToUnprotectedComma)959 TEST_F(ExpectNonfatalFailureTest, AcceptsMacroThatExpandsToUnprotectedComma) {
960 EXPECT_NONFATAL_FAILURE({
961 GTEST_USE_UNPROTECTED_COMMA_;
962 AddFailure(NONFATAL_FAILURE);
963 }, "");
964
965 EXPECT_NONFATAL_FAILURE_ON_ALL_THREADS({
966 GTEST_USE_UNPROTECTED_COMMA_;
967 AddFailure(NONFATAL_FAILURE);
968 }, "");
969 }
970
971 #if GTEST_IS_THREADSAFE && GTEST_HAS_PTHREAD
972
973 typedef ScopedFakeTestPartResultReporterWithThreadsTest
974 ExpectFailureWithThreadsTest;
975
TEST_F(ExpectFailureWithThreadsTest,ExpectFatalFailureOnAllThreads)976 TEST_F(ExpectFailureWithThreadsTest, ExpectFatalFailureOnAllThreads) {
977 EXPECT_FATAL_FAILURE_ON_ALL_THREADS(AddFailureInOtherThread(FATAL_FAILURE),
978 "Expected fatal failure.");
979 }
980
TEST_F(ExpectFailureWithThreadsTest,ExpectNonFatalFailureOnAllThreads)981 TEST_F(ExpectFailureWithThreadsTest, ExpectNonFatalFailureOnAllThreads) {
982 EXPECT_NONFATAL_FAILURE_ON_ALL_THREADS(
983 AddFailureInOtherThread(NONFATAL_FAILURE), "Expected non-fatal failure.");
984 }
985
986 #endif // GTEST_IS_THREADSAFE && GTEST_HAS_PTHREAD
987
988 // Tests the TestResult class
989
990 // The test fixture for testing TestResult.
991 class TestResultTest : public Test {
992 protected:
993 typedef List<TestPartResult> TPRList;
994
995 // We make use of 2 TestPartResult objects,
996 TestPartResult * pr1, * pr2;
997
998 // ... and 3 TestResult objects.
999 TestResult * r0, * r1, * r2;
1000
SetUp()1001 virtual void SetUp() {
1002 // pr1 is for success.
1003 pr1 = new TestPartResult(TPRT_SUCCESS, "foo/bar.cc", 10, "Success!");
1004
1005 // pr2 is for fatal failure.
1006 pr2 = new TestPartResult(TPRT_FATAL_FAILURE, "foo/bar.cc",
1007 -1, // This line number means "unknown"
1008 "Failure!");
1009
1010 // Creates the TestResult objects.
1011 r0 = new TestResult();
1012 r1 = new TestResult();
1013 r2 = new TestResult();
1014
1015 // In order to test TestResult, we need to modify its internal
1016 // state, in particular the TestPartResult list it holds.
1017 // test_part_results() returns a const reference to this list.
1018 // We cast it to a non-const object s.t. it can be modified (yes,
1019 // this is a hack).
1020 TPRList * list1, * list2;
1021 list1 = const_cast<List<TestPartResult> *>(
1022 & r1->test_part_results());
1023 list2 = const_cast<List<TestPartResult> *>(
1024 & r2->test_part_results());
1025
1026 // r0 is an empty TestResult.
1027
1028 // r1 contains a single SUCCESS TestPartResult.
1029 list1->PushBack(*pr1);
1030
1031 // r2 contains a SUCCESS, and a FAILURE.
1032 list2->PushBack(*pr1);
1033 list2->PushBack(*pr2);
1034 }
1035
TearDown()1036 virtual void TearDown() {
1037 delete pr1;
1038 delete pr2;
1039
1040 delete r0;
1041 delete r1;
1042 delete r2;
1043 }
1044 };
1045
1046 // Tests TestResult::test_part_results()
TEST_F(TestResultTest,test_part_results)1047 TEST_F(TestResultTest, test_part_results) {
1048 ASSERT_EQ(0u, r0->test_part_results().size());
1049 ASSERT_EQ(1u, r1->test_part_results().size());
1050 ASSERT_EQ(2u, r2->test_part_results().size());
1051 }
1052
1053 // Tests TestResult::successful_part_count()
TEST_F(TestResultTest,successful_part_count)1054 TEST_F(TestResultTest, successful_part_count) {
1055 ASSERT_EQ(0u, r0->successful_part_count());
1056 ASSERT_EQ(1u, r1->successful_part_count());
1057 ASSERT_EQ(1u, r2->successful_part_count());
1058 }
1059
1060 // Tests TestResult::failed_part_count()
TEST_F(TestResultTest,failed_part_count)1061 TEST_F(TestResultTest, failed_part_count) {
1062 ASSERT_EQ(0u, r0->failed_part_count());
1063 ASSERT_EQ(0u, r1->failed_part_count());
1064 ASSERT_EQ(1u, r2->failed_part_count());
1065 }
1066
1067 // Tests testing::internal::GetFailedPartCount().
TEST_F(TestResultTest,GetFailedPartCount)1068 TEST_F(TestResultTest, GetFailedPartCount) {
1069 ASSERT_EQ(0u, GetFailedPartCount(r0));
1070 ASSERT_EQ(0u, GetFailedPartCount(r1));
1071 ASSERT_EQ(1u, GetFailedPartCount(r2));
1072 }
1073
1074 // Tests TestResult::total_part_count()
TEST_F(TestResultTest,total_part_count)1075 TEST_F(TestResultTest, total_part_count) {
1076 ASSERT_EQ(0u, r0->total_part_count());
1077 ASSERT_EQ(1u, r1->total_part_count());
1078 ASSERT_EQ(2u, r2->total_part_count());
1079 }
1080
1081 // Tests TestResult::Passed()
TEST_F(TestResultTest,Passed)1082 TEST_F(TestResultTest, Passed) {
1083 ASSERT_TRUE(r0->Passed());
1084 ASSERT_TRUE(r1->Passed());
1085 ASSERT_FALSE(r2->Passed());
1086 }
1087
1088 // Tests TestResult::Failed()
TEST_F(TestResultTest,Failed)1089 TEST_F(TestResultTest, Failed) {
1090 ASSERT_FALSE(r0->Failed());
1091 ASSERT_FALSE(r1->Failed());
1092 ASSERT_TRUE(r2->Failed());
1093 }
1094
1095 // Tests TestResult::test_properties() has no properties when none are added.
TEST(TestResultPropertyTest,NoPropertiesFoundWhenNoneAreAdded)1096 TEST(TestResultPropertyTest, NoPropertiesFoundWhenNoneAreAdded) {
1097 TestResult test_result;
1098 ASSERT_EQ(0u, test_result.test_properties().size());
1099 }
1100
1101 // Tests TestResult::test_properties() has the expected property when added.
TEST(TestResultPropertyTest,OnePropertyFoundWhenAdded)1102 TEST(TestResultPropertyTest, OnePropertyFoundWhenAdded) {
1103 TestResult test_result;
1104 TestProperty property("key_1", "1");
1105 test_result.RecordProperty(property);
1106 const List<TestProperty>& properties = test_result.test_properties();
1107 ASSERT_EQ(1u, properties.size());
1108 TestProperty actual_property = properties.Head()->element();
1109 EXPECT_STREQ("key_1", actual_property.key());
1110 EXPECT_STREQ("1", actual_property.value());
1111 }
1112
1113 // Tests TestResult::test_properties() has multiple properties when added.
TEST(TestResultPropertyTest,MultiplePropertiesFoundWhenAdded)1114 TEST(TestResultPropertyTest, MultiplePropertiesFoundWhenAdded) {
1115 TestResult test_result;
1116 TestProperty property_1("key_1", "1");
1117 TestProperty property_2("key_2", "2");
1118 test_result.RecordProperty(property_1);
1119 test_result.RecordProperty(property_2);
1120 const List<TestProperty>& properties = test_result.test_properties();
1121 ASSERT_EQ(2u, properties.size());
1122 TestProperty actual_property_1 = properties.Head()->element();
1123 EXPECT_STREQ("key_1", actual_property_1.key());
1124 EXPECT_STREQ("1", actual_property_1.value());
1125
1126 TestProperty actual_property_2 = properties.Last()->element();
1127 EXPECT_STREQ("key_2", actual_property_2.key());
1128 EXPECT_STREQ("2", actual_property_2.value());
1129 }
1130
1131 // Tests TestResult::test_properties() overrides values for duplicate keys.
TEST(TestResultPropertyTest,OverridesValuesForDuplicateKeys)1132 TEST(TestResultPropertyTest, OverridesValuesForDuplicateKeys) {
1133 TestResult test_result;
1134 TestProperty property_1_1("key_1", "1");
1135 TestProperty property_2_1("key_2", "2");
1136 TestProperty property_1_2("key_1", "12");
1137 TestProperty property_2_2("key_2", "22");
1138 test_result.RecordProperty(property_1_1);
1139 test_result.RecordProperty(property_2_1);
1140 test_result.RecordProperty(property_1_2);
1141 test_result.RecordProperty(property_2_2);
1142
1143 const List<TestProperty>& properties = test_result.test_properties();
1144 ASSERT_EQ(2u, properties.size());
1145 TestProperty actual_property_1 = properties.Head()->element();
1146 EXPECT_STREQ("key_1", actual_property_1.key());
1147 EXPECT_STREQ("12", actual_property_1.value());
1148
1149 TestProperty actual_property_2 = properties.Last()->element();
1150 EXPECT_STREQ("key_2", actual_property_2.key());
1151 EXPECT_STREQ("22", actual_property_2.value());
1152 }
1153
1154 // When a property using a reserved key is supplied to this function, it tests
1155 // that a non-fatal failure is added, a fatal failure is not added, and that the
1156 // property is not recorded.
ExpectNonFatalFailureRecordingPropertyWithReservedKey(const char * key)1157 void ExpectNonFatalFailureRecordingPropertyWithReservedKey(const char* key) {
1158 TestResult test_result;
1159 TestProperty property(key, "1");
1160 EXPECT_NONFATAL_FAILURE(test_result.RecordProperty(property), "Reserved key");
1161 ASSERT_TRUE(test_result.test_properties().IsEmpty()) << "Not recorded";
1162 }
1163
1164 // Attempting to recording a property with the Reserved literal "name"
1165 // should add a non-fatal failure and the property should not be recorded.
TEST(TestResultPropertyTest,AddFailureWhenUsingReservedKeyCalledName)1166 TEST(TestResultPropertyTest, AddFailureWhenUsingReservedKeyCalledName) {
1167 ExpectNonFatalFailureRecordingPropertyWithReservedKey("name");
1168 }
1169
1170 // Attempting to recording a property with the Reserved literal "status"
1171 // should add a non-fatal failure and the property should not be recorded.
TEST(TestResultPropertyTest,AddFailureWhenUsingReservedKeyCalledStatus)1172 TEST(TestResultPropertyTest, AddFailureWhenUsingReservedKeyCalledStatus) {
1173 ExpectNonFatalFailureRecordingPropertyWithReservedKey("status");
1174 }
1175
1176 // Attempting to recording a property with the Reserved literal "time"
1177 // should add a non-fatal failure and the property should not be recorded.
TEST(TestResultPropertyTest,AddFailureWhenUsingReservedKeyCalledTime)1178 TEST(TestResultPropertyTest, AddFailureWhenUsingReservedKeyCalledTime) {
1179 ExpectNonFatalFailureRecordingPropertyWithReservedKey("time");
1180 }
1181
1182 // Attempting to recording a property with the Reserved literal "classname"
1183 // should add a non-fatal failure and the property should not be recorded.
TEST(TestResultPropertyTest,AddFailureWhenUsingReservedKeyCalledClassname)1184 TEST(TestResultPropertyTest, AddFailureWhenUsingReservedKeyCalledClassname) {
1185 ExpectNonFatalFailureRecordingPropertyWithReservedKey("classname");
1186 }
1187
1188 // Tests that GTestFlagSaver works on Windows and Mac.
1189
1190 class GTestFlagSaverTest : public Test {
1191 protected:
1192 // Saves the Google Test flags such that we can restore them later, and
1193 // then sets them to their default values. This will be called
1194 // before the first test in this test case is run.
SetUpTestCase()1195 static void SetUpTestCase() {
1196 saver_ = new GTestFlagSaver;
1197
1198 GTEST_FLAG(also_run_disabled_tests) = false;
1199 GTEST_FLAG(break_on_failure) = false;
1200 GTEST_FLAG(catch_exceptions) = false;
1201 GTEST_FLAG(death_test_use_fork) = false;
1202 GTEST_FLAG(color) = "auto";
1203 GTEST_FLAG(filter) = "";
1204 GTEST_FLAG(list_tests) = false;
1205 GTEST_FLAG(output) = "";
1206 GTEST_FLAG(print_time) = false;
1207 GTEST_FLAG(repeat) = 1;
1208 GTEST_FLAG(throw_on_failure) = false;
1209 }
1210
1211 // Restores the Google Test flags that the tests have modified. This will
1212 // be called after the last test in this test case is run.
TearDownTestCase()1213 static void TearDownTestCase() {
1214 delete saver_;
1215 saver_ = NULL;
1216 }
1217
1218 // Verifies that the Google Test flags have their default values, and then
1219 // modifies each of them.
VerifyAndModifyFlags()1220 void VerifyAndModifyFlags() {
1221 EXPECT_FALSE(GTEST_FLAG(also_run_disabled_tests));
1222 EXPECT_FALSE(GTEST_FLAG(break_on_failure));
1223 EXPECT_FALSE(GTEST_FLAG(catch_exceptions));
1224 EXPECT_STREQ("auto", GTEST_FLAG(color).c_str());
1225 EXPECT_FALSE(GTEST_FLAG(death_test_use_fork));
1226 EXPECT_STREQ("", GTEST_FLAG(filter).c_str());
1227 EXPECT_FALSE(GTEST_FLAG(list_tests));
1228 EXPECT_STREQ("", GTEST_FLAG(output).c_str());
1229 EXPECT_FALSE(GTEST_FLAG(print_time));
1230 EXPECT_EQ(1, GTEST_FLAG(repeat));
1231 EXPECT_FALSE(GTEST_FLAG(throw_on_failure));
1232
1233 GTEST_FLAG(also_run_disabled_tests) = true;
1234 GTEST_FLAG(break_on_failure) = true;
1235 GTEST_FLAG(catch_exceptions) = true;
1236 GTEST_FLAG(color) = "no";
1237 GTEST_FLAG(death_test_use_fork) = true;
1238 GTEST_FLAG(filter) = "abc";
1239 GTEST_FLAG(list_tests) = true;
1240 GTEST_FLAG(output) = "xml:foo.xml";
1241 GTEST_FLAG(print_time) = true;
1242 GTEST_FLAG(repeat) = 100;
1243 GTEST_FLAG(throw_on_failure) = true;
1244 }
1245 private:
1246 // For saving Google Test flags during this test case.
1247 static GTestFlagSaver* saver_;
1248 };
1249
1250 GTestFlagSaver* GTestFlagSaverTest::saver_ = NULL;
1251
1252 // Google Test doesn't guarantee the order of tests. The following two
1253 // tests are designed to work regardless of their order.
1254
1255 // Modifies the Google Test flags in the test body.
TEST_F(GTestFlagSaverTest,ModifyGTestFlags)1256 TEST_F(GTestFlagSaverTest, ModifyGTestFlags) {
1257 VerifyAndModifyFlags();
1258 }
1259
1260 // Verifies that the Google Test flags in the body of the previous test were
1261 // restored to their original values.
TEST_F(GTestFlagSaverTest,VerifyGTestFlags)1262 TEST_F(GTestFlagSaverTest, VerifyGTestFlags) {
1263 VerifyAndModifyFlags();
1264 }
1265
1266 // Sets an environment variable with the given name to the given
1267 // value. If the value argument is "", unsets the environment
1268 // variable. The caller must ensure that both arguments are not NULL.
SetEnv(const char * name,const char * value)1269 static void SetEnv(const char* name, const char* value) {
1270 #ifdef _WIN32_WCE
1271 // Environment variables are not supported on Windows CE.
1272 return;
1273 #elif GTEST_OS_WINDOWS // If we are on Windows proper.
1274 _putenv((Message() << name << "=" << value).GetString().c_str());
1275 #else
1276 if (*value == '\0') {
1277 unsetenv(name);
1278 } else {
1279 setenv(name, value, 1);
1280 }
1281 #endif
1282 }
1283
1284 #ifndef _WIN32_WCE
1285 // Environment variables are not supported on Windows CE.
1286
1287 using testing::internal::Int32FromGTestEnv;
1288
1289 // Tests Int32FromGTestEnv().
1290
1291 // Tests that Int32FromGTestEnv() returns the default value when the
1292 // environment variable is not set.
TEST(Int32FromGTestEnvTest,ReturnsDefaultWhenVariableIsNotSet)1293 TEST(Int32FromGTestEnvTest, ReturnsDefaultWhenVariableIsNotSet) {
1294 SetEnv(GTEST_FLAG_PREFIX_UPPER_ "TEMP", "");
1295 EXPECT_EQ(10, Int32FromGTestEnv("temp", 10));
1296 }
1297
1298 // Tests that Int32FromGTestEnv() returns the default value when the
1299 // environment variable overflows as an Int32.
TEST(Int32FromGTestEnvTest,ReturnsDefaultWhenValueOverflows)1300 TEST(Int32FromGTestEnvTest, ReturnsDefaultWhenValueOverflows) {
1301 printf("(expecting 2 warnings)\n");
1302
1303 SetEnv(GTEST_FLAG_PREFIX_UPPER_ "TEMP", "12345678987654321");
1304 EXPECT_EQ(20, Int32FromGTestEnv("temp", 20));
1305
1306 SetEnv(GTEST_FLAG_PREFIX_UPPER_ "TEMP", "-12345678987654321");
1307 EXPECT_EQ(30, Int32FromGTestEnv("temp", 30));
1308 }
1309
1310 // Tests that Int32FromGTestEnv() returns the default value when the
1311 // environment variable does not represent a valid decimal integer.
TEST(Int32FromGTestEnvTest,ReturnsDefaultWhenValueIsInvalid)1312 TEST(Int32FromGTestEnvTest, ReturnsDefaultWhenValueIsInvalid) {
1313 printf("(expecting 2 warnings)\n");
1314
1315 SetEnv(GTEST_FLAG_PREFIX_UPPER_ "TEMP", "A1");
1316 EXPECT_EQ(40, Int32FromGTestEnv("temp", 40));
1317
1318 SetEnv(GTEST_FLAG_PREFIX_UPPER_ "TEMP", "12X");
1319 EXPECT_EQ(50, Int32FromGTestEnv("temp", 50));
1320 }
1321
1322 // Tests that Int32FromGTestEnv() parses and returns the value of the
1323 // environment variable when it represents a valid decimal integer in
1324 // the range of an Int32.
TEST(Int32FromGTestEnvTest,ParsesAndReturnsValidValue)1325 TEST(Int32FromGTestEnvTest, ParsesAndReturnsValidValue) {
1326 SetEnv(GTEST_FLAG_PREFIX_UPPER_ "TEMP", "123");
1327 EXPECT_EQ(123, Int32FromGTestEnv("temp", 0));
1328
1329 SetEnv(GTEST_FLAG_PREFIX_UPPER_ "TEMP", "-321");
1330 EXPECT_EQ(-321, Int32FromGTestEnv("temp", 0));
1331 }
1332 #endif // !defined(_WIN32_WCE)
1333
1334 // Tests ParseInt32Flag().
1335
1336 // Tests that ParseInt32Flag() returns false and doesn't change the
1337 // output value when the flag has wrong format
TEST(ParseInt32FlagTest,ReturnsFalseForInvalidFlag)1338 TEST(ParseInt32FlagTest, ReturnsFalseForInvalidFlag) {
1339 Int32 value = 123;
1340 EXPECT_FALSE(ParseInt32Flag("--a=100", "b", &value));
1341 EXPECT_EQ(123, value);
1342
1343 EXPECT_FALSE(ParseInt32Flag("a=100", "a", &value));
1344 EXPECT_EQ(123, value);
1345 }
1346
1347 // Tests that ParseInt32Flag() returns false and doesn't change the
1348 // output value when the flag overflows as an Int32.
TEST(ParseInt32FlagTest,ReturnsDefaultWhenValueOverflows)1349 TEST(ParseInt32FlagTest, ReturnsDefaultWhenValueOverflows) {
1350 printf("(expecting 2 warnings)\n");
1351
1352 Int32 value = 123;
1353 EXPECT_FALSE(ParseInt32Flag("--abc=12345678987654321", "abc", &value));
1354 EXPECT_EQ(123, value);
1355
1356 EXPECT_FALSE(ParseInt32Flag("--abc=-12345678987654321", "abc", &value));
1357 EXPECT_EQ(123, value);
1358 }
1359
1360 // Tests that ParseInt32Flag() returns false and doesn't change the
1361 // output value when the flag does not represent a valid decimal
1362 // integer.
TEST(ParseInt32FlagTest,ReturnsDefaultWhenValueIsInvalid)1363 TEST(ParseInt32FlagTest, ReturnsDefaultWhenValueIsInvalid) {
1364 printf("(expecting 2 warnings)\n");
1365
1366 Int32 value = 123;
1367 EXPECT_FALSE(ParseInt32Flag("--abc=A1", "abc", &value));
1368 EXPECT_EQ(123, value);
1369
1370 EXPECT_FALSE(ParseInt32Flag("--abc=12X", "abc", &value));
1371 EXPECT_EQ(123, value);
1372 }
1373
1374 // Tests that ParseInt32Flag() parses the value of the flag and
1375 // returns true when the flag represents a valid decimal integer in
1376 // the range of an Int32.
TEST(ParseInt32FlagTest,ParsesAndReturnsValidValue)1377 TEST(ParseInt32FlagTest, ParsesAndReturnsValidValue) {
1378 Int32 value = 123;
1379 EXPECT_TRUE(ParseInt32Flag("--" GTEST_FLAG_PREFIX_ "abc=456", "abc", &value));
1380 EXPECT_EQ(456, value);
1381
1382 EXPECT_TRUE(ParseInt32Flag("--" GTEST_FLAG_PREFIX_ "abc=-789", "abc", &value));
1383 EXPECT_EQ(-789, value);
1384 }
1385
1386 // Tests that Int32FromEnvOrDie() parses the value of the var or
1387 // returns the correct default.
TEST(Int32FromEnvOrDieTest,ParsesAndReturnsValidValue)1388 TEST(Int32FromEnvOrDieTest, ParsesAndReturnsValidValue) {
1389 EXPECT_EQ(333, Int32FromEnvOrDie(GTEST_FLAG_PREFIX_UPPER_ "UnsetVar", 333));
1390 SetEnv(GTEST_FLAG_PREFIX_UPPER_ "UnsetVar", "123");
1391 EXPECT_EQ(123, Int32FromEnvOrDie(GTEST_FLAG_PREFIX_UPPER_ "UnsetVar", 333));
1392 SetEnv(GTEST_FLAG_PREFIX_UPPER_ "UnsetVar", "-123");
1393 EXPECT_EQ(-123, Int32FromEnvOrDie(GTEST_FLAG_PREFIX_UPPER_ "UnsetVar", 333));
1394 }
1395
1396 #if GTEST_HAS_DEATH_TEST
1397
1398 // Tests that Int32FromEnvOrDie() aborts with an error message
1399 // if the variable is not an Int32.
TEST(Int32FromEnvOrDieDeathTest,AbortsOnFailure)1400 TEST(Int32FromEnvOrDieDeathTest, AbortsOnFailure) {
1401 SetEnv(GTEST_FLAG_PREFIX_UPPER_ "VAR", "xxx");
1402 EXPECT_DEATH({Int32FromEnvOrDie(GTEST_FLAG_PREFIX_UPPER_ "VAR", 123);},
1403 ".*");
1404 }
1405
1406 // Tests that Int32FromEnvOrDie() aborts with an error message
1407 // if the variable cannot be represnted by an Int32.
TEST(Int32FromEnvOrDieDeathTest,AbortsOnInt32Overflow)1408 TEST(Int32FromEnvOrDieDeathTest, AbortsOnInt32Overflow) {
1409 SetEnv(GTEST_FLAG_PREFIX_UPPER_ "VAR", "1234567891234567891234");
1410 EXPECT_DEATH({Int32FromEnvOrDie(GTEST_FLAG_PREFIX_UPPER_ "VAR", 123);},
1411 ".*");
1412 }
1413
1414 #endif // GTEST_HAS_DEATH_TEST
1415
1416
1417 // Tests that ShouldRunTestOnShard() selects all tests
1418 // where there is 1 shard.
TEST(ShouldRunTestOnShardTest,IsPartitionWhenThereIsOneShard)1419 TEST(ShouldRunTestOnShardTest, IsPartitionWhenThereIsOneShard) {
1420 EXPECT_TRUE(ShouldRunTestOnShard(1, 0, 0));
1421 EXPECT_TRUE(ShouldRunTestOnShard(1, 0, 1));
1422 EXPECT_TRUE(ShouldRunTestOnShard(1, 0, 2));
1423 EXPECT_TRUE(ShouldRunTestOnShard(1, 0, 3));
1424 EXPECT_TRUE(ShouldRunTestOnShard(1, 0, 4));
1425 }
1426
1427 class ShouldShardTest : public testing::Test {
1428 protected:
SetUp()1429 virtual void SetUp() {
1430 index_var_ = GTEST_FLAG_PREFIX_UPPER_ "INDEX";
1431 total_var_ = GTEST_FLAG_PREFIX_UPPER_ "TOTAL";
1432 }
1433
TearDown()1434 virtual void TearDown() {
1435 SetEnv(index_var_, "");
1436 SetEnv(total_var_, "");
1437 }
1438
1439 const char* index_var_;
1440 const char* total_var_;
1441 };
1442
1443 // Tests that sharding is disabled if neither of the environment variables
1444 // are set.
TEST_F(ShouldShardTest,ReturnsFalseWhenNeitherEnvVarIsSet)1445 TEST_F(ShouldShardTest, ReturnsFalseWhenNeitherEnvVarIsSet) {
1446 SetEnv(index_var_, "");
1447 SetEnv(total_var_, "");
1448
1449 EXPECT_FALSE(ShouldShard(total_var_, index_var_, false));
1450 EXPECT_FALSE(ShouldShard(total_var_, index_var_, true));
1451 }
1452
1453 // Tests that sharding is not enabled if total_shards == 1.
TEST_F(ShouldShardTest,ReturnsFalseWhenTotalShardIsOne)1454 TEST_F(ShouldShardTest, ReturnsFalseWhenTotalShardIsOne) {
1455 SetEnv(index_var_, "0");
1456 SetEnv(total_var_, "1");
1457 EXPECT_FALSE(ShouldShard(total_var_, index_var_, false));
1458 EXPECT_FALSE(ShouldShard(total_var_, index_var_, true));
1459 }
1460
1461 // Tests that sharding is enabled if total_shards > 1 and
1462 // we are not in a death test subprocess.
TEST_F(ShouldShardTest,WorksWhenShardEnvVarsAreValid)1463 TEST_F(ShouldShardTest, WorksWhenShardEnvVarsAreValid) {
1464 SetEnv(index_var_, "4");
1465 SetEnv(total_var_, "22");
1466 EXPECT_TRUE(ShouldShard(total_var_, index_var_, false));
1467 EXPECT_FALSE(ShouldShard(total_var_, index_var_, true));
1468
1469 SetEnv(index_var_, "8");
1470 SetEnv(total_var_, "9");
1471 EXPECT_TRUE(ShouldShard(total_var_, index_var_, false));
1472 EXPECT_FALSE(ShouldShard(total_var_, index_var_, true));
1473
1474 SetEnv(index_var_, "0");
1475 SetEnv(total_var_, "9");
1476 EXPECT_TRUE(ShouldShard(total_var_, index_var_, false));
1477 EXPECT_FALSE(ShouldShard(total_var_, index_var_, true));
1478 }
1479
1480 #if GTEST_HAS_DEATH_TEST
1481
1482 // Tests that we exit in error if the sharding values are not valid.
TEST_F(ShouldShardTest,AbortsWhenShardingEnvVarsAreInvalid)1483 TEST_F(ShouldShardTest, AbortsWhenShardingEnvVarsAreInvalid) {
1484 SetEnv(index_var_, "4");
1485 SetEnv(total_var_, "4");
1486 EXPECT_DEATH({ShouldShard(total_var_, index_var_, false);},
1487 ".*");
1488
1489 SetEnv(index_var_, "4");
1490 SetEnv(total_var_, "-2");
1491 EXPECT_DEATH({ShouldShard(total_var_, index_var_, false);},
1492 ".*");
1493
1494 SetEnv(index_var_, "5");
1495 SetEnv(total_var_, "");
1496 EXPECT_DEATH({ShouldShard(total_var_, index_var_, false);},
1497 ".*");
1498
1499 SetEnv(index_var_, "");
1500 SetEnv(total_var_, "5");
1501 EXPECT_DEATH({ShouldShard(total_var_, index_var_, false);},
1502 ".*");
1503 }
1504
1505 #endif // GTEST_HAS_DEATH_TEST
1506
1507 // Tests that ShouldRunTestOnShard is a partition when 5
1508 // shards are used.
TEST(ShouldRunTestOnShardTest,IsPartitionWhenThereAreFiveShards)1509 TEST(ShouldRunTestOnShardTest, IsPartitionWhenThereAreFiveShards) {
1510 // Choose an arbitrary number of tests and shards.
1511 const int num_tests = 17;
1512 const int num_shards = 5;
1513
1514 // Check partitioning: each test should be on exactly 1 shard.
1515 for (int test_id = 0; test_id < num_tests; test_id++) {
1516 int prev_selected_shard_index = -1;
1517 for (int shard_index = 0; shard_index < num_shards; shard_index++) {
1518 if (ShouldRunTestOnShard(num_shards, shard_index, test_id)) {
1519 if (prev_selected_shard_index < 0) {
1520 prev_selected_shard_index = shard_index;
1521 } else {
1522 ADD_FAILURE() << "Shard " << prev_selected_shard_index << " and "
1523 << shard_index << " are both selected to run test " << test_id;
1524 }
1525 }
1526 }
1527 }
1528
1529 // Check balance: This is not required by the sharding protocol, but is a
1530 // desirable property for performance.
1531 for (int shard_index = 0; shard_index < num_shards; shard_index++) {
1532 int num_tests_on_shard = 0;
1533 for (int test_id = 0; test_id < num_tests; test_id++) {
1534 num_tests_on_shard +=
1535 ShouldRunTestOnShard(num_shards, shard_index, test_id);
1536 }
1537 EXPECT_GE(num_tests_on_shard, num_tests / num_shards);
1538 }
1539 }
1540
1541 // For the same reason we are not explicitly testing everything in the
1542 // Test class, there are no separate tests for the following classes
1543 // (except for some trivial cases):
1544 //
1545 // TestCase, UnitTest, UnitTestResultPrinter.
1546 //
1547 // Similarly, there are no separate tests for the following macros:
1548 //
1549 // TEST, TEST_F, RUN_ALL_TESTS
1550
TEST(UnitTestTest,CanGetOriginalWorkingDir)1551 TEST(UnitTestTest, CanGetOriginalWorkingDir) {
1552 ASSERT_TRUE(UnitTest::GetInstance()->original_working_dir() != NULL);
1553 EXPECT_STRNE(UnitTest::GetInstance()->original_working_dir(), "");
1554 }
1555
1556 // This group of tests is for predicate assertions (ASSERT_PRED*, etc)
1557 // of various arities. They do not attempt to be exhaustive. Rather,
1558 // view them as smoke tests that can be easily reviewed and verified.
1559 // A more complete set of tests for predicate assertions can be found
1560 // in gtest_pred_impl_unittest.cc.
1561
1562 // First, some predicates and predicate-formatters needed by the tests.
1563
1564 // Returns true iff the argument is an even number.
IsEven(int n)1565 bool IsEven(int n) {
1566 return (n % 2) == 0;
1567 }
1568
1569 // A functor that returns true iff the argument is an even number.
1570 struct IsEvenFunctor {
operator ()__anon696925310111::IsEvenFunctor1571 bool operator()(int n) { return IsEven(n); }
1572 };
1573
1574 // A predicate-formatter function that asserts the argument is an even
1575 // number.
AssertIsEven(const char * expr,int n)1576 AssertionResult AssertIsEven(const char* expr, int n) {
1577 if (IsEven(n)) {
1578 return AssertionSuccess();
1579 }
1580
1581 Message msg;
1582 msg << expr << " evaluates to " << n << ", which is not even.";
1583 return AssertionFailure(msg);
1584 }
1585
1586 // A predicate-formatter functor that asserts the argument is an even
1587 // number.
1588 struct AssertIsEvenFunctor {
operator ()__anon696925310111::AssertIsEvenFunctor1589 AssertionResult operator()(const char* expr, int n) {
1590 return AssertIsEven(expr, n);
1591 }
1592 };
1593
1594 // Returns true iff the sum of the arguments is an even number.
SumIsEven2(int n1,int n2)1595 bool SumIsEven2(int n1, int n2) {
1596 return IsEven(n1 + n2);
1597 }
1598
1599 // A functor that returns true iff the sum of the arguments is an even
1600 // number.
1601 struct SumIsEven3Functor {
operator ()__anon696925310111::SumIsEven3Functor1602 bool operator()(int n1, int n2, int n3) {
1603 return IsEven(n1 + n2 + n3);
1604 }
1605 };
1606
1607 // A predicate-formatter function that asserts the sum of the
1608 // arguments is an even number.
AssertSumIsEven4(const char * e1,const char * e2,const char * e3,const char * e4,int n1,int n2,int n3,int n4)1609 AssertionResult AssertSumIsEven4(
1610 const char* e1, const char* e2, const char* e3, const char* e4,
1611 int n1, int n2, int n3, int n4) {
1612 const int sum = n1 + n2 + n3 + n4;
1613 if (IsEven(sum)) {
1614 return AssertionSuccess();
1615 }
1616
1617 Message msg;
1618 msg << e1 << " + " << e2 << " + " << e3 << " + " << e4
1619 << " (" << n1 << " + " << n2 << " + " << n3 << " + " << n4
1620 << ") evaluates to " << sum << ", which is not even.";
1621 return AssertionFailure(msg);
1622 }
1623
1624 // A predicate-formatter functor that asserts the sum of the arguments
1625 // is an even number.
1626 struct AssertSumIsEven5Functor {
operator ()__anon696925310111::AssertSumIsEven5Functor1627 AssertionResult operator()(
1628 const char* e1, const char* e2, const char* e3, const char* e4,
1629 const char* e5, int n1, int n2, int n3, int n4, int n5) {
1630 const int sum = n1 + n2 + n3 + n4 + n5;
1631 if (IsEven(sum)) {
1632 return AssertionSuccess();
1633 }
1634
1635 Message msg;
1636 msg << e1 << " + " << e2 << " + " << e3 << " + " << e4 << " + " << e5
1637 << " ("
1638 << n1 << " + " << n2 << " + " << n3 << " + " << n4 << " + " << n5
1639 << ") evaluates to " << sum << ", which is not even.";
1640 return AssertionFailure(msg);
1641 }
1642 };
1643
1644
1645 // Tests unary predicate assertions.
1646
1647 // Tests unary predicate assertions that don't use a custom formatter.
TEST(Pred1Test,WithoutFormat)1648 TEST(Pred1Test, WithoutFormat) {
1649 // Success cases.
1650 EXPECT_PRED1(IsEvenFunctor(), 2) << "This failure is UNEXPECTED!";
1651 ASSERT_PRED1(IsEven, 4);
1652
1653 // Failure cases.
1654 EXPECT_NONFATAL_FAILURE({ // NOLINT
1655 EXPECT_PRED1(IsEven, 5) << "This failure is expected.";
1656 }, "This failure is expected.");
1657 EXPECT_FATAL_FAILURE(ASSERT_PRED1(IsEvenFunctor(), 5),
1658 "evaluates to false");
1659 }
1660
1661 // Tests unary predicate assertions that use a custom formatter.
TEST(Pred1Test,WithFormat)1662 TEST(Pred1Test, WithFormat) {
1663 // Success cases.
1664 EXPECT_PRED_FORMAT1(AssertIsEven, 2);
1665 ASSERT_PRED_FORMAT1(AssertIsEvenFunctor(), 4)
1666 << "This failure is UNEXPECTED!";
1667
1668 // Failure cases.
1669 const int n = 5;
1670 EXPECT_NONFATAL_FAILURE(EXPECT_PRED_FORMAT1(AssertIsEvenFunctor(), n),
1671 "n evaluates to 5, which is not even.");
1672 EXPECT_FATAL_FAILURE({ // NOLINT
1673 ASSERT_PRED_FORMAT1(AssertIsEven, 5) << "This failure is expected.";
1674 }, "This failure is expected.");
1675 }
1676
1677 // Tests that unary predicate assertions evaluates their arguments
1678 // exactly once.
TEST(Pred1Test,SingleEvaluationOnFailure)1679 TEST(Pred1Test, SingleEvaluationOnFailure) {
1680 // A success case.
1681 static int n = 0;
1682 EXPECT_PRED1(IsEven, n++);
1683 EXPECT_EQ(1, n) << "The argument is not evaluated exactly once.";
1684
1685 // A failure case.
1686 EXPECT_FATAL_FAILURE({ // NOLINT
1687 ASSERT_PRED_FORMAT1(AssertIsEvenFunctor(), n++)
1688 << "This failure is expected.";
1689 }, "This failure is expected.");
1690 EXPECT_EQ(2, n) << "The argument is not evaluated exactly once.";
1691 }
1692
1693
1694 // Tests predicate assertions whose arity is >= 2.
1695
1696 // Tests predicate assertions that don't use a custom formatter.
TEST(PredTest,WithoutFormat)1697 TEST(PredTest, WithoutFormat) {
1698 // Success cases.
1699 ASSERT_PRED2(SumIsEven2, 2, 4) << "This failure is UNEXPECTED!";
1700 EXPECT_PRED3(SumIsEven3Functor(), 4, 6, 8);
1701
1702 // Failure cases.
1703 const int n1 = 1;
1704 const int n2 = 2;
1705 EXPECT_NONFATAL_FAILURE({ // NOLINT
1706 EXPECT_PRED2(SumIsEven2, n1, n2) << "This failure is expected.";
1707 }, "This failure is expected.");
1708 EXPECT_FATAL_FAILURE({ // NOLINT
1709 ASSERT_PRED3(SumIsEven3Functor(), 1, 2, 4);
1710 }, "evaluates to false");
1711 }
1712
1713 // Tests predicate assertions that use a custom formatter.
TEST(PredTest,WithFormat)1714 TEST(PredTest, WithFormat) {
1715 // Success cases.
1716 ASSERT_PRED_FORMAT4(AssertSumIsEven4, 4, 6, 8, 10) <<
1717 "This failure is UNEXPECTED!";
1718 EXPECT_PRED_FORMAT5(AssertSumIsEven5Functor(), 2, 4, 6, 8, 10);
1719
1720 // Failure cases.
1721 const int n1 = 1;
1722 const int n2 = 2;
1723 const int n3 = 4;
1724 const int n4 = 6;
1725 EXPECT_NONFATAL_FAILURE({ // NOLINT
1726 EXPECT_PRED_FORMAT4(AssertSumIsEven4, n1, n2, n3, n4);
1727 }, "evaluates to 13, which is not even.");
1728 EXPECT_FATAL_FAILURE({ // NOLINT
1729 ASSERT_PRED_FORMAT5(AssertSumIsEven5Functor(), 1, 2, 4, 6, 8)
1730 << "This failure is expected.";
1731 }, "This failure is expected.");
1732 }
1733
1734 // Tests that predicate assertions evaluates their arguments
1735 // exactly once.
TEST(PredTest,SingleEvaluationOnFailure)1736 TEST(PredTest, SingleEvaluationOnFailure) {
1737 // A success case.
1738 int n1 = 0;
1739 int n2 = 0;
1740 EXPECT_PRED2(SumIsEven2, n1++, n2++);
1741 EXPECT_EQ(1, n1) << "Argument 1 is not evaluated exactly once.";
1742 EXPECT_EQ(1, n2) << "Argument 2 is not evaluated exactly once.";
1743
1744 // Another success case.
1745 n1 = n2 = 0;
1746 int n3 = 0;
1747 int n4 = 0;
1748 int n5 = 0;
1749 ASSERT_PRED_FORMAT5(AssertSumIsEven5Functor(),
1750 n1++, n2++, n3++, n4++, n5++)
1751 << "This failure is UNEXPECTED!";
1752 EXPECT_EQ(1, n1) << "Argument 1 is not evaluated exactly once.";
1753 EXPECT_EQ(1, n2) << "Argument 2 is not evaluated exactly once.";
1754 EXPECT_EQ(1, n3) << "Argument 3 is not evaluated exactly once.";
1755 EXPECT_EQ(1, n4) << "Argument 4 is not evaluated exactly once.";
1756 EXPECT_EQ(1, n5) << "Argument 5 is not evaluated exactly once.";
1757
1758 // A failure case.
1759 n1 = n2 = n3 = 0;
1760 EXPECT_NONFATAL_FAILURE({ // NOLINT
1761 EXPECT_PRED3(SumIsEven3Functor(), ++n1, n2++, n3++)
1762 << "This failure is expected.";
1763 }, "This failure is expected.");
1764 EXPECT_EQ(1, n1) << "Argument 1 is not evaluated exactly once.";
1765 EXPECT_EQ(1, n2) << "Argument 2 is not evaluated exactly once.";
1766 EXPECT_EQ(1, n3) << "Argument 3 is not evaluated exactly once.";
1767
1768 // Another failure case.
1769 n1 = n2 = n3 = n4 = 0;
1770 EXPECT_NONFATAL_FAILURE({ // NOLINT
1771 EXPECT_PRED_FORMAT4(AssertSumIsEven4, ++n1, n2++, n3++, n4++);
1772 }, "evaluates to 1, which is not even.");
1773 EXPECT_EQ(1, n1) << "Argument 1 is not evaluated exactly once.";
1774 EXPECT_EQ(1, n2) << "Argument 2 is not evaluated exactly once.";
1775 EXPECT_EQ(1, n3) << "Argument 3 is not evaluated exactly once.";
1776 EXPECT_EQ(1, n4) << "Argument 4 is not evaluated exactly once.";
1777 }
1778
1779
1780 // Some helper functions for testing using overloaded/template
1781 // functions with ASSERT_PREDn and EXPECT_PREDn.
1782
IsPositive(int n)1783 bool IsPositive(int n) {
1784 return n > 0;
1785 }
1786
IsPositive(double x)1787 bool IsPositive(double x) {
1788 return x > 0;
1789 }
1790
1791 template <typename T>
IsNegative(T x)1792 bool IsNegative(T x) {
1793 return x < 0;
1794 }
1795
1796 template <typename T1, typename T2>
GreaterThan(T1 x1,T2 x2)1797 bool GreaterThan(T1 x1, T2 x2) {
1798 return x1 > x2;
1799 }
1800
1801 // Tests that overloaded functions can be used in *_PRED* as long as
1802 // their types are explicitly specified.
TEST(PredicateAssertionTest,AcceptsOverloadedFunction)1803 TEST(PredicateAssertionTest, AcceptsOverloadedFunction) {
1804 EXPECT_PRED1(static_cast<bool (*)(int)>(IsPositive), 5); // NOLINT
1805 ASSERT_PRED1(static_cast<bool (*)(double)>(IsPositive), 6.0); // NOLINT
1806 }
1807
1808 // Tests that template functions can be used in *_PRED* as long as
1809 // their types are explicitly specified.
TEST(PredicateAssertionTest,AcceptsTemplateFunction)1810 TEST(PredicateAssertionTest, AcceptsTemplateFunction) {
1811 EXPECT_PRED1(IsNegative<int>, -5);
1812 // Makes sure that we can handle templates with more than one
1813 // parameter.
1814 ASSERT_PRED2((GreaterThan<int, int>), 5, 0);
1815 }
1816
1817
1818 // Some helper functions for testing using overloaded/template
1819 // functions with ASSERT_PRED_FORMATn and EXPECT_PRED_FORMATn.
1820
IsPositiveFormat(const char *,int n)1821 AssertionResult IsPositiveFormat(const char* /* expr */, int n) {
1822 return n > 0 ? AssertionSuccess() :
1823 AssertionFailure(Message() << "Failure");
1824 }
1825
IsPositiveFormat(const char *,double x)1826 AssertionResult IsPositiveFormat(const char* /* expr */, double x) {
1827 return x > 0 ? AssertionSuccess() :
1828 AssertionFailure(Message() << "Failure");
1829 }
1830
1831 template <typename T>
IsNegativeFormat(const char *,T x)1832 AssertionResult IsNegativeFormat(const char* /* expr */, T x) {
1833 return x < 0 ? AssertionSuccess() :
1834 AssertionFailure(Message() << "Failure");
1835 }
1836
1837 template <typename T1, typename T2>
EqualsFormat(const char *,const char *,const T1 & x1,const T2 & x2)1838 AssertionResult EqualsFormat(const char* /* expr1 */, const char* /* expr2 */,
1839 const T1& x1, const T2& x2) {
1840 return x1 == x2 ? AssertionSuccess() :
1841 AssertionFailure(Message() << "Failure");
1842 }
1843
1844 // Tests that overloaded functions can be used in *_PRED_FORMAT*
1845 // without explicitly specifying their types.
TEST(PredicateFormatAssertionTest,AcceptsOverloadedFunction)1846 TEST(PredicateFormatAssertionTest, AcceptsOverloadedFunction) {
1847 EXPECT_PRED_FORMAT1(IsPositiveFormat, 5);
1848 ASSERT_PRED_FORMAT1(IsPositiveFormat, 6.0);
1849 }
1850
1851 // Tests that template functions can be used in *_PRED_FORMAT* without
1852 // explicitly specifying their types.
TEST(PredicateFormatAssertionTest,AcceptsTemplateFunction)1853 TEST(PredicateFormatAssertionTest, AcceptsTemplateFunction) {
1854 EXPECT_PRED_FORMAT1(IsNegativeFormat, -5);
1855 ASSERT_PRED_FORMAT2(EqualsFormat, 3, 3);
1856 }
1857
1858
1859 // Tests string assertions.
1860
1861 // Tests ASSERT_STREQ with non-NULL arguments.
TEST(StringAssertionTest,ASSERT_STREQ)1862 TEST(StringAssertionTest, ASSERT_STREQ) {
1863 const char * const p1 = "good";
1864 ASSERT_STREQ(p1, p1);
1865
1866 // Let p2 have the same content as p1, but be at a different address.
1867 const char p2[] = "good";
1868 ASSERT_STREQ(p1, p2);
1869
1870 EXPECT_FATAL_FAILURE(ASSERT_STREQ("bad", "good"),
1871 "Expected: \"bad\"");
1872 }
1873
1874 // Tests ASSERT_STREQ with NULL arguments.
TEST(StringAssertionTest,ASSERT_STREQ_Null)1875 TEST(StringAssertionTest, ASSERT_STREQ_Null) {
1876 ASSERT_STREQ(static_cast<const char *>(NULL), NULL);
1877 EXPECT_FATAL_FAILURE(ASSERT_STREQ(NULL, "non-null"),
1878 "non-null");
1879 }
1880
1881 // Tests ASSERT_STREQ with NULL arguments.
TEST(StringAssertionTest,ASSERT_STREQ_Null2)1882 TEST(StringAssertionTest, ASSERT_STREQ_Null2) {
1883 EXPECT_FATAL_FAILURE(ASSERT_STREQ("non-null", NULL),
1884 "non-null");
1885 }
1886
1887 // Tests ASSERT_STRNE.
TEST(StringAssertionTest,ASSERT_STRNE)1888 TEST(StringAssertionTest, ASSERT_STRNE) {
1889 ASSERT_STRNE("hi", "Hi");
1890 ASSERT_STRNE("Hi", NULL);
1891 ASSERT_STRNE(NULL, "Hi");
1892 ASSERT_STRNE("", NULL);
1893 ASSERT_STRNE(NULL, "");
1894 ASSERT_STRNE("", "Hi");
1895 ASSERT_STRNE("Hi", "");
1896 EXPECT_FATAL_FAILURE(ASSERT_STRNE("Hi", "Hi"),
1897 "\"Hi\" vs \"Hi\"");
1898 }
1899
1900 // Tests ASSERT_STRCASEEQ.
TEST(StringAssertionTest,ASSERT_STRCASEEQ)1901 TEST(StringAssertionTest, ASSERT_STRCASEEQ) {
1902 ASSERT_STRCASEEQ("hi", "Hi");
1903 ASSERT_STRCASEEQ(static_cast<const char *>(NULL), NULL);
1904
1905 ASSERT_STRCASEEQ("", "");
1906 EXPECT_FATAL_FAILURE(ASSERT_STRCASEEQ("Hi", "hi2"),
1907 "(ignoring case)");
1908 }
1909
1910 // Tests ASSERT_STRCASENE.
TEST(StringAssertionTest,ASSERT_STRCASENE)1911 TEST(StringAssertionTest, ASSERT_STRCASENE) {
1912 ASSERT_STRCASENE("hi1", "Hi2");
1913 ASSERT_STRCASENE("Hi", NULL);
1914 ASSERT_STRCASENE(NULL, "Hi");
1915 ASSERT_STRCASENE("", NULL);
1916 ASSERT_STRCASENE(NULL, "");
1917 ASSERT_STRCASENE("", "Hi");
1918 ASSERT_STRCASENE("Hi", "");
1919 EXPECT_FATAL_FAILURE(ASSERT_STRCASENE("Hi", "hi"),
1920 "(ignoring case)");
1921 }
1922
1923 // Tests *_STREQ on wide strings.
TEST(StringAssertionTest,STREQ_Wide)1924 TEST(StringAssertionTest, STREQ_Wide) {
1925 // NULL strings.
1926 ASSERT_STREQ(static_cast<const wchar_t *>(NULL), NULL);
1927
1928 // Empty strings.
1929 ASSERT_STREQ(L"", L"");
1930
1931 // Non-null vs NULL.
1932 EXPECT_NONFATAL_FAILURE(EXPECT_STREQ(L"non-null", NULL),
1933 "non-null");
1934
1935 // Equal strings.
1936 EXPECT_STREQ(L"Hi", L"Hi");
1937
1938 // Unequal strings.
1939 EXPECT_NONFATAL_FAILURE(EXPECT_STREQ(L"abc", L"Abc"),
1940 "Abc");
1941
1942 // Strings containing wide characters.
1943 EXPECT_NONFATAL_FAILURE(EXPECT_STREQ(L"abc\x8119", L"abc\x8120"),
1944 "abc");
1945 }
1946
1947 // Tests *_STRNE on wide strings.
TEST(StringAssertionTest,STRNE_Wide)1948 TEST(StringAssertionTest, STRNE_Wide) {
1949 // NULL strings.
1950 EXPECT_NONFATAL_FAILURE({ // NOLINT
1951 EXPECT_STRNE(static_cast<const wchar_t *>(NULL), NULL);
1952 }, "");
1953
1954 // Empty strings.
1955 EXPECT_NONFATAL_FAILURE(EXPECT_STRNE(L"", L""),
1956 "L\"\"");
1957
1958 // Non-null vs NULL.
1959 ASSERT_STRNE(L"non-null", NULL);
1960
1961 // Equal strings.
1962 EXPECT_NONFATAL_FAILURE(EXPECT_STRNE(L"Hi", L"Hi"),
1963 "L\"Hi\"");
1964
1965 // Unequal strings.
1966 EXPECT_STRNE(L"abc", L"Abc");
1967
1968 // Strings containing wide characters.
1969 EXPECT_NONFATAL_FAILURE(EXPECT_STRNE(L"abc\x8119", L"abc\x8119"),
1970 "abc");
1971 }
1972
1973 // Tests for ::testing::IsSubstring().
1974
1975 // Tests that IsSubstring() returns the correct result when the input
1976 // argument type is const char*.
TEST(IsSubstringTest,ReturnsCorrectResultForCString)1977 TEST(IsSubstringTest, ReturnsCorrectResultForCString) {
1978 EXPECT_FALSE(IsSubstring("", "", NULL, "a"));
1979 EXPECT_FALSE(IsSubstring("", "", "b", NULL));
1980 EXPECT_FALSE(IsSubstring("", "", "needle", "haystack"));
1981
1982 EXPECT_TRUE(IsSubstring("", "", static_cast<const char*>(NULL), NULL));
1983 EXPECT_TRUE(IsSubstring("", "", "needle", "two needles"));
1984 }
1985
1986 // Tests that IsSubstring() returns the correct result when the input
1987 // argument type is const wchar_t*.
TEST(IsSubstringTest,ReturnsCorrectResultForWideCString)1988 TEST(IsSubstringTest, ReturnsCorrectResultForWideCString) {
1989 EXPECT_FALSE(IsSubstring("", "", NULL, L"a"));
1990 EXPECT_FALSE(IsSubstring("", "", L"b", NULL));
1991 EXPECT_FALSE(IsSubstring("", "", L"needle", L"haystack"));
1992
1993 EXPECT_TRUE(IsSubstring("", "", static_cast<const wchar_t*>(NULL), NULL));
1994 EXPECT_TRUE(IsSubstring("", "", L"needle", L"two needles"));
1995 }
1996
1997 // Tests that IsSubstring() generates the correct message when the input
1998 // argument type is const char*.
TEST(IsSubstringTest,GeneratesCorrectMessageForCString)1999 TEST(IsSubstringTest, GeneratesCorrectMessageForCString) {
2000 EXPECT_STREQ("Value of: needle_expr\n"
2001 " Actual: \"needle\"\n"
2002 "Expected: a substring of haystack_expr\n"
2003 "Which is: \"haystack\"",
2004 IsSubstring("needle_expr", "haystack_expr",
2005 "needle", "haystack").failure_message());
2006 }
2007
2008 #if GTEST_HAS_STD_STRING
2009
2010 // Tests that IsSubstring returns the correct result when the input
2011 // argument type is ::std::string.
TEST(IsSubstringTest,ReturnsCorrectResultsForStdString)2012 TEST(IsSubstringTest, ReturnsCorrectResultsForStdString) {
2013 EXPECT_TRUE(IsSubstring("", "", std::string("hello"), "ahellob"));
2014 EXPECT_FALSE(IsSubstring("", "", "hello", std::string("world")));
2015 }
2016
2017 #endif // GTEST_HAS_STD_STRING
2018
2019 #if GTEST_HAS_STD_WSTRING
2020 // Tests that IsSubstring returns the correct result when the input
2021 // argument type is ::std::wstring.
TEST(IsSubstringTest,ReturnsCorrectResultForStdWstring)2022 TEST(IsSubstringTest, ReturnsCorrectResultForStdWstring) {
2023 EXPECT_TRUE(IsSubstring("", "", ::std::wstring(L"needle"), L"two needles"));
2024 EXPECT_FALSE(IsSubstring("", "", L"needle", ::std::wstring(L"haystack")));
2025 }
2026
2027 // Tests that IsSubstring() generates the correct message when the input
2028 // argument type is ::std::wstring.
TEST(IsSubstringTest,GeneratesCorrectMessageForWstring)2029 TEST(IsSubstringTest, GeneratesCorrectMessageForWstring) {
2030 EXPECT_STREQ("Value of: needle_expr\n"
2031 " Actual: L\"needle\"\n"
2032 "Expected: a substring of haystack_expr\n"
2033 "Which is: L\"haystack\"",
2034 IsSubstring(
2035 "needle_expr", "haystack_expr",
2036 ::std::wstring(L"needle"), L"haystack").failure_message());
2037 }
2038
2039 #endif // GTEST_HAS_STD_WSTRING
2040
2041 // Tests for ::testing::IsNotSubstring().
2042
2043 // Tests that IsNotSubstring() returns the correct result when the input
2044 // argument type is const char*.
TEST(IsNotSubstringTest,ReturnsCorrectResultForCString)2045 TEST(IsNotSubstringTest, ReturnsCorrectResultForCString) {
2046 EXPECT_TRUE(IsNotSubstring("", "", "needle", "haystack"));
2047 EXPECT_FALSE(IsNotSubstring("", "", "needle", "two needles"));
2048 }
2049
2050 // Tests that IsNotSubstring() returns the correct result when the input
2051 // argument type is const wchar_t*.
TEST(IsNotSubstringTest,ReturnsCorrectResultForWideCString)2052 TEST(IsNotSubstringTest, ReturnsCorrectResultForWideCString) {
2053 EXPECT_TRUE(IsNotSubstring("", "", L"needle", L"haystack"));
2054 EXPECT_FALSE(IsNotSubstring("", "", L"needle", L"two needles"));
2055 }
2056
2057 // Tests that IsNotSubstring() generates the correct message when the input
2058 // argument type is const wchar_t*.
TEST(IsNotSubstringTest,GeneratesCorrectMessageForWideCString)2059 TEST(IsNotSubstringTest, GeneratesCorrectMessageForWideCString) {
2060 EXPECT_STREQ("Value of: needle_expr\n"
2061 " Actual: L\"needle\"\n"
2062 "Expected: not a substring of haystack_expr\n"
2063 "Which is: L\"two needles\"",
2064 IsNotSubstring(
2065 "needle_expr", "haystack_expr",
2066 L"needle", L"two needles").failure_message());
2067 }
2068
2069 #if GTEST_HAS_STD_STRING
2070
2071 // Tests that IsNotSubstring returns the correct result when the input
2072 // argument type is ::std::string.
TEST(IsNotSubstringTest,ReturnsCorrectResultsForStdString)2073 TEST(IsNotSubstringTest, ReturnsCorrectResultsForStdString) {
2074 EXPECT_FALSE(IsNotSubstring("", "", std::string("hello"), "ahellob"));
2075 EXPECT_TRUE(IsNotSubstring("", "", "hello", std::string("world")));
2076 }
2077
2078 // Tests that IsNotSubstring() generates the correct message when the input
2079 // argument type is ::std::string.
TEST(IsNotSubstringTest,GeneratesCorrectMessageForStdString)2080 TEST(IsNotSubstringTest, GeneratesCorrectMessageForStdString) {
2081 EXPECT_STREQ("Value of: needle_expr\n"
2082 " Actual: \"needle\"\n"
2083 "Expected: not a substring of haystack_expr\n"
2084 "Which is: \"two needles\"",
2085 IsNotSubstring(
2086 "needle_expr", "haystack_expr",
2087 ::std::string("needle"), "two needles").failure_message());
2088 }
2089
2090 #endif // GTEST_HAS_STD_STRING
2091
2092 #if GTEST_HAS_STD_WSTRING
2093
2094 // Tests that IsNotSubstring returns the correct result when the input
2095 // argument type is ::std::wstring.
TEST(IsNotSubstringTest,ReturnsCorrectResultForStdWstring)2096 TEST(IsNotSubstringTest, ReturnsCorrectResultForStdWstring) {
2097 EXPECT_FALSE(
2098 IsNotSubstring("", "", ::std::wstring(L"needle"), L"two needles"));
2099 EXPECT_TRUE(IsNotSubstring("", "", L"needle", ::std::wstring(L"haystack")));
2100 }
2101
2102 #endif // GTEST_HAS_STD_WSTRING
2103
2104 // Tests floating-point assertions.
2105
2106 template <typename RawType>
2107 class FloatingPointTest : public Test {
2108 protected:
2109 typedef typename testing::internal::FloatingPoint<RawType> Floating;
2110 typedef typename Floating::Bits Bits;
2111
SetUp()2112 virtual void SetUp() {
2113 const size_t max_ulps = Floating::kMaxUlps;
2114
2115 // The bits that represent 0.0.
2116 const Bits zero_bits = Floating(0).bits();
2117
2118 // Makes some numbers close to 0.0.
2119 close_to_positive_zero_ = Floating::ReinterpretBits(zero_bits + max_ulps/2);
2120 close_to_negative_zero_ = -Floating::ReinterpretBits(
2121 zero_bits + max_ulps - max_ulps/2);
2122 further_from_negative_zero_ = -Floating::ReinterpretBits(
2123 zero_bits + max_ulps + 1 - max_ulps/2);
2124
2125 // The bits that represent 1.0.
2126 const Bits one_bits = Floating(1).bits();
2127
2128 // Makes some numbers close to 1.0.
2129 close_to_one_ = Floating::ReinterpretBits(one_bits + max_ulps);
2130 further_from_one_ = Floating::ReinterpretBits(one_bits + max_ulps + 1);
2131
2132 // +infinity.
2133 infinity_ = Floating::Infinity();
2134
2135 // The bits that represent +infinity.
2136 const Bits infinity_bits = Floating(infinity_).bits();
2137
2138 // Makes some numbers close to infinity.
2139 close_to_infinity_ = Floating::ReinterpretBits(infinity_bits - max_ulps);
2140 further_from_infinity_ = Floating::ReinterpretBits(
2141 infinity_bits - max_ulps - 1);
2142
2143 // Makes some NAN's.
2144 nan1_ = Floating::ReinterpretBits(Floating::kExponentBitMask | 1);
2145 nan2_ = Floating::ReinterpretBits(Floating::kExponentBitMask | 200);
2146 }
2147
TestSize()2148 void TestSize() {
2149 EXPECT_EQ(sizeof(RawType), sizeof(Bits));
2150 }
2151
2152 // Pre-calculated numbers to be used by the tests.
2153
2154 static RawType close_to_positive_zero_;
2155 static RawType close_to_negative_zero_;
2156 static RawType further_from_negative_zero_;
2157
2158 static RawType close_to_one_;
2159 static RawType further_from_one_;
2160
2161 static RawType infinity_;
2162 static RawType close_to_infinity_;
2163 static RawType further_from_infinity_;
2164
2165 static RawType nan1_;
2166 static RawType nan2_;
2167 };
2168
2169 template <typename RawType>
2170 RawType FloatingPointTest<RawType>::close_to_positive_zero_;
2171
2172 template <typename RawType>
2173 RawType FloatingPointTest<RawType>::close_to_negative_zero_;
2174
2175 template <typename RawType>
2176 RawType FloatingPointTest<RawType>::further_from_negative_zero_;
2177
2178 template <typename RawType>
2179 RawType FloatingPointTest<RawType>::close_to_one_;
2180
2181 template <typename RawType>
2182 RawType FloatingPointTest<RawType>::further_from_one_;
2183
2184 template <typename RawType>
2185 RawType FloatingPointTest<RawType>::infinity_;
2186
2187 template <typename RawType>
2188 RawType FloatingPointTest<RawType>::close_to_infinity_;
2189
2190 template <typename RawType>
2191 RawType FloatingPointTest<RawType>::further_from_infinity_;
2192
2193 template <typename RawType>
2194 RawType FloatingPointTest<RawType>::nan1_;
2195
2196 template <typename RawType>
2197 RawType FloatingPointTest<RawType>::nan2_;
2198
2199 // Instantiates FloatingPointTest for testing *_FLOAT_EQ.
2200 typedef FloatingPointTest<float> FloatTest;
2201
2202 // Tests that the size of Float::Bits matches the size of float.
TEST_F(FloatTest,Size)2203 TEST_F(FloatTest, Size) {
2204 TestSize();
2205 }
2206
2207 // Tests comparing with +0 and -0.
TEST_F(FloatTest,Zeros)2208 TEST_F(FloatTest, Zeros) {
2209 EXPECT_FLOAT_EQ(0.0, -0.0);
2210 EXPECT_NONFATAL_FAILURE(EXPECT_FLOAT_EQ(-0.0, 1.0),
2211 "1.0");
2212 EXPECT_FATAL_FAILURE(ASSERT_FLOAT_EQ(0.0, 1.5),
2213 "1.5");
2214 }
2215
2216 // Tests comparing numbers close to 0.
2217 //
2218 // This ensures that *_FLOAT_EQ handles the sign correctly and no
2219 // overflow occurs when comparing numbers whose absolute value is very
2220 // small.
TEST_F(FloatTest,AlmostZeros)2221 TEST_F(FloatTest, AlmostZeros) {
2222 EXPECT_FLOAT_EQ(0.0, close_to_positive_zero_);
2223 EXPECT_FLOAT_EQ(-0.0, close_to_negative_zero_);
2224 EXPECT_FLOAT_EQ(close_to_positive_zero_, close_to_negative_zero_);
2225
2226 EXPECT_FATAL_FAILURE({ // NOLINT
2227 ASSERT_FLOAT_EQ(close_to_positive_zero_, further_from_negative_zero_);
2228 }, "further_from_negative_zero_");
2229 }
2230
2231 // Tests comparing numbers close to each other.
TEST_F(FloatTest,SmallDiff)2232 TEST_F(FloatTest, SmallDiff) {
2233 EXPECT_FLOAT_EQ(1.0, close_to_one_);
2234 EXPECT_NONFATAL_FAILURE(EXPECT_FLOAT_EQ(1.0, further_from_one_),
2235 "further_from_one_");
2236 }
2237
2238 // Tests comparing numbers far apart.
TEST_F(FloatTest,LargeDiff)2239 TEST_F(FloatTest, LargeDiff) {
2240 EXPECT_NONFATAL_FAILURE(EXPECT_FLOAT_EQ(2.5, 3.0),
2241 "3.0");
2242 }
2243
2244 // Tests comparing with infinity.
2245 //
2246 // This ensures that no overflow occurs when comparing numbers whose
2247 // absolute value is very large.
TEST_F(FloatTest,Infinity)2248 TEST_F(FloatTest, Infinity) {
2249 EXPECT_FLOAT_EQ(infinity_, close_to_infinity_);
2250 EXPECT_FLOAT_EQ(-infinity_, -close_to_infinity_);
2251 #if !GTEST_OS_SYMBIAN
2252 // Nokia's STLport crashes if we try to output infinity or NaN.
2253 EXPECT_NONFATAL_FAILURE(EXPECT_FLOAT_EQ(infinity_, -infinity_),
2254 "-infinity_");
2255
2256 // This is interesting as the representations of infinity_ and nan1_
2257 // are only 1 DLP apart.
2258 EXPECT_NONFATAL_FAILURE(EXPECT_FLOAT_EQ(infinity_, nan1_),
2259 "nan1_");
2260 #endif // !GTEST_OS_SYMBIAN
2261 }
2262
2263 // Tests that comparing with NAN always returns false.
TEST_F(FloatTest,NaN)2264 TEST_F(FloatTest, NaN) {
2265 #if !GTEST_OS_SYMBIAN
2266 // Nokia's STLport crashes if we try to output infinity or NaN.
2267 EXPECT_NONFATAL_FAILURE(EXPECT_FLOAT_EQ(nan1_, nan1_),
2268 "nan1_");
2269 EXPECT_NONFATAL_FAILURE(EXPECT_FLOAT_EQ(nan1_, nan2_),
2270 "nan2_");
2271 EXPECT_NONFATAL_FAILURE(EXPECT_FLOAT_EQ(1.0, nan1_),
2272 "nan1_");
2273
2274 EXPECT_FATAL_FAILURE(ASSERT_FLOAT_EQ(nan1_, infinity_),
2275 "infinity_");
2276 #endif // !GTEST_OS_SYMBIAN
2277 }
2278
2279 // Tests that *_FLOAT_EQ are reflexive.
TEST_F(FloatTest,Reflexive)2280 TEST_F(FloatTest, Reflexive) {
2281 EXPECT_FLOAT_EQ(0.0, 0.0);
2282 EXPECT_FLOAT_EQ(1.0, 1.0);
2283 ASSERT_FLOAT_EQ(infinity_, infinity_);
2284 }
2285
2286 // Tests that *_FLOAT_EQ are commutative.
TEST_F(FloatTest,Commutative)2287 TEST_F(FloatTest, Commutative) {
2288 // We already tested EXPECT_FLOAT_EQ(1.0, close_to_one_).
2289 EXPECT_FLOAT_EQ(close_to_one_, 1.0);
2290
2291 // We already tested EXPECT_FLOAT_EQ(1.0, further_from_one_).
2292 EXPECT_NONFATAL_FAILURE(EXPECT_FLOAT_EQ(further_from_one_, 1.0),
2293 "1.0");
2294 }
2295
2296 // Tests EXPECT_NEAR.
TEST_F(FloatTest,EXPECT_NEAR)2297 TEST_F(FloatTest, EXPECT_NEAR) {
2298 EXPECT_NEAR(-1.0f, -1.1f, 0.2f);
2299 EXPECT_NEAR(2.0f, 3.0f, 1.0f);
2300 EXPECT_NONFATAL_FAILURE(EXPECT_NEAR(1.0f,1.2f, 0.1f), // NOLINT
2301 "The difference between 1.0f and 1.2f is 0.2, "
2302 "which exceeds 0.1f");
2303 // To work around a bug in gcc 2.95.0, there is intentionally no
2304 // space after the first comma in the previous line.
2305 }
2306
2307 // Tests ASSERT_NEAR.
TEST_F(FloatTest,ASSERT_NEAR)2308 TEST_F(FloatTest, ASSERT_NEAR) {
2309 ASSERT_NEAR(-1.0f, -1.1f, 0.2f);
2310 ASSERT_NEAR(2.0f, 3.0f, 1.0f);
2311 EXPECT_FATAL_FAILURE(ASSERT_NEAR(1.0f,1.2f, 0.1f), // NOLINT
2312 "The difference between 1.0f and 1.2f is 0.2, "
2313 "which exceeds 0.1f");
2314 // To work around a bug in gcc 2.95.0, there is intentionally no
2315 // space after the first comma in the previous line.
2316 }
2317
2318 // Tests the cases where FloatLE() should succeed.
TEST_F(FloatTest,FloatLESucceeds)2319 TEST_F(FloatTest, FloatLESucceeds) {
2320 EXPECT_PRED_FORMAT2(FloatLE, 1.0f, 2.0f); // When val1 < val2,
2321 ASSERT_PRED_FORMAT2(FloatLE, 1.0f, 1.0f); // val1 == val2,
2322
2323 // or when val1 is greater than, but almost equals to, val2.
2324 EXPECT_PRED_FORMAT2(FloatLE, close_to_positive_zero_, 0.0f);
2325 }
2326
2327 // Tests the cases where FloatLE() should fail.
TEST_F(FloatTest,FloatLEFails)2328 TEST_F(FloatTest, FloatLEFails) {
2329 // When val1 is greater than val2 by a large margin,
2330 EXPECT_NONFATAL_FAILURE(EXPECT_PRED_FORMAT2(FloatLE, 2.0f, 1.0f),
2331 "(2.0f) <= (1.0f)");
2332
2333 // or by a small yet non-negligible margin,
2334 EXPECT_NONFATAL_FAILURE({ // NOLINT
2335 EXPECT_PRED_FORMAT2(FloatLE, further_from_one_, 1.0f);
2336 }, "(further_from_one_) <= (1.0f)");
2337
2338 #if !GTEST_OS_SYMBIAN
2339 // Nokia's STLport crashes if we try to output infinity or NaN.
2340 // or when either val1 or val2 is NaN.
2341 EXPECT_NONFATAL_FAILURE({ // NOLINT
2342 EXPECT_PRED_FORMAT2(FloatLE, nan1_, infinity_);
2343 }, "(nan1_) <= (infinity_)");
2344 EXPECT_NONFATAL_FAILURE({ // NOLINT
2345 EXPECT_PRED_FORMAT2(FloatLE, -infinity_, nan1_);
2346 }, "(-infinity_) <= (nan1_)");
2347
2348 EXPECT_FATAL_FAILURE({ // NOLINT
2349 ASSERT_PRED_FORMAT2(FloatLE, nan1_, nan1_);
2350 }, "(nan1_) <= (nan1_)");
2351 #endif // !GTEST_OS_SYMBIAN
2352 }
2353
2354 // Instantiates FloatingPointTest for testing *_DOUBLE_EQ.
2355 typedef FloatingPointTest<double> DoubleTest;
2356
2357 // Tests that the size of Double::Bits matches the size of double.
TEST_F(DoubleTest,Size)2358 TEST_F(DoubleTest, Size) {
2359 TestSize();
2360 }
2361
2362 // Tests comparing with +0 and -0.
TEST_F(DoubleTest,Zeros)2363 TEST_F(DoubleTest, Zeros) {
2364 EXPECT_DOUBLE_EQ(0.0, -0.0);
2365 EXPECT_NONFATAL_FAILURE(EXPECT_DOUBLE_EQ(-0.0, 1.0),
2366 "1.0");
2367 EXPECT_FATAL_FAILURE(ASSERT_DOUBLE_EQ(0.0, 1.0),
2368 "1.0");
2369 }
2370
2371 // Tests comparing numbers close to 0.
2372 //
2373 // This ensures that *_DOUBLE_EQ handles the sign correctly and no
2374 // overflow occurs when comparing numbers whose absolute value is very
2375 // small.
TEST_F(DoubleTest,AlmostZeros)2376 TEST_F(DoubleTest, AlmostZeros) {
2377 EXPECT_DOUBLE_EQ(0.0, close_to_positive_zero_);
2378 EXPECT_DOUBLE_EQ(-0.0, close_to_negative_zero_);
2379 EXPECT_DOUBLE_EQ(close_to_positive_zero_, close_to_negative_zero_);
2380
2381 EXPECT_FATAL_FAILURE({ // NOLINT
2382 ASSERT_DOUBLE_EQ(close_to_positive_zero_, further_from_negative_zero_);
2383 }, "further_from_negative_zero_");
2384 }
2385
2386 // Tests comparing numbers close to each other.
TEST_F(DoubleTest,SmallDiff)2387 TEST_F(DoubleTest, SmallDiff) {
2388 EXPECT_DOUBLE_EQ(1.0, close_to_one_);
2389 EXPECT_NONFATAL_FAILURE(EXPECT_DOUBLE_EQ(1.0, further_from_one_),
2390 "further_from_one_");
2391 }
2392
2393 // Tests comparing numbers far apart.
TEST_F(DoubleTest,LargeDiff)2394 TEST_F(DoubleTest, LargeDiff) {
2395 EXPECT_NONFATAL_FAILURE(EXPECT_DOUBLE_EQ(2.0, 3.0),
2396 "3.0");
2397 }
2398
2399 // Tests comparing with infinity.
2400 //
2401 // This ensures that no overflow occurs when comparing numbers whose
2402 // absolute value is very large.
TEST_F(DoubleTest,Infinity)2403 TEST_F(DoubleTest, Infinity) {
2404 EXPECT_DOUBLE_EQ(infinity_, close_to_infinity_);
2405 EXPECT_DOUBLE_EQ(-infinity_, -close_to_infinity_);
2406 #if !GTEST_OS_SYMBIAN
2407 // Nokia's STLport crashes if we try to output infinity or NaN.
2408 EXPECT_NONFATAL_FAILURE(EXPECT_DOUBLE_EQ(infinity_, -infinity_),
2409 "-infinity_");
2410
2411 // This is interesting as the representations of infinity_ and nan1_
2412 // are only 1 DLP apart.
2413 EXPECT_NONFATAL_FAILURE(EXPECT_DOUBLE_EQ(infinity_, nan1_),
2414 "nan1_");
2415 #endif // !GTEST_OS_SYMBIAN
2416 }
2417
2418 // Tests that comparing with NAN always returns false.
TEST_F(DoubleTest,NaN)2419 TEST_F(DoubleTest, NaN) {
2420 #if !GTEST_OS_SYMBIAN
2421 // Nokia's STLport crashes if we try to output infinity or NaN.
2422 EXPECT_NONFATAL_FAILURE(EXPECT_DOUBLE_EQ(nan1_, nan1_),
2423 "nan1_");
2424 EXPECT_NONFATAL_FAILURE(EXPECT_DOUBLE_EQ(nan1_, nan2_), "nan2_");
2425 EXPECT_NONFATAL_FAILURE(EXPECT_DOUBLE_EQ(1.0, nan1_), "nan1_");
2426 EXPECT_FATAL_FAILURE(ASSERT_DOUBLE_EQ(nan1_, infinity_), "infinity_");
2427 #endif // !GTEST_OS_SYMBIAN
2428 }
2429
2430 // Tests that *_DOUBLE_EQ are reflexive.
TEST_F(DoubleTest,Reflexive)2431 TEST_F(DoubleTest, Reflexive) {
2432 EXPECT_DOUBLE_EQ(0.0, 0.0);
2433 EXPECT_DOUBLE_EQ(1.0, 1.0);
2434 #if !GTEST_OS_SYMBIAN
2435 // Nokia's STLport crashes if we try to output infinity or NaN.
2436 ASSERT_DOUBLE_EQ(infinity_, infinity_);
2437 #endif // !GTEST_OS_SYMBIAN
2438 }
2439
2440 // Tests that *_DOUBLE_EQ are commutative.
TEST_F(DoubleTest,Commutative)2441 TEST_F(DoubleTest, Commutative) {
2442 // We already tested EXPECT_DOUBLE_EQ(1.0, close_to_one_).
2443 EXPECT_DOUBLE_EQ(close_to_one_, 1.0);
2444
2445 // We already tested EXPECT_DOUBLE_EQ(1.0, further_from_one_).
2446 EXPECT_NONFATAL_FAILURE(EXPECT_DOUBLE_EQ(further_from_one_, 1.0), "1.0");
2447 }
2448
2449 // Tests EXPECT_NEAR.
TEST_F(DoubleTest,EXPECT_NEAR)2450 TEST_F(DoubleTest, EXPECT_NEAR) {
2451 EXPECT_NEAR(-1.0, -1.1, 0.2);
2452 EXPECT_NEAR(2.0, 3.0, 1.0);
2453 EXPECT_NONFATAL_FAILURE(EXPECT_NEAR(1.0, 1.2, 0.1), // NOLINT
2454 "The difference between 1.0 and 1.2 is 0.2, "
2455 "which exceeds 0.1");
2456 // To work around a bug in gcc 2.95.0, there is intentionally no
2457 // space after the first comma in the previous statement.
2458 }
2459
2460 // Tests ASSERT_NEAR.
TEST_F(DoubleTest,ASSERT_NEAR)2461 TEST_F(DoubleTest, ASSERT_NEAR) {
2462 ASSERT_NEAR(-1.0, -1.1, 0.2);
2463 ASSERT_NEAR(2.0, 3.0, 1.0);
2464 EXPECT_FATAL_FAILURE(ASSERT_NEAR(1.0, 1.2, 0.1), // NOLINT
2465 "The difference between 1.0 and 1.2 is 0.2, "
2466 "which exceeds 0.1");
2467 // To work around a bug in gcc 2.95.0, there is intentionally no
2468 // space after the first comma in the previous statement.
2469 }
2470
2471 // Tests the cases where DoubleLE() should succeed.
TEST_F(DoubleTest,DoubleLESucceeds)2472 TEST_F(DoubleTest, DoubleLESucceeds) {
2473 EXPECT_PRED_FORMAT2(DoubleLE, 1.0, 2.0); // When val1 < val2,
2474 ASSERT_PRED_FORMAT2(DoubleLE, 1.0, 1.0); // val1 == val2,
2475
2476 // or when val1 is greater than, but almost equals to, val2.
2477 EXPECT_PRED_FORMAT2(DoubleLE, close_to_positive_zero_, 0.0);
2478 }
2479
2480 // Tests the cases where DoubleLE() should fail.
TEST_F(DoubleTest,DoubleLEFails)2481 TEST_F(DoubleTest, DoubleLEFails) {
2482 // When val1 is greater than val2 by a large margin,
2483 EXPECT_NONFATAL_FAILURE(EXPECT_PRED_FORMAT2(DoubleLE, 2.0, 1.0),
2484 "(2.0) <= (1.0)");
2485
2486 // or by a small yet non-negligible margin,
2487 EXPECT_NONFATAL_FAILURE({ // NOLINT
2488 EXPECT_PRED_FORMAT2(DoubleLE, further_from_one_, 1.0);
2489 }, "(further_from_one_) <= (1.0)");
2490
2491 #if !GTEST_OS_SYMBIAN
2492 // Nokia's STLport crashes if we try to output infinity or NaN.
2493 // or when either val1 or val2 is NaN.
2494 EXPECT_NONFATAL_FAILURE({ // NOLINT
2495 EXPECT_PRED_FORMAT2(DoubleLE, nan1_, infinity_);
2496 }, "(nan1_) <= (infinity_)");
2497 EXPECT_NONFATAL_FAILURE({ // NOLINT
2498 EXPECT_PRED_FORMAT2(DoubleLE, -infinity_, nan1_);
2499 }, " (-infinity_) <= (nan1_)");
2500 EXPECT_FATAL_FAILURE({ // NOLINT
2501 ASSERT_PRED_FORMAT2(DoubleLE, nan1_, nan1_);
2502 }, "(nan1_) <= (nan1_)");
2503 #endif // !GTEST_OS_SYMBIAN
2504 }
2505
2506
2507 // Verifies that a test or test case whose name starts with DISABLED_ is
2508 // not run.
2509
2510 // A test whose name starts with DISABLED_.
2511 // Should not run.
TEST(DisabledTest,DISABLED_TestShouldNotRun)2512 TEST(DisabledTest, DISABLED_TestShouldNotRun) {
2513 FAIL() << "Unexpected failure: Disabled test should not be run.";
2514 }
2515
2516 // A test whose name does not start with DISABLED_.
2517 // Should run.
TEST(DisabledTest,NotDISABLED_TestShouldRun)2518 TEST(DisabledTest, NotDISABLED_TestShouldRun) {
2519 EXPECT_EQ(1, 1);
2520 }
2521
2522 // A test case whose name starts with DISABLED_.
2523 // Should not run.
TEST(DISABLED_TestCase,TestShouldNotRun)2524 TEST(DISABLED_TestCase, TestShouldNotRun) {
2525 FAIL() << "Unexpected failure: Test in disabled test case should not be run.";
2526 }
2527
2528 // A test case and test whose names start with DISABLED_.
2529 // Should not run.
TEST(DISABLED_TestCase,DISABLED_TestShouldNotRun)2530 TEST(DISABLED_TestCase, DISABLED_TestShouldNotRun) {
2531 FAIL() << "Unexpected failure: Test in disabled test case should not be run.";
2532 }
2533
2534 // Check that when all tests in a test case are disabled, SetupTestCase() and
2535 // TearDownTestCase() are not called.
2536 class DisabledTestsTest : public Test {
2537 protected:
SetUpTestCase()2538 static void SetUpTestCase() {
2539 FAIL() << "Unexpected failure: All tests disabled in test case. "
2540 "SetupTestCase() should not be called.";
2541 }
2542
TearDownTestCase()2543 static void TearDownTestCase() {
2544 FAIL() << "Unexpected failure: All tests disabled in test case. "
2545 "TearDownTestCase() should not be called.";
2546 }
2547 };
2548
TEST_F(DisabledTestsTest,DISABLED_TestShouldNotRun_1)2549 TEST_F(DisabledTestsTest, DISABLED_TestShouldNotRun_1) {
2550 FAIL() << "Unexpected failure: Disabled test should not be run.";
2551 }
2552
TEST_F(DisabledTestsTest,DISABLED_TestShouldNotRun_2)2553 TEST_F(DisabledTestsTest, DISABLED_TestShouldNotRun_2) {
2554 FAIL() << "Unexpected failure: Disabled test should not be run.";
2555 }
2556
2557 // Tests that disabled typed tests aren't run.
2558
2559 #if GTEST_HAS_TYPED_TEST
2560
2561 template <typename T>
2562 class TypedTest : public Test {
2563 };
2564
2565 typedef testing::Types<int, double> NumericTypes;
2566 TYPED_TEST_CASE(TypedTest, NumericTypes);
2567
TYPED_TEST(TypedTest,DISABLED_ShouldNotRun)2568 TYPED_TEST(TypedTest, DISABLED_ShouldNotRun) {
2569 FAIL() << "Unexpected failure: Disabled typed test should not run.";
2570 }
2571
2572 template <typename T>
2573 class DISABLED_TypedTest : public Test {
2574 };
2575
2576 TYPED_TEST_CASE(DISABLED_TypedTest, NumericTypes);
2577
TYPED_TEST(DISABLED_TypedTest,ShouldNotRun)2578 TYPED_TEST(DISABLED_TypedTest, ShouldNotRun) {
2579 FAIL() << "Unexpected failure: Disabled typed test should not run.";
2580 }
2581
2582 #endif // GTEST_HAS_TYPED_TEST
2583
2584 // Tests that disabled type-parameterized tests aren't run.
2585
2586 #if GTEST_HAS_TYPED_TEST_P
2587
2588 template <typename T>
2589 class TypedTestP : public Test {
2590 };
2591
2592 TYPED_TEST_CASE_P(TypedTestP);
2593
TYPED_TEST_P(TypedTestP,DISABLED_ShouldNotRun)2594 TYPED_TEST_P(TypedTestP, DISABLED_ShouldNotRun) {
2595 FAIL() << "Unexpected failure: "
2596 << "Disabled type-parameterized test should not run.";
2597 }
2598
2599 REGISTER_TYPED_TEST_CASE_P(TypedTestP, DISABLED_ShouldNotRun);
2600
2601 INSTANTIATE_TYPED_TEST_CASE_P(My, TypedTestP, NumericTypes);
2602
2603 template <typename T>
2604 class DISABLED_TypedTestP : public Test {
2605 };
2606
2607 TYPED_TEST_CASE_P(DISABLED_TypedTestP);
2608
TYPED_TEST_P(DISABLED_TypedTestP,ShouldNotRun)2609 TYPED_TEST_P(DISABLED_TypedTestP, ShouldNotRun) {
2610 FAIL() << "Unexpected failure: "
2611 << "Disabled type-parameterized test should not run.";
2612 }
2613
2614 REGISTER_TYPED_TEST_CASE_P(DISABLED_TypedTestP, ShouldNotRun);
2615
2616 INSTANTIATE_TYPED_TEST_CASE_P(My, DISABLED_TypedTestP, NumericTypes);
2617
2618 #endif // GTEST_HAS_TYPED_TEST_P
2619
2620 // Tests that assertion macros evaluate their arguments exactly once.
2621
2622 class SingleEvaluationTest : public Test {
2623 protected:
SingleEvaluationTest()2624 SingleEvaluationTest() {
2625 p1_ = s1_;
2626 p2_ = s2_;
2627 a_ = 0;
2628 b_ = 0;
2629 }
2630
2631 // This helper function is needed by the FailedASSERT_STREQ test
2632 // below.
CompareAndIncrementCharPtrs()2633 static void CompareAndIncrementCharPtrs() {
2634 ASSERT_STREQ(p1_++, p2_++);
2635 }
2636
2637 // This helper function is needed by the FailedASSERT_NE test below.
CompareAndIncrementInts()2638 static void CompareAndIncrementInts() {
2639 ASSERT_NE(a_++, b_++);
2640 }
2641
2642 static const char* const s1_;
2643 static const char* const s2_;
2644 static const char* p1_;
2645 static const char* p2_;
2646
2647 static int a_;
2648 static int b_;
2649 };
2650
2651 const char* const SingleEvaluationTest::s1_ = "01234";
2652 const char* const SingleEvaluationTest::s2_ = "abcde";
2653 const char* SingleEvaluationTest::p1_;
2654 const char* SingleEvaluationTest::p2_;
2655 int SingleEvaluationTest::a_;
2656 int SingleEvaluationTest::b_;
2657
2658 // Tests that when ASSERT_STREQ fails, it evaluates its arguments
2659 // exactly once.
TEST_F(SingleEvaluationTest,FailedASSERT_STREQ)2660 TEST_F(SingleEvaluationTest, FailedASSERT_STREQ) {
2661 EXPECT_FATAL_FAILURE(CompareAndIncrementCharPtrs(),
2662 "p2_++");
2663 EXPECT_EQ(s1_ + 1, p1_);
2664 EXPECT_EQ(s2_ + 1, p2_);
2665 }
2666
2667 // Tests that string assertion arguments are evaluated exactly once.
TEST_F(SingleEvaluationTest,ASSERT_STR)2668 TEST_F(SingleEvaluationTest, ASSERT_STR) {
2669 // successful EXPECT_STRNE
2670 EXPECT_STRNE(p1_++, p2_++);
2671 EXPECT_EQ(s1_ + 1, p1_);
2672 EXPECT_EQ(s2_ + 1, p2_);
2673
2674 // failed EXPECT_STRCASEEQ
2675 EXPECT_NONFATAL_FAILURE(EXPECT_STRCASEEQ(p1_++, p2_++),
2676 "ignoring case");
2677 EXPECT_EQ(s1_ + 2, p1_);
2678 EXPECT_EQ(s2_ + 2, p2_);
2679 }
2680
2681 // Tests that when ASSERT_NE fails, it evaluates its arguments exactly
2682 // once.
TEST_F(SingleEvaluationTest,FailedASSERT_NE)2683 TEST_F(SingleEvaluationTest, FailedASSERT_NE) {
2684 EXPECT_FATAL_FAILURE(CompareAndIncrementInts(), "(a_++) != (b_++)");
2685 EXPECT_EQ(1, a_);
2686 EXPECT_EQ(1, b_);
2687 }
2688
2689 // Tests that assertion arguments are evaluated exactly once.
TEST_F(SingleEvaluationTest,OtherCases)2690 TEST_F(SingleEvaluationTest, OtherCases) {
2691 // successful EXPECT_TRUE
2692 EXPECT_TRUE(0 == a_++); // NOLINT
2693 EXPECT_EQ(1, a_);
2694
2695 // failed EXPECT_TRUE
2696 EXPECT_NONFATAL_FAILURE(EXPECT_TRUE(-1 == a_++), "-1 == a_++");
2697 EXPECT_EQ(2, a_);
2698
2699 // successful EXPECT_GT
2700 EXPECT_GT(a_++, b_++);
2701 EXPECT_EQ(3, a_);
2702 EXPECT_EQ(1, b_);
2703
2704 // failed EXPECT_LT
2705 EXPECT_NONFATAL_FAILURE(EXPECT_LT(a_++, b_++), "(a_++) < (b_++)");
2706 EXPECT_EQ(4, a_);
2707 EXPECT_EQ(2, b_);
2708
2709 // successful ASSERT_TRUE
2710 ASSERT_TRUE(0 < a_++); // NOLINT
2711 EXPECT_EQ(5, a_);
2712
2713 // successful ASSERT_GT
2714 ASSERT_GT(a_++, b_++);
2715 EXPECT_EQ(6, a_);
2716 EXPECT_EQ(3, b_);
2717 }
2718
2719 #if GTEST_HAS_EXCEPTIONS
2720
ThrowAnInteger()2721 void ThrowAnInteger() {
2722 throw 1;
2723 }
2724
2725 // Tests that assertion arguments are evaluated exactly once.
TEST_F(SingleEvaluationTest,ExceptionTests)2726 TEST_F(SingleEvaluationTest, ExceptionTests) {
2727 // successful EXPECT_THROW
2728 EXPECT_THROW({ // NOLINT
2729 a_++;
2730 ThrowAnInteger();
2731 }, int);
2732 EXPECT_EQ(1, a_);
2733
2734 // failed EXPECT_THROW, throws different
2735 EXPECT_NONFATAL_FAILURE(EXPECT_THROW({ // NOLINT
2736 a_++;
2737 ThrowAnInteger();
2738 }, bool), "throws a different type");
2739 EXPECT_EQ(2, a_);
2740
2741 // failed EXPECT_THROW, throws nothing
2742 EXPECT_NONFATAL_FAILURE(EXPECT_THROW(a_++, bool), "throws nothing");
2743 EXPECT_EQ(3, a_);
2744
2745 // successful EXPECT_NO_THROW
2746 EXPECT_NO_THROW(a_++);
2747 EXPECT_EQ(4, a_);
2748
2749 // failed EXPECT_NO_THROW
2750 EXPECT_NONFATAL_FAILURE(EXPECT_NO_THROW({ // NOLINT
2751 a_++;
2752 ThrowAnInteger();
2753 }), "it throws");
2754 EXPECT_EQ(5, a_);
2755
2756 // successful EXPECT_ANY_THROW
2757 EXPECT_ANY_THROW({ // NOLINT
2758 a_++;
2759 ThrowAnInteger();
2760 });
2761 EXPECT_EQ(6, a_);
2762
2763 // failed EXPECT_ANY_THROW
2764 EXPECT_NONFATAL_FAILURE(EXPECT_ANY_THROW(a_++), "it doesn't");
2765 EXPECT_EQ(7, a_);
2766 }
2767
2768 #endif // GTEST_HAS_EXCEPTIONS
2769
2770 // Tests {ASSERT|EXPECT}_NO_FATAL_FAILURE.
2771 class NoFatalFailureTest : public Test {
2772 protected:
Succeeds()2773 void Succeeds() {}
FailsNonFatal()2774 void FailsNonFatal() {
2775 ADD_FAILURE() << "some non-fatal failure";
2776 }
Fails()2777 void Fails() {
2778 FAIL() << "some fatal failure";
2779 }
2780
DoAssertNoFatalFailureOnFails()2781 void DoAssertNoFatalFailureOnFails() {
2782 ASSERT_NO_FATAL_FAILURE(Fails());
2783 ADD_FAILURE() << "shold not reach here.";
2784 }
2785
DoExpectNoFatalFailureOnFails()2786 void DoExpectNoFatalFailureOnFails() {
2787 EXPECT_NO_FATAL_FAILURE(Fails());
2788 ADD_FAILURE() << "other failure";
2789 }
2790 };
2791
TEST_F(NoFatalFailureTest,NoFailure)2792 TEST_F(NoFatalFailureTest, NoFailure) {
2793 EXPECT_NO_FATAL_FAILURE(Succeeds());
2794 ASSERT_NO_FATAL_FAILURE(Succeeds());
2795 }
2796
TEST_F(NoFatalFailureTest,NonFatalIsNoFailure)2797 TEST_F(NoFatalFailureTest, NonFatalIsNoFailure) {
2798 EXPECT_NONFATAL_FAILURE(
2799 EXPECT_NO_FATAL_FAILURE(FailsNonFatal()),
2800 "some non-fatal failure");
2801 EXPECT_NONFATAL_FAILURE(
2802 ASSERT_NO_FATAL_FAILURE(FailsNonFatal()),
2803 "some non-fatal failure");
2804 }
2805
TEST_F(NoFatalFailureTest,AssertNoFatalFailureOnFatalFailure)2806 TEST_F(NoFatalFailureTest, AssertNoFatalFailureOnFatalFailure) {
2807 TestPartResultArray gtest_failures;
2808 {
2809 ScopedFakeTestPartResultReporter gtest_reporter(>est_failures);
2810 DoAssertNoFatalFailureOnFails();
2811 }
2812 ASSERT_EQ(2, gtest_failures.size());
2813 EXPECT_EQ(testing::TPRT_FATAL_FAILURE,
2814 gtest_failures.GetTestPartResult(0).type());
2815 EXPECT_EQ(testing::TPRT_FATAL_FAILURE,
2816 gtest_failures.GetTestPartResult(1).type());
2817 EXPECT_PRED_FORMAT2(testing::IsSubstring, "some fatal failure",
2818 gtest_failures.GetTestPartResult(0).message());
2819 EXPECT_PRED_FORMAT2(testing::IsSubstring, "it does",
2820 gtest_failures.GetTestPartResult(1).message());
2821 }
2822
TEST_F(NoFatalFailureTest,ExpectNoFatalFailureOnFatalFailure)2823 TEST_F(NoFatalFailureTest, ExpectNoFatalFailureOnFatalFailure) {
2824 TestPartResultArray gtest_failures;
2825 {
2826 ScopedFakeTestPartResultReporter gtest_reporter(>est_failures);
2827 DoExpectNoFatalFailureOnFails();
2828 }
2829 ASSERT_EQ(3, gtest_failures.size());
2830 EXPECT_EQ(testing::TPRT_FATAL_FAILURE,
2831 gtest_failures.GetTestPartResult(0).type());
2832 EXPECT_EQ(testing::TPRT_NONFATAL_FAILURE,
2833 gtest_failures.GetTestPartResult(1).type());
2834 EXPECT_EQ(testing::TPRT_NONFATAL_FAILURE,
2835 gtest_failures.GetTestPartResult(2).type());
2836 EXPECT_PRED_FORMAT2(testing::IsSubstring, "some fatal failure",
2837 gtest_failures.GetTestPartResult(0).message());
2838 EXPECT_PRED_FORMAT2(testing::IsSubstring, "it does",
2839 gtest_failures.GetTestPartResult(1).message());
2840 EXPECT_PRED_FORMAT2(testing::IsSubstring, "other failure",
2841 gtest_failures.GetTestPartResult(2).message());
2842 }
2843
TEST_F(NoFatalFailureTest,MessageIsStreamable)2844 TEST_F(NoFatalFailureTest, MessageIsStreamable) {
2845 TestPartResultArray gtest_failures;
2846 {
2847 ScopedFakeTestPartResultReporter gtest_reporter(>est_failures);
2848 EXPECT_NO_FATAL_FAILURE(FAIL() << "foo") << "my message";
2849 }
2850 ASSERT_EQ(2, gtest_failures.size());
2851 EXPECT_EQ(testing::TPRT_NONFATAL_FAILURE,
2852 gtest_failures.GetTestPartResult(0).type());
2853 EXPECT_EQ(testing::TPRT_NONFATAL_FAILURE,
2854 gtest_failures.GetTestPartResult(1).type());
2855 EXPECT_PRED_FORMAT2(testing::IsSubstring, "foo",
2856 gtest_failures.GetTestPartResult(0).message());
2857 EXPECT_PRED_FORMAT2(testing::IsSubstring, "my message",
2858 gtest_failures.GetTestPartResult(1).message());
2859 }
2860
2861 // Tests non-string assertions.
2862
2863 // Tests EqFailure(), used for implementing *EQ* assertions.
TEST(AssertionTest,EqFailure)2864 TEST(AssertionTest, EqFailure) {
2865 const String foo_val("5"), bar_val("6");
2866 const String msg1(
2867 EqFailure("foo", "bar", foo_val, bar_val, false)
2868 .failure_message());
2869 EXPECT_STREQ(
2870 "Value of: bar\n"
2871 " Actual: 6\n"
2872 "Expected: foo\n"
2873 "Which is: 5",
2874 msg1.c_str());
2875
2876 const String msg2(
2877 EqFailure("foo", "6", foo_val, bar_val, false)
2878 .failure_message());
2879 EXPECT_STREQ(
2880 "Value of: 6\n"
2881 "Expected: foo\n"
2882 "Which is: 5",
2883 msg2.c_str());
2884
2885 const String msg3(
2886 EqFailure("5", "bar", foo_val, bar_val, false)
2887 .failure_message());
2888 EXPECT_STREQ(
2889 "Value of: bar\n"
2890 " Actual: 6\n"
2891 "Expected: 5",
2892 msg3.c_str());
2893
2894 const String msg4(
2895 EqFailure("5", "6", foo_val, bar_val, false).failure_message());
2896 EXPECT_STREQ(
2897 "Value of: 6\n"
2898 "Expected: 5",
2899 msg4.c_str());
2900
2901 const String msg5(
2902 EqFailure("foo", "bar",
2903 String("\"x\""), String("\"y\""),
2904 true).failure_message());
2905 EXPECT_STREQ(
2906 "Value of: bar\n"
2907 " Actual: \"y\"\n"
2908 "Expected: foo (ignoring case)\n"
2909 "Which is: \"x\"",
2910 msg5.c_str());
2911 }
2912
2913 // Tests AppendUserMessage(), used for implementing the *EQ* macros.
TEST(AssertionTest,AppendUserMessage)2914 TEST(AssertionTest, AppendUserMessage) {
2915 const String foo("foo");
2916
2917 Message msg;
2918 EXPECT_STREQ("foo",
2919 AppendUserMessage(foo, msg).c_str());
2920
2921 msg << "bar";
2922 EXPECT_STREQ("foo\nbar",
2923 AppendUserMessage(foo, msg).c_str());
2924 }
2925
2926 // Tests ASSERT_TRUE.
TEST(AssertionTest,ASSERT_TRUE)2927 TEST(AssertionTest, ASSERT_TRUE) {
2928 ASSERT_TRUE(2 > 1); // NOLINT
2929 EXPECT_FATAL_FAILURE(ASSERT_TRUE(2 < 1),
2930 "2 < 1");
2931 }
2932
2933 // Tests ASSERT_FALSE.
TEST(AssertionTest,ASSERT_FALSE)2934 TEST(AssertionTest, ASSERT_FALSE) {
2935 ASSERT_FALSE(2 < 1); // NOLINT
2936 EXPECT_FATAL_FAILURE(ASSERT_FALSE(2 > 1),
2937 "Value of: 2 > 1\n"
2938 " Actual: true\n"
2939 "Expected: false");
2940 }
2941
2942 // Tests using ASSERT_EQ on double values. The purpose is to make
2943 // sure that the specialization we did for integer and anonymous enums
2944 // isn't used for double arguments.
TEST(ExpectTest,ASSERT_EQ_Double)2945 TEST(ExpectTest, ASSERT_EQ_Double) {
2946 // A success.
2947 ASSERT_EQ(5.6, 5.6);
2948
2949 // A failure.
2950 EXPECT_FATAL_FAILURE(ASSERT_EQ(5.1, 5.2),
2951 "5.1");
2952 }
2953
2954 // Tests ASSERT_EQ.
TEST(AssertionTest,ASSERT_EQ)2955 TEST(AssertionTest, ASSERT_EQ) {
2956 ASSERT_EQ(5, 2 + 3);
2957 EXPECT_FATAL_FAILURE(ASSERT_EQ(5, 2*3),
2958 "Value of: 2*3\n"
2959 " Actual: 6\n"
2960 "Expected: 5");
2961 }
2962
2963 // Tests ASSERT_EQ(NULL, pointer).
2964 #if !GTEST_OS_SYMBIAN
2965 // The NULL-detection template magic fails to compile with
2966 // the Nokia compiler and crashes the ARM compiler, hence
2967 // not testing on Symbian.
TEST(AssertionTest,ASSERT_EQ_NULL)2968 TEST(AssertionTest, ASSERT_EQ_NULL) {
2969 // A success.
2970 const char* p = NULL;
2971 ASSERT_EQ(NULL, p);
2972
2973 // A failure.
2974 static int n = 0;
2975 EXPECT_FATAL_FAILURE(ASSERT_EQ(NULL, &n),
2976 "Value of: &n\n");
2977 }
2978 #endif // !GTEST_OS_SYMBIAN
2979
2980 // Tests ASSERT_EQ(0, non_pointer). Since the literal 0 can be
2981 // treated as a null pointer by the compiler, we need to make sure
2982 // that ASSERT_EQ(0, non_pointer) isn't interpreted by Google Test as
2983 // ASSERT_EQ(static_cast<void*>(NULL), non_pointer).
TEST(ExpectTest,ASSERT_EQ_0)2984 TEST(ExpectTest, ASSERT_EQ_0) {
2985 int n = 0;
2986
2987 // A success.
2988 ASSERT_EQ(0, n);
2989
2990 // A failure.
2991 EXPECT_FATAL_FAILURE(ASSERT_EQ(0, 5.6),
2992 "Expected: 0");
2993 }
2994
2995 // Tests ASSERT_NE.
TEST(AssertionTest,ASSERT_NE)2996 TEST(AssertionTest, ASSERT_NE) {
2997 ASSERT_NE(6, 7);
2998 EXPECT_FATAL_FAILURE(ASSERT_NE('a', 'a'),
2999 "Expected: ('a') != ('a'), "
3000 "actual: 'a' (97, 0x61) vs 'a' (97, 0x61)");
3001 }
3002
3003 // Tests ASSERT_LE.
TEST(AssertionTest,ASSERT_LE)3004 TEST(AssertionTest, ASSERT_LE) {
3005 ASSERT_LE(2, 3);
3006 ASSERT_LE(2, 2);
3007 EXPECT_FATAL_FAILURE(ASSERT_LE(2, 0),
3008 "Expected: (2) <= (0), actual: 2 vs 0");
3009 }
3010
3011 // Tests ASSERT_LT.
TEST(AssertionTest,ASSERT_LT)3012 TEST(AssertionTest, ASSERT_LT) {
3013 ASSERT_LT(2, 3);
3014 EXPECT_FATAL_FAILURE(ASSERT_LT(2, 2),
3015 "Expected: (2) < (2), actual: 2 vs 2");
3016 }
3017
3018 // Tests ASSERT_GE.
TEST(AssertionTest,ASSERT_GE)3019 TEST(AssertionTest, ASSERT_GE) {
3020 ASSERT_GE(2, 1);
3021 ASSERT_GE(2, 2);
3022 EXPECT_FATAL_FAILURE(ASSERT_GE(2, 3),
3023 "Expected: (2) >= (3), actual: 2 vs 3");
3024 }
3025
3026 // Tests ASSERT_GT.
TEST(AssertionTest,ASSERT_GT)3027 TEST(AssertionTest, ASSERT_GT) {
3028 ASSERT_GT(2, 1);
3029 EXPECT_FATAL_FAILURE(ASSERT_GT(2, 2),
3030 "Expected: (2) > (2), actual: 2 vs 2");
3031 }
3032
3033 #if GTEST_HAS_EXCEPTIONS
3034
ThrowNothing()3035 void ThrowNothing() {}
3036
3037
3038 // Tests ASSERT_THROW.
TEST(AssertionTest,ASSERT_THROW)3039 TEST(AssertionTest, ASSERT_THROW) {
3040 ASSERT_THROW(ThrowAnInteger(), int);
3041 EXPECT_FATAL_FAILURE(
3042 ASSERT_THROW(ThrowAnInteger(), bool),
3043 "Expected: ThrowAnInteger() throws an exception of type bool.\n"
3044 " Actual: it throws a different type.");
3045 EXPECT_FATAL_FAILURE(
3046 ASSERT_THROW(ThrowNothing(), bool),
3047 "Expected: ThrowNothing() throws an exception of type bool.\n"
3048 " Actual: it throws nothing.");
3049 }
3050
3051 // Tests ASSERT_NO_THROW.
TEST(AssertionTest,ASSERT_NO_THROW)3052 TEST(AssertionTest, ASSERT_NO_THROW) {
3053 ASSERT_NO_THROW(ThrowNothing());
3054 EXPECT_FATAL_FAILURE(ASSERT_NO_THROW(ThrowAnInteger()),
3055 "Expected: ThrowAnInteger() doesn't throw an exception."
3056 "\n Actual: it throws.");
3057 }
3058
3059 // Tests ASSERT_ANY_THROW.
TEST(AssertionTest,ASSERT_ANY_THROW)3060 TEST(AssertionTest, ASSERT_ANY_THROW) {
3061 ASSERT_ANY_THROW(ThrowAnInteger());
3062 EXPECT_FATAL_FAILURE(
3063 ASSERT_ANY_THROW(ThrowNothing()),
3064 "Expected: ThrowNothing() throws an exception.\n"
3065 " Actual: it doesn't.");
3066 }
3067
3068 #endif // GTEST_HAS_EXCEPTIONS
3069
3070 // Makes sure we deal with the precedence of <<. This test should
3071 // compile.
TEST(AssertionTest,AssertPrecedence)3072 TEST(AssertionTest, AssertPrecedence) {
3073 ASSERT_EQ(1 < 2, true);
3074 ASSERT_EQ(true && false, false);
3075 }
3076
3077 // A subroutine used by the following test.
TestEq1(int x)3078 void TestEq1(int x) {
3079 ASSERT_EQ(1, x);
3080 }
3081
3082 // Tests calling a test subroutine that's not part of a fixture.
TEST(AssertionTest,NonFixtureSubroutine)3083 TEST(AssertionTest, NonFixtureSubroutine) {
3084 EXPECT_FATAL_FAILURE(TestEq1(2),
3085 "Value of: x");
3086 }
3087
3088 // An uncopyable class.
3089 class Uncopyable {
3090 public:
Uncopyable(int value)3091 explicit Uncopyable(int value) : value_(value) {}
3092
value() const3093 int value() const { return value_; }
operator ==(const Uncopyable & rhs) const3094 bool operator==(const Uncopyable& rhs) const {
3095 return value() == rhs.value();
3096 }
3097 private:
3098 // This constructor deliberately has no implementation, as we don't
3099 // want this class to be copyable.
3100 Uncopyable(const Uncopyable&); // NOLINT
3101
3102 int value_;
3103 };
3104
operator <<(::std::ostream & os,const Uncopyable & value)3105 ::std::ostream& operator<<(::std::ostream& os, const Uncopyable& value) {
3106 return os << value.value();
3107 }
3108
3109
IsPositiveUncopyable(const Uncopyable & x)3110 bool IsPositiveUncopyable(const Uncopyable& x) {
3111 return x.value() > 0;
3112 }
3113
3114 // A subroutine used by the following test.
TestAssertNonPositive()3115 void TestAssertNonPositive() {
3116 Uncopyable y(-1);
3117 ASSERT_PRED1(IsPositiveUncopyable, y);
3118 }
3119 // A subroutine used by the following test.
TestAssertEqualsUncopyable()3120 void TestAssertEqualsUncopyable() {
3121 Uncopyable x(5);
3122 Uncopyable y(-1);
3123 ASSERT_EQ(x, y);
3124 }
3125
3126 // Tests that uncopyable objects can be used in assertions.
TEST(AssertionTest,AssertWorksWithUncopyableObject)3127 TEST(AssertionTest, AssertWorksWithUncopyableObject) {
3128 Uncopyable x(5);
3129 ASSERT_PRED1(IsPositiveUncopyable, x);
3130 ASSERT_EQ(x, x);
3131 EXPECT_FATAL_FAILURE(TestAssertNonPositive(),
3132 "IsPositiveUncopyable(y) evaluates to false, where\ny evaluates to -1");
3133 EXPECT_FATAL_FAILURE(TestAssertEqualsUncopyable(),
3134 "Value of: y\n Actual: -1\nExpected: x\nWhich is: 5");
3135 }
3136
3137 // Tests that uncopyable objects can be used in expects.
TEST(AssertionTest,ExpectWorksWithUncopyableObject)3138 TEST(AssertionTest, ExpectWorksWithUncopyableObject) {
3139 Uncopyable x(5);
3140 EXPECT_PRED1(IsPositiveUncopyable, x);
3141 Uncopyable y(-1);
3142 EXPECT_NONFATAL_FAILURE(EXPECT_PRED1(IsPositiveUncopyable, y),
3143 "IsPositiveUncopyable(y) evaluates to false, where\ny evaluates to -1");
3144 EXPECT_EQ(x, x);
3145 EXPECT_NONFATAL_FAILURE(EXPECT_EQ(x, y),
3146 "Value of: y\n Actual: -1\nExpected: x\nWhich is: 5");
3147 }
3148
3149
3150 // The version of gcc used in XCode 2.2 has a bug and doesn't allow
3151 // anonymous enums in assertions. Therefore the following test is
3152 // done only on Linux and Windows.
3153 #if GTEST_OS_LINUX || GTEST_OS_WINDOWS
3154
3155 // Tests using assertions with anonymous enums.
3156 enum {
3157 CASE_A = -1,
3158 #if GTEST_OS_LINUX
3159 // We want to test the case where the size of the anonymous enum is
3160 // larger than sizeof(int), to make sure our implementation of the
3161 // assertions doesn't truncate the enums. However, MSVC
3162 // (incorrectly) doesn't allow an enum value to exceed the range of
3163 // an int, so this has to be conditionally compiled.
3164 //
3165 // On Linux, CASE_B and CASE_A have the same value when truncated to
3166 // int size. We want to test whether this will confuse the
3167 // assertions.
3168 CASE_B = testing::internal::kMaxBiggestInt,
3169 #else
3170 CASE_B = INT_MAX,
3171 #endif // GTEST_OS_LINUX
3172 };
3173
TEST(AssertionTest,AnonymousEnum)3174 TEST(AssertionTest, AnonymousEnum) {
3175 #if GTEST_OS_LINUX
3176 EXPECT_EQ(static_cast<int>(CASE_A), static_cast<int>(CASE_B));
3177 #endif // GTEST_OS_LINUX
3178
3179 EXPECT_EQ(CASE_A, CASE_A);
3180 EXPECT_NE(CASE_A, CASE_B);
3181 EXPECT_LT(CASE_A, CASE_B);
3182 EXPECT_LE(CASE_A, CASE_B);
3183 EXPECT_GT(CASE_B, CASE_A);
3184 EXPECT_GE(CASE_A, CASE_A);
3185 EXPECT_NONFATAL_FAILURE(EXPECT_GE(CASE_A, CASE_B),
3186 "(CASE_A) >= (CASE_B)");
3187
3188 ASSERT_EQ(CASE_A, CASE_A);
3189 ASSERT_NE(CASE_A, CASE_B);
3190 ASSERT_LT(CASE_A, CASE_B);
3191 ASSERT_LE(CASE_A, CASE_B);
3192 ASSERT_GT(CASE_B, CASE_A);
3193 ASSERT_GE(CASE_A, CASE_A);
3194 EXPECT_FATAL_FAILURE(ASSERT_EQ(CASE_A, CASE_B),
3195 "Value of: CASE_B");
3196 }
3197
3198 #endif // GTEST_OS_LINUX || GTEST_OS_WINDOWS
3199
3200 #if GTEST_OS_WINDOWS
3201
UnexpectedHRESULTFailure()3202 static HRESULT UnexpectedHRESULTFailure() {
3203 return E_UNEXPECTED;
3204 }
3205
OkHRESULTSuccess()3206 static HRESULT OkHRESULTSuccess() {
3207 return S_OK;
3208 }
3209
FalseHRESULTSuccess()3210 static HRESULT FalseHRESULTSuccess() {
3211 return S_FALSE;
3212 }
3213
3214 // HRESULT assertion tests test both zero and non-zero
3215 // success codes as well as failure message for each.
3216 //
3217 // Windows CE doesn't support message texts.
TEST(HRESULTAssertionTest,EXPECT_HRESULT_SUCCEEDED)3218 TEST(HRESULTAssertionTest, EXPECT_HRESULT_SUCCEEDED) {
3219 EXPECT_HRESULT_SUCCEEDED(S_OK);
3220 EXPECT_HRESULT_SUCCEEDED(S_FALSE);
3221
3222 EXPECT_NONFATAL_FAILURE(EXPECT_HRESULT_SUCCEEDED(UnexpectedHRESULTFailure()),
3223 "Expected: (UnexpectedHRESULTFailure()) succeeds.\n"
3224 " Actual: 0x8000FFFF");
3225 }
3226
TEST(HRESULTAssertionTest,ASSERT_HRESULT_SUCCEEDED)3227 TEST(HRESULTAssertionTest, ASSERT_HRESULT_SUCCEEDED) {
3228 ASSERT_HRESULT_SUCCEEDED(S_OK);
3229 ASSERT_HRESULT_SUCCEEDED(S_FALSE);
3230
3231 EXPECT_FATAL_FAILURE(ASSERT_HRESULT_SUCCEEDED(UnexpectedHRESULTFailure()),
3232 "Expected: (UnexpectedHRESULTFailure()) succeeds.\n"
3233 " Actual: 0x8000FFFF");
3234 }
3235
TEST(HRESULTAssertionTest,EXPECT_HRESULT_FAILED)3236 TEST(HRESULTAssertionTest, EXPECT_HRESULT_FAILED) {
3237 EXPECT_HRESULT_FAILED(E_UNEXPECTED);
3238
3239 EXPECT_NONFATAL_FAILURE(EXPECT_HRESULT_FAILED(OkHRESULTSuccess()),
3240 "Expected: (OkHRESULTSuccess()) fails.\n"
3241 " Actual: 0x00000000");
3242 EXPECT_NONFATAL_FAILURE(EXPECT_HRESULT_FAILED(FalseHRESULTSuccess()),
3243 "Expected: (FalseHRESULTSuccess()) fails.\n"
3244 " Actual: 0x00000001");
3245 }
3246
TEST(HRESULTAssertionTest,ASSERT_HRESULT_FAILED)3247 TEST(HRESULTAssertionTest, ASSERT_HRESULT_FAILED) {
3248 ASSERT_HRESULT_FAILED(E_UNEXPECTED);
3249
3250 EXPECT_FATAL_FAILURE(ASSERT_HRESULT_FAILED(OkHRESULTSuccess()),
3251 "Expected: (OkHRESULTSuccess()) fails.\n"
3252 " Actual: 0x00000000");
3253 EXPECT_FATAL_FAILURE(ASSERT_HRESULT_FAILED(FalseHRESULTSuccess()),
3254 "Expected: (FalseHRESULTSuccess()) fails.\n"
3255 " Actual: 0x00000001");
3256 }
3257
3258 // Tests that streaming to the HRESULT macros works.
TEST(HRESULTAssertionTest,Streaming)3259 TEST(HRESULTAssertionTest, Streaming) {
3260 EXPECT_HRESULT_SUCCEEDED(S_OK) << "unexpected failure";
3261 ASSERT_HRESULT_SUCCEEDED(S_OK) << "unexpected failure";
3262 EXPECT_HRESULT_FAILED(E_UNEXPECTED) << "unexpected failure";
3263 ASSERT_HRESULT_FAILED(E_UNEXPECTED) << "unexpected failure";
3264
3265 EXPECT_NONFATAL_FAILURE(
3266 EXPECT_HRESULT_SUCCEEDED(E_UNEXPECTED) << "expected failure",
3267 "expected failure");
3268
3269 EXPECT_FATAL_FAILURE(
3270 ASSERT_HRESULT_SUCCEEDED(E_UNEXPECTED) << "expected failure",
3271 "expected failure");
3272
3273 EXPECT_NONFATAL_FAILURE(
3274 EXPECT_HRESULT_FAILED(S_OK) << "expected failure",
3275 "expected failure");
3276
3277 EXPECT_FATAL_FAILURE(
3278 ASSERT_HRESULT_FAILED(S_OK) << "expected failure",
3279 "expected failure");
3280 }
3281
3282 #endif // GTEST_OS_WINDOWS
3283
3284 // Tests that the assertion macros behave like single statements.
TEST(AssertionSyntaxTest,BasicAssertionsBehavesLikeSingleStatement)3285 TEST(AssertionSyntaxTest, BasicAssertionsBehavesLikeSingleStatement) {
3286 if (false)
3287 ASSERT_TRUE(false) << "This should never be executed; "
3288 "It's a compilation test only.";
3289
3290 if (true)
3291 EXPECT_FALSE(false);
3292 else
3293 ;
3294
3295 if (false)
3296 ASSERT_LT(1, 3);
3297
3298 if (false)
3299 ;
3300 else
3301 EXPECT_GT(3, 2) << "";
3302 }
3303
3304 #if GTEST_HAS_EXCEPTIONS
3305 // Tests that the compiler will not complain about unreachable code in the
3306 // EXPECT_THROW/EXPECT_ANY_THROW/EXPECT_NO_THROW macros.
TEST(ExpectThrowTest,DoesNotGenerateUnreachableCodeWarning)3307 TEST(ExpectThrowTest, DoesNotGenerateUnreachableCodeWarning) {
3308 int n = 0;
3309
3310 EXPECT_THROW(throw 1, int);
3311 EXPECT_NONFATAL_FAILURE(EXPECT_THROW(n++, int), "");
3312 EXPECT_NONFATAL_FAILURE(EXPECT_THROW(throw 1, const char*), "");
3313 EXPECT_NO_THROW(n++);
3314 EXPECT_NONFATAL_FAILURE(EXPECT_NO_THROW(throw 1), "");
3315 EXPECT_ANY_THROW(throw 1);
3316 EXPECT_NONFATAL_FAILURE(EXPECT_ANY_THROW(n++), "");
3317 }
3318
TEST(AssertionSyntaxTest,ExceptionAssertionsBehavesLikeSingleStatement)3319 TEST(AssertionSyntaxTest, ExceptionAssertionsBehavesLikeSingleStatement) {
3320 if (false)
3321 EXPECT_THROW(ThrowNothing(), bool);
3322
3323 if (true)
3324 EXPECT_THROW(ThrowAnInteger(), int);
3325 else
3326 ;
3327
3328 if (false)
3329 EXPECT_NO_THROW(ThrowAnInteger());
3330
3331 if (true)
3332 EXPECT_NO_THROW(ThrowNothing());
3333 else
3334 ;
3335
3336 if (false)
3337 EXPECT_ANY_THROW(ThrowNothing());
3338
3339 if (true)
3340 EXPECT_ANY_THROW(ThrowAnInteger());
3341 else
3342 ;
3343 }
3344 #endif // GTEST_HAS_EXCEPTIONS
3345
TEST(AssertionSyntaxTest,NoFatalFailureAssertionsBehavesLikeSingleStatement)3346 TEST(AssertionSyntaxTest, NoFatalFailureAssertionsBehavesLikeSingleStatement) {
3347 if (false)
3348 EXPECT_NO_FATAL_FAILURE(FAIL()) << "This should never be executed. "
3349 << "It's a compilation test only.";
3350 else
3351 ;
3352
3353 if (false)
3354 ASSERT_NO_FATAL_FAILURE(FAIL()) << "";
3355 else
3356 ;
3357
3358 if (true)
3359 EXPECT_NO_FATAL_FAILURE(SUCCEED());
3360 else
3361 ;
3362
3363 if (false)
3364 ;
3365 else
3366 ASSERT_NO_FATAL_FAILURE(SUCCEED());
3367 }
3368
3369 // Tests that the assertion macros work well with switch statements.
TEST(AssertionSyntaxTest,WorksWithSwitch)3370 TEST(AssertionSyntaxTest, WorksWithSwitch) {
3371 switch (0) {
3372 case 1:
3373 break;
3374 default:
3375 ASSERT_TRUE(true);
3376 }
3377
3378 switch (0)
3379 case 0:
3380 EXPECT_FALSE(false) << "EXPECT_FALSE failed in switch case";
3381
3382 // Binary assertions are implemented using a different code path
3383 // than the Boolean assertions. Hence we test them separately.
3384 switch (0) {
3385 case 1:
3386 default:
3387 ASSERT_EQ(1, 1) << "ASSERT_EQ failed in default switch handler";
3388 }
3389
3390 switch (0)
3391 case 0:
3392 EXPECT_NE(1, 2);
3393 }
3394
3395 #if GTEST_HAS_EXCEPTIONS
3396
ThrowAString()3397 void ThrowAString() {
3398 throw "String";
3399 }
3400
3401 // Test that the exception assertion macros compile and work with const
3402 // type qualifier.
TEST(AssertionSyntaxTest,WorksWithConst)3403 TEST(AssertionSyntaxTest, WorksWithConst) {
3404 ASSERT_THROW(ThrowAString(), const char*);
3405
3406 EXPECT_THROW(ThrowAString(), const char*);
3407 }
3408
3409 #endif // GTEST_HAS_EXCEPTIONS
3410
3411 } // namespace
3412
3413 // Returns the number of successful parts in the current test.
GetSuccessfulPartCount()3414 static size_t GetSuccessfulPartCount() {
3415 return UnitTest::GetInstance()->impl()->current_test_result()->
3416 successful_part_count();
3417 }
3418
3419 namespace testing {
3420
3421 // Tests that Google Test tracks SUCCEED*.
TEST(SuccessfulAssertionTest,SUCCEED)3422 TEST(SuccessfulAssertionTest, SUCCEED) {
3423 SUCCEED();
3424 SUCCEED() << "OK";
3425 EXPECT_EQ(2u, GetSuccessfulPartCount());
3426 }
3427
3428 // Tests that Google Test doesn't track successful EXPECT_*.
TEST(SuccessfulAssertionTest,EXPECT)3429 TEST(SuccessfulAssertionTest, EXPECT) {
3430 EXPECT_TRUE(true);
3431 EXPECT_EQ(0u, GetSuccessfulPartCount());
3432 }
3433
3434 // Tests that Google Test doesn't track successful EXPECT_STR*.
TEST(SuccessfulAssertionTest,EXPECT_STR)3435 TEST(SuccessfulAssertionTest, EXPECT_STR) {
3436 EXPECT_STREQ("", "");
3437 EXPECT_EQ(0u, GetSuccessfulPartCount());
3438 }
3439
3440 // Tests that Google Test doesn't track successful ASSERT_*.
TEST(SuccessfulAssertionTest,ASSERT)3441 TEST(SuccessfulAssertionTest, ASSERT) {
3442 ASSERT_TRUE(true);
3443 EXPECT_EQ(0u, GetSuccessfulPartCount());
3444 }
3445
3446 // Tests that Google Test doesn't track successful ASSERT_STR*.
TEST(SuccessfulAssertionTest,ASSERT_STR)3447 TEST(SuccessfulAssertionTest, ASSERT_STR) {
3448 ASSERT_STREQ("", "");
3449 EXPECT_EQ(0u, GetSuccessfulPartCount());
3450 }
3451
3452 } // namespace testing
3453
3454 namespace {
3455
3456 // Tests EXPECT_TRUE.
TEST(ExpectTest,EXPECT_TRUE)3457 TEST(ExpectTest, EXPECT_TRUE) {
3458 EXPECT_TRUE(2 > 1); // NOLINT
3459 EXPECT_NONFATAL_FAILURE(EXPECT_TRUE(2 < 1),
3460 "Value of: 2 < 1\n"
3461 " Actual: false\n"
3462 "Expected: true");
3463 EXPECT_NONFATAL_FAILURE(EXPECT_TRUE(2 > 3),
3464 "2 > 3");
3465 }
3466
3467 // Tests EXPECT_FALSE.
TEST(ExpectTest,EXPECT_FALSE)3468 TEST(ExpectTest, EXPECT_FALSE) {
3469 EXPECT_FALSE(2 < 1); // NOLINT
3470 EXPECT_NONFATAL_FAILURE(EXPECT_FALSE(2 > 1),
3471 "Value of: 2 > 1\n"
3472 " Actual: true\n"
3473 "Expected: false");
3474 EXPECT_NONFATAL_FAILURE(EXPECT_FALSE(2 < 3),
3475 "2 < 3");
3476 }
3477
3478 // Tests EXPECT_EQ.
TEST(ExpectTest,EXPECT_EQ)3479 TEST(ExpectTest, EXPECT_EQ) {
3480 EXPECT_EQ(5, 2 + 3);
3481 EXPECT_NONFATAL_FAILURE(EXPECT_EQ(5, 2*3),
3482 "Value of: 2*3\n"
3483 " Actual: 6\n"
3484 "Expected: 5");
3485 EXPECT_NONFATAL_FAILURE(EXPECT_EQ(5, 2 - 3),
3486 "2 - 3");
3487 }
3488
3489 // Tests using EXPECT_EQ on double values. The purpose is to make
3490 // sure that the specialization we did for integer and anonymous enums
3491 // isn't used for double arguments.
TEST(ExpectTest,EXPECT_EQ_Double)3492 TEST(ExpectTest, EXPECT_EQ_Double) {
3493 // A success.
3494 EXPECT_EQ(5.6, 5.6);
3495
3496 // A failure.
3497 EXPECT_NONFATAL_FAILURE(EXPECT_EQ(5.1, 5.2),
3498 "5.1");
3499 }
3500
3501 #if !GTEST_OS_SYMBIAN
3502 // Tests EXPECT_EQ(NULL, pointer).
TEST(ExpectTest,EXPECT_EQ_NULL)3503 TEST(ExpectTest, EXPECT_EQ_NULL) {
3504 // A success.
3505 const char* p = NULL;
3506 EXPECT_EQ(NULL, p);
3507
3508 // A failure.
3509 int n = 0;
3510 EXPECT_NONFATAL_FAILURE(EXPECT_EQ(NULL, &n),
3511 "Value of: &n\n");
3512 }
3513 #endif // !GTEST_OS_SYMBIAN
3514
3515 // Tests EXPECT_EQ(0, non_pointer). Since the literal 0 can be
3516 // treated as a null pointer by the compiler, we need to make sure
3517 // that EXPECT_EQ(0, non_pointer) isn't interpreted by Google Test as
3518 // EXPECT_EQ(static_cast<void*>(NULL), non_pointer).
TEST(ExpectTest,EXPECT_EQ_0)3519 TEST(ExpectTest, EXPECT_EQ_0) {
3520 int n = 0;
3521
3522 // A success.
3523 EXPECT_EQ(0, n);
3524
3525 // A failure.
3526 EXPECT_NONFATAL_FAILURE(EXPECT_EQ(0, 5.6),
3527 "Expected: 0");
3528 }
3529
3530 // Tests EXPECT_NE.
TEST(ExpectTest,EXPECT_NE)3531 TEST(ExpectTest, EXPECT_NE) {
3532 EXPECT_NE(6, 7);
3533
3534 EXPECT_NONFATAL_FAILURE(EXPECT_NE('a', 'a'),
3535 "Expected: ('a') != ('a'), "
3536 "actual: 'a' (97, 0x61) vs 'a' (97, 0x61)");
3537 EXPECT_NONFATAL_FAILURE(EXPECT_NE(2, 2),
3538 "2");
3539 char* const p0 = NULL;
3540 EXPECT_NONFATAL_FAILURE(EXPECT_NE(p0, p0),
3541 "p0");
3542 // Only way to get the Nokia compiler to compile the cast
3543 // is to have a separate void* variable first. Putting
3544 // the two casts on the same line doesn't work, neither does
3545 // a direct C-style to char*.
3546 void* pv1 = (void*)0x1234; // NOLINT
3547 char* const p1 = reinterpret_cast<char*>(pv1);
3548 EXPECT_NONFATAL_FAILURE(EXPECT_NE(p1, p1),
3549 "p1");
3550 }
3551
3552 // Tests EXPECT_LE.
TEST(ExpectTest,EXPECT_LE)3553 TEST(ExpectTest, EXPECT_LE) {
3554 EXPECT_LE(2, 3);
3555 EXPECT_LE(2, 2);
3556 EXPECT_NONFATAL_FAILURE(EXPECT_LE(2, 0),
3557 "Expected: (2) <= (0), actual: 2 vs 0");
3558 EXPECT_NONFATAL_FAILURE(EXPECT_LE(1.1, 0.9),
3559 "(1.1) <= (0.9)");
3560 }
3561
3562 // Tests EXPECT_LT.
TEST(ExpectTest,EXPECT_LT)3563 TEST(ExpectTest, EXPECT_LT) {
3564 EXPECT_LT(2, 3);
3565 EXPECT_NONFATAL_FAILURE(EXPECT_LT(2, 2),
3566 "Expected: (2) < (2), actual: 2 vs 2");
3567 EXPECT_NONFATAL_FAILURE(EXPECT_LT(2, 1),
3568 "(2) < (1)");
3569 }
3570
3571 // Tests EXPECT_GE.
TEST(ExpectTest,EXPECT_GE)3572 TEST(ExpectTest, EXPECT_GE) {
3573 EXPECT_GE(2, 1);
3574 EXPECT_GE(2, 2);
3575 EXPECT_NONFATAL_FAILURE(EXPECT_GE(2, 3),
3576 "Expected: (2) >= (3), actual: 2 vs 3");
3577 EXPECT_NONFATAL_FAILURE(EXPECT_GE(0.9, 1.1),
3578 "(0.9) >= (1.1)");
3579 }
3580
3581 // Tests EXPECT_GT.
TEST(ExpectTest,EXPECT_GT)3582 TEST(ExpectTest, EXPECT_GT) {
3583 EXPECT_GT(2, 1);
3584 EXPECT_NONFATAL_FAILURE(EXPECT_GT(2, 2),
3585 "Expected: (2) > (2), actual: 2 vs 2");
3586 EXPECT_NONFATAL_FAILURE(EXPECT_GT(2, 3),
3587 "(2) > (3)");
3588 }
3589
3590 #if GTEST_HAS_EXCEPTIONS
3591
3592 // Tests EXPECT_THROW.
TEST(ExpectTest,EXPECT_THROW)3593 TEST(ExpectTest, EXPECT_THROW) {
3594 EXPECT_THROW(ThrowAnInteger(), int);
3595 EXPECT_NONFATAL_FAILURE(EXPECT_THROW(ThrowAnInteger(), bool),
3596 "Expected: ThrowAnInteger() throws an exception of "
3597 "type bool.\n Actual: it throws a different type.");
3598 EXPECT_NONFATAL_FAILURE(
3599 EXPECT_THROW(ThrowNothing(), bool),
3600 "Expected: ThrowNothing() throws an exception of type bool.\n"
3601 " Actual: it throws nothing.");
3602 }
3603
3604 // Tests EXPECT_NO_THROW.
TEST(ExpectTest,EXPECT_NO_THROW)3605 TEST(ExpectTest, EXPECT_NO_THROW) {
3606 EXPECT_NO_THROW(ThrowNothing());
3607 EXPECT_NONFATAL_FAILURE(EXPECT_NO_THROW(ThrowAnInteger()),
3608 "Expected: ThrowAnInteger() doesn't throw an "
3609 "exception.\n Actual: it throws.");
3610 }
3611
3612 // Tests EXPECT_ANY_THROW.
TEST(ExpectTest,EXPECT_ANY_THROW)3613 TEST(ExpectTest, EXPECT_ANY_THROW) {
3614 EXPECT_ANY_THROW(ThrowAnInteger());
3615 EXPECT_NONFATAL_FAILURE(
3616 EXPECT_ANY_THROW(ThrowNothing()),
3617 "Expected: ThrowNothing() throws an exception.\n"
3618 " Actual: it doesn't.");
3619 }
3620
3621 #endif // GTEST_HAS_EXCEPTIONS
3622
3623 // Make sure we deal with the precedence of <<.
TEST(ExpectTest,ExpectPrecedence)3624 TEST(ExpectTest, ExpectPrecedence) {
3625 EXPECT_EQ(1 < 2, true);
3626 EXPECT_NONFATAL_FAILURE(EXPECT_EQ(true, true && false),
3627 "Value of: true && false");
3628 }
3629
3630
3631 // Tests the StreamableToString() function.
3632
3633 // Tests using StreamableToString() on a scalar.
TEST(StreamableToStringTest,Scalar)3634 TEST(StreamableToStringTest, Scalar) {
3635 EXPECT_STREQ("5", StreamableToString(5).c_str());
3636 }
3637
3638 // Tests using StreamableToString() on a non-char pointer.
TEST(StreamableToStringTest,Pointer)3639 TEST(StreamableToStringTest, Pointer) {
3640 int n = 0;
3641 int* p = &n;
3642 EXPECT_STRNE("(null)", StreamableToString(p).c_str());
3643 }
3644
3645 // Tests using StreamableToString() on a NULL non-char pointer.
TEST(StreamableToStringTest,NullPointer)3646 TEST(StreamableToStringTest, NullPointer) {
3647 int* p = NULL;
3648 EXPECT_STREQ("(null)", StreamableToString(p).c_str());
3649 }
3650
3651 // Tests using StreamableToString() on a C string.
TEST(StreamableToStringTest,CString)3652 TEST(StreamableToStringTest, CString) {
3653 EXPECT_STREQ("Foo", StreamableToString("Foo").c_str());
3654 }
3655
3656 // Tests using StreamableToString() on a NULL C string.
TEST(StreamableToStringTest,NullCString)3657 TEST(StreamableToStringTest, NullCString) {
3658 char* p = NULL;
3659 EXPECT_STREQ("(null)", StreamableToString(p).c_str());
3660 }
3661
3662 // Tests using streamable values as assertion messages.
3663
3664 #if GTEST_HAS_STD_STRING
3665 // Tests using std::string as an assertion message.
TEST(StreamableTest,string)3666 TEST(StreamableTest, string) {
3667 static const std::string str(
3668 "This failure message is a std::string, and is expected.");
3669 EXPECT_FATAL_FAILURE(FAIL() << str,
3670 str.c_str());
3671 }
3672
3673 // Tests that we can output strings containing embedded NULs.
3674 // Limited to Linux because we can only do this with std::string's.
TEST(StreamableTest,stringWithEmbeddedNUL)3675 TEST(StreamableTest, stringWithEmbeddedNUL) {
3676 static const char char_array_with_nul[] =
3677 "Here's a NUL\0 and some more string";
3678 static const std::string string_with_nul(char_array_with_nul,
3679 sizeof(char_array_with_nul)
3680 - 1); // drops the trailing NUL
3681 EXPECT_FATAL_FAILURE(FAIL() << string_with_nul,
3682 "Here's a NUL\\0 and some more string");
3683 }
3684
3685 #endif // GTEST_HAS_STD_STRING
3686
3687 // Tests that we can output a NUL char.
TEST(StreamableTest,NULChar)3688 TEST(StreamableTest, NULChar) {
3689 EXPECT_FATAL_FAILURE({ // NOLINT
3690 FAIL() << "A NUL" << '\0' << " and some more string";
3691 }, "A NUL\\0 and some more string");
3692 }
3693
3694 // Tests using int as an assertion message.
TEST(StreamableTest,int)3695 TEST(StreamableTest, int) {
3696 EXPECT_FATAL_FAILURE(FAIL() << 900913,
3697 "900913");
3698 }
3699
3700 // Tests using NULL char pointer as an assertion message.
3701 //
3702 // In MSVC, streaming a NULL char * causes access violation. Google Test
3703 // implemented a workaround (substituting "(null)" for NULL). This
3704 // tests whether the workaround works.
TEST(StreamableTest,NullCharPtr)3705 TEST(StreamableTest, NullCharPtr) {
3706 EXPECT_FATAL_FAILURE(FAIL() << static_cast<const char*>(NULL),
3707 "(null)");
3708 }
3709
3710 // Tests that basic IO manipulators (endl, ends, and flush) can be
3711 // streamed to testing::Message.
TEST(StreamableTest,BasicIoManip)3712 TEST(StreamableTest, BasicIoManip) {
3713 EXPECT_FATAL_FAILURE({ // NOLINT
3714 FAIL() << "Line 1." << std::endl
3715 << "A NUL char " << std::ends << std::flush << " in line 2.";
3716 }, "Line 1.\nA NUL char \\0 in line 2.");
3717 }
3718
3719 // Tests the macros that haven't been covered so far.
3720
AddFailureHelper(bool * aborted)3721 void AddFailureHelper(bool* aborted) {
3722 *aborted = true;
3723 ADD_FAILURE() << "Failure";
3724 *aborted = false;
3725 }
3726
3727 // Tests ADD_FAILURE.
TEST(MacroTest,ADD_FAILURE)3728 TEST(MacroTest, ADD_FAILURE) {
3729 bool aborted = true;
3730 EXPECT_NONFATAL_FAILURE(AddFailureHelper(&aborted),
3731 "Failure");
3732 EXPECT_FALSE(aborted);
3733 }
3734
3735 // Tests FAIL.
TEST(MacroTest,FAIL)3736 TEST(MacroTest, FAIL) {
3737 EXPECT_FATAL_FAILURE(FAIL(),
3738 "Failed");
3739 EXPECT_FATAL_FAILURE(FAIL() << "Intentional failure.",
3740 "Intentional failure.");
3741 }
3742
3743 // Tests SUCCEED
TEST(MacroTest,SUCCEED)3744 TEST(MacroTest, SUCCEED) {
3745 SUCCEED();
3746 SUCCEED() << "Explicit success.";
3747 }
3748
3749
3750 // Tests for EXPECT_EQ() and ASSERT_EQ().
3751 //
3752 // These tests fail *intentionally*, s.t. the failure messages can be
3753 // generated and tested.
3754 //
3755 // We have different tests for different argument types.
3756
3757 // Tests using bool values in {EXPECT|ASSERT}_EQ.
TEST(EqAssertionTest,Bool)3758 TEST(EqAssertionTest, Bool) {
3759 EXPECT_EQ(true, true);
3760 EXPECT_FATAL_FAILURE(ASSERT_EQ(false, true),
3761 "Value of: true");
3762 }
3763
3764 // Tests using int values in {EXPECT|ASSERT}_EQ.
TEST(EqAssertionTest,Int)3765 TEST(EqAssertionTest, Int) {
3766 ASSERT_EQ(32, 32);
3767 EXPECT_NONFATAL_FAILURE(EXPECT_EQ(32, 33),
3768 "33");
3769 }
3770
3771 // Tests using time_t values in {EXPECT|ASSERT}_EQ.
TEST(EqAssertionTest,Time_T)3772 TEST(EqAssertionTest, Time_T) {
3773 EXPECT_EQ(static_cast<time_t>(0),
3774 static_cast<time_t>(0));
3775 EXPECT_FATAL_FAILURE(ASSERT_EQ(static_cast<time_t>(0),
3776 static_cast<time_t>(1234)),
3777 "1234");
3778 }
3779
3780 // Tests using char values in {EXPECT|ASSERT}_EQ.
TEST(EqAssertionTest,Char)3781 TEST(EqAssertionTest, Char) {
3782 ASSERT_EQ('z', 'z');
3783 const char ch = 'b';
3784 EXPECT_NONFATAL_FAILURE(EXPECT_EQ('\0', ch),
3785 "ch");
3786 EXPECT_NONFATAL_FAILURE(EXPECT_EQ('a', ch),
3787 "ch");
3788 }
3789
3790 // Tests using wchar_t values in {EXPECT|ASSERT}_EQ.
TEST(EqAssertionTest,WideChar)3791 TEST(EqAssertionTest, WideChar) {
3792 EXPECT_EQ(L'b', L'b');
3793
3794 EXPECT_NONFATAL_FAILURE(EXPECT_EQ(L'\0', L'x'),
3795 "Value of: L'x'\n"
3796 " Actual: L'x' (120, 0x78)\n"
3797 "Expected: L'\0'\n"
3798 "Which is: L'\0' (0, 0x0)");
3799
3800 static wchar_t wchar;
3801 wchar = L'b';
3802 EXPECT_NONFATAL_FAILURE(EXPECT_EQ(L'a', wchar),
3803 "wchar");
3804 wchar = L'\x8119';
3805 EXPECT_FATAL_FAILURE(ASSERT_EQ(L'\x8120', wchar),
3806 "Value of: wchar");
3807 }
3808
3809 #if GTEST_HAS_STD_STRING
3810 // Tests using ::std::string values in {EXPECT|ASSERT}_EQ.
TEST(EqAssertionTest,StdString)3811 TEST(EqAssertionTest, StdString) {
3812 // Compares a const char* to an std::string that has identical
3813 // content.
3814 ASSERT_EQ("Test", ::std::string("Test"));
3815
3816 // Compares two identical std::strings.
3817 static const ::std::string str1("A * in the middle");
3818 static const ::std::string str2(str1);
3819 EXPECT_EQ(str1, str2);
3820
3821 // Compares a const char* to an std::string that has different
3822 // content
3823 EXPECT_NONFATAL_FAILURE(EXPECT_EQ("Test", ::std::string("test")),
3824 "::std::string(\"test\")");
3825
3826 // Compares an std::string to a char* that has different content.
3827 char* const p1 = const_cast<char*>("foo");
3828 EXPECT_NONFATAL_FAILURE(EXPECT_EQ(::std::string("bar"), p1),
3829 "p1");
3830
3831 // Compares two std::strings that have different contents, one of
3832 // which having a NUL character in the middle. This should fail.
3833 static ::std::string str3(str1);
3834 str3.at(2) = '\0';
3835 EXPECT_FATAL_FAILURE(ASSERT_EQ(str1, str3),
3836 "Value of: str3\n"
3837 " Actual: \"A \\0 in the middle\"");
3838 }
3839
3840 #endif // GTEST_HAS_STD_STRING
3841
3842 #if GTEST_HAS_STD_WSTRING
3843
3844 // Tests using ::std::wstring values in {EXPECT|ASSERT}_EQ.
TEST(EqAssertionTest,StdWideString)3845 TEST(EqAssertionTest, StdWideString) {
3846 // Compares an std::wstring to a const wchar_t* that has identical
3847 // content.
3848 EXPECT_EQ(::std::wstring(L"Test\x8119"), L"Test\x8119");
3849
3850 // Compares two identical std::wstrings.
3851 const ::std::wstring wstr1(L"A * in the middle");
3852 const ::std::wstring wstr2(wstr1);
3853 ASSERT_EQ(wstr1, wstr2);
3854
3855 // Compares an std::wstring to a const wchar_t* that has different
3856 // content.
3857 EXPECT_NONFATAL_FAILURE({ // NOLINT
3858 EXPECT_EQ(::std::wstring(L"Test\x8119"), L"Test\x8120");
3859 }, "L\"Test\\x8120\"");
3860
3861 // Compares two std::wstrings that have different contents, one of
3862 // which having a NUL character in the middle.
3863 ::std::wstring wstr3(wstr1);
3864 wstr3.at(2) = L'\0';
3865 EXPECT_NONFATAL_FAILURE(EXPECT_EQ(wstr1, wstr3),
3866 "wstr3");
3867
3868 // Compares a wchar_t* to an std::wstring that has different
3869 // content.
3870 EXPECT_FATAL_FAILURE({ // NOLINT
3871 ASSERT_EQ(const_cast<wchar_t*>(L"foo"), ::std::wstring(L"bar"));
3872 }, "");
3873 }
3874
3875 #endif // GTEST_HAS_STD_WSTRING
3876
3877 #if GTEST_HAS_GLOBAL_STRING
3878 // Tests using ::string values in {EXPECT|ASSERT}_EQ.
TEST(EqAssertionTest,GlobalString)3879 TEST(EqAssertionTest, GlobalString) {
3880 // Compares a const char* to a ::string that has identical content.
3881 EXPECT_EQ("Test", ::string("Test"));
3882
3883 // Compares two identical ::strings.
3884 const ::string str1("A * in the middle");
3885 const ::string str2(str1);
3886 ASSERT_EQ(str1, str2);
3887
3888 // Compares a ::string to a const char* that has different content.
3889 EXPECT_NONFATAL_FAILURE(EXPECT_EQ(::string("Test"), "test"),
3890 "test");
3891
3892 // Compares two ::strings that have different contents, one of which
3893 // having a NUL character in the middle.
3894 ::string str3(str1);
3895 str3.at(2) = '\0';
3896 EXPECT_NONFATAL_FAILURE(EXPECT_EQ(str1, str3),
3897 "str3");
3898
3899 // Compares a ::string to a char* that has different content.
3900 EXPECT_FATAL_FAILURE({ // NOLINT
3901 ASSERT_EQ(::string("bar"), const_cast<char*>("foo"));
3902 }, "");
3903 }
3904
3905 #endif // GTEST_HAS_GLOBAL_STRING
3906
3907 #if GTEST_HAS_GLOBAL_WSTRING
3908
3909 // Tests using ::wstring values in {EXPECT|ASSERT}_EQ.
TEST(EqAssertionTest,GlobalWideString)3910 TEST(EqAssertionTest, GlobalWideString) {
3911 // Compares a const wchar_t* to a ::wstring that has identical content.
3912 ASSERT_EQ(L"Test\x8119", ::wstring(L"Test\x8119"));
3913
3914 // Compares two identical ::wstrings.
3915 static const ::wstring wstr1(L"A * in the middle");
3916 static const ::wstring wstr2(wstr1);
3917 EXPECT_EQ(wstr1, wstr2);
3918
3919 // Compares a const wchar_t* to a ::wstring that has different
3920 // content.
3921 EXPECT_NONFATAL_FAILURE({ // NOLINT
3922 EXPECT_EQ(L"Test\x8120", ::wstring(L"Test\x8119"));
3923 }, "Test\\x8119");
3924
3925 // Compares a wchar_t* to a ::wstring that has different content.
3926 wchar_t* const p1 = const_cast<wchar_t*>(L"foo");
3927 EXPECT_NONFATAL_FAILURE(EXPECT_EQ(p1, ::wstring(L"bar")),
3928 "bar");
3929
3930 // Compares two ::wstrings that have different contents, one of which
3931 // having a NUL character in the middle.
3932 static ::wstring wstr3;
3933 wstr3 = wstr1;
3934 wstr3.at(2) = L'\0';
3935 EXPECT_FATAL_FAILURE(ASSERT_EQ(wstr1, wstr3),
3936 "wstr3");
3937 }
3938
3939 #endif // GTEST_HAS_GLOBAL_WSTRING
3940
3941 // Tests using char pointers in {EXPECT|ASSERT}_EQ.
TEST(EqAssertionTest,CharPointer)3942 TEST(EqAssertionTest, CharPointer) {
3943 char* const p0 = NULL;
3944 // Only way to get the Nokia compiler to compile the cast
3945 // is to have a separate void* variable first. Putting
3946 // the two casts on the same line doesn't work, neither does
3947 // a direct C-style to char*.
3948 void* pv1 = (void*)0x1234; // NOLINT
3949 void* pv2 = (void*)0xABC0; // NOLINT
3950 char* const p1 = reinterpret_cast<char*>(pv1);
3951 char* const p2 = reinterpret_cast<char*>(pv2);
3952 ASSERT_EQ(p1, p1);
3953
3954 EXPECT_NONFATAL_FAILURE(EXPECT_EQ(p0, p2),
3955 "Value of: p2");
3956 EXPECT_NONFATAL_FAILURE(EXPECT_EQ(p1, p2),
3957 "p2");
3958 EXPECT_FATAL_FAILURE(ASSERT_EQ(reinterpret_cast<char*>(0x1234),
3959 reinterpret_cast<char*>(0xABC0)),
3960 "ABC0");
3961 }
3962
3963 // Tests using wchar_t pointers in {EXPECT|ASSERT}_EQ.
TEST(EqAssertionTest,WideCharPointer)3964 TEST(EqAssertionTest, WideCharPointer) {
3965 wchar_t* const p0 = NULL;
3966 // Only way to get the Nokia compiler to compile the cast
3967 // is to have a separate void* variable first. Putting
3968 // the two casts on the same line doesn't work, neither does
3969 // a direct C-style to char*.
3970 void* pv1 = (void*)0x1234; // NOLINT
3971 void* pv2 = (void*)0xABC0; // NOLINT
3972 wchar_t* const p1 = reinterpret_cast<wchar_t*>(pv1);
3973 wchar_t* const p2 = reinterpret_cast<wchar_t*>(pv2);
3974 EXPECT_EQ(p0, p0);
3975
3976 EXPECT_NONFATAL_FAILURE(EXPECT_EQ(p0, p2),
3977 "Value of: p2");
3978 EXPECT_NONFATAL_FAILURE(EXPECT_EQ(p1, p2),
3979 "p2");
3980 void* pv3 = (void*)0x1234; // NOLINT
3981 void* pv4 = (void*)0xABC0; // NOLINT
3982 const wchar_t* p3 = reinterpret_cast<const wchar_t*>(pv3);
3983 const wchar_t* p4 = reinterpret_cast<const wchar_t*>(pv4);
3984 EXPECT_NONFATAL_FAILURE(EXPECT_EQ(p3, p4),
3985 "p4");
3986 }
3987
3988 // Tests using other types of pointers in {EXPECT|ASSERT}_EQ.
TEST(EqAssertionTest,OtherPointer)3989 TEST(EqAssertionTest, OtherPointer) {
3990 ASSERT_EQ(static_cast<const int*>(NULL),
3991 static_cast<const int*>(NULL));
3992 EXPECT_FATAL_FAILURE(ASSERT_EQ(static_cast<const int*>(NULL),
3993 reinterpret_cast<const int*>(0x1234)),
3994 "0x1234");
3995 }
3996
3997 // Tests the FRIEND_TEST macro.
3998
3999 // This class has a private member we want to test. We will test it
4000 // both in a TEST and in a TEST_F.
4001 class Foo {
4002 public:
Foo()4003 Foo() {}
4004
4005 private:
Bar() const4006 int Bar() const { return 1; }
4007
4008 // Declares the friend tests that can access the private member
4009 // Bar().
4010 FRIEND_TEST(FRIEND_TEST_Test, TEST);
4011 FRIEND_TEST(FRIEND_TEST_Test2, TEST_F);
4012 };
4013
4014 // Tests that the FRIEND_TEST declaration allows a TEST to access a
4015 // class's private members. This should compile.
TEST(FRIEND_TEST_Test,TEST)4016 TEST(FRIEND_TEST_Test, TEST) {
4017 ASSERT_EQ(1, Foo().Bar());
4018 }
4019
4020 // The fixture needed to test using FRIEND_TEST with TEST_F.
4021 class FRIEND_TEST_Test2 : public Test {
4022 protected:
4023 Foo foo;
4024 };
4025
4026 // Tests that the FRIEND_TEST declaration allows a TEST_F to access a
4027 // class's private members. This should compile.
TEST_F(FRIEND_TEST_Test2,TEST_F)4028 TEST_F(FRIEND_TEST_Test2, TEST_F) {
4029 ASSERT_EQ(1, foo.Bar());
4030 }
4031
4032 // Tests the life cycle of Test objects.
4033
4034 // The test fixture for testing the life cycle of Test objects.
4035 //
4036 // This class counts the number of live test objects that uses this
4037 // fixture.
4038 class TestLifeCycleTest : public Test {
4039 protected:
4040 // Constructor. Increments the number of test objects that uses
4041 // this fixture.
TestLifeCycleTest()4042 TestLifeCycleTest() { count_++; }
4043
4044 // Destructor. Decrements the number of test objects that uses this
4045 // fixture.
~TestLifeCycleTest()4046 ~TestLifeCycleTest() { count_--; }
4047
4048 // Returns the number of live test objects that uses this fixture.
count() const4049 int count() const { return count_; }
4050
4051 private:
4052 static int count_;
4053 };
4054
4055 int TestLifeCycleTest::count_ = 0;
4056
4057 // Tests the life cycle of test objects.
TEST_F(TestLifeCycleTest,Test1)4058 TEST_F(TestLifeCycleTest, Test1) {
4059 // There should be only one test object in this test case that's
4060 // currently alive.
4061 ASSERT_EQ(1, count());
4062 }
4063
4064 // Tests the life cycle of test objects.
TEST_F(TestLifeCycleTest,Test2)4065 TEST_F(TestLifeCycleTest, Test2) {
4066 // After Test1 is done and Test2 is started, there should still be
4067 // only one live test object, as the object for Test1 should've been
4068 // deleted.
4069 ASSERT_EQ(1, count());
4070 }
4071
4072 } // namespace
4073
4074 // Tests streaming a user type whose definition and operator << are
4075 // both in the global namespace.
4076 class Base {
4077 public:
Base(int x)4078 explicit Base(int x) : x_(x) {}
x() const4079 int x() const { return x_; }
4080 private:
4081 int x_;
4082 };
operator <<(std::ostream & os,const Base & val)4083 std::ostream& operator<<(std::ostream& os,
4084 const Base& val) {
4085 return os << val.x();
4086 }
operator <<(std::ostream & os,const Base * pointer)4087 std::ostream& operator<<(std::ostream& os,
4088 const Base* pointer) {
4089 return os << "(" << pointer->x() << ")";
4090 }
4091
TEST(MessageTest,CanStreamUserTypeInGlobalNameSpace)4092 TEST(MessageTest, CanStreamUserTypeInGlobalNameSpace) {
4093 Message msg;
4094 Base a(1);
4095
4096 msg << a << &a; // Uses ::operator<<.
4097 EXPECT_STREQ("1(1)", msg.GetString().c_str());
4098 }
4099
4100 // Tests streaming a user type whose definition and operator<< are
4101 // both in an unnamed namespace.
4102 namespace {
4103 class MyTypeInUnnamedNameSpace : public Base {
4104 public:
MyTypeInUnnamedNameSpace(int x)4105 explicit MyTypeInUnnamedNameSpace(int x): Base(x) {}
4106 };
operator <<(std::ostream & os,const MyTypeInUnnamedNameSpace & val)4107 std::ostream& operator<<(std::ostream& os,
4108 const MyTypeInUnnamedNameSpace& val) {
4109 return os << val.x();
4110 }
operator <<(std::ostream & os,const MyTypeInUnnamedNameSpace * pointer)4111 std::ostream& operator<<(std::ostream& os,
4112 const MyTypeInUnnamedNameSpace* pointer) {
4113 return os << "(" << pointer->x() << ")";
4114 }
4115 } // namespace
4116
TEST(MessageTest,CanStreamUserTypeInUnnamedNameSpace)4117 TEST(MessageTest, CanStreamUserTypeInUnnamedNameSpace) {
4118 Message msg;
4119 MyTypeInUnnamedNameSpace a(1);
4120
4121 msg << a << &a; // Uses <unnamed_namespace>::operator<<.
4122 EXPECT_STREQ("1(1)", msg.GetString().c_str());
4123 }
4124
4125 // Tests streaming a user type whose definition and operator<< are
4126 // both in a user namespace.
4127 namespace namespace1 {
4128 class MyTypeInNameSpace1 : public Base {
4129 public:
MyTypeInNameSpace1(int x)4130 explicit MyTypeInNameSpace1(int x): Base(x) {}
4131 };
operator <<(std::ostream & os,const MyTypeInNameSpace1 & val)4132 std::ostream& operator<<(std::ostream& os,
4133 const MyTypeInNameSpace1& val) {
4134 return os << val.x();
4135 }
operator <<(std::ostream & os,const MyTypeInNameSpace1 * pointer)4136 std::ostream& operator<<(std::ostream& os,
4137 const MyTypeInNameSpace1* pointer) {
4138 return os << "(" << pointer->x() << ")";
4139 }
4140 } // namespace namespace1
4141
TEST(MessageTest,CanStreamUserTypeInUserNameSpace)4142 TEST(MessageTest, CanStreamUserTypeInUserNameSpace) {
4143 Message msg;
4144 namespace1::MyTypeInNameSpace1 a(1);
4145
4146 msg << a << &a; // Uses namespace1::operator<<.
4147 EXPECT_STREQ("1(1)", msg.GetString().c_str());
4148 }
4149
4150 // Tests streaming a user type whose definition is in a user namespace
4151 // but whose operator<< is in the global namespace.
4152 namespace namespace2 {
4153 class MyTypeInNameSpace2 : public ::Base {
4154 public:
MyTypeInNameSpace2(int x)4155 explicit MyTypeInNameSpace2(int x): Base(x) {}
4156 };
4157 } // namespace namespace2
operator <<(std::ostream & os,const namespace2::MyTypeInNameSpace2 & val)4158 std::ostream& operator<<(std::ostream& os,
4159 const namespace2::MyTypeInNameSpace2& val) {
4160 return os << val.x();
4161 }
operator <<(std::ostream & os,const namespace2::MyTypeInNameSpace2 * pointer)4162 std::ostream& operator<<(std::ostream& os,
4163 const namespace2::MyTypeInNameSpace2* pointer) {
4164 return os << "(" << pointer->x() << ")";
4165 }
4166
TEST(MessageTest,CanStreamUserTypeInUserNameSpaceWithStreamOperatorInGlobal)4167 TEST(MessageTest, CanStreamUserTypeInUserNameSpaceWithStreamOperatorInGlobal) {
4168 Message msg;
4169 namespace2::MyTypeInNameSpace2 a(1);
4170
4171 msg << a << &a; // Uses ::operator<<.
4172 EXPECT_STREQ("1(1)", msg.GetString().c_str());
4173 }
4174
4175 // Tests streaming NULL pointers to testing::Message.
TEST(MessageTest,NullPointers)4176 TEST(MessageTest, NullPointers) {
4177 Message msg;
4178 char* const p1 = NULL;
4179 unsigned char* const p2 = NULL;
4180 int* p3 = NULL;
4181 double* p4 = NULL;
4182 bool* p5 = NULL;
4183 Message* p6 = NULL;
4184
4185 msg << p1 << p2 << p3 << p4 << p5 << p6;
4186 ASSERT_STREQ("(null)(null)(null)(null)(null)(null)",
4187 msg.GetString().c_str());
4188 }
4189
4190 // Tests streaming wide strings to testing::Message.
TEST(MessageTest,WideStrings)4191 TEST(MessageTest, WideStrings) {
4192 // Streams a NULL of type const wchar_t*.
4193 const wchar_t* const_wstr = NULL;
4194 EXPECT_STREQ("(null)",
4195 (Message() << const_wstr).GetString().c_str());
4196
4197 // Streams a NULL of type wchar_t*.
4198 wchar_t* wstr = NULL;
4199 EXPECT_STREQ("(null)",
4200 (Message() << wstr).GetString().c_str());
4201
4202 // Streams a non-NULL of type const wchar_t*.
4203 const_wstr = L"abc\x8119";
4204 EXPECT_STREQ("abc\xe8\x84\x99",
4205 (Message() << const_wstr).GetString().c_str());
4206
4207 // Streams a non-NULL of type wchar_t*.
4208 wstr = const_cast<wchar_t*>(const_wstr);
4209 EXPECT_STREQ("abc\xe8\x84\x99",
4210 (Message() << wstr).GetString().c_str());
4211 }
4212
4213
4214 // This line tests that we can define tests in the testing namespace.
4215 namespace testing {
4216
4217 // Tests the TestInfo class.
4218
4219 class TestInfoTest : public Test {
4220 protected:
GetTestInfo(const char * test_name)4221 static TestInfo * GetTestInfo(const char* test_name) {
4222 return UnitTest::GetInstance()->impl()->
4223 GetTestCase("TestInfoTest", "", NULL, NULL)->
4224 GetTestInfo(test_name);
4225 }
4226
GetTestResult(const TestInfo * test_info)4227 static const TestResult* GetTestResult(
4228 const TestInfo* test_info) {
4229 return test_info->result();
4230 }
4231 };
4232
4233 // Tests TestInfo::test_case_name() and TestInfo::name().
TEST_F(TestInfoTest,Names)4234 TEST_F(TestInfoTest, Names) {
4235 TestInfo * const test_info = GetTestInfo("Names");
4236
4237 ASSERT_STREQ("TestInfoTest", test_info->test_case_name());
4238 ASSERT_STREQ("Names", test_info->name());
4239 }
4240
4241 // Tests TestInfo::result().
TEST_F(TestInfoTest,result)4242 TEST_F(TestInfoTest, result) {
4243 TestInfo * const test_info = GetTestInfo("result");
4244
4245 // Initially, there is no TestPartResult for this test.
4246 ASSERT_EQ(0u, GetTestResult(test_info)->total_part_count());
4247
4248 // After the previous assertion, there is still none.
4249 ASSERT_EQ(0u, GetTestResult(test_info)->total_part_count());
4250 }
4251
4252 // Tests setting up and tearing down a test case.
4253
4254 class SetUpTestCaseTest : public Test {
4255 protected:
4256 // This will be called once before the first test in this test case
4257 // is run.
SetUpTestCase()4258 static void SetUpTestCase() {
4259 printf("Setting up the test case . . .\n");
4260
4261 // Initializes some shared resource. In this simple example, we
4262 // just create a C string. More complex stuff can be done if
4263 // desired.
4264 shared_resource_ = "123";
4265
4266 // Increments the number of test cases that have been set up.
4267 counter_++;
4268
4269 // SetUpTestCase() should be called only once.
4270 EXPECT_EQ(1, counter_);
4271 }
4272
4273 // This will be called once after the last test in this test case is
4274 // run.
TearDownTestCase()4275 static void TearDownTestCase() {
4276 printf("Tearing down the test case . . .\n");
4277
4278 // Decrements the number of test cases that have been set up.
4279 counter_--;
4280
4281 // TearDownTestCase() should be called only once.
4282 EXPECT_EQ(0, counter_);
4283
4284 // Cleans up the shared resource.
4285 shared_resource_ = NULL;
4286 }
4287
4288 // This will be called before each test in this test case.
SetUp()4289 virtual void SetUp() {
4290 // SetUpTestCase() should be called only once, so counter_ should
4291 // always be 1.
4292 EXPECT_EQ(1, counter_);
4293 }
4294
4295 // Number of test cases that have been set up.
4296 static int counter_;
4297
4298 // Some resource to be shared by all tests in this test case.
4299 static const char* shared_resource_;
4300 };
4301
4302 int SetUpTestCaseTest::counter_ = 0;
4303 const char* SetUpTestCaseTest::shared_resource_ = NULL;
4304
4305 // A test that uses the shared resource.
TEST_F(SetUpTestCaseTest,Test1)4306 TEST_F(SetUpTestCaseTest, Test1) {
4307 EXPECT_STRNE(NULL, shared_resource_);
4308 }
4309
4310 // Another test that uses the shared resource.
TEST_F(SetUpTestCaseTest,Test2)4311 TEST_F(SetUpTestCaseTest, Test2) {
4312 EXPECT_STREQ("123", shared_resource_);
4313 }
4314
4315 // The InitGoogleTestTest test case tests testing::InitGoogleTest().
4316
4317 // The Flags struct stores a copy of all Google Test flags.
4318 struct Flags {
4319 // Constructs a Flags struct where each flag has its default value.
Flagstesting::Flags4320 Flags() : also_run_disabled_tests(false),
4321 break_on_failure(false),
4322 catch_exceptions(false),
4323 death_test_use_fork(false),
4324 filter(""),
4325 list_tests(false),
4326 output(""),
4327 print_time(false),
4328 repeat(1),
4329 throw_on_failure(false) {}
4330
4331 // Factory methods.
4332
4333 // Creates a Flags struct where the gtest_also_run_disabled_tests flag has
4334 // the given value.
AlsoRunDisabledTeststesting::Flags4335 static Flags AlsoRunDisabledTests(bool also_run_disabled_tests) {
4336 Flags flags;
4337 flags.also_run_disabled_tests = also_run_disabled_tests;
4338 return flags;
4339 }
4340
4341 // Creates a Flags struct where the gtest_break_on_failure flag has
4342 // the given value.
BreakOnFailuretesting::Flags4343 static Flags BreakOnFailure(bool break_on_failure) {
4344 Flags flags;
4345 flags.break_on_failure = break_on_failure;
4346 return flags;
4347 }
4348
4349 // Creates a Flags struct where the gtest_catch_exceptions flag has
4350 // the given value.
CatchExceptionstesting::Flags4351 static Flags CatchExceptions(bool catch_exceptions) {
4352 Flags flags;
4353 flags.catch_exceptions = catch_exceptions;
4354 return flags;
4355 }
4356
4357 // Creates a Flags struct where the gtest_death_test_use_fork flag has
4358 // the given value.
DeathTestUseForktesting::Flags4359 static Flags DeathTestUseFork(bool death_test_use_fork) {
4360 Flags flags;
4361 flags.death_test_use_fork = death_test_use_fork;
4362 return flags;
4363 }
4364
4365 // Creates a Flags struct where the gtest_filter flag has the given
4366 // value.
Filtertesting::Flags4367 static Flags Filter(const char* filter) {
4368 Flags flags;
4369 flags.filter = filter;
4370 return flags;
4371 }
4372
4373 // Creates a Flags struct where the gtest_list_tests flag has the
4374 // given value.
ListTeststesting::Flags4375 static Flags ListTests(bool list_tests) {
4376 Flags flags;
4377 flags.list_tests = list_tests;
4378 return flags;
4379 }
4380
4381 // Creates a Flags struct where the gtest_output flag has the given
4382 // value.
Outputtesting::Flags4383 static Flags Output(const char* output) {
4384 Flags flags;
4385 flags.output = output;
4386 return flags;
4387 }
4388
4389 // Creates a Flags struct where the gtest_print_time flag has the given
4390 // value.
PrintTimetesting::Flags4391 static Flags PrintTime(bool print_time) {
4392 Flags flags;
4393 flags.print_time = print_time;
4394 return flags;
4395 }
4396
4397 // Creates a Flags struct where the gtest_repeat flag has the given
4398 // value.
Repeattesting::Flags4399 static Flags Repeat(Int32 repeat) {
4400 Flags flags;
4401 flags.repeat = repeat;
4402 return flags;
4403 }
4404
4405 // Creates a Flags struct where the gtest_throw_on_failure flag has
4406 // the given value.
ThrowOnFailuretesting::Flags4407 static Flags ThrowOnFailure(bool throw_on_failure) {
4408 Flags flags;
4409 flags.throw_on_failure = throw_on_failure;
4410 return flags;
4411 }
4412
4413 // These fields store the flag values.
4414 bool also_run_disabled_tests;
4415 bool break_on_failure;
4416 bool catch_exceptions;
4417 bool death_test_use_fork;
4418 const char* filter;
4419 bool list_tests;
4420 const char* output;
4421 bool print_time;
4422 Int32 repeat;
4423 bool throw_on_failure;
4424 };
4425
4426 // Fixture for testing InitGoogleTest().
4427 class InitGoogleTestTest : public Test {
4428 protected:
4429 // Clears the flags before each test.
SetUp()4430 virtual void SetUp() {
4431 GTEST_FLAG(also_run_disabled_tests) = false;
4432 GTEST_FLAG(break_on_failure) = false;
4433 GTEST_FLAG(catch_exceptions) = false;
4434 GTEST_FLAG(death_test_use_fork) = false;
4435 GTEST_FLAG(filter) = "";
4436 GTEST_FLAG(list_tests) = false;
4437 GTEST_FLAG(output) = "";
4438 GTEST_FLAG(print_time) = false;
4439 GTEST_FLAG(repeat) = 1;
4440 GTEST_FLAG(throw_on_failure) = false;
4441 }
4442
4443 // Asserts that two narrow or wide string arrays are equal.
4444 template <typename CharType>
AssertStringArrayEq(size_t size1,CharType ** array1,size_t size2,CharType ** array2)4445 static void AssertStringArrayEq(size_t size1, CharType** array1,
4446 size_t size2, CharType** array2) {
4447 ASSERT_EQ(size1, size2) << " Array sizes different.";
4448
4449 for (size_t i = 0; i != size1; i++) {
4450 ASSERT_STREQ(array1[i], array2[i]) << " where i == " << i;
4451 }
4452 }
4453
4454 // Verifies that the flag values match the expected values.
CheckFlags(const Flags & expected)4455 static void CheckFlags(const Flags& expected) {
4456 EXPECT_EQ(expected.also_run_disabled_tests,
4457 GTEST_FLAG(also_run_disabled_tests));
4458 EXPECT_EQ(expected.break_on_failure, GTEST_FLAG(break_on_failure));
4459 EXPECT_EQ(expected.catch_exceptions, GTEST_FLAG(catch_exceptions));
4460 EXPECT_EQ(expected.death_test_use_fork, GTEST_FLAG(death_test_use_fork));
4461 EXPECT_STREQ(expected.filter, GTEST_FLAG(filter).c_str());
4462 EXPECT_EQ(expected.list_tests, GTEST_FLAG(list_tests));
4463 EXPECT_STREQ(expected.output, GTEST_FLAG(output).c_str());
4464 EXPECT_EQ(expected.print_time, GTEST_FLAG(print_time));
4465 EXPECT_EQ(expected.repeat, GTEST_FLAG(repeat));
4466 EXPECT_EQ(expected.throw_on_failure, GTEST_FLAG(throw_on_failure));
4467 }
4468
4469 // Parses a command line (specified by argc1 and argv1), then
4470 // verifies that the flag values are expected and that the
4471 // recognized flags are removed from the command line.
4472 template <typename CharType>
TestParsingFlags(int argc1,const CharType ** argv1,int argc2,const CharType ** argv2,const Flags & expected)4473 static void TestParsingFlags(int argc1, const CharType** argv1,
4474 int argc2, const CharType** argv2,
4475 const Flags& expected) {
4476 // Parses the command line.
4477 internal::ParseGoogleTestFlagsOnly(&argc1, const_cast<CharType**>(argv1));
4478
4479 // Verifies the flag values.
4480 CheckFlags(expected);
4481
4482 // Verifies that the recognized flags are removed from the command
4483 // line.
4484 AssertStringArrayEq(argc1 + 1, argv1, argc2 + 1, argv2);
4485 }
4486
4487 // This macro wraps TestParsingFlags s.t. the user doesn't need
4488 // to specify the array sizes.
4489 #define GTEST_TEST_PARSING_FLAGS_(argv1, argv2, expected) \
4490 TestParsingFlags(sizeof(argv1)/sizeof(*argv1) - 1, argv1, \
4491 sizeof(argv2)/sizeof(*argv2) - 1, argv2, expected)
4492 };
4493
4494 // Tests parsing an empty command line.
TEST_F(InitGoogleTestTest,Empty)4495 TEST_F(InitGoogleTestTest, Empty) {
4496 const char* argv[] = {
4497 NULL
4498 };
4499
4500 const char* argv2[] = {
4501 NULL
4502 };
4503
4504 GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags());
4505 }
4506
4507 // Tests parsing a command line that has no flag.
TEST_F(InitGoogleTestTest,NoFlag)4508 TEST_F(InitGoogleTestTest, NoFlag) {
4509 const char* argv[] = {
4510 "foo.exe",
4511 NULL
4512 };
4513
4514 const char* argv2[] = {
4515 "foo.exe",
4516 NULL
4517 };
4518
4519 GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags());
4520 }
4521
4522 // Tests parsing a bad --gtest_filter flag.
TEST_F(InitGoogleTestTest,FilterBad)4523 TEST_F(InitGoogleTestTest, FilterBad) {
4524 const char* argv[] = {
4525 "foo.exe",
4526 "--gtest_filter",
4527 NULL
4528 };
4529
4530 const char* argv2[] = {
4531 "foo.exe",
4532 "--gtest_filter",
4533 NULL
4534 };
4535
4536 GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::Filter(""));
4537 }
4538
4539 // Tests parsing an empty --gtest_filter flag.
TEST_F(InitGoogleTestTest,FilterEmpty)4540 TEST_F(InitGoogleTestTest, FilterEmpty) {
4541 const char* argv[] = {
4542 "foo.exe",
4543 "--gtest_filter=",
4544 NULL
4545 };
4546
4547 const char* argv2[] = {
4548 "foo.exe",
4549 NULL
4550 };
4551
4552 GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::Filter(""));
4553 }
4554
4555 // Tests parsing a non-empty --gtest_filter flag.
TEST_F(InitGoogleTestTest,FilterNonEmpty)4556 TEST_F(InitGoogleTestTest, FilterNonEmpty) {
4557 const char* argv[] = {
4558 "foo.exe",
4559 "--gtest_filter=abc",
4560 NULL
4561 };
4562
4563 const char* argv2[] = {
4564 "foo.exe",
4565 NULL
4566 };
4567
4568 GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::Filter("abc"));
4569 }
4570
4571 // Tests parsing --gtest_break_on_failure.
TEST_F(InitGoogleTestTest,BreakOnFailureNoDef)4572 TEST_F(InitGoogleTestTest, BreakOnFailureNoDef) {
4573 const char* argv[] = {
4574 "foo.exe",
4575 "--gtest_break_on_failure",
4576 NULL
4577 };
4578
4579 const char* argv2[] = {
4580 "foo.exe",
4581 NULL
4582 };
4583
4584 GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::BreakOnFailure(true));
4585 }
4586
4587 // Tests parsing --gtest_break_on_failure=0.
TEST_F(InitGoogleTestTest,BreakOnFailureFalse_0)4588 TEST_F(InitGoogleTestTest, BreakOnFailureFalse_0) {
4589 const char* argv[] = {
4590 "foo.exe",
4591 "--gtest_break_on_failure=0",
4592 NULL
4593 };
4594
4595 const char* argv2[] = {
4596 "foo.exe",
4597 NULL
4598 };
4599
4600 GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::BreakOnFailure(false));
4601 }
4602
4603 // Tests parsing --gtest_break_on_failure=f.
TEST_F(InitGoogleTestTest,BreakOnFailureFalse_f)4604 TEST_F(InitGoogleTestTest, BreakOnFailureFalse_f) {
4605 const char* argv[] = {
4606 "foo.exe",
4607 "--gtest_break_on_failure=f",
4608 NULL
4609 };
4610
4611 const char* argv2[] = {
4612 "foo.exe",
4613 NULL
4614 };
4615
4616 GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::BreakOnFailure(false));
4617 }
4618
4619 // Tests parsing --gtest_break_on_failure=F.
TEST_F(InitGoogleTestTest,BreakOnFailureFalse_F)4620 TEST_F(InitGoogleTestTest, BreakOnFailureFalse_F) {
4621 const char* argv[] = {
4622 "foo.exe",
4623 "--gtest_break_on_failure=F",
4624 NULL
4625 };
4626
4627 const char* argv2[] = {
4628 "foo.exe",
4629 NULL
4630 };
4631
4632 GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::BreakOnFailure(false));
4633 }
4634
4635 // Tests parsing a --gtest_break_on_failure flag that has a "true"
4636 // definition.
TEST_F(InitGoogleTestTest,BreakOnFailureTrue)4637 TEST_F(InitGoogleTestTest, BreakOnFailureTrue) {
4638 const char* argv[] = {
4639 "foo.exe",
4640 "--gtest_break_on_failure=1",
4641 NULL
4642 };
4643
4644 const char* argv2[] = {
4645 "foo.exe",
4646 NULL
4647 };
4648
4649 GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::BreakOnFailure(true));
4650 }
4651
4652 // Tests parsing --gtest_catch_exceptions.
TEST_F(InitGoogleTestTest,CatchExceptions)4653 TEST_F(InitGoogleTestTest, CatchExceptions) {
4654 const char* argv[] = {
4655 "foo.exe",
4656 "--gtest_catch_exceptions",
4657 NULL
4658 };
4659
4660 const char* argv2[] = {
4661 "foo.exe",
4662 NULL
4663 };
4664
4665 GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::CatchExceptions(true));
4666 }
4667
4668 // Tests parsing --gtest_death_test_use_fork.
TEST_F(InitGoogleTestTest,DeathTestUseFork)4669 TEST_F(InitGoogleTestTest, DeathTestUseFork) {
4670 const char* argv[] = {
4671 "foo.exe",
4672 "--gtest_death_test_use_fork",
4673 NULL
4674 };
4675
4676 const char* argv2[] = {
4677 "foo.exe",
4678 NULL
4679 };
4680
4681 GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::DeathTestUseFork(true));
4682 }
4683
4684 // Tests having the same flag twice with different values. The
4685 // expected behavior is that the one coming last takes precedence.
TEST_F(InitGoogleTestTest,DuplicatedFlags)4686 TEST_F(InitGoogleTestTest, DuplicatedFlags) {
4687 const char* argv[] = {
4688 "foo.exe",
4689 "--gtest_filter=a",
4690 "--gtest_filter=b",
4691 NULL
4692 };
4693
4694 const char* argv2[] = {
4695 "foo.exe",
4696 NULL
4697 };
4698
4699 GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::Filter("b"));
4700 }
4701
4702 // Tests having an unrecognized flag on the command line.
TEST_F(InitGoogleTestTest,UnrecognizedFlag)4703 TEST_F(InitGoogleTestTest, UnrecognizedFlag) {
4704 const char* argv[] = {
4705 "foo.exe",
4706 "--gtest_break_on_failure",
4707 "bar", // Unrecognized by Google Test.
4708 "--gtest_filter=b",
4709 NULL
4710 };
4711
4712 const char* argv2[] = {
4713 "foo.exe",
4714 "bar",
4715 NULL
4716 };
4717
4718 Flags flags;
4719 flags.break_on_failure = true;
4720 flags.filter = "b";
4721 GTEST_TEST_PARSING_FLAGS_(argv, argv2, flags);
4722 }
4723
4724 // Tests having a --gtest_list_tests flag
TEST_F(InitGoogleTestTest,ListTestsFlag)4725 TEST_F(InitGoogleTestTest, ListTestsFlag) {
4726 const char* argv[] = {
4727 "foo.exe",
4728 "--gtest_list_tests",
4729 NULL
4730 };
4731
4732 const char* argv2[] = {
4733 "foo.exe",
4734 NULL
4735 };
4736
4737 GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::ListTests(true));
4738 }
4739
4740 // Tests having a --gtest_list_tests flag with a "true" value
TEST_F(InitGoogleTestTest,ListTestsTrue)4741 TEST_F(InitGoogleTestTest, ListTestsTrue) {
4742 const char* argv[] = {
4743 "foo.exe",
4744 "--gtest_list_tests=1",
4745 NULL
4746 };
4747
4748 const char* argv2[] = {
4749 "foo.exe",
4750 NULL
4751 };
4752
4753 GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::ListTests(true));
4754 }
4755
4756 // Tests having a --gtest_list_tests flag with a "false" value
TEST_F(InitGoogleTestTest,ListTestsFalse)4757 TEST_F(InitGoogleTestTest, ListTestsFalse) {
4758 const char* argv[] = {
4759 "foo.exe",
4760 "--gtest_list_tests=0",
4761 NULL
4762 };
4763
4764 const char* argv2[] = {
4765 "foo.exe",
4766 NULL
4767 };
4768
4769 GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::ListTests(false));
4770 }
4771
4772 // Tests parsing --gtest_list_tests=f.
TEST_F(InitGoogleTestTest,ListTestsFalse_f)4773 TEST_F(InitGoogleTestTest, ListTestsFalse_f) {
4774 const char* argv[] = {
4775 "foo.exe",
4776 "--gtest_list_tests=f",
4777 NULL
4778 };
4779
4780 const char* argv2[] = {
4781 "foo.exe",
4782 NULL
4783 };
4784
4785 GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::ListTests(false));
4786 }
4787
4788 // Tests parsing --gtest_break_on_failure=F.
TEST_F(InitGoogleTestTest,ListTestsFalse_F)4789 TEST_F(InitGoogleTestTest, ListTestsFalse_F) {
4790 const char* argv[] = {
4791 "foo.exe",
4792 "--gtest_list_tests=F",
4793 NULL
4794 };
4795
4796 const char* argv2[] = {
4797 "foo.exe",
4798 NULL
4799 };
4800
4801 GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::ListTests(false));
4802 }
4803
4804 // Tests parsing --gtest_output (invalid).
TEST_F(InitGoogleTestTest,OutputEmpty)4805 TEST_F(InitGoogleTestTest, OutputEmpty) {
4806 const char* argv[] = {
4807 "foo.exe",
4808 "--gtest_output",
4809 NULL
4810 };
4811
4812 const char* argv2[] = {
4813 "foo.exe",
4814 "--gtest_output",
4815 NULL
4816 };
4817
4818 GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags());
4819 }
4820
4821 // Tests parsing --gtest_output=xml
TEST_F(InitGoogleTestTest,OutputXml)4822 TEST_F(InitGoogleTestTest, OutputXml) {
4823 const char* argv[] = {
4824 "foo.exe",
4825 "--gtest_output=xml",
4826 NULL
4827 };
4828
4829 const char* argv2[] = {
4830 "foo.exe",
4831 NULL
4832 };
4833
4834 GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::Output("xml"));
4835 }
4836
4837 // Tests parsing --gtest_output=xml:file
TEST_F(InitGoogleTestTest,OutputXmlFile)4838 TEST_F(InitGoogleTestTest, OutputXmlFile) {
4839 const char* argv[] = {
4840 "foo.exe",
4841 "--gtest_output=xml:file",
4842 NULL
4843 };
4844
4845 const char* argv2[] = {
4846 "foo.exe",
4847 NULL
4848 };
4849
4850 GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::Output("xml:file"));
4851 }
4852
4853 // Tests parsing --gtest_output=xml:directory/path/
TEST_F(InitGoogleTestTest,OutputXmlDirectory)4854 TEST_F(InitGoogleTestTest, OutputXmlDirectory) {
4855 const char* argv[] = {
4856 "foo.exe",
4857 "--gtest_output=xml:directory/path/",
4858 NULL
4859 };
4860
4861 const char* argv2[] = {
4862 "foo.exe",
4863 NULL
4864 };
4865
4866 GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::Output("xml:directory/path/"));
4867 }
4868
4869 // Tests having a --gtest_print_time flag
TEST_F(InitGoogleTestTest,PrintTimeFlag)4870 TEST_F(InitGoogleTestTest, PrintTimeFlag) {
4871 const char* argv[] = {
4872 "foo.exe",
4873 "--gtest_print_time",
4874 NULL
4875 };
4876
4877 const char* argv2[] = {
4878 "foo.exe",
4879 NULL
4880 };
4881
4882 GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::PrintTime(true));
4883 }
4884
4885 // Tests having a --gtest_print_time flag with a "true" value
TEST_F(InitGoogleTestTest,PrintTimeTrue)4886 TEST_F(InitGoogleTestTest, PrintTimeTrue) {
4887 const char* argv[] = {
4888 "foo.exe",
4889 "--gtest_print_time=1",
4890 NULL
4891 };
4892
4893 const char* argv2[] = {
4894 "foo.exe",
4895 NULL
4896 };
4897
4898 GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::PrintTime(true));
4899 }
4900
4901 // Tests having a --gtest_print_time flag with a "false" value
TEST_F(InitGoogleTestTest,PrintTimeFalse)4902 TEST_F(InitGoogleTestTest, PrintTimeFalse) {
4903 const char* argv[] = {
4904 "foo.exe",
4905 "--gtest_print_time=0",
4906 NULL
4907 };
4908
4909 const char* argv2[] = {
4910 "foo.exe",
4911 NULL
4912 };
4913
4914 GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::PrintTime(false));
4915 }
4916
4917 // Tests parsing --gtest_print_time=f.
TEST_F(InitGoogleTestTest,PrintTimeFalse_f)4918 TEST_F(InitGoogleTestTest, PrintTimeFalse_f) {
4919 const char* argv[] = {
4920 "foo.exe",
4921 "--gtest_print_time=f",
4922 NULL
4923 };
4924
4925 const char* argv2[] = {
4926 "foo.exe",
4927 NULL
4928 };
4929
4930 GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::PrintTime(false));
4931 }
4932
4933 // Tests parsing --gtest_print_time=F.
TEST_F(InitGoogleTestTest,PrintTimeFalse_F)4934 TEST_F(InitGoogleTestTest, PrintTimeFalse_F) {
4935 const char* argv[] = {
4936 "foo.exe",
4937 "--gtest_print_time=F",
4938 NULL
4939 };
4940
4941 const char* argv2[] = {
4942 "foo.exe",
4943 NULL
4944 };
4945
4946 GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::PrintTime(false));
4947 }
4948
4949 // Tests parsing --gtest_repeat=number
TEST_F(InitGoogleTestTest,Repeat)4950 TEST_F(InitGoogleTestTest, Repeat) {
4951 const char* argv[] = {
4952 "foo.exe",
4953 "--gtest_repeat=1000",
4954 NULL
4955 };
4956
4957 const char* argv2[] = {
4958 "foo.exe",
4959 NULL
4960 };
4961
4962 GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::Repeat(1000));
4963 }
4964
4965 // Tests having a --gtest_also_run_disabled_tests flag
TEST_F(InitGoogleTestTest,AlsoRunDisabledTestsFlag)4966 TEST_F(InitGoogleTestTest, AlsoRunDisabledTestsFlag) {
4967 const char* argv[] = {
4968 "foo.exe",
4969 "--gtest_also_run_disabled_tests",
4970 NULL
4971 };
4972
4973 const char* argv2[] = {
4974 "foo.exe",
4975 NULL
4976 };
4977
4978 GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::AlsoRunDisabledTests(true));
4979 }
4980
4981 // Tests having a --gtest_also_run_disabled_tests flag with a "true" value
TEST_F(InitGoogleTestTest,AlsoRunDisabledTestsTrue)4982 TEST_F(InitGoogleTestTest, AlsoRunDisabledTestsTrue) {
4983 const char* argv[] = {
4984 "foo.exe",
4985 "--gtest_also_run_disabled_tests=1",
4986 NULL
4987 };
4988
4989 const char* argv2[] = {
4990 "foo.exe",
4991 NULL
4992 };
4993
4994 GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::AlsoRunDisabledTests(true));
4995 }
4996
4997 // Tests having a --gtest_also_run_disabled_tests flag with a "false" value
TEST_F(InitGoogleTestTest,AlsoRunDisabledTestsFalse)4998 TEST_F(InitGoogleTestTest, AlsoRunDisabledTestsFalse) {
4999 const char* argv[] = {
5000 "foo.exe",
5001 "--gtest_also_run_disabled_tests=0",
5002 NULL
5003 };
5004
5005 const char* argv2[] = {
5006 "foo.exe",
5007 NULL
5008 };
5009
5010 GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::AlsoRunDisabledTests(false));
5011 }
5012
5013
5014 // Tests parsing --gtest_throw_on_failure.
TEST_F(InitGoogleTestTest,ThrowOnFailureNoDef)5015 TEST_F(InitGoogleTestTest, ThrowOnFailureNoDef) {
5016 const char* argv[] = {
5017 "foo.exe",
5018 "--gtest_throw_on_failure",
5019 NULL
5020 };
5021
5022 const char* argv2[] = {
5023 "foo.exe",
5024 NULL
5025 };
5026
5027 GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::ThrowOnFailure(true));
5028 }
5029
5030 // Tests parsing --gtest_throw_on_failure=0.
TEST_F(InitGoogleTestTest,ThrowOnFailureFalse_0)5031 TEST_F(InitGoogleTestTest, ThrowOnFailureFalse_0) {
5032 const char* argv[] = {
5033 "foo.exe",
5034 "--gtest_throw_on_failure=0",
5035 NULL
5036 };
5037
5038 const char* argv2[] = {
5039 "foo.exe",
5040 NULL
5041 };
5042
5043 GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::ThrowOnFailure(false));
5044 }
5045
5046 // Tests parsing a --gtest_throw_on_failure flag that has a "true"
5047 // definition.
TEST_F(InitGoogleTestTest,ThrowOnFailureTrue)5048 TEST_F(InitGoogleTestTest, ThrowOnFailureTrue) {
5049 const char* argv[] = {
5050 "foo.exe",
5051 "--gtest_throw_on_failure=1",
5052 NULL
5053 };
5054
5055 const char* argv2[] = {
5056 "foo.exe",
5057 NULL
5058 };
5059
5060 GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::ThrowOnFailure(true));
5061 }
5062
5063 #if GTEST_OS_WINDOWS
5064 // Tests parsing wide strings.
TEST_F(InitGoogleTestTest,WideStrings)5065 TEST_F(InitGoogleTestTest, WideStrings) {
5066 const wchar_t* argv[] = {
5067 L"foo.exe",
5068 L"--gtest_filter=Foo*",
5069 L"--gtest_list_tests=1",
5070 L"--gtest_break_on_failure",
5071 L"--non_gtest_flag",
5072 NULL
5073 };
5074
5075 const wchar_t* argv2[] = {
5076 L"foo.exe",
5077 L"--non_gtest_flag",
5078 NULL
5079 };
5080
5081 Flags expected_flags;
5082 expected_flags.break_on_failure = true;
5083 expected_flags.filter = "Foo*";
5084 expected_flags.list_tests = true;
5085
5086 GTEST_TEST_PARSING_FLAGS_(argv, argv2, expected_flags);
5087 }
5088 #endif // GTEST_OS_WINDOWS
5089
5090 // Tests current_test_info() in UnitTest.
5091 class CurrentTestInfoTest : public Test {
5092 protected:
5093 // Tests that current_test_info() returns NULL before the first test in
5094 // the test case is run.
SetUpTestCase()5095 static void SetUpTestCase() {
5096 // There should be no tests running at this point.
5097 const TestInfo* test_info =
5098 UnitTest::GetInstance()->current_test_info();
5099 EXPECT_EQ(NULL, test_info)
5100 << "There should be no tests running at this point.";
5101 }
5102
5103 // Tests that current_test_info() returns NULL after the last test in
5104 // the test case has run.
TearDownTestCase()5105 static void TearDownTestCase() {
5106 const TestInfo* test_info =
5107 UnitTest::GetInstance()->current_test_info();
5108 EXPECT_EQ(NULL, test_info)
5109 << "There should be no tests running at this point.";
5110 }
5111 };
5112
5113 // Tests that current_test_info() returns TestInfo for currently running
5114 // test by checking the expected test name against the actual one.
TEST_F(CurrentTestInfoTest,WorksForFirstTestInATestCase)5115 TEST_F(CurrentTestInfoTest, WorksForFirstTestInATestCase) {
5116 const TestInfo* test_info =
5117 UnitTest::GetInstance()->current_test_info();
5118 ASSERT_TRUE(NULL != test_info)
5119 << "There is a test running so we should have a valid TestInfo.";
5120 EXPECT_STREQ("CurrentTestInfoTest", test_info->test_case_name())
5121 << "Expected the name of the currently running test case.";
5122 EXPECT_STREQ("WorksForFirstTestInATestCase", test_info->name())
5123 << "Expected the name of the currently running test.";
5124 }
5125
5126 // Tests that current_test_info() returns TestInfo for currently running
5127 // test by checking the expected test name against the actual one. We
5128 // use this test to see that the TestInfo object actually changed from
5129 // the previous invocation.
TEST_F(CurrentTestInfoTest,WorksForSecondTestInATestCase)5130 TEST_F(CurrentTestInfoTest, WorksForSecondTestInATestCase) {
5131 const TestInfo* test_info =
5132 UnitTest::GetInstance()->current_test_info();
5133 ASSERT_TRUE(NULL != test_info)
5134 << "There is a test running so we should have a valid TestInfo.";
5135 EXPECT_STREQ("CurrentTestInfoTest", test_info->test_case_name())
5136 << "Expected the name of the currently running test case.";
5137 EXPECT_STREQ("WorksForSecondTestInATestCase", test_info->name())
5138 << "Expected the name of the currently running test.";
5139 }
5140
5141 } // namespace testing
5142
5143 // These two lines test that we can define tests in a namespace that
5144 // has the name "testing" and is nested in another namespace.
5145 namespace my_namespace {
5146 namespace testing {
5147
5148 // Makes sure that TEST knows to use ::testing::Test instead of
5149 // ::my_namespace::testing::Test.
5150 class Test {};
5151
5152 // Makes sure that an assertion knows to use ::testing::Message instead of
5153 // ::my_namespace::testing::Message.
5154 class Message {};
5155
5156 // Makes sure that an assertion knows to use
5157 // ::testing::AssertionResult instead of
5158 // ::my_namespace::testing::AssertionResult.
5159 class AssertionResult {};
5160
5161 // Tests that an assertion that should succeed works as expected.
TEST(NestedTestingNamespaceTest,Success)5162 TEST(NestedTestingNamespaceTest, Success) {
5163 EXPECT_EQ(1, 1) << "This shouldn't fail.";
5164 }
5165
5166 // Tests that an assertion that should fail works as expected.
TEST(NestedTestingNamespaceTest,Failure)5167 TEST(NestedTestingNamespaceTest, Failure) {
5168 EXPECT_FATAL_FAILURE(FAIL() << "This failure is expected.",
5169 "This failure is expected.");
5170 }
5171
5172 } // namespace testing
5173 } // namespace my_namespace
5174
5175 // Tests that one can call superclass SetUp and TearDown methods--
5176 // that is, that they are not private.
5177 // No tests are based on this fixture; the test "passes" if it compiles
5178 // successfully.
5179 class ProtectedFixtureMethodsTest : public Test {
5180 protected:
SetUp()5181 virtual void SetUp() {
5182 Test::SetUp();
5183 }
TearDown()5184 virtual void TearDown() {
5185 Test::TearDown();
5186 }
5187 };
5188
5189 // StreamingAssertionsTest tests the streaming versions of a representative
5190 // sample of assertions.
TEST(StreamingAssertionsTest,Unconditional)5191 TEST(StreamingAssertionsTest, Unconditional) {
5192 SUCCEED() << "expected success";
5193 EXPECT_NONFATAL_FAILURE(ADD_FAILURE() << "expected failure",
5194 "expected failure");
5195 EXPECT_FATAL_FAILURE(FAIL() << "expected failure",
5196 "expected failure");
5197 }
5198
TEST(StreamingAssertionsTest,Truth)5199 TEST(StreamingAssertionsTest, Truth) {
5200 EXPECT_TRUE(true) << "unexpected failure";
5201 ASSERT_TRUE(true) << "unexpected failure";
5202 EXPECT_NONFATAL_FAILURE(EXPECT_TRUE(false) << "expected failure",
5203 "expected failure");
5204 EXPECT_FATAL_FAILURE(ASSERT_TRUE(false) << "expected failure",
5205 "expected failure");
5206 }
5207
TEST(StreamingAssertionsTest,Truth2)5208 TEST(StreamingAssertionsTest, Truth2) {
5209 EXPECT_FALSE(false) << "unexpected failure";
5210 ASSERT_FALSE(false) << "unexpected failure";
5211 EXPECT_NONFATAL_FAILURE(EXPECT_FALSE(true) << "expected failure",
5212 "expected failure");
5213 EXPECT_FATAL_FAILURE(ASSERT_FALSE(true) << "expected failure",
5214 "expected failure");
5215 }
5216
TEST(StreamingAssertionsTest,IntegerEquals)5217 TEST(StreamingAssertionsTest, IntegerEquals) {
5218 EXPECT_EQ(1, 1) << "unexpected failure";
5219 ASSERT_EQ(1, 1) << "unexpected failure";
5220 EXPECT_NONFATAL_FAILURE(EXPECT_EQ(1, 2) << "expected failure",
5221 "expected failure");
5222 EXPECT_FATAL_FAILURE(ASSERT_EQ(1, 2) << "expected failure",
5223 "expected failure");
5224 }
5225
TEST(StreamingAssertionsTest,IntegerLessThan)5226 TEST(StreamingAssertionsTest, IntegerLessThan) {
5227 EXPECT_LT(1, 2) << "unexpected failure";
5228 ASSERT_LT(1, 2) << "unexpected failure";
5229 EXPECT_NONFATAL_FAILURE(EXPECT_LT(2, 1) << "expected failure",
5230 "expected failure");
5231 EXPECT_FATAL_FAILURE(ASSERT_LT(2, 1) << "expected failure",
5232 "expected failure");
5233 }
5234
TEST(StreamingAssertionsTest,StringsEqual)5235 TEST(StreamingAssertionsTest, StringsEqual) {
5236 EXPECT_STREQ("foo", "foo") << "unexpected failure";
5237 ASSERT_STREQ("foo", "foo") << "unexpected failure";
5238 EXPECT_NONFATAL_FAILURE(EXPECT_STREQ("foo", "bar") << "expected failure",
5239 "expected failure");
5240 EXPECT_FATAL_FAILURE(ASSERT_STREQ("foo", "bar") << "expected failure",
5241 "expected failure");
5242 }
5243
TEST(StreamingAssertionsTest,StringsNotEqual)5244 TEST(StreamingAssertionsTest, StringsNotEqual) {
5245 EXPECT_STRNE("foo", "bar") << "unexpected failure";
5246 ASSERT_STRNE("foo", "bar") << "unexpected failure";
5247 EXPECT_NONFATAL_FAILURE(EXPECT_STRNE("foo", "foo") << "expected failure",
5248 "expected failure");
5249 EXPECT_FATAL_FAILURE(ASSERT_STRNE("foo", "foo") << "expected failure",
5250 "expected failure");
5251 }
5252
TEST(StreamingAssertionsTest,StringsEqualIgnoringCase)5253 TEST(StreamingAssertionsTest, StringsEqualIgnoringCase) {
5254 EXPECT_STRCASEEQ("foo", "FOO") << "unexpected failure";
5255 ASSERT_STRCASEEQ("foo", "FOO") << "unexpected failure";
5256 EXPECT_NONFATAL_FAILURE(EXPECT_STRCASEEQ("foo", "bar") << "expected failure",
5257 "expected failure");
5258 EXPECT_FATAL_FAILURE(ASSERT_STRCASEEQ("foo", "bar") << "expected failure",
5259 "expected failure");
5260 }
5261
TEST(StreamingAssertionsTest,StringNotEqualIgnoringCase)5262 TEST(StreamingAssertionsTest, StringNotEqualIgnoringCase) {
5263 EXPECT_STRCASENE("foo", "bar") << "unexpected failure";
5264 ASSERT_STRCASENE("foo", "bar") << "unexpected failure";
5265 EXPECT_NONFATAL_FAILURE(EXPECT_STRCASENE("foo", "FOO") << "expected failure",
5266 "expected failure");
5267 EXPECT_FATAL_FAILURE(ASSERT_STRCASENE("bar", "BAR") << "expected failure",
5268 "expected failure");
5269 }
5270
TEST(StreamingAssertionsTest,FloatingPointEquals)5271 TEST(StreamingAssertionsTest, FloatingPointEquals) {
5272 EXPECT_FLOAT_EQ(1.0, 1.0) << "unexpected failure";
5273 ASSERT_FLOAT_EQ(1.0, 1.0) << "unexpected failure";
5274 EXPECT_NONFATAL_FAILURE(EXPECT_FLOAT_EQ(0.0, 1.0) << "expected failure",
5275 "expected failure");
5276 EXPECT_FATAL_FAILURE(ASSERT_FLOAT_EQ(0.0, 1.0) << "expected failure",
5277 "expected failure");
5278 }
5279
5280 #if GTEST_HAS_EXCEPTIONS
5281
TEST(StreamingAssertionsTest,Throw)5282 TEST(StreamingAssertionsTest, Throw) {
5283 EXPECT_THROW(ThrowAnInteger(), int) << "unexpected failure";
5284 ASSERT_THROW(ThrowAnInteger(), int) << "unexpected failure";
5285 EXPECT_NONFATAL_FAILURE(EXPECT_THROW(ThrowAnInteger(), bool) <<
5286 "expected failure", "expected failure");
5287 EXPECT_FATAL_FAILURE(ASSERT_THROW(ThrowAnInteger(), bool) <<
5288 "expected failure", "expected failure");
5289 }
5290
TEST(StreamingAssertionsTest,NoThrow)5291 TEST(StreamingAssertionsTest, NoThrow) {
5292 EXPECT_NO_THROW(ThrowNothing()) << "unexpected failure";
5293 ASSERT_NO_THROW(ThrowNothing()) << "unexpected failure";
5294 EXPECT_NONFATAL_FAILURE(EXPECT_NO_THROW(ThrowAnInteger()) <<
5295 "expected failure", "expected failure");
5296 EXPECT_FATAL_FAILURE(ASSERT_NO_THROW(ThrowAnInteger()) <<
5297 "expected failure", "expected failure");
5298 }
5299
TEST(StreamingAssertionsTest,AnyThrow)5300 TEST(StreamingAssertionsTest, AnyThrow) {
5301 EXPECT_ANY_THROW(ThrowAnInteger()) << "unexpected failure";
5302 ASSERT_ANY_THROW(ThrowAnInteger()) << "unexpected failure";
5303 EXPECT_NONFATAL_FAILURE(EXPECT_ANY_THROW(ThrowNothing()) <<
5304 "expected failure", "expected failure");
5305 EXPECT_FATAL_FAILURE(ASSERT_ANY_THROW(ThrowNothing()) <<
5306 "expected failure", "expected failure");
5307 }
5308
5309 #endif // GTEST_HAS_EXCEPTIONS
5310
5311 // Tests that Google Test correctly decides whether to use colors in the output.
5312
TEST(ColoredOutputTest,UsesColorsWhenGTestColorFlagIsYes)5313 TEST(ColoredOutputTest, UsesColorsWhenGTestColorFlagIsYes) {
5314 GTEST_FLAG(color) = "yes";
5315
5316 SetEnv("TERM", "xterm"); // TERM supports colors.
5317 EXPECT_TRUE(ShouldUseColor(true)); // Stdout is a TTY.
5318 EXPECT_TRUE(ShouldUseColor(false)); // Stdout is not a TTY.
5319
5320 SetEnv("TERM", "dumb"); // TERM doesn't support colors.
5321 EXPECT_TRUE(ShouldUseColor(true)); // Stdout is a TTY.
5322 EXPECT_TRUE(ShouldUseColor(false)); // Stdout is not a TTY.
5323 }
5324
TEST(ColoredOutputTest,UsesColorsWhenGTestColorFlagIsAliasOfYes)5325 TEST(ColoredOutputTest, UsesColorsWhenGTestColorFlagIsAliasOfYes) {
5326 SetEnv("TERM", "dumb"); // TERM doesn't support colors.
5327
5328 GTEST_FLAG(color) = "True";
5329 EXPECT_TRUE(ShouldUseColor(false)); // Stdout is not a TTY.
5330
5331 GTEST_FLAG(color) = "t";
5332 EXPECT_TRUE(ShouldUseColor(false)); // Stdout is not a TTY.
5333
5334 GTEST_FLAG(color) = "1";
5335 EXPECT_TRUE(ShouldUseColor(false)); // Stdout is not a TTY.
5336 }
5337
TEST(ColoredOutputTest,UsesNoColorWhenGTestColorFlagIsNo)5338 TEST(ColoredOutputTest, UsesNoColorWhenGTestColorFlagIsNo) {
5339 GTEST_FLAG(color) = "no";
5340
5341 SetEnv("TERM", "xterm"); // TERM supports colors.
5342 EXPECT_FALSE(ShouldUseColor(true)); // Stdout is a TTY.
5343 EXPECT_FALSE(ShouldUseColor(false)); // Stdout is not a TTY.
5344
5345 SetEnv("TERM", "dumb"); // TERM doesn't support colors.
5346 EXPECT_FALSE(ShouldUseColor(true)); // Stdout is a TTY.
5347 EXPECT_FALSE(ShouldUseColor(false)); // Stdout is not a TTY.
5348 }
5349
TEST(ColoredOutputTest,UsesNoColorWhenGTestColorFlagIsInvalid)5350 TEST(ColoredOutputTest, UsesNoColorWhenGTestColorFlagIsInvalid) {
5351 SetEnv("TERM", "xterm"); // TERM supports colors.
5352
5353 GTEST_FLAG(color) = "F";
5354 EXPECT_FALSE(ShouldUseColor(true)); // Stdout is a TTY.
5355
5356 GTEST_FLAG(color) = "0";
5357 EXPECT_FALSE(ShouldUseColor(true)); // Stdout is a TTY.
5358
5359 GTEST_FLAG(color) = "unknown";
5360 EXPECT_FALSE(ShouldUseColor(true)); // Stdout is a TTY.
5361 }
5362
TEST(ColoredOutputTest,UsesColorsWhenStdoutIsTty)5363 TEST(ColoredOutputTest, UsesColorsWhenStdoutIsTty) {
5364 GTEST_FLAG(color) = "auto";
5365
5366 SetEnv("TERM", "xterm"); // TERM supports colors.
5367 EXPECT_FALSE(ShouldUseColor(false)); // Stdout is not a TTY.
5368 EXPECT_TRUE(ShouldUseColor(true)); // Stdout is a TTY.
5369 }
5370
TEST(ColoredOutputTest,UsesColorsWhenTermSupportsColors)5371 TEST(ColoredOutputTest, UsesColorsWhenTermSupportsColors) {
5372 GTEST_FLAG(color) = "auto";
5373
5374 #if GTEST_OS_WINDOWS
5375 // On Windows, we ignore the TERM variable as it's usually not set.
5376
5377 SetEnv("TERM", "dumb");
5378 EXPECT_TRUE(ShouldUseColor(true)); // Stdout is a TTY.
5379
5380 SetEnv("TERM", "");
5381 EXPECT_TRUE(ShouldUseColor(true)); // Stdout is a TTY.
5382
5383 SetEnv("TERM", "xterm");
5384 EXPECT_TRUE(ShouldUseColor(true)); // Stdout is a TTY.
5385 #else
5386 // On non-Windows platforms, we rely on TERM to determine if the
5387 // terminal supports colors.
5388
5389 SetEnv("TERM", "dumb"); // TERM doesn't support colors.
5390 EXPECT_FALSE(ShouldUseColor(true)); // Stdout is a TTY.
5391
5392 SetEnv("TERM", "emacs"); // TERM doesn't support colors.
5393 EXPECT_FALSE(ShouldUseColor(true)); // Stdout is a TTY.
5394
5395 SetEnv("TERM", "vt100"); // TERM doesn't support colors.
5396 EXPECT_FALSE(ShouldUseColor(true)); // Stdout is a TTY.
5397
5398 SetEnv("TERM", "xterm-mono"); // TERM doesn't support colors.
5399 EXPECT_FALSE(ShouldUseColor(true)); // Stdout is a TTY.
5400
5401 SetEnv("TERM", "xterm"); // TERM supports colors.
5402 EXPECT_TRUE(ShouldUseColor(true)); // Stdout is a TTY.
5403
5404 SetEnv("TERM", "xterm-color"); // TERM supports colors.
5405 EXPECT_TRUE(ShouldUseColor(true)); // Stdout is a TTY.
5406 #endif // GTEST_OS_WINDOWS
5407 }
5408
5409 // Verifies that StaticAssertTypeEq works in a namespace scope.
5410
5411 static bool dummy1 = StaticAssertTypeEq<bool, bool>();
5412 static bool dummy2 = StaticAssertTypeEq<const int, const int>();
5413
5414 // Verifies that StaticAssertTypeEq works in a class.
5415
5416 template <typename T>
5417 class StaticAssertTypeEqTestHelper {
5418 public:
StaticAssertTypeEqTestHelper()5419 StaticAssertTypeEqTestHelper() { StaticAssertTypeEq<bool, T>(); }
5420 };
5421
TEST(StaticAssertTypeEqTest,WorksInClass)5422 TEST(StaticAssertTypeEqTest, WorksInClass) {
5423 StaticAssertTypeEqTestHelper<bool>();
5424 }
5425
5426 // Verifies that StaticAssertTypeEq works inside a function.
5427
5428 typedef int IntAlias;
5429
TEST(StaticAssertTypeEqTest,CompilesForEqualTypes)5430 TEST(StaticAssertTypeEqTest, CompilesForEqualTypes) {
5431 StaticAssertTypeEq<int, IntAlias>();
5432 StaticAssertTypeEq<int*, IntAlias*>();
5433 }
5434
TEST(ThreadLocalTest,DefaultConstructor)5435 TEST(ThreadLocalTest, DefaultConstructor) {
5436 ThreadLocal<int> t1;
5437 EXPECT_EQ(0, t1.get());
5438
5439 ThreadLocal<void*> t2;
5440 EXPECT_TRUE(t2.get() == NULL);
5441 }
5442
TEST(ThreadLocalTest,Init)5443 TEST(ThreadLocalTest, Init) {
5444 ThreadLocal<int> t1(123);
5445 EXPECT_EQ(123, t1.get());
5446
5447 int i = 0;
5448 ThreadLocal<int*> t2(&i);
5449 EXPECT_EQ(&i, t2.get());
5450 }
5451
TEST(GetCurrentOsStackTraceExceptTopTest,ReturnsTheStackTrace)5452 TEST(GetCurrentOsStackTraceExceptTopTest, ReturnsTheStackTrace) {
5453 testing::UnitTest* const unit_test = testing::UnitTest::GetInstance();
5454
5455 // We don't have a stack walker in Google Test yet.
5456 EXPECT_STREQ("", GetCurrentOsStackTraceExceptTop(unit_test, 0).c_str());
5457 EXPECT_STREQ("", GetCurrentOsStackTraceExceptTop(unit_test, 1).c_str());
5458 }
5459