gtest-port_test.cc 40 KB

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