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
43 #include <thread> // NOLINT
44 #include <utility> // For std::pair and std::make_pair.
47 #include "gtest/gtest-spi.h"
48 #include "gtest/gtest.h"
49 #include "src/gtest-internal-inl.h"
57 TEST(IsXDigitTest, WorksForNarrowAscii) {
58 EXPECT_TRUE(IsXDigit('0'));
59 EXPECT_TRUE(IsXDigit('9'));
60 EXPECT_TRUE(IsXDigit('A'));
61 EXPECT_TRUE(IsXDigit('F'));
62 EXPECT_TRUE(IsXDigit('a'));
63 EXPECT_TRUE(IsXDigit('f'));
65 EXPECT_FALSE(IsXDigit('-'));
66 EXPECT_FALSE(IsXDigit('g'));
67 EXPECT_FALSE(IsXDigit('G'));
70 TEST(IsXDigitTest, ReturnsFalseForNarrowNonAscii) {
71 EXPECT_FALSE(IsXDigit(static_cast<char>('\x80')));
72 EXPECT_FALSE(IsXDigit(static_cast<char>('0' | '\x80')));
75 TEST(IsXDigitTest, WorksForWideAscii) {
76 EXPECT_TRUE(IsXDigit(L'0'));
77 EXPECT_TRUE(IsXDigit(L'9'));
78 EXPECT_TRUE(IsXDigit(L'A'));
79 EXPECT_TRUE(IsXDigit(L'F'));
80 EXPECT_TRUE(IsXDigit(L'a'));
81 EXPECT_TRUE(IsXDigit(L'f'));
83 EXPECT_FALSE(IsXDigit(L'-'));
84 EXPECT_FALSE(IsXDigit(L'g'));
85 EXPECT_FALSE(IsXDigit(L'G'));
88 TEST(IsXDigitTest, ReturnsFalseForWideNonAscii) {
89 EXPECT_FALSE(IsXDigit(static_cast<wchar_t>(0x80)));
90 EXPECT_FALSE(IsXDigit(static_cast<wchar_t>(L'0' | 0x80)));
91 EXPECT_FALSE(IsXDigit(static_cast<wchar_t>(L'0' | 0x100)));
96 Base() : member_(0) {}
97 explicit Base(int n) : member_(n) {}
98 Base(const Base&) = default;
99 Base& operator=(const Base&) = default;
100 virtual ~Base() = default;
101 int member() { return member_; }
107 class Derived : public Base {
109 explicit Derived(int n) : Base(n) {}
112 TEST(ImplicitCastTest, ConvertsPointers) {
114 EXPECT_TRUE(&derived == ::testing::internal::ImplicitCast_<Base*>(&derived));
117 TEST(ImplicitCastTest, CanUseInheritance) {
119 Base base = ::testing::internal::ImplicitCast_<Base>(derived);
120 EXPECT_EQ(derived.member(), base.member());
125 explicit Castable(bool* converted) : converted_(converted) {}
135 TEST(ImplicitCastTest, CanUseNonConstCastOperator) {
136 bool converted = false;
137 Castable castable(&converted);
138 Base base = ::testing::internal::ImplicitCast_<Base>(castable);
139 EXPECT_TRUE(converted);
142 class ConstCastable {
144 explicit ConstCastable(bool* converted) : converted_(converted) {}
145 operator Base() const {
154 TEST(ImplicitCastTest, CanUseConstCastOperatorOnConstValues) {
155 bool converted = false;
156 const ConstCastable const_castable(&converted);
157 Base base = ::testing::internal::ImplicitCast_<Base>(const_castable);
158 EXPECT_TRUE(converted);
161 class ConstAndNonConstCastable {
163 ConstAndNonConstCastable(bool* converted, bool* const_converted)
164 : converted_(converted), const_converted_(const_converted) {}
169 operator Base() const {
170 *const_converted_ = true;
176 bool* const_converted_;
179 TEST(ImplicitCastTest, CanSelectBetweenConstAndNonConstCasrAppropriately) {
180 bool converted = false;
181 bool const_converted = false;
182 ConstAndNonConstCastable castable(&converted, &const_converted);
183 Base base = ::testing::internal::ImplicitCast_<Base>(castable);
184 EXPECT_TRUE(converted);
185 EXPECT_FALSE(const_converted);
188 const_converted = false;
189 const ConstAndNonConstCastable const_castable(&converted, &const_converted);
190 base = ::testing::internal::ImplicitCast_<Base>(const_castable);
191 EXPECT_FALSE(converted);
192 EXPECT_TRUE(const_converted);
197 To(bool* converted) { *converted = true; } // NOLINT
200 TEST(ImplicitCastTest, CanUseImplicitConstructor) {
201 bool converted = false;
202 To to = ::testing::internal::ImplicitCast_<To>(&converted);
204 EXPECT_TRUE(converted);
207 // The following code intentionally tests a suboptimal syntax.
209 #pragma GCC diagnostic push
210 #pragma GCC diagnostic ignored "-Wdangling-else"
211 #pragma GCC diagnostic ignored "-Wempty-body"
212 #pragma GCC diagnostic ignored "-Wpragmas"
214 TEST(GtestCheckSyntaxTest, BehavesLikeASingleStatement) {
216 GTEST_CHECK_(false) << "This should never be executed; "
217 "It's a compilation test only.";
227 GTEST_CHECK_(true) << "";
230 #pragma GCC diagnostic pop
233 TEST(GtestCheckSyntaxTest, WorksWithSwitch) {
243 GTEST_CHECK_(true) << "Check failed in switch case";
246 // Verifies behavior of FormatFileLocation.
247 TEST(FormatFileLocationTest, FormatsFileLocation) {
248 EXPECT_PRED_FORMAT2(IsSubstring, "foo.cc", FormatFileLocation("foo.cc", 42));
249 EXPECT_PRED_FORMAT2(IsSubstring, "42", FormatFileLocation("foo.cc", 42));
252 TEST(FormatFileLocationTest, FormatsUnknownFile) {
253 EXPECT_PRED_FORMAT2(IsSubstring, "unknown file",
254 FormatFileLocation(nullptr, 42));
255 EXPECT_PRED_FORMAT2(IsSubstring, "42", FormatFileLocation(nullptr, 42));
258 TEST(FormatFileLocationTest, FormatsUknownLine) {
259 EXPECT_EQ("foo.cc:", FormatFileLocation("foo.cc", -1));
262 TEST(FormatFileLocationTest, FormatsUknownFileAndLine) {
263 EXPECT_EQ("unknown file:", FormatFileLocation(nullptr, -1));
266 // Verifies behavior of FormatCompilerIndependentFileLocation.
267 TEST(FormatCompilerIndependentFileLocationTest, FormatsFileLocation) {
268 EXPECT_EQ("foo.cc:42", FormatCompilerIndependentFileLocation("foo.cc", 42));
271 TEST(FormatCompilerIndependentFileLocationTest, FormatsUknownFile) {
272 EXPECT_EQ("unknown file:42",
273 FormatCompilerIndependentFileLocation(nullptr, 42));
276 TEST(FormatCompilerIndependentFileLocationTest, FormatsUknownLine) {
277 EXPECT_EQ("foo.cc", FormatCompilerIndependentFileLocation("foo.cc", -1));
280 TEST(FormatCompilerIndependentFileLocationTest, FormatsUknownFileAndLine) {
281 EXPECT_EQ("unknown file", FormatCompilerIndependentFileLocation(nullptr, -1));
284 #if defined(GTEST_OS_LINUX) || defined(GTEST_OS_MAC) || \
285 defined(GTEST_OS_QNX) || defined(GTEST_OS_FUCHSIA) || \
286 defined(GTEST_OS_DRAGONFLY) || defined(GTEST_OS_FREEBSD) || \
287 defined(GTEST_OS_GNU_KFREEBSD) || defined(GTEST_OS_NETBSD) || \
288 defined(GTEST_OS_OPENBSD) || defined(GTEST_OS_GNU_HURD)
289 void* ThreadFunc(void* data) {
290 internal::Mutex* mutex = static_cast<internal::Mutex*>(data);
296 TEST(GetThreadCountTest, ReturnsCorrectValue) {
297 size_t starting_count;
298 size_t thread_count_after_create;
299 size_t thread_count_after_join;
301 // We can't guarantee that no other thread was created or destroyed between
302 // any two calls to GetThreadCount(). We make multiple attempts, hoping that
303 // background noise is not constant and we would see the "right" values at
305 for (int attempt = 0; attempt < 20; ++attempt) {
306 starting_count = GetThreadCount();
309 internal::Mutex mutex;
311 internal::MutexLock lock(&mutex);
313 ASSERT_EQ(0, pthread_attr_init(&attr));
314 ASSERT_EQ(0, pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_JOINABLE));
316 const int status = pthread_create(&thread_id, &attr, &ThreadFunc, &mutex);
317 ASSERT_EQ(0, pthread_attr_destroy(&attr));
318 ASSERT_EQ(0, status);
321 thread_count_after_create = GetThreadCount();
324 ASSERT_EQ(0, pthread_join(thread_id, &dummy));
326 // Join before we decide whether we need to retry the test. Retry if an
327 // arbitrary other thread was created or destroyed in the meantime.
328 if (thread_count_after_create != starting_count + 1) continue;
330 // The OS may not immediately report the updated thread count after
331 // joining a thread, causing flakiness in this test. To counter that, we
332 // wait for up to .5 seconds for the OS to report the correct value.
333 bool thread_count_matches = false;
334 for (int i = 0; i < 5; ++i) {
335 thread_count_after_join = GetThreadCount();
336 if (thread_count_after_join == starting_count) {
337 thread_count_matches = true;
341 std::this_thread::sleep_for(std::chrono::milliseconds(100));
344 // Retry if an arbitrary other thread was created or destroyed.
345 if (!thread_count_matches) continue;
350 EXPECT_EQ(thread_count_after_create, starting_count + 1);
351 EXPECT_EQ(thread_count_after_join, starting_count);
354 TEST(GetThreadCountTest, ReturnsZeroWhenUnableToCountThreads) {
355 EXPECT_EQ(0U, GetThreadCount());
357 #endif // GTEST_OS_LINUX || GTEST_OS_MAC || GTEST_OS_QNX || GTEST_OS_FUCHSIA
359 TEST(GtestCheckDeathTest, DiesWithCorrectOutputOnFailure) {
360 const bool a_false_condition = false;
363 "googletest-port-test\\.cc\\(\\d+\\):"
364 #elif defined(GTEST_USES_POSIX_RE)
365 "googletest-port-test\\.cc:[0-9]+"
367 "googletest-port-test\\.cc:\\d+"
369 ".*a_false_condition.*Extra info.*";
371 EXPECT_DEATH_IF_SUPPORTED(GTEST_CHECK_(a_false_condition) << "Extra info",
375 #ifdef GTEST_HAS_DEATH_TEST
377 TEST(GtestCheckDeathTest, LivesSilentlyOnSuccess) {
380 GTEST_CHECK_(true) << "Extra info";
381 ::std::cerr << "Success\n";
384 ::testing::ExitedWithCode(0), "Success");
387 #endif // GTEST_HAS_DEATH_TEST
389 // Verifies that Google Test choose regular expression engine appropriate to
390 // the platform. The test will produce compiler errors in case of failure.
391 // For simplicity, we only cover the most important platforms here.
392 TEST(RegexEngineSelectionTest, SelectsCorrectRegexEngine) {
393 #ifdef GTEST_HAS_ABSL
394 EXPECT_TRUE(GTEST_USES_RE2);
395 #elif GTEST_HAS_POSIX_RE
396 EXPECT_TRUE(GTEST_USES_POSIX_RE);
398 EXPECT_TRUE(GTEST_USES_SIMPLE_RE);
402 #ifdef GTEST_USES_POSIX_RE
404 template <typename Str>
405 class RETest : public ::testing::Test {};
407 // Defines StringTypes as the list of all string types that class RE
409 typedef testing::Types< ::std::string, const char*> StringTypes;
411 TYPED_TEST_SUITE(RETest, StringTypes);
413 // Tests RE's implicit constructors.
414 TYPED_TEST(RETest, ImplicitConstructorWorks) {
415 const RE empty(TypeParam(""));
416 EXPECT_STREQ("", empty.pattern());
418 const RE simple(TypeParam("hello"));
419 EXPECT_STREQ("hello", simple.pattern());
421 const RE normal(TypeParam(".*(\\w+)"));
422 EXPECT_STREQ(".*(\\w+)", normal.pattern());
425 // Tests that RE's constructors reject invalid regular expressions.
426 TYPED_TEST(RETest, RejectsInvalidRegex) {
427 EXPECT_NONFATAL_FAILURE(
428 { const RE invalid(TypeParam("?")); },
429 "\"?\" is not a valid POSIX Extended regular expression.");
432 // Tests RE::FullMatch().
433 TYPED_TEST(RETest, FullMatchWorks) {
434 const RE empty(TypeParam(""));
435 EXPECT_TRUE(RE::FullMatch(TypeParam(""), empty));
436 EXPECT_FALSE(RE::FullMatch(TypeParam("a"), empty));
438 const RE re(TypeParam("a.*z"));
439 EXPECT_TRUE(RE::FullMatch(TypeParam("az"), re));
440 EXPECT_TRUE(RE::FullMatch(TypeParam("axyz"), re));
441 EXPECT_FALSE(RE::FullMatch(TypeParam("baz"), re));
442 EXPECT_FALSE(RE::FullMatch(TypeParam("azy"), re));
445 // Tests RE::PartialMatch().
446 TYPED_TEST(RETest, PartialMatchWorks) {
447 const RE empty(TypeParam(""));
448 EXPECT_TRUE(RE::PartialMatch(TypeParam(""), empty));
449 EXPECT_TRUE(RE::PartialMatch(TypeParam("a"), empty));
451 const RE re(TypeParam("a.*z"));
452 EXPECT_TRUE(RE::PartialMatch(TypeParam("az"), re));
453 EXPECT_TRUE(RE::PartialMatch(TypeParam("axyz"), re));
454 EXPECT_TRUE(RE::PartialMatch(TypeParam("baz"), re));
455 EXPECT_TRUE(RE::PartialMatch(TypeParam("azy"), re));
456 EXPECT_FALSE(RE::PartialMatch(TypeParam("zza"), re));
459 #elif defined(GTEST_USES_SIMPLE_RE)
461 TEST(IsInSetTest, NulCharIsNotInAnySet) {
462 EXPECT_FALSE(IsInSet('\0', ""));
463 EXPECT_FALSE(IsInSet('\0', "\0"));
464 EXPECT_FALSE(IsInSet('\0', "a"));
467 TEST(IsInSetTest, WorksForNonNulChars) {
468 EXPECT_FALSE(IsInSet('a', "Ab"));
469 EXPECT_FALSE(IsInSet('c', ""));
471 EXPECT_TRUE(IsInSet('b', "bcd"));
472 EXPECT_TRUE(IsInSet('b', "ab"));
475 TEST(IsAsciiDigitTest, IsFalseForNonDigit) {
476 EXPECT_FALSE(IsAsciiDigit('\0'));
477 EXPECT_FALSE(IsAsciiDigit(' '));
478 EXPECT_FALSE(IsAsciiDigit('+'));
479 EXPECT_FALSE(IsAsciiDigit('-'));
480 EXPECT_FALSE(IsAsciiDigit('.'));
481 EXPECT_FALSE(IsAsciiDigit('a'));
484 TEST(IsAsciiDigitTest, IsTrueForDigit) {
485 EXPECT_TRUE(IsAsciiDigit('0'));
486 EXPECT_TRUE(IsAsciiDigit('1'));
487 EXPECT_TRUE(IsAsciiDigit('5'));
488 EXPECT_TRUE(IsAsciiDigit('9'));
491 TEST(IsAsciiPunctTest, IsFalseForNonPunct) {
492 EXPECT_FALSE(IsAsciiPunct('\0'));
493 EXPECT_FALSE(IsAsciiPunct(' '));
494 EXPECT_FALSE(IsAsciiPunct('\n'));
495 EXPECT_FALSE(IsAsciiPunct('a'));
496 EXPECT_FALSE(IsAsciiPunct('0'));
499 TEST(IsAsciiPunctTest, IsTrueForPunct) {
500 for (const char* p = "^-!\"#$%&'()*+,./:;<=>?@[\\]_`{|}~"; *p; p++) {
501 EXPECT_PRED1(IsAsciiPunct, *p);
505 TEST(IsRepeatTest, IsFalseForNonRepeatChar) {
506 EXPECT_FALSE(IsRepeat('\0'));
507 EXPECT_FALSE(IsRepeat(' '));
508 EXPECT_FALSE(IsRepeat('a'));
509 EXPECT_FALSE(IsRepeat('1'));
510 EXPECT_FALSE(IsRepeat('-'));
513 TEST(IsRepeatTest, IsTrueForRepeatChar) {
514 EXPECT_TRUE(IsRepeat('?'));
515 EXPECT_TRUE(IsRepeat('*'));
516 EXPECT_TRUE(IsRepeat('+'));
519 TEST(IsAsciiWhiteSpaceTest, IsFalseForNonWhiteSpace) {
520 EXPECT_FALSE(IsAsciiWhiteSpace('\0'));
521 EXPECT_FALSE(IsAsciiWhiteSpace('a'));
522 EXPECT_FALSE(IsAsciiWhiteSpace('1'));
523 EXPECT_FALSE(IsAsciiWhiteSpace('+'));
524 EXPECT_FALSE(IsAsciiWhiteSpace('_'));
527 TEST(IsAsciiWhiteSpaceTest, IsTrueForWhiteSpace) {
528 EXPECT_TRUE(IsAsciiWhiteSpace(' '));
529 EXPECT_TRUE(IsAsciiWhiteSpace('\n'));
530 EXPECT_TRUE(IsAsciiWhiteSpace('\r'));
531 EXPECT_TRUE(IsAsciiWhiteSpace('\t'));
532 EXPECT_TRUE(IsAsciiWhiteSpace('\v'));
533 EXPECT_TRUE(IsAsciiWhiteSpace('\f'));
536 TEST(IsAsciiWordCharTest, IsFalseForNonWordChar) {
537 EXPECT_FALSE(IsAsciiWordChar('\0'));
538 EXPECT_FALSE(IsAsciiWordChar('+'));
539 EXPECT_FALSE(IsAsciiWordChar('.'));
540 EXPECT_FALSE(IsAsciiWordChar(' '));
541 EXPECT_FALSE(IsAsciiWordChar('\n'));
544 TEST(IsAsciiWordCharTest, IsTrueForLetter) {
545 EXPECT_TRUE(IsAsciiWordChar('a'));
546 EXPECT_TRUE(IsAsciiWordChar('b'));
547 EXPECT_TRUE(IsAsciiWordChar('A'));
548 EXPECT_TRUE(IsAsciiWordChar('Z'));
551 TEST(IsAsciiWordCharTest, IsTrueForDigit) {
552 EXPECT_TRUE(IsAsciiWordChar('0'));
553 EXPECT_TRUE(IsAsciiWordChar('1'));
554 EXPECT_TRUE(IsAsciiWordChar('7'));
555 EXPECT_TRUE(IsAsciiWordChar('9'));
558 TEST(IsAsciiWordCharTest, IsTrueForUnderscore) {
559 EXPECT_TRUE(IsAsciiWordChar('_'));
562 TEST(IsValidEscapeTest, IsFalseForNonPrintable) {
563 EXPECT_FALSE(IsValidEscape('\0'));
564 EXPECT_FALSE(IsValidEscape('\007'));
567 TEST(IsValidEscapeTest, IsFalseForDigit) {
568 EXPECT_FALSE(IsValidEscape('0'));
569 EXPECT_FALSE(IsValidEscape('9'));
572 TEST(IsValidEscapeTest, IsFalseForWhiteSpace) {
573 EXPECT_FALSE(IsValidEscape(' '));
574 EXPECT_FALSE(IsValidEscape('\n'));
577 TEST(IsValidEscapeTest, IsFalseForSomeLetter) {
578 EXPECT_FALSE(IsValidEscape('a'));
579 EXPECT_FALSE(IsValidEscape('Z'));
582 TEST(IsValidEscapeTest, IsTrueForPunct) {
583 EXPECT_TRUE(IsValidEscape('.'));
584 EXPECT_TRUE(IsValidEscape('-'));
585 EXPECT_TRUE(IsValidEscape('^'));
586 EXPECT_TRUE(IsValidEscape('$'));
587 EXPECT_TRUE(IsValidEscape('('));
588 EXPECT_TRUE(IsValidEscape(']'));
589 EXPECT_TRUE(IsValidEscape('{'));
590 EXPECT_TRUE(IsValidEscape('|'));
593 TEST(IsValidEscapeTest, IsTrueForSomeLetter) {
594 EXPECT_TRUE(IsValidEscape('d'));
595 EXPECT_TRUE(IsValidEscape('D'));
596 EXPECT_TRUE(IsValidEscape('s'));
597 EXPECT_TRUE(IsValidEscape('S'));
598 EXPECT_TRUE(IsValidEscape('w'));
599 EXPECT_TRUE(IsValidEscape('W'));
602 TEST(AtomMatchesCharTest, EscapedPunct) {
603 EXPECT_FALSE(AtomMatchesChar(true, '\\', '\0'));
604 EXPECT_FALSE(AtomMatchesChar(true, '\\', ' '));
605 EXPECT_FALSE(AtomMatchesChar(true, '_', '.'));
606 EXPECT_FALSE(AtomMatchesChar(true, '.', 'a'));
608 EXPECT_TRUE(AtomMatchesChar(true, '\\', '\\'));
609 EXPECT_TRUE(AtomMatchesChar(true, '_', '_'));
610 EXPECT_TRUE(AtomMatchesChar(true, '+', '+'));
611 EXPECT_TRUE(AtomMatchesChar(true, '.', '.'));
614 TEST(AtomMatchesCharTest, Escaped_d) {
615 EXPECT_FALSE(AtomMatchesChar(true, 'd', '\0'));
616 EXPECT_FALSE(AtomMatchesChar(true, 'd', 'a'));
617 EXPECT_FALSE(AtomMatchesChar(true, 'd', '.'));
619 EXPECT_TRUE(AtomMatchesChar(true, 'd', '0'));
620 EXPECT_TRUE(AtomMatchesChar(true, 'd', '9'));
623 TEST(AtomMatchesCharTest, Escaped_D) {
624 EXPECT_FALSE(AtomMatchesChar(true, 'D', '0'));
625 EXPECT_FALSE(AtomMatchesChar(true, 'D', '9'));
627 EXPECT_TRUE(AtomMatchesChar(true, 'D', '\0'));
628 EXPECT_TRUE(AtomMatchesChar(true, 'D', 'a'));
629 EXPECT_TRUE(AtomMatchesChar(true, 'D', '-'));
632 TEST(AtomMatchesCharTest, Escaped_s) {
633 EXPECT_FALSE(AtomMatchesChar(true, 's', '\0'));
634 EXPECT_FALSE(AtomMatchesChar(true, 's', 'a'));
635 EXPECT_FALSE(AtomMatchesChar(true, 's', '.'));
636 EXPECT_FALSE(AtomMatchesChar(true, 's', '9'));
638 EXPECT_TRUE(AtomMatchesChar(true, 's', ' '));
639 EXPECT_TRUE(AtomMatchesChar(true, 's', '\n'));
640 EXPECT_TRUE(AtomMatchesChar(true, 's', '\t'));
643 TEST(AtomMatchesCharTest, Escaped_S) {
644 EXPECT_FALSE(AtomMatchesChar(true, 'S', ' '));
645 EXPECT_FALSE(AtomMatchesChar(true, 'S', '\r'));
647 EXPECT_TRUE(AtomMatchesChar(true, 'S', '\0'));
648 EXPECT_TRUE(AtomMatchesChar(true, 'S', 'a'));
649 EXPECT_TRUE(AtomMatchesChar(true, 'S', '9'));
652 TEST(AtomMatchesCharTest, Escaped_w) {
653 EXPECT_FALSE(AtomMatchesChar(true, 'w', '\0'));
654 EXPECT_FALSE(AtomMatchesChar(true, 'w', '+'));
655 EXPECT_FALSE(AtomMatchesChar(true, 'w', ' '));
656 EXPECT_FALSE(AtomMatchesChar(true, 'w', '\n'));
658 EXPECT_TRUE(AtomMatchesChar(true, 'w', '0'));
659 EXPECT_TRUE(AtomMatchesChar(true, 'w', 'b'));
660 EXPECT_TRUE(AtomMatchesChar(true, 'w', 'C'));
661 EXPECT_TRUE(AtomMatchesChar(true, 'w', '_'));
664 TEST(AtomMatchesCharTest, Escaped_W) {
665 EXPECT_FALSE(AtomMatchesChar(true, 'W', 'A'));
666 EXPECT_FALSE(AtomMatchesChar(true, 'W', 'b'));
667 EXPECT_FALSE(AtomMatchesChar(true, 'W', '9'));
668 EXPECT_FALSE(AtomMatchesChar(true, 'W', '_'));
670 EXPECT_TRUE(AtomMatchesChar(true, 'W', '\0'));
671 EXPECT_TRUE(AtomMatchesChar(true, 'W', '*'));
672 EXPECT_TRUE(AtomMatchesChar(true, 'W', '\n'));
675 TEST(AtomMatchesCharTest, EscapedWhiteSpace) {
676 EXPECT_FALSE(AtomMatchesChar(true, 'f', '\0'));
677 EXPECT_FALSE(AtomMatchesChar(true, 'f', '\n'));
678 EXPECT_FALSE(AtomMatchesChar(true, 'n', '\0'));
679 EXPECT_FALSE(AtomMatchesChar(true, 'n', '\r'));
680 EXPECT_FALSE(AtomMatchesChar(true, 'r', '\0'));
681 EXPECT_FALSE(AtomMatchesChar(true, 'r', 'a'));
682 EXPECT_FALSE(AtomMatchesChar(true, 't', '\0'));
683 EXPECT_FALSE(AtomMatchesChar(true, 't', 't'));
684 EXPECT_FALSE(AtomMatchesChar(true, 'v', '\0'));
685 EXPECT_FALSE(AtomMatchesChar(true, 'v', '\f'));
687 EXPECT_TRUE(AtomMatchesChar(true, 'f', '\f'));
688 EXPECT_TRUE(AtomMatchesChar(true, 'n', '\n'));
689 EXPECT_TRUE(AtomMatchesChar(true, 'r', '\r'));
690 EXPECT_TRUE(AtomMatchesChar(true, 't', '\t'));
691 EXPECT_TRUE(AtomMatchesChar(true, 'v', '\v'));
694 TEST(AtomMatchesCharTest, UnescapedDot) {
695 EXPECT_FALSE(AtomMatchesChar(false, '.', '\n'));
697 EXPECT_TRUE(AtomMatchesChar(false, '.', '\0'));
698 EXPECT_TRUE(AtomMatchesChar(false, '.', '.'));
699 EXPECT_TRUE(AtomMatchesChar(false, '.', 'a'));
700 EXPECT_TRUE(AtomMatchesChar(false, '.', ' '));
703 TEST(AtomMatchesCharTest, UnescapedChar) {
704 EXPECT_FALSE(AtomMatchesChar(false, 'a', '\0'));
705 EXPECT_FALSE(AtomMatchesChar(false, 'a', 'b'));
706 EXPECT_FALSE(AtomMatchesChar(false, '$', 'a'));
708 EXPECT_TRUE(AtomMatchesChar(false, '$', '$'));
709 EXPECT_TRUE(AtomMatchesChar(false, '5', '5'));
710 EXPECT_TRUE(AtomMatchesChar(false, 'Z', 'Z'));
713 TEST(ValidateRegexTest, GeneratesFailureAndReturnsFalseForInvalid) {
714 EXPECT_NONFATAL_FAILURE(ASSERT_FALSE(ValidateRegex(NULL)),
715 "NULL is not a valid simple regular expression");
716 EXPECT_NONFATAL_FAILURE(
717 ASSERT_FALSE(ValidateRegex("a\\")),
718 "Syntax error at index 1 in simple regular expression \"a\\\": ");
719 EXPECT_NONFATAL_FAILURE(ASSERT_FALSE(ValidateRegex("a\\")),
720 "'\\' cannot appear at the end");
721 EXPECT_NONFATAL_FAILURE(ASSERT_FALSE(ValidateRegex("\\n\\")),
722 "'\\' cannot appear at the end");
723 EXPECT_NONFATAL_FAILURE(ASSERT_FALSE(ValidateRegex("\\s\\hb")),
724 "invalid escape sequence \"\\h\"");
725 EXPECT_NONFATAL_FAILURE(ASSERT_FALSE(ValidateRegex("^^")),
726 "'^' can only appear at the beginning");
727 EXPECT_NONFATAL_FAILURE(ASSERT_FALSE(ValidateRegex(".*^b")),
728 "'^' can only appear at the beginning");
729 EXPECT_NONFATAL_FAILURE(ASSERT_FALSE(ValidateRegex("$$")),
730 "'$' can only appear at the end");
731 EXPECT_NONFATAL_FAILURE(ASSERT_FALSE(ValidateRegex("^$a")),
732 "'$' can only appear at the end");
733 EXPECT_NONFATAL_FAILURE(ASSERT_FALSE(ValidateRegex("a(b")),
734 "'(' is unsupported");
735 EXPECT_NONFATAL_FAILURE(ASSERT_FALSE(ValidateRegex("ab)")),
736 "')' is unsupported");
737 EXPECT_NONFATAL_FAILURE(ASSERT_FALSE(ValidateRegex("[ab")),
738 "'[' is unsupported");
739 EXPECT_NONFATAL_FAILURE(ASSERT_FALSE(ValidateRegex("a{2")),
740 "'{' is unsupported");
741 EXPECT_NONFATAL_FAILURE(ASSERT_FALSE(ValidateRegex("?")),
742 "'?' can only follow a repeatable token");
743 EXPECT_NONFATAL_FAILURE(ASSERT_FALSE(ValidateRegex("^*")),
744 "'*' can only follow a repeatable token");
745 EXPECT_NONFATAL_FAILURE(ASSERT_FALSE(ValidateRegex("5*+")),
746 "'+' can only follow a repeatable token");
749 TEST(ValidateRegexTest, ReturnsTrueForValid) {
750 EXPECT_TRUE(ValidateRegex(""));
751 EXPECT_TRUE(ValidateRegex("a"));
752 EXPECT_TRUE(ValidateRegex(".*"));
753 EXPECT_TRUE(ValidateRegex("^a_+"));
754 EXPECT_TRUE(ValidateRegex("^a\\t\\&?"));
755 EXPECT_TRUE(ValidateRegex("09*$"));
756 EXPECT_TRUE(ValidateRegex("^Z$"));
757 EXPECT_TRUE(ValidateRegex("a\\^Z\\$\\(\\)\\|\\[\\]\\{\\}"));
760 TEST(MatchRepetitionAndRegexAtHeadTest, WorksForZeroOrOne) {
761 EXPECT_FALSE(MatchRepetitionAndRegexAtHead(false, 'a', '?', "a", "ba"));
762 // Repeating more than once.
763 EXPECT_FALSE(MatchRepetitionAndRegexAtHead(false, 'a', '?', "b", "aab"));
765 // Repeating zero times.
766 EXPECT_TRUE(MatchRepetitionAndRegexAtHead(false, 'a', '?', "b", "ba"));
768 EXPECT_TRUE(MatchRepetitionAndRegexAtHead(false, 'a', '?', "b", "ab"));
769 EXPECT_TRUE(MatchRepetitionAndRegexAtHead(false, '#', '?', ".", "##"));
772 TEST(MatchRepetitionAndRegexAtHeadTest, WorksForZeroOrMany) {
773 EXPECT_FALSE(MatchRepetitionAndRegexAtHead(false, '.', '*', "a$", "baab"));
775 // Repeating zero times.
776 EXPECT_TRUE(MatchRepetitionAndRegexAtHead(false, '.', '*', "b", "bc"));
778 EXPECT_TRUE(MatchRepetitionAndRegexAtHead(false, '.', '*', "b", "abc"));
779 // Repeating more than once.
780 EXPECT_TRUE(MatchRepetitionAndRegexAtHead(true, 'w', '*', "-", "ab_1-g"));
783 TEST(MatchRepetitionAndRegexAtHeadTest, WorksForOneOrMany) {
784 EXPECT_FALSE(MatchRepetitionAndRegexAtHead(false, '.', '+', "a$", "baab"));
785 // Repeating zero times.
786 EXPECT_FALSE(MatchRepetitionAndRegexAtHead(false, '.', '+', "b", "bc"));
789 EXPECT_TRUE(MatchRepetitionAndRegexAtHead(false, '.', '+', "b", "abc"));
790 // Repeating more than once.
791 EXPECT_TRUE(MatchRepetitionAndRegexAtHead(true, 'w', '+', "-", "ab_1-g"));
794 TEST(MatchRegexAtHeadTest, ReturnsTrueForEmptyRegex) {
795 EXPECT_TRUE(MatchRegexAtHead("", ""));
796 EXPECT_TRUE(MatchRegexAtHead("", "ab"));
799 TEST(MatchRegexAtHeadTest, WorksWhenDollarIsInRegex) {
800 EXPECT_FALSE(MatchRegexAtHead("$", "a"));
802 EXPECT_TRUE(MatchRegexAtHead("$", ""));
803 EXPECT_TRUE(MatchRegexAtHead("a$", "a"));
806 TEST(MatchRegexAtHeadTest, WorksWhenRegexStartsWithEscapeSequence) {
807 EXPECT_FALSE(MatchRegexAtHead("\\w", "+"));
808 EXPECT_FALSE(MatchRegexAtHead("\\W", "ab"));
810 EXPECT_TRUE(MatchRegexAtHead("\\sa", "\nab"));
811 EXPECT_TRUE(MatchRegexAtHead("\\d", "1a"));
814 TEST(MatchRegexAtHeadTest, WorksWhenRegexStartsWithRepetition) {
815 EXPECT_FALSE(MatchRegexAtHead(".+a", "abc"));
816 EXPECT_FALSE(MatchRegexAtHead("a?b", "aab"));
818 EXPECT_TRUE(MatchRegexAtHead(".*a", "bc12-ab"));
819 EXPECT_TRUE(MatchRegexAtHead("a?b", "b"));
820 EXPECT_TRUE(MatchRegexAtHead("a?b", "ab"));
823 TEST(MatchRegexAtHeadTest, WorksWhenRegexStartsWithRepetionOfEscapeSequence) {
824 EXPECT_FALSE(MatchRegexAtHead("\\.+a", "abc"));
825 EXPECT_FALSE(MatchRegexAtHead("\\s?b", " b"));
827 EXPECT_TRUE(MatchRegexAtHead("\\(*a", "((((ab"));
828 EXPECT_TRUE(MatchRegexAtHead("\\^?b", "^b"));
829 EXPECT_TRUE(MatchRegexAtHead("\\\\?b", "b"));
830 EXPECT_TRUE(MatchRegexAtHead("\\\\?b", "\\b"));
833 TEST(MatchRegexAtHeadTest, MatchesSequentially) {
834 EXPECT_FALSE(MatchRegexAtHead("ab.*c", "acabc"));
836 EXPECT_TRUE(MatchRegexAtHead("ab.*c", "ab-fsc"));
839 TEST(MatchRegexAnywhereTest, ReturnsFalseWhenStringIsNull) {
840 EXPECT_FALSE(MatchRegexAnywhere("", NULL));
843 TEST(MatchRegexAnywhereTest, WorksWhenRegexStartsWithCaret) {
844 EXPECT_FALSE(MatchRegexAnywhere("^a", "ba"));
845 EXPECT_FALSE(MatchRegexAnywhere("^$", "a"));
847 EXPECT_TRUE(MatchRegexAnywhere("^a", "ab"));
848 EXPECT_TRUE(MatchRegexAnywhere("^", "ab"));
849 EXPECT_TRUE(MatchRegexAnywhere("^$", ""));
852 TEST(MatchRegexAnywhereTest, ReturnsFalseWhenNoMatch) {
853 EXPECT_FALSE(MatchRegexAnywhere("a", "bcde123"));
854 EXPECT_FALSE(MatchRegexAnywhere("a.+a", "--aa88888888"));
857 TEST(MatchRegexAnywhereTest, ReturnsTrueWhenMatchingPrefix) {
858 EXPECT_TRUE(MatchRegexAnywhere("\\w+", "ab1_ - 5"));
859 EXPECT_TRUE(MatchRegexAnywhere(".*=", "="));
860 EXPECT_TRUE(MatchRegexAnywhere("x.*ab?.*bc", "xaaabc"));
863 TEST(MatchRegexAnywhereTest, ReturnsTrueWhenMatchingNonPrefix) {
864 EXPECT_TRUE(MatchRegexAnywhere("\\w+", "$$$ ab1_ - 5"));
865 EXPECT_TRUE(MatchRegexAnywhere("\\.+=", "= ...="));
868 // Tests RE's implicit constructors.
869 TEST(RETest, ImplicitConstructorWorks) {
871 EXPECT_STREQ("", empty.pattern());
873 const RE simple("hello");
874 EXPECT_STREQ("hello", simple.pattern());
877 // Tests that RE's constructors reject invalid regular expressions.
878 TEST(RETest, RejectsInvalidRegex) {
879 EXPECT_NONFATAL_FAILURE({ const RE normal(NULL); },
880 "NULL is not a valid simple regular expression");
882 EXPECT_NONFATAL_FAILURE({ const RE normal(".*(\\w+"); },
883 "'(' is unsupported");
885 EXPECT_NONFATAL_FAILURE({ const RE invalid("^?"); },
886 "'?' can only follow a repeatable token");
889 // Tests RE::FullMatch().
890 TEST(RETest, FullMatchWorks) {
892 EXPECT_TRUE(RE::FullMatch("", empty));
893 EXPECT_FALSE(RE::FullMatch("a", empty));
896 EXPECT_TRUE(RE::FullMatch("a", re1));
899 EXPECT_TRUE(RE::FullMatch("az", re));
900 EXPECT_TRUE(RE::FullMatch("axyz", re));
901 EXPECT_FALSE(RE::FullMatch("baz", re));
902 EXPECT_FALSE(RE::FullMatch("azy", re));
905 // Tests RE::PartialMatch().
906 TEST(RETest, PartialMatchWorks) {
908 EXPECT_TRUE(RE::PartialMatch("", empty));
909 EXPECT_TRUE(RE::PartialMatch("a", empty));
912 EXPECT_TRUE(RE::PartialMatch("az", re));
913 EXPECT_TRUE(RE::PartialMatch("axyz", re));
914 EXPECT_TRUE(RE::PartialMatch("baz", re));
915 EXPECT_TRUE(RE::PartialMatch("azy", re));
916 EXPECT_FALSE(RE::PartialMatch("zza", re));
919 #endif // GTEST_USES_POSIX_RE
921 #ifndef GTEST_OS_WINDOWS_MOBILE
923 TEST(CaptureTest, CapturesStdout) {
925 fprintf(stdout, "abc");
926 EXPECT_STREQ("abc", GetCapturedStdout().c_str());
929 fprintf(stdout, "def%cghi", '\0');
930 EXPECT_EQ(::std::string("def\0ghi", 7), ::std::string(GetCapturedStdout()));
933 TEST(CaptureTest, CapturesStderr) {
935 fprintf(stderr, "jkl");
936 EXPECT_STREQ("jkl", GetCapturedStderr().c_str());
939 fprintf(stderr, "jkl%cmno", '\0');
940 EXPECT_EQ(::std::string("jkl\0mno", 7), ::std::string(GetCapturedStderr()));
943 // Tests that stdout and stderr capture don't interfere with each other.
944 TEST(CaptureTest, CapturesStdoutAndStderr) {
947 fprintf(stdout, "pqr");
948 fprintf(stderr, "stu");
949 EXPECT_STREQ("pqr", GetCapturedStdout().c_str());
950 EXPECT_STREQ("stu", GetCapturedStderr().c_str());
953 TEST(CaptureDeathTest, CannotReenterStdoutCapture) {
955 EXPECT_DEATH_IF_SUPPORTED(CaptureStdout(),
956 "Only one stdout capturer can exist at a time");
959 // We cannot test stderr capturing using death tests as they use it
963 #endif // !GTEST_OS_WINDOWS_MOBILE
965 TEST(ThreadLocalTest, DefaultConstructorInitializesToDefaultValues) {
967 EXPECT_EQ(0, t1.get());
969 ThreadLocal<void*> t2;
970 EXPECT_TRUE(t2.get() == nullptr);
973 TEST(ThreadLocalTest, SingleParamConstructorInitializesToParam) {
974 ThreadLocal<int> t1(123);
975 EXPECT_EQ(123, t1.get());
978 ThreadLocal<int*> t2(&i);
979 EXPECT_EQ(&i, t2.get());
982 class NoDefaultConstructor {
984 explicit NoDefaultConstructor(const char*) {}
985 NoDefaultConstructor(const NoDefaultConstructor&) = default;
988 TEST(ThreadLocalTest, ValueDefaultContructorIsNotRequiredForParamVersion) {
989 ThreadLocal<NoDefaultConstructor> bar(NoDefaultConstructor("foo"));
993 TEST(ThreadLocalTest, GetAndPointerReturnSameValue) {
994 ThreadLocal<std::string> thread_local_string;
996 EXPECT_EQ(thread_local_string.pointer(), &(thread_local_string.get()));
998 // Verifies the condition still holds after calling set.
999 thread_local_string.set("foo");
1000 EXPECT_EQ(thread_local_string.pointer(), &(thread_local_string.get()));
1003 TEST(ThreadLocalTest, PointerAndConstPointerReturnSameValue) {
1004 ThreadLocal<std::string> thread_local_string;
1005 const ThreadLocal<std::string>& const_thread_local_string =
1006 thread_local_string;
1008 EXPECT_EQ(thread_local_string.pointer(), const_thread_local_string.pointer());
1010 thread_local_string.set("foo");
1011 EXPECT_EQ(thread_local_string.pointer(), const_thread_local_string.pointer());
1014 #ifdef GTEST_IS_THREADSAFE
1016 void AddTwo(int* param) { *param += 2; }
1018 TEST(ThreadWithParamTest, ConstructorExecutesThreadFunc) {
1020 ThreadWithParam<int*> thread(&AddTwo, &i, nullptr);
1025 TEST(MutexDeathTest, AssertHeldShouldAssertWhenNotLocked) {
1026 // AssertHeld() is flaky only in the presence of multiple threads accessing
1027 // the lock. In this case, the test is robust.
1028 EXPECT_DEATH_IF_SUPPORTED(
1031 { MutexLock lock(&m); }
1037 TEST(MutexTest, AssertHeldShouldNotAssertWhenLocked) {
1043 class AtomicCounterWithMutex {
1045 explicit AtomicCounterWithMutex(Mutex* mutex)
1046 : value_(0), mutex_(mutex), random_(42) {}
1049 MutexLock lock(mutex_);
1052 // We need to put up a memory barrier to prevent reads and writes to
1053 // value_ rearranged with the call to sleep_for when observed
1054 // from other threads.
1055 #if GTEST_HAS_PTHREAD
1056 // On POSIX, locking a mutex puts up a memory barrier. We cannot use
1057 // Mutex and MutexLock here or rely on their memory barrier
1058 // functionality as we are testing them here.
1059 pthread_mutex_t memory_barrier_mutex;
1060 GTEST_CHECK_POSIX_SUCCESS_(
1061 pthread_mutex_init(&memory_barrier_mutex, nullptr));
1062 GTEST_CHECK_POSIX_SUCCESS_(pthread_mutex_lock(&memory_barrier_mutex));
1064 std::this_thread::sleep_for(
1065 std::chrono::milliseconds(random_.Generate(30)));
1067 GTEST_CHECK_POSIX_SUCCESS_(pthread_mutex_unlock(&memory_barrier_mutex));
1068 GTEST_CHECK_POSIX_SUCCESS_(pthread_mutex_destroy(&memory_barrier_mutex));
1069 #elif defined(GTEST_OS_WINDOWS)
1070 // On Windows, performing an interlocked access puts up a memory barrier.
1071 volatile LONG dummy = 0;
1072 ::InterlockedIncrement(&dummy);
1073 std::this_thread::sleep_for(
1074 std::chrono::milliseconds(random_.Generate(30)));
1075 ::InterlockedIncrement(&dummy);
1077 #error "Memory barrier not implemented on this platform."
1078 #endif // GTEST_HAS_PTHREAD
1082 int value() const { return value_; }
1085 volatile int value_;
1086 Mutex* const mutex_; // Protects value_.
1090 void CountingThreadFunc(pair<AtomicCounterWithMutex*, int> param) {
1091 for (int i = 0; i < param.second; ++i) param.first->Increment();
1094 // Tests that the mutex only lets one thread at a time to lock it.
1095 TEST(MutexTest, OnlyOneThreadCanLockAtATime) {
1097 AtomicCounterWithMutex locked_counter(&mutex);
1099 typedef ThreadWithParam<pair<AtomicCounterWithMutex*, int> > ThreadType;
1100 const int kCycleCount = 20;
1101 const int kThreadCount = 7;
1102 std::unique_ptr<ThreadType> counting_threads[kThreadCount];
1103 Notification threads_can_start;
1104 // Creates and runs kThreadCount threads that increment locked_counter
1105 // kCycleCount times each.
1106 for (int i = 0; i < kThreadCount; ++i) {
1107 counting_threads[i] = std::make_unique<ThreadType>(
1108 &CountingThreadFunc, make_pair(&locked_counter, kCycleCount),
1109 &threads_can_start);
1111 threads_can_start.Notify();
1112 for (int i = 0; i < kThreadCount; ++i) counting_threads[i]->Join();
1114 // If the mutex lets more than one thread to increment the counter at a
1115 // time, they are likely to encounter a race condition and have some
1116 // increments overwritten, resulting in the lower then expected counter
1118 EXPECT_EQ(kCycleCount * kThreadCount, locked_counter.value());
1121 template <typename T>
1122 void RunFromThread(void(func)(T), T param) {
1123 ThreadWithParam<T> thread(func, param, nullptr);
1127 void RetrieveThreadLocalValue(
1128 pair<ThreadLocal<std::string>*, std::string*> param) {
1129 *param.second = param.first->get();
1132 TEST(ThreadLocalTest, ParameterizedConstructorSetsDefault) {
1133 ThreadLocal<std::string> thread_local_string("foo");
1134 EXPECT_STREQ("foo", thread_local_string.get().c_str());
1136 thread_local_string.set("bar");
1137 EXPECT_STREQ("bar", thread_local_string.get().c_str());
1140 RunFromThread(&RetrieveThreadLocalValue,
1141 make_pair(&thread_local_string, &result));
1142 EXPECT_STREQ("foo", result.c_str());
1145 // Keeps track of whether of destructors being called on instances of
1146 // DestructorTracker. On Windows, waits for the destructor call reports.
1147 class DestructorCall {
1151 #ifdef GTEST_OS_WINDOWS
1152 wait_event_.Reset(::CreateEvent(NULL, TRUE, FALSE, NULL));
1153 GTEST_CHECK_(wait_event_.Get() != NULL);
1157 bool CheckDestroyed() const {
1158 #ifdef GTEST_OS_WINDOWS
1159 if (::WaitForSingleObject(wait_event_.Get(), 1000) != WAIT_OBJECT_0)
1165 void ReportDestroyed() {
1167 #ifdef GTEST_OS_WINDOWS
1168 ::SetEvent(wait_event_.Get());
1172 static std::vector<DestructorCall*>& List() { return *list_; }
1174 static void ResetList() {
1175 for (size_t i = 0; i < list_->size(); ++i) {
1176 delete list_->at(i);
1183 #ifdef GTEST_OS_WINDOWS
1184 AutoHandle wait_event_;
1186 static std::vector<DestructorCall*>* const list_;
1188 DestructorCall(const DestructorCall&) = delete;
1189 DestructorCall& operator=(const DestructorCall&) = delete;
1192 std::vector<DestructorCall*>* const DestructorCall::list_ =
1193 new std::vector<DestructorCall*>;
1195 // DestructorTracker keeps track of whether its instances have been
1197 class DestructorTracker {
1199 DestructorTracker() : index_(GetNewIndex()) {}
1200 DestructorTracker(const DestructorTracker& /* rhs */)
1201 : index_(GetNewIndex()) {}
1202 ~DestructorTracker() {
1203 // We never access DestructorCall::List() concurrently, so we don't need
1204 // to protect this access with a mutex.
1205 DestructorCall::List()[index_]->ReportDestroyed();
1209 static size_t GetNewIndex() {
1210 DestructorCall::List().push_back(new DestructorCall);
1211 return DestructorCall::List().size() - 1;
1213 const size_t index_;
1216 typedef ThreadLocal<DestructorTracker>* ThreadParam;
1218 void CallThreadLocalGet(ThreadParam thread_local_param) {
1219 thread_local_param->get();
1222 // Tests that when a ThreadLocal object dies in a thread, it destroys
1223 // the managed object for that thread.
1224 TEST(ThreadLocalTest, DestroysManagedObjectForOwnThreadWhenDying) {
1225 DestructorCall::ResetList();
1228 ThreadLocal<DestructorTracker> thread_local_tracker;
1229 ASSERT_EQ(0U, DestructorCall::List().size());
1231 // This creates another DestructorTracker object for the main thread.
1232 thread_local_tracker.get();
1233 ASSERT_EQ(1U, DestructorCall::List().size());
1234 ASSERT_FALSE(DestructorCall::List()[0]->CheckDestroyed());
1237 // Now thread_local_tracker has died.
1238 ASSERT_EQ(1U, DestructorCall::List().size());
1239 EXPECT_TRUE(DestructorCall::List()[0]->CheckDestroyed());
1241 DestructorCall::ResetList();
1244 // Tests that when a thread exits, the thread-local object for that
1245 // thread is destroyed.
1246 TEST(ThreadLocalTest, DestroysManagedObjectAtThreadExit) {
1247 DestructorCall::ResetList();
1250 ThreadLocal<DestructorTracker> thread_local_tracker;
1251 ASSERT_EQ(0U, DestructorCall::List().size());
1253 // This creates another DestructorTracker object in the new thread.
1254 ThreadWithParam<ThreadParam> thread(&CallThreadLocalGet,
1255 &thread_local_tracker, nullptr);
1258 // The thread has exited, and we should have a DestroyedTracker
1259 // instance created for it. But it may not have been destroyed yet.
1260 ASSERT_EQ(1U, DestructorCall::List().size());
1263 // The thread has exited and thread_local_tracker has died.
1264 ASSERT_EQ(1U, DestructorCall::List().size());
1265 EXPECT_TRUE(DestructorCall::List()[0]->CheckDestroyed());
1267 DestructorCall::ResetList();
1270 TEST(ThreadLocalTest, ThreadLocalMutationsAffectOnlyCurrentThread) {
1271 ThreadLocal<std::string> thread_local_string;
1272 thread_local_string.set("Foo");
1273 EXPECT_STREQ("Foo", thread_local_string.get().c_str());
1276 RunFromThread(&RetrieveThreadLocalValue,
1277 make_pair(&thread_local_string, &result));
1278 EXPECT_TRUE(result.empty());
1281 #endif // GTEST_IS_THREADSAFE
1283 #ifdef GTEST_OS_WINDOWS
1284 TEST(WindowsTypesTest, HANDLEIsVoidStar) {
1285 StaticAssertTypeEq<HANDLE, void*>();
1288 #if defined(GTEST_OS_WINDOWS_MINGW) && !defined(__MINGW64_VERSION_MAJOR)
1289 TEST(WindowsTypesTest, _CRITICAL_SECTIONIs_CRITICAL_SECTION) {
1290 StaticAssertTypeEq<CRITICAL_SECTION, _CRITICAL_SECTION>();
1293 TEST(WindowsTypesTest, CRITICAL_SECTIONIs_RTL_CRITICAL_SECTION) {
1294 StaticAssertTypeEq<CRITICAL_SECTION, _RTL_CRITICAL_SECTION>();
1298 #endif // GTEST_OS_WINDOWS
1300 } // namespace internal
1301 } // namespace testing