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
40 #include <utility> // For std::pair and std::make_pair.
43 #include "gtest/gtest.h"
44 #include "gtest/gtest-spi.h"
45 #include "src/gtest-internal-inl.h"
53 TEST(IsXDigitTest, WorksForNarrowAscii) {
54 EXPECT_TRUE(IsXDigit('0'));
55 EXPECT_TRUE(IsXDigit('9'));
56 EXPECT_TRUE(IsXDigit('A'));
57 EXPECT_TRUE(IsXDigit('F'));
58 EXPECT_TRUE(IsXDigit('a'));
59 EXPECT_TRUE(IsXDigit('f'));
61 EXPECT_FALSE(IsXDigit('-'));
62 EXPECT_FALSE(IsXDigit('g'));
63 EXPECT_FALSE(IsXDigit('G'));
66 TEST(IsXDigitTest, ReturnsFalseForNarrowNonAscii) {
67 EXPECT_FALSE(IsXDigit(static_cast<char>('\x80')));
68 EXPECT_FALSE(IsXDigit(static_cast<char>('0' | '\x80')));
71 TEST(IsXDigitTest, WorksForWideAscii) {
72 EXPECT_TRUE(IsXDigit(L'0'));
73 EXPECT_TRUE(IsXDigit(L'9'));
74 EXPECT_TRUE(IsXDigit(L'A'));
75 EXPECT_TRUE(IsXDigit(L'F'));
76 EXPECT_TRUE(IsXDigit(L'a'));
77 EXPECT_TRUE(IsXDigit(L'f'));
79 EXPECT_FALSE(IsXDigit(L'-'));
80 EXPECT_FALSE(IsXDigit(L'g'));
81 EXPECT_FALSE(IsXDigit(L'G'));
84 TEST(IsXDigitTest, ReturnsFalseForWideNonAscii) {
85 EXPECT_FALSE(IsXDigit(static_cast<wchar_t>(0x80)));
86 EXPECT_FALSE(IsXDigit(static_cast<wchar_t>(L'0' | 0x80)));
87 EXPECT_FALSE(IsXDigit(static_cast<wchar_t>(L'0' | 0x100)));
92 // Copy constructor and assignment operator do exactly what we need, so we
94 Base() : member_(0) {}
95 explicit Base(int n) : member_(n) {}
97 int member() { return member_; }
103 class Derived : public Base {
105 explicit Derived(int n) : Base(n) {}
108 TEST(ImplicitCastTest, ConvertsPointers) {
110 EXPECT_TRUE(&derived == ::testing::internal::ImplicitCast_<Base*>(&derived));
113 TEST(ImplicitCastTest, CanUseInheritance) {
115 Base base = ::testing::internal::ImplicitCast_<Base>(derived);
116 EXPECT_EQ(derived.member(), base.member());
121 explicit Castable(bool* converted) : converted_(converted) {}
131 TEST(ImplicitCastTest, CanUseNonConstCastOperator) {
132 bool converted = false;
133 Castable castable(&converted);
134 Base base = ::testing::internal::ImplicitCast_<Base>(castable);
135 EXPECT_TRUE(converted);
138 class ConstCastable {
140 explicit ConstCastable(bool* converted) : converted_(converted) {}
141 operator Base() const {
150 TEST(ImplicitCastTest, CanUseConstCastOperatorOnConstValues) {
151 bool converted = false;
152 const ConstCastable const_castable(&converted);
153 Base base = ::testing::internal::ImplicitCast_<Base>(const_castable);
154 EXPECT_TRUE(converted);
157 class ConstAndNonConstCastable {
159 ConstAndNonConstCastable(bool* converted, bool* const_converted)
160 : converted_(converted), const_converted_(const_converted) {}
165 operator Base() const {
166 *const_converted_ = true;
172 bool* const_converted_;
175 TEST(ImplicitCastTest, CanSelectBetweenConstAndNonConstCasrAppropriately) {
176 bool converted = false;
177 bool const_converted = false;
178 ConstAndNonConstCastable castable(&converted, &const_converted);
179 Base base = ::testing::internal::ImplicitCast_<Base>(castable);
180 EXPECT_TRUE(converted);
181 EXPECT_FALSE(const_converted);
184 const_converted = false;
185 const ConstAndNonConstCastable const_castable(&converted, &const_converted);
186 base = ::testing::internal::ImplicitCast_<Base>(const_castable);
187 EXPECT_FALSE(converted);
188 EXPECT_TRUE(const_converted);
193 To(bool* converted) { *converted = true; } // NOLINT
196 TEST(ImplicitCastTest, CanUseImplicitConstructor) {
197 bool converted = false;
198 To to = ::testing::internal::ImplicitCast_<To>(&converted);
200 EXPECT_TRUE(converted);
203 TEST(IteratorTraitsTest, WorksForSTLContainerIterators) {
204 StaticAssertTypeEq<int,
205 IteratorTraits< ::std::vector<int>::const_iterator>::value_type>();
206 StaticAssertTypeEq<bool,
207 IteratorTraits< ::std::list<bool>::iterator>::value_type>();
210 TEST(IteratorTraitsTest, WorksForPointerToNonConst) {
211 StaticAssertTypeEq<char, IteratorTraits<char*>::value_type>();
212 StaticAssertTypeEq<const void*, IteratorTraits<const void**>::value_type>();
215 TEST(IteratorTraitsTest, WorksForPointerToConst) {
216 StaticAssertTypeEq<char, IteratorTraits<const char*>::value_type>();
217 StaticAssertTypeEq<const void*,
218 IteratorTraits<const void* const*>::value_type>();
221 // Tests that the element_type typedef is available in scoped_ptr and refers
222 // to the parameter type.
223 TEST(ScopedPtrTest, DefinesElementType) {
224 StaticAssertTypeEq<int, ::testing::internal::scoped_ptr<int>::element_type>();
227 // FIXME: Implement THE REST of scoped_ptr tests.
229 TEST(GtestCheckSyntaxTest, BehavesLikeASingleStatement) {
231 GTEST_CHECK_(false) << "This should never be executed; "
232 "It's a compilation test only.";
242 GTEST_CHECK_(true) << "";
245 TEST(GtestCheckSyntaxTest, WorksWithSwitch) {
255 GTEST_CHECK_(true) << "Check failed in switch case";
258 // Verifies behavior of FormatFileLocation.
259 TEST(FormatFileLocationTest, FormatsFileLocation) {
260 EXPECT_PRED_FORMAT2(IsSubstring, "foo.cc", FormatFileLocation("foo.cc", 42));
261 EXPECT_PRED_FORMAT2(IsSubstring, "42", FormatFileLocation("foo.cc", 42));
264 TEST(FormatFileLocationTest, FormatsUnknownFile) {
266 IsSubstring, "unknown file", FormatFileLocation(NULL, 42));
267 EXPECT_PRED_FORMAT2(IsSubstring, "42", FormatFileLocation(NULL, 42));
270 TEST(FormatFileLocationTest, FormatsUknownLine) {
271 EXPECT_EQ("foo.cc:", FormatFileLocation("foo.cc", -1));
274 TEST(FormatFileLocationTest, FormatsUknownFileAndLine) {
275 EXPECT_EQ("unknown file:", FormatFileLocation(NULL, -1));
278 // Verifies behavior of FormatCompilerIndependentFileLocation.
279 TEST(FormatCompilerIndependentFileLocationTest, FormatsFileLocation) {
280 EXPECT_EQ("foo.cc:42", FormatCompilerIndependentFileLocation("foo.cc", 42));
283 TEST(FormatCompilerIndependentFileLocationTest, FormatsUknownFile) {
284 EXPECT_EQ("unknown file:42",
285 FormatCompilerIndependentFileLocation(NULL, 42));
288 TEST(FormatCompilerIndependentFileLocationTest, FormatsUknownLine) {
289 EXPECT_EQ("foo.cc", FormatCompilerIndependentFileLocation("foo.cc", -1));
292 TEST(FormatCompilerIndependentFileLocationTest, FormatsUknownFileAndLine) {
293 EXPECT_EQ("unknown file", FormatCompilerIndependentFileLocation(NULL, -1));
296 #if GTEST_OS_LINUX || GTEST_OS_MAC || GTEST_OS_QNX || GTEST_OS_FUCHSIA
297 void* ThreadFunc(void* data) {
298 internal::Mutex* mutex = static_cast<internal::Mutex*>(data);
304 TEST(GetThreadCountTest, ReturnsCorrectValue) {
305 const size_t starting_count = GetThreadCount();
308 internal::Mutex mutex;
310 internal::MutexLock lock(&mutex);
312 ASSERT_EQ(0, pthread_attr_init(&attr));
313 ASSERT_EQ(0, pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_JOINABLE));
315 const int status = pthread_create(&thread_id, &attr, &ThreadFunc, &mutex);
316 ASSERT_EQ(0, pthread_attr_destroy(&attr));
317 ASSERT_EQ(0, status);
318 EXPECT_EQ(starting_count + 1, GetThreadCount());
322 ASSERT_EQ(0, pthread_join(thread_id, &dummy));
324 // The OS may not immediately report the updated thread count after
325 // joining a thread, causing flakiness in this test. To counter that, we
326 // wait for up to .5 seconds for the OS to report the correct value.
327 for (int i = 0; i < 5; ++i) {
328 if (GetThreadCount() == starting_count)
331 SleepMilliseconds(100);
334 EXPECT_EQ(starting_count, GetThreadCount());
337 TEST(GetThreadCountTest, ReturnsZeroWhenUnableToCountThreads) {
338 EXPECT_EQ(0U, GetThreadCount());
340 #endif // GTEST_OS_LINUX || GTEST_OS_MAC || GTEST_OS_QNX || GTEST_OS_FUCHSIA
342 TEST(GtestCheckDeathTest, DiesWithCorrectOutputOnFailure) {
343 const bool a_false_condition = false;
346 "googletest-port-test\\.cc\\(\\d+\\):"
347 #elif GTEST_USES_POSIX_RE
348 "googletest-port-test\\.cc:[0-9]+"
350 "googletest-port-test\\.cc:\\d+"
352 ".*a_false_condition.*Extra info.*";
354 EXPECT_DEATH_IF_SUPPORTED(GTEST_CHECK_(a_false_condition) << "Extra info",
358 #if GTEST_HAS_DEATH_TEST
360 TEST(GtestCheckDeathTest, LivesSilentlyOnSuccess) {
362 GTEST_CHECK_(true) << "Extra info";
363 ::std::cerr << "Success\n";
365 ::testing::ExitedWithCode(0), "Success");
368 #endif // GTEST_HAS_DEATH_TEST
370 // Verifies that Google Test choose regular expression engine appropriate to
371 // the platform. The test will produce compiler errors in case of failure.
372 // For simplicity, we only cover the most important platforms here.
373 TEST(RegexEngineSelectionTest, SelectsCorrectRegexEngine) {
375 # if GTEST_HAS_POSIX_RE
377 EXPECT_TRUE(GTEST_USES_POSIX_RE);
381 EXPECT_TRUE(GTEST_USES_SIMPLE_RE);
384 #endif // !GTEST_USES_PCRE
387 #if GTEST_USES_POSIX_RE
389 # if GTEST_HAS_TYPED_TEST
391 template <typename Str>
392 class RETest : public ::testing::Test {};
394 // Defines StringTypes as the list of all string types that class RE
396 typedef testing::Types<
398 # if GTEST_HAS_GLOBAL_STRING
400 # endif // GTEST_HAS_GLOBAL_STRING
401 const char*> StringTypes;
403 TYPED_TEST_CASE(RETest, StringTypes);
405 // Tests RE's implicit constructors.
406 TYPED_TEST(RETest, ImplicitConstructorWorks) {
407 const RE empty(TypeParam(""));
408 EXPECT_STREQ("", empty.pattern());
410 const RE simple(TypeParam("hello"));
411 EXPECT_STREQ("hello", simple.pattern());
413 const RE normal(TypeParam(".*(\\w+)"));
414 EXPECT_STREQ(".*(\\w+)", normal.pattern());
417 // Tests that RE's constructors reject invalid regular expressions.
418 TYPED_TEST(RETest, RejectsInvalidRegex) {
419 EXPECT_NONFATAL_FAILURE({
420 const RE invalid(TypeParam("?"));
421 }, "\"?\" is not a valid POSIX Extended regular expression.");
424 // Tests RE::FullMatch().
425 TYPED_TEST(RETest, FullMatchWorks) {
426 const RE empty(TypeParam(""));
427 EXPECT_TRUE(RE::FullMatch(TypeParam(""), empty));
428 EXPECT_FALSE(RE::FullMatch(TypeParam("a"), empty));
430 const RE re(TypeParam("a.*z"));
431 EXPECT_TRUE(RE::FullMatch(TypeParam("az"), re));
432 EXPECT_TRUE(RE::FullMatch(TypeParam("axyz"), re));
433 EXPECT_FALSE(RE::FullMatch(TypeParam("baz"), re));
434 EXPECT_FALSE(RE::FullMatch(TypeParam("azy"), re));
437 // Tests RE::PartialMatch().
438 TYPED_TEST(RETest, PartialMatchWorks) {
439 const RE empty(TypeParam(""));
440 EXPECT_TRUE(RE::PartialMatch(TypeParam(""), empty));
441 EXPECT_TRUE(RE::PartialMatch(TypeParam("a"), empty));
443 const RE re(TypeParam("a.*z"));
444 EXPECT_TRUE(RE::PartialMatch(TypeParam("az"), re));
445 EXPECT_TRUE(RE::PartialMatch(TypeParam("axyz"), re));
446 EXPECT_TRUE(RE::PartialMatch(TypeParam("baz"), re));
447 EXPECT_TRUE(RE::PartialMatch(TypeParam("azy"), re));
448 EXPECT_FALSE(RE::PartialMatch(TypeParam("zza"), re));
451 # endif // GTEST_HAS_TYPED_TEST
453 #elif GTEST_USES_SIMPLE_RE
455 TEST(IsInSetTest, NulCharIsNotInAnySet) {
456 EXPECT_FALSE(IsInSet('\0', ""));
457 EXPECT_FALSE(IsInSet('\0', "\0"));
458 EXPECT_FALSE(IsInSet('\0', "a"));
461 TEST(IsInSetTest, WorksForNonNulChars) {
462 EXPECT_FALSE(IsInSet('a', "Ab"));
463 EXPECT_FALSE(IsInSet('c', ""));
465 EXPECT_TRUE(IsInSet('b', "bcd"));
466 EXPECT_TRUE(IsInSet('b', "ab"));
469 TEST(IsAsciiDigitTest, IsFalseForNonDigit) {
470 EXPECT_FALSE(IsAsciiDigit('\0'));
471 EXPECT_FALSE(IsAsciiDigit(' '));
472 EXPECT_FALSE(IsAsciiDigit('+'));
473 EXPECT_FALSE(IsAsciiDigit('-'));
474 EXPECT_FALSE(IsAsciiDigit('.'));
475 EXPECT_FALSE(IsAsciiDigit('a'));
478 TEST(IsAsciiDigitTest, IsTrueForDigit) {
479 EXPECT_TRUE(IsAsciiDigit('0'));
480 EXPECT_TRUE(IsAsciiDigit('1'));
481 EXPECT_TRUE(IsAsciiDigit('5'));
482 EXPECT_TRUE(IsAsciiDigit('9'));
485 TEST(IsAsciiPunctTest, IsFalseForNonPunct) {
486 EXPECT_FALSE(IsAsciiPunct('\0'));
487 EXPECT_FALSE(IsAsciiPunct(' '));
488 EXPECT_FALSE(IsAsciiPunct('\n'));
489 EXPECT_FALSE(IsAsciiPunct('a'));
490 EXPECT_FALSE(IsAsciiPunct('0'));
493 TEST(IsAsciiPunctTest, IsTrueForPunct) {
494 for (const char* p = "^-!\"#$%&'()*+,./:;<=>?@[\\]_`{|}~"; *p; p++) {
495 EXPECT_PRED1(IsAsciiPunct, *p);
499 TEST(IsRepeatTest, IsFalseForNonRepeatChar) {
500 EXPECT_FALSE(IsRepeat('\0'));
501 EXPECT_FALSE(IsRepeat(' '));
502 EXPECT_FALSE(IsRepeat('a'));
503 EXPECT_FALSE(IsRepeat('1'));
504 EXPECT_FALSE(IsRepeat('-'));
507 TEST(IsRepeatTest, IsTrueForRepeatChar) {
508 EXPECT_TRUE(IsRepeat('?'));
509 EXPECT_TRUE(IsRepeat('*'));
510 EXPECT_TRUE(IsRepeat('+'));
513 TEST(IsAsciiWhiteSpaceTest, IsFalseForNonWhiteSpace) {
514 EXPECT_FALSE(IsAsciiWhiteSpace('\0'));
515 EXPECT_FALSE(IsAsciiWhiteSpace('a'));
516 EXPECT_FALSE(IsAsciiWhiteSpace('1'));
517 EXPECT_FALSE(IsAsciiWhiteSpace('+'));
518 EXPECT_FALSE(IsAsciiWhiteSpace('_'));
521 TEST(IsAsciiWhiteSpaceTest, IsTrueForWhiteSpace) {
522 EXPECT_TRUE(IsAsciiWhiteSpace(' '));
523 EXPECT_TRUE(IsAsciiWhiteSpace('\n'));
524 EXPECT_TRUE(IsAsciiWhiteSpace('\r'));
525 EXPECT_TRUE(IsAsciiWhiteSpace('\t'));
526 EXPECT_TRUE(IsAsciiWhiteSpace('\v'));
527 EXPECT_TRUE(IsAsciiWhiteSpace('\f'));
530 TEST(IsAsciiWordCharTest, IsFalseForNonWordChar) {
531 EXPECT_FALSE(IsAsciiWordChar('\0'));
532 EXPECT_FALSE(IsAsciiWordChar('+'));
533 EXPECT_FALSE(IsAsciiWordChar('.'));
534 EXPECT_FALSE(IsAsciiWordChar(' '));
535 EXPECT_FALSE(IsAsciiWordChar('\n'));
538 TEST(IsAsciiWordCharTest, IsTrueForLetter) {
539 EXPECT_TRUE(IsAsciiWordChar('a'));
540 EXPECT_TRUE(IsAsciiWordChar('b'));
541 EXPECT_TRUE(IsAsciiWordChar('A'));
542 EXPECT_TRUE(IsAsciiWordChar('Z'));
545 TEST(IsAsciiWordCharTest, IsTrueForDigit) {
546 EXPECT_TRUE(IsAsciiWordChar('0'));
547 EXPECT_TRUE(IsAsciiWordChar('1'));
548 EXPECT_TRUE(IsAsciiWordChar('7'));
549 EXPECT_TRUE(IsAsciiWordChar('9'));
552 TEST(IsAsciiWordCharTest, IsTrueForUnderscore) {
553 EXPECT_TRUE(IsAsciiWordChar('_'));
556 TEST(IsValidEscapeTest, IsFalseForNonPrintable) {
557 EXPECT_FALSE(IsValidEscape('\0'));
558 EXPECT_FALSE(IsValidEscape('\007'));
561 TEST(IsValidEscapeTest, IsFalseForDigit) {
562 EXPECT_FALSE(IsValidEscape('0'));
563 EXPECT_FALSE(IsValidEscape('9'));
566 TEST(IsValidEscapeTest, IsFalseForWhiteSpace) {
567 EXPECT_FALSE(IsValidEscape(' '));
568 EXPECT_FALSE(IsValidEscape('\n'));
571 TEST(IsValidEscapeTest, IsFalseForSomeLetter) {
572 EXPECT_FALSE(IsValidEscape('a'));
573 EXPECT_FALSE(IsValidEscape('Z'));
576 TEST(IsValidEscapeTest, IsTrueForPunct) {
577 EXPECT_TRUE(IsValidEscape('.'));
578 EXPECT_TRUE(IsValidEscape('-'));
579 EXPECT_TRUE(IsValidEscape('^'));
580 EXPECT_TRUE(IsValidEscape('$'));
581 EXPECT_TRUE(IsValidEscape('('));
582 EXPECT_TRUE(IsValidEscape(']'));
583 EXPECT_TRUE(IsValidEscape('{'));
584 EXPECT_TRUE(IsValidEscape('|'));
587 TEST(IsValidEscapeTest, IsTrueForSomeLetter) {
588 EXPECT_TRUE(IsValidEscape('d'));
589 EXPECT_TRUE(IsValidEscape('D'));
590 EXPECT_TRUE(IsValidEscape('s'));
591 EXPECT_TRUE(IsValidEscape('S'));
592 EXPECT_TRUE(IsValidEscape('w'));
593 EXPECT_TRUE(IsValidEscape('W'));
596 TEST(AtomMatchesCharTest, EscapedPunct) {
597 EXPECT_FALSE(AtomMatchesChar(true, '\\', '\0'));
598 EXPECT_FALSE(AtomMatchesChar(true, '\\', ' '));
599 EXPECT_FALSE(AtomMatchesChar(true, '_', '.'));
600 EXPECT_FALSE(AtomMatchesChar(true, '.', 'a'));
602 EXPECT_TRUE(AtomMatchesChar(true, '\\', '\\'));
603 EXPECT_TRUE(AtomMatchesChar(true, '_', '_'));
604 EXPECT_TRUE(AtomMatchesChar(true, '+', '+'));
605 EXPECT_TRUE(AtomMatchesChar(true, '.', '.'));
608 TEST(AtomMatchesCharTest, Escaped_d) {
609 EXPECT_FALSE(AtomMatchesChar(true, 'd', '\0'));
610 EXPECT_FALSE(AtomMatchesChar(true, 'd', 'a'));
611 EXPECT_FALSE(AtomMatchesChar(true, 'd', '.'));
613 EXPECT_TRUE(AtomMatchesChar(true, 'd', '0'));
614 EXPECT_TRUE(AtomMatchesChar(true, 'd', '9'));
617 TEST(AtomMatchesCharTest, Escaped_D) {
618 EXPECT_FALSE(AtomMatchesChar(true, 'D', '0'));
619 EXPECT_FALSE(AtomMatchesChar(true, 'D', '9'));
621 EXPECT_TRUE(AtomMatchesChar(true, 'D', '\0'));
622 EXPECT_TRUE(AtomMatchesChar(true, 'D', 'a'));
623 EXPECT_TRUE(AtomMatchesChar(true, 'D', '-'));
626 TEST(AtomMatchesCharTest, Escaped_s) {
627 EXPECT_FALSE(AtomMatchesChar(true, 's', '\0'));
628 EXPECT_FALSE(AtomMatchesChar(true, 's', 'a'));
629 EXPECT_FALSE(AtomMatchesChar(true, 's', '.'));
630 EXPECT_FALSE(AtomMatchesChar(true, 's', '9'));
632 EXPECT_TRUE(AtomMatchesChar(true, 's', ' '));
633 EXPECT_TRUE(AtomMatchesChar(true, 's', '\n'));
634 EXPECT_TRUE(AtomMatchesChar(true, 's', '\t'));
637 TEST(AtomMatchesCharTest, Escaped_S) {
638 EXPECT_FALSE(AtomMatchesChar(true, 'S', ' '));
639 EXPECT_FALSE(AtomMatchesChar(true, 'S', '\r'));
641 EXPECT_TRUE(AtomMatchesChar(true, 'S', '\0'));
642 EXPECT_TRUE(AtomMatchesChar(true, 'S', 'a'));
643 EXPECT_TRUE(AtomMatchesChar(true, 'S', '9'));
646 TEST(AtomMatchesCharTest, Escaped_w) {
647 EXPECT_FALSE(AtomMatchesChar(true, 'w', '\0'));
648 EXPECT_FALSE(AtomMatchesChar(true, 'w', '+'));
649 EXPECT_FALSE(AtomMatchesChar(true, 'w', ' '));
650 EXPECT_FALSE(AtomMatchesChar(true, 'w', '\n'));
652 EXPECT_TRUE(AtomMatchesChar(true, 'w', '0'));
653 EXPECT_TRUE(AtomMatchesChar(true, 'w', 'b'));
654 EXPECT_TRUE(AtomMatchesChar(true, 'w', 'C'));
655 EXPECT_TRUE(AtomMatchesChar(true, 'w', '_'));
658 TEST(AtomMatchesCharTest, Escaped_W) {
659 EXPECT_FALSE(AtomMatchesChar(true, 'W', 'A'));
660 EXPECT_FALSE(AtomMatchesChar(true, 'W', 'b'));
661 EXPECT_FALSE(AtomMatchesChar(true, 'W', '9'));
662 EXPECT_FALSE(AtomMatchesChar(true, 'W', '_'));
664 EXPECT_TRUE(AtomMatchesChar(true, 'W', '\0'));
665 EXPECT_TRUE(AtomMatchesChar(true, 'W', '*'));
666 EXPECT_TRUE(AtomMatchesChar(true, 'W', '\n'));
669 TEST(AtomMatchesCharTest, EscapedWhiteSpace) {
670 EXPECT_FALSE(AtomMatchesChar(true, 'f', '\0'));
671 EXPECT_FALSE(AtomMatchesChar(true, 'f', '\n'));
672 EXPECT_FALSE(AtomMatchesChar(true, 'n', '\0'));
673 EXPECT_FALSE(AtomMatchesChar(true, 'n', '\r'));
674 EXPECT_FALSE(AtomMatchesChar(true, 'r', '\0'));
675 EXPECT_FALSE(AtomMatchesChar(true, 'r', 'a'));
676 EXPECT_FALSE(AtomMatchesChar(true, 't', '\0'));
677 EXPECT_FALSE(AtomMatchesChar(true, 't', 't'));
678 EXPECT_FALSE(AtomMatchesChar(true, 'v', '\0'));
679 EXPECT_FALSE(AtomMatchesChar(true, 'v', '\f'));
681 EXPECT_TRUE(AtomMatchesChar(true, 'f', '\f'));
682 EXPECT_TRUE(AtomMatchesChar(true, 'n', '\n'));
683 EXPECT_TRUE(AtomMatchesChar(true, 'r', '\r'));
684 EXPECT_TRUE(AtomMatchesChar(true, 't', '\t'));
685 EXPECT_TRUE(AtomMatchesChar(true, 'v', '\v'));
688 TEST(AtomMatchesCharTest, UnescapedDot) {
689 EXPECT_FALSE(AtomMatchesChar(false, '.', '\n'));
691 EXPECT_TRUE(AtomMatchesChar(false, '.', '\0'));
692 EXPECT_TRUE(AtomMatchesChar(false, '.', '.'));
693 EXPECT_TRUE(AtomMatchesChar(false, '.', 'a'));
694 EXPECT_TRUE(AtomMatchesChar(false, '.', ' '));
697 TEST(AtomMatchesCharTest, UnescapedChar) {
698 EXPECT_FALSE(AtomMatchesChar(false, 'a', '\0'));
699 EXPECT_FALSE(AtomMatchesChar(false, 'a', 'b'));
700 EXPECT_FALSE(AtomMatchesChar(false, '$', 'a'));
702 EXPECT_TRUE(AtomMatchesChar(false, '$', '$'));
703 EXPECT_TRUE(AtomMatchesChar(false, '5', '5'));
704 EXPECT_TRUE(AtomMatchesChar(false, 'Z', 'Z'));
707 TEST(ValidateRegexTest, GeneratesFailureAndReturnsFalseForInvalid) {
708 EXPECT_NONFATAL_FAILURE(ASSERT_FALSE(ValidateRegex(NULL)),
709 "NULL is not a valid simple regular expression");
710 EXPECT_NONFATAL_FAILURE(
711 ASSERT_FALSE(ValidateRegex("a\\")),
712 "Syntax error at index 1 in simple regular expression \"a\\\": ");
713 EXPECT_NONFATAL_FAILURE(ASSERT_FALSE(ValidateRegex("a\\")),
714 "'\\' cannot appear at the end");
715 EXPECT_NONFATAL_FAILURE(ASSERT_FALSE(ValidateRegex("\\n\\")),
716 "'\\' cannot appear at the end");
717 EXPECT_NONFATAL_FAILURE(ASSERT_FALSE(ValidateRegex("\\s\\hb")),
718 "invalid escape sequence \"\\h\"");
719 EXPECT_NONFATAL_FAILURE(ASSERT_FALSE(ValidateRegex("^^")),
720 "'^' can only appear at the beginning");
721 EXPECT_NONFATAL_FAILURE(ASSERT_FALSE(ValidateRegex(".*^b")),
722 "'^' can only appear at the beginning");
723 EXPECT_NONFATAL_FAILURE(ASSERT_FALSE(ValidateRegex("$$")),
724 "'$' can only appear at the end");
725 EXPECT_NONFATAL_FAILURE(ASSERT_FALSE(ValidateRegex("^$a")),
726 "'$' can only appear at the end");
727 EXPECT_NONFATAL_FAILURE(ASSERT_FALSE(ValidateRegex("a(b")),
728 "'(' is unsupported");
729 EXPECT_NONFATAL_FAILURE(ASSERT_FALSE(ValidateRegex("ab)")),
730 "')' is unsupported");
731 EXPECT_NONFATAL_FAILURE(ASSERT_FALSE(ValidateRegex("[ab")),
732 "'[' is unsupported");
733 EXPECT_NONFATAL_FAILURE(ASSERT_FALSE(ValidateRegex("a{2")),
734 "'{' is unsupported");
735 EXPECT_NONFATAL_FAILURE(ASSERT_FALSE(ValidateRegex("?")),
736 "'?' can only follow a repeatable token");
737 EXPECT_NONFATAL_FAILURE(ASSERT_FALSE(ValidateRegex("^*")),
738 "'*' can only follow a repeatable token");
739 EXPECT_NONFATAL_FAILURE(ASSERT_FALSE(ValidateRegex("5*+")),
740 "'+' can only follow a repeatable token");
743 TEST(ValidateRegexTest, ReturnsTrueForValid) {
744 EXPECT_TRUE(ValidateRegex(""));
745 EXPECT_TRUE(ValidateRegex("a"));
746 EXPECT_TRUE(ValidateRegex(".*"));
747 EXPECT_TRUE(ValidateRegex("^a_+"));
748 EXPECT_TRUE(ValidateRegex("^a\\t\\&?"));
749 EXPECT_TRUE(ValidateRegex("09*$"));
750 EXPECT_TRUE(ValidateRegex("^Z$"));
751 EXPECT_TRUE(ValidateRegex("a\\^Z\\$\\(\\)\\|\\[\\]\\{\\}"));
754 TEST(MatchRepetitionAndRegexAtHeadTest, WorksForZeroOrOne) {
755 EXPECT_FALSE(MatchRepetitionAndRegexAtHead(false, 'a', '?', "a", "ba"));
756 // Repeating more than once.
757 EXPECT_FALSE(MatchRepetitionAndRegexAtHead(false, 'a', '?', "b", "aab"));
759 // Repeating zero times.
760 EXPECT_TRUE(MatchRepetitionAndRegexAtHead(false, 'a', '?', "b", "ba"));
762 EXPECT_TRUE(MatchRepetitionAndRegexAtHead(false, 'a', '?', "b", "ab"));
763 EXPECT_TRUE(MatchRepetitionAndRegexAtHead(false, '#', '?', ".", "##"));
766 TEST(MatchRepetitionAndRegexAtHeadTest, WorksForZeroOrMany) {
767 EXPECT_FALSE(MatchRepetitionAndRegexAtHead(false, '.', '*', "a$", "baab"));
769 // Repeating zero times.
770 EXPECT_TRUE(MatchRepetitionAndRegexAtHead(false, '.', '*', "b", "bc"));
772 EXPECT_TRUE(MatchRepetitionAndRegexAtHead(false, '.', '*', "b", "abc"));
773 // Repeating more than once.
774 EXPECT_TRUE(MatchRepetitionAndRegexAtHead(true, 'w', '*', "-", "ab_1-g"));
777 TEST(MatchRepetitionAndRegexAtHeadTest, WorksForOneOrMany) {
778 EXPECT_FALSE(MatchRepetitionAndRegexAtHead(false, '.', '+', "a$", "baab"));
779 // Repeating zero times.
780 EXPECT_FALSE(MatchRepetitionAndRegexAtHead(false, '.', '+', "b", "bc"));
783 EXPECT_TRUE(MatchRepetitionAndRegexAtHead(false, '.', '+', "b", "abc"));
784 // Repeating more than once.
785 EXPECT_TRUE(MatchRepetitionAndRegexAtHead(true, 'w', '+', "-", "ab_1-g"));
788 TEST(MatchRegexAtHeadTest, ReturnsTrueForEmptyRegex) {
789 EXPECT_TRUE(MatchRegexAtHead("", ""));
790 EXPECT_TRUE(MatchRegexAtHead("", "ab"));
793 TEST(MatchRegexAtHeadTest, WorksWhenDollarIsInRegex) {
794 EXPECT_FALSE(MatchRegexAtHead("$", "a"));
796 EXPECT_TRUE(MatchRegexAtHead("$", ""));
797 EXPECT_TRUE(MatchRegexAtHead("a$", "a"));
800 TEST(MatchRegexAtHeadTest, WorksWhenRegexStartsWithEscapeSequence) {
801 EXPECT_FALSE(MatchRegexAtHead("\\w", "+"));
802 EXPECT_FALSE(MatchRegexAtHead("\\W", "ab"));
804 EXPECT_TRUE(MatchRegexAtHead("\\sa", "\nab"));
805 EXPECT_TRUE(MatchRegexAtHead("\\d", "1a"));
808 TEST(MatchRegexAtHeadTest, WorksWhenRegexStartsWithRepetition) {
809 EXPECT_FALSE(MatchRegexAtHead(".+a", "abc"));
810 EXPECT_FALSE(MatchRegexAtHead("a?b", "aab"));
812 EXPECT_TRUE(MatchRegexAtHead(".*a", "bc12-ab"));
813 EXPECT_TRUE(MatchRegexAtHead("a?b", "b"));
814 EXPECT_TRUE(MatchRegexAtHead("a?b", "ab"));
817 TEST(MatchRegexAtHeadTest,
818 WorksWhenRegexStartsWithRepetionOfEscapeSequence) {
819 EXPECT_FALSE(MatchRegexAtHead("\\.+a", "abc"));
820 EXPECT_FALSE(MatchRegexAtHead("\\s?b", " b"));
822 EXPECT_TRUE(MatchRegexAtHead("\\(*a", "((((ab"));
823 EXPECT_TRUE(MatchRegexAtHead("\\^?b", "^b"));
824 EXPECT_TRUE(MatchRegexAtHead("\\\\?b", "b"));
825 EXPECT_TRUE(MatchRegexAtHead("\\\\?b", "\\b"));
828 TEST(MatchRegexAtHeadTest, MatchesSequentially) {
829 EXPECT_FALSE(MatchRegexAtHead("ab.*c", "acabc"));
831 EXPECT_TRUE(MatchRegexAtHead("ab.*c", "ab-fsc"));
834 TEST(MatchRegexAnywhereTest, ReturnsFalseWhenStringIsNull) {
835 EXPECT_FALSE(MatchRegexAnywhere("", NULL));
838 TEST(MatchRegexAnywhereTest, WorksWhenRegexStartsWithCaret) {
839 EXPECT_FALSE(MatchRegexAnywhere("^a", "ba"));
840 EXPECT_FALSE(MatchRegexAnywhere("^$", "a"));
842 EXPECT_TRUE(MatchRegexAnywhere("^a", "ab"));
843 EXPECT_TRUE(MatchRegexAnywhere("^", "ab"));
844 EXPECT_TRUE(MatchRegexAnywhere("^$", ""));
847 TEST(MatchRegexAnywhereTest, ReturnsFalseWhenNoMatch) {
848 EXPECT_FALSE(MatchRegexAnywhere("a", "bcde123"));
849 EXPECT_FALSE(MatchRegexAnywhere("a.+a", "--aa88888888"));
852 TEST(MatchRegexAnywhereTest, ReturnsTrueWhenMatchingPrefix) {
853 EXPECT_TRUE(MatchRegexAnywhere("\\w+", "ab1_ - 5"));
854 EXPECT_TRUE(MatchRegexAnywhere(".*=", "="));
855 EXPECT_TRUE(MatchRegexAnywhere("x.*ab?.*bc", "xaaabc"));
858 TEST(MatchRegexAnywhereTest, ReturnsTrueWhenMatchingNonPrefix) {
859 EXPECT_TRUE(MatchRegexAnywhere("\\w+", "$$$ ab1_ - 5"));
860 EXPECT_TRUE(MatchRegexAnywhere("\\.+=", "= ...="));
863 // Tests RE's implicit constructors.
864 TEST(RETest, ImplicitConstructorWorks) {
866 EXPECT_STREQ("", empty.pattern());
868 const RE simple("hello");
869 EXPECT_STREQ("hello", simple.pattern());
872 // Tests that RE's constructors reject invalid regular expressions.
873 TEST(RETest, RejectsInvalidRegex) {
874 EXPECT_NONFATAL_FAILURE({
875 const RE normal(NULL);
876 }, "NULL is not a valid simple regular expression");
878 EXPECT_NONFATAL_FAILURE({
879 const RE normal(".*(\\w+");
880 }, "'(' is unsupported");
882 EXPECT_NONFATAL_FAILURE({
883 const RE invalid("^?");
884 }, "'?' can only follow a repeatable token");
887 // Tests RE::FullMatch().
888 TEST(RETest, FullMatchWorks) {
890 EXPECT_TRUE(RE::FullMatch("", empty));
891 EXPECT_FALSE(RE::FullMatch("a", empty));
894 EXPECT_TRUE(RE::FullMatch("a", re1));
897 EXPECT_TRUE(RE::FullMatch("az", re));
898 EXPECT_TRUE(RE::FullMatch("axyz", re));
899 EXPECT_FALSE(RE::FullMatch("baz", re));
900 EXPECT_FALSE(RE::FullMatch("azy", re));
903 // Tests RE::PartialMatch().
904 TEST(RETest, PartialMatchWorks) {
906 EXPECT_TRUE(RE::PartialMatch("", empty));
907 EXPECT_TRUE(RE::PartialMatch("a", empty));
910 EXPECT_TRUE(RE::PartialMatch("az", re));
911 EXPECT_TRUE(RE::PartialMatch("axyz", re));
912 EXPECT_TRUE(RE::PartialMatch("baz", re));
913 EXPECT_TRUE(RE::PartialMatch("azy", re));
914 EXPECT_FALSE(RE::PartialMatch("zza", re));
917 #endif // GTEST_USES_POSIX_RE
919 #if !GTEST_OS_WINDOWS_MOBILE
921 TEST(CaptureTest, CapturesStdout) {
923 fprintf(stdout, "abc");
924 EXPECT_STREQ("abc", GetCapturedStdout().c_str());
927 fprintf(stdout, "def%cghi", '\0');
928 EXPECT_EQ(::std::string("def\0ghi", 7), ::std::string(GetCapturedStdout()));
931 TEST(CaptureTest, CapturesStderr) {
933 fprintf(stderr, "jkl");
934 EXPECT_STREQ("jkl", GetCapturedStderr().c_str());
937 fprintf(stderr, "jkl%cmno", '\0');
938 EXPECT_EQ(::std::string("jkl\0mno", 7), ::std::string(GetCapturedStderr()));
941 // Tests that stdout and stderr capture don't interfere with each other.
942 TEST(CaptureTest, CapturesStdoutAndStderr) {
945 fprintf(stdout, "pqr");
946 fprintf(stderr, "stu");
947 EXPECT_STREQ("pqr", GetCapturedStdout().c_str());
948 EXPECT_STREQ("stu", GetCapturedStderr().c_str());
951 TEST(CaptureDeathTest, CannotReenterStdoutCapture) {
953 EXPECT_DEATH_IF_SUPPORTED(CaptureStdout(),
954 "Only one stdout capturer can exist at a time");
957 // We cannot test stderr capturing using death tests as they use it
961 #endif // !GTEST_OS_WINDOWS_MOBILE
963 TEST(ThreadLocalTest, DefaultConstructorInitializesToDefaultValues) {
965 EXPECT_EQ(0, t1.get());
967 ThreadLocal<void*> t2;
968 EXPECT_TRUE(t2.get() == NULL);
971 TEST(ThreadLocalTest, SingleParamConstructorInitializesToParam) {
972 ThreadLocal<int> t1(123);
973 EXPECT_EQ(123, t1.get());
976 ThreadLocal<int*> t2(&i);
977 EXPECT_EQ(&i, t2.get());
980 class NoDefaultContructor {
982 explicit NoDefaultContructor(const char*) {}
983 NoDefaultContructor(const NoDefaultContructor&) {}
986 TEST(ThreadLocalTest, ValueDefaultContructorIsNotRequiredForParamVersion) {
987 ThreadLocal<NoDefaultContructor> bar(NoDefaultContructor("foo"));
991 TEST(ThreadLocalTest, GetAndPointerReturnSameValue) {
992 ThreadLocal<std::string> thread_local_string;
994 EXPECT_EQ(thread_local_string.pointer(), &(thread_local_string.get()));
996 // Verifies the condition still holds after calling set.
997 thread_local_string.set("foo");
998 EXPECT_EQ(thread_local_string.pointer(), &(thread_local_string.get()));
1001 TEST(ThreadLocalTest, PointerAndConstPointerReturnSameValue) {
1002 ThreadLocal<std::string> thread_local_string;
1003 const ThreadLocal<std::string>& const_thread_local_string =
1004 thread_local_string;
1006 EXPECT_EQ(thread_local_string.pointer(), const_thread_local_string.pointer());
1008 thread_local_string.set("foo");
1009 EXPECT_EQ(thread_local_string.pointer(), const_thread_local_string.pointer());
1012 #if GTEST_IS_THREADSAFE
1014 void AddTwo(int* param) { *param += 2; }
1016 TEST(ThreadWithParamTest, ConstructorExecutesThreadFunc) {
1018 ThreadWithParam<int*> thread(&AddTwo, &i, NULL);
1023 TEST(MutexDeathTest, AssertHeldShouldAssertWhenNotLocked) {
1024 // AssertHeld() is flaky only in the presence of multiple threads accessing
1025 // the lock. In this case, the test is robust.
1026 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 SleepMilliseconds 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, NULL));
1059 GTEST_CHECK_POSIX_SUCCESS_(pthread_mutex_lock(&memory_barrier_mutex));
1061 SleepMilliseconds(random_.Generate(30));
1063 GTEST_CHECK_POSIX_SUCCESS_(pthread_mutex_unlock(&memory_barrier_mutex));
1064 GTEST_CHECK_POSIX_SUCCESS_(pthread_mutex_destroy(&memory_barrier_mutex));
1065 #elif GTEST_OS_WINDOWS
1066 // On Windows, performing an interlocked access puts up a memory barrier.
1067 volatile LONG dummy = 0;
1068 ::InterlockedIncrement(&dummy);
1069 SleepMilliseconds(random_.Generate(30));
1070 ::InterlockedIncrement(&dummy);
1072 # error "Memory barrier not implemented on this platform."
1073 #endif // GTEST_HAS_PTHREAD
1077 int value() const { return value_; }
1080 volatile int value_;
1081 Mutex* const mutex_; // Protects value_.
1085 void CountingThreadFunc(pair<AtomicCounterWithMutex*, int> param) {
1086 for (int i = 0; i < param.second; ++i)
1087 param.first->Increment();
1090 // Tests that the mutex only lets one thread at a time to lock it.
1091 TEST(MutexTest, OnlyOneThreadCanLockAtATime) {
1093 AtomicCounterWithMutex locked_counter(&mutex);
1095 typedef ThreadWithParam<pair<AtomicCounterWithMutex*, int> > ThreadType;
1096 const int kCycleCount = 20;
1097 const int kThreadCount = 7;
1098 scoped_ptr<ThreadType> counting_threads[kThreadCount];
1099 Notification threads_can_start;
1100 // Creates and runs kThreadCount threads that increment locked_counter
1101 // kCycleCount times each.
1102 for (int i = 0; i < kThreadCount; ++i) {
1103 counting_threads[i].reset(new ThreadType(&CountingThreadFunc,
1104 make_pair(&locked_counter,
1106 &threads_can_start));
1108 threads_can_start.Notify();
1109 for (int i = 0; i < kThreadCount; ++i)
1110 counting_threads[i]->Join();
1112 // If the mutex lets more than one thread to increment the counter at a
1113 // time, they are likely to encounter a race condition and have some
1114 // increments overwritten, resulting in the lower then expected counter
1116 EXPECT_EQ(kCycleCount * kThreadCount, locked_counter.value());
1119 template <typename T>
1120 void RunFromThread(void (func)(T), T param) {
1121 ThreadWithParam<T> thread(func, param, NULL);
1125 void RetrieveThreadLocalValue(
1126 pair<ThreadLocal<std::string>*, std::string*> param) {
1127 *param.second = param.first->get();
1130 TEST(ThreadLocalTest, ParameterizedConstructorSetsDefault) {
1131 ThreadLocal<std::string> thread_local_string("foo");
1132 EXPECT_STREQ("foo", thread_local_string.get().c_str());
1134 thread_local_string.set("bar");
1135 EXPECT_STREQ("bar", thread_local_string.get().c_str());
1138 RunFromThread(&RetrieveThreadLocalValue,
1139 make_pair(&thread_local_string, &result));
1140 EXPECT_STREQ("foo", result.c_str());
1143 // Keeps track of whether of destructors being called on instances of
1144 // DestructorTracker. On Windows, waits for the destructor call reports.
1145 class DestructorCall {
1149 #if GTEST_OS_WINDOWS
1150 wait_event_.Reset(::CreateEvent(NULL, TRUE, FALSE, NULL));
1151 GTEST_CHECK_(wait_event_.Get() != NULL);
1155 bool CheckDestroyed() const {
1156 #if GTEST_OS_WINDOWS
1157 if (::WaitForSingleObject(wait_event_.Get(), 1000) != WAIT_OBJECT_0)
1163 void ReportDestroyed() {
1165 #if GTEST_OS_WINDOWS
1166 ::SetEvent(wait_event_.Get());
1170 static std::vector<DestructorCall*>& List() { return *list_; }
1172 static void ResetList() {
1173 for (size_t i = 0; i < list_->size(); ++i) {
1174 delete list_->at(i);
1181 #if GTEST_OS_WINDOWS
1182 AutoHandle wait_event_;
1184 static std::vector<DestructorCall*>* const list_;
1186 GTEST_DISALLOW_COPY_AND_ASSIGN_(DestructorCall);
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_;
1212 GTEST_DISALLOW_ASSIGN_(DestructorTracker);
1215 typedef ThreadLocal<DestructorTracker>* ThreadParam;
1217 void CallThreadLocalGet(ThreadParam thread_local_param) {
1218 thread_local_param->get();
1221 // Tests that when a ThreadLocal object dies in a thread, it destroys
1222 // the managed object for that thread.
1223 TEST(ThreadLocalTest, DestroysManagedObjectForOwnThreadWhenDying) {
1224 DestructorCall::ResetList();
1227 ThreadLocal<DestructorTracker> thread_local_tracker;
1228 ASSERT_EQ(0U, DestructorCall::List().size());
1230 // This creates another DestructorTracker object for the main thread.
1231 thread_local_tracker.get();
1232 ASSERT_EQ(1U, DestructorCall::List().size());
1233 ASSERT_FALSE(DestructorCall::List()[0]->CheckDestroyed());
1236 // Now thread_local_tracker has died.
1237 ASSERT_EQ(1U, DestructorCall::List().size());
1238 EXPECT_TRUE(DestructorCall::List()[0]->CheckDestroyed());
1240 DestructorCall::ResetList();
1243 // Tests that when a thread exits, the thread-local object for that
1244 // thread is destroyed.
1245 TEST(ThreadLocalTest, DestroysManagedObjectAtThreadExit) {
1246 DestructorCall::ResetList();
1249 ThreadLocal<DestructorTracker> thread_local_tracker;
1250 ASSERT_EQ(0U, DestructorCall::List().size());
1252 // This creates another DestructorTracker object in the new thread.
1253 ThreadWithParam<ThreadParam> thread(
1254 &CallThreadLocalGet, &thread_local_tracker, NULL);
1257 // The thread has exited, and we should have a DestroyedTracker
1258 // instance created for it. But it may not have been destroyed yet.
1259 ASSERT_EQ(1U, DestructorCall::List().size());
1262 // The thread has exited and thread_local_tracker has died.
1263 ASSERT_EQ(1U, DestructorCall::List().size());
1264 EXPECT_TRUE(DestructorCall::List()[0]->CheckDestroyed());
1266 DestructorCall::ResetList();
1269 TEST(ThreadLocalTest, ThreadLocalMutationsAffectOnlyCurrentThread) {
1270 ThreadLocal<std::string> thread_local_string;
1271 thread_local_string.set("Foo");
1272 EXPECT_STREQ("Foo", thread_local_string.get().c_str());
1275 RunFromThread(&RetrieveThreadLocalValue,
1276 make_pair(&thread_local_string, &result));
1277 EXPECT_TRUE(result.empty());
1280 #endif // GTEST_IS_THREADSAFE
1282 #if GTEST_OS_WINDOWS
1283 TEST(WindowsTypesTest, HANDLEIsVoidStar) {
1284 StaticAssertTypeEq<HANDLE, void*>();
1287 #if GTEST_OS_WINDOWS_MINGW && !defined(__MINGW64_VERSION_MAJOR)
1288 TEST(WindowsTypesTest, _CRITICAL_SECTIONIs_CRITICAL_SECTION) {
1289 StaticAssertTypeEq<CRITICAL_SECTION, _CRITICAL_SECTION>();
1292 TEST(WindowsTypesTest, CRITICAL_SECTIONIs_RTL_CRITICAL_SECTION) {
1293 StaticAssertTypeEq<CRITICAL_SECTION, _RTL_CRITICAL_SECTION>();
1297 #endif // GTEST_OS_WINDOWS
1299 } // namespace internal
1300 } // namespace testing