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.

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