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
41 #include <utility> // For std::pair and std::make_pair.
44 #include "gtest/gtest.h"
45 #include "gtest/gtest-spi.h"
46 #include "src/gtest-internal-inl.h"
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'));
62 EXPECT_FALSE(IsXDigit('-'));
63 EXPECT_FALSE(IsXDigit('g'));
64 EXPECT_FALSE(IsXDigit('G'));
67 TEST(IsXDigitTest, ReturnsFalseForNarrowNonAscii) {
68 EXPECT_FALSE(IsXDigit(static_cast<char>('\x80')));
69 EXPECT_FALSE(IsXDigit(static_cast<char>('0' | '\x80')));
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'));
80 EXPECT_FALSE(IsXDigit(L'-'));
81 EXPECT_FALSE(IsXDigit(L'g'));
82 EXPECT_FALSE(IsXDigit(L'G'));
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)));
93 Base() : member_(0) {}
94 explicit Base(int n) : member_(n) {}
95 Base(const Base&) = default;
96 Base& operator=(const Base&) = default;
98 int member() { return member_; }
104 class Derived : public Base {
106 explicit Derived(int n) : Base(n) {}
109 TEST(ImplicitCastTest, ConvertsPointers) {
111 EXPECT_TRUE(&derived == ::testing::internal::ImplicitCast_<Base*>(&derived));
114 TEST(ImplicitCastTest, CanUseInheritance) {
116 Base base = ::testing::internal::ImplicitCast_<Base>(derived);
117 EXPECT_EQ(derived.member(), base.member());
122 explicit Castable(bool* converted) : converted_(converted) {}
132 TEST(ImplicitCastTest, CanUseNonConstCastOperator) {
133 bool converted = false;
134 Castable castable(&converted);
135 Base base = ::testing::internal::ImplicitCast_<Base>(castable);
136 EXPECT_TRUE(converted);
139 class ConstCastable {
141 explicit ConstCastable(bool* converted) : converted_(converted) {}
142 operator Base() const {
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);
158 class ConstAndNonConstCastable {
160 ConstAndNonConstCastable(bool* converted, bool* const_converted)
161 : converted_(converted), const_converted_(const_converted) {}
166 operator Base() const {
167 *const_converted_ = true;
173 bool* const_converted_;
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);
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);
194 To(bool* converted) { *converted = true; } // NOLINT
197 TEST(ImplicitCastTest, CanUseImplicitConstructor) {
198 bool converted = false;
199 To to = ::testing::internal::ImplicitCast_<To>(&converted);
201 EXPECT_TRUE(converted);
204 // The following code intentionally tests a suboptimal syntax.
206 #pragma GCC diagnostic push
207 #pragma GCC diagnostic ignored "-Wdangling-else"
208 #pragma GCC diagnostic ignored "-Wempty-body"
209 #pragma GCC diagnostic ignored "-Wpragmas"
211 TEST(GtestCheckSyntaxTest, BehavesLikeASingleStatement) {
213 GTEST_CHECK_(false) << "This should never be executed; "
214 "It's a compilation test only.";
224 GTEST_CHECK_(true) << "";
227 #pragma GCC diagnostic pop
230 TEST(GtestCheckSyntaxTest, WorksWithSwitch) {
240 GTEST_CHECK_(true) << "Check failed in switch case";
243 // Verifies behavior of FormatFileLocation.
244 TEST(FormatFileLocationTest, FormatsFileLocation) {
245 EXPECT_PRED_FORMAT2(IsSubstring, "foo.cc", FormatFileLocation("foo.cc", 42));
246 EXPECT_PRED_FORMAT2(IsSubstring, "42", FormatFileLocation("foo.cc", 42));
249 TEST(FormatFileLocationTest, FormatsUnknownFile) {
250 EXPECT_PRED_FORMAT2(IsSubstring, "unknown file",
251 FormatFileLocation(nullptr, 42));
252 EXPECT_PRED_FORMAT2(IsSubstring, "42", FormatFileLocation(nullptr, 42));
255 TEST(FormatFileLocationTest, FormatsUknownLine) {
256 EXPECT_EQ("foo.cc:", FormatFileLocation("foo.cc", -1));
259 TEST(FormatFileLocationTest, FormatsUknownFileAndLine) {
260 EXPECT_EQ("unknown file:", FormatFileLocation(nullptr, -1));
263 // Verifies behavior of FormatCompilerIndependentFileLocation.
264 TEST(FormatCompilerIndependentFileLocationTest, FormatsFileLocation) {
265 EXPECT_EQ("foo.cc:42", FormatCompilerIndependentFileLocation("foo.cc", 42));
268 TEST(FormatCompilerIndependentFileLocationTest, FormatsUknownFile) {
269 EXPECT_EQ("unknown file:42",
270 FormatCompilerIndependentFileLocation(nullptr, 42));
273 TEST(FormatCompilerIndependentFileLocationTest, FormatsUknownLine) {
274 EXPECT_EQ("foo.cc", FormatCompilerIndependentFileLocation("foo.cc", -1));
277 TEST(FormatCompilerIndependentFileLocationTest, FormatsUknownFileAndLine) {
278 EXPECT_EQ("unknown file", FormatCompilerIndependentFileLocation(nullptr, -1));
281 #if GTEST_OS_LINUX || GTEST_OS_MAC || GTEST_OS_QNX || GTEST_OS_FUCHSIA || \
282 GTEST_OS_DRAGONFLY || GTEST_OS_FREEBSD || GTEST_OS_GNU_KFREEBSD || \
283 GTEST_OS_NETBSD || GTEST_OS_OPENBSD || GTEST_OS_GNU_HURD
284 void* ThreadFunc(void* data) {
285 internal::Mutex* mutex = static_cast<internal::Mutex*>(data);
291 TEST(GetThreadCountTest, ReturnsCorrectValue) {
292 size_t starting_count;
293 size_t thread_count_after_create;
294 size_t thread_count_after_join;
296 // We can't guarantee that no other thread was created or destroyed between
297 // any two calls to GetThreadCount(). We make multiple attempts, hoping that
298 // background noise is not constant and we would see the "right" values at
300 for (int attempt = 0; attempt < 20; ++attempt) {
301 starting_count = GetThreadCount();
304 internal::Mutex mutex;
306 internal::MutexLock lock(&mutex);
308 ASSERT_EQ(0, pthread_attr_init(&attr));
309 ASSERT_EQ(0, pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_JOINABLE));
311 const int status = pthread_create(&thread_id, &attr, &ThreadFunc, &mutex);
312 ASSERT_EQ(0, pthread_attr_destroy(&attr));
313 ASSERT_EQ(0, status);
316 thread_count_after_create = GetThreadCount();
319 ASSERT_EQ(0, pthread_join(thread_id, &dummy));
321 // Join before we decide whether we need to retry the test. Retry if an
322 // arbitrary other thread was created or destroyed in the meantime.
323 if (thread_count_after_create != starting_count + 1) continue;
325 // The OS may not immediately report the updated thread count after
326 // joining a thread, causing flakiness in this test. To counter that, we
327 // wait for up to .5 seconds for the OS to report the correct value.
328 bool thread_count_matches = false;
329 for (int i = 0; i < 5; ++i) {
330 thread_count_after_join = GetThreadCount();
331 if (thread_count_after_join == starting_count) {
332 thread_count_matches = true;
336 SleepMilliseconds(100);
339 // Retry if an arbitrary other thread was created or destroyed.
340 if (!thread_count_matches) continue;
345 EXPECT_EQ(thread_count_after_create, starting_count + 1);
346 EXPECT_EQ(thread_count_after_join, starting_count);
349 TEST(GetThreadCountTest, ReturnsZeroWhenUnableToCountThreads) {
350 EXPECT_EQ(0U, GetThreadCount());
352 #endif // GTEST_OS_LINUX || GTEST_OS_MAC || GTEST_OS_QNX || GTEST_OS_FUCHSIA
354 TEST(GtestCheckDeathTest, DiesWithCorrectOutputOnFailure) {
355 const bool a_false_condition = false;
358 "googletest-port-test\\.cc\\(\\d+\\):"
359 #elif GTEST_USES_POSIX_RE
360 "googletest-port-test\\.cc:[0-9]+"
362 "googletest-port-test\\.cc:\\d+"
364 ".*a_false_condition.*Extra info.*";
366 EXPECT_DEATH_IF_SUPPORTED(GTEST_CHECK_(a_false_condition) << "Extra info",
370 #if GTEST_HAS_DEATH_TEST
372 TEST(GtestCheckDeathTest, LivesSilentlyOnSuccess) {
374 GTEST_CHECK_(true) << "Extra info";
375 ::std::cerr << "Success\n";
377 ::testing::ExitedWithCode(0), "Success");
380 #endif // GTEST_HAS_DEATH_TEST
382 // Verifies that Google Test choose regular expression engine appropriate to
383 // the platform. The test will produce compiler errors in case of failure.
384 // For simplicity, we only cover the most important platforms here.
385 TEST(RegexEngineSelectionTest, SelectsCorrectRegexEngine) {
387 # if GTEST_HAS_POSIX_RE
389 EXPECT_TRUE(GTEST_USES_POSIX_RE);
393 EXPECT_TRUE(GTEST_USES_SIMPLE_RE);
396 #endif // !GTEST_USES_PCRE
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,
821 WorksWhenRegexStartsWithRepetionOfEscapeSequence) {
822 EXPECT_FALSE(MatchRegexAtHead("\\.+a", "abc"));
823 EXPECT_FALSE(MatchRegexAtHead("\\s?b", " b"));
825 EXPECT_TRUE(MatchRegexAtHead("\\(*a", "((((ab"));
826 EXPECT_TRUE(MatchRegexAtHead("\\^?b", "^b"));
827 EXPECT_TRUE(MatchRegexAtHead("\\\\?b", "b"));
828 EXPECT_TRUE(MatchRegexAtHead("\\\\?b", "\\b"));
831 TEST(MatchRegexAtHeadTest, MatchesSequentially) {
832 EXPECT_FALSE(MatchRegexAtHead("ab.*c", "acabc"));
834 EXPECT_TRUE(MatchRegexAtHead("ab.*c", "ab-fsc"));
837 TEST(MatchRegexAnywhereTest, ReturnsFalseWhenStringIsNull) {
838 EXPECT_FALSE(MatchRegexAnywhere("", NULL));
841 TEST(MatchRegexAnywhereTest, WorksWhenRegexStartsWithCaret) {
842 EXPECT_FALSE(MatchRegexAnywhere("^a", "ba"));
843 EXPECT_FALSE(MatchRegexAnywhere("^$", "a"));
845 EXPECT_TRUE(MatchRegexAnywhere("^a", "ab"));
846 EXPECT_TRUE(MatchRegexAnywhere("^", "ab"));
847 EXPECT_TRUE(MatchRegexAnywhere("^$", ""));
850 TEST(MatchRegexAnywhereTest, ReturnsFalseWhenNoMatch) {
851 EXPECT_FALSE(MatchRegexAnywhere("a", "bcde123"));
852 EXPECT_FALSE(MatchRegexAnywhere("a.+a", "--aa88888888"));
855 TEST(MatchRegexAnywhereTest, ReturnsTrueWhenMatchingPrefix) {
856 EXPECT_TRUE(MatchRegexAnywhere("\\w+", "ab1_ - 5"));
857 EXPECT_TRUE(MatchRegexAnywhere(".*=", "="));
858 EXPECT_TRUE(MatchRegexAnywhere("x.*ab?.*bc", "xaaabc"));
861 TEST(MatchRegexAnywhereTest, ReturnsTrueWhenMatchingNonPrefix) {
862 EXPECT_TRUE(MatchRegexAnywhere("\\w+", "$$$ ab1_ - 5"));
863 EXPECT_TRUE(MatchRegexAnywhere("\\.+=", "= ...="));
866 // Tests RE's implicit constructors.
867 TEST(RETest, ImplicitConstructorWorks) {
869 EXPECT_STREQ("", empty.pattern());
871 const RE simple("hello");
872 EXPECT_STREQ("hello", simple.pattern());
875 // Tests that RE's constructors reject invalid regular expressions.
876 TEST(RETest, RejectsInvalidRegex) {
877 EXPECT_NONFATAL_FAILURE({
878 const RE normal(NULL);
879 }, "NULL is not a valid simple regular expression");
881 EXPECT_NONFATAL_FAILURE({
882 const RE normal(".*(\\w+");
883 }, "'(' is unsupported");
885 EXPECT_NONFATAL_FAILURE({
886 const RE invalid("^?");
887 }, "'?' can only follow a repeatable token");
890 // Tests RE::FullMatch().
891 TEST(RETest, FullMatchWorks) {
893 EXPECT_TRUE(RE::FullMatch("", empty));
894 EXPECT_FALSE(RE::FullMatch("a", empty));
897 EXPECT_TRUE(RE::FullMatch("a", re1));
900 EXPECT_TRUE(RE::FullMatch("az", re));
901 EXPECT_TRUE(RE::FullMatch("axyz", re));
902 EXPECT_FALSE(RE::FullMatch("baz", re));
903 EXPECT_FALSE(RE::FullMatch("azy", re));
906 // Tests RE::PartialMatch().
907 TEST(RETest, PartialMatchWorks) {
909 EXPECT_TRUE(RE::PartialMatch("", empty));
910 EXPECT_TRUE(RE::PartialMatch("a", empty));
913 EXPECT_TRUE(RE::PartialMatch("az", re));
914 EXPECT_TRUE(RE::PartialMatch("axyz", re));
915 EXPECT_TRUE(RE::PartialMatch("baz", re));
916 EXPECT_TRUE(RE::PartialMatch("azy", re));
917 EXPECT_FALSE(RE::PartialMatch("zza", re));
920 #endif // GTEST_USES_POSIX_RE
922 #if !GTEST_OS_WINDOWS_MOBILE
924 TEST(CaptureTest, CapturesStdout) {
926 fprintf(stdout, "abc");
927 EXPECT_STREQ("abc", GetCapturedStdout().c_str());
930 fprintf(stdout, "def%cghi", '\0');
931 EXPECT_EQ(::std::string("def\0ghi", 7), ::std::string(GetCapturedStdout()));
934 TEST(CaptureTest, CapturesStderr) {
936 fprintf(stderr, "jkl");
937 EXPECT_STREQ("jkl", GetCapturedStderr().c_str());
940 fprintf(stderr, "jkl%cmno", '\0');
941 EXPECT_EQ(::std::string("jkl\0mno", 7), ::std::string(GetCapturedStderr()));
944 // Tests that stdout and stderr capture don't interfere with each other.
945 TEST(CaptureTest, CapturesStdoutAndStderr) {
948 fprintf(stdout, "pqr");
949 fprintf(stderr, "stu");
950 EXPECT_STREQ("pqr", GetCapturedStdout().c_str());
951 EXPECT_STREQ("stu", GetCapturedStderr().c_str());
954 TEST(CaptureDeathTest, CannotReenterStdoutCapture) {
956 EXPECT_DEATH_IF_SUPPORTED(CaptureStdout(),
957 "Only one stdout capturer can exist at a time");
960 // We cannot test stderr capturing using death tests as they use it
964 #endif // !GTEST_OS_WINDOWS_MOBILE
966 TEST(ThreadLocalTest, DefaultConstructorInitializesToDefaultValues) {
968 EXPECT_EQ(0, t1.get());
970 ThreadLocal<void*> t2;
971 EXPECT_TRUE(t2.get() == nullptr);
974 TEST(ThreadLocalTest, SingleParamConstructorInitializesToParam) {
975 ThreadLocal<int> t1(123);
976 EXPECT_EQ(123, t1.get());
979 ThreadLocal<int*> t2(&i);
980 EXPECT_EQ(&i, t2.get());
983 class NoDefaultContructor {
985 explicit NoDefaultContructor(const char*) {}
986 NoDefaultContructor(const NoDefaultContructor&) {}
989 TEST(ThreadLocalTest, ValueDefaultContructorIsNotRequiredForParamVersion) {
990 ThreadLocal<NoDefaultContructor> bar(NoDefaultContructor("foo"));
994 TEST(ThreadLocalTest, GetAndPointerReturnSameValue) {
995 ThreadLocal<std::string> thread_local_string;
997 EXPECT_EQ(thread_local_string.pointer(), &(thread_local_string.get()));
999 // Verifies the condition still holds after calling set.
1000 thread_local_string.set("foo");
1001 EXPECT_EQ(thread_local_string.pointer(), &(thread_local_string.get()));
1004 TEST(ThreadLocalTest, PointerAndConstPointerReturnSameValue) {
1005 ThreadLocal<std::string> thread_local_string;
1006 const ThreadLocal<std::string>& const_thread_local_string =
1007 thread_local_string;
1009 EXPECT_EQ(thread_local_string.pointer(), const_thread_local_string.pointer());
1011 thread_local_string.set("foo");
1012 EXPECT_EQ(thread_local_string.pointer(), const_thread_local_string.pointer());
1015 #if GTEST_IS_THREADSAFE
1017 void AddTwo(int* param) { *param += 2; }
1019 TEST(ThreadWithParamTest, ConstructorExecutesThreadFunc) {
1021 ThreadWithParam<int*> thread(&AddTwo, &i, nullptr);
1026 TEST(MutexDeathTest, AssertHeldShouldAssertWhenNotLocked) {
1027 // AssertHeld() is flaky only in the presence of multiple threads accessing
1028 // the lock. In this case, the test is robust.
1029 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 SleepMilliseconds 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 SleepMilliseconds(static_cast<int>(random_.Generate(30)));
1066 GTEST_CHECK_POSIX_SUCCESS_(pthread_mutex_unlock(&memory_barrier_mutex));
1067 GTEST_CHECK_POSIX_SUCCESS_(pthread_mutex_destroy(&memory_barrier_mutex));
1068 #elif GTEST_OS_WINDOWS
1069 // On Windows, performing an interlocked access puts up a memory barrier.
1070 volatile LONG dummy = 0;
1071 ::InterlockedIncrement(&dummy);
1072 SleepMilliseconds(static_cast<int>(random_.Generate(30)));
1073 ::InterlockedIncrement(&dummy);
1075 # error "Memory barrier not implemented on this platform."
1076 #endif // GTEST_HAS_PTHREAD
1080 int value() const { return value_; }
1083 volatile int value_;
1084 Mutex* const mutex_; // Protects value_.
1088 void CountingThreadFunc(pair<AtomicCounterWithMutex*, int> param) {
1089 for (int i = 0; i < param.second; ++i)
1090 param.first->Increment();
1093 // Tests that the mutex only lets one thread at a time to lock it.
1094 TEST(MutexTest, OnlyOneThreadCanLockAtATime) {
1096 AtomicCounterWithMutex locked_counter(&mutex);
1098 typedef ThreadWithParam<pair<AtomicCounterWithMutex*, int> > ThreadType;
1099 const int kCycleCount = 20;
1100 const int kThreadCount = 7;
1101 std::unique_ptr<ThreadType> counting_threads[kThreadCount];
1102 Notification threads_can_start;
1103 // Creates and runs kThreadCount threads that increment locked_counter
1104 // kCycleCount times each.
1105 for (int i = 0; i < kThreadCount; ++i) {
1106 counting_threads[i].reset(new ThreadType(&CountingThreadFunc,
1107 make_pair(&locked_counter,
1109 &threads_can_start));
1111 threads_can_start.Notify();
1112 for (int i = 0; i < kThreadCount; ++i)
1113 counting_threads[i]->Join();
1115 // If the mutex lets more than one thread to increment the counter at a
1116 // time, they are likely to encounter a race condition and have some
1117 // increments overwritten, resulting in the lower then expected counter
1119 EXPECT_EQ(kCycleCount * kThreadCount, locked_counter.value());
1122 template <typename T>
1123 void RunFromThread(void (func)(T), T param) {
1124 ThreadWithParam<T> thread(func, param, nullptr);
1128 void RetrieveThreadLocalValue(
1129 pair<ThreadLocal<std::string>*, std::string*> param) {
1130 *param.second = param.first->get();
1133 TEST(ThreadLocalTest, ParameterizedConstructorSetsDefault) {
1134 ThreadLocal<std::string> thread_local_string("foo");
1135 EXPECT_STREQ("foo", thread_local_string.get().c_str());
1137 thread_local_string.set("bar");
1138 EXPECT_STREQ("bar", thread_local_string.get().c_str());
1141 RunFromThread(&RetrieveThreadLocalValue,
1142 make_pair(&thread_local_string, &result));
1143 EXPECT_STREQ("foo", result.c_str());
1146 // Keeps track of whether of destructors being called on instances of
1147 // DestructorTracker. On Windows, waits for the destructor call reports.
1148 class DestructorCall {
1152 #if GTEST_OS_WINDOWS
1153 wait_event_.Reset(::CreateEvent(NULL, TRUE, FALSE, NULL));
1154 GTEST_CHECK_(wait_event_.Get() != NULL);
1158 bool CheckDestroyed() const {
1159 #if GTEST_OS_WINDOWS
1160 if (::WaitForSingleObject(wait_event_.Get(), 1000) != WAIT_OBJECT_0)
1166 void ReportDestroyed() {
1168 #if GTEST_OS_WINDOWS
1169 ::SetEvent(wait_event_.Get());
1173 static std::vector<DestructorCall*>& List() { return *list_; }
1175 static void ResetList() {
1176 for (size_t i = 0; i < list_->size(); ++i) {
1177 delete list_->at(i);
1184 #if GTEST_OS_WINDOWS
1185 AutoHandle wait_event_;
1187 static std::vector<DestructorCall*>* const list_;
1189 GTEST_DISALLOW_COPY_AND_ASSIGN_(DestructorCall);
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 #if GTEST_OS_WINDOWS
1284 TEST(WindowsTypesTest, HANDLEIsVoidStar) {
1285 StaticAssertTypeEq<HANDLE, void*>();
1288 #if 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