1 // Copyright 2008, Google Inc.
2 // All rights reserved.
4 // Redistribution and use in source and binary forms, with or without
5 // modification, are permitted provided that the following conditions are
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
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.
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.
30 // This file tests the internal cross-platform support utilities.
33 #include "gtest/internal/gtest-port.h"
37 #endif // GTEST_OS_MAC
39 #include <chrono> // NOLINT
42 #include <thread> // NOLINT
43 #include <utility> // For std::pair and std::make_pair.
46 #include "gtest/gtest-spi.h"
47 #include "gtest/gtest.h"
48 #include "src/gtest-internal-inl.h"
56 TEST(IsXDigitTest, WorksForNarrowAscii) {
57 EXPECT_TRUE(IsXDigit('0'));
58 EXPECT_TRUE(IsXDigit('9'));
59 EXPECT_TRUE(IsXDigit('A'));
60 EXPECT_TRUE(IsXDigit('F'));
61 EXPECT_TRUE(IsXDigit('a'));
62 EXPECT_TRUE(IsXDigit('f'));
64 EXPECT_FALSE(IsXDigit('-'));
65 EXPECT_FALSE(IsXDigit('g'));
66 EXPECT_FALSE(IsXDigit('G'));
69 TEST(IsXDigitTest, ReturnsFalseForNarrowNonAscii) {
70 EXPECT_FALSE(IsXDigit(static_cast<char>('\x80')));
71 EXPECT_FALSE(IsXDigit(static_cast<char>('0' | '\x80')));
74 TEST(IsXDigitTest, WorksForWideAscii) {
75 EXPECT_TRUE(IsXDigit(L'0'));
76 EXPECT_TRUE(IsXDigit(L'9'));
77 EXPECT_TRUE(IsXDigit(L'A'));
78 EXPECT_TRUE(IsXDigit(L'F'));
79 EXPECT_TRUE(IsXDigit(L'a'));
80 EXPECT_TRUE(IsXDigit(L'f'));
82 EXPECT_FALSE(IsXDigit(L'-'));
83 EXPECT_FALSE(IsXDigit(L'g'));
84 EXPECT_FALSE(IsXDigit(L'G'));
87 TEST(IsXDigitTest, ReturnsFalseForWideNonAscii) {
88 EXPECT_FALSE(IsXDigit(static_cast<wchar_t>(0x80)));
89 EXPECT_FALSE(IsXDigit(static_cast<wchar_t>(L'0' | 0x80)));
90 EXPECT_FALSE(IsXDigit(static_cast<wchar_t>(L'0' | 0x100)));
95 Base() : member_(0) {}
96 explicit Base(int n) : member_(n) {}
97 Base(const Base&) = default;
98 Base& operator=(const Base&) = default;
100 int member() { return member_; }
106 class Derived : public Base {
108 explicit Derived(int n) : Base(n) {}
111 TEST(ImplicitCastTest, ConvertsPointers) {
113 EXPECT_TRUE(&derived == ::testing::internal::ImplicitCast_<Base*>(&derived));
116 TEST(ImplicitCastTest, CanUseInheritance) {
118 Base base = ::testing::internal::ImplicitCast_<Base>(derived);
119 EXPECT_EQ(derived.member(), base.member());
124 explicit Castable(bool* converted) : converted_(converted) {}
134 TEST(ImplicitCastTest, CanUseNonConstCastOperator) {
135 bool converted = false;
136 Castable castable(&converted);
137 Base base = ::testing::internal::ImplicitCast_<Base>(castable);
138 EXPECT_TRUE(converted);
141 class ConstCastable {
143 explicit ConstCastable(bool* converted) : converted_(converted) {}
144 operator Base() const {
153 TEST(ImplicitCastTest, CanUseConstCastOperatorOnConstValues) {
154 bool converted = false;
155 const ConstCastable const_castable(&converted);
156 Base base = ::testing::internal::ImplicitCast_<Base>(const_castable);
157 EXPECT_TRUE(converted);
160 class ConstAndNonConstCastable {
162 ConstAndNonConstCastable(bool* converted, bool* const_converted)
163 : converted_(converted), const_converted_(const_converted) {}
168 operator Base() const {
169 *const_converted_ = true;
175 bool* const_converted_;
178 TEST(ImplicitCastTest, CanSelectBetweenConstAndNonConstCasrAppropriately) {
179 bool converted = false;
180 bool const_converted = false;
181 ConstAndNonConstCastable castable(&converted, &const_converted);
182 Base base = ::testing::internal::ImplicitCast_<Base>(castable);
183 EXPECT_TRUE(converted);
184 EXPECT_FALSE(const_converted);
187 const_converted = false;
188 const ConstAndNonConstCastable const_castable(&converted, &const_converted);
189 base = ::testing::internal::ImplicitCast_<Base>(const_castable);
190 EXPECT_FALSE(converted);
191 EXPECT_TRUE(const_converted);
196 To(bool* converted) { *converted = true; } // NOLINT
199 TEST(ImplicitCastTest, CanUseImplicitConstructor) {
200 bool converted = false;
201 To to = ::testing::internal::ImplicitCast_<To>(&converted);
203 EXPECT_TRUE(converted);
206 // The following code intentionally tests a suboptimal syntax.
208 #pragma GCC diagnostic push
209 #pragma GCC diagnostic ignored "-Wdangling-else"
210 #pragma GCC diagnostic ignored "-Wempty-body"
211 #pragma GCC diagnostic ignored "-Wpragmas"
213 TEST(GtestCheckSyntaxTest, BehavesLikeASingleStatement) {
215 GTEST_CHECK_(false) << "This should never be executed; "
216 "It's a compilation test only.";
226 GTEST_CHECK_(true) << "";
229 #pragma GCC diagnostic pop
232 TEST(GtestCheckSyntaxTest, WorksWithSwitch) {
242 GTEST_CHECK_(true) << "Check failed in switch case";
245 // Verifies behavior of FormatFileLocation.
246 TEST(FormatFileLocationTest, FormatsFileLocation) {
247 EXPECT_PRED_FORMAT2(IsSubstring, "foo.cc", FormatFileLocation("foo.cc", 42));
248 EXPECT_PRED_FORMAT2(IsSubstring, "42", FormatFileLocation("foo.cc", 42));
251 TEST(FormatFileLocationTest, FormatsUnknownFile) {
252 EXPECT_PRED_FORMAT2(IsSubstring, "unknown file",
253 FormatFileLocation(nullptr, 42));
254 EXPECT_PRED_FORMAT2(IsSubstring, "42", FormatFileLocation(nullptr, 42));
257 TEST(FormatFileLocationTest, FormatsUknownLine) {
258 EXPECT_EQ("foo.cc:", FormatFileLocation("foo.cc", -1));
261 TEST(FormatFileLocationTest, FormatsUknownFileAndLine) {
262 EXPECT_EQ("unknown file:", FormatFileLocation(nullptr, -1));
265 // Verifies behavior of FormatCompilerIndependentFileLocation.
266 TEST(FormatCompilerIndependentFileLocationTest, FormatsFileLocation) {
267 EXPECT_EQ("foo.cc:42", FormatCompilerIndependentFileLocation("foo.cc", 42));
270 TEST(FormatCompilerIndependentFileLocationTest, FormatsUknownFile) {
271 EXPECT_EQ("unknown file:42",
272 FormatCompilerIndependentFileLocation(nullptr, 42));
275 TEST(FormatCompilerIndependentFileLocationTest, FormatsUknownLine) {
276 EXPECT_EQ("foo.cc", FormatCompilerIndependentFileLocation("foo.cc", -1));
279 TEST(FormatCompilerIndependentFileLocationTest, FormatsUknownFileAndLine) {
280 EXPECT_EQ("unknown file", FormatCompilerIndependentFileLocation(nullptr, -1));
283 #if GTEST_OS_LINUX || GTEST_OS_MAC || GTEST_OS_QNX || GTEST_OS_FUCHSIA || \
284 GTEST_OS_DRAGONFLY || GTEST_OS_FREEBSD || GTEST_OS_GNU_KFREEBSD || \
285 GTEST_OS_NETBSD || GTEST_OS_OPENBSD || GTEST_OS_GNU_HURD
286 void* ThreadFunc(void* data) {
287 internal::Mutex* mutex = static_cast<internal::Mutex*>(data);
293 TEST(GetThreadCountTest, ReturnsCorrectValue) {
294 size_t starting_count;
295 size_t thread_count_after_create;
296 size_t thread_count_after_join;
298 // We can't guarantee that no other thread was created or destroyed between
299 // any two calls to GetThreadCount(). We make multiple attempts, hoping that
300 // background noise is not constant and we would see the "right" values at
302 for (int attempt = 0; attempt < 20; ++attempt) {
303 starting_count = GetThreadCount();
306 internal::Mutex mutex;
308 internal::MutexLock lock(&mutex);
310 ASSERT_EQ(0, pthread_attr_init(&attr));
311 ASSERT_EQ(0, pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_JOINABLE));
313 const int status = pthread_create(&thread_id, &attr, &ThreadFunc, &mutex);
314 ASSERT_EQ(0, pthread_attr_destroy(&attr));
315 ASSERT_EQ(0, status);
318 thread_count_after_create = GetThreadCount();
321 ASSERT_EQ(0, pthread_join(thread_id, &dummy));
323 // Join before we decide whether we need to retry the test. Retry if an
324 // arbitrary other thread was created or destroyed in the meantime.
325 if (thread_count_after_create != starting_count + 1) continue;
327 // The OS may not immediately report the updated thread count after
328 // joining a thread, causing flakiness in this test. To counter that, we
329 // wait for up to .5 seconds for the OS to report the correct value.
330 bool thread_count_matches = false;
331 for (int i = 0; i < 5; ++i) {
332 thread_count_after_join = GetThreadCount();
333 if (thread_count_after_join == starting_count) {
334 thread_count_matches = true;
338 std::this_thread::sleep_for(std::chrono::milliseconds(100));
341 // Retry if an arbitrary other thread was created or destroyed.
342 if (!thread_count_matches) continue;
347 EXPECT_EQ(thread_count_after_create, starting_count + 1);
348 EXPECT_EQ(thread_count_after_join, starting_count);
351 TEST(GetThreadCountTest, ReturnsZeroWhenUnableToCountThreads) {
352 EXPECT_EQ(0U, GetThreadCount());
354 #endif // GTEST_OS_LINUX || GTEST_OS_MAC || GTEST_OS_QNX || GTEST_OS_FUCHSIA
356 TEST(GtestCheckDeathTest, DiesWithCorrectOutputOnFailure) {
357 const bool a_false_condition = false;
360 "googletest-port-test\\.cc\\(\\d+\\):"
361 #elif GTEST_USES_POSIX_RE
362 "googletest-port-test\\.cc:[0-9]+"
364 "googletest-port-test\\.cc:\\d+"
366 ".*a_false_condition.*Extra info.*";
368 EXPECT_DEATH_IF_SUPPORTED(GTEST_CHECK_(a_false_condition) << "Extra info",
372 #if GTEST_HAS_DEATH_TEST
374 TEST(GtestCheckDeathTest, LivesSilentlyOnSuccess) {
377 GTEST_CHECK_(true) << "Extra info";
378 ::std::cerr << "Success\n";
381 ::testing::ExitedWithCode(0), "Success");
384 #endif // GTEST_HAS_DEATH_TEST
386 // Verifies that Google Test choose regular expression engine appropriate to
387 // the platform. The test will produce compiler errors in case of failure.
388 // For simplicity, we only cover the most important platforms here.
389 TEST(RegexEngineSelectionTest, SelectsCorrectRegexEngine) {
391 EXPECT_TRUE(GTEST_USES_RE2);
392 #elif GTEST_HAS_POSIX_RE
393 EXPECT_TRUE(GTEST_USES_POSIX_RE);
395 EXPECT_TRUE(GTEST_USES_SIMPLE_RE);
399 #if GTEST_USES_POSIX_RE
401 template <typename Str>
402 class RETest : public ::testing::Test {};
404 // Defines StringTypes as the list of all string types that class RE
406 typedef testing::Types< ::std::string, const char*> StringTypes;
408 TYPED_TEST_SUITE(RETest, StringTypes);
410 // Tests RE's implicit constructors.
411 TYPED_TEST(RETest, ImplicitConstructorWorks) {
412 const RE empty(TypeParam(""));
413 EXPECT_STREQ("", empty.pattern());
415 const RE simple(TypeParam("hello"));
416 EXPECT_STREQ("hello", simple.pattern());
418 const RE normal(TypeParam(".*(\\w+)"));
419 EXPECT_STREQ(".*(\\w+)", normal.pattern());
422 // Tests that RE's constructors reject invalid regular expressions.
423 TYPED_TEST(RETest, RejectsInvalidRegex) {
424 EXPECT_NONFATAL_FAILURE(
425 { const RE invalid(TypeParam("?")); },
426 "\"?\" is not a valid POSIX Extended regular expression.");
429 // Tests RE::FullMatch().
430 TYPED_TEST(RETest, FullMatchWorks) {
431 const RE empty(TypeParam(""));
432 EXPECT_TRUE(RE::FullMatch(TypeParam(""), empty));
433 EXPECT_FALSE(RE::FullMatch(TypeParam("a"), empty));
435 const RE re(TypeParam("a.*z"));
436 EXPECT_TRUE(RE::FullMatch(TypeParam("az"), re));
437 EXPECT_TRUE(RE::FullMatch(TypeParam("axyz"), re));
438 EXPECT_FALSE(RE::FullMatch(TypeParam("baz"), re));
439 EXPECT_FALSE(RE::FullMatch(TypeParam("azy"), re));
442 // Tests RE::PartialMatch().
443 TYPED_TEST(RETest, PartialMatchWorks) {
444 const RE empty(TypeParam(""));
445 EXPECT_TRUE(RE::PartialMatch(TypeParam(""), empty));
446 EXPECT_TRUE(RE::PartialMatch(TypeParam("a"), empty));
448 const RE re(TypeParam("a.*z"));
449 EXPECT_TRUE(RE::PartialMatch(TypeParam("az"), re));
450 EXPECT_TRUE(RE::PartialMatch(TypeParam("axyz"), re));
451 EXPECT_TRUE(RE::PartialMatch(TypeParam("baz"), re));
452 EXPECT_TRUE(RE::PartialMatch(TypeParam("azy"), re));
453 EXPECT_FALSE(RE::PartialMatch(TypeParam("zza"), re));
456 #elif GTEST_USES_SIMPLE_RE
458 TEST(IsInSetTest, NulCharIsNotInAnySet) {
459 EXPECT_FALSE(IsInSet('\0', ""));
460 EXPECT_FALSE(IsInSet('\0', "\0"));
461 EXPECT_FALSE(IsInSet('\0', "a"));
464 TEST(IsInSetTest, WorksForNonNulChars) {
465 EXPECT_FALSE(IsInSet('a', "Ab"));
466 EXPECT_FALSE(IsInSet('c', ""));
468 EXPECT_TRUE(IsInSet('b', "bcd"));
469 EXPECT_TRUE(IsInSet('b', "ab"));
472 TEST(IsAsciiDigitTest, IsFalseForNonDigit) {
473 EXPECT_FALSE(IsAsciiDigit('\0'));
474 EXPECT_FALSE(IsAsciiDigit(' '));
475 EXPECT_FALSE(IsAsciiDigit('+'));
476 EXPECT_FALSE(IsAsciiDigit('-'));
477 EXPECT_FALSE(IsAsciiDigit('.'));
478 EXPECT_FALSE(IsAsciiDigit('a'));
481 TEST(IsAsciiDigitTest, IsTrueForDigit) {
482 EXPECT_TRUE(IsAsciiDigit('0'));
483 EXPECT_TRUE(IsAsciiDigit('1'));
484 EXPECT_TRUE(IsAsciiDigit('5'));
485 EXPECT_TRUE(IsAsciiDigit('9'));
488 TEST(IsAsciiPunctTest, IsFalseForNonPunct) {
489 EXPECT_FALSE(IsAsciiPunct('\0'));
490 EXPECT_FALSE(IsAsciiPunct(' '));
491 EXPECT_FALSE(IsAsciiPunct('\n'));
492 EXPECT_FALSE(IsAsciiPunct('a'));
493 EXPECT_FALSE(IsAsciiPunct('0'));
496 TEST(IsAsciiPunctTest, IsTrueForPunct) {
497 for (const char* p = "^-!\"#$%&'()*+,./:;<=>?@[\\]_`{|}~"; *p; p++) {
498 EXPECT_PRED1(IsAsciiPunct, *p);
502 TEST(IsRepeatTest, IsFalseForNonRepeatChar) {
503 EXPECT_FALSE(IsRepeat('\0'));
504 EXPECT_FALSE(IsRepeat(' '));
505 EXPECT_FALSE(IsRepeat('a'));
506 EXPECT_FALSE(IsRepeat('1'));
507 EXPECT_FALSE(IsRepeat('-'));
510 TEST(IsRepeatTest, IsTrueForRepeatChar) {
511 EXPECT_TRUE(IsRepeat('?'));
512 EXPECT_TRUE(IsRepeat('*'));
513 EXPECT_TRUE(IsRepeat('+'));
516 TEST(IsAsciiWhiteSpaceTest, IsFalseForNonWhiteSpace) {
517 EXPECT_FALSE(IsAsciiWhiteSpace('\0'));
518 EXPECT_FALSE(IsAsciiWhiteSpace('a'));
519 EXPECT_FALSE(IsAsciiWhiteSpace('1'));
520 EXPECT_FALSE(IsAsciiWhiteSpace('+'));
521 EXPECT_FALSE(IsAsciiWhiteSpace('_'));
524 TEST(IsAsciiWhiteSpaceTest, IsTrueForWhiteSpace) {
525 EXPECT_TRUE(IsAsciiWhiteSpace(' '));
526 EXPECT_TRUE(IsAsciiWhiteSpace('\n'));
527 EXPECT_TRUE(IsAsciiWhiteSpace('\r'));
528 EXPECT_TRUE(IsAsciiWhiteSpace('\t'));
529 EXPECT_TRUE(IsAsciiWhiteSpace('\v'));
530 EXPECT_TRUE(IsAsciiWhiteSpace('\f'));
533 TEST(IsAsciiWordCharTest, IsFalseForNonWordChar) {
534 EXPECT_FALSE(IsAsciiWordChar('\0'));
535 EXPECT_FALSE(IsAsciiWordChar('+'));
536 EXPECT_FALSE(IsAsciiWordChar('.'));
537 EXPECT_FALSE(IsAsciiWordChar(' '));
538 EXPECT_FALSE(IsAsciiWordChar('\n'));
541 TEST(IsAsciiWordCharTest, IsTrueForLetter) {
542 EXPECT_TRUE(IsAsciiWordChar('a'));
543 EXPECT_TRUE(IsAsciiWordChar('b'));
544 EXPECT_TRUE(IsAsciiWordChar('A'));
545 EXPECT_TRUE(IsAsciiWordChar('Z'));
548 TEST(IsAsciiWordCharTest, IsTrueForDigit) {
549 EXPECT_TRUE(IsAsciiWordChar('0'));
550 EXPECT_TRUE(IsAsciiWordChar('1'));
551 EXPECT_TRUE(IsAsciiWordChar('7'));
552 EXPECT_TRUE(IsAsciiWordChar('9'));
555 TEST(IsAsciiWordCharTest, IsTrueForUnderscore) {
556 EXPECT_TRUE(IsAsciiWordChar('_'));
559 TEST(IsValidEscapeTest, IsFalseForNonPrintable) {
560 EXPECT_FALSE(IsValidEscape('\0'));
561 EXPECT_FALSE(IsValidEscape('\007'));
564 TEST(IsValidEscapeTest, IsFalseForDigit) {
565 EXPECT_FALSE(IsValidEscape('0'));
566 EXPECT_FALSE(IsValidEscape('9'));
569 TEST(IsValidEscapeTest, IsFalseForWhiteSpace) {
570 EXPECT_FALSE(IsValidEscape(' '));
571 EXPECT_FALSE(IsValidEscape('\n'));
574 TEST(IsValidEscapeTest, IsFalseForSomeLetter) {
575 EXPECT_FALSE(IsValidEscape('a'));
576 EXPECT_FALSE(IsValidEscape('Z'));
579 TEST(IsValidEscapeTest, IsTrueForPunct) {
580 EXPECT_TRUE(IsValidEscape('.'));
581 EXPECT_TRUE(IsValidEscape('-'));
582 EXPECT_TRUE(IsValidEscape('^'));
583 EXPECT_TRUE(IsValidEscape('$'));
584 EXPECT_TRUE(IsValidEscape('('));
585 EXPECT_TRUE(IsValidEscape(']'));
586 EXPECT_TRUE(IsValidEscape('{'));
587 EXPECT_TRUE(IsValidEscape('|'));
590 TEST(IsValidEscapeTest, IsTrueForSomeLetter) {
591 EXPECT_TRUE(IsValidEscape('d'));
592 EXPECT_TRUE(IsValidEscape('D'));
593 EXPECT_TRUE(IsValidEscape('s'));
594 EXPECT_TRUE(IsValidEscape('S'));
595 EXPECT_TRUE(IsValidEscape('w'));
596 EXPECT_TRUE(IsValidEscape('W'));
599 TEST(AtomMatchesCharTest, EscapedPunct) {
600 EXPECT_FALSE(AtomMatchesChar(true, '\\', '\0'));
601 EXPECT_FALSE(AtomMatchesChar(true, '\\', ' '));
602 EXPECT_FALSE(AtomMatchesChar(true, '_', '.'));
603 EXPECT_FALSE(AtomMatchesChar(true, '.', 'a'));
605 EXPECT_TRUE(AtomMatchesChar(true, '\\', '\\'));
606 EXPECT_TRUE(AtomMatchesChar(true, '_', '_'));
607 EXPECT_TRUE(AtomMatchesChar(true, '+', '+'));
608 EXPECT_TRUE(AtomMatchesChar(true, '.', '.'));
611 TEST(AtomMatchesCharTest, Escaped_d) {
612 EXPECT_FALSE(AtomMatchesChar(true, 'd', '\0'));
613 EXPECT_FALSE(AtomMatchesChar(true, 'd', 'a'));
614 EXPECT_FALSE(AtomMatchesChar(true, 'd', '.'));
616 EXPECT_TRUE(AtomMatchesChar(true, 'd', '0'));
617 EXPECT_TRUE(AtomMatchesChar(true, 'd', '9'));
620 TEST(AtomMatchesCharTest, Escaped_D) {
621 EXPECT_FALSE(AtomMatchesChar(true, 'D', '0'));
622 EXPECT_FALSE(AtomMatchesChar(true, 'D', '9'));
624 EXPECT_TRUE(AtomMatchesChar(true, 'D', '\0'));
625 EXPECT_TRUE(AtomMatchesChar(true, 'D', 'a'));
626 EXPECT_TRUE(AtomMatchesChar(true, 'D', '-'));
629 TEST(AtomMatchesCharTest, Escaped_s) {
630 EXPECT_FALSE(AtomMatchesChar(true, 's', '\0'));
631 EXPECT_FALSE(AtomMatchesChar(true, 's', 'a'));
632 EXPECT_FALSE(AtomMatchesChar(true, 's', '.'));
633 EXPECT_FALSE(AtomMatchesChar(true, 's', '9'));
635 EXPECT_TRUE(AtomMatchesChar(true, 's', ' '));
636 EXPECT_TRUE(AtomMatchesChar(true, 's', '\n'));
637 EXPECT_TRUE(AtomMatchesChar(true, 's', '\t'));
640 TEST(AtomMatchesCharTest, Escaped_S) {
641 EXPECT_FALSE(AtomMatchesChar(true, 'S', ' '));
642 EXPECT_FALSE(AtomMatchesChar(true, 'S', '\r'));
644 EXPECT_TRUE(AtomMatchesChar(true, 'S', '\0'));
645 EXPECT_TRUE(AtomMatchesChar(true, 'S', 'a'));
646 EXPECT_TRUE(AtomMatchesChar(true, 'S', '9'));
649 TEST(AtomMatchesCharTest, Escaped_w) {
650 EXPECT_FALSE(AtomMatchesChar(true, 'w', '\0'));
651 EXPECT_FALSE(AtomMatchesChar(true, 'w', '+'));
652 EXPECT_FALSE(AtomMatchesChar(true, 'w', ' '));
653 EXPECT_FALSE(AtomMatchesChar(true, 'w', '\n'));
655 EXPECT_TRUE(AtomMatchesChar(true, 'w', '0'));
656 EXPECT_TRUE(AtomMatchesChar(true, 'w', 'b'));
657 EXPECT_TRUE(AtomMatchesChar(true, 'w', 'C'));
658 EXPECT_TRUE(AtomMatchesChar(true, 'w', '_'));
661 TEST(AtomMatchesCharTest, Escaped_W) {
662 EXPECT_FALSE(AtomMatchesChar(true, 'W', 'A'));
663 EXPECT_FALSE(AtomMatchesChar(true, 'W', 'b'));
664 EXPECT_FALSE(AtomMatchesChar(true, 'W', '9'));
665 EXPECT_FALSE(AtomMatchesChar(true, 'W', '_'));
667 EXPECT_TRUE(AtomMatchesChar(true, 'W', '\0'));
668 EXPECT_TRUE(AtomMatchesChar(true, 'W', '*'));
669 EXPECT_TRUE(AtomMatchesChar(true, 'W', '\n'));
672 TEST(AtomMatchesCharTest, EscapedWhiteSpace) {
673 EXPECT_FALSE(AtomMatchesChar(true, 'f', '\0'));
674 EXPECT_FALSE(AtomMatchesChar(true, 'f', '\n'));
675 EXPECT_FALSE(AtomMatchesChar(true, 'n', '\0'));
676 EXPECT_FALSE(AtomMatchesChar(true, 'n', '\r'));
677 EXPECT_FALSE(AtomMatchesChar(true, 'r', '\0'));
678 EXPECT_FALSE(AtomMatchesChar(true, 'r', 'a'));
679 EXPECT_FALSE(AtomMatchesChar(true, 't', '\0'));
680 EXPECT_FALSE(AtomMatchesChar(true, 't', 't'));
681 EXPECT_FALSE(AtomMatchesChar(true, 'v', '\0'));
682 EXPECT_FALSE(AtomMatchesChar(true, 'v', '\f'));
684 EXPECT_TRUE(AtomMatchesChar(true, 'f', '\f'));
685 EXPECT_TRUE(AtomMatchesChar(true, 'n', '\n'));
686 EXPECT_TRUE(AtomMatchesChar(true, 'r', '\r'));
687 EXPECT_TRUE(AtomMatchesChar(true, 't', '\t'));
688 EXPECT_TRUE(AtomMatchesChar(true, 'v', '\v'));
691 TEST(AtomMatchesCharTest, UnescapedDot) {
692 EXPECT_FALSE(AtomMatchesChar(false, '.', '\n'));
694 EXPECT_TRUE(AtomMatchesChar(false, '.', '\0'));
695 EXPECT_TRUE(AtomMatchesChar(false, '.', '.'));
696 EXPECT_TRUE(AtomMatchesChar(false, '.', 'a'));
697 EXPECT_TRUE(AtomMatchesChar(false, '.', ' '));
700 TEST(AtomMatchesCharTest, UnescapedChar) {
701 EXPECT_FALSE(AtomMatchesChar(false, 'a', '\0'));
702 EXPECT_FALSE(AtomMatchesChar(false, 'a', 'b'));
703 EXPECT_FALSE(AtomMatchesChar(false, '$', 'a'));
705 EXPECT_TRUE(AtomMatchesChar(false, '$', '$'));
706 EXPECT_TRUE(AtomMatchesChar(false, '5', '5'));
707 EXPECT_TRUE(AtomMatchesChar(false, 'Z', 'Z'));
710 TEST(ValidateRegexTest, GeneratesFailureAndReturnsFalseForInvalid) {
711 EXPECT_NONFATAL_FAILURE(ASSERT_FALSE(ValidateRegex(NULL)),
712 "NULL is not a valid simple regular expression");
713 EXPECT_NONFATAL_FAILURE(
714 ASSERT_FALSE(ValidateRegex("a\\")),
715 "Syntax error at index 1 in simple regular expression \"a\\\": ");
716 EXPECT_NONFATAL_FAILURE(ASSERT_FALSE(ValidateRegex("a\\")),
717 "'\\' cannot appear at the end");
718 EXPECT_NONFATAL_FAILURE(ASSERT_FALSE(ValidateRegex("\\n\\")),
719 "'\\' cannot appear at the end");
720 EXPECT_NONFATAL_FAILURE(ASSERT_FALSE(ValidateRegex("\\s\\hb")),
721 "invalid escape sequence \"\\h\"");
722 EXPECT_NONFATAL_FAILURE(ASSERT_FALSE(ValidateRegex("^^")),
723 "'^' can only appear at the beginning");
724 EXPECT_NONFATAL_FAILURE(ASSERT_FALSE(ValidateRegex(".*^b")),
725 "'^' can only appear at the beginning");
726 EXPECT_NONFATAL_FAILURE(ASSERT_FALSE(ValidateRegex("$$")),
727 "'$' can only appear at the end");
728 EXPECT_NONFATAL_FAILURE(ASSERT_FALSE(ValidateRegex("^$a")),
729 "'$' can only appear at the end");
730 EXPECT_NONFATAL_FAILURE(ASSERT_FALSE(ValidateRegex("a(b")),
731 "'(' is unsupported");
732 EXPECT_NONFATAL_FAILURE(ASSERT_FALSE(ValidateRegex("ab)")),
733 "')' is unsupported");
734 EXPECT_NONFATAL_FAILURE(ASSERT_FALSE(ValidateRegex("[ab")),
735 "'[' is unsupported");
736 EXPECT_NONFATAL_FAILURE(ASSERT_FALSE(ValidateRegex("a{2")),
737 "'{' is unsupported");
738 EXPECT_NONFATAL_FAILURE(ASSERT_FALSE(ValidateRegex("?")),
739 "'?' can only follow a repeatable token");
740 EXPECT_NONFATAL_FAILURE(ASSERT_FALSE(ValidateRegex("^*")),
741 "'*' can only follow a repeatable token");
742 EXPECT_NONFATAL_FAILURE(ASSERT_FALSE(ValidateRegex("5*+")),
743 "'+' can only follow a repeatable token");
746 TEST(ValidateRegexTest, ReturnsTrueForValid) {
747 EXPECT_TRUE(ValidateRegex(""));
748 EXPECT_TRUE(ValidateRegex("a"));
749 EXPECT_TRUE(ValidateRegex(".*"));
750 EXPECT_TRUE(ValidateRegex("^a_+"));
751 EXPECT_TRUE(ValidateRegex("^a\\t\\&?"));
752 EXPECT_TRUE(ValidateRegex("09*$"));
753 EXPECT_TRUE(ValidateRegex("^Z$"));
754 EXPECT_TRUE(ValidateRegex("a\\^Z\\$\\(\\)\\|\\[\\]\\{\\}"));
757 TEST(MatchRepetitionAndRegexAtHeadTest, WorksForZeroOrOne) {
758 EXPECT_FALSE(MatchRepetitionAndRegexAtHead(false, 'a', '?', "a", "ba"));
759 // Repeating more than once.
760 EXPECT_FALSE(MatchRepetitionAndRegexAtHead(false, 'a', '?', "b", "aab"));
762 // Repeating zero times.
763 EXPECT_TRUE(MatchRepetitionAndRegexAtHead(false, 'a', '?', "b", "ba"));
765 EXPECT_TRUE(MatchRepetitionAndRegexAtHead(false, 'a', '?', "b", "ab"));
766 EXPECT_TRUE(MatchRepetitionAndRegexAtHead(false, '#', '?', ".", "##"));
769 TEST(MatchRepetitionAndRegexAtHeadTest, WorksForZeroOrMany) {
770 EXPECT_FALSE(MatchRepetitionAndRegexAtHead(false, '.', '*', "a$", "baab"));
772 // Repeating zero times.
773 EXPECT_TRUE(MatchRepetitionAndRegexAtHead(false, '.', '*', "b", "bc"));
775 EXPECT_TRUE(MatchRepetitionAndRegexAtHead(false, '.', '*', "b", "abc"));
776 // Repeating more than once.
777 EXPECT_TRUE(MatchRepetitionAndRegexAtHead(true, 'w', '*', "-", "ab_1-g"));
780 TEST(MatchRepetitionAndRegexAtHeadTest, WorksForOneOrMany) {
781 EXPECT_FALSE(MatchRepetitionAndRegexAtHead(false, '.', '+', "a$", "baab"));
782 // Repeating zero times.
783 EXPECT_FALSE(MatchRepetitionAndRegexAtHead(false, '.', '+', "b", "bc"));
786 EXPECT_TRUE(MatchRepetitionAndRegexAtHead(false, '.', '+', "b", "abc"));
787 // Repeating more than once.
788 EXPECT_TRUE(MatchRepetitionAndRegexAtHead(true, 'w', '+', "-", "ab_1-g"));
791 TEST(MatchRegexAtHeadTest, ReturnsTrueForEmptyRegex) {
792 EXPECT_TRUE(MatchRegexAtHead("", ""));
793 EXPECT_TRUE(MatchRegexAtHead("", "ab"));
796 TEST(MatchRegexAtHeadTest, WorksWhenDollarIsInRegex) {
797 EXPECT_FALSE(MatchRegexAtHead("$", "a"));
799 EXPECT_TRUE(MatchRegexAtHead("$", ""));
800 EXPECT_TRUE(MatchRegexAtHead("a$", "a"));
803 TEST(MatchRegexAtHeadTest, WorksWhenRegexStartsWithEscapeSequence) {
804 EXPECT_FALSE(MatchRegexAtHead("\\w", "+"));
805 EXPECT_FALSE(MatchRegexAtHead("\\W", "ab"));
807 EXPECT_TRUE(MatchRegexAtHead("\\sa", "\nab"));
808 EXPECT_TRUE(MatchRegexAtHead("\\d", "1a"));
811 TEST(MatchRegexAtHeadTest, WorksWhenRegexStartsWithRepetition) {
812 EXPECT_FALSE(MatchRegexAtHead(".+a", "abc"));
813 EXPECT_FALSE(MatchRegexAtHead("a?b", "aab"));
815 EXPECT_TRUE(MatchRegexAtHead(".*a", "bc12-ab"));
816 EXPECT_TRUE(MatchRegexAtHead("a?b", "b"));
817 EXPECT_TRUE(MatchRegexAtHead("a?b", "ab"));
820 TEST(MatchRegexAtHeadTest, WorksWhenRegexStartsWithRepetionOfEscapeSequence) {
821 EXPECT_FALSE(MatchRegexAtHead("\\.+a", "abc"));
822 EXPECT_FALSE(MatchRegexAtHead("\\s?b", " b"));
824 EXPECT_TRUE(MatchRegexAtHead("\\(*a", "((((ab"));
825 EXPECT_TRUE(MatchRegexAtHead("\\^?b", "^b"));
826 EXPECT_TRUE(MatchRegexAtHead("\\\\?b", "b"));
827 EXPECT_TRUE(MatchRegexAtHead("\\\\?b", "\\b"));
830 TEST(MatchRegexAtHeadTest, MatchesSequentially) {
831 EXPECT_FALSE(MatchRegexAtHead("ab.*c", "acabc"));
833 EXPECT_TRUE(MatchRegexAtHead("ab.*c", "ab-fsc"));
836 TEST(MatchRegexAnywhereTest, ReturnsFalseWhenStringIsNull) {
837 EXPECT_FALSE(MatchRegexAnywhere("", NULL));
840 TEST(MatchRegexAnywhereTest, WorksWhenRegexStartsWithCaret) {
841 EXPECT_FALSE(MatchRegexAnywhere("^a", "ba"));
842 EXPECT_FALSE(MatchRegexAnywhere("^$", "a"));
844 EXPECT_TRUE(MatchRegexAnywhere("^a", "ab"));
845 EXPECT_TRUE(MatchRegexAnywhere("^", "ab"));
846 EXPECT_TRUE(MatchRegexAnywhere("^$", ""));
849 TEST(MatchRegexAnywhereTest, ReturnsFalseWhenNoMatch) {
850 EXPECT_FALSE(MatchRegexAnywhere("a", "bcde123"));
851 EXPECT_FALSE(MatchRegexAnywhere("a.+a", "--aa88888888"));
854 TEST(MatchRegexAnywhereTest, ReturnsTrueWhenMatchingPrefix) {
855 EXPECT_TRUE(MatchRegexAnywhere("\\w+", "ab1_ - 5"));
856 EXPECT_TRUE(MatchRegexAnywhere(".*=", "="));
857 EXPECT_TRUE(MatchRegexAnywhere("x.*ab?.*bc", "xaaabc"));
860 TEST(MatchRegexAnywhereTest, ReturnsTrueWhenMatchingNonPrefix) {
861 EXPECT_TRUE(MatchRegexAnywhere("\\w+", "$$$ ab1_ - 5"));
862 EXPECT_TRUE(MatchRegexAnywhere("\\.+=", "= ...="));
865 // Tests RE's implicit constructors.
866 TEST(RETest, ImplicitConstructorWorks) {
868 EXPECT_STREQ("", empty.pattern());
870 const RE simple("hello");
871 EXPECT_STREQ("hello", simple.pattern());
874 // Tests that RE's constructors reject invalid regular expressions.
875 TEST(RETest, RejectsInvalidRegex) {
876 EXPECT_NONFATAL_FAILURE({ const RE normal(NULL); },
877 "NULL is not a valid simple regular expression");
879 EXPECT_NONFATAL_FAILURE({ const RE normal(".*(\\w+"); },
880 "'(' is unsupported");
882 EXPECT_NONFATAL_FAILURE({ const RE invalid("^?"); },
883 "'?' can only follow a repeatable token");
886 // Tests RE::FullMatch().
887 TEST(RETest, FullMatchWorks) {
889 EXPECT_TRUE(RE::FullMatch("", empty));
890 EXPECT_FALSE(RE::FullMatch("a", empty));
893 EXPECT_TRUE(RE::FullMatch("a", re1));
896 EXPECT_TRUE(RE::FullMatch("az", re));
897 EXPECT_TRUE(RE::FullMatch("axyz", re));
898 EXPECT_FALSE(RE::FullMatch("baz", re));
899 EXPECT_FALSE(RE::FullMatch("azy", re));
902 // Tests RE::PartialMatch().
903 TEST(RETest, PartialMatchWorks) {
905 EXPECT_TRUE(RE::PartialMatch("", empty));
906 EXPECT_TRUE(RE::PartialMatch("a", empty));
909 EXPECT_TRUE(RE::PartialMatch("az", re));
910 EXPECT_TRUE(RE::PartialMatch("axyz", re));
911 EXPECT_TRUE(RE::PartialMatch("baz", re));
912 EXPECT_TRUE(RE::PartialMatch("azy", re));
913 EXPECT_FALSE(RE::PartialMatch("zza", re));
916 #endif // GTEST_USES_POSIX_RE
918 #if !GTEST_OS_WINDOWS_MOBILE
920 TEST(CaptureTest, CapturesStdout) {
922 fprintf(stdout, "abc");
923 EXPECT_STREQ("abc", GetCapturedStdout().c_str());
926 fprintf(stdout, "def%cghi", '\0');
927 EXPECT_EQ(::std::string("def\0ghi", 7), ::std::string(GetCapturedStdout()));
930 TEST(CaptureTest, CapturesStderr) {
932 fprintf(stderr, "jkl");
933 EXPECT_STREQ("jkl", GetCapturedStderr().c_str());
936 fprintf(stderr, "jkl%cmno", '\0');
937 EXPECT_EQ(::std::string("jkl\0mno", 7), ::std::string(GetCapturedStderr()));
940 // Tests that stdout and stderr capture don't interfere with each other.
941 TEST(CaptureTest, CapturesStdoutAndStderr) {
944 fprintf(stdout, "pqr");
945 fprintf(stderr, "stu");
946 EXPECT_STREQ("pqr", GetCapturedStdout().c_str());
947 EXPECT_STREQ("stu", GetCapturedStderr().c_str());
950 TEST(CaptureDeathTest, CannotReenterStdoutCapture) {
952 EXPECT_DEATH_IF_SUPPORTED(CaptureStdout(),
953 "Only one stdout capturer can exist at a time");
956 // We cannot test stderr capturing using death tests as they use it
960 #endif // !GTEST_OS_WINDOWS_MOBILE
962 TEST(ThreadLocalTest, DefaultConstructorInitializesToDefaultValues) {
964 EXPECT_EQ(0, t1.get());
966 ThreadLocal<void*> t2;
967 EXPECT_TRUE(t2.get() == nullptr);
970 TEST(ThreadLocalTest, SingleParamConstructorInitializesToParam) {
971 ThreadLocal<int> t1(123);
972 EXPECT_EQ(123, t1.get());
975 ThreadLocal<int*> t2(&i);
976 EXPECT_EQ(&i, t2.get());
979 class NoDefaultContructor {
981 explicit NoDefaultContructor(const char*) {}
982 NoDefaultContructor(const NoDefaultContructor&) {}
985 TEST(ThreadLocalTest, ValueDefaultContructorIsNotRequiredForParamVersion) {
986 ThreadLocal<NoDefaultContructor> bar(NoDefaultContructor("foo"));
990 TEST(ThreadLocalTest, GetAndPointerReturnSameValue) {
991 ThreadLocal<std::string> thread_local_string;
993 EXPECT_EQ(thread_local_string.pointer(), &(thread_local_string.get()));
995 // Verifies the condition still holds after calling set.
996 thread_local_string.set("foo");
997 EXPECT_EQ(thread_local_string.pointer(), &(thread_local_string.get()));
1000 TEST(ThreadLocalTest, PointerAndConstPointerReturnSameValue) {
1001 ThreadLocal<std::string> thread_local_string;
1002 const ThreadLocal<std::string>& const_thread_local_string =
1003 thread_local_string;
1005 EXPECT_EQ(thread_local_string.pointer(), const_thread_local_string.pointer());
1007 thread_local_string.set("foo");
1008 EXPECT_EQ(thread_local_string.pointer(), const_thread_local_string.pointer());
1011 #if GTEST_IS_THREADSAFE
1013 void AddTwo(int* param) { *param += 2; }
1015 TEST(ThreadWithParamTest, ConstructorExecutesThreadFunc) {
1017 ThreadWithParam<int*> thread(&AddTwo, &i, nullptr);
1022 TEST(MutexDeathTest, AssertHeldShouldAssertWhenNotLocked) {
1023 // AssertHeld() is flaky only in the presence of multiple threads accessing
1024 // the lock. In this case, the test is robust.
1025 EXPECT_DEATH_IF_SUPPORTED(
1028 { MutexLock lock(&m); }
1034 TEST(MutexTest, AssertHeldShouldNotAssertWhenLocked) {
1040 class AtomicCounterWithMutex {
1042 explicit AtomicCounterWithMutex(Mutex* mutex)
1043 : value_(0), mutex_(mutex), random_(42) {}
1046 MutexLock lock(mutex_);
1049 // We need to put up a memory barrier to prevent reads and writes to
1050 // value_ rearranged with the call to sleep_for when observed
1051 // from other threads.
1052 #if GTEST_HAS_PTHREAD
1053 // On POSIX, locking a mutex puts up a memory barrier. We cannot use
1054 // Mutex and MutexLock here or rely on their memory barrier
1055 // functionality as we are testing them here.
1056 pthread_mutex_t memory_barrier_mutex;
1057 GTEST_CHECK_POSIX_SUCCESS_(
1058 pthread_mutex_init(&memory_barrier_mutex, nullptr));
1059 GTEST_CHECK_POSIX_SUCCESS_(pthread_mutex_lock(&memory_barrier_mutex));
1061 std::this_thread::sleep_for(
1062 std::chrono::milliseconds(random_.Generate(30)));
1064 GTEST_CHECK_POSIX_SUCCESS_(pthread_mutex_unlock(&memory_barrier_mutex));
1065 GTEST_CHECK_POSIX_SUCCESS_(pthread_mutex_destroy(&memory_barrier_mutex));
1066 #elif GTEST_OS_WINDOWS
1067 // On Windows, performing an interlocked access puts up a memory barrier.
1068 volatile LONG dummy = 0;
1069 ::InterlockedIncrement(&dummy);
1070 std::this_thread::sleep_for(
1071 std::chrono::milliseconds(random_.Generate(30)));
1072 ::InterlockedIncrement(&dummy);
1074 #error "Memory barrier not implemented on this platform."
1075 #endif // GTEST_HAS_PTHREAD
1079 int value() const { return value_; }
1082 volatile int value_;
1083 Mutex* const mutex_; // Protects value_.
1087 void CountingThreadFunc(pair<AtomicCounterWithMutex*, int> param) {
1088 for (int i = 0; i < param.second; ++i) param.first->Increment();
1091 // Tests that the mutex only lets one thread at a time to lock it.
1092 TEST(MutexTest, OnlyOneThreadCanLockAtATime) {
1094 AtomicCounterWithMutex locked_counter(&mutex);
1096 typedef ThreadWithParam<pair<AtomicCounterWithMutex*, int> > ThreadType;
1097 const int kCycleCount = 20;
1098 const int kThreadCount = 7;
1099 std::unique_ptr<ThreadType> counting_threads[kThreadCount];
1100 Notification threads_can_start;
1101 // Creates and runs kThreadCount threads that increment locked_counter
1102 // kCycleCount times each.
1103 for (int i = 0; i < kThreadCount; ++i) {
1104 counting_threads[i].reset(new ThreadType(
1105 &CountingThreadFunc, make_pair(&locked_counter, kCycleCount),
1106 &threads_can_start));
1108 threads_can_start.Notify();
1109 for (int i = 0; i < kThreadCount; ++i) counting_threads[i]->Join();
1111 // If the mutex lets more than one thread to increment the counter at a
1112 // time, they are likely to encounter a race condition and have some
1113 // increments overwritten, resulting in the lower then expected counter
1115 EXPECT_EQ(kCycleCount * kThreadCount, locked_counter.value());
1118 template <typename T>
1119 void RunFromThread(void(func)(T), T param) {
1120 ThreadWithParam<T> thread(func, param, nullptr);
1124 void RetrieveThreadLocalValue(
1125 pair<ThreadLocal<std::string>*, std::string*> param) {
1126 *param.second = param.first->get();
1129 TEST(ThreadLocalTest, ParameterizedConstructorSetsDefault) {
1130 ThreadLocal<std::string> thread_local_string("foo");
1131 EXPECT_STREQ("foo", thread_local_string.get().c_str());
1133 thread_local_string.set("bar");
1134 EXPECT_STREQ("bar", thread_local_string.get().c_str());
1137 RunFromThread(&RetrieveThreadLocalValue,
1138 make_pair(&thread_local_string, &result));
1139 EXPECT_STREQ("foo", result.c_str());
1142 // Keeps track of whether of destructors being called on instances of
1143 // DestructorTracker. On Windows, waits for the destructor call reports.
1144 class DestructorCall {
1148 #if GTEST_OS_WINDOWS
1149 wait_event_.Reset(::CreateEvent(NULL, TRUE, FALSE, NULL));
1150 GTEST_CHECK_(wait_event_.Get() != NULL);
1154 bool CheckDestroyed() const {
1155 #if GTEST_OS_WINDOWS
1156 if (::WaitForSingleObject(wait_event_.Get(), 1000) != WAIT_OBJECT_0)
1162 void ReportDestroyed() {
1164 #if GTEST_OS_WINDOWS
1165 ::SetEvent(wait_event_.Get());
1169 static std::vector<DestructorCall*>& List() { return *list_; }
1171 static void ResetList() {
1172 for (size_t i = 0; i < list_->size(); ++i) {
1173 delete list_->at(i);
1180 #if GTEST_OS_WINDOWS
1181 AutoHandle wait_event_;
1183 static std::vector<DestructorCall*>* const list_;
1185 DestructorCall(const DestructorCall&) = delete;
1186 DestructorCall& operator=(const DestructorCall&) = delete;
1189 std::vector<DestructorCall*>* const DestructorCall::list_ =
1190 new std::vector<DestructorCall*>;
1192 // DestructorTracker keeps track of whether its instances have been
1194 class DestructorTracker {
1196 DestructorTracker() : index_(GetNewIndex()) {}
1197 DestructorTracker(const DestructorTracker& /* rhs */)
1198 : index_(GetNewIndex()) {}
1199 ~DestructorTracker() {
1200 // We never access DestructorCall::List() concurrently, so we don't need
1201 // to protect this access with a mutex.
1202 DestructorCall::List()[index_]->ReportDestroyed();
1206 static size_t GetNewIndex() {
1207 DestructorCall::List().push_back(new DestructorCall);
1208 return DestructorCall::List().size() - 1;
1210 const size_t index_;
1213 typedef ThreadLocal<DestructorTracker>* ThreadParam;
1215 void CallThreadLocalGet(ThreadParam thread_local_param) {
1216 thread_local_param->get();
1219 // Tests that when a ThreadLocal object dies in a thread, it destroys
1220 // the managed object for that thread.
1221 TEST(ThreadLocalTest, DestroysManagedObjectForOwnThreadWhenDying) {
1222 DestructorCall::ResetList();
1225 ThreadLocal<DestructorTracker> thread_local_tracker;
1226 ASSERT_EQ(0U, DestructorCall::List().size());
1228 // This creates another DestructorTracker object for the main thread.
1229 thread_local_tracker.get();
1230 ASSERT_EQ(1U, DestructorCall::List().size());
1231 ASSERT_FALSE(DestructorCall::List()[0]->CheckDestroyed());
1234 // Now thread_local_tracker has died.
1235 ASSERT_EQ(1U, DestructorCall::List().size());
1236 EXPECT_TRUE(DestructorCall::List()[0]->CheckDestroyed());
1238 DestructorCall::ResetList();
1241 // Tests that when a thread exits, the thread-local object for that
1242 // thread is destroyed.
1243 TEST(ThreadLocalTest, DestroysManagedObjectAtThreadExit) {
1244 DestructorCall::ResetList();
1247 ThreadLocal<DestructorTracker> thread_local_tracker;
1248 ASSERT_EQ(0U, DestructorCall::List().size());
1250 // This creates another DestructorTracker object in the new thread.
1251 ThreadWithParam<ThreadParam> thread(&CallThreadLocalGet,
1252 &thread_local_tracker, nullptr);
1255 // The thread has exited, and we should have a DestroyedTracker
1256 // instance created for it. But it may not have been destroyed yet.
1257 ASSERT_EQ(1U, DestructorCall::List().size());
1260 // The thread has exited and thread_local_tracker has died.
1261 ASSERT_EQ(1U, DestructorCall::List().size());
1262 EXPECT_TRUE(DestructorCall::List()[0]->CheckDestroyed());
1264 DestructorCall::ResetList();
1267 TEST(ThreadLocalTest, ThreadLocalMutationsAffectOnlyCurrentThread) {
1268 ThreadLocal<std::string> thread_local_string;
1269 thread_local_string.set("Foo");
1270 EXPECT_STREQ("Foo", thread_local_string.get().c_str());
1273 RunFromThread(&RetrieveThreadLocalValue,
1274 make_pair(&thread_local_string, &result));
1275 EXPECT_TRUE(result.empty());
1278 #endif // GTEST_IS_THREADSAFE
1280 #if GTEST_OS_WINDOWS
1281 TEST(WindowsTypesTest, HANDLEIsVoidStar) {
1282 StaticAssertTypeEq<HANDLE, void*>();
1285 #if GTEST_OS_WINDOWS_MINGW && !defined(__MINGW64_VERSION_MAJOR)
1286 TEST(WindowsTypesTest, _CRITICAL_SECTIONIs_CRITICAL_SECTION) {
1287 StaticAssertTypeEq<CRITICAL_SECTION, _CRITICAL_SECTION>();
1290 TEST(WindowsTypesTest, CRITICAL_SECTIONIs_RTL_CRITICAL_SECTION) {
1291 StaticAssertTypeEq<CRITICAL_SECTION, _RTL_CRITICAL_SECTION>();
1295 #endif // GTEST_OS_WINDOWS
1297 } // namespace internal
1298 } // namespace testing