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 // Authors: vladl@google.com (Vlad Losev), wan@google.com (Zhanyong Wan)
32 // This file tests the internal cross-platform support utilities.
34 #include "gtest/internal/gtest-port.h"
40 #endif // GTEST_OS_MAC
43 #include <utility> // For std::pair and std::make_pair.
46 #include "gtest/gtest.h"
47 #include "gtest/gtest-spi.h"
49 // Indicates that this translation unit is part of Google Test's
50 // implementation. It must come before gtest-internal-inl.h is
51 // included, or there will be a compiler error. This trick is to
52 // prevent a user from accidentally including gtest-internal-inl.h in
54 #define GTEST_IMPLEMENTATION_ 1
55 #include "src/gtest-internal-inl.h"
56 #undef GTEST_IMPLEMENTATION_
64 TEST(IsXDigitTest, WorksForNarrowAscii) {
65 EXPECT_TRUE(IsXDigit('0'));
66 EXPECT_TRUE(IsXDigit('9'));
67 EXPECT_TRUE(IsXDigit('A'));
68 EXPECT_TRUE(IsXDigit('F'));
69 EXPECT_TRUE(IsXDigit('a'));
70 EXPECT_TRUE(IsXDigit('f'));
72 EXPECT_FALSE(IsXDigit('-'));
73 EXPECT_FALSE(IsXDigit('g'));
74 EXPECT_FALSE(IsXDigit('G'));
77 TEST(IsXDigitTest, ReturnsFalseForNarrowNonAscii) {
78 EXPECT_FALSE(IsXDigit('\x80'));
79 EXPECT_FALSE(IsXDigit(static_cast<char>('0' | '\x80')));
82 TEST(IsXDigitTest, WorksForWideAscii) {
83 EXPECT_TRUE(IsXDigit(L'0'));
84 EXPECT_TRUE(IsXDigit(L'9'));
85 EXPECT_TRUE(IsXDigit(L'A'));
86 EXPECT_TRUE(IsXDigit(L'F'));
87 EXPECT_TRUE(IsXDigit(L'a'));
88 EXPECT_TRUE(IsXDigit(L'f'));
90 EXPECT_FALSE(IsXDigit(L'-'));
91 EXPECT_FALSE(IsXDigit(L'g'));
92 EXPECT_FALSE(IsXDigit(L'G'));
95 TEST(IsXDigitTest, ReturnsFalseForWideNonAscii) {
96 EXPECT_FALSE(IsXDigit(static_cast<wchar_t>(0x80)));
97 EXPECT_FALSE(IsXDigit(static_cast<wchar_t>(L'0' | 0x80)));
98 EXPECT_FALSE(IsXDigit(static_cast<wchar_t>(L'0' | 0x100)));
103 // Copy constructor and assignment operator do exactly what we need, so we
105 Base() : member_(0) {}
106 explicit Base(int n) : member_(n) {}
108 int member() { return member_; }
114 class Derived : public Base {
116 explicit Derived(int n) : Base(n) {}
119 TEST(ImplicitCastTest, ConvertsPointers) {
121 EXPECT_TRUE(&derived == ::testing::internal::ImplicitCast_<Base*>(&derived));
124 TEST(ImplicitCastTest, CanUseInheritance) {
126 Base base = ::testing::internal::ImplicitCast_<Base>(derived);
127 EXPECT_EQ(derived.member(), base.member());
132 explicit Castable(bool* converted) : converted_(converted) {}
142 TEST(ImplicitCastTest, CanUseNonConstCastOperator) {
143 bool converted = false;
144 Castable castable(&converted);
145 Base base = ::testing::internal::ImplicitCast_<Base>(castable);
146 EXPECT_TRUE(converted);
149 class ConstCastable {
151 explicit ConstCastable(bool* converted) : converted_(converted) {}
152 operator Base() const {
161 TEST(ImplicitCastTest, CanUseConstCastOperatorOnConstValues) {
162 bool converted = false;
163 const ConstCastable const_castable(&converted);
164 Base base = ::testing::internal::ImplicitCast_<Base>(const_castable);
165 EXPECT_TRUE(converted);
168 class ConstAndNonConstCastable {
170 ConstAndNonConstCastable(bool* converted, bool* const_converted)
171 : converted_(converted), const_converted_(const_converted) {}
176 operator Base() const {
177 *const_converted_ = true;
183 bool* const_converted_;
186 TEST(ImplicitCastTest, CanSelectBetweenConstAndNonConstCasrAppropriately) {
187 bool converted = false;
188 bool const_converted = false;
189 ConstAndNonConstCastable castable(&converted, &const_converted);
190 Base base = ::testing::internal::ImplicitCast_<Base>(castable);
191 EXPECT_TRUE(converted);
192 EXPECT_FALSE(const_converted);
195 const_converted = false;
196 const ConstAndNonConstCastable const_castable(&converted, &const_converted);
197 base = ::testing::internal::ImplicitCast_<Base>(const_castable);
198 EXPECT_FALSE(converted);
199 EXPECT_TRUE(const_converted);
204 To(bool* converted) { *converted = true; } // NOLINT
207 TEST(ImplicitCastTest, CanUseImplicitConstructor) {
208 bool converted = false;
209 To to = ::testing::internal::ImplicitCast_<To>(&converted);
211 EXPECT_TRUE(converted);
214 TEST(IteratorTraitsTest, WorksForSTLContainerIterators) {
215 StaticAssertTypeEq<int,
216 IteratorTraits< ::std::vector<int>::const_iterator>::value_type>();
217 StaticAssertTypeEq<bool,
218 IteratorTraits< ::std::list<bool>::iterator>::value_type>();
221 TEST(IteratorTraitsTest, WorksForPointerToNonConst) {
222 StaticAssertTypeEq<char, IteratorTraits<char*>::value_type>();
223 StaticAssertTypeEq<const void*, IteratorTraits<const void**>::value_type>();
226 TEST(IteratorTraitsTest, WorksForPointerToConst) {
227 StaticAssertTypeEq<char, IteratorTraits<const char*>::value_type>();
228 StaticAssertTypeEq<const void*,
229 IteratorTraits<const void* const*>::value_type>();
232 // Tests that the element_type typedef is available in scoped_ptr and refers
233 // to the parameter type.
234 TEST(ScopedPtrTest, DefinesElementType) {
235 StaticAssertTypeEq<int, ::testing::internal::scoped_ptr<int>::element_type>();
238 // TODO(vladl@google.com): Implement THE REST of scoped_ptr tests.
240 TEST(GtestCheckSyntaxTest, BehavesLikeASingleStatement) {
242 GTEST_CHECK_(false) << "This should never be executed; "
243 "It's a compilation test only.";
253 GTEST_CHECK_(true) << "";
256 TEST(GtestCheckSyntaxTest, WorksWithSwitch) {
266 GTEST_CHECK_(true) << "Check failed in switch case";
269 // Verifies behavior of FormatFileLocation.
270 TEST(FormatFileLocationTest, FormatsFileLocation) {
271 EXPECT_PRED_FORMAT2(IsSubstring, "foo.cc", FormatFileLocation("foo.cc", 42));
272 EXPECT_PRED_FORMAT2(IsSubstring, "42", FormatFileLocation("foo.cc", 42));
275 TEST(FormatFileLocationTest, FormatsUnknownFile) {
277 IsSubstring, "unknown file", FormatFileLocation(NULL, 42));
278 EXPECT_PRED_FORMAT2(IsSubstring, "42", FormatFileLocation(NULL, 42));
281 TEST(FormatFileLocationTest, FormatsUknownLine) {
282 EXPECT_EQ("foo.cc:", FormatFileLocation("foo.cc", -1));
285 TEST(FormatFileLocationTest, FormatsUknownFileAndLine) {
286 EXPECT_EQ("unknown file:", FormatFileLocation(NULL, -1));
289 // Verifies behavior of FormatCompilerIndependentFileLocation.
290 TEST(FormatCompilerIndependentFileLocationTest, FormatsFileLocation) {
291 EXPECT_EQ("foo.cc:42", FormatCompilerIndependentFileLocation("foo.cc", 42));
294 TEST(FormatCompilerIndependentFileLocationTest, FormatsUknownFile) {
295 EXPECT_EQ("unknown file:42",
296 FormatCompilerIndependentFileLocation(NULL, 42));
299 TEST(FormatCompilerIndependentFileLocationTest, FormatsUknownLine) {
300 EXPECT_EQ("foo.cc", FormatCompilerIndependentFileLocation("foo.cc", -1));
303 TEST(FormatCompilerIndependentFileLocationTest, FormatsUknownFileAndLine) {
304 EXPECT_EQ("unknown file", FormatCompilerIndependentFileLocation(NULL, -1));
307 #if GTEST_OS_LINUX || GTEST_OS_MAC || GTEST_OS_QNX
308 void* ThreadFunc(void* data) {
309 internal::Mutex* mutex = static_cast<internal::Mutex*>(data);
315 TEST(GetThreadCountTest, ReturnsCorrectValue) {
316 const size_t starting_count = GetThreadCount();
319 internal::Mutex mutex;
321 internal::MutexLock lock(&mutex);
323 ASSERT_EQ(0, pthread_attr_init(&attr));
324 ASSERT_EQ(0, pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_JOINABLE));
326 const int status = pthread_create(&thread_id, &attr, &ThreadFunc, &mutex);
327 ASSERT_EQ(0, pthread_attr_destroy(&attr));
328 ASSERT_EQ(0, status);
329 EXPECT_EQ(starting_count + 1, GetThreadCount());
333 ASSERT_EQ(0, pthread_join(thread_id, &dummy));
335 // The OS may not immediately report the updated thread count after
336 // joining a thread, causing flakiness in this test. To counter that, we
337 // wait for up to .5 seconds for the OS to report the correct value.
338 for (int i = 0; i < 5; ++i) {
339 if (GetThreadCount() == starting_count)
342 SleepMilliseconds(100);
345 EXPECT_EQ(starting_count, GetThreadCount());
348 TEST(GetThreadCountTest, ReturnsZeroWhenUnableToCountThreads) {
349 EXPECT_EQ(0U, GetThreadCount());
351 #endif // GTEST_OS_LINUX || GTEST_OS_MAC || GTEST_OS_QNX
353 TEST(GtestCheckDeathTest, DiesWithCorrectOutputOnFailure) {
354 const bool a_false_condition = false;
357 "gtest-port_test\\.cc\\(\\d+\\):"
358 #elif GTEST_USES_POSIX_RE
359 "gtest-port_test\\.cc:[0-9]+"
361 "gtest-port_test\\.cc:\\d+"
363 ".*a_false_condition.*Extra info.*";
365 EXPECT_DEATH_IF_SUPPORTED(GTEST_CHECK_(a_false_condition) << "Extra info",
369 #if GTEST_HAS_DEATH_TEST
371 TEST(GtestCheckDeathTest, LivesSilentlyOnSuccess) {
373 GTEST_CHECK_(true) << "Extra info";
374 ::std::cerr << "Success\n";
376 ::testing::ExitedWithCode(0), "Success");
379 #endif // GTEST_HAS_DEATH_TEST
381 // Verifies that Google Test choose regular expression engine appropriate to
382 // the platform. The test will produce compiler errors in case of failure.
383 // For simplicity, we only cover the most important platforms here.
384 TEST(RegexEngineSelectionTest, SelectsCorrectRegexEngine) {
386 # if GTEST_HAS_POSIX_RE
388 EXPECT_TRUE(GTEST_USES_POSIX_RE);
392 EXPECT_TRUE(GTEST_USES_SIMPLE_RE);
395 #endif // !GTEST_USES_PCRE
398 #if GTEST_USES_POSIX_RE
400 # if GTEST_HAS_TYPED_TEST
402 template <typename Str>
403 class RETest : public ::testing::Test {};
405 // Defines StringTypes as the list of all string types that class RE
407 typedef testing::Types<
409 # if GTEST_HAS_GLOBAL_STRING
411 # endif // GTEST_HAS_GLOBAL_STRING
412 const char*> StringTypes;
414 TYPED_TEST_CASE(RETest, StringTypes);
416 // Tests RE's implicit constructors.
417 TYPED_TEST(RETest, ImplicitConstructorWorks) {
418 const RE empty(TypeParam(""));
419 EXPECT_STREQ("", empty.pattern());
421 const RE simple(TypeParam("hello"));
422 EXPECT_STREQ("hello", simple.pattern());
424 const RE normal(TypeParam(".*(\\w+)"));
425 EXPECT_STREQ(".*(\\w+)", normal.pattern());
428 // Tests that RE's constructors reject invalid regular expressions.
429 TYPED_TEST(RETest, RejectsInvalidRegex) {
430 EXPECT_NONFATAL_FAILURE({
431 const RE invalid(TypeParam("?"));
432 }, "\"?\" is not a valid POSIX Extended regular expression.");
435 // Tests RE::FullMatch().
436 TYPED_TEST(RETest, FullMatchWorks) {
437 const RE empty(TypeParam(""));
438 EXPECT_TRUE(RE::FullMatch(TypeParam(""), empty));
439 EXPECT_FALSE(RE::FullMatch(TypeParam("a"), empty));
441 const RE re(TypeParam("a.*z"));
442 EXPECT_TRUE(RE::FullMatch(TypeParam("az"), re));
443 EXPECT_TRUE(RE::FullMatch(TypeParam("axyz"), re));
444 EXPECT_FALSE(RE::FullMatch(TypeParam("baz"), re));
445 EXPECT_FALSE(RE::FullMatch(TypeParam("azy"), re));
448 // Tests RE::PartialMatch().
449 TYPED_TEST(RETest, PartialMatchWorks) {
450 const RE empty(TypeParam(""));
451 EXPECT_TRUE(RE::PartialMatch(TypeParam(""), empty));
452 EXPECT_TRUE(RE::PartialMatch(TypeParam("a"), empty));
454 const RE re(TypeParam("a.*z"));
455 EXPECT_TRUE(RE::PartialMatch(TypeParam("az"), re));
456 EXPECT_TRUE(RE::PartialMatch(TypeParam("axyz"), re));
457 EXPECT_TRUE(RE::PartialMatch(TypeParam("baz"), re));
458 EXPECT_TRUE(RE::PartialMatch(TypeParam("azy"), re));
459 EXPECT_FALSE(RE::PartialMatch(TypeParam("zza"), re));
462 # endif // GTEST_HAS_TYPED_TEST
464 #elif GTEST_USES_SIMPLE_RE
466 TEST(IsInSetTest, NulCharIsNotInAnySet) {
467 EXPECT_FALSE(IsInSet('\0', ""));
468 EXPECT_FALSE(IsInSet('\0', "\0"));
469 EXPECT_FALSE(IsInSet('\0', "a"));
472 TEST(IsInSetTest, WorksForNonNulChars) {
473 EXPECT_FALSE(IsInSet('a', "Ab"));
474 EXPECT_FALSE(IsInSet('c', ""));
476 EXPECT_TRUE(IsInSet('b', "bcd"));
477 EXPECT_TRUE(IsInSet('b', "ab"));
480 TEST(IsAsciiDigitTest, IsFalseForNonDigit) {
481 EXPECT_FALSE(IsAsciiDigit('\0'));
482 EXPECT_FALSE(IsAsciiDigit(' '));
483 EXPECT_FALSE(IsAsciiDigit('+'));
484 EXPECT_FALSE(IsAsciiDigit('-'));
485 EXPECT_FALSE(IsAsciiDigit('.'));
486 EXPECT_FALSE(IsAsciiDigit('a'));
489 TEST(IsAsciiDigitTest, IsTrueForDigit) {
490 EXPECT_TRUE(IsAsciiDigit('0'));
491 EXPECT_TRUE(IsAsciiDigit('1'));
492 EXPECT_TRUE(IsAsciiDigit('5'));
493 EXPECT_TRUE(IsAsciiDigit('9'));
496 TEST(IsAsciiPunctTest, IsFalseForNonPunct) {
497 EXPECT_FALSE(IsAsciiPunct('\0'));
498 EXPECT_FALSE(IsAsciiPunct(' '));
499 EXPECT_FALSE(IsAsciiPunct('\n'));
500 EXPECT_FALSE(IsAsciiPunct('a'));
501 EXPECT_FALSE(IsAsciiPunct('0'));
504 TEST(IsAsciiPunctTest, IsTrueForPunct) {
505 for (const char* p = "^-!\"#$%&'()*+,./:;<=>?@[\\]_`{|}~"; *p; p++) {
506 EXPECT_PRED1(IsAsciiPunct, *p);
510 TEST(IsRepeatTest, IsFalseForNonRepeatChar) {
511 EXPECT_FALSE(IsRepeat('\0'));
512 EXPECT_FALSE(IsRepeat(' '));
513 EXPECT_FALSE(IsRepeat('a'));
514 EXPECT_FALSE(IsRepeat('1'));
515 EXPECT_FALSE(IsRepeat('-'));
518 TEST(IsRepeatTest, IsTrueForRepeatChar) {
519 EXPECT_TRUE(IsRepeat('?'));
520 EXPECT_TRUE(IsRepeat('*'));
521 EXPECT_TRUE(IsRepeat('+'));
524 TEST(IsAsciiWhiteSpaceTest, IsFalseForNonWhiteSpace) {
525 EXPECT_FALSE(IsAsciiWhiteSpace('\0'));
526 EXPECT_FALSE(IsAsciiWhiteSpace('a'));
527 EXPECT_FALSE(IsAsciiWhiteSpace('1'));
528 EXPECT_FALSE(IsAsciiWhiteSpace('+'));
529 EXPECT_FALSE(IsAsciiWhiteSpace('_'));
532 TEST(IsAsciiWhiteSpaceTest, IsTrueForWhiteSpace) {
533 EXPECT_TRUE(IsAsciiWhiteSpace(' '));
534 EXPECT_TRUE(IsAsciiWhiteSpace('\n'));
535 EXPECT_TRUE(IsAsciiWhiteSpace('\r'));
536 EXPECT_TRUE(IsAsciiWhiteSpace('\t'));
537 EXPECT_TRUE(IsAsciiWhiteSpace('\v'));
538 EXPECT_TRUE(IsAsciiWhiteSpace('\f'));
541 TEST(IsAsciiWordCharTest, IsFalseForNonWordChar) {
542 EXPECT_FALSE(IsAsciiWordChar('\0'));
543 EXPECT_FALSE(IsAsciiWordChar('+'));
544 EXPECT_FALSE(IsAsciiWordChar('.'));
545 EXPECT_FALSE(IsAsciiWordChar(' '));
546 EXPECT_FALSE(IsAsciiWordChar('\n'));
549 TEST(IsAsciiWordCharTest, IsTrueForLetter) {
550 EXPECT_TRUE(IsAsciiWordChar('a'));
551 EXPECT_TRUE(IsAsciiWordChar('b'));
552 EXPECT_TRUE(IsAsciiWordChar('A'));
553 EXPECT_TRUE(IsAsciiWordChar('Z'));
556 TEST(IsAsciiWordCharTest, IsTrueForDigit) {
557 EXPECT_TRUE(IsAsciiWordChar('0'));
558 EXPECT_TRUE(IsAsciiWordChar('1'));
559 EXPECT_TRUE(IsAsciiWordChar('7'));
560 EXPECT_TRUE(IsAsciiWordChar('9'));
563 TEST(IsAsciiWordCharTest, IsTrueForUnderscore) {
564 EXPECT_TRUE(IsAsciiWordChar('_'));
567 TEST(IsValidEscapeTest, IsFalseForNonPrintable) {
568 EXPECT_FALSE(IsValidEscape('\0'));
569 EXPECT_FALSE(IsValidEscape('\007'));
572 TEST(IsValidEscapeTest, IsFalseForDigit) {
573 EXPECT_FALSE(IsValidEscape('0'));
574 EXPECT_FALSE(IsValidEscape('9'));
577 TEST(IsValidEscapeTest, IsFalseForWhiteSpace) {
578 EXPECT_FALSE(IsValidEscape(' '));
579 EXPECT_FALSE(IsValidEscape('\n'));
582 TEST(IsValidEscapeTest, IsFalseForSomeLetter) {
583 EXPECT_FALSE(IsValidEscape('a'));
584 EXPECT_FALSE(IsValidEscape('Z'));
587 TEST(IsValidEscapeTest, IsTrueForPunct) {
588 EXPECT_TRUE(IsValidEscape('.'));
589 EXPECT_TRUE(IsValidEscape('-'));
590 EXPECT_TRUE(IsValidEscape('^'));
591 EXPECT_TRUE(IsValidEscape('$'));
592 EXPECT_TRUE(IsValidEscape('('));
593 EXPECT_TRUE(IsValidEscape(']'));
594 EXPECT_TRUE(IsValidEscape('{'));
595 EXPECT_TRUE(IsValidEscape('|'));
598 TEST(IsValidEscapeTest, IsTrueForSomeLetter) {
599 EXPECT_TRUE(IsValidEscape('d'));
600 EXPECT_TRUE(IsValidEscape('D'));
601 EXPECT_TRUE(IsValidEscape('s'));
602 EXPECT_TRUE(IsValidEscape('S'));
603 EXPECT_TRUE(IsValidEscape('w'));
604 EXPECT_TRUE(IsValidEscape('W'));
607 TEST(AtomMatchesCharTest, EscapedPunct) {
608 EXPECT_FALSE(AtomMatchesChar(true, '\\', '\0'));
609 EXPECT_FALSE(AtomMatchesChar(true, '\\', ' '));
610 EXPECT_FALSE(AtomMatchesChar(true, '_', '.'));
611 EXPECT_FALSE(AtomMatchesChar(true, '.', 'a'));
613 EXPECT_TRUE(AtomMatchesChar(true, '\\', '\\'));
614 EXPECT_TRUE(AtomMatchesChar(true, '_', '_'));
615 EXPECT_TRUE(AtomMatchesChar(true, '+', '+'));
616 EXPECT_TRUE(AtomMatchesChar(true, '.', '.'));
619 TEST(AtomMatchesCharTest, Escaped_d) {
620 EXPECT_FALSE(AtomMatchesChar(true, 'd', '\0'));
621 EXPECT_FALSE(AtomMatchesChar(true, 'd', 'a'));
622 EXPECT_FALSE(AtomMatchesChar(true, 'd', '.'));
624 EXPECT_TRUE(AtomMatchesChar(true, 'd', '0'));
625 EXPECT_TRUE(AtomMatchesChar(true, 'd', '9'));
628 TEST(AtomMatchesCharTest, Escaped_D) {
629 EXPECT_FALSE(AtomMatchesChar(true, 'D', '0'));
630 EXPECT_FALSE(AtomMatchesChar(true, 'D', '9'));
632 EXPECT_TRUE(AtomMatchesChar(true, 'D', '\0'));
633 EXPECT_TRUE(AtomMatchesChar(true, 'D', 'a'));
634 EXPECT_TRUE(AtomMatchesChar(true, 'D', '-'));
637 TEST(AtomMatchesCharTest, Escaped_s) {
638 EXPECT_FALSE(AtomMatchesChar(true, 's', '\0'));
639 EXPECT_FALSE(AtomMatchesChar(true, 's', 'a'));
640 EXPECT_FALSE(AtomMatchesChar(true, 's', '.'));
641 EXPECT_FALSE(AtomMatchesChar(true, 's', '9'));
643 EXPECT_TRUE(AtomMatchesChar(true, 's', ' '));
644 EXPECT_TRUE(AtomMatchesChar(true, 's', '\n'));
645 EXPECT_TRUE(AtomMatchesChar(true, 's', '\t'));
648 TEST(AtomMatchesCharTest, Escaped_S) {
649 EXPECT_FALSE(AtomMatchesChar(true, 'S', ' '));
650 EXPECT_FALSE(AtomMatchesChar(true, 'S', '\r'));
652 EXPECT_TRUE(AtomMatchesChar(true, 'S', '\0'));
653 EXPECT_TRUE(AtomMatchesChar(true, 'S', 'a'));
654 EXPECT_TRUE(AtomMatchesChar(true, 'S', '9'));
657 TEST(AtomMatchesCharTest, Escaped_w) {
658 EXPECT_FALSE(AtomMatchesChar(true, 'w', '\0'));
659 EXPECT_FALSE(AtomMatchesChar(true, 'w', '+'));
660 EXPECT_FALSE(AtomMatchesChar(true, 'w', ' '));
661 EXPECT_FALSE(AtomMatchesChar(true, 'w', '\n'));
663 EXPECT_TRUE(AtomMatchesChar(true, 'w', '0'));
664 EXPECT_TRUE(AtomMatchesChar(true, 'w', 'b'));
665 EXPECT_TRUE(AtomMatchesChar(true, 'w', 'C'));
666 EXPECT_TRUE(AtomMatchesChar(true, 'w', '_'));
669 TEST(AtomMatchesCharTest, Escaped_W) {
670 EXPECT_FALSE(AtomMatchesChar(true, 'W', 'A'));
671 EXPECT_FALSE(AtomMatchesChar(true, 'W', 'b'));
672 EXPECT_FALSE(AtomMatchesChar(true, 'W', '9'));
673 EXPECT_FALSE(AtomMatchesChar(true, 'W', '_'));
675 EXPECT_TRUE(AtomMatchesChar(true, 'W', '\0'));
676 EXPECT_TRUE(AtomMatchesChar(true, 'W', '*'));
677 EXPECT_TRUE(AtomMatchesChar(true, 'W', '\n'));
680 TEST(AtomMatchesCharTest, EscapedWhiteSpace) {
681 EXPECT_FALSE(AtomMatchesChar(true, 'f', '\0'));
682 EXPECT_FALSE(AtomMatchesChar(true, 'f', '\n'));
683 EXPECT_FALSE(AtomMatchesChar(true, 'n', '\0'));
684 EXPECT_FALSE(AtomMatchesChar(true, 'n', '\r'));
685 EXPECT_FALSE(AtomMatchesChar(true, 'r', '\0'));
686 EXPECT_FALSE(AtomMatchesChar(true, 'r', 'a'));
687 EXPECT_FALSE(AtomMatchesChar(true, 't', '\0'));
688 EXPECT_FALSE(AtomMatchesChar(true, 't', 't'));
689 EXPECT_FALSE(AtomMatchesChar(true, 'v', '\0'));
690 EXPECT_FALSE(AtomMatchesChar(true, 'v', '\f'));
692 EXPECT_TRUE(AtomMatchesChar(true, 'f', '\f'));
693 EXPECT_TRUE(AtomMatchesChar(true, 'n', '\n'));
694 EXPECT_TRUE(AtomMatchesChar(true, 'r', '\r'));
695 EXPECT_TRUE(AtomMatchesChar(true, 't', '\t'));
696 EXPECT_TRUE(AtomMatchesChar(true, 'v', '\v'));
699 TEST(AtomMatchesCharTest, UnescapedDot) {
700 EXPECT_FALSE(AtomMatchesChar(false, '.', '\n'));
702 EXPECT_TRUE(AtomMatchesChar(false, '.', '\0'));
703 EXPECT_TRUE(AtomMatchesChar(false, '.', '.'));
704 EXPECT_TRUE(AtomMatchesChar(false, '.', 'a'));
705 EXPECT_TRUE(AtomMatchesChar(false, '.', ' '));
708 TEST(AtomMatchesCharTest, UnescapedChar) {
709 EXPECT_FALSE(AtomMatchesChar(false, 'a', '\0'));
710 EXPECT_FALSE(AtomMatchesChar(false, 'a', 'b'));
711 EXPECT_FALSE(AtomMatchesChar(false, '$', 'a'));
713 EXPECT_TRUE(AtomMatchesChar(false, '$', '$'));
714 EXPECT_TRUE(AtomMatchesChar(false, '5', '5'));
715 EXPECT_TRUE(AtomMatchesChar(false, 'Z', 'Z'));
718 TEST(ValidateRegexTest, GeneratesFailureAndReturnsFalseForInvalid) {
719 EXPECT_NONFATAL_FAILURE(ASSERT_FALSE(ValidateRegex(NULL)),
720 "NULL is not a valid simple regular expression");
721 EXPECT_NONFATAL_FAILURE(
722 ASSERT_FALSE(ValidateRegex("a\\")),
723 "Syntax error at index 1 in simple regular expression \"a\\\": ");
724 EXPECT_NONFATAL_FAILURE(ASSERT_FALSE(ValidateRegex("a\\")),
725 "'\\' cannot appear at the end");
726 EXPECT_NONFATAL_FAILURE(ASSERT_FALSE(ValidateRegex("\\n\\")),
727 "'\\' cannot appear at the end");
728 EXPECT_NONFATAL_FAILURE(ASSERT_FALSE(ValidateRegex("\\s\\hb")),
729 "invalid escape sequence \"\\h\"");
730 EXPECT_NONFATAL_FAILURE(ASSERT_FALSE(ValidateRegex("^^")),
731 "'^' can only appear at the beginning");
732 EXPECT_NONFATAL_FAILURE(ASSERT_FALSE(ValidateRegex(".*^b")),
733 "'^' can only appear at the beginning");
734 EXPECT_NONFATAL_FAILURE(ASSERT_FALSE(ValidateRegex("$$")),
735 "'$' can only appear at the end");
736 EXPECT_NONFATAL_FAILURE(ASSERT_FALSE(ValidateRegex("^$a")),
737 "'$' can only appear at the end");
738 EXPECT_NONFATAL_FAILURE(ASSERT_FALSE(ValidateRegex("a(b")),
739 "'(' is unsupported");
740 EXPECT_NONFATAL_FAILURE(ASSERT_FALSE(ValidateRegex("ab)")),
741 "')' is unsupported");
742 EXPECT_NONFATAL_FAILURE(ASSERT_FALSE(ValidateRegex("[ab")),
743 "'[' is unsupported");
744 EXPECT_NONFATAL_FAILURE(ASSERT_FALSE(ValidateRegex("a{2")),
745 "'{' is unsupported");
746 EXPECT_NONFATAL_FAILURE(ASSERT_FALSE(ValidateRegex("?")),
747 "'?' can only follow a repeatable token");
748 EXPECT_NONFATAL_FAILURE(ASSERT_FALSE(ValidateRegex("^*")),
749 "'*' can only follow a repeatable token");
750 EXPECT_NONFATAL_FAILURE(ASSERT_FALSE(ValidateRegex("5*+")),
751 "'+' can only follow a repeatable token");
754 TEST(ValidateRegexTest, ReturnsTrueForValid) {
755 EXPECT_TRUE(ValidateRegex(""));
756 EXPECT_TRUE(ValidateRegex("a"));
757 EXPECT_TRUE(ValidateRegex(".*"));
758 EXPECT_TRUE(ValidateRegex("^a_+"));
759 EXPECT_TRUE(ValidateRegex("^a\\t\\&?"));
760 EXPECT_TRUE(ValidateRegex("09*$"));
761 EXPECT_TRUE(ValidateRegex("^Z$"));
762 EXPECT_TRUE(ValidateRegex("a\\^Z\\$\\(\\)\\|\\[\\]\\{\\}"));
765 TEST(MatchRepetitionAndRegexAtHeadTest, WorksForZeroOrOne) {
766 EXPECT_FALSE(MatchRepetitionAndRegexAtHead(false, 'a', '?', "a", "ba"));
767 // Repeating more than once.
768 EXPECT_FALSE(MatchRepetitionAndRegexAtHead(false, 'a', '?', "b", "aab"));
770 // Repeating zero times.
771 EXPECT_TRUE(MatchRepetitionAndRegexAtHead(false, 'a', '?', "b", "ba"));
773 EXPECT_TRUE(MatchRepetitionAndRegexAtHead(false, 'a', '?', "b", "ab"));
774 EXPECT_TRUE(MatchRepetitionAndRegexAtHead(false, '#', '?', ".", "##"));
777 TEST(MatchRepetitionAndRegexAtHeadTest, WorksForZeroOrMany) {
778 EXPECT_FALSE(MatchRepetitionAndRegexAtHead(false, '.', '*', "a$", "baab"));
780 // Repeating zero times.
781 EXPECT_TRUE(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(MatchRepetitionAndRegexAtHeadTest, WorksForOneOrMany) {
789 EXPECT_FALSE(MatchRepetitionAndRegexAtHead(false, '.', '+', "a$", "baab"));
790 // Repeating zero times.
791 EXPECT_FALSE(MatchRepetitionAndRegexAtHead(false, '.', '+', "b", "bc"));
794 EXPECT_TRUE(MatchRepetitionAndRegexAtHead(false, '.', '+', "b", "abc"));
795 // Repeating more than once.
796 EXPECT_TRUE(MatchRepetitionAndRegexAtHead(true, 'w', '+', "-", "ab_1-g"));
799 TEST(MatchRegexAtHeadTest, ReturnsTrueForEmptyRegex) {
800 EXPECT_TRUE(MatchRegexAtHead("", ""));
801 EXPECT_TRUE(MatchRegexAtHead("", "ab"));
804 TEST(MatchRegexAtHeadTest, WorksWhenDollarIsInRegex) {
805 EXPECT_FALSE(MatchRegexAtHead("$", "a"));
807 EXPECT_TRUE(MatchRegexAtHead("$", ""));
808 EXPECT_TRUE(MatchRegexAtHead("a$", "a"));
811 TEST(MatchRegexAtHeadTest, WorksWhenRegexStartsWithEscapeSequence) {
812 EXPECT_FALSE(MatchRegexAtHead("\\w", "+"));
813 EXPECT_FALSE(MatchRegexAtHead("\\W", "ab"));
815 EXPECT_TRUE(MatchRegexAtHead("\\sa", "\nab"));
816 EXPECT_TRUE(MatchRegexAtHead("\\d", "1a"));
819 TEST(MatchRegexAtHeadTest, WorksWhenRegexStartsWithRepetition) {
820 EXPECT_FALSE(MatchRegexAtHead(".+a", "abc"));
821 EXPECT_FALSE(MatchRegexAtHead("a?b", "aab"));
823 EXPECT_TRUE(MatchRegexAtHead(".*a", "bc12-ab"));
824 EXPECT_TRUE(MatchRegexAtHead("a?b", "b"));
825 EXPECT_TRUE(MatchRegexAtHead("a?b", "ab"));
828 TEST(MatchRegexAtHeadTest,
829 WorksWhenRegexStartsWithRepetionOfEscapeSequence) {
830 EXPECT_FALSE(MatchRegexAtHead("\\.+a", "abc"));
831 EXPECT_FALSE(MatchRegexAtHead("\\s?b", " b"));
833 EXPECT_TRUE(MatchRegexAtHead("\\(*a", "((((ab"));
834 EXPECT_TRUE(MatchRegexAtHead("\\^?b", "^b"));
835 EXPECT_TRUE(MatchRegexAtHead("\\\\?b", "b"));
836 EXPECT_TRUE(MatchRegexAtHead("\\\\?b", "\\b"));
839 TEST(MatchRegexAtHeadTest, MatchesSequentially) {
840 EXPECT_FALSE(MatchRegexAtHead("ab.*c", "acabc"));
842 EXPECT_TRUE(MatchRegexAtHead("ab.*c", "ab-fsc"));
845 TEST(MatchRegexAnywhereTest, ReturnsFalseWhenStringIsNull) {
846 EXPECT_FALSE(MatchRegexAnywhere("", NULL));
849 TEST(MatchRegexAnywhereTest, WorksWhenRegexStartsWithCaret) {
850 EXPECT_FALSE(MatchRegexAnywhere("^a", "ba"));
851 EXPECT_FALSE(MatchRegexAnywhere("^$", "a"));
853 EXPECT_TRUE(MatchRegexAnywhere("^a", "ab"));
854 EXPECT_TRUE(MatchRegexAnywhere("^", "ab"));
855 EXPECT_TRUE(MatchRegexAnywhere("^$", ""));
858 TEST(MatchRegexAnywhereTest, ReturnsFalseWhenNoMatch) {
859 EXPECT_FALSE(MatchRegexAnywhere("a", "bcde123"));
860 EXPECT_FALSE(MatchRegexAnywhere("a.+a", "--aa88888888"));
863 TEST(MatchRegexAnywhereTest, ReturnsTrueWhenMatchingPrefix) {
864 EXPECT_TRUE(MatchRegexAnywhere("\\w+", "ab1_ - 5"));
865 EXPECT_TRUE(MatchRegexAnywhere(".*=", "="));
866 EXPECT_TRUE(MatchRegexAnywhere("x.*ab?.*bc", "xaaabc"));
869 TEST(MatchRegexAnywhereTest, ReturnsTrueWhenMatchingNonPrefix) {
870 EXPECT_TRUE(MatchRegexAnywhere("\\w+", "$$$ ab1_ - 5"));
871 EXPECT_TRUE(MatchRegexAnywhere("\\.+=", "= ...="));
874 // Tests RE's implicit constructors.
875 TEST(RETest, ImplicitConstructorWorks) {
877 EXPECT_STREQ("", empty.pattern());
879 const RE simple("hello");
880 EXPECT_STREQ("hello", simple.pattern());
883 // Tests that RE's constructors reject invalid regular expressions.
884 TEST(RETest, RejectsInvalidRegex) {
885 EXPECT_NONFATAL_FAILURE({
886 const RE normal(NULL);
887 }, "NULL is not a valid simple regular expression");
889 EXPECT_NONFATAL_FAILURE({
890 const RE normal(".*(\\w+");
891 }, "'(' is unsupported");
893 EXPECT_NONFATAL_FAILURE({
894 const RE invalid("^?");
895 }, "'?' can only follow a repeatable token");
898 // Tests RE::FullMatch().
899 TEST(RETest, FullMatchWorks) {
901 EXPECT_TRUE(RE::FullMatch("", empty));
902 EXPECT_FALSE(RE::FullMatch("a", empty));
905 EXPECT_TRUE(RE::FullMatch("a", re1));
908 EXPECT_TRUE(RE::FullMatch("az", re));
909 EXPECT_TRUE(RE::FullMatch("axyz", re));
910 EXPECT_FALSE(RE::FullMatch("baz", re));
911 EXPECT_FALSE(RE::FullMatch("azy", re));
914 // Tests RE::PartialMatch().
915 TEST(RETest, PartialMatchWorks) {
917 EXPECT_TRUE(RE::PartialMatch("", empty));
918 EXPECT_TRUE(RE::PartialMatch("a", empty));
921 EXPECT_TRUE(RE::PartialMatch("az", re));
922 EXPECT_TRUE(RE::PartialMatch("axyz", re));
923 EXPECT_TRUE(RE::PartialMatch("baz", re));
924 EXPECT_TRUE(RE::PartialMatch("azy", re));
925 EXPECT_FALSE(RE::PartialMatch("zza", re));
928 #endif // GTEST_USES_POSIX_RE
930 #if !GTEST_OS_WINDOWS_MOBILE
932 TEST(CaptureTest, CapturesStdout) {
934 fprintf(stdout, "abc");
935 EXPECT_STREQ("abc", GetCapturedStdout().c_str());
938 fprintf(stdout, "def%cghi", '\0');
939 EXPECT_EQ(::std::string("def\0ghi", 7), ::std::string(GetCapturedStdout()));
942 TEST(CaptureTest, CapturesStderr) {
944 fprintf(stderr, "jkl");
945 EXPECT_STREQ("jkl", GetCapturedStderr().c_str());
948 fprintf(stderr, "jkl%cmno", '\0');
949 EXPECT_EQ(::std::string("jkl\0mno", 7), ::std::string(GetCapturedStderr()));
952 // Tests that stdout and stderr capture don't interfere with each other.
953 TEST(CaptureTest, CapturesStdoutAndStderr) {
956 fprintf(stdout, "pqr");
957 fprintf(stderr, "stu");
958 EXPECT_STREQ("pqr", GetCapturedStdout().c_str());
959 EXPECT_STREQ("stu", GetCapturedStderr().c_str());
962 TEST(CaptureDeathTest, CannotReenterStdoutCapture) {
964 EXPECT_DEATH_IF_SUPPORTED(CaptureStdout(),
965 "Only one stdout capturer can exist at a time");
968 // We cannot test stderr capturing using death tests as they use it
972 #endif // !GTEST_OS_WINDOWS_MOBILE
974 TEST(ThreadLocalTest, DefaultConstructorInitializesToDefaultValues) {
976 EXPECT_EQ(0, t1.get());
978 ThreadLocal<void*> t2;
979 EXPECT_TRUE(t2.get() == NULL);
982 TEST(ThreadLocalTest, SingleParamConstructorInitializesToParam) {
983 ThreadLocal<int> t1(123);
984 EXPECT_EQ(123, t1.get());
987 ThreadLocal<int*> t2(&i);
988 EXPECT_EQ(&i, t2.get());
991 class NoDefaultContructor {
993 explicit NoDefaultContructor(const char*) {}
994 NoDefaultContructor(const NoDefaultContructor&) {}
997 TEST(ThreadLocalTest, ValueDefaultContructorIsNotRequiredForParamVersion) {
998 ThreadLocal<NoDefaultContructor> bar(NoDefaultContructor("foo"));
1002 TEST(ThreadLocalTest, GetAndPointerReturnSameValue) {
1003 ThreadLocal<std::string> thread_local_string;
1005 EXPECT_EQ(thread_local_string.pointer(), &(thread_local_string.get()));
1007 // Verifies the condition still holds after calling set.
1008 thread_local_string.set("foo");
1009 EXPECT_EQ(thread_local_string.pointer(), &(thread_local_string.get()));
1012 TEST(ThreadLocalTest, PointerAndConstPointerReturnSameValue) {
1013 ThreadLocal<std::string> thread_local_string;
1014 const ThreadLocal<std::string>& const_thread_local_string =
1015 thread_local_string;
1017 EXPECT_EQ(thread_local_string.pointer(), const_thread_local_string.pointer());
1019 thread_local_string.set("foo");
1020 EXPECT_EQ(thread_local_string.pointer(), const_thread_local_string.pointer());
1023 #if GTEST_IS_THREADSAFE
1025 void AddTwo(int* param) { *param += 2; }
1027 TEST(ThreadWithParamTest, ConstructorExecutesThreadFunc) {
1029 ThreadWithParam<int*> thread(&AddTwo, &i, NULL);
1034 TEST(MutexDeathTest, AssertHeldShouldAssertWhenNotLocked) {
1035 // AssertHeld() is flaky only in the presence of multiple threads accessing
1036 // the lock. In this case, the test is robust.
1037 EXPECT_DEATH_IF_SUPPORTED({
1039 { MutexLock lock(&m); }
1045 TEST(MutexTest, AssertHeldShouldNotAssertWhenLocked) {
1051 class AtomicCounterWithMutex {
1053 explicit AtomicCounterWithMutex(Mutex* mutex) :
1054 value_(0), mutex_(mutex), random_(42) {}
1057 MutexLock lock(mutex_);
1060 // We need to put up a memory barrier to prevent reads and writes to
1061 // value_ rearranged with the call to SleepMilliseconds when observed
1062 // from other threads.
1063 #if GTEST_HAS_PTHREAD
1064 // On POSIX, locking a mutex puts up a memory barrier. We cannot use
1065 // Mutex and MutexLock here or rely on their memory barrier
1066 // functionality as we are testing them here.
1067 pthread_mutex_t memory_barrier_mutex;
1068 GTEST_CHECK_POSIX_SUCCESS_(
1069 pthread_mutex_init(&memory_barrier_mutex, NULL));
1070 GTEST_CHECK_POSIX_SUCCESS_(pthread_mutex_lock(&memory_barrier_mutex));
1072 SleepMilliseconds(random_.Generate(30));
1074 GTEST_CHECK_POSIX_SUCCESS_(pthread_mutex_unlock(&memory_barrier_mutex));
1075 GTEST_CHECK_POSIX_SUCCESS_(pthread_mutex_destroy(&memory_barrier_mutex));
1076 #elif GTEST_OS_WINDOWS
1077 // On Windows, performing an interlocked access puts up a memory barrier.
1078 volatile LONG dummy = 0;
1079 ::InterlockedIncrement(&dummy);
1080 SleepMilliseconds(random_.Generate(30));
1081 ::InterlockedIncrement(&dummy);
1083 # error "Memory barrier not implemented on this platform."
1084 #endif // GTEST_HAS_PTHREAD
1088 int value() const { return value_; }
1091 volatile int value_;
1092 Mutex* const mutex_; // Protects value_.
1096 void CountingThreadFunc(pair<AtomicCounterWithMutex*, int> param) {
1097 for (int i = 0; i < param.second; ++i)
1098 param.first->Increment();
1101 // Tests that the mutex only lets one thread at a time to lock it.
1102 TEST(MutexTest, OnlyOneThreadCanLockAtATime) {
1104 AtomicCounterWithMutex locked_counter(&mutex);
1106 typedef ThreadWithParam<pair<AtomicCounterWithMutex*, int> > ThreadType;
1107 const int kCycleCount = 20;
1108 const int kThreadCount = 7;
1109 scoped_ptr<ThreadType> counting_threads[kThreadCount];
1110 Notification threads_can_start;
1111 // Creates and runs kThreadCount threads that increment locked_counter
1112 // kCycleCount times each.
1113 for (int i = 0; i < kThreadCount; ++i) {
1114 counting_threads[i].reset(new ThreadType(&CountingThreadFunc,
1115 make_pair(&locked_counter,
1117 &threads_can_start));
1119 threads_can_start.Notify();
1120 for (int i = 0; i < kThreadCount; ++i)
1121 counting_threads[i]->Join();
1123 // If the mutex lets more than one thread to increment the counter at a
1124 // time, they are likely to encounter a race condition and have some
1125 // increments overwritten, resulting in the lower then expected counter
1127 EXPECT_EQ(kCycleCount * kThreadCount, locked_counter.value());
1130 template <typename T>
1131 void RunFromThread(void (func)(T), T param) {
1132 ThreadWithParam<T> thread(func, param, NULL);
1136 void RetrieveThreadLocalValue(
1137 pair<ThreadLocal<std::string>*, std::string*> param) {
1138 *param.second = param.first->get();
1141 TEST(ThreadLocalTest, ParameterizedConstructorSetsDefault) {
1142 ThreadLocal<std::string> thread_local_string("foo");
1143 EXPECT_STREQ("foo", thread_local_string.get().c_str());
1145 thread_local_string.set("bar");
1146 EXPECT_STREQ("bar", thread_local_string.get().c_str());
1149 RunFromThread(&RetrieveThreadLocalValue,
1150 make_pair(&thread_local_string, &result));
1151 EXPECT_STREQ("foo", result.c_str());
1154 // Keeps track of whether of destructors being called on instances of
1155 // DestructorTracker. On Windows, waits for the destructor call reports.
1156 class DestructorCall {
1160 #if GTEST_OS_WINDOWS
1161 wait_event_.Reset(::CreateEvent(NULL, TRUE, FALSE, NULL));
1162 GTEST_CHECK_(wait_event_.Get() != NULL);
1166 bool CheckDestroyed() const {
1167 #if GTEST_OS_WINDOWS
1168 if (::WaitForSingleObject(wait_event_.Get(), 1000) != WAIT_OBJECT_0)
1174 void ReportDestroyed() {
1176 #if GTEST_OS_WINDOWS
1177 ::SetEvent(wait_event_.Get());
1181 static std::vector<DestructorCall*>& List() { return *list_; }
1183 static void ResetList() {
1184 for (size_t i = 0; i < list_->size(); ++i) {
1185 delete list_->at(i);
1192 #if GTEST_OS_WINDOWS
1193 AutoHandle wait_event_;
1195 static std::vector<DestructorCall*>* const list_;
1197 GTEST_DISALLOW_COPY_AND_ASSIGN_(DestructorCall);
1200 std::vector<DestructorCall*>* const DestructorCall::list_ =
1201 new std::vector<DestructorCall*>;
1203 // DestructorTracker keeps track of whether its instances have been
1205 class DestructorTracker {
1207 DestructorTracker() : index_(GetNewIndex()) {}
1208 DestructorTracker(const DestructorTracker& /* rhs */)
1209 : index_(GetNewIndex()) {}
1210 ~DestructorTracker() {
1211 // We never access DestructorCall::List() concurrently, so we don't need
1212 // to protect this acccess with a mutex.
1213 DestructorCall::List()[index_]->ReportDestroyed();
1217 static size_t GetNewIndex() {
1218 DestructorCall::List().push_back(new DestructorCall);
1219 return DestructorCall::List().size() - 1;
1221 const size_t index_;
1223 GTEST_DISALLOW_ASSIGN_(DestructorTracker);
1226 typedef ThreadLocal<DestructorTracker>* ThreadParam;
1228 void CallThreadLocalGet(ThreadParam thread_local_param) {
1229 thread_local_param->get();
1232 // Tests that when a ThreadLocal object dies in a thread, it destroys
1233 // the managed object for that thread.
1234 TEST(ThreadLocalTest, DestroysManagedObjectForOwnThreadWhenDying) {
1235 DestructorCall::ResetList();
1238 ThreadLocal<DestructorTracker> thread_local_tracker;
1239 ASSERT_EQ(0U, DestructorCall::List().size());
1241 // This creates another DestructorTracker object for the main thread.
1242 thread_local_tracker.get();
1243 ASSERT_EQ(1U, DestructorCall::List().size());
1244 ASSERT_FALSE(DestructorCall::List()[0]->CheckDestroyed());
1247 // Now thread_local_tracker has died.
1248 ASSERT_EQ(1U, DestructorCall::List().size());
1249 EXPECT_TRUE(DestructorCall::List()[0]->CheckDestroyed());
1251 DestructorCall::ResetList();
1254 // Tests that when a thread exits, the thread-local object for that
1255 // thread is destroyed.
1256 TEST(ThreadLocalTest, DestroysManagedObjectAtThreadExit) {
1257 DestructorCall::ResetList();
1260 ThreadLocal<DestructorTracker> thread_local_tracker;
1261 ASSERT_EQ(0U, DestructorCall::List().size());
1263 // This creates another DestructorTracker object in the new thread.
1264 ThreadWithParam<ThreadParam> thread(
1265 &CallThreadLocalGet, &thread_local_tracker, NULL);
1268 // The thread has exited, and we should have a DestroyedTracker
1269 // instance created for it. But it may not have been destroyed yet.
1270 ASSERT_EQ(1U, DestructorCall::List().size());
1273 // The thread has exited and thread_local_tracker has died.
1274 ASSERT_EQ(1U, DestructorCall::List().size());
1275 EXPECT_TRUE(DestructorCall::List()[0]->CheckDestroyed());
1277 DestructorCall::ResetList();
1280 TEST(ThreadLocalTest, ThreadLocalMutationsAffectOnlyCurrentThread) {
1281 ThreadLocal<std::string> thread_local_string;
1282 thread_local_string.set("Foo");
1283 EXPECT_STREQ("Foo", thread_local_string.get().c_str());
1286 RunFromThread(&RetrieveThreadLocalValue,
1287 make_pair(&thread_local_string, &result));
1288 EXPECT_TRUE(result.empty());
1291 #endif // GTEST_IS_THREADSAFE
1293 #if GTEST_OS_WINDOWS
1294 TEST(WindowsTypesTest, HANDLEIsVoidStar) {
1295 StaticAssertTypeEq<HANDLE, void*>();
1298 TEST(WindowsTypesTest, CRITICAL_SECTIONIs_RTL_CRITICAL_SECTION) {
1299 StaticAssertTypeEq<CRITICAL_SECTION, _RTL_CRITICAL_SECTION>();
1301 #endif // GTEST_OS_WINDOWS
1303 } // namespace internal
1304 } // namespace testing