googletest-port-test.cc 39 KB

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