Home | History | Annotate | Download | only in test
      1 // Copyright 2008, Google Inc.
      2 // All rights reserved.
      3 //
      4 // Redistribution and use in source and binary forms, with or without
      5 // modification, are permitted provided that the following conditions are
      6 // met:
      7 //
      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
     13 // distribution.
     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.
     17 //
     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.
     29 //
     30 // Authors: vladl (at) google.com (Vlad Losev), wan (at) google.com (Zhanyong Wan)
     31 //
     32 // This file tests the internal cross-platform support utilities.
     33 
     34 #include "gtest/internal/gtest-port.h"
     35 
     36 #include <stdio.h>
     37 
     38 #if GTEST_OS_MAC
     39 # include <time.h>
     40 #endif  // GTEST_OS_MAC
     41 
     42 #include <list>
     43 #include <utility>  // For std::pair and std::make_pair.
     44 #include <vector>
     45 
     46 #include "gtest/gtest.h"
     47 #include "gtest/gtest-spi.h"
     48 
     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
     53 // his code.
     54 #define GTEST_IMPLEMENTATION_ 1
     55 #include "src/gtest-internal-inl.h"
     56 #undef GTEST_IMPLEMENTATION_
     57 
     58 using std::make_pair;
     59 using std::pair;
     60 
     61 namespace testing {
     62 namespace internal {
     63 
     64 class Base {
     65  public:
     66   // Copy constructor and assignment operator do exactly what we need, so we
     67   // use them.
     68   Base() : member_(0) {}
     69   explicit Base(int n) : member_(n) {}
     70   virtual ~Base() {}
     71   int member() { return member_; }
     72 
     73  private:
     74   int member_;
     75 };
     76 
     77 class Derived : public Base {
     78  public:
     79   explicit Derived(int n) : Base(n) {}
     80 };
     81 
     82 TEST(ImplicitCastTest, ConvertsPointers) {
     83   Derived derived(0);
     84   EXPECT_TRUE(&derived == ::testing::internal::ImplicitCast_<Base*>(&derived));
     85 }
     86 
     87 TEST(ImplicitCastTest, CanUseInheritance) {
     88   Derived derived(1);
     89   Base base = ::testing::internal::ImplicitCast_<Base>(derived);
     90   EXPECT_EQ(derived.member(), base.member());
     91 }
     92 
     93 class Castable {
     94  public:
     95   explicit Castable(bool* converted) : converted_(converted) {}
     96   operator Base() {
     97     *converted_ = true;
     98     return Base();
     99   }
    100 
    101  private:
    102   bool* converted_;
    103 };
    104 
    105 TEST(ImplicitCastTest, CanUseNonConstCastOperator) {
    106   bool converted = false;
    107   Castable castable(&converted);
    108   Base base = ::testing::internal::ImplicitCast_<Base>(castable);
    109   EXPECT_TRUE(converted);
    110 }
    111 
    112 class ConstCastable {
    113  public:
    114   explicit ConstCastable(bool* converted) : converted_(converted) {}
    115   operator Base() const {
    116     *converted_ = true;
    117     return Base();
    118   }
    119 
    120  private:
    121   bool* converted_;
    122 };
    123 
    124 TEST(ImplicitCastTest, CanUseConstCastOperatorOnConstValues) {
    125   bool converted = false;
    126   const ConstCastable const_castable(&converted);
    127   Base base = ::testing::internal::ImplicitCast_<Base>(const_castable);
    128   EXPECT_TRUE(converted);
    129 }
    130 
    131 class ConstAndNonConstCastable {
    132  public:
    133   ConstAndNonConstCastable(bool* converted, bool* const_converted)
    134       : converted_(converted), const_converted_(const_converted) {}
    135   operator Base() {
    136     *converted_ = true;
    137     return Base();
    138   }
    139   operator Base() const {
    140     *const_converted_ = true;
    141     return Base();
    142   }
    143 
    144  private:
    145   bool* converted_;
    146   bool* const_converted_;
    147 };
    148 
    149 TEST(ImplicitCastTest, CanSelectBetweenConstAndNonConstCasrAppropriately) {
    150   bool converted = false;
    151   bool const_converted = false;
    152   ConstAndNonConstCastable castable(&converted, &const_converted);
    153   Base base = ::testing::internal::ImplicitCast_<Base>(castable);
    154   EXPECT_TRUE(converted);
    155   EXPECT_FALSE(const_converted);
    156 
    157   converted = false;
    158   const_converted = false;
    159   const ConstAndNonConstCastable const_castable(&converted, &const_converted);
    160   base = ::testing::internal::ImplicitCast_<Base>(const_castable);
    161   EXPECT_FALSE(converted);
    162   EXPECT_TRUE(const_converted);
    163 }
    164 
    165 class To {
    166  public:
    167   To(bool* converted) { *converted = true; }  // NOLINT
    168 };
    169 
    170 TEST(ImplicitCastTest, CanUseImplicitConstructor) {
    171   bool converted = false;
    172   To to = ::testing::internal::ImplicitCast_<To>(&converted);
    173   (void)to;
    174   EXPECT_TRUE(converted);
    175 }
    176 
    177 TEST(IteratorTraitsTest, WorksForSTLContainerIterators) {
    178   StaticAssertTypeEq<int,
    179       IteratorTraits< ::std::vector<int>::const_iterator>::value_type>();
    180   StaticAssertTypeEq<bool,
    181       IteratorTraits< ::std::list<bool>::iterator>::value_type>();
    182 }
    183 
    184 TEST(IteratorTraitsTest, WorksForPointerToNonConst) {
    185   StaticAssertTypeEq<char, IteratorTraits<char*>::value_type>();
    186   StaticAssertTypeEq<const void*, IteratorTraits<const void**>::value_type>();
    187 }
    188 
    189 TEST(IteratorTraitsTest, WorksForPointerToConst) {
    190   StaticAssertTypeEq<char, IteratorTraits<const char*>::value_type>();
    191   StaticAssertTypeEq<const void*,
    192       IteratorTraits<const void* const*>::value_type>();
    193 }
    194 
    195 // Tests that the element_type typedef is available in scoped_ptr and refers
    196 // to the parameter type.
    197 TEST(ScopedPtrTest, DefinesElementType) {
    198   StaticAssertTypeEq<int, ::testing::internal::scoped_ptr<int>::element_type>();
    199 }
    200 
    201 // TODO(vladl (at) google.com): Implement THE REST of scoped_ptr tests.
    202 
    203 TEST(GtestCheckSyntaxTest, BehavesLikeASingleStatement) {
    204   if (AlwaysFalse())
    205     GTEST_CHECK_(false) << "This should never be executed; "
    206                            "It's a compilation test only.";
    207 
    208   if (AlwaysTrue())
    209     GTEST_CHECK_(true);
    210   else
    211     ;  // NOLINT
    212 
    213   if (AlwaysFalse())
    214     ;  // NOLINT
    215   else
    216     GTEST_CHECK_(true) << "";
    217 }
    218 
    219 TEST(GtestCheckSyntaxTest, WorksWithSwitch) {
    220   switch (0) {
    221     case 1:
    222       break;
    223     default:
    224       GTEST_CHECK_(true);
    225   }
    226 
    227   switch (0)
    228     case 0:
    229       GTEST_CHECK_(true) << "Check failed in switch case";
    230 }
    231 
    232 // Verifies behavior of FormatFileLocation.
    233 TEST(FormatFileLocationTest, FormatsFileLocation) {
    234   EXPECT_PRED_FORMAT2(IsSubstring, "foo.cc", FormatFileLocation("foo.cc", 42));
    235   EXPECT_PRED_FORMAT2(IsSubstring, "42", FormatFileLocation("foo.cc", 42));
    236 }
    237 
    238 TEST(FormatFileLocationTest, FormatsUnknownFile) {
    239   EXPECT_PRED_FORMAT2(
    240       IsSubstring, "unknown file", FormatFileLocation(NULL, 42));
    241   EXPECT_PRED_FORMAT2(IsSubstring, "42", FormatFileLocation(NULL, 42));
    242 }
    243 
    244 TEST(FormatFileLocationTest, FormatsUknownLine) {
    245   EXPECT_EQ("foo.cc:", FormatFileLocation("foo.cc", -1));
    246 }
    247 
    248 TEST(FormatFileLocationTest, FormatsUknownFileAndLine) {
    249   EXPECT_EQ("unknown file:", FormatFileLocation(NULL, -1));
    250 }
    251 
    252 // Verifies behavior of FormatCompilerIndependentFileLocation.
    253 TEST(FormatCompilerIndependentFileLocationTest, FormatsFileLocation) {
    254   EXPECT_EQ("foo.cc:42", FormatCompilerIndependentFileLocation("foo.cc", 42));
    255 }
    256 
    257 TEST(FormatCompilerIndependentFileLocationTest, FormatsUknownFile) {
    258   EXPECT_EQ("unknown file:42",
    259             FormatCompilerIndependentFileLocation(NULL, 42));
    260 }
    261 
    262 TEST(FormatCompilerIndependentFileLocationTest, FormatsUknownLine) {
    263   EXPECT_EQ("foo.cc", FormatCompilerIndependentFileLocation("foo.cc", -1));
    264 }
    265 
    266 TEST(FormatCompilerIndependentFileLocationTest, FormatsUknownFileAndLine) {
    267   EXPECT_EQ("unknown file", FormatCompilerIndependentFileLocation(NULL, -1));
    268 }
    269 
    270 #if GTEST_OS_MAC || GTEST_OS_QNX
    271 void* ThreadFunc(void* data) {
    272   pthread_mutex_t* mutex = static_cast<pthread_mutex_t*>(data);
    273   pthread_mutex_lock(mutex);
    274   pthread_mutex_unlock(mutex);
    275   return NULL;
    276 }
    277 
    278 TEST(GetThreadCountTest, ReturnsCorrectValue) {
    279   EXPECT_EQ(1U, GetThreadCount());
    280   pthread_mutex_t mutex;
    281   pthread_attr_t  attr;
    282   pthread_t       thread_id;
    283 
    284   // TODO(vladl (at) google.com): turn mutex into internal::Mutex for automatic
    285   // destruction.
    286   pthread_mutex_init(&mutex, NULL);
    287   pthread_mutex_lock(&mutex);
    288   ASSERT_EQ(0, pthread_attr_init(&attr));
    289   ASSERT_EQ(0, pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_JOINABLE));
    290 
    291   const int status = pthread_create(&thread_id, &attr, &ThreadFunc, &mutex);
    292   ASSERT_EQ(0, pthread_attr_destroy(&attr));
    293   ASSERT_EQ(0, status);
    294   EXPECT_EQ(2U, GetThreadCount());
    295   pthread_mutex_unlock(&mutex);
    296 
    297   void* dummy;
    298   ASSERT_EQ(0, pthread_join(thread_id, &dummy));
    299 
    300 # if GTEST_OS_MAC
    301 
    302   // MacOS X may not immediately report the updated thread count after
    303   // joining a thread, causing flakiness in this test. To counter that, we
    304   // wait for up to .5 seconds for the OS to report the correct value.
    305   for (int i = 0; i < 5; ++i) {
    306     if (GetThreadCount() == 1)
    307       break;
    308 
    309     SleepMilliseconds(100);
    310   }
    311 
    312 # endif  // GTEST_OS_MAC
    313 
    314   EXPECT_EQ(1U, GetThreadCount());
    315   pthread_mutex_destroy(&mutex);
    316 }
    317 #else
    318 TEST(GetThreadCountTest, ReturnsZeroWhenUnableToCountThreads) {
    319   EXPECT_EQ(0U, GetThreadCount());
    320 }
    321 #endif  // GTEST_OS_MAC || GTEST_OS_QNX
    322 
    323 TEST(GtestCheckDeathTest, DiesWithCorrectOutputOnFailure) {
    324   const bool a_false_condition = false;
    325   const char regex[] =
    326 #ifdef _MSC_VER
    327      "gtest-port_test\\.cc\\(\\d+\\):"
    328 #elif GTEST_USES_POSIX_RE
    329      "gtest-port_test\\.cc:[0-9]+"
    330 #else
    331      "gtest-port_test\\.cc:\\d+"
    332 #endif  // _MSC_VER
    333      ".*a_false_condition.*Extra info.*";
    334 
    335   EXPECT_DEATH_IF_SUPPORTED(GTEST_CHECK_(a_false_condition) << "Extra info",
    336                             regex);
    337 }
    338 
    339 #if GTEST_HAS_DEATH_TEST
    340 
    341 TEST(GtestCheckDeathTest, LivesSilentlyOnSuccess) {
    342   EXPECT_EXIT({
    343       GTEST_CHECK_(true) << "Extra info";
    344       ::std::cerr << "Success\n";
    345       exit(0); },
    346       ::testing::ExitedWithCode(0), "Success");
    347 }
    348 
    349 #endif  // GTEST_HAS_DEATH_TEST
    350 
    351 // Verifies that Google Test choose regular expression engine appropriate to
    352 // the platform. The test will produce compiler errors in case of failure.
    353 // For simplicity, we only cover the most important platforms here.
    354 TEST(RegexEngineSelectionTest, SelectsCorrectRegexEngine) {
    355 #if GTEST_HAS_POSIX_RE
    356 
    357   EXPECT_TRUE(GTEST_USES_POSIX_RE);
    358 
    359 #else
    360 
    361   EXPECT_TRUE(GTEST_USES_SIMPLE_RE);
    362 
    363 #endif
    364 }
    365 
    366 #if GTEST_USES_POSIX_RE
    367 
    368 # if GTEST_HAS_TYPED_TEST
    369 
    370 template <typename Str>
    371 class RETest : public ::testing::Test {};
    372 
    373 // Defines StringTypes as the list of all string types that class RE
    374 // supports.
    375 typedef testing::Types<
    376     ::std::string,
    377 #  if GTEST_HAS_GLOBAL_STRING
    378     ::string,
    379 #  endif  // GTEST_HAS_GLOBAL_STRING
    380     const char*> StringTypes;
    381 
    382 TYPED_TEST_CASE(RETest, StringTypes);
    383 
    384 // Tests RE's implicit constructors.
    385 TYPED_TEST(RETest, ImplicitConstructorWorks) {
    386   const RE empty(TypeParam(""));
    387   EXPECT_STREQ("", empty.pattern());
    388 
    389   const RE simple(TypeParam("hello"));
    390   EXPECT_STREQ("hello", simple.pattern());
    391 
    392   const RE normal(TypeParam(".*(\\w+)"));
    393   EXPECT_STREQ(".*(\\w+)", normal.pattern());
    394 }
    395 
    396 // Tests that RE's constructors reject invalid regular expressions.
    397 TYPED_TEST(RETest, RejectsInvalidRegex) {
    398   EXPECT_NONFATAL_FAILURE({
    399     const RE invalid(TypeParam("?"));
    400   }, "\"?\" is not a valid POSIX Extended regular expression.");
    401 }
    402 
    403 // Tests RE::FullMatch().
    404 TYPED_TEST(RETest, FullMatchWorks) {
    405   const RE empty(TypeParam(""));
    406   EXPECT_TRUE(RE::FullMatch(TypeParam(""), empty));
    407   EXPECT_FALSE(RE::FullMatch(TypeParam("a"), empty));
    408 
    409   const RE re(TypeParam("a.*z"));
    410   EXPECT_TRUE(RE::FullMatch(TypeParam("az"), re));
    411   EXPECT_TRUE(RE::FullMatch(TypeParam("axyz"), re));
    412   EXPECT_FALSE(RE::FullMatch(TypeParam("baz"), re));
    413   EXPECT_FALSE(RE::FullMatch(TypeParam("azy"), re));
    414 }
    415 
    416 // Tests RE::PartialMatch().
    417 TYPED_TEST(RETest, PartialMatchWorks) {
    418   const RE empty(TypeParam(""));
    419   EXPECT_TRUE(RE::PartialMatch(TypeParam(""), empty));
    420   EXPECT_TRUE(RE::PartialMatch(TypeParam("a"), empty));
    421 
    422   const RE re(TypeParam("a.*z"));
    423   EXPECT_TRUE(RE::PartialMatch(TypeParam("az"), re));
    424   EXPECT_TRUE(RE::PartialMatch(TypeParam("axyz"), re));
    425   EXPECT_TRUE(RE::PartialMatch(TypeParam("baz"), re));
    426   EXPECT_TRUE(RE::PartialMatch(TypeParam("azy"), re));
    427   EXPECT_FALSE(RE::PartialMatch(TypeParam("zza"), re));
    428 }
    429 
    430 # endif  // GTEST_HAS_TYPED_TEST
    431 
    432 #elif GTEST_USES_SIMPLE_RE
    433 
    434 TEST(IsInSetTest, NulCharIsNotInAnySet) {
    435   EXPECT_FALSE(IsInSet('\0', ""));
    436   EXPECT_FALSE(IsInSet('\0', "\0"));
    437   EXPECT_FALSE(IsInSet('\0', "a"));
    438 }
    439 
    440 TEST(IsInSetTest, WorksForNonNulChars) {
    441   EXPECT_FALSE(IsInSet('a', "Ab"));
    442   EXPECT_FALSE(IsInSet('c', ""));
    443 
    444   EXPECT_TRUE(IsInSet('b', "bcd"));
    445   EXPECT_TRUE(IsInSet('b', "ab"));
    446 }
    447 
    448 TEST(IsAsciiDigitTest, IsFalseForNonDigit) {
    449   EXPECT_FALSE(IsAsciiDigit('\0'));
    450   EXPECT_FALSE(IsAsciiDigit(' '));
    451   EXPECT_FALSE(IsAsciiDigit('+'));
    452   EXPECT_FALSE(IsAsciiDigit('-'));
    453   EXPECT_FALSE(IsAsciiDigit('.'));
    454   EXPECT_FALSE(IsAsciiDigit('a'));
    455 }
    456 
    457 TEST(IsAsciiDigitTest, IsTrueForDigit) {
    458   EXPECT_TRUE(IsAsciiDigit('0'));
    459   EXPECT_TRUE(IsAsciiDigit('1'));
    460   EXPECT_TRUE(IsAsciiDigit('5'));
    461   EXPECT_TRUE(IsAsciiDigit('9'));
    462 }
    463 
    464 TEST(IsAsciiPunctTest, IsFalseForNonPunct) {
    465   EXPECT_FALSE(IsAsciiPunct('\0'));
    466   EXPECT_FALSE(IsAsciiPunct(' '));
    467   EXPECT_FALSE(IsAsciiPunct('\n'));
    468   EXPECT_FALSE(IsAsciiPunct('a'));
    469   EXPECT_FALSE(IsAsciiPunct('0'));
    470 }
    471 
    472 TEST(IsAsciiPunctTest, IsTrueForPunct) {
    473   for (const char* p = "^-!\"#$%&'()*+,./:;<=>?@[\\]_`{|}~"; *p; p++) {
    474     EXPECT_PRED1(IsAsciiPunct, *p);
    475   }
    476 }
    477 
    478 TEST(IsRepeatTest, IsFalseForNonRepeatChar) {
    479   EXPECT_FALSE(IsRepeat('\0'));
    480   EXPECT_FALSE(IsRepeat(' '));
    481   EXPECT_FALSE(IsRepeat('a'));
    482   EXPECT_FALSE(IsRepeat('1'));
    483   EXPECT_FALSE(IsRepeat('-'));
    484 }
    485 
    486 TEST(IsRepeatTest, IsTrueForRepeatChar) {
    487   EXPECT_TRUE(IsRepeat('?'));
    488   EXPECT_TRUE(IsRepeat('*'));
    489   EXPECT_TRUE(IsRepeat('+'));
    490 }
    491 
    492 TEST(IsAsciiWhiteSpaceTest, IsFalseForNonWhiteSpace) {
    493   EXPECT_FALSE(IsAsciiWhiteSpace('\0'));
    494   EXPECT_FALSE(IsAsciiWhiteSpace('a'));
    495   EXPECT_FALSE(IsAsciiWhiteSpace('1'));
    496   EXPECT_FALSE(IsAsciiWhiteSpace('+'));
    497   EXPECT_FALSE(IsAsciiWhiteSpace('_'));
    498 }
    499 
    500 TEST(IsAsciiWhiteSpaceTest, IsTrueForWhiteSpace) {
    501   EXPECT_TRUE(IsAsciiWhiteSpace(' '));
    502   EXPECT_TRUE(IsAsciiWhiteSpace('\n'));
    503   EXPECT_TRUE(IsAsciiWhiteSpace('\r'));
    504   EXPECT_TRUE(IsAsciiWhiteSpace('\t'));
    505   EXPECT_TRUE(IsAsciiWhiteSpace('\v'));
    506   EXPECT_TRUE(IsAsciiWhiteSpace('\f'));
    507 }
    508 
    509 TEST(IsAsciiWordCharTest, IsFalseForNonWordChar) {
    510   EXPECT_FALSE(IsAsciiWordChar('\0'));
    511   EXPECT_FALSE(IsAsciiWordChar('+'));
    512   EXPECT_FALSE(IsAsciiWordChar('.'));
    513   EXPECT_FALSE(IsAsciiWordChar(' '));
    514   EXPECT_FALSE(IsAsciiWordChar('\n'));
    515 }
    516 
    517 TEST(IsAsciiWordCharTest, IsTrueForLetter) {
    518   EXPECT_TRUE(IsAsciiWordChar('a'));
    519   EXPECT_TRUE(IsAsciiWordChar('b'));
    520   EXPECT_TRUE(IsAsciiWordChar('A'));
    521   EXPECT_TRUE(IsAsciiWordChar('Z'));
    522 }
    523 
    524 TEST(IsAsciiWordCharTest, IsTrueForDigit) {
    525   EXPECT_TRUE(IsAsciiWordChar('0'));
    526   EXPECT_TRUE(IsAsciiWordChar('1'));
    527   EXPECT_TRUE(IsAsciiWordChar('7'));
    528   EXPECT_TRUE(IsAsciiWordChar('9'));
    529 }
    530 
    531 TEST(IsAsciiWordCharTest, IsTrueForUnderscore) {
    532   EXPECT_TRUE(IsAsciiWordChar('_'));
    533 }
    534 
    535 TEST(IsValidEscapeTest, IsFalseForNonPrintable) {
    536   EXPECT_FALSE(IsValidEscape('\0'));
    537   EXPECT_FALSE(IsValidEscape('\007'));
    538 }
    539 
    540 TEST(IsValidEscapeTest, IsFalseForDigit) {
    541   EXPECT_FALSE(IsValidEscape('0'));
    542   EXPECT_FALSE(IsValidEscape('9'));
    543 }
    544 
    545 TEST(IsValidEscapeTest, IsFalseForWhiteSpace) {
    546   EXPECT_FALSE(IsValidEscape(' '));
    547   EXPECT_FALSE(IsValidEscape('\n'));
    548 }
    549 
    550 TEST(IsValidEscapeTest, IsFalseForSomeLetter) {
    551   EXPECT_FALSE(IsValidEscape('a'));
    552   EXPECT_FALSE(IsValidEscape('Z'));
    553 }
    554 
    555 TEST(IsValidEscapeTest, IsTrueForPunct) {
    556   EXPECT_TRUE(IsValidEscape('.'));
    557   EXPECT_TRUE(IsValidEscape('-'));
    558   EXPECT_TRUE(IsValidEscape('^'));
    559   EXPECT_TRUE(IsValidEscape('$'));
    560   EXPECT_TRUE(IsValidEscape('('));
    561   EXPECT_TRUE(IsValidEscape(']'));
    562   EXPECT_TRUE(IsValidEscape('{'));
    563   EXPECT_TRUE(IsValidEscape('|'));
    564 }
    565 
    566 TEST(IsValidEscapeTest, IsTrueForSomeLetter) {
    567   EXPECT_TRUE(IsValidEscape('d'));
    568   EXPECT_TRUE(IsValidEscape('D'));
    569   EXPECT_TRUE(IsValidEscape('s'));
    570   EXPECT_TRUE(IsValidEscape('S'));
    571   EXPECT_TRUE(IsValidEscape('w'));
    572   EXPECT_TRUE(IsValidEscape('W'));
    573 }
    574 
    575 TEST(AtomMatchesCharTest, EscapedPunct) {
    576   EXPECT_FALSE(AtomMatchesChar(true, '\\', '\0'));
    577   EXPECT_FALSE(AtomMatchesChar(true, '\\', ' '));
    578   EXPECT_FALSE(AtomMatchesChar(true, '_', '.'));
    579   EXPECT_FALSE(AtomMatchesChar(true, '.', 'a'));
    580 
    581   EXPECT_TRUE(AtomMatchesChar(true, '\\', '\\'));
    582   EXPECT_TRUE(AtomMatchesChar(true, '_', '_'));
    583   EXPECT_TRUE(AtomMatchesChar(true, '+', '+'));
    584   EXPECT_TRUE(AtomMatchesChar(true, '.', '.'));
    585 }
    586 
    587 TEST(AtomMatchesCharTest, Escaped_d) {
    588   EXPECT_FALSE(AtomMatchesChar(true, 'd', '\0'));
    589   EXPECT_FALSE(AtomMatchesChar(true, 'd', 'a'));
    590   EXPECT_FALSE(AtomMatchesChar(true, 'd', '.'));
    591 
    592   EXPECT_TRUE(AtomMatchesChar(true, 'd', '0'));
    593   EXPECT_TRUE(AtomMatchesChar(true, 'd', '9'));
    594 }
    595 
    596 TEST(AtomMatchesCharTest, Escaped_D) {
    597   EXPECT_FALSE(AtomMatchesChar(true, 'D', '0'));
    598   EXPECT_FALSE(AtomMatchesChar(true, 'D', '9'));
    599 
    600   EXPECT_TRUE(AtomMatchesChar(true, 'D', '\0'));
    601   EXPECT_TRUE(AtomMatchesChar(true, 'D', 'a'));
    602   EXPECT_TRUE(AtomMatchesChar(true, 'D', '-'));
    603 }
    604 
    605 TEST(AtomMatchesCharTest, Escaped_s) {
    606   EXPECT_FALSE(AtomMatchesChar(true, 's', '\0'));
    607   EXPECT_FALSE(AtomMatchesChar(true, 's', 'a'));
    608   EXPECT_FALSE(AtomMatchesChar(true, 's', '.'));
    609   EXPECT_FALSE(AtomMatchesChar(true, 's', '9'));
    610 
    611   EXPECT_TRUE(AtomMatchesChar(true, 's', ' '));
    612   EXPECT_TRUE(AtomMatchesChar(true, 's', '\n'));
    613   EXPECT_TRUE(AtomMatchesChar(true, 's', '\t'));
    614 }
    615 
    616 TEST(AtomMatchesCharTest, Escaped_S) {
    617   EXPECT_FALSE(AtomMatchesChar(true, 'S', ' '));
    618   EXPECT_FALSE(AtomMatchesChar(true, 'S', '\r'));
    619 
    620   EXPECT_TRUE(AtomMatchesChar(true, 'S', '\0'));
    621   EXPECT_TRUE(AtomMatchesChar(true, 'S', 'a'));
    622   EXPECT_TRUE(AtomMatchesChar(true, 'S', '9'));
    623 }
    624 
    625 TEST(AtomMatchesCharTest, Escaped_w) {
    626   EXPECT_FALSE(AtomMatchesChar(true, 'w', '\0'));
    627   EXPECT_FALSE(AtomMatchesChar(true, 'w', '+'));
    628   EXPECT_FALSE(AtomMatchesChar(true, 'w', ' '));
    629   EXPECT_FALSE(AtomMatchesChar(true, 'w', '\n'));
    630 
    631   EXPECT_TRUE(AtomMatchesChar(true, 'w', '0'));
    632   EXPECT_TRUE(AtomMatchesChar(true, 'w', 'b'));
    633   EXPECT_TRUE(AtomMatchesChar(true, 'w', 'C'));
    634   EXPECT_TRUE(AtomMatchesChar(true, 'w', '_'));
    635 }
    636 
    637 TEST(AtomMatchesCharTest, Escaped_W) {
    638   EXPECT_FALSE(AtomMatchesChar(true, 'W', 'A'));
    639   EXPECT_FALSE(AtomMatchesChar(true, 'W', 'b'));
    640   EXPECT_FALSE(AtomMatchesChar(true, 'W', '9'));
    641   EXPECT_FALSE(AtomMatchesChar(true, 'W', '_'));
    642 
    643   EXPECT_TRUE(AtomMatchesChar(true, 'W', '\0'));
    644   EXPECT_TRUE(AtomMatchesChar(true, 'W', '*'));
    645   EXPECT_TRUE(AtomMatchesChar(true, 'W', '\n'));
    646 }
    647 
    648 TEST(AtomMatchesCharTest, EscapedWhiteSpace) {
    649   EXPECT_FALSE(AtomMatchesChar(true, 'f', '\0'));
    650   EXPECT_FALSE(AtomMatchesChar(true, 'f', '\n'));
    651   EXPECT_FALSE(AtomMatchesChar(true, 'n', '\0'));
    652   EXPECT_FALSE(AtomMatchesChar(true, 'n', '\r'));
    653   EXPECT_FALSE(AtomMatchesChar(true, 'r', '\0'));
    654   EXPECT_FALSE(AtomMatchesChar(true, 'r', 'a'));
    655   EXPECT_FALSE(AtomMatchesChar(true, 't', '\0'));
    656   EXPECT_FALSE(AtomMatchesChar(true, 't', 't'));
    657   EXPECT_FALSE(AtomMatchesChar(true, 'v', '\0'));
    658   EXPECT_FALSE(AtomMatchesChar(true, 'v', '\f'));
    659 
    660   EXPECT_TRUE(AtomMatchesChar(true, 'f', '\f'));
    661   EXPECT_TRUE(AtomMatchesChar(true, 'n', '\n'));
    662   EXPECT_TRUE(AtomMatchesChar(true, 'r', '\r'));
    663   EXPECT_TRUE(AtomMatchesChar(true, 't', '\t'));
    664   EXPECT_TRUE(AtomMatchesChar(true, 'v', '\v'));
    665 }
    666 
    667 TEST(AtomMatchesCharTest, UnescapedDot) {
    668   EXPECT_FALSE(AtomMatchesChar(false, '.', '\n'));
    669 
    670   EXPECT_TRUE(AtomMatchesChar(false, '.', '\0'));
    671   EXPECT_TRUE(AtomMatchesChar(false, '.', '.'));
    672   EXPECT_TRUE(AtomMatchesChar(false, '.', 'a'));
    673   EXPECT_TRUE(AtomMatchesChar(false, '.', ' '));
    674 }
    675 
    676 TEST(AtomMatchesCharTest, UnescapedChar) {
    677   EXPECT_FALSE(AtomMatchesChar(false, 'a', '\0'));
    678   EXPECT_FALSE(AtomMatchesChar(false, 'a', 'b'));
    679   EXPECT_FALSE(AtomMatchesChar(false, '$', 'a'));
    680 
    681   EXPECT_TRUE(AtomMatchesChar(false, '$', '$'));
    682   EXPECT_TRUE(AtomMatchesChar(false, '5', '5'));
    683   EXPECT_TRUE(AtomMatchesChar(false, 'Z', 'Z'));
    684 }
    685 
    686 TEST(ValidateRegexTest, GeneratesFailureAndReturnsFalseForInvalid) {
    687   EXPECT_NONFATAL_FAILURE(ASSERT_FALSE(ValidateRegex(NULL)),
    688                           "NULL is not a valid simple regular expression");
    689   EXPECT_NONFATAL_FAILURE(
    690       ASSERT_FALSE(ValidateRegex("a\\")),
    691       "Syntax error at index 1 in simple regular expression \"a\\\": ");
    692   EXPECT_NONFATAL_FAILURE(ASSERT_FALSE(ValidateRegex("a\\")),
    693                           "'\\' cannot appear at the end");
    694   EXPECT_NONFATAL_FAILURE(ASSERT_FALSE(ValidateRegex("\\n\\")),
    695                           "'\\' cannot appear at the end");
    696   EXPECT_NONFATAL_FAILURE(ASSERT_FALSE(ValidateRegex("\\s\\hb")),
    697                           "invalid escape sequence \"\\h\"");
    698   EXPECT_NONFATAL_FAILURE(ASSERT_FALSE(ValidateRegex("^^")),
    699                           "'^' can only appear at the beginning");
    700   EXPECT_NONFATAL_FAILURE(ASSERT_FALSE(ValidateRegex(".*^b")),
    701                           "'^' can only appear at the beginning");
    702   EXPECT_NONFATAL_FAILURE(ASSERT_FALSE(ValidateRegex("$$")),
    703                           "'$' can only appear at the end");
    704   EXPECT_NONFATAL_FAILURE(ASSERT_FALSE(ValidateRegex("^$a")),
    705                           "'$' can only appear at the end");
    706   EXPECT_NONFATAL_FAILURE(ASSERT_FALSE(ValidateRegex("a(b")),
    707                           "'(' is unsupported");
    708   EXPECT_NONFATAL_FAILURE(ASSERT_FALSE(ValidateRegex("ab)")),
    709                           "')' is unsupported");
    710   EXPECT_NONFATAL_FAILURE(ASSERT_FALSE(ValidateRegex("[ab")),
    711                           "'[' is unsupported");
    712   EXPECT_NONFATAL_FAILURE(ASSERT_FALSE(ValidateRegex("a{2")),
    713                           "'{' is unsupported");
    714   EXPECT_NONFATAL_FAILURE(ASSERT_FALSE(ValidateRegex("?")),
    715                           "'?' can only follow a repeatable token");
    716   EXPECT_NONFATAL_FAILURE(ASSERT_FALSE(ValidateRegex("^*")),
    717                           "'*' can only follow a repeatable token");
    718   EXPECT_NONFATAL_FAILURE(ASSERT_FALSE(ValidateRegex("5*+")),
    719                           "'+' can only follow a repeatable token");
    720 }
    721 
    722 TEST(ValidateRegexTest, ReturnsTrueForValid) {
    723   EXPECT_TRUE(ValidateRegex(""));
    724   EXPECT_TRUE(ValidateRegex("a"));
    725   EXPECT_TRUE(ValidateRegex(".*"));
    726   EXPECT_TRUE(ValidateRegex("^a_+"));
    727   EXPECT_TRUE(ValidateRegex("^a\\t\\&?"));
    728   EXPECT_TRUE(ValidateRegex("09*$"));
    729   EXPECT_TRUE(ValidateRegex("^Z$"));
    730   EXPECT_TRUE(ValidateRegex("a\\^Z\\$\\(\\)\\|\\[\\]\\{\\}"));
    731 }
    732 
    733 TEST(MatchRepetitionAndRegexAtHeadTest, WorksForZeroOrOne) {
    734   EXPECT_FALSE(MatchRepetitionAndRegexAtHead(false, 'a', '?', "a", "ba"));
    735   // Repeating more than once.
    736   EXPECT_FALSE(MatchRepetitionAndRegexAtHead(false, 'a', '?', "b", "aab"));
    737 
    738   // Repeating zero times.
    739   EXPECT_TRUE(MatchRepetitionAndRegexAtHead(false, 'a', '?', "b", "ba"));
    740   // Repeating once.
    741   EXPECT_TRUE(MatchRepetitionAndRegexAtHead(false, 'a', '?', "b", "ab"));
    742   EXPECT_TRUE(MatchRepetitionAndRegexAtHead(false, '#', '?', ".", "##"));
    743 }
    744 
    745 TEST(MatchRepetitionAndRegexAtHeadTest, WorksForZeroOrMany) {
    746   EXPECT_FALSE(MatchRepetitionAndRegexAtHead(false, '.', '*', "a$", "baab"));
    747 
    748   // Repeating zero times.
    749   EXPECT_TRUE(MatchRepetitionAndRegexAtHead(false, '.', '*', "b", "bc"));
    750   // Repeating once.
    751   EXPECT_TRUE(MatchRepetitionAndRegexAtHead(false, '.', '*', "b", "abc"));
    752   // Repeating more than once.
    753   EXPECT_TRUE(MatchRepetitionAndRegexAtHead(true, 'w', '*', "-", "ab_1-g"));
    754 }
    755 
    756 TEST(MatchRepetitionAndRegexAtHeadTest, WorksForOneOrMany) {
    757   EXPECT_FALSE(MatchRepetitionAndRegexAtHead(false, '.', '+', "a$", "baab"));
    758   // Repeating zero times.
    759   EXPECT_FALSE(MatchRepetitionAndRegexAtHead(false, '.', '+', "b", "bc"));
    760 
    761   // Repeating once.
    762   EXPECT_TRUE(MatchRepetitionAndRegexAtHead(false, '.', '+', "b", "abc"));
    763   // Repeating more than once.
    764   EXPECT_TRUE(MatchRepetitionAndRegexAtHead(true, 'w', '+', "-", "ab_1-g"));
    765 }
    766 
    767 TEST(MatchRegexAtHeadTest, ReturnsTrueForEmptyRegex) {
    768   EXPECT_TRUE(MatchRegexAtHead("", ""));
    769   EXPECT_TRUE(MatchRegexAtHead("", "ab"));
    770 }
    771 
    772 TEST(MatchRegexAtHeadTest, WorksWhenDollarIsInRegex) {
    773   EXPECT_FALSE(MatchRegexAtHead("$", "a"));
    774 
    775   EXPECT_TRUE(MatchRegexAtHead("$", ""));
    776   EXPECT_TRUE(MatchRegexAtHead("a$", "a"));
    777 }
    778 
    779 TEST(MatchRegexAtHeadTest, WorksWhenRegexStartsWithEscapeSequence) {
    780   EXPECT_FALSE(MatchRegexAtHead("\\w", "+"));
    781   EXPECT_FALSE(MatchRegexAtHead("\\W", "ab"));
    782 
    783   EXPECT_TRUE(MatchRegexAtHead("\\sa", "\nab"));
    784   EXPECT_TRUE(MatchRegexAtHead("\\d", "1a"));
    785 }
    786 
    787 TEST(MatchRegexAtHeadTest, WorksWhenRegexStartsWithRepetition) {
    788   EXPECT_FALSE(MatchRegexAtHead(".+a", "abc"));
    789   EXPECT_FALSE(MatchRegexAtHead("a?b", "aab"));
    790 
    791   EXPECT_TRUE(MatchRegexAtHead(".*a", "bc12-ab"));
    792   EXPECT_TRUE(MatchRegexAtHead("a?b", "b"));
    793   EXPECT_TRUE(MatchRegexAtHead("a?b", "ab"));
    794 }
    795 
    796 TEST(MatchRegexAtHeadTest,
    797      WorksWhenRegexStartsWithRepetionOfEscapeSequence) {
    798   EXPECT_FALSE(MatchRegexAtHead("\\.+a", "abc"));
    799   EXPECT_FALSE(MatchRegexAtHead("\\s?b", "  b"));
    800 
    801   EXPECT_TRUE(MatchRegexAtHead("\\(*a", "((((ab"));
    802   EXPECT_TRUE(MatchRegexAtHead("\\^?b", "^b"));
    803   EXPECT_TRUE(MatchRegexAtHead("\\\\?b", "b"));
    804   EXPECT_TRUE(MatchRegexAtHead("\\\\?b", "\\b"));
    805 }
    806 
    807 TEST(MatchRegexAtHeadTest, MatchesSequentially) {
    808   EXPECT_FALSE(MatchRegexAtHead("ab.*c", "acabc"));
    809 
    810   EXPECT_TRUE(MatchRegexAtHead("ab.*c", "ab-fsc"));
    811 }
    812 
    813 TEST(MatchRegexAnywhereTest, ReturnsFalseWhenStringIsNull) {
    814   EXPECT_FALSE(MatchRegexAnywhere("", NULL));
    815 }
    816 
    817 TEST(MatchRegexAnywhereTest, WorksWhenRegexStartsWithCaret) {
    818   EXPECT_FALSE(MatchRegexAnywhere("^a", "ba"));
    819   EXPECT_FALSE(MatchRegexAnywhere("^$", "a"));
    820 
    821   EXPECT_TRUE(MatchRegexAnywhere("^a", "ab"));
    822   EXPECT_TRUE(MatchRegexAnywhere("^", "ab"));
    823   EXPECT_TRUE(MatchRegexAnywhere("^$", ""));
    824 }
    825 
    826 TEST(MatchRegexAnywhereTest, ReturnsFalseWhenNoMatch) {
    827   EXPECT_FALSE(MatchRegexAnywhere("a", "bcde123"));
    828   EXPECT_FALSE(MatchRegexAnywhere("a.+a", "--aa88888888"));
    829 }
    830 
    831 TEST(MatchRegexAnywhereTest, ReturnsTrueWhenMatchingPrefix) {
    832   EXPECT_TRUE(MatchRegexAnywhere("\\w+", "ab1_ - 5"));
    833   EXPECT_TRUE(MatchRegexAnywhere(".*=", "="));
    834   EXPECT_TRUE(MatchRegexAnywhere("x.*ab?.*bc", "xaaabc"));
    835 }
    836 
    837 TEST(MatchRegexAnywhereTest, ReturnsTrueWhenMatchingNonPrefix) {
    838   EXPECT_TRUE(MatchRegexAnywhere("\\w+", "$$$ ab1_ - 5"));
    839   EXPECT_TRUE(MatchRegexAnywhere("\\.+=", "=  ...="));
    840 }
    841 
    842 // Tests RE's implicit constructors.
    843 TEST(RETest, ImplicitConstructorWorks) {
    844   const RE empty("");
    845   EXPECT_STREQ("", empty.pattern());
    846 
    847   const RE simple("hello");
    848   EXPECT_STREQ("hello", simple.pattern());
    849 }
    850 
    851 // Tests that RE's constructors reject invalid regular expressions.
    852 TEST(RETest, RejectsInvalidRegex) {
    853   EXPECT_NONFATAL_FAILURE({
    854     const RE normal(NULL);
    855   }, "NULL is not a valid simple regular expression");
    856 
    857   EXPECT_NONFATAL_FAILURE({
    858     const RE normal(".*(\\w+");
    859   }, "'(' is unsupported");
    860 
    861   EXPECT_NONFATAL_FAILURE({
    862     const RE invalid("^?");
    863   }, "'?' can only follow a repeatable token");
    864 }
    865 
    866 // Tests RE::FullMatch().
    867 TEST(RETest, FullMatchWorks) {
    868   const RE empty("");
    869   EXPECT_TRUE(RE::FullMatch("", empty));
    870   EXPECT_FALSE(RE::FullMatch("a", empty));
    871 
    872   const RE re1("a");
    873   EXPECT_TRUE(RE::FullMatch("a", re1));
    874 
    875   const RE re("a.*z");
    876   EXPECT_TRUE(RE::FullMatch("az", re));
    877   EXPECT_TRUE(RE::FullMatch("axyz", re));
    878   EXPECT_FALSE(RE::FullMatch("baz", re));
    879   EXPECT_FALSE(RE::FullMatch("azy", re));
    880 }
    881 
    882 // Tests RE::PartialMatch().
    883 TEST(RETest, PartialMatchWorks) {
    884   const RE empty("");
    885   EXPECT_TRUE(RE::PartialMatch("", empty));
    886   EXPECT_TRUE(RE::PartialMatch("a", empty));
    887 
    888   const RE re("a.*z");
    889   EXPECT_TRUE(RE::PartialMatch("az", re));
    890   EXPECT_TRUE(RE::PartialMatch("axyz", re));
    891   EXPECT_TRUE(RE::PartialMatch("baz", re));
    892   EXPECT_TRUE(RE::PartialMatch("azy", re));
    893   EXPECT_FALSE(RE::PartialMatch("zza", re));
    894 }
    895 
    896 #endif  // GTEST_USES_POSIX_RE
    897 
    898 #if !GTEST_OS_WINDOWS_MOBILE
    899 
    900 TEST(CaptureTest, CapturesStdout) {
    901   CaptureStdout();
    902   fprintf(stdout, "abc");
    903   EXPECT_STREQ("abc", GetCapturedStdout().c_str());
    904 
    905   CaptureStdout();
    906   fprintf(stdout, "def%cghi", '\0');
    907   EXPECT_EQ(::std::string("def\0ghi", 7), ::std::string(GetCapturedStdout()));
    908 }
    909 
    910 TEST(CaptureTest, CapturesStderr) {
    911   CaptureStderr();
    912   fprintf(stderr, "jkl");
    913   EXPECT_STREQ("jkl", GetCapturedStderr().c_str());
    914 
    915   CaptureStderr();
    916   fprintf(stderr, "jkl%cmno", '\0');
    917   EXPECT_EQ(::std::string("jkl\0mno", 7), ::std::string(GetCapturedStderr()));
    918 }
    919 
    920 // Tests that stdout and stderr capture don't interfere with each other.
    921 TEST(CaptureTest, CapturesStdoutAndStderr) {
    922   CaptureStdout();
    923   CaptureStderr();
    924   fprintf(stdout, "pqr");
    925   fprintf(stderr, "stu");
    926   EXPECT_STREQ("pqr", GetCapturedStdout().c_str());
    927   EXPECT_STREQ("stu", GetCapturedStderr().c_str());
    928 }
    929 
    930 TEST(CaptureDeathTest, CannotReenterStdoutCapture) {
    931   CaptureStdout();
    932   EXPECT_DEATH_IF_SUPPORTED(CaptureStdout(),
    933                             "Only one stdout capturer can exist at a time");
    934   GetCapturedStdout();
    935 
    936   // We cannot test stderr capturing using death tests as they use it
    937   // themselves.
    938 }
    939 
    940 #endif  // !GTEST_OS_WINDOWS_MOBILE
    941 
    942 TEST(ThreadLocalTest, DefaultConstructorInitializesToDefaultValues) {
    943   ThreadLocal<int> t1;
    944   EXPECT_EQ(0, t1.get());
    945 
    946   ThreadLocal<void*> t2;
    947   EXPECT_TRUE(t2.get() == NULL);
    948 }
    949 
    950 TEST(ThreadLocalTest, SingleParamConstructorInitializesToParam) {
    951   ThreadLocal<int> t1(123);
    952   EXPECT_EQ(123, t1.get());
    953 
    954   int i = 0;
    955   ThreadLocal<int*> t2(&i);
    956   EXPECT_EQ(&i, t2.get());
    957 }
    958 
    959 class NoDefaultContructor {
    960  public:
    961   explicit NoDefaultContructor(const char*) {}
    962   NoDefaultContructor(const NoDefaultContructor&) {}
    963 };
    964 
    965 TEST(ThreadLocalTest, ValueDefaultContructorIsNotRequiredForParamVersion) {
    966   ThreadLocal<NoDefaultContructor> bar(NoDefaultContructor("foo"));
    967   bar.pointer();
    968 }
    969 
    970 TEST(ThreadLocalTest, GetAndPointerReturnSameValue) {
    971   ThreadLocal<String> thread_local_string;
    972 
    973   EXPECT_EQ(thread_local_string.pointer(), &(thread_local_string.get()));
    974 
    975   // Verifies the condition still holds after calling set.
    976   thread_local_string.set("foo");
    977   EXPECT_EQ(thread_local_string.pointer(), &(thread_local_string.get()));
    978 }
    979 
    980 TEST(ThreadLocalTest, PointerAndConstPointerReturnSameValue) {
    981   ThreadLocal<String> thread_local_string;
    982   const ThreadLocal<String>& const_thread_local_string = thread_local_string;
    983 
    984   EXPECT_EQ(thread_local_string.pointer(), const_thread_local_string.pointer());
    985 
    986   thread_local_string.set("foo");
    987   EXPECT_EQ(thread_local_string.pointer(), const_thread_local_string.pointer());
    988 }
    989 
    990 #if GTEST_IS_THREADSAFE
    991 
    992 void AddTwo(int* param) { *param += 2; }
    993 
    994 TEST(ThreadWithParamTest, ConstructorExecutesThreadFunc) {
    995   int i = 40;
    996   ThreadWithParam<int*> thread(&AddTwo, &i, NULL);
    997   thread.Join();
    998   EXPECT_EQ(42, i);
    999 }
   1000 
   1001 TEST(MutexDeathTest, AssertHeldShouldAssertWhenNotLocked) {
   1002   // AssertHeld() is flaky only in the presence of multiple threads accessing
   1003   // the lock. In this case, the test is robust.
   1004   EXPECT_DEATH_IF_SUPPORTED({
   1005     Mutex m;
   1006     { MutexLock lock(&m); }
   1007     m.AssertHeld();
   1008   },
   1009   "thread .*hold");
   1010 }
   1011 
   1012 TEST(MutexTest, AssertHeldShouldNotAssertWhenLocked) {
   1013   Mutex m;
   1014   MutexLock lock(&m);
   1015   m.AssertHeld();
   1016 }
   1017 
   1018 class AtomicCounterWithMutex {
   1019  public:
   1020   explicit AtomicCounterWithMutex(Mutex* mutex) :
   1021     value_(0), mutex_(mutex), random_(42) {}
   1022 
   1023   void Increment() {
   1024     MutexLock lock(mutex_);
   1025     int temp = value_;
   1026     {
   1027       // Locking a mutex puts up a memory barrier, preventing reads and
   1028       // writes to value_ rearranged when observed from other threads.
   1029       //
   1030       // We cannot use Mutex and MutexLock here or rely on their memory
   1031       // barrier functionality as we are testing them here.
   1032       pthread_mutex_t memory_barrier_mutex;
   1033       GTEST_CHECK_POSIX_SUCCESS_(
   1034           pthread_mutex_init(&memory_barrier_mutex, NULL));
   1035       GTEST_CHECK_POSIX_SUCCESS_(pthread_mutex_lock(&memory_barrier_mutex));
   1036 
   1037       SleepMilliseconds(random_.Generate(30));
   1038 
   1039       GTEST_CHECK_POSIX_SUCCESS_(pthread_mutex_unlock(&memory_barrier_mutex));
   1040       GTEST_CHECK_POSIX_SUCCESS_(pthread_mutex_destroy(&memory_barrier_mutex));
   1041     }
   1042     value_ = temp + 1;
   1043   }
   1044   int value() const { return value_; }
   1045 
   1046  private:
   1047   volatile int value_;
   1048   Mutex* const mutex_;  // Protects value_.
   1049   Random       random_;
   1050 };
   1051 
   1052 void CountingThreadFunc(pair<AtomicCounterWithMutex*, int> param) {
   1053   for (int i = 0; i < param.second; ++i)
   1054       param.first->Increment();
   1055 }
   1056 
   1057 // Tests that the mutex only lets one thread at a time to lock it.
   1058 TEST(MutexTest, OnlyOneThreadCanLockAtATime) {
   1059   Mutex mutex;
   1060   AtomicCounterWithMutex locked_counter(&mutex);
   1061 
   1062   typedef ThreadWithParam<pair<AtomicCounterWithMutex*, int> > ThreadType;
   1063   const int kCycleCount = 20;
   1064   const int kThreadCount = 7;
   1065   scoped_ptr<ThreadType> counting_threads[kThreadCount];
   1066   Notification threads_can_start;
   1067   // Creates and runs kThreadCount threads that increment locked_counter
   1068   // kCycleCount times each.
   1069   for (int i = 0; i < kThreadCount; ++i) {
   1070     counting_threads[i].reset(new ThreadType(&CountingThreadFunc,
   1071                                              make_pair(&locked_counter,
   1072                                                        kCycleCount),
   1073                                              &threads_can_start));
   1074   }
   1075   threads_can_start.Notify();
   1076   for (int i = 0; i < kThreadCount; ++i)
   1077     counting_threads[i]->Join();
   1078 
   1079   // If the mutex lets more than one thread to increment the counter at a
   1080   // time, they are likely to encounter a race condition and have some
   1081   // increments overwritten, resulting in the lower then expected counter
   1082   // value.
   1083   EXPECT_EQ(kCycleCount * kThreadCount, locked_counter.value());
   1084 }
   1085 
   1086 template <typename T>
   1087 void RunFromThread(void (func)(T), T param) {
   1088   ThreadWithParam<T> thread(func, param, NULL);
   1089   thread.Join();
   1090 }
   1091 
   1092 void RetrieveThreadLocalValue(pair<ThreadLocal<String>*, String*> param) {
   1093   *param.second = param.first->get();
   1094 }
   1095 
   1096 TEST(ThreadLocalTest, ParameterizedConstructorSetsDefault) {
   1097   ThreadLocal<String> thread_local_string("foo");
   1098   EXPECT_STREQ("foo", thread_local_string.get().c_str());
   1099 
   1100   thread_local_string.set("bar");
   1101   EXPECT_STREQ("bar", thread_local_string.get().c_str());
   1102 
   1103   String result;
   1104   RunFromThread(&RetrieveThreadLocalValue,
   1105                 make_pair(&thread_local_string, &result));
   1106   EXPECT_STREQ("foo", result.c_str());
   1107 }
   1108 
   1109 // DestructorTracker keeps track of whether its instances have been
   1110 // destroyed.
   1111 static std::vector<bool> g_destroyed;
   1112 
   1113 class DestructorTracker {
   1114  public:
   1115   DestructorTracker() : index_(GetNewIndex()) {}
   1116   DestructorTracker(const DestructorTracker& /* rhs */)
   1117       : index_(GetNewIndex()) {}
   1118   ~DestructorTracker() {
   1119     // We never access g_destroyed concurrently, so we don't need to
   1120     // protect the write operation under a mutex.
   1121     g_destroyed[index_] = true;
   1122   }
   1123 
   1124  private:
   1125   static int GetNewIndex() {
   1126     g_destroyed.push_back(false);
   1127     return g_destroyed.size() - 1;
   1128   }
   1129   const int index_;
   1130 };
   1131 
   1132 typedef ThreadLocal<DestructorTracker>* ThreadParam;
   1133 
   1134 void CallThreadLocalGet(ThreadParam thread_local_param) {
   1135   thread_local_param->get();
   1136 }
   1137 
   1138 // Tests that when a ThreadLocal object dies in a thread, it destroys
   1139 // the managed object for that thread.
   1140 TEST(ThreadLocalTest, DestroysManagedObjectForOwnThreadWhenDying) {
   1141   g_destroyed.clear();
   1142 
   1143   {
   1144     // The next line default constructs a DestructorTracker object as
   1145     // the default value of objects managed by thread_local_tracker.
   1146     ThreadLocal<DestructorTracker> thread_local_tracker;
   1147     ASSERT_EQ(1U, g_destroyed.size());
   1148     ASSERT_FALSE(g_destroyed[0]);
   1149 
   1150     // This creates another DestructorTracker object for the main thread.
   1151     thread_local_tracker.get();
   1152     ASSERT_EQ(2U, g_destroyed.size());
   1153     ASSERT_FALSE(g_destroyed[0]);
   1154     ASSERT_FALSE(g_destroyed[1]);
   1155   }
   1156 
   1157   // Now thread_local_tracker has died.  It should have destroyed both the
   1158   // default value shared by all threads and the value for the main
   1159   // thread.
   1160   ASSERT_EQ(2U, g_destroyed.size());
   1161   EXPECT_TRUE(g_destroyed[0]);
   1162   EXPECT_TRUE(g_destroyed[1]);
   1163 
   1164   g_destroyed.clear();
   1165 }
   1166 
   1167 // Tests that when a thread exits, the thread-local object for that
   1168 // thread is destroyed.
   1169 TEST(ThreadLocalTest, DestroysManagedObjectAtThreadExit) {
   1170   g_destroyed.clear();
   1171 
   1172   {
   1173     // The next line default constructs a DestructorTracker object as
   1174     // the default value of objects managed by thread_local_tracker.
   1175     ThreadLocal<DestructorTracker> thread_local_tracker;
   1176     ASSERT_EQ(1U, g_destroyed.size());
   1177     ASSERT_FALSE(g_destroyed[0]);
   1178 
   1179     // This creates another DestructorTracker object in the new thread.
   1180     ThreadWithParam<ThreadParam> thread(
   1181         &CallThreadLocalGet, &thread_local_tracker, NULL);
   1182     thread.Join();
   1183 
   1184     // Now the new thread has exited.  The per-thread object for it
   1185     // should have been destroyed.
   1186     ASSERT_EQ(2U, g_destroyed.size());
   1187     ASSERT_FALSE(g_destroyed[0]);
   1188     ASSERT_TRUE(g_destroyed[1]);
   1189   }
   1190 
   1191   // Now thread_local_tracker has died.  The default value should have been
   1192   // destroyed too.
   1193   ASSERT_EQ(2U, g_destroyed.size());
   1194   EXPECT_TRUE(g_destroyed[0]);
   1195   EXPECT_TRUE(g_destroyed[1]);
   1196 
   1197   g_destroyed.clear();
   1198 }
   1199 
   1200 TEST(ThreadLocalTest, ThreadLocalMutationsAffectOnlyCurrentThread) {
   1201   ThreadLocal<String> thread_local_string;
   1202   thread_local_string.set("Foo");
   1203   EXPECT_STREQ("Foo", thread_local_string.get().c_str());
   1204 
   1205   String result;
   1206   RunFromThread(&RetrieveThreadLocalValue,
   1207                 make_pair(&thread_local_string, &result));
   1208   EXPECT_TRUE(result.c_str() == NULL);
   1209 }
   1210 
   1211 #endif  // GTEST_IS_THREADSAFE
   1212 
   1213 }  // namespace internal
   1214 }  // namespace testing
   1215