googletest-port-test.cc 40 KB

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