googletest-port-test.cc 40 KB

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