gtest-port_test.cc
Go to the documentation of this file.
00001 // Copyright 2008, Google Inc.
00002 // All rights reserved.
00003 //
00004 // Redistribution and use in source and binary forms, with or without
00005 // modification, are permitted provided that the following conditions are
00006 // met:
00007 //
00008 //     * Redistributions of source code must retain the above copyright
00009 // notice, this list of conditions and the following disclaimer.
00010 //     * Redistributions in binary form must reproduce the above
00011 // copyright notice, this list of conditions and the following disclaimer
00012 // in the documentation and/or other materials provided with the
00013 // distribution.
00014 //     * Neither the name of Google Inc. nor the names of its
00015 // contributors may be used to endorse or promote products derived from
00016 // this software without specific prior written permission.
00017 //
00018 // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
00019 // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
00020 // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
00021 // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
00022 // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
00023 // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
00024 // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
00025 // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
00026 // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
00027 // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
00028 // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
00029 //
00030 // Authors: vladl@google.com (Vlad Losev), wan@google.com (Zhanyong Wan)
00031 //
00032 // This file tests the internal cross-platform support utilities.
00033 
00034 #include "gtest/internal/gtest-port.h"
00035 
00036 #include <stdio.h>
00037 
00038 #if GTEST_OS_MAC
00039 # include <time.h>
00040 #endif  // GTEST_OS_MAC
00041 
00042 #include <list>
00043 #include <utility>  // For std::pair and std::make_pair.
00044 #include <vector>
00045 
00046 #include "gtest/gtest.h"
00047 #include "gtest/gtest-spi.h"
00048 
00049 // Indicates that this translation unit is part of Google Test's
00050 // implementation.  It must come before gtest-internal-inl.h is
00051 // included, or there will be a compiler error.  This trick is to
00052 // prevent a user from accidentally including gtest-internal-inl.h in
00053 // his code.
00054 #define GTEST_IMPLEMENTATION_ 1
00055 #include "src/gtest-internal-inl.h"
00056 #undef GTEST_IMPLEMENTATION_
00057 
00058 using std::make_pair;
00059 using std::pair;
00060 
00061 namespace testing {
00062 namespace internal {
00063 
00064 TEST(IsXDigitTest, WorksForNarrowAscii) {
00065   EXPECT_TRUE(IsXDigit('0'));
00066   EXPECT_TRUE(IsXDigit('9'));
00067   EXPECT_TRUE(IsXDigit('A'));
00068   EXPECT_TRUE(IsXDigit('F'));
00069   EXPECT_TRUE(IsXDigit('a'));
00070   EXPECT_TRUE(IsXDigit('f'));
00071 
00072   EXPECT_FALSE(IsXDigit('-'));
00073   EXPECT_FALSE(IsXDigit('g'));
00074   EXPECT_FALSE(IsXDigit('G'));
00075 }
00076 
00077 TEST(IsXDigitTest, ReturnsFalseForNarrowNonAscii) {
00078   EXPECT_FALSE(IsXDigit(static_cast<char>(0x80)));
00079   EXPECT_FALSE(IsXDigit(static_cast<char>('0' | 0x80)));
00080 }
00081 
00082 TEST(IsXDigitTest, WorksForWideAscii) {
00083   EXPECT_TRUE(IsXDigit(L'0'));
00084   EXPECT_TRUE(IsXDigit(L'9'));
00085   EXPECT_TRUE(IsXDigit(L'A'));
00086   EXPECT_TRUE(IsXDigit(L'F'));
00087   EXPECT_TRUE(IsXDigit(L'a'));
00088   EXPECT_TRUE(IsXDigit(L'f'));
00089 
00090   EXPECT_FALSE(IsXDigit(L'-'));
00091   EXPECT_FALSE(IsXDigit(L'g'));
00092   EXPECT_FALSE(IsXDigit(L'G'));
00093 }
00094 
00095 TEST(IsXDigitTest, ReturnsFalseForWideNonAscii) {
00096   EXPECT_FALSE(IsXDigit(static_cast<wchar_t>(0x80)));
00097   EXPECT_FALSE(IsXDigit(static_cast<wchar_t>(L'0' | 0x80)));
00098   EXPECT_FALSE(IsXDigit(static_cast<wchar_t>(L'0' | 0x100)));
00099 }
00100 
00101 class Base {
00102  public:
00103   // Copy constructor and assignment operator do exactly what we need, so we
00104   // use them.
00105   Base() : member_(0) {}
00106   explicit Base(int n) : member_(n) {}
00107   virtual ~Base() {}
00108   int member() { return member_; }
00109 
00110  private:
00111   int member_;
00112 };
00113 
00114 class Derived : public Base {
00115  public:
00116   explicit Derived(int n) : Base(n) {}
00117 };
00118 
00119 TEST(ImplicitCastTest, ConvertsPointers) {
00120   Derived derived(0);
00121   EXPECT_TRUE(&derived == ::testing::internal::ImplicitCast_<Base*>(&derived));
00122 }
00123 
00124 TEST(ImplicitCastTest, CanUseInheritance) {
00125   Derived derived(1);
00126   Base base = ::testing::internal::ImplicitCast_<Base>(derived);
00127   EXPECT_EQ(derived.member(), base.member());
00128 }
00129 
00130 class Castable {
00131  public:
00132   explicit Castable(bool* converted) : converted_(converted) {}
00133   operator Base() {
00134     *converted_ = true;
00135     return Base();
00136   }
00137 
00138  private:
00139   bool* converted_;
00140 };
00141 
00142 TEST(ImplicitCastTest, CanUseNonConstCastOperator) {
00143   bool converted = false;
00144   Castable castable(&converted);
00145   Base base = ::testing::internal::ImplicitCast_<Base>(castable);
00146   EXPECT_TRUE(converted);
00147 }
00148 
00149 class ConstCastable {
00150  public:
00151   explicit ConstCastable(bool* converted) : converted_(converted) {}
00152   operator Base() const {
00153     *converted_ = true;
00154     return Base();
00155   }
00156 
00157  private:
00158   bool* converted_;
00159 };
00160 
00161 TEST(ImplicitCastTest, CanUseConstCastOperatorOnConstValues) {
00162   bool converted = false;
00163   const ConstCastable const_castable(&converted);
00164   Base base = ::testing::internal::ImplicitCast_<Base>(const_castable);
00165   EXPECT_TRUE(converted);
00166 }
00167 
00168 class ConstAndNonConstCastable {
00169  public:
00170   ConstAndNonConstCastable(bool* converted, bool* const_converted)
00171       : converted_(converted), const_converted_(const_converted) {}
00172   operator Base() {
00173     *converted_ = true;
00174     return Base();
00175   }
00176   operator Base() const {
00177     *const_converted_ = true;
00178     return Base();
00179   }
00180 
00181  private:
00182   bool* converted_;
00183   bool* const_converted_;
00184 };
00185 
00186 TEST(ImplicitCastTest, CanSelectBetweenConstAndNonConstCasrAppropriately) {
00187   bool converted = false;
00188   bool const_converted = false;
00189   ConstAndNonConstCastable castable(&converted, &const_converted);
00190   Base base = ::testing::internal::ImplicitCast_<Base>(castable);
00191   EXPECT_TRUE(converted);
00192   EXPECT_FALSE(const_converted);
00193 
00194   converted = false;
00195   const_converted = false;
00196   const ConstAndNonConstCastable const_castable(&converted, &const_converted);
00197   base = ::testing::internal::ImplicitCast_<Base>(const_castable);
00198   EXPECT_FALSE(converted);
00199   EXPECT_TRUE(const_converted);
00200 }
00201 
00202 class To {
00203  public:
00204   To(bool* converted) { *converted = true; }  // NOLINT
00205 };
00206 
00207 TEST(ImplicitCastTest, CanUseImplicitConstructor) {
00208   bool converted = false;
00209   To to = ::testing::internal::ImplicitCast_<To>(&converted);
00210   (void)to;
00211   EXPECT_TRUE(converted);
00212 }
00213 
00214 TEST(IteratorTraitsTest, WorksForSTLContainerIterators) {
00215   StaticAssertTypeEq<int,
00216       IteratorTraits< ::std::vector<int>::const_iterator>::value_type>();
00217   StaticAssertTypeEq<bool,
00218       IteratorTraits< ::std::list<bool>::iterator>::value_type>();
00219 }
00220 
00221 TEST(IteratorTraitsTest, WorksForPointerToNonConst) {
00222   StaticAssertTypeEq<char, IteratorTraits<char*>::value_type>();
00223   StaticAssertTypeEq<const void*, IteratorTraits<const void**>::value_type>();
00224 }
00225 
00226 TEST(IteratorTraitsTest, WorksForPointerToConst) {
00227   StaticAssertTypeEq<char, IteratorTraits<const char*>::value_type>();
00228   StaticAssertTypeEq<const void*,
00229       IteratorTraits<const void* const*>::value_type>();
00230 }
00231 
00232 // Tests that the element_type typedef is available in scoped_ptr and refers
00233 // to the parameter type.
00234 TEST(ScopedPtrTest, DefinesElementType) {
00235   StaticAssertTypeEq<int, ::testing::internal::scoped_ptr<int>::element_type>();
00236 }
00237 
00238 // TODO(vladl@google.com): Implement THE REST of scoped_ptr tests.
00239 
00240 TEST(GtestCheckSyntaxTest, BehavesLikeASingleStatement) {
00241   if (AlwaysFalse())
00242     GTEST_CHECK_(false) << "This should never be executed; "
00243                            "It's a compilation test only.";
00244 
00245   if (AlwaysTrue())
00246     GTEST_CHECK_(true);
00247   else
00248     ;  // NOLINT
00249 
00250   if (AlwaysFalse())
00251     ;  // NOLINT
00252   else
00253     GTEST_CHECK_(true) << "";
00254 }
00255 
00256 TEST(GtestCheckSyntaxTest, WorksWithSwitch) {
00257   switch (0) {
00258     case 1:
00259       break;
00260     default:
00261       GTEST_CHECK_(true);
00262   }
00263 
00264   switch (0)
00265     case 0:
00266       GTEST_CHECK_(true) << "Check failed in switch case";
00267 }
00268 
00269 // Verifies behavior of FormatFileLocation.
00270 TEST(FormatFileLocationTest, FormatsFileLocation) {
00271   EXPECT_PRED_FORMAT2(IsSubstring, "foo.cc", FormatFileLocation("foo.cc", 42));
00272   EXPECT_PRED_FORMAT2(IsSubstring, "42", FormatFileLocation("foo.cc", 42));
00273 }
00274 
00275 TEST(FormatFileLocationTest, FormatsUnknownFile) {
00276   EXPECT_PRED_FORMAT2(
00277       IsSubstring, "unknown file", FormatFileLocation(NULL, 42));
00278   EXPECT_PRED_FORMAT2(IsSubstring, "42", FormatFileLocation(NULL, 42));
00279 }
00280 
00281 TEST(FormatFileLocationTest, FormatsUknownLine) {
00282   EXPECT_EQ("foo.cc:", FormatFileLocation("foo.cc", -1));
00283 }
00284 
00285 TEST(FormatFileLocationTest, FormatsUknownFileAndLine) {
00286   EXPECT_EQ("unknown file:", FormatFileLocation(NULL, -1));
00287 }
00288 
00289 // Verifies behavior of FormatCompilerIndependentFileLocation.
00290 TEST(FormatCompilerIndependentFileLocationTest, FormatsFileLocation) {
00291   EXPECT_EQ("foo.cc:42", FormatCompilerIndependentFileLocation("foo.cc", 42));
00292 }
00293 
00294 TEST(FormatCompilerIndependentFileLocationTest, FormatsUknownFile) {
00295   EXPECT_EQ("unknown file:42",
00296             FormatCompilerIndependentFileLocation(NULL, 42));
00297 }
00298 
00299 TEST(FormatCompilerIndependentFileLocationTest, FormatsUknownLine) {
00300   EXPECT_EQ("foo.cc", FormatCompilerIndependentFileLocation("foo.cc", -1));
00301 }
00302 
00303 TEST(FormatCompilerIndependentFileLocationTest, FormatsUknownFileAndLine) {
00304   EXPECT_EQ("unknown file", FormatCompilerIndependentFileLocation(NULL, -1));
00305 }
00306 
00307 #if GTEST_OS_MAC || GTEST_OS_QNX
00308 void* ThreadFunc(void* data) {
00309   pthread_mutex_t* mutex = static_cast<pthread_mutex_t*>(data);
00310   pthread_mutex_lock(mutex);
00311   pthread_mutex_unlock(mutex);
00312   return NULL;
00313 }
00314 
00315 TEST(GetThreadCountTest, ReturnsCorrectValue) {
00316   EXPECT_EQ(1U, GetThreadCount());
00317   pthread_mutex_t mutex;
00318   pthread_attr_t  attr;
00319   pthread_t       thread_id;
00320 
00321   // TODO(vladl@google.com): turn mutex into internal::Mutex for automatic
00322   // destruction.
00323   pthread_mutex_init(&mutex, NULL);
00324   pthread_mutex_lock(&mutex);
00325   ASSERT_EQ(0, pthread_attr_init(&attr));
00326   ASSERT_EQ(0, pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_JOINABLE));
00327 
00328   const int status = pthread_create(&thread_id, &attr, &ThreadFunc, &mutex);
00329   ASSERT_EQ(0, pthread_attr_destroy(&attr));
00330   ASSERT_EQ(0, status);
00331   EXPECT_EQ(2U, GetThreadCount());
00332   pthread_mutex_unlock(&mutex);
00333 
00334   void* dummy;
00335   ASSERT_EQ(0, pthread_join(thread_id, &dummy));
00336 
00337 # if GTEST_OS_MAC
00338 
00339   // MacOS X may not immediately report the updated thread count after
00340   // joining a thread, causing flakiness in this test. To counter that, we
00341   // wait for up to .5 seconds for the OS to report the correct value.
00342   for (int i = 0; i < 5; ++i) {
00343     if (GetThreadCount() == 1)
00344       break;
00345 
00346     SleepMilliseconds(100);
00347   }
00348 
00349 # endif  // GTEST_OS_MAC
00350 
00351   EXPECT_EQ(1U, GetThreadCount());
00352   pthread_mutex_destroy(&mutex);
00353 }
00354 #else
00355 TEST(GetThreadCountTest, ReturnsZeroWhenUnableToCountThreads) {
00356   EXPECT_EQ(0U, GetThreadCount());
00357 }
00358 #endif  // GTEST_OS_MAC || GTEST_OS_QNX
00359 
00360 TEST(GtestCheckDeathTest, DiesWithCorrectOutputOnFailure) {
00361   const bool a_false_condition = false;
00362   const char regex[] =
00363 #ifdef _MSC_VER
00364      "gtest-port_test\\.cc\\(\\d+\\):"
00365 #elif GTEST_USES_POSIX_RE
00366      "gtest-port_test\\.cc:[0-9]+"
00367 #else
00368      "gtest-port_test\\.cc:\\d+"
00369 #endif  // _MSC_VER
00370      ".*a_false_condition.*Extra info.*";
00371 
00372   EXPECT_DEATH_IF_SUPPORTED(GTEST_CHECK_(a_false_condition) << "Extra info",
00373                             regex);
00374 }
00375 
00376 #if GTEST_HAS_DEATH_TEST
00377 
00378 TEST(GtestCheckDeathTest, LivesSilentlyOnSuccess) {
00379   EXPECT_EXIT({
00380       GTEST_CHECK_(true) << "Extra info";
00381       ::std::cerr << "Success\n";
00382       exit(0); },
00383       ::testing::ExitedWithCode(0), "Success");
00384 }
00385 
00386 #endif  // GTEST_HAS_DEATH_TEST
00387 
00388 // Verifies that Google Test choose regular expression engine appropriate to
00389 // the platform. The test will produce compiler errors in case of failure.
00390 // For simplicity, we only cover the most important platforms here.
00391 TEST(RegexEngineSelectionTest, SelectsCorrectRegexEngine) {
00392 #if GTEST_HAS_POSIX_RE
00393 
00394   EXPECT_TRUE(GTEST_USES_POSIX_RE);
00395 
00396 #else
00397 
00398   EXPECT_TRUE(GTEST_USES_SIMPLE_RE);
00399 
00400 #endif
00401 }
00402 
00403 #if GTEST_USES_POSIX_RE
00404 
00405 # if GTEST_HAS_TYPED_TEST
00406 
00407 template <typename Str>
00408 class RETest : public ::testing::Test {};
00409 
00410 // Defines StringTypes as the list of all string types that class RE
00411 // supports.
00412 typedef testing::Types<
00413     ::std::string,
00414 #  if GTEST_HAS_GLOBAL_STRING
00415     ::string,
00416 #  endif  // GTEST_HAS_GLOBAL_STRING
00417     const char*> StringTypes;
00418 
00419 TYPED_TEST_CASE(RETest, StringTypes);
00420 
00421 // Tests RE's implicit constructors.
00422 TYPED_TEST(RETest, ImplicitConstructorWorks) {
00423   const RE empty(TypeParam(""));
00424   EXPECT_STREQ("", empty.pattern());
00425 
00426   const RE simple(TypeParam("hello"));
00427   EXPECT_STREQ("hello", simple.pattern());
00428 
00429   const RE normal(TypeParam(".*(\\w+)"));
00430   EXPECT_STREQ(".*(\\w+)", normal.pattern());
00431 }
00432 
00433 // Tests that RE's constructors reject invalid regular expressions.
00434 TYPED_TEST(RETest, RejectsInvalidRegex) {
00435   EXPECT_NONFATAL_FAILURE({
00436     const RE invalid(TypeParam("?"));
00437   }, "\"?\" is not a valid POSIX Extended regular expression.");
00438 }
00439 
00440 // Tests RE::FullMatch().
00441 TYPED_TEST(RETest, FullMatchWorks) {
00442   const RE empty(TypeParam(""));
00443   EXPECT_TRUE(RE::FullMatch(TypeParam(""), empty));
00444   EXPECT_FALSE(RE::FullMatch(TypeParam("a"), empty));
00445 
00446   const RE re(TypeParam("a.*z"));
00447   EXPECT_TRUE(RE::FullMatch(TypeParam("az"), re));
00448   EXPECT_TRUE(RE::FullMatch(TypeParam("axyz"), re));
00449   EXPECT_FALSE(RE::FullMatch(TypeParam("baz"), re));
00450   EXPECT_FALSE(RE::FullMatch(TypeParam("azy"), re));
00451 }
00452 
00453 // Tests RE::PartialMatch().
00454 TYPED_TEST(RETest, PartialMatchWorks) {
00455   const RE empty(TypeParam(""));
00456   EXPECT_TRUE(RE::PartialMatch(TypeParam(""), empty));
00457   EXPECT_TRUE(RE::PartialMatch(TypeParam("a"), empty));
00458 
00459   const RE re(TypeParam("a.*z"));
00460   EXPECT_TRUE(RE::PartialMatch(TypeParam("az"), re));
00461   EXPECT_TRUE(RE::PartialMatch(TypeParam("axyz"), re));
00462   EXPECT_TRUE(RE::PartialMatch(TypeParam("baz"), re));
00463   EXPECT_TRUE(RE::PartialMatch(TypeParam("azy"), re));
00464   EXPECT_FALSE(RE::PartialMatch(TypeParam("zza"), re));
00465 }
00466 
00467 # endif  // GTEST_HAS_TYPED_TEST
00468 
00469 #elif GTEST_USES_SIMPLE_RE
00470 
00471 TEST(IsInSetTest, NulCharIsNotInAnySet) {
00472   EXPECT_FALSE(IsInSet('\0', ""));
00473   EXPECT_FALSE(IsInSet('\0', "\0"));
00474   EXPECT_FALSE(IsInSet('\0', "a"));
00475 }
00476 
00477 TEST(IsInSetTest, WorksForNonNulChars) {
00478   EXPECT_FALSE(IsInSet('a', "Ab"));
00479   EXPECT_FALSE(IsInSet('c', ""));
00480 
00481   EXPECT_TRUE(IsInSet('b', "bcd"));
00482   EXPECT_TRUE(IsInSet('b', "ab"));
00483 }
00484 
00485 TEST(IsAsciiDigitTest, IsFalseForNonDigit) {
00486   EXPECT_FALSE(IsAsciiDigit('\0'));
00487   EXPECT_FALSE(IsAsciiDigit(' '));
00488   EXPECT_FALSE(IsAsciiDigit('+'));
00489   EXPECT_FALSE(IsAsciiDigit('-'));
00490   EXPECT_FALSE(IsAsciiDigit('.'));
00491   EXPECT_FALSE(IsAsciiDigit('a'));
00492 }
00493 
00494 TEST(IsAsciiDigitTest, IsTrueForDigit) {
00495   EXPECT_TRUE(IsAsciiDigit('0'));
00496   EXPECT_TRUE(IsAsciiDigit('1'));
00497   EXPECT_TRUE(IsAsciiDigit('5'));
00498   EXPECT_TRUE(IsAsciiDigit('9'));
00499 }
00500 
00501 TEST(IsAsciiPunctTest, IsFalseForNonPunct) {
00502   EXPECT_FALSE(IsAsciiPunct('\0'));
00503   EXPECT_FALSE(IsAsciiPunct(' '));
00504   EXPECT_FALSE(IsAsciiPunct('\n'));
00505   EXPECT_FALSE(IsAsciiPunct('a'));
00506   EXPECT_FALSE(IsAsciiPunct('0'));
00507 }
00508 
00509 TEST(IsAsciiPunctTest, IsTrueForPunct) {
00510   for (const char* p = "^-!\"#$%&'()*+,./:;<=>?@[\\]_`{|}~"; *p; p++) {
00511     EXPECT_PRED1(IsAsciiPunct, *p);
00512   }
00513 }
00514 
00515 TEST(IsRepeatTest, IsFalseForNonRepeatChar) {
00516   EXPECT_FALSE(IsRepeat('\0'));
00517   EXPECT_FALSE(IsRepeat(' '));
00518   EXPECT_FALSE(IsRepeat('a'));
00519   EXPECT_FALSE(IsRepeat('1'));
00520   EXPECT_FALSE(IsRepeat('-'));
00521 }
00522 
00523 TEST(IsRepeatTest, IsTrueForRepeatChar) {
00524   EXPECT_TRUE(IsRepeat('?'));
00525   EXPECT_TRUE(IsRepeat('*'));
00526   EXPECT_TRUE(IsRepeat('+'));
00527 }
00528 
00529 TEST(IsAsciiWhiteSpaceTest, IsFalseForNonWhiteSpace) {
00530   EXPECT_FALSE(IsAsciiWhiteSpace('\0'));
00531   EXPECT_FALSE(IsAsciiWhiteSpace('a'));
00532   EXPECT_FALSE(IsAsciiWhiteSpace('1'));
00533   EXPECT_FALSE(IsAsciiWhiteSpace('+'));
00534   EXPECT_FALSE(IsAsciiWhiteSpace('_'));
00535 }
00536 
00537 TEST(IsAsciiWhiteSpaceTest, IsTrueForWhiteSpace) {
00538   EXPECT_TRUE(IsAsciiWhiteSpace(' '));
00539   EXPECT_TRUE(IsAsciiWhiteSpace('\n'));
00540   EXPECT_TRUE(IsAsciiWhiteSpace('\r'));
00541   EXPECT_TRUE(IsAsciiWhiteSpace('\t'));
00542   EXPECT_TRUE(IsAsciiWhiteSpace('\v'));
00543   EXPECT_TRUE(IsAsciiWhiteSpace('\f'));
00544 }
00545 
00546 TEST(IsAsciiWordCharTest, IsFalseForNonWordChar) {
00547   EXPECT_FALSE(IsAsciiWordChar('\0'));
00548   EXPECT_FALSE(IsAsciiWordChar('+'));
00549   EXPECT_FALSE(IsAsciiWordChar('.'));
00550   EXPECT_FALSE(IsAsciiWordChar(' '));
00551   EXPECT_FALSE(IsAsciiWordChar('\n'));
00552 }
00553 
00554 TEST(IsAsciiWordCharTest, IsTrueForLetter) {
00555   EXPECT_TRUE(IsAsciiWordChar('a'));
00556   EXPECT_TRUE(IsAsciiWordChar('b'));
00557   EXPECT_TRUE(IsAsciiWordChar('A'));
00558   EXPECT_TRUE(IsAsciiWordChar('Z'));
00559 }
00560 
00561 TEST(IsAsciiWordCharTest, IsTrueForDigit) {
00562   EXPECT_TRUE(IsAsciiWordChar('0'));
00563   EXPECT_TRUE(IsAsciiWordChar('1'));
00564   EXPECT_TRUE(IsAsciiWordChar('7'));
00565   EXPECT_TRUE(IsAsciiWordChar('9'));
00566 }
00567 
00568 TEST(IsAsciiWordCharTest, IsTrueForUnderscore) {
00569   EXPECT_TRUE(IsAsciiWordChar('_'));
00570 }
00571 
00572 TEST(IsValidEscapeTest, IsFalseForNonPrintable) {
00573   EXPECT_FALSE(IsValidEscape('\0'));
00574   EXPECT_FALSE(IsValidEscape('\007'));
00575 }
00576 
00577 TEST(IsValidEscapeTest, IsFalseForDigit) {
00578   EXPECT_FALSE(IsValidEscape('0'));
00579   EXPECT_FALSE(IsValidEscape('9'));
00580 }
00581 
00582 TEST(IsValidEscapeTest, IsFalseForWhiteSpace) {
00583   EXPECT_FALSE(IsValidEscape(' '));
00584   EXPECT_FALSE(IsValidEscape('\n'));
00585 }
00586 
00587 TEST(IsValidEscapeTest, IsFalseForSomeLetter) {
00588   EXPECT_FALSE(IsValidEscape('a'));
00589   EXPECT_FALSE(IsValidEscape('Z'));
00590 }
00591 
00592 TEST(IsValidEscapeTest, IsTrueForPunct) {
00593   EXPECT_TRUE(IsValidEscape('.'));
00594   EXPECT_TRUE(IsValidEscape('-'));
00595   EXPECT_TRUE(IsValidEscape('^'));
00596   EXPECT_TRUE(IsValidEscape('$'));
00597   EXPECT_TRUE(IsValidEscape('('));
00598   EXPECT_TRUE(IsValidEscape(']'));
00599   EXPECT_TRUE(IsValidEscape('{'));
00600   EXPECT_TRUE(IsValidEscape('|'));
00601 }
00602 
00603 TEST(IsValidEscapeTest, IsTrueForSomeLetter) {
00604   EXPECT_TRUE(IsValidEscape('d'));
00605   EXPECT_TRUE(IsValidEscape('D'));
00606   EXPECT_TRUE(IsValidEscape('s'));
00607   EXPECT_TRUE(IsValidEscape('S'));
00608   EXPECT_TRUE(IsValidEscape('w'));
00609   EXPECT_TRUE(IsValidEscape('W'));
00610 }
00611 
00612 TEST(AtomMatchesCharTest, EscapedPunct) {
00613   EXPECT_FALSE(AtomMatchesChar(true, '\\', '\0'));
00614   EXPECT_FALSE(AtomMatchesChar(true, '\\', ' '));
00615   EXPECT_FALSE(AtomMatchesChar(true, '_', '.'));
00616   EXPECT_FALSE(AtomMatchesChar(true, '.', 'a'));
00617 
00618   EXPECT_TRUE(AtomMatchesChar(true, '\\', '\\'));
00619   EXPECT_TRUE(AtomMatchesChar(true, '_', '_'));
00620   EXPECT_TRUE(AtomMatchesChar(true, '+', '+'));
00621   EXPECT_TRUE(AtomMatchesChar(true, '.', '.'));
00622 }
00623 
00624 TEST(AtomMatchesCharTest, Escaped_d) {
00625   EXPECT_FALSE(AtomMatchesChar(true, 'd', '\0'));
00626   EXPECT_FALSE(AtomMatchesChar(true, 'd', 'a'));
00627   EXPECT_FALSE(AtomMatchesChar(true, 'd', '.'));
00628 
00629   EXPECT_TRUE(AtomMatchesChar(true, 'd', '0'));
00630   EXPECT_TRUE(AtomMatchesChar(true, 'd', '9'));
00631 }
00632 
00633 TEST(AtomMatchesCharTest, Escaped_D) {
00634   EXPECT_FALSE(AtomMatchesChar(true, 'D', '0'));
00635   EXPECT_FALSE(AtomMatchesChar(true, 'D', '9'));
00636 
00637   EXPECT_TRUE(AtomMatchesChar(true, 'D', '\0'));
00638   EXPECT_TRUE(AtomMatchesChar(true, 'D', 'a'));
00639   EXPECT_TRUE(AtomMatchesChar(true, 'D', '-'));
00640 }
00641 
00642 TEST(AtomMatchesCharTest, Escaped_s) {
00643   EXPECT_FALSE(AtomMatchesChar(true, 's', '\0'));
00644   EXPECT_FALSE(AtomMatchesChar(true, 's', 'a'));
00645   EXPECT_FALSE(AtomMatchesChar(true, 's', '.'));
00646   EXPECT_FALSE(AtomMatchesChar(true, 's', '9'));
00647 
00648   EXPECT_TRUE(AtomMatchesChar(true, 's', ' '));
00649   EXPECT_TRUE(AtomMatchesChar(true, 's', '\n'));
00650   EXPECT_TRUE(AtomMatchesChar(true, 's', '\t'));
00651 }
00652 
00653 TEST(AtomMatchesCharTest, Escaped_S) {
00654   EXPECT_FALSE(AtomMatchesChar(true, 'S', ' '));
00655   EXPECT_FALSE(AtomMatchesChar(true, 'S', '\r'));
00656 
00657   EXPECT_TRUE(AtomMatchesChar(true, 'S', '\0'));
00658   EXPECT_TRUE(AtomMatchesChar(true, 'S', 'a'));
00659   EXPECT_TRUE(AtomMatchesChar(true, 'S', '9'));
00660 }
00661 
00662 TEST(AtomMatchesCharTest, Escaped_w) {
00663   EXPECT_FALSE(AtomMatchesChar(true, 'w', '\0'));
00664   EXPECT_FALSE(AtomMatchesChar(true, 'w', '+'));
00665   EXPECT_FALSE(AtomMatchesChar(true, 'w', ' '));
00666   EXPECT_FALSE(AtomMatchesChar(true, 'w', '\n'));
00667 
00668   EXPECT_TRUE(AtomMatchesChar(true, 'w', '0'));
00669   EXPECT_TRUE(AtomMatchesChar(true, 'w', 'b'));
00670   EXPECT_TRUE(AtomMatchesChar(true, 'w', 'C'));
00671   EXPECT_TRUE(AtomMatchesChar(true, 'w', '_'));
00672 }
00673 
00674 TEST(AtomMatchesCharTest, Escaped_W) {
00675   EXPECT_FALSE(AtomMatchesChar(true, 'W', 'A'));
00676   EXPECT_FALSE(AtomMatchesChar(true, 'W', 'b'));
00677   EXPECT_FALSE(AtomMatchesChar(true, 'W', '9'));
00678   EXPECT_FALSE(AtomMatchesChar(true, 'W', '_'));
00679 
00680   EXPECT_TRUE(AtomMatchesChar(true, 'W', '\0'));
00681   EXPECT_TRUE(AtomMatchesChar(true, 'W', '*'));
00682   EXPECT_TRUE(AtomMatchesChar(true, 'W', '\n'));
00683 }
00684 
00685 TEST(AtomMatchesCharTest, EscapedWhiteSpace) {
00686   EXPECT_FALSE(AtomMatchesChar(true, 'f', '\0'));
00687   EXPECT_FALSE(AtomMatchesChar(true, 'f', '\n'));
00688   EXPECT_FALSE(AtomMatchesChar(true, 'n', '\0'));
00689   EXPECT_FALSE(AtomMatchesChar(true, 'n', '\r'));
00690   EXPECT_FALSE(AtomMatchesChar(true, 'r', '\0'));
00691   EXPECT_FALSE(AtomMatchesChar(true, 'r', 'a'));
00692   EXPECT_FALSE(AtomMatchesChar(true, 't', '\0'));
00693   EXPECT_FALSE(AtomMatchesChar(true, 't', 't'));
00694   EXPECT_FALSE(AtomMatchesChar(true, 'v', '\0'));
00695   EXPECT_FALSE(AtomMatchesChar(true, 'v', '\f'));
00696 
00697   EXPECT_TRUE(AtomMatchesChar(true, 'f', '\f'));
00698   EXPECT_TRUE(AtomMatchesChar(true, 'n', '\n'));
00699   EXPECT_TRUE(AtomMatchesChar(true, 'r', '\r'));
00700   EXPECT_TRUE(AtomMatchesChar(true, 't', '\t'));
00701   EXPECT_TRUE(AtomMatchesChar(true, 'v', '\v'));
00702 }
00703 
00704 TEST(AtomMatchesCharTest, UnescapedDot) {
00705   EXPECT_FALSE(AtomMatchesChar(false, '.', '\n'));
00706 
00707   EXPECT_TRUE(AtomMatchesChar(false, '.', '\0'));
00708   EXPECT_TRUE(AtomMatchesChar(false, '.', '.'));
00709   EXPECT_TRUE(AtomMatchesChar(false, '.', 'a'));
00710   EXPECT_TRUE(AtomMatchesChar(false, '.', ' '));
00711 }
00712 
00713 TEST(AtomMatchesCharTest, UnescapedChar) {
00714   EXPECT_FALSE(AtomMatchesChar(false, 'a', '\0'));
00715   EXPECT_FALSE(AtomMatchesChar(false, 'a', 'b'));
00716   EXPECT_FALSE(AtomMatchesChar(false, '$', 'a'));
00717 
00718   EXPECT_TRUE(AtomMatchesChar(false, '$', '$'));
00719   EXPECT_TRUE(AtomMatchesChar(false, '5', '5'));
00720   EXPECT_TRUE(AtomMatchesChar(false, 'Z', 'Z'));
00721 }
00722 
00723 TEST(ValidateRegexTest, GeneratesFailureAndReturnsFalseForInvalid) {
00724   EXPECT_NONFATAL_FAILURE(ASSERT_FALSE(ValidateRegex(NULL)),
00725                           "NULL is not a valid simple regular expression");
00726   EXPECT_NONFATAL_FAILURE(
00727       ASSERT_FALSE(ValidateRegex("a\\")),
00728       "Syntax error at index 1 in simple regular expression \"a\\\": ");
00729   EXPECT_NONFATAL_FAILURE(ASSERT_FALSE(ValidateRegex("a\\")),
00730                           "'\\' cannot appear at the end");
00731   EXPECT_NONFATAL_FAILURE(ASSERT_FALSE(ValidateRegex("\\n\\")),
00732                           "'\\' cannot appear at the end");
00733   EXPECT_NONFATAL_FAILURE(ASSERT_FALSE(ValidateRegex("\\s\\hb")),
00734                           "invalid escape sequence \"\\h\"");
00735   EXPECT_NONFATAL_FAILURE(ASSERT_FALSE(ValidateRegex("^^")),
00736                           "'^' can only appear at the beginning");
00737   EXPECT_NONFATAL_FAILURE(ASSERT_FALSE(ValidateRegex(".*^b")),
00738                           "'^' can only appear at the beginning");
00739   EXPECT_NONFATAL_FAILURE(ASSERT_FALSE(ValidateRegex("$$")),
00740                           "'$' can only appear at the end");
00741   EXPECT_NONFATAL_FAILURE(ASSERT_FALSE(ValidateRegex("^$a")),
00742                           "'$' can only appear at the end");
00743   EXPECT_NONFATAL_FAILURE(ASSERT_FALSE(ValidateRegex("a(b")),
00744                           "'(' is unsupported");
00745   EXPECT_NONFATAL_FAILURE(ASSERT_FALSE(ValidateRegex("ab)")),
00746                           "')' is unsupported");
00747   EXPECT_NONFATAL_FAILURE(ASSERT_FALSE(ValidateRegex("[ab")),
00748                           "'[' is unsupported");
00749   EXPECT_NONFATAL_FAILURE(ASSERT_FALSE(ValidateRegex("a{2")),
00750                           "'{' is unsupported");
00751   EXPECT_NONFATAL_FAILURE(ASSERT_FALSE(ValidateRegex("?")),
00752                           "'?' can only follow a repeatable token");
00753   EXPECT_NONFATAL_FAILURE(ASSERT_FALSE(ValidateRegex("^*")),
00754                           "'*' can only follow a repeatable token");
00755   EXPECT_NONFATAL_FAILURE(ASSERT_FALSE(ValidateRegex("5*+")),
00756                           "'+' can only follow a repeatable token");
00757 }
00758 
00759 TEST(ValidateRegexTest, ReturnsTrueForValid) {
00760   EXPECT_TRUE(ValidateRegex(""));
00761   EXPECT_TRUE(ValidateRegex("a"));
00762   EXPECT_TRUE(ValidateRegex(".*"));
00763   EXPECT_TRUE(ValidateRegex("^a_+"));
00764   EXPECT_TRUE(ValidateRegex("^a\\t\\&?"));
00765   EXPECT_TRUE(ValidateRegex("09*$"));
00766   EXPECT_TRUE(ValidateRegex("^Z$"));
00767   EXPECT_TRUE(ValidateRegex("a\\^Z\\$\\(\\)\\|\\[\\]\\{\\}"));
00768 }
00769 
00770 TEST(MatchRepetitionAndRegexAtHeadTest, WorksForZeroOrOne) {
00771   EXPECT_FALSE(MatchRepetitionAndRegexAtHead(false, 'a', '?', "a", "ba"));
00772   // Repeating more than once.
00773   EXPECT_FALSE(MatchRepetitionAndRegexAtHead(false, 'a', '?', "b", "aab"));
00774 
00775   // Repeating zero times.
00776   EXPECT_TRUE(MatchRepetitionAndRegexAtHead(false, 'a', '?', "b", "ba"));
00777   // Repeating once.
00778   EXPECT_TRUE(MatchRepetitionAndRegexAtHead(false, 'a', '?', "b", "ab"));
00779   EXPECT_TRUE(MatchRepetitionAndRegexAtHead(false, '#', '?', ".", "##"));
00780 }
00781 
00782 TEST(MatchRepetitionAndRegexAtHeadTest, WorksForZeroOrMany) {
00783   EXPECT_FALSE(MatchRepetitionAndRegexAtHead(false, '.', '*', "a$", "baab"));
00784 
00785   // Repeating zero times.
00786   EXPECT_TRUE(MatchRepetitionAndRegexAtHead(false, '.', '*', "b", "bc"));
00787   // Repeating once.
00788   EXPECT_TRUE(MatchRepetitionAndRegexAtHead(false, '.', '*', "b", "abc"));
00789   // Repeating more than once.
00790   EXPECT_TRUE(MatchRepetitionAndRegexAtHead(true, 'w', '*', "-", "ab_1-g"));
00791 }
00792 
00793 TEST(MatchRepetitionAndRegexAtHeadTest, WorksForOneOrMany) {
00794   EXPECT_FALSE(MatchRepetitionAndRegexAtHead(false, '.', '+', "a$", "baab"));
00795   // Repeating zero times.
00796   EXPECT_FALSE(MatchRepetitionAndRegexAtHead(false, '.', '+', "b", "bc"));
00797 
00798   // Repeating once.
00799   EXPECT_TRUE(MatchRepetitionAndRegexAtHead(false, '.', '+', "b", "abc"));
00800   // Repeating more than once.
00801   EXPECT_TRUE(MatchRepetitionAndRegexAtHead(true, 'w', '+', "-", "ab_1-g"));
00802 }
00803 
00804 TEST(MatchRegexAtHeadTest, ReturnsTrueForEmptyRegex) {
00805   EXPECT_TRUE(MatchRegexAtHead("", ""));
00806   EXPECT_TRUE(MatchRegexAtHead("", "ab"));
00807 }
00808 
00809 TEST(MatchRegexAtHeadTest, WorksWhenDollarIsInRegex) {
00810   EXPECT_FALSE(MatchRegexAtHead("$", "a"));
00811 
00812   EXPECT_TRUE(MatchRegexAtHead("$", ""));
00813   EXPECT_TRUE(MatchRegexAtHead("a$", "a"));
00814 }
00815 
00816 TEST(MatchRegexAtHeadTest, WorksWhenRegexStartsWithEscapeSequence) {
00817   EXPECT_FALSE(MatchRegexAtHead("\\w", "+"));
00818   EXPECT_FALSE(MatchRegexAtHead("\\W", "ab"));
00819 
00820   EXPECT_TRUE(MatchRegexAtHead("\\sa", "\nab"));
00821   EXPECT_TRUE(MatchRegexAtHead("\\d", "1a"));
00822 }
00823 
00824 TEST(MatchRegexAtHeadTest, WorksWhenRegexStartsWithRepetition) {
00825   EXPECT_FALSE(MatchRegexAtHead(".+a", "abc"));
00826   EXPECT_FALSE(MatchRegexAtHead("a?b", "aab"));
00827 
00828   EXPECT_TRUE(MatchRegexAtHead(".*a", "bc12-ab"));
00829   EXPECT_TRUE(MatchRegexAtHead("a?b", "b"));
00830   EXPECT_TRUE(MatchRegexAtHead("a?b", "ab"));
00831 }
00832 
00833 TEST(MatchRegexAtHeadTest,
00834      WorksWhenRegexStartsWithRepetionOfEscapeSequence) {
00835   EXPECT_FALSE(MatchRegexAtHead("\\.+a", "abc"));
00836   EXPECT_FALSE(MatchRegexAtHead("\\s?b", "  b"));
00837 
00838   EXPECT_TRUE(MatchRegexAtHead("\\(*a", "((((ab"));
00839   EXPECT_TRUE(MatchRegexAtHead("\\^?b", "^b"));
00840   EXPECT_TRUE(MatchRegexAtHead("\\\\?b", "b"));
00841   EXPECT_TRUE(MatchRegexAtHead("\\\\?b", "\\b"));
00842 }
00843 
00844 TEST(MatchRegexAtHeadTest, MatchesSequentially) {
00845   EXPECT_FALSE(MatchRegexAtHead("ab.*c", "acabc"));
00846 
00847   EXPECT_TRUE(MatchRegexAtHead("ab.*c", "ab-fsc"));
00848 }
00849 
00850 TEST(MatchRegexAnywhereTest, ReturnsFalseWhenStringIsNull) {
00851   EXPECT_FALSE(MatchRegexAnywhere("", NULL));
00852 }
00853 
00854 TEST(MatchRegexAnywhereTest, WorksWhenRegexStartsWithCaret) {
00855   EXPECT_FALSE(MatchRegexAnywhere("^a", "ba"));
00856   EXPECT_FALSE(MatchRegexAnywhere("^$", "a"));
00857 
00858   EXPECT_TRUE(MatchRegexAnywhere("^a", "ab"));
00859   EXPECT_TRUE(MatchRegexAnywhere("^", "ab"));
00860   EXPECT_TRUE(MatchRegexAnywhere("^$", ""));
00861 }
00862 
00863 TEST(MatchRegexAnywhereTest, ReturnsFalseWhenNoMatch) {
00864   EXPECT_FALSE(MatchRegexAnywhere("a", "bcde123"));
00865   EXPECT_FALSE(MatchRegexAnywhere("a.+a", "--aa88888888"));
00866 }
00867 
00868 TEST(MatchRegexAnywhereTest, ReturnsTrueWhenMatchingPrefix) {
00869   EXPECT_TRUE(MatchRegexAnywhere("\\w+", "ab1_ - 5"));
00870   EXPECT_TRUE(MatchRegexAnywhere(".*=", "="));
00871   EXPECT_TRUE(MatchRegexAnywhere("x.*ab?.*bc", "xaaabc"));
00872 }
00873 
00874 TEST(MatchRegexAnywhereTest, ReturnsTrueWhenMatchingNonPrefix) {
00875   EXPECT_TRUE(MatchRegexAnywhere("\\w+", "$$$ ab1_ - 5"));
00876   EXPECT_TRUE(MatchRegexAnywhere("\\.+=", "=  ...="));
00877 }
00878 
00879 // Tests RE's implicit constructors.
00880 TEST(RETest, ImplicitConstructorWorks) {
00881   const RE empty("");
00882   EXPECT_STREQ("", empty.pattern());
00883 
00884   const RE simple("hello");
00885   EXPECT_STREQ("hello", simple.pattern());
00886 }
00887 
00888 // Tests that RE's constructors reject invalid regular expressions.
00889 TEST(RETest, RejectsInvalidRegex) {
00890   EXPECT_NONFATAL_FAILURE({
00891     const RE normal(NULL);
00892   }, "NULL is not a valid simple regular expression");
00893 
00894   EXPECT_NONFATAL_FAILURE({
00895     const RE normal(".*(\\w+");
00896   }, "'(' is unsupported");
00897 
00898   EXPECT_NONFATAL_FAILURE({
00899     const RE invalid("^?");
00900   }, "'?' can only follow a repeatable token");
00901 }
00902 
00903 // Tests RE::FullMatch().
00904 TEST(RETest, FullMatchWorks) {
00905   const RE empty("");
00906   EXPECT_TRUE(RE::FullMatch("", empty));
00907   EXPECT_FALSE(RE::FullMatch("a", empty));
00908 
00909   const RE re1("a");
00910   EXPECT_TRUE(RE::FullMatch("a", re1));
00911 
00912   const RE re("a.*z");
00913   EXPECT_TRUE(RE::FullMatch("az", re));
00914   EXPECT_TRUE(RE::FullMatch("axyz", re));
00915   EXPECT_FALSE(RE::FullMatch("baz", re));
00916   EXPECT_FALSE(RE::FullMatch("azy", re));
00917 }
00918 
00919 // Tests RE::PartialMatch().
00920 TEST(RETest, PartialMatchWorks) {
00921   const RE empty("");
00922   EXPECT_TRUE(RE::PartialMatch("", empty));
00923   EXPECT_TRUE(RE::PartialMatch("a", empty));
00924 
00925   const RE re("a.*z");
00926   EXPECT_TRUE(RE::PartialMatch("az", re));
00927   EXPECT_TRUE(RE::PartialMatch("axyz", re));
00928   EXPECT_TRUE(RE::PartialMatch("baz", re));
00929   EXPECT_TRUE(RE::PartialMatch("azy", re));
00930   EXPECT_FALSE(RE::PartialMatch("zza", re));
00931 }
00932 
00933 #endif  // GTEST_USES_POSIX_RE
00934 
00935 #if !GTEST_OS_WINDOWS_MOBILE
00936 
00937 TEST(CaptureTest, CapturesStdout) {
00938   CaptureStdout();
00939   fprintf(stdout, "abc");
00940   EXPECT_STREQ("abc", GetCapturedStdout().c_str());
00941 
00942   CaptureStdout();
00943   fprintf(stdout, "def%cghi", '\0');
00944   EXPECT_EQ(::std::string("def\0ghi", 7), ::std::string(GetCapturedStdout()));
00945 }
00946 
00947 TEST(CaptureTest, CapturesStderr) {
00948   CaptureStderr();
00949   fprintf(stderr, "jkl");
00950   EXPECT_STREQ("jkl", GetCapturedStderr().c_str());
00951 
00952   CaptureStderr();
00953   fprintf(stderr, "jkl%cmno", '\0');
00954   EXPECT_EQ(::std::string("jkl\0mno", 7), ::std::string(GetCapturedStderr()));
00955 }
00956 
00957 // Tests that stdout and stderr capture don't interfere with each other.
00958 TEST(CaptureTest, CapturesStdoutAndStderr) {
00959   CaptureStdout();
00960   CaptureStderr();
00961   fprintf(stdout, "pqr");
00962   fprintf(stderr, "stu");
00963   EXPECT_STREQ("pqr", GetCapturedStdout().c_str());
00964   EXPECT_STREQ("stu", GetCapturedStderr().c_str());
00965 }
00966 
00967 TEST(CaptureDeathTest, CannotReenterStdoutCapture) {
00968   CaptureStdout();
00969   EXPECT_DEATH_IF_SUPPORTED(CaptureStdout(),
00970                             "Only one stdout capturer can exist at a time");
00971   GetCapturedStdout();
00972 
00973   // We cannot test stderr capturing using death tests as they use it
00974   // themselves.
00975 }
00976 
00977 #endif  // !GTEST_OS_WINDOWS_MOBILE
00978 
00979 TEST(ThreadLocalTest, DefaultConstructorInitializesToDefaultValues) {
00980   ThreadLocal<int> t1;
00981   EXPECT_EQ(0, t1.get());
00982 
00983   ThreadLocal<void*> t2;
00984   EXPECT_TRUE(t2.get() == NULL);
00985 }
00986 
00987 TEST(ThreadLocalTest, SingleParamConstructorInitializesToParam) {
00988   ThreadLocal<int> t1(123);
00989   EXPECT_EQ(123, t1.get());
00990 
00991   int i = 0;
00992   ThreadLocal<int*> t2(&i);
00993   EXPECT_EQ(&i, t2.get());
00994 }
00995 
00996 class NoDefaultContructor {
00997  public:
00998   explicit NoDefaultContructor(const char*) {}
00999   NoDefaultContructor(const NoDefaultContructor&) {}
01000 };
01001 
01002 TEST(ThreadLocalTest, ValueDefaultContructorIsNotRequiredForParamVersion) {
01003   ThreadLocal<NoDefaultContructor> bar(NoDefaultContructor("foo"));
01004   bar.pointer();
01005 }
01006 
01007 TEST(ThreadLocalTest, GetAndPointerReturnSameValue) {
01008   ThreadLocal<std::string> thread_local_string;
01009 
01010   EXPECT_EQ(thread_local_string.pointer(), &(thread_local_string.get()));
01011 
01012   // Verifies the condition still holds after calling set.
01013   thread_local_string.set("foo");
01014   EXPECT_EQ(thread_local_string.pointer(), &(thread_local_string.get()));
01015 }
01016 
01017 TEST(ThreadLocalTest, PointerAndConstPointerReturnSameValue) {
01018   ThreadLocal<std::string> thread_local_string;
01019   const ThreadLocal<std::string>& const_thread_local_string =
01020       thread_local_string;
01021 
01022   EXPECT_EQ(thread_local_string.pointer(), const_thread_local_string.pointer());
01023 
01024   thread_local_string.set("foo");
01025   EXPECT_EQ(thread_local_string.pointer(), const_thread_local_string.pointer());
01026 }
01027 
01028 #if GTEST_IS_THREADSAFE
01029 
01030 void AddTwo(int* param) { *param += 2; }
01031 
01032 TEST(ThreadWithParamTest, ConstructorExecutesThreadFunc) {
01033   int i = 40;
01034   ThreadWithParam<int*> thread(&AddTwo, &i, NULL);
01035   thread.Join();
01036   EXPECT_EQ(42, i);
01037 }
01038 
01039 TEST(MutexDeathTest, AssertHeldShouldAssertWhenNotLocked) {
01040   // AssertHeld() is flaky only in the presence of multiple threads accessing
01041   // the lock. In this case, the test is robust.
01042   EXPECT_DEATH_IF_SUPPORTED({
01043     Mutex m;
01044     { MutexLock lock(&m); }
01045     m.AssertHeld();
01046   },
01047   "thread .*hold");
01048 }
01049 
01050 TEST(MutexTest, AssertHeldShouldNotAssertWhenLocked) {
01051   Mutex m;
01052   MutexLock lock(&m);
01053   m.AssertHeld();
01054 }
01055 
01056 class AtomicCounterWithMutex {
01057  public:
01058   explicit AtomicCounterWithMutex(Mutex* mutex) :
01059     value_(0), mutex_(mutex), random_(42) {}
01060 
01061   void Increment() {
01062     MutexLock lock(mutex_);
01063     int temp = value_;
01064     {
01065       // We need to put up a memory barrier to prevent reads and writes to
01066       // value_ rearranged with the call to SleepMilliseconds when observed
01067       // from other threads.
01068 #if GTEST_HAS_PTHREAD
01069       // On POSIX, locking a mutex puts up a memory barrier.  We cannot use
01070       // Mutex and MutexLock here or rely on their memory barrier
01071       // functionality as we are testing them here.
01072       pthread_mutex_t memory_barrier_mutex;
01073       GTEST_CHECK_POSIX_SUCCESS_(
01074           pthread_mutex_init(&memory_barrier_mutex, NULL));
01075       GTEST_CHECK_POSIX_SUCCESS_(pthread_mutex_lock(&memory_barrier_mutex));
01076 
01077       SleepMilliseconds(random_.Generate(30));
01078 
01079       GTEST_CHECK_POSIX_SUCCESS_(pthread_mutex_unlock(&memory_barrier_mutex));
01080       GTEST_CHECK_POSIX_SUCCESS_(pthread_mutex_destroy(&memory_barrier_mutex));
01081 #elif GTEST_OS_WINDOWS
01082       // On Windows, performing an interlocked access puts up a memory barrier.
01083       volatile LONG dummy = 0;
01084       ::InterlockedIncrement(&dummy);
01085       SleepMilliseconds(random_.Generate(30));
01086       ::InterlockedIncrement(&dummy);
01087 #else
01088 # error "Memory barrier not implemented on this platform."
01089 #endif  // GTEST_HAS_PTHREAD
01090     }
01091     value_ = temp + 1;
01092   }
01093   int value() const { return value_; }
01094 
01095  private:
01096   volatile int value_;
01097   Mutex* const mutex_;  // Protects value_.
01098   Random       random_;
01099 };
01100 
01101 void CountingThreadFunc(pair<AtomicCounterWithMutex*, int> param) {
01102   for (int i = 0; i < param.second; ++i)
01103       param.first->Increment();
01104 }
01105 
01106 // Tests that the mutex only lets one thread at a time to lock it.
01107 TEST(MutexTest, OnlyOneThreadCanLockAtATime) {
01108   Mutex mutex;
01109   AtomicCounterWithMutex locked_counter(&mutex);
01110 
01111   typedef ThreadWithParam<pair<AtomicCounterWithMutex*, int> > ThreadType;
01112   const int kCycleCount = 20;
01113   const int kThreadCount = 7;
01114   scoped_ptr<ThreadType> counting_threads[kThreadCount];
01115   Notification threads_can_start;
01116   // Creates and runs kThreadCount threads that increment locked_counter
01117   // kCycleCount times each.
01118   for (int i = 0; i < kThreadCount; ++i) {
01119     counting_threads[i].reset(new ThreadType(&CountingThreadFunc,
01120                                              make_pair(&locked_counter,
01121                                                        kCycleCount),
01122                                              &threads_can_start));
01123   }
01124   threads_can_start.Notify();
01125   for (int i = 0; i < kThreadCount; ++i)
01126     counting_threads[i]->Join();
01127 
01128   // If the mutex lets more than one thread to increment the counter at a
01129   // time, they are likely to encounter a race condition and have some
01130   // increments overwritten, resulting in the lower then expected counter
01131   // value.
01132   EXPECT_EQ(kCycleCount * kThreadCount, locked_counter.value());
01133 }
01134 
01135 template <typename T>
01136 void RunFromThread(void (func)(T), T param) {
01137   ThreadWithParam<T> thread(func, param, NULL);
01138   thread.Join();
01139 }
01140 
01141 void RetrieveThreadLocalValue(
01142     pair<ThreadLocal<std::string>*, std::string*> param) {
01143   *param.second = param.first->get();
01144 }
01145 
01146 TEST(ThreadLocalTest, ParameterizedConstructorSetsDefault) {
01147   ThreadLocal<std::string> thread_local_string("foo");
01148   EXPECT_STREQ("foo", thread_local_string.get().c_str());
01149 
01150   thread_local_string.set("bar");
01151   EXPECT_STREQ("bar", thread_local_string.get().c_str());
01152 
01153   std::string result;
01154   RunFromThread(&RetrieveThreadLocalValue,
01155                 make_pair(&thread_local_string, &result));
01156   EXPECT_STREQ("foo", result.c_str());
01157 }
01158 
01159 // Keeps track of whether of destructors being called on instances of
01160 // DestructorTracker.  On Windows, waits for the destructor call reports.
01161 class DestructorCall {
01162  public:
01163   DestructorCall() {
01164     invoked_ = false;
01165 #if GTEST_OS_WINDOWS
01166     wait_event_.Reset(::CreateEvent(NULL, TRUE, FALSE, NULL));
01167     GTEST_CHECK_(wait_event_.Get() != NULL);
01168 #endif
01169   }
01170 
01171   bool CheckDestroyed() const {
01172 #if GTEST_OS_WINDOWS
01173     if (::WaitForSingleObject(wait_event_.Get(), 1000) != WAIT_OBJECT_0)
01174       return false;
01175 #endif
01176     return invoked_;
01177   }
01178 
01179   void ReportDestroyed() {
01180     invoked_ = true;
01181 #if GTEST_OS_WINDOWS
01182     ::SetEvent(wait_event_.Get());
01183 #endif
01184   }
01185 
01186   static std::vector<DestructorCall*>& List() { return *list_; }
01187 
01188   static void ResetList() {
01189     for (size_t i = 0; i < list_->size(); ++i) {
01190       delete list_->at(i);
01191     }
01192     list_->clear();
01193   }
01194 
01195  private:
01196   bool invoked_;
01197 #if GTEST_OS_WINDOWS
01198   AutoHandle wait_event_;
01199 #endif
01200   static std::vector<DestructorCall*>* const list_;
01201 
01202   GTEST_DISALLOW_COPY_AND_ASSIGN_(DestructorCall);
01203 };
01204 
01205 std::vector<DestructorCall*>* const DestructorCall::list_ =
01206     new std::vector<DestructorCall*>;
01207 
01208 // DestructorTracker keeps track of whether its instances have been
01209 // destroyed.
01210 class DestructorTracker {
01211  public:
01212   DestructorTracker() : index_(GetNewIndex()) {}
01213   DestructorTracker(const DestructorTracker& /* rhs */)
01214       : index_(GetNewIndex()) {}
01215   ~DestructorTracker() {
01216     // We never access DestructorCall::List() concurrently, so we don't need
01217     // to protect this acccess with a mutex.
01218     DestructorCall::List()[index_]->ReportDestroyed();
01219   }
01220 
01221  private:
01222   static int GetNewIndex() {
01223     DestructorCall::List().push_back(new DestructorCall);
01224     return DestructorCall::List().size() - 1;
01225   }
01226   const int index_;
01227 
01228   GTEST_DISALLOW_ASSIGN_(DestructorTracker);
01229 };
01230 
01231 typedef ThreadLocal<DestructorTracker>* ThreadParam;
01232 
01233 void CallThreadLocalGet(ThreadParam thread_local_param) {
01234   thread_local_param->get();
01235 }
01236 
01237 // Tests that when a ThreadLocal object dies in a thread, it destroys
01238 // the managed object for that thread.
01239 TEST(ThreadLocalTest, DestroysManagedObjectForOwnThreadWhenDying) {
01240   DestructorCall::ResetList();
01241 
01242   {
01243     // The next line default constructs a DestructorTracker object as
01244     // the default value of objects managed by thread_local_tracker.
01245     ThreadLocal<DestructorTracker> thread_local_tracker;
01246     ASSERT_EQ(1U, DestructorCall::List().size());
01247     ASSERT_FALSE(DestructorCall::List()[0]->CheckDestroyed());
01248 
01249     // This creates another DestructorTracker object for the main thread.
01250     thread_local_tracker.get();
01251     ASSERT_EQ(2U, DestructorCall::List().size());
01252     ASSERT_FALSE(DestructorCall::List()[0]->CheckDestroyed());
01253     ASSERT_FALSE(DestructorCall::List()[1]->CheckDestroyed());
01254   }
01255 
01256   // Now thread_local_tracker has died.  It should have destroyed both the
01257   // default value shared by all threads and the value for the main
01258   // thread.
01259   ASSERT_EQ(2U, DestructorCall::List().size());
01260   EXPECT_TRUE(DestructorCall::List()[0]->CheckDestroyed());
01261   EXPECT_TRUE(DestructorCall::List()[1]->CheckDestroyed());
01262 
01263   DestructorCall::ResetList();
01264 }
01265 
01266 // Tests that when a thread exits, the thread-local object for that
01267 // thread is destroyed.
01268 TEST(ThreadLocalTest, DestroysManagedObjectAtThreadExit) {
01269   DestructorCall::ResetList();
01270 
01271   {
01272     // The next line default constructs a DestructorTracker object as
01273     // the default value of objects managed by thread_local_tracker.
01274     ThreadLocal<DestructorTracker> thread_local_tracker;
01275     ASSERT_EQ(1U, DestructorCall::List().size());
01276     ASSERT_FALSE(DestructorCall::List()[0]->CheckDestroyed());
01277 
01278     // This creates another DestructorTracker object in the new thread.
01279     ThreadWithParam<ThreadParam> thread(
01280         &CallThreadLocalGet, &thread_local_tracker, NULL);
01281     thread.Join();
01282 
01283     // The thread has exited, and we should have another DestroyedTracker
01284     // instance created for it. But it may not have been destroyed yet.
01285     // The instance for the main thread should still persist.
01286     ASSERT_EQ(2U, DestructorCall::List().size());
01287     ASSERT_FALSE(DestructorCall::List()[0]->CheckDestroyed());
01288   }
01289 
01290   // The thread has exited and thread_local_tracker has died.  The default
01291   // value should have been destroyed too.
01292   ASSERT_EQ(2U, DestructorCall::List().size());
01293   EXPECT_TRUE(DestructorCall::List()[0]->CheckDestroyed());
01294   EXPECT_TRUE(DestructorCall::List()[1]->CheckDestroyed());
01295 
01296   DestructorCall::ResetList();
01297 }
01298 
01299 TEST(ThreadLocalTest, ThreadLocalMutationsAffectOnlyCurrentThread) {
01300   ThreadLocal<std::string> thread_local_string;
01301   thread_local_string.set("Foo");
01302   EXPECT_STREQ("Foo", thread_local_string.get().c_str());
01303 
01304   std::string result;
01305   RunFromThread(&RetrieveThreadLocalValue,
01306                 make_pair(&thread_local_string, &result));
01307   EXPECT_TRUE(result.empty());
01308 }
01309 
01310 #endif  // GTEST_IS_THREADSAFE
01311 
01312 #if GTEST_OS_WINDOWS
01313 TEST(WindowsTypesTest, HANDLEIsVoidStar) {
01314   StaticAssertTypeEq<HANDLE, void*>();
01315 }
01316 
01317 TEST(WindowsTypesTest, CRITICAL_SECTIONIs_RTL_CRITICAL_SECTION) {
01318   StaticAssertTypeEq<CRITICAL_SECTION, _RTL_CRITICAL_SECTION>();
01319 }
01320 #endif  // GTEST_OS_WINDOWS
01321 
01322 }  // namespace internal
01323 }  // namespace testing


rc_visard_driver
Author(s): Heiko Hirschmueller , Christian Emmerich , Felix Ruess
autogenerated on Thu Jun 6 2019 20:43:03