1 // Copyright 2008, 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 // This file tests the internal cross-platform support utilities.
31 #include <stdio.h>
32
33 #include "gtest/internal/gtest-port.h"
34
35 #if GTEST_OS_MAC
36 #include <time.h>
37 #endif // GTEST_OS_MAC
38
39 #include <list>
40 #include <memory>
41 #include <utility> // For std::pair and std::make_pair.
42 #include <vector>
43
44 #include "gtest/gtest.h"
45 #include "gtest/gtest-spi.h"
46 #include "src/gtest-internal-inl.h"
47
48 using std::make_pair;
49 using std::pair;
50
51 namespace testing {
52 namespace internal {
53
TEST(IsXDigitTest,WorksForNarrowAscii)54 TEST(IsXDigitTest, WorksForNarrowAscii) {
55 EXPECT_TRUE(IsXDigit('0'));
56 EXPECT_TRUE(IsXDigit('9'));
57 EXPECT_TRUE(IsXDigit('A'));
58 EXPECT_TRUE(IsXDigit('F'));
59 EXPECT_TRUE(IsXDigit('a'));
60 EXPECT_TRUE(IsXDigit('f'));
61
62 EXPECT_FALSE(IsXDigit('-'));
63 EXPECT_FALSE(IsXDigit('g'));
64 EXPECT_FALSE(IsXDigit('G'));
65 }
66
TEST(IsXDigitTest,ReturnsFalseForNarrowNonAscii)67 TEST(IsXDigitTest, ReturnsFalseForNarrowNonAscii) {
68 EXPECT_FALSE(IsXDigit(static_cast<char>('\x80')));
69 EXPECT_FALSE(IsXDigit(static_cast<char>('0' | '\x80')));
70 }
71
TEST(IsXDigitTest,WorksForWideAscii)72 TEST(IsXDigitTest, WorksForWideAscii) {
73 EXPECT_TRUE(IsXDigit(L'0'));
74 EXPECT_TRUE(IsXDigit(L'9'));
75 EXPECT_TRUE(IsXDigit(L'A'));
76 EXPECT_TRUE(IsXDigit(L'F'));
77 EXPECT_TRUE(IsXDigit(L'a'));
78 EXPECT_TRUE(IsXDigit(L'f'));
79
80 EXPECT_FALSE(IsXDigit(L'-'));
81 EXPECT_FALSE(IsXDigit(L'g'));
82 EXPECT_FALSE(IsXDigit(L'G'));
83 }
84
TEST(IsXDigitTest,ReturnsFalseForWideNonAscii)85 TEST(IsXDigitTest, ReturnsFalseForWideNonAscii) {
86 EXPECT_FALSE(IsXDigit(static_cast<wchar_t>(0x80)));
87 EXPECT_FALSE(IsXDigit(static_cast<wchar_t>(L'0' | 0x80)));
88 EXPECT_FALSE(IsXDigit(static_cast<wchar_t>(L'0' | 0x100)));
89 }
90
91 class Base {
92 public:
93 // Copy constructor and assignment operator do exactly what we need, so we
94 // use them.
Base()95 Base() : member_(0) {}
Base(int n)96 explicit Base(int n) : member_(n) {}
~Base()97 virtual ~Base() {}
member()98 int member() { return member_; }
99
100 private:
101 int member_;
102 };
103
104 class Derived : public Base {
105 public:
Derived(int n)106 explicit Derived(int n) : Base(n) {}
107 };
108
TEST(ImplicitCastTest,ConvertsPointers)109 TEST(ImplicitCastTest, ConvertsPointers) {
110 Derived derived(0);
111 EXPECT_TRUE(&derived == ::testing::internal::ImplicitCast_<Base*>(&derived));
112 }
113
TEST(ImplicitCastTest,CanUseInheritance)114 TEST(ImplicitCastTest, CanUseInheritance) {
115 Derived derived(1);
116 Base base = ::testing::internal::ImplicitCast_<Base>(derived);
117 EXPECT_EQ(derived.member(), base.member());
118 }
119
120 class Castable {
121 public:
Castable(bool * converted)122 explicit Castable(bool* converted) : converted_(converted) {}
operator Base()123 operator Base() {
124 *converted_ = true;
125 return Base();
126 }
127
128 private:
129 bool* converted_;
130 };
131
TEST(ImplicitCastTest,CanUseNonConstCastOperator)132 TEST(ImplicitCastTest, CanUseNonConstCastOperator) {
133 bool converted = false;
134 Castable castable(&converted);
135 Base base = ::testing::internal::ImplicitCast_<Base>(castable);
136 EXPECT_TRUE(converted);
137 }
138
139 class ConstCastable {
140 public:
ConstCastable(bool * converted)141 explicit ConstCastable(bool* converted) : converted_(converted) {}
operator Base() const142 operator Base() const {
143 *converted_ = true;
144 return Base();
145 }
146
147 private:
148 bool* converted_;
149 };
150
TEST(ImplicitCastTest,CanUseConstCastOperatorOnConstValues)151 TEST(ImplicitCastTest, CanUseConstCastOperatorOnConstValues) {
152 bool converted = false;
153 const ConstCastable const_castable(&converted);
154 Base base = ::testing::internal::ImplicitCast_<Base>(const_castable);
155 EXPECT_TRUE(converted);
156 }
157
158 class ConstAndNonConstCastable {
159 public:
ConstAndNonConstCastable(bool * converted,bool * const_converted)160 ConstAndNonConstCastable(bool* converted, bool* const_converted)
161 : converted_(converted), const_converted_(const_converted) {}
operator Base()162 operator Base() {
163 *converted_ = true;
164 return Base();
165 }
operator Base() const166 operator Base() const {
167 *const_converted_ = true;
168 return Base();
169 }
170
171 private:
172 bool* converted_;
173 bool* const_converted_;
174 };
175
TEST(ImplicitCastTest,CanSelectBetweenConstAndNonConstCasrAppropriately)176 TEST(ImplicitCastTest, CanSelectBetweenConstAndNonConstCasrAppropriately) {
177 bool converted = false;
178 bool const_converted = false;
179 ConstAndNonConstCastable castable(&converted, &const_converted);
180 Base base = ::testing::internal::ImplicitCast_<Base>(castable);
181 EXPECT_TRUE(converted);
182 EXPECT_FALSE(const_converted);
183
184 converted = false;
185 const_converted = false;
186 const ConstAndNonConstCastable const_castable(&converted, &const_converted);
187 base = ::testing::internal::ImplicitCast_<Base>(const_castable);
188 EXPECT_FALSE(converted);
189 EXPECT_TRUE(const_converted);
190 }
191
192 class To {
193 public:
To(bool * converted)194 To(bool* converted) { *converted = true; } // NOLINT
195 };
196
TEST(ImplicitCastTest,CanUseImplicitConstructor)197 TEST(ImplicitCastTest, CanUseImplicitConstructor) {
198 bool converted = false;
199 To to = ::testing::internal::ImplicitCast_<To>(&converted);
200 (void)to;
201 EXPECT_TRUE(converted);
202 }
203
TEST(GtestCheckSyntaxTest,BehavesLikeASingleStatement)204 TEST(GtestCheckSyntaxTest, BehavesLikeASingleStatement) {
205 if (AlwaysFalse())
206 GTEST_CHECK_(false) << "This should never be executed; "
207 "It's a compilation test only.";
208
209 if (AlwaysTrue())
210 GTEST_CHECK_(true);
211 else
212 ; // NOLINT
213
214 if (AlwaysFalse())
215 ; // NOLINT
216 else
217 GTEST_CHECK_(true) << "";
218 }
219
TEST(GtestCheckSyntaxTest,WorksWithSwitch)220 TEST(GtestCheckSyntaxTest, WorksWithSwitch) {
221 switch (0) {
222 case 1:
223 break;
224 default:
225 GTEST_CHECK_(true);
226 }
227
228 switch (0)
229 case 0:
230 GTEST_CHECK_(true) << "Check failed in switch case";
231 }
232
233 // Verifies behavior of FormatFileLocation.
TEST(FormatFileLocationTest,FormatsFileLocation)234 TEST(FormatFileLocationTest, FormatsFileLocation) {
235 EXPECT_PRED_FORMAT2(IsSubstring, "foo.cc", FormatFileLocation("foo.cc", 42));
236 EXPECT_PRED_FORMAT2(IsSubstring, "42", FormatFileLocation("foo.cc", 42));
237 }
238
TEST(FormatFileLocationTest,FormatsUnknownFile)239 TEST(FormatFileLocationTest, FormatsUnknownFile) {
240 EXPECT_PRED_FORMAT2(IsSubstring, "unknown file",
241 FormatFileLocation(nullptr, 42));
242 EXPECT_PRED_FORMAT2(IsSubstring, "42", FormatFileLocation(nullptr, 42));
243 }
244
TEST(FormatFileLocationTest,FormatsUknownLine)245 TEST(FormatFileLocationTest, FormatsUknownLine) {
246 EXPECT_EQ("foo.cc:", FormatFileLocation("foo.cc", -1));
247 }
248
TEST(FormatFileLocationTest,FormatsUknownFileAndLine)249 TEST(FormatFileLocationTest, FormatsUknownFileAndLine) {
250 EXPECT_EQ("unknown file:", FormatFileLocation(nullptr, -1));
251 }
252
253 // Verifies behavior of FormatCompilerIndependentFileLocation.
TEST(FormatCompilerIndependentFileLocationTest,FormatsFileLocation)254 TEST(FormatCompilerIndependentFileLocationTest, FormatsFileLocation) {
255 EXPECT_EQ("foo.cc:42", FormatCompilerIndependentFileLocation("foo.cc", 42));
256 }
257
TEST(FormatCompilerIndependentFileLocationTest,FormatsUknownFile)258 TEST(FormatCompilerIndependentFileLocationTest, FormatsUknownFile) {
259 EXPECT_EQ("unknown file:42",
260 FormatCompilerIndependentFileLocation(nullptr, 42));
261 }
262
TEST(FormatCompilerIndependentFileLocationTest,FormatsUknownLine)263 TEST(FormatCompilerIndependentFileLocationTest, FormatsUknownLine) {
264 EXPECT_EQ("foo.cc", FormatCompilerIndependentFileLocation("foo.cc", -1));
265 }
266
TEST(FormatCompilerIndependentFileLocationTest,FormatsUknownFileAndLine)267 TEST(FormatCompilerIndependentFileLocationTest, FormatsUknownFileAndLine) {
268 EXPECT_EQ("unknown file", FormatCompilerIndependentFileLocation(nullptr, -1));
269 }
270
271 #if GTEST_OS_LINUX || GTEST_OS_MAC || GTEST_OS_QNX || GTEST_OS_FUCHSIA || \
272 GTEST_OS_DRAGONFLY || GTEST_OS_FREEBSD || GTEST_OS_GNU_KFREEBSD || \
273 GTEST_OS_NETBSD || GTEST_OS_OPENBSD
ThreadFunc(void * data)274 void* ThreadFunc(void* data) {
275 internal::Mutex* mutex = static_cast<internal::Mutex*>(data);
276 mutex->Lock();
277 mutex->Unlock();
278 return nullptr;
279 }
280
TEST(GetThreadCountTest,ReturnsCorrectValue)281 TEST(GetThreadCountTest, ReturnsCorrectValue) {
282 const size_t starting_count = GetThreadCount();
283 pthread_t thread_id;
284
285 internal::Mutex mutex;
286 {
287 internal::MutexLock lock(&mutex);
288 pthread_attr_t attr;
289 ASSERT_EQ(0, pthread_attr_init(&attr));
290 ASSERT_EQ(0, pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_JOINABLE));
291
292 const int status = pthread_create(&thread_id, &attr, &ThreadFunc, &mutex);
293 ASSERT_EQ(0, pthread_attr_destroy(&attr));
294 ASSERT_EQ(0, status);
295 EXPECT_EQ(starting_count + 1, GetThreadCount());
296 }
297
298 void* dummy;
299 ASSERT_EQ(0, pthread_join(thread_id, &dummy));
300
301 // The OS may not immediately report the updated thread count after
302 // joining a thread, causing flakiness in this test. To counter that, we
303 // wait for up to .5 seconds for the OS to report the correct value.
304 for (int i = 0; i < 5; ++i) {
305 if (GetThreadCount() == starting_count) break;
306
307 SleepMilliseconds(100);
308 }
309
310 EXPECT_EQ(starting_count, GetThreadCount());
311 }
312 #else
TEST(GetThreadCountTest,ReturnsZeroWhenUnableToCountThreads)313 TEST(GetThreadCountTest, ReturnsZeroWhenUnableToCountThreads) {
314 EXPECT_EQ(0U, GetThreadCount());
315 }
316 #endif // GTEST_OS_LINUX || GTEST_OS_MAC || GTEST_OS_QNX || GTEST_OS_FUCHSIA
317
TEST(GtestCheckDeathTest,DiesWithCorrectOutputOnFailure)318 TEST(GtestCheckDeathTest, DiesWithCorrectOutputOnFailure) {
319 const bool a_false_condition = false;
320 const char regex[] =
321 #ifdef _MSC_VER
322 "googletest-port-test\\.cc\\(\\d+\\):"
323 #elif GTEST_USES_POSIX_RE
324 "googletest-port-test\\.cc:[0-9]+"
325 #else
326 "googletest-port-test\\.cc:\\d+"
327 #endif // _MSC_VER
328 ".*a_false_condition.*Extra info.*";
329
330 EXPECT_DEATH_IF_SUPPORTED(GTEST_CHECK_(a_false_condition) << "Extra info",
331 regex);
332 }
333
334 #if GTEST_HAS_DEATH_TEST
335
TEST(GtestCheckDeathTest,LivesSilentlyOnSuccess)336 TEST(GtestCheckDeathTest, LivesSilentlyOnSuccess) {
337 EXPECT_EXIT(
338 {
339 GTEST_CHECK_(true) << "Extra info";
340 ::std::cerr << "Success\n";
341 exit(0);
342 },
343 ::testing::ExitedWithCode(0), "Success");
344 }
345
346 #endif // GTEST_HAS_DEATH_TEST
347
348 // Verifies that Google Test choose regular expression engine appropriate to
349 // the platform. The test will produce compiler errors in case of failure.
350 // For simplicity, we only cover the most important platforms here.
TEST(RegexEngineSelectionTest,SelectsCorrectRegexEngine)351 TEST(RegexEngineSelectionTest, SelectsCorrectRegexEngine) {
352 #if !GTEST_USES_PCRE
353 #if GTEST_HAS_POSIX_RE
354
355 EXPECT_TRUE(GTEST_USES_POSIX_RE);
356
357 #else
358
359 EXPECT_TRUE(GTEST_USES_SIMPLE_RE);
360
361 #endif
362 #endif // !GTEST_USES_PCRE
363 }
364
365 #if GTEST_USES_POSIX_RE
366
367 #if GTEST_HAS_TYPED_TEST
368
369 template <typename Str>
370 class RETest : public ::testing::Test {};
371
372 // Defines StringTypes as the list of all string types that class RE
373 // supports.
374 typedef testing::Types< ::std::string, const char*> StringTypes;
375
376 TYPED_TEST_SUITE(RETest, StringTypes);
377
378 // Tests RE's implicit constructors.
TYPED_TEST(RETest,ImplicitConstructorWorks)379 TYPED_TEST(RETest, ImplicitConstructorWorks) {
380 const RE empty(TypeParam(""));
381 EXPECT_STREQ("", empty.pattern());
382
383 const RE simple(TypeParam("hello"));
384 EXPECT_STREQ("hello", simple.pattern());
385
386 const RE normal(TypeParam(".*(\\w+)"));
387 EXPECT_STREQ(".*(\\w+)", normal.pattern());
388 }
389
390 // Tests that RE's constructors reject invalid regular expressions.
TYPED_TEST(RETest,RejectsInvalidRegex)391 TYPED_TEST(RETest, RejectsInvalidRegex) {
392 EXPECT_NONFATAL_FAILURE(
393 { const RE invalid(TypeParam("?")); },
394 "\"?\" is not a valid POSIX Extended regular expression.");
395 }
396
397 // Tests RE::FullMatch().
TYPED_TEST(RETest,FullMatchWorks)398 TYPED_TEST(RETest, FullMatchWorks) {
399 const RE empty(TypeParam(""));
400 EXPECT_TRUE(RE::FullMatch(TypeParam(""), empty));
401 EXPECT_FALSE(RE::FullMatch(TypeParam("a"), empty));
402
403 const RE re(TypeParam("a.*z"));
404 EXPECT_TRUE(RE::FullMatch(TypeParam("az"), re));
405 EXPECT_TRUE(RE::FullMatch(TypeParam("axyz"), re));
406 EXPECT_FALSE(RE::FullMatch(TypeParam("baz"), re));
407 EXPECT_FALSE(RE::FullMatch(TypeParam("azy"), re));
408 }
409
410 // Tests RE::PartialMatch().
TYPED_TEST(RETest,PartialMatchWorks)411 TYPED_TEST(RETest, PartialMatchWorks) {
412 const RE empty(TypeParam(""));
413 EXPECT_TRUE(RE::PartialMatch(TypeParam(""), empty));
414 EXPECT_TRUE(RE::PartialMatch(TypeParam("a"), empty));
415
416 const RE re(TypeParam("a.*z"));
417 EXPECT_TRUE(RE::PartialMatch(TypeParam("az"), re));
418 EXPECT_TRUE(RE::PartialMatch(TypeParam("axyz"), re));
419 EXPECT_TRUE(RE::PartialMatch(TypeParam("baz"), re));
420 EXPECT_TRUE(RE::PartialMatch(TypeParam("azy"), re));
421 EXPECT_FALSE(RE::PartialMatch(TypeParam("zza"), re));
422 }
423
424 #endif // GTEST_HAS_TYPED_TEST
425
426 #elif GTEST_USES_SIMPLE_RE
427
TEST(IsInSetTest,NulCharIsNotInAnySet)428 TEST(IsInSetTest, NulCharIsNotInAnySet) {
429 EXPECT_FALSE(IsInSet('\0', ""));
430 EXPECT_FALSE(IsInSet('\0', "\0"));
431 EXPECT_FALSE(IsInSet('\0', "a"));
432 }
433
TEST(IsInSetTest,WorksForNonNulChars)434 TEST(IsInSetTest, WorksForNonNulChars) {
435 EXPECT_FALSE(IsInSet('a', "Ab"));
436 EXPECT_FALSE(IsInSet('c', ""));
437
438 EXPECT_TRUE(IsInSet('b', "bcd"));
439 EXPECT_TRUE(IsInSet('b', "ab"));
440 }
441
TEST(IsAsciiDigitTest,IsFalseForNonDigit)442 TEST(IsAsciiDigitTest, IsFalseForNonDigit) {
443 EXPECT_FALSE(IsAsciiDigit('\0'));
444 EXPECT_FALSE(IsAsciiDigit(' '));
445 EXPECT_FALSE(IsAsciiDigit('+'));
446 EXPECT_FALSE(IsAsciiDigit('-'));
447 EXPECT_FALSE(IsAsciiDigit('.'));
448 EXPECT_FALSE(IsAsciiDigit('a'));
449 }
450
TEST(IsAsciiDigitTest,IsTrueForDigit)451 TEST(IsAsciiDigitTest, IsTrueForDigit) {
452 EXPECT_TRUE(IsAsciiDigit('0'));
453 EXPECT_TRUE(IsAsciiDigit('1'));
454 EXPECT_TRUE(IsAsciiDigit('5'));
455 EXPECT_TRUE(IsAsciiDigit('9'));
456 }
457
TEST(IsAsciiPunctTest,IsFalseForNonPunct)458 TEST(IsAsciiPunctTest, IsFalseForNonPunct) {
459 EXPECT_FALSE(IsAsciiPunct('\0'));
460 EXPECT_FALSE(IsAsciiPunct(' '));
461 EXPECT_FALSE(IsAsciiPunct('\n'));
462 EXPECT_FALSE(IsAsciiPunct('a'));
463 EXPECT_FALSE(IsAsciiPunct('0'));
464 }
465
TEST(IsAsciiPunctTest,IsTrueForPunct)466 TEST(IsAsciiPunctTest, IsTrueForPunct) {
467 for (const char* p = "^-!\"#$%&'()*+,./:;<=>?@[\\]_`{|}~"; *p; p++) {
468 EXPECT_PRED1(IsAsciiPunct, *p);
469 }
470 }
471
TEST(IsRepeatTest,IsFalseForNonRepeatChar)472 TEST(IsRepeatTest, IsFalseForNonRepeatChar) {
473 EXPECT_FALSE(IsRepeat('\0'));
474 EXPECT_FALSE(IsRepeat(' '));
475 EXPECT_FALSE(IsRepeat('a'));
476 EXPECT_FALSE(IsRepeat('1'));
477 EXPECT_FALSE(IsRepeat('-'));
478 }
479
TEST(IsRepeatTest,IsTrueForRepeatChar)480 TEST(IsRepeatTest, IsTrueForRepeatChar) {
481 EXPECT_TRUE(IsRepeat('?'));
482 EXPECT_TRUE(IsRepeat('*'));
483 EXPECT_TRUE(IsRepeat('+'));
484 }
485
TEST(IsAsciiWhiteSpaceTest,IsFalseForNonWhiteSpace)486 TEST(IsAsciiWhiteSpaceTest, IsFalseForNonWhiteSpace) {
487 EXPECT_FALSE(IsAsciiWhiteSpace('\0'));
488 EXPECT_FALSE(IsAsciiWhiteSpace('a'));
489 EXPECT_FALSE(IsAsciiWhiteSpace('1'));
490 EXPECT_FALSE(IsAsciiWhiteSpace('+'));
491 EXPECT_FALSE(IsAsciiWhiteSpace('_'));
492 }
493
TEST(IsAsciiWhiteSpaceTest,IsTrueForWhiteSpace)494 TEST(IsAsciiWhiteSpaceTest, IsTrueForWhiteSpace) {
495 EXPECT_TRUE(IsAsciiWhiteSpace(' '));
496 EXPECT_TRUE(IsAsciiWhiteSpace('\n'));
497 EXPECT_TRUE(IsAsciiWhiteSpace('\r'));
498 EXPECT_TRUE(IsAsciiWhiteSpace('\t'));
499 EXPECT_TRUE(IsAsciiWhiteSpace('\v'));
500 EXPECT_TRUE(IsAsciiWhiteSpace('\f'));
501 }
502
TEST(IsAsciiWordCharTest,IsFalseForNonWordChar)503 TEST(IsAsciiWordCharTest, IsFalseForNonWordChar) {
504 EXPECT_FALSE(IsAsciiWordChar('\0'));
505 EXPECT_FALSE(IsAsciiWordChar('+'));
506 EXPECT_FALSE(IsAsciiWordChar('.'));
507 EXPECT_FALSE(IsAsciiWordChar(' '));
508 EXPECT_FALSE(IsAsciiWordChar('\n'));
509 }
510
TEST(IsAsciiWordCharTest,IsTrueForLetter)511 TEST(IsAsciiWordCharTest, IsTrueForLetter) {
512 EXPECT_TRUE(IsAsciiWordChar('a'));
513 EXPECT_TRUE(IsAsciiWordChar('b'));
514 EXPECT_TRUE(IsAsciiWordChar('A'));
515 EXPECT_TRUE(IsAsciiWordChar('Z'));
516 }
517
TEST(IsAsciiWordCharTest,IsTrueForDigit)518 TEST(IsAsciiWordCharTest, IsTrueForDigit) {
519 EXPECT_TRUE(IsAsciiWordChar('0'));
520 EXPECT_TRUE(IsAsciiWordChar('1'));
521 EXPECT_TRUE(IsAsciiWordChar('7'));
522 EXPECT_TRUE(IsAsciiWordChar('9'));
523 }
524
TEST(IsAsciiWordCharTest,IsTrueForUnderscore)525 TEST(IsAsciiWordCharTest, IsTrueForUnderscore) {
526 EXPECT_TRUE(IsAsciiWordChar('_'));
527 }
528
TEST(IsValidEscapeTest,IsFalseForNonPrintable)529 TEST(IsValidEscapeTest, IsFalseForNonPrintable) {
530 EXPECT_FALSE(IsValidEscape('\0'));
531 EXPECT_FALSE(IsValidEscape('\007'));
532 }
533
TEST(IsValidEscapeTest,IsFalseForDigit)534 TEST(IsValidEscapeTest, IsFalseForDigit) {
535 EXPECT_FALSE(IsValidEscape('0'));
536 EXPECT_FALSE(IsValidEscape('9'));
537 }
538
TEST(IsValidEscapeTest,IsFalseForWhiteSpace)539 TEST(IsValidEscapeTest, IsFalseForWhiteSpace) {
540 EXPECT_FALSE(IsValidEscape(' '));
541 EXPECT_FALSE(IsValidEscape('\n'));
542 }
543
TEST(IsValidEscapeTest,IsFalseForSomeLetter)544 TEST(IsValidEscapeTest, IsFalseForSomeLetter) {
545 EXPECT_FALSE(IsValidEscape('a'));
546 EXPECT_FALSE(IsValidEscape('Z'));
547 }
548
TEST(IsValidEscapeTest,IsTrueForPunct)549 TEST(IsValidEscapeTest, IsTrueForPunct) {
550 EXPECT_TRUE(IsValidEscape('.'));
551 EXPECT_TRUE(IsValidEscape('-'));
552 EXPECT_TRUE(IsValidEscape('^'));
553 EXPECT_TRUE(IsValidEscape('$'));
554 EXPECT_TRUE(IsValidEscape('('));
555 EXPECT_TRUE(IsValidEscape(']'));
556 EXPECT_TRUE(IsValidEscape('{'));
557 EXPECT_TRUE(IsValidEscape('|'));
558 }
559
TEST(IsValidEscapeTest,IsTrueForSomeLetter)560 TEST(IsValidEscapeTest, IsTrueForSomeLetter) {
561 EXPECT_TRUE(IsValidEscape('d'));
562 EXPECT_TRUE(IsValidEscape('D'));
563 EXPECT_TRUE(IsValidEscape('s'));
564 EXPECT_TRUE(IsValidEscape('S'));
565 EXPECT_TRUE(IsValidEscape('w'));
566 EXPECT_TRUE(IsValidEscape('W'));
567 }
568
TEST(AtomMatchesCharTest,EscapedPunct)569 TEST(AtomMatchesCharTest, EscapedPunct) {
570 EXPECT_FALSE(AtomMatchesChar(true, '\\', '\0'));
571 EXPECT_FALSE(AtomMatchesChar(true, '\\', ' '));
572 EXPECT_FALSE(AtomMatchesChar(true, '_', '.'));
573 EXPECT_FALSE(AtomMatchesChar(true, '.', 'a'));
574
575 EXPECT_TRUE(AtomMatchesChar(true, '\\', '\\'));
576 EXPECT_TRUE(AtomMatchesChar(true, '_', '_'));
577 EXPECT_TRUE(AtomMatchesChar(true, '+', '+'));
578 EXPECT_TRUE(AtomMatchesChar(true, '.', '.'));
579 }
580
TEST(AtomMatchesCharTest,Escaped_d)581 TEST(AtomMatchesCharTest, Escaped_d) {
582 EXPECT_FALSE(AtomMatchesChar(true, 'd', '\0'));
583 EXPECT_FALSE(AtomMatchesChar(true, 'd', 'a'));
584 EXPECT_FALSE(AtomMatchesChar(true, 'd', '.'));
585
586 EXPECT_TRUE(AtomMatchesChar(true, 'd', '0'));
587 EXPECT_TRUE(AtomMatchesChar(true, 'd', '9'));
588 }
589
TEST(AtomMatchesCharTest,Escaped_D)590 TEST(AtomMatchesCharTest, Escaped_D) {
591 EXPECT_FALSE(AtomMatchesChar(true, 'D', '0'));
592 EXPECT_FALSE(AtomMatchesChar(true, 'D', '9'));
593
594 EXPECT_TRUE(AtomMatchesChar(true, 'D', '\0'));
595 EXPECT_TRUE(AtomMatchesChar(true, 'D', 'a'));
596 EXPECT_TRUE(AtomMatchesChar(true, 'D', '-'));
597 }
598
TEST(AtomMatchesCharTest,Escaped_s)599 TEST(AtomMatchesCharTest, Escaped_s) {
600 EXPECT_FALSE(AtomMatchesChar(true, 's', '\0'));
601 EXPECT_FALSE(AtomMatchesChar(true, 's', 'a'));
602 EXPECT_FALSE(AtomMatchesChar(true, 's', '.'));
603 EXPECT_FALSE(AtomMatchesChar(true, 's', '9'));
604
605 EXPECT_TRUE(AtomMatchesChar(true, 's', ' '));
606 EXPECT_TRUE(AtomMatchesChar(true, 's', '\n'));
607 EXPECT_TRUE(AtomMatchesChar(true, 's', '\t'));
608 }
609
TEST(AtomMatchesCharTest,Escaped_S)610 TEST(AtomMatchesCharTest, Escaped_S) {
611 EXPECT_FALSE(AtomMatchesChar(true, 'S', ' '));
612 EXPECT_FALSE(AtomMatchesChar(true, 'S', '\r'));
613
614 EXPECT_TRUE(AtomMatchesChar(true, 'S', '\0'));
615 EXPECT_TRUE(AtomMatchesChar(true, 'S', 'a'));
616 EXPECT_TRUE(AtomMatchesChar(true, 'S', '9'));
617 }
618
TEST(AtomMatchesCharTest,Escaped_w)619 TEST(AtomMatchesCharTest, Escaped_w) {
620 EXPECT_FALSE(AtomMatchesChar(true, 'w', '\0'));
621 EXPECT_FALSE(AtomMatchesChar(true, 'w', '+'));
622 EXPECT_FALSE(AtomMatchesChar(true, 'w', ' '));
623 EXPECT_FALSE(AtomMatchesChar(true, 'w', '\n'));
624
625 EXPECT_TRUE(AtomMatchesChar(true, 'w', '0'));
626 EXPECT_TRUE(AtomMatchesChar(true, 'w', 'b'));
627 EXPECT_TRUE(AtomMatchesChar(true, 'w', 'C'));
628 EXPECT_TRUE(AtomMatchesChar(true, 'w', '_'));
629 }
630
TEST(AtomMatchesCharTest,Escaped_W)631 TEST(AtomMatchesCharTest, Escaped_W) {
632 EXPECT_FALSE(AtomMatchesChar(true, 'W', 'A'));
633 EXPECT_FALSE(AtomMatchesChar(true, 'W', 'b'));
634 EXPECT_FALSE(AtomMatchesChar(true, 'W', '9'));
635 EXPECT_FALSE(AtomMatchesChar(true, 'W', '_'));
636
637 EXPECT_TRUE(AtomMatchesChar(true, 'W', '\0'));
638 EXPECT_TRUE(AtomMatchesChar(true, 'W', '*'));
639 EXPECT_TRUE(AtomMatchesChar(true, 'W', '\n'));
640 }
641
TEST(AtomMatchesCharTest,EscapedWhiteSpace)642 TEST(AtomMatchesCharTest, EscapedWhiteSpace) {
643 EXPECT_FALSE(AtomMatchesChar(true, 'f', '\0'));
644 EXPECT_FALSE(AtomMatchesChar(true, 'f', '\n'));
645 EXPECT_FALSE(AtomMatchesChar(true, 'n', '\0'));
646 EXPECT_FALSE(AtomMatchesChar(true, 'n', '\r'));
647 EXPECT_FALSE(AtomMatchesChar(true, 'r', '\0'));
648 EXPECT_FALSE(AtomMatchesChar(true, 'r', 'a'));
649 EXPECT_FALSE(AtomMatchesChar(true, 't', '\0'));
650 EXPECT_FALSE(AtomMatchesChar(true, 't', 't'));
651 EXPECT_FALSE(AtomMatchesChar(true, 'v', '\0'));
652 EXPECT_FALSE(AtomMatchesChar(true, 'v', '\f'));
653
654 EXPECT_TRUE(AtomMatchesChar(true, 'f', '\f'));
655 EXPECT_TRUE(AtomMatchesChar(true, 'n', '\n'));
656 EXPECT_TRUE(AtomMatchesChar(true, 'r', '\r'));
657 EXPECT_TRUE(AtomMatchesChar(true, 't', '\t'));
658 EXPECT_TRUE(AtomMatchesChar(true, 'v', '\v'));
659 }
660
TEST(AtomMatchesCharTest,UnescapedDot)661 TEST(AtomMatchesCharTest, UnescapedDot) {
662 EXPECT_FALSE(AtomMatchesChar(false, '.', '\n'));
663
664 EXPECT_TRUE(AtomMatchesChar(false, '.', '\0'));
665 EXPECT_TRUE(AtomMatchesChar(false, '.', '.'));
666 EXPECT_TRUE(AtomMatchesChar(false, '.', 'a'));
667 EXPECT_TRUE(AtomMatchesChar(false, '.', ' '));
668 }
669
TEST(AtomMatchesCharTest,UnescapedChar)670 TEST(AtomMatchesCharTest, UnescapedChar) {
671 EXPECT_FALSE(AtomMatchesChar(false, 'a', '\0'));
672 EXPECT_FALSE(AtomMatchesChar(false, 'a', 'b'));
673 EXPECT_FALSE(AtomMatchesChar(false, '$', 'a'));
674
675 EXPECT_TRUE(AtomMatchesChar(false, '$', '$'));
676 EXPECT_TRUE(AtomMatchesChar(false, '5', '5'));
677 EXPECT_TRUE(AtomMatchesChar(false, 'Z', 'Z'));
678 }
679
TEST(ValidateRegexTest,GeneratesFailureAndReturnsFalseForInvalid)680 TEST(ValidateRegexTest, GeneratesFailureAndReturnsFalseForInvalid) {
681 EXPECT_NONFATAL_FAILURE(ASSERT_FALSE(ValidateRegex(NULL)),
682 "NULL is not a valid simple regular expression");
683 EXPECT_NONFATAL_FAILURE(
684 ASSERT_FALSE(ValidateRegex("a\\")),
685 "Syntax error at index 1 in simple regular expression \"a\\\": ");
686 EXPECT_NONFATAL_FAILURE(ASSERT_FALSE(ValidateRegex("a\\")),
687 "'\\' cannot appear at the end");
688 EXPECT_NONFATAL_FAILURE(ASSERT_FALSE(ValidateRegex("\\n\\")),
689 "'\\' cannot appear at the end");
690 EXPECT_NONFATAL_FAILURE(ASSERT_FALSE(ValidateRegex("\\s\\hb")),
691 "invalid escape sequence \"\\h\"");
692 EXPECT_NONFATAL_FAILURE(ASSERT_FALSE(ValidateRegex("^^")),
693 "'^' can only appear at the beginning");
694 EXPECT_NONFATAL_FAILURE(ASSERT_FALSE(ValidateRegex(".*^b")),
695 "'^' can only appear at the beginning");
696 EXPECT_NONFATAL_FAILURE(ASSERT_FALSE(ValidateRegex("$$")),
697 "'$' can only appear at the end");
698 EXPECT_NONFATAL_FAILURE(ASSERT_FALSE(ValidateRegex("^$a")),
699 "'$' can only appear at the end");
700 EXPECT_NONFATAL_FAILURE(ASSERT_FALSE(ValidateRegex("a(b")),
701 "'(' is unsupported");
702 EXPECT_NONFATAL_FAILURE(ASSERT_FALSE(ValidateRegex("ab)")),
703 "')' is unsupported");
704 EXPECT_NONFATAL_FAILURE(ASSERT_FALSE(ValidateRegex("[ab")),
705 "'[' is unsupported");
706 EXPECT_NONFATAL_FAILURE(ASSERT_FALSE(ValidateRegex("a{2")),
707 "'{' is unsupported");
708 EXPECT_NONFATAL_FAILURE(ASSERT_FALSE(ValidateRegex("?")),
709 "'?' can only follow a repeatable token");
710 EXPECT_NONFATAL_FAILURE(ASSERT_FALSE(ValidateRegex("^*")),
711 "'*' can only follow a repeatable token");
712 EXPECT_NONFATAL_FAILURE(ASSERT_FALSE(ValidateRegex("5*+")),
713 "'+' can only follow a repeatable token");
714 }
715
TEST(ValidateRegexTest,ReturnsTrueForValid)716 TEST(ValidateRegexTest, ReturnsTrueForValid) {
717 EXPECT_TRUE(ValidateRegex(""));
718 EXPECT_TRUE(ValidateRegex("a"));
719 EXPECT_TRUE(ValidateRegex(".*"));
720 EXPECT_TRUE(ValidateRegex("^a_+"));
721 EXPECT_TRUE(ValidateRegex("^a\\t\\&?"));
722 EXPECT_TRUE(ValidateRegex("09*$"));
723 EXPECT_TRUE(ValidateRegex("^Z$"));
724 EXPECT_TRUE(ValidateRegex("a\\^Z\\$\\(\\)\\|\\[\\]\\{\\}"));
725 }
726
TEST(MatchRepetitionAndRegexAtHeadTest,WorksForZeroOrOne)727 TEST(MatchRepetitionAndRegexAtHeadTest, WorksForZeroOrOne) {
728 EXPECT_FALSE(MatchRepetitionAndRegexAtHead(false, 'a', '?', "a", "ba"));
729 // Repeating more than once.
730 EXPECT_FALSE(MatchRepetitionAndRegexAtHead(false, 'a', '?', "b", "aab"));
731
732 // Repeating zero times.
733 EXPECT_TRUE(MatchRepetitionAndRegexAtHead(false, 'a', '?', "b", "ba"));
734 // Repeating once.
735 EXPECT_TRUE(MatchRepetitionAndRegexAtHead(false, 'a', '?', "b", "ab"));
736 EXPECT_TRUE(MatchRepetitionAndRegexAtHead(false, '#', '?', ".", "##"));
737 }
738
TEST(MatchRepetitionAndRegexAtHeadTest,WorksForZeroOrMany)739 TEST(MatchRepetitionAndRegexAtHeadTest, WorksForZeroOrMany) {
740 EXPECT_FALSE(MatchRepetitionAndRegexAtHead(false, '.', '*', "a$", "baab"));
741
742 // Repeating zero times.
743 EXPECT_TRUE(MatchRepetitionAndRegexAtHead(false, '.', '*', "b", "bc"));
744 // Repeating once.
745 EXPECT_TRUE(MatchRepetitionAndRegexAtHead(false, '.', '*', "b", "abc"));
746 // Repeating more than once.
747 EXPECT_TRUE(MatchRepetitionAndRegexAtHead(true, 'w', '*', "-", "ab_1-g"));
748 }
749
TEST(MatchRepetitionAndRegexAtHeadTest,WorksForOneOrMany)750 TEST(MatchRepetitionAndRegexAtHeadTest, WorksForOneOrMany) {
751 EXPECT_FALSE(MatchRepetitionAndRegexAtHead(false, '.', '+', "a$", "baab"));
752 // Repeating zero times.
753 EXPECT_FALSE(MatchRepetitionAndRegexAtHead(false, '.', '+', "b", "bc"));
754
755 // Repeating once.
756 EXPECT_TRUE(MatchRepetitionAndRegexAtHead(false, '.', '+', "b", "abc"));
757 // Repeating more than once.
758 EXPECT_TRUE(MatchRepetitionAndRegexAtHead(true, 'w', '+', "-", "ab_1-g"));
759 }
760
TEST(MatchRegexAtHeadTest,ReturnsTrueForEmptyRegex)761 TEST(MatchRegexAtHeadTest, ReturnsTrueForEmptyRegex) {
762 EXPECT_TRUE(MatchRegexAtHead("", ""));
763 EXPECT_TRUE(MatchRegexAtHead("", "ab"));
764 }
765
TEST(MatchRegexAtHeadTest,WorksWhenDollarIsInRegex)766 TEST(MatchRegexAtHeadTest, WorksWhenDollarIsInRegex) {
767 EXPECT_FALSE(MatchRegexAtHead("$", "a"));
768
769 EXPECT_TRUE(MatchRegexAtHead("$", ""));
770 EXPECT_TRUE(MatchRegexAtHead("a$", "a"));
771 }
772
TEST(MatchRegexAtHeadTest,WorksWhenRegexStartsWithEscapeSequence)773 TEST(MatchRegexAtHeadTest, WorksWhenRegexStartsWithEscapeSequence) {
774 EXPECT_FALSE(MatchRegexAtHead("\\w", "+"));
775 EXPECT_FALSE(MatchRegexAtHead("\\W", "ab"));
776
777 EXPECT_TRUE(MatchRegexAtHead("\\sa", "\nab"));
778 EXPECT_TRUE(MatchRegexAtHead("\\d", "1a"));
779 }
780
TEST(MatchRegexAtHeadTest,WorksWhenRegexStartsWithRepetition)781 TEST(MatchRegexAtHeadTest, WorksWhenRegexStartsWithRepetition) {
782 EXPECT_FALSE(MatchRegexAtHead(".+a", "abc"));
783 EXPECT_FALSE(MatchRegexAtHead("a?b", "aab"));
784
785 EXPECT_TRUE(MatchRegexAtHead(".*a", "bc12-ab"));
786 EXPECT_TRUE(MatchRegexAtHead("a?b", "b"));
787 EXPECT_TRUE(MatchRegexAtHead("a?b", "ab"));
788 }
789
TEST(MatchRegexAtHeadTest,WorksWhenRegexStartsWithRepetionOfEscapeSequence)790 TEST(MatchRegexAtHeadTest, WorksWhenRegexStartsWithRepetionOfEscapeSequence) {
791 EXPECT_FALSE(MatchRegexAtHead("\\.+a", "abc"));
792 EXPECT_FALSE(MatchRegexAtHead("\\s?b", " b"));
793
794 EXPECT_TRUE(MatchRegexAtHead("\\(*a", "((((ab"));
795 EXPECT_TRUE(MatchRegexAtHead("\\^?b", "^b"));
796 EXPECT_TRUE(MatchRegexAtHead("\\\\?b", "b"));
797 EXPECT_TRUE(MatchRegexAtHead("\\\\?b", "\\b"));
798 }
799
TEST(MatchRegexAtHeadTest,MatchesSequentially)800 TEST(MatchRegexAtHeadTest, MatchesSequentially) {
801 EXPECT_FALSE(MatchRegexAtHead("ab.*c", "acabc"));
802
803 EXPECT_TRUE(MatchRegexAtHead("ab.*c", "ab-fsc"));
804 }
805
TEST(MatchRegexAnywhereTest,ReturnsFalseWhenStringIsNull)806 TEST(MatchRegexAnywhereTest, ReturnsFalseWhenStringIsNull) {
807 EXPECT_FALSE(MatchRegexAnywhere("", NULL));
808 }
809
TEST(MatchRegexAnywhereTest,WorksWhenRegexStartsWithCaret)810 TEST(MatchRegexAnywhereTest, WorksWhenRegexStartsWithCaret) {
811 EXPECT_FALSE(MatchRegexAnywhere("^a", "ba"));
812 EXPECT_FALSE(MatchRegexAnywhere("^$", "a"));
813
814 EXPECT_TRUE(MatchRegexAnywhere("^a", "ab"));
815 EXPECT_TRUE(MatchRegexAnywhere("^", "ab"));
816 EXPECT_TRUE(MatchRegexAnywhere("^$", ""));
817 }
818
TEST(MatchRegexAnywhereTest,ReturnsFalseWhenNoMatch)819 TEST(MatchRegexAnywhereTest, ReturnsFalseWhenNoMatch) {
820 EXPECT_FALSE(MatchRegexAnywhere("a", "bcde123"));
821 EXPECT_FALSE(MatchRegexAnywhere("a.+a", "--aa88888888"));
822 }
823
TEST(MatchRegexAnywhereTest,ReturnsTrueWhenMatchingPrefix)824 TEST(MatchRegexAnywhereTest, ReturnsTrueWhenMatchingPrefix) {
825 EXPECT_TRUE(MatchRegexAnywhere("\\w+", "ab1_ - 5"));
826 EXPECT_TRUE(MatchRegexAnywhere(".*=", "="));
827 EXPECT_TRUE(MatchRegexAnywhere("x.*ab?.*bc", "xaaabc"));
828 }
829
TEST(MatchRegexAnywhereTest,ReturnsTrueWhenMatchingNonPrefix)830 TEST(MatchRegexAnywhereTest, ReturnsTrueWhenMatchingNonPrefix) {
831 EXPECT_TRUE(MatchRegexAnywhere("\\w+", "$$$ ab1_ - 5"));
832 EXPECT_TRUE(MatchRegexAnywhere("\\.+=", "= ...="));
833 }
834
835 // Tests RE's implicit constructors.
TEST(RETest,ImplicitConstructorWorks)836 TEST(RETest, ImplicitConstructorWorks) {
837 const RE empty("");
838 EXPECT_STREQ("", empty.pattern());
839
840 const RE simple("hello");
841 EXPECT_STREQ("hello", simple.pattern());
842 }
843
844 // Tests that RE's constructors reject invalid regular expressions.
TEST(RETest,RejectsInvalidRegex)845 TEST(RETest, RejectsInvalidRegex) {
846 EXPECT_NONFATAL_FAILURE({ const RE normal(NULL); },
847 "NULL is not a valid simple regular expression");
848
849 EXPECT_NONFATAL_FAILURE({ const RE normal(".*(\\w+"); },
850 "'(' is unsupported");
851
852 EXPECT_NONFATAL_FAILURE({ const RE invalid("^?"); },
853 "'?' can only follow a repeatable token");
854 }
855
856 // Tests RE::FullMatch().
TEST(RETest,FullMatchWorks)857 TEST(RETest, FullMatchWorks) {
858 const RE empty("");
859 EXPECT_TRUE(RE::FullMatch("", empty));
860 EXPECT_FALSE(RE::FullMatch("a", empty));
861
862 const RE re1("a");
863 EXPECT_TRUE(RE::FullMatch("a", re1));
864
865 const RE re("a.*z");
866 EXPECT_TRUE(RE::FullMatch("az", re));
867 EXPECT_TRUE(RE::FullMatch("axyz", re));
868 EXPECT_FALSE(RE::FullMatch("baz", re));
869 EXPECT_FALSE(RE::FullMatch("azy", re));
870 }
871
872 // Tests RE::PartialMatch().
TEST(RETest,PartialMatchWorks)873 TEST(RETest, PartialMatchWorks) {
874 const RE empty("");
875 EXPECT_TRUE(RE::PartialMatch("", empty));
876 EXPECT_TRUE(RE::PartialMatch("a", empty));
877
878 const RE re("a.*z");
879 EXPECT_TRUE(RE::PartialMatch("az", re));
880 EXPECT_TRUE(RE::PartialMatch("axyz", re));
881 EXPECT_TRUE(RE::PartialMatch("baz", re));
882 EXPECT_TRUE(RE::PartialMatch("azy", re));
883 EXPECT_FALSE(RE::PartialMatch("zza", re));
884 }
885
886 #endif // GTEST_USES_POSIX_RE
887
888 #if !GTEST_OS_WINDOWS_MOBILE
889
TEST(CaptureTest,CapturesStdout)890 TEST(CaptureTest, CapturesStdout) {
891 CaptureStdout();
892 fprintf(stdout, "abc");
893 EXPECT_STREQ("abc", GetCapturedStdout().c_str());
894
895 CaptureStdout();
896 fprintf(stdout, "def%cghi", '\0');
897 EXPECT_EQ(::std::string("def\0ghi", 7), ::std::string(GetCapturedStdout()));
898 }
899
TEST(CaptureTest,CapturesStderr)900 TEST(CaptureTest, CapturesStderr) {
901 CaptureStderr();
902 fprintf(stderr, "jkl");
903 EXPECT_STREQ("jkl", GetCapturedStderr().c_str());
904
905 CaptureStderr();
906 fprintf(stderr, "jkl%cmno", '\0');
907 EXPECT_EQ(::std::string("jkl\0mno", 7), ::std::string(GetCapturedStderr()));
908 }
909
910 // Tests that stdout and stderr capture don't interfere with each other.
TEST(CaptureTest,CapturesStdoutAndStderr)911 TEST(CaptureTest, CapturesStdoutAndStderr) {
912 CaptureStdout();
913 CaptureStderr();
914 fprintf(stdout, "pqr");
915 fprintf(stderr, "stu");
916 EXPECT_STREQ("pqr", GetCapturedStdout().c_str());
917 EXPECT_STREQ("stu", GetCapturedStderr().c_str());
918 }
919
TEST(CaptureDeathTest,CannotReenterStdoutCapture)920 TEST(CaptureDeathTest, CannotReenterStdoutCapture) {
921 CaptureStdout();
922 EXPECT_DEATH_IF_SUPPORTED(CaptureStdout(),
923 "Only one stdout capturer can exist at a time");
924 GetCapturedStdout();
925
926 // We cannot test stderr capturing using death tests as they use it
927 // themselves.
928 }
929
930 #endif // !GTEST_OS_WINDOWS_MOBILE
931
TEST(ThreadLocalTest,DefaultConstructorInitializesToDefaultValues)932 TEST(ThreadLocalTest, DefaultConstructorInitializesToDefaultValues) {
933 ThreadLocal<int> t1;
934 EXPECT_EQ(0, t1.get());
935
936 ThreadLocal<void*> t2;
937 EXPECT_TRUE(t2.get() == nullptr);
938 }
939
TEST(ThreadLocalTest,SingleParamConstructorInitializesToParam)940 TEST(ThreadLocalTest, SingleParamConstructorInitializesToParam) {
941 ThreadLocal<int> t1(123);
942 EXPECT_EQ(123, t1.get());
943
944 int i = 0;
945 ThreadLocal<int*> t2(&i);
946 EXPECT_EQ(&i, t2.get());
947 }
948
949 class NoDefaultContructor {
950 public:
NoDefaultContructor(const char *)951 explicit NoDefaultContructor(const char*) {}
NoDefaultContructor(const NoDefaultContructor &)952 NoDefaultContructor(const NoDefaultContructor&) {}
953 };
954
TEST(ThreadLocalTest,ValueDefaultContructorIsNotRequiredForParamVersion)955 TEST(ThreadLocalTest, ValueDefaultContructorIsNotRequiredForParamVersion) {
956 ThreadLocal<NoDefaultContructor> bar(NoDefaultContructor("foo"));
957 bar.pointer();
958 }
959
TEST(ThreadLocalTest,GetAndPointerReturnSameValue)960 TEST(ThreadLocalTest, GetAndPointerReturnSameValue) {
961 ThreadLocal<std::string> thread_local_string;
962
963 EXPECT_EQ(thread_local_string.pointer(), &(thread_local_string.get()));
964
965 // Verifies the condition still holds after calling set.
966 thread_local_string.set("foo");
967 EXPECT_EQ(thread_local_string.pointer(), &(thread_local_string.get()));
968 }
969
TEST(ThreadLocalTest,PointerAndConstPointerReturnSameValue)970 TEST(ThreadLocalTest, PointerAndConstPointerReturnSameValue) {
971 ThreadLocal<std::string> thread_local_string;
972 const ThreadLocal<std::string>& const_thread_local_string =
973 thread_local_string;
974
975 EXPECT_EQ(thread_local_string.pointer(), const_thread_local_string.pointer());
976
977 thread_local_string.set("foo");
978 EXPECT_EQ(thread_local_string.pointer(), const_thread_local_string.pointer());
979 }
980
981 #if GTEST_IS_THREADSAFE
982
AddTwo(int * param)983 void AddTwo(int* param) { *param += 2; }
984
TEST(ThreadWithParamTest,ConstructorExecutesThreadFunc)985 TEST(ThreadWithParamTest, ConstructorExecutesThreadFunc) {
986 int i = 40;
987 ThreadWithParam<int*> thread(&AddTwo, &i, nullptr);
988 thread.Join();
989 EXPECT_EQ(42, i);
990 }
991
TEST(MutexDeathTest,AssertHeldShouldAssertWhenNotLocked)992 TEST(MutexDeathTest, AssertHeldShouldAssertWhenNotLocked) {
993 // AssertHeld() is flaky only in the presence of multiple threads accessing
994 // the lock. In this case, the test is robust.
995 EXPECT_DEATH_IF_SUPPORTED(
996 {
997 Mutex m;
998 { MutexLock lock(&m); }
999 m.AssertHeld();
1000 },
1001 "thread .*hold");
1002 }
1003
TEST(MutexTest,AssertHeldShouldNotAssertWhenLocked)1004 TEST(MutexTest, AssertHeldShouldNotAssertWhenLocked) {
1005 Mutex m;
1006 MutexLock lock(&m);
1007 m.AssertHeld();
1008 }
1009
1010 class AtomicCounterWithMutex {
1011 public:
AtomicCounterWithMutex(Mutex * mutex)1012 explicit AtomicCounterWithMutex(Mutex* mutex)
1013 : value_(0), mutex_(mutex), random_(42) {}
1014
Increment()1015 void Increment() {
1016 MutexLock lock(mutex_);
1017 int temp = value_;
1018 {
1019 // We need to put up a memory barrier to prevent reads and writes to
1020 // value_ rearranged with the call to SleepMilliseconds when observed
1021 // from other threads.
1022 #if GTEST_HAS_PTHREAD
1023 // On POSIX, locking a mutex puts up a memory barrier. We cannot use
1024 // Mutex and MutexLock here or rely on their memory barrier
1025 // functionality as we are testing them here.
1026 pthread_mutex_t memory_barrier_mutex;
1027 GTEST_CHECK_POSIX_SUCCESS_(
1028 pthread_mutex_init(&memory_barrier_mutex, nullptr));
1029 GTEST_CHECK_POSIX_SUCCESS_(pthread_mutex_lock(&memory_barrier_mutex));
1030
1031 SleepMilliseconds(static_cast<int>(random_.Generate(30)));
1032
1033 GTEST_CHECK_POSIX_SUCCESS_(pthread_mutex_unlock(&memory_barrier_mutex));
1034 GTEST_CHECK_POSIX_SUCCESS_(pthread_mutex_destroy(&memory_barrier_mutex));
1035 #elif GTEST_OS_WINDOWS
1036 // On Windows, performing an interlocked access puts up a memory barrier.
1037 volatile LONG dummy = 0;
1038 ::InterlockedIncrement(&dummy);
1039 SleepMilliseconds(static_cast<int>(random_.Generate(30)));
1040 ::InterlockedIncrement(&dummy);
1041 #else
1042 #error "Memory barrier not implemented on this platform."
1043 #endif // GTEST_HAS_PTHREAD
1044 }
1045 value_ = temp + 1;
1046 }
value() const1047 int value() const { return value_; }
1048
1049 private:
1050 volatile int value_;
1051 Mutex* const mutex_; // Protects value_.
1052 Random random_;
1053 };
1054
CountingThreadFunc(pair<AtomicCounterWithMutex *,int> param)1055 void CountingThreadFunc(pair<AtomicCounterWithMutex*, int> param) {
1056 for (int i = 0; i < param.second; ++i) param.first->Increment();
1057 }
1058
1059 // Tests that the mutex only lets one thread at a time to lock it.
TEST(MutexTest,OnlyOneThreadCanLockAtATime)1060 TEST(MutexTest, OnlyOneThreadCanLockAtATime) {
1061 Mutex mutex;
1062 AtomicCounterWithMutex locked_counter(&mutex);
1063
1064 typedef ThreadWithParam<pair<AtomicCounterWithMutex*, int> > ThreadType;
1065 const int kCycleCount = 20;
1066 const int kThreadCount = 7;
1067 std::unique_ptr<ThreadType> counting_threads[kThreadCount];
1068 Notification threads_can_start;
1069 // Creates and runs kThreadCount threads that increment locked_counter
1070 // kCycleCount times each.
1071 for (int i = 0; i < kThreadCount; ++i) {
1072 counting_threads[i].reset(new ThreadType(
1073 &CountingThreadFunc, make_pair(&locked_counter, kCycleCount),
1074 &threads_can_start));
1075 }
1076 threads_can_start.Notify();
1077 for (int i = 0; i < kThreadCount; ++i) counting_threads[i]->Join();
1078
1079 // If the mutex lets more than one thread to increment the counter at a
1080 // time, they are likely to encounter a race condition and have some
1081 // increments overwritten, resulting in the lower then expected counter
1082 // value.
1083 EXPECT_EQ(kCycleCount * kThreadCount, locked_counter.value());
1084 }
1085
1086 template <typename T>
RunFromThread(void (func)(T),T param)1087 void RunFromThread(void(func)(T), T param) {
1088 ThreadWithParam<T> thread(func, param, nullptr);
1089 thread.Join();
1090 }
1091
RetrieveThreadLocalValue(pair<ThreadLocal<std::string> *,std::string * > param)1092 void RetrieveThreadLocalValue(
1093 pair<ThreadLocal<std::string>*, std::string*> param) {
1094 *param.second = param.first->get();
1095 }
1096
TEST(ThreadLocalTest,ParameterizedConstructorSetsDefault)1097 TEST(ThreadLocalTest, ParameterizedConstructorSetsDefault) {
1098 ThreadLocal<std::string> thread_local_string("foo");
1099 EXPECT_STREQ("foo", thread_local_string.get().c_str());
1100
1101 thread_local_string.set("bar");
1102 EXPECT_STREQ("bar", thread_local_string.get().c_str());
1103
1104 std::string result;
1105 RunFromThread(&RetrieveThreadLocalValue,
1106 make_pair(&thread_local_string, &result));
1107 EXPECT_STREQ("foo", result.c_str());
1108 }
1109
1110 // Keeps track of whether of destructors being called on instances of
1111 // DestructorTracker. On Windows, waits for the destructor call reports.
1112 class DestructorCall {
1113 public:
DestructorCall()1114 DestructorCall() {
1115 invoked_ = false;
1116 #if GTEST_OS_WINDOWS
1117 wait_event_.Reset(::CreateEvent(NULL, TRUE, FALSE, NULL));
1118 GTEST_CHECK_(wait_event_.Get() != NULL);
1119 #endif
1120 }
1121
CheckDestroyed() const1122 bool CheckDestroyed() const {
1123 #if GTEST_OS_WINDOWS
1124 if (::WaitForSingleObject(wait_event_.Get(), 1000) != WAIT_OBJECT_0)
1125 return false;
1126 #endif
1127 return invoked_;
1128 }
1129
ReportDestroyed()1130 void ReportDestroyed() {
1131 invoked_ = true;
1132 #if GTEST_OS_WINDOWS
1133 ::SetEvent(wait_event_.Get());
1134 #endif
1135 }
1136
List()1137 static std::vector<DestructorCall*>& List() { return *list_; }
1138
ResetList()1139 static void ResetList() {
1140 for (size_t i = 0; i < list_->size(); ++i) {
1141 delete list_->at(i);
1142 }
1143 list_->clear();
1144 }
1145
1146 private:
1147 bool invoked_;
1148 #if GTEST_OS_WINDOWS
1149 AutoHandle wait_event_;
1150 #endif
1151 static std::vector<DestructorCall*>* const list_;
1152
1153 GTEST_DISALLOW_COPY_AND_ASSIGN_(DestructorCall);
1154 };
1155
1156 std::vector<DestructorCall*>* const DestructorCall::list_ =
1157 new std::vector<DestructorCall*>;
1158
1159 // DestructorTracker keeps track of whether its instances have been
1160 // destroyed.
1161 class DestructorTracker {
1162 public:
DestructorTracker()1163 DestructorTracker() : index_(GetNewIndex()) {}
DestructorTracker(const DestructorTracker &)1164 DestructorTracker(const DestructorTracker& /* rhs */)
1165 : index_(GetNewIndex()) {}
~DestructorTracker()1166 ~DestructorTracker() {
1167 // We never access DestructorCall::List() concurrently, so we don't need
1168 // to protect this access with a mutex.
1169 DestructorCall::List()[index_]->ReportDestroyed();
1170 }
1171
1172 private:
GetNewIndex()1173 static size_t GetNewIndex() {
1174 DestructorCall::List().push_back(new DestructorCall);
1175 return DestructorCall::List().size() - 1;
1176 }
1177 const size_t index_;
1178
1179 GTEST_DISALLOW_ASSIGN_(DestructorTracker);
1180 };
1181
1182 typedef ThreadLocal<DestructorTracker>* ThreadParam;
1183
CallThreadLocalGet(ThreadParam thread_local_param)1184 void CallThreadLocalGet(ThreadParam thread_local_param) {
1185 thread_local_param->get();
1186 }
1187
1188 // Tests that when a ThreadLocal object dies in a thread, it destroys
1189 // the managed object for that thread.
TEST(ThreadLocalTest,DestroysManagedObjectForOwnThreadWhenDying)1190 TEST(ThreadLocalTest, DestroysManagedObjectForOwnThreadWhenDying) {
1191 DestructorCall::ResetList();
1192
1193 {
1194 ThreadLocal<DestructorTracker> thread_local_tracker;
1195 ASSERT_EQ(0U, DestructorCall::List().size());
1196
1197 // This creates another DestructorTracker object for the main thread.
1198 thread_local_tracker.get();
1199 ASSERT_EQ(1U, DestructorCall::List().size());
1200 ASSERT_FALSE(DestructorCall::List()[0]->CheckDestroyed());
1201 }
1202
1203 // Now thread_local_tracker has died.
1204 ASSERT_EQ(1U, DestructorCall::List().size());
1205 EXPECT_TRUE(DestructorCall::List()[0]->CheckDestroyed());
1206
1207 DestructorCall::ResetList();
1208 }
1209
1210 // Tests that when a thread exits, the thread-local object for that
1211 // thread is destroyed.
TEST(ThreadLocalTest,DestroysManagedObjectAtThreadExit)1212 TEST(ThreadLocalTest, DestroysManagedObjectAtThreadExit) {
1213 DestructorCall::ResetList();
1214
1215 {
1216 ThreadLocal<DestructorTracker> thread_local_tracker;
1217 ASSERT_EQ(0U, DestructorCall::List().size());
1218
1219 // This creates another DestructorTracker object in the new thread.
1220 ThreadWithParam<ThreadParam> thread(&CallThreadLocalGet,
1221 &thread_local_tracker, nullptr);
1222 thread.Join();
1223
1224 // The thread has exited, and we should have a DestroyedTracker
1225 // instance created for it. But it may not have been destroyed yet.
1226 ASSERT_EQ(1U, DestructorCall::List().size());
1227 }
1228
1229 // The thread has exited and thread_local_tracker has died.
1230 ASSERT_EQ(1U, DestructorCall::List().size());
1231 EXPECT_TRUE(DestructorCall::List()[0]->CheckDestroyed());
1232
1233 DestructorCall::ResetList();
1234 }
1235
TEST(ThreadLocalTest,ThreadLocalMutationsAffectOnlyCurrentThread)1236 TEST(ThreadLocalTest, ThreadLocalMutationsAffectOnlyCurrentThread) {
1237 ThreadLocal<std::string> thread_local_string;
1238 thread_local_string.set("Foo");
1239 EXPECT_STREQ("Foo", thread_local_string.get().c_str());
1240
1241 std::string result;
1242 RunFromThread(&RetrieveThreadLocalValue,
1243 make_pair(&thread_local_string, &result));
1244 EXPECT_TRUE(result.empty());
1245 }
1246
1247 #endif // GTEST_IS_THREADSAFE
1248
1249 #if GTEST_OS_WINDOWS
TEST(WindowsTypesTest,HANDLEIsVoidStar)1250 TEST(WindowsTypesTest, HANDLEIsVoidStar) {
1251 StaticAssertTypeEq<HANDLE, void*>();
1252 }
1253
1254 #if GTEST_OS_WINDOWS_MINGW && !defined(__MINGW64_VERSION_MAJOR)
TEST(WindowsTypesTest,_CRITICAL_SECTIONIs_CRITICAL_SECTION)1255 TEST(WindowsTypesTest, _CRITICAL_SECTIONIs_CRITICAL_SECTION) {
1256 StaticAssertTypeEq<CRITICAL_SECTION, _CRITICAL_SECTION>();
1257 }
1258 #else
TEST(WindowsTypesTest,CRITICAL_SECTIONIs_RTL_CRITICAL_SECTION)1259 TEST(WindowsTypesTest, CRITICAL_SECTIONIs_RTL_CRITICAL_SECTION) {
1260 StaticAssertTypeEq<CRITICAL_SECTION, _RTL_CRITICAL_SECTION>();
1261 }
1262 #endif
1263
1264 #endif // GTEST_OS_WINDOWS
1265
1266 } // namespace internal
1267 } // namespace testing
1268