You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

1206 lines
37 KiB

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