googletest-port-test.cc 39 KB

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