gtest-port_test.cc 38 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253
  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(static_cast<char>(0x80)));
  68. EXPECT_FALSE(IsXDigit(static_cast<char>('0' | 0x80)));
  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_MAC || GTEST_OS_QNX
  258. void* ThreadFunc(void* data) {
  259. pthread_mutex_t* mutex = static_cast<pthread_mutex_t*>(data);
  260. pthread_mutex_lock(mutex);
  261. pthread_mutex_unlock(mutex);
  262. return NULL;
  263. }
  264. TEST(GetThreadCountTest, ReturnsCorrectValue) {
  265. EXPECT_EQ(1U, GetThreadCount());
  266. pthread_mutex_t mutex;
  267. pthread_attr_t attr;
  268. pthread_t thread_id;
  269. // TODO(vladl@google.com): turn mutex into internal::Mutex for automatic
  270. // destruction.
  271. pthread_mutex_init(&mutex, NULL);
  272. pthread_mutex_lock(&mutex);
  273. ASSERT_EQ(0, pthread_attr_init(&attr));
  274. ASSERT_EQ(0, pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_JOINABLE));
  275. const int status = pthread_create(&thread_id, &attr, &ThreadFunc, &mutex);
  276. ASSERT_EQ(0, pthread_attr_destroy(&attr));
  277. ASSERT_EQ(0, status);
  278. EXPECT_EQ(2U, GetThreadCount());
  279. pthread_mutex_unlock(&mutex);
  280. void* dummy;
  281. ASSERT_EQ(0, pthread_join(thread_id, &dummy));
  282. # if GTEST_OS_MAC
  283. // MacOS X may not immediately report the updated thread count after
  284. // joining a thread, causing flakiness in this test. To counter that, we
  285. // wait for up to .5 seconds for the OS to report the correct value.
  286. for (int i = 0; i < 5; ++i) {
  287. if (GetThreadCount() == 1)
  288. break;
  289. SleepMilliseconds(100);
  290. }
  291. # endif // GTEST_OS_MAC
  292. EXPECT_EQ(1U, GetThreadCount());
  293. pthread_mutex_destroy(&mutex);
  294. }
  295. #else
  296. TEST(GetThreadCountTest, ReturnsZeroWhenUnableToCountThreads) {
  297. EXPECT_EQ(0U, GetThreadCount());
  298. }
  299. #endif // GTEST_OS_MAC || GTEST_OS_QNX
  300. TEST(GtestCheckDeathTest, DiesWithCorrectOutputOnFailure) {
  301. const bool a_false_condition = false;
  302. const char regex[] =
  303. #ifdef _MSC_VER
  304. "gtest-port_test\\.cc\\(\\d+\\):"
  305. #elif GTEST_USES_POSIX_RE
  306. "gtest-port_test\\.cc:[0-9]+"
  307. #else
  308. "gtest-port_test\\.cc:\\d+"
  309. #endif // _MSC_VER
  310. ".*a_false_condition.*Extra info.*";
  311. EXPECT_DEATH_IF_SUPPORTED(GTEST_CHECK_(a_false_condition) << "Extra info",
  312. regex);
  313. }
  314. #if GTEST_HAS_DEATH_TEST
  315. TEST(GtestCheckDeathTest, LivesSilentlyOnSuccess) {
  316. EXPECT_EXIT({
  317. GTEST_CHECK_(true) << "Extra info";
  318. ::std::cerr << "Success\n";
  319. exit(0); },
  320. ::testing::ExitedWithCode(0), "Success");
  321. }
  322. #endif // GTEST_HAS_DEATH_TEST
  323. // Verifies that Google Test choose regular expression engine appropriate to
  324. // the platform. The test will produce compiler errors in case of failure.
  325. // For simplicity, we only cover the most important platforms here.
  326. TEST(RegexEngineSelectionTest, SelectsCorrectRegexEngine) {
  327. #if GTEST_HAS_POSIX_RE
  328. EXPECT_TRUE(GTEST_USES_POSIX_RE);
  329. #else
  330. EXPECT_TRUE(GTEST_USES_SIMPLE_RE);
  331. #endif
  332. }
  333. #if GTEST_USES_POSIX_RE
  334. # if GTEST_HAS_TYPED_TEST
  335. template <typename Str>
  336. class RETest : public ::testing::Test {};
  337. // Defines StringTypes as the list of all string types that class RE
  338. // supports.
  339. typedef testing::Types<
  340. ::std::string,
  341. # if GTEST_HAS_GLOBAL_STRING
  342. ::string,
  343. # endif // GTEST_HAS_GLOBAL_STRING
  344. const char*> StringTypes;
  345. TYPED_TEST_CASE(RETest, StringTypes);
  346. // Tests RE's implicit constructors.
  347. TYPED_TEST(RETest, ImplicitConstructorWorks) {
  348. const RE empty(TypeParam(""));
  349. EXPECT_STREQ("", empty.pattern());
  350. const RE simple(TypeParam("hello"));
  351. EXPECT_STREQ("hello", simple.pattern());
  352. const RE normal(TypeParam(".*(\\w+)"));
  353. EXPECT_STREQ(".*(\\w+)", normal.pattern());
  354. }
  355. // Tests that RE's constructors reject invalid regular expressions.
  356. TYPED_TEST(RETest, RejectsInvalidRegex) {
  357. EXPECT_NONFATAL_FAILURE({
  358. const RE invalid(TypeParam("?"));
  359. }, "\"?\" is not a valid POSIX Extended regular expression.");
  360. }
  361. // Tests RE::FullMatch().
  362. TYPED_TEST(RETest, FullMatchWorks) {
  363. const RE empty(TypeParam(""));
  364. EXPECT_TRUE(RE::FullMatch(TypeParam(""), empty));
  365. EXPECT_FALSE(RE::FullMatch(TypeParam("a"), empty));
  366. const RE re(TypeParam("a.*z"));
  367. EXPECT_TRUE(RE::FullMatch(TypeParam("az"), re));
  368. EXPECT_TRUE(RE::FullMatch(TypeParam("axyz"), re));
  369. EXPECT_FALSE(RE::FullMatch(TypeParam("baz"), re));
  370. EXPECT_FALSE(RE::FullMatch(TypeParam("azy"), re));
  371. }
  372. // Tests RE::PartialMatch().
  373. TYPED_TEST(RETest, PartialMatchWorks) {
  374. const RE empty(TypeParam(""));
  375. EXPECT_TRUE(RE::PartialMatch(TypeParam(""), empty));
  376. EXPECT_TRUE(RE::PartialMatch(TypeParam("a"), empty));
  377. const RE re(TypeParam("a.*z"));
  378. EXPECT_TRUE(RE::PartialMatch(TypeParam("az"), re));
  379. EXPECT_TRUE(RE::PartialMatch(TypeParam("axyz"), re));
  380. EXPECT_TRUE(RE::PartialMatch(TypeParam("baz"), re));
  381. EXPECT_TRUE(RE::PartialMatch(TypeParam("azy"), re));
  382. EXPECT_FALSE(RE::PartialMatch(TypeParam("zza"), re));
  383. }
  384. # endif // GTEST_HAS_TYPED_TEST
  385. #elif 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,
  693. WorksWhenRegexStartsWithRepetionOfEscapeSequence) {
  694. EXPECT_FALSE(MatchRegexAtHead("\\.+a", "abc"));
  695. EXPECT_FALSE(MatchRegexAtHead("\\s?b", " b"));
  696. EXPECT_TRUE(MatchRegexAtHead("\\(*a", "((((ab"));
  697. EXPECT_TRUE(MatchRegexAtHead("\\^?b", "^b"));
  698. EXPECT_TRUE(MatchRegexAtHead("\\\\?b", "b"));
  699. EXPECT_TRUE(MatchRegexAtHead("\\\\?b", "\\b"));
  700. }
  701. TEST(MatchRegexAtHeadTest, MatchesSequentially) {
  702. EXPECT_FALSE(MatchRegexAtHead("ab.*c", "acabc"));
  703. EXPECT_TRUE(MatchRegexAtHead("ab.*c", "ab-fsc"));
  704. }
  705. TEST(MatchRegexAnywhereTest, ReturnsFalseWhenStringIsNull) {
  706. EXPECT_FALSE(MatchRegexAnywhere("", NULL));
  707. }
  708. TEST(MatchRegexAnywhereTest, WorksWhenRegexStartsWithCaret) {
  709. EXPECT_FALSE(MatchRegexAnywhere("^a", "ba"));
  710. EXPECT_FALSE(MatchRegexAnywhere("^$", "a"));
  711. EXPECT_TRUE(MatchRegexAnywhere("^a", "ab"));
  712. EXPECT_TRUE(MatchRegexAnywhere("^", "ab"));
  713. EXPECT_TRUE(MatchRegexAnywhere("^$", ""));
  714. }
  715. TEST(MatchRegexAnywhereTest, ReturnsFalseWhenNoMatch) {
  716. EXPECT_FALSE(MatchRegexAnywhere("a", "bcde123"));
  717. EXPECT_FALSE(MatchRegexAnywhere("a.+a", "--aa88888888"));
  718. }
  719. TEST(MatchRegexAnywhereTest, ReturnsTrueWhenMatchingPrefix) {
  720. EXPECT_TRUE(MatchRegexAnywhere("\\w+", "ab1_ - 5"));
  721. EXPECT_TRUE(MatchRegexAnywhere(".*=", "="));
  722. EXPECT_TRUE(MatchRegexAnywhere("x.*ab?.*bc", "xaaabc"));
  723. }
  724. TEST(MatchRegexAnywhereTest, ReturnsTrueWhenMatchingNonPrefix) {
  725. EXPECT_TRUE(MatchRegexAnywhere("\\w+", "$$$ ab1_ - 5"));
  726. EXPECT_TRUE(MatchRegexAnywhere("\\.+=", "= ...="));
  727. }
  728. // Tests RE's implicit constructors.
  729. TEST(RETest, ImplicitConstructorWorks) {
  730. const RE empty("");
  731. EXPECT_STREQ("", empty.pattern());
  732. const RE simple("hello");
  733. EXPECT_STREQ("hello", simple.pattern());
  734. }
  735. // Tests that RE's constructors reject invalid regular expressions.
  736. TEST(RETest, RejectsInvalidRegex) {
  737. EXPECT_NONFATAL_FAILURE({
  738. const RE normal(NULL);
  739. }, "NULL is not a valid simple regular expression");
  740. EXPECT_NONFATAL_FAILURE({
  741. const RE normal(".*(\\w+");
  742. }, "'(' is unsupported");
  743. EXPECT_NONFATAL_FAILURE({
  744. const RE invalid("^?");
  745. }, "'?' can only follow a repeatable token");
  746. }
  747. // Tests RE::FullMatch().
  748. TEST(RETest, FullMatchWorks) {
  749. const RE empty("");
  750. EXPECT_TRUE(RE::FullMatch("", empty));
  751. EXPECT_FALSE(RE::FullMatch("a", empty));
  752. const RE re1("a");
  753. EXPECT_TRUE(RE::FullMatch("a", re1));
  754. const RE re("a.*z");
  755. EXPECT_TRUE(RE::FullMatch("az", re));
  756. EXPECT_TRUE(RE::FullMatch("axyz", re));
  757. EXPECT_FALSE(RE::FullMatch("baz", re));
  758. EXPECT_FALSE(RE::FullMatch("azy", re));
  759. }
  760. // Tests RE::PartialMatch().
  761. TEST(RETest, PartialMatchWorks) {
  762. const RE empty("");
  763. EXPECT_TRUE(RE::PartialMatch("", empty));
  764. EXPECT_TRUE(RE::PartialMatch("a", empty));
  765. const RE re("a.*z");
  766. EXPECT_TRUE(RE::PartialMatch("az", re));
  767. EXPECT_TRUE(RE::PartialMatch("axyz", re));
  768. EXPECT_TRUE(RE::PartialMatch("baz", re));
  769. EXPECT_TRUE(RE::PartialMatch("azy", re));
  770. EXPECT_FALSE(RE::PartialMatch("zza", re));
  771. }
  772. #endif // GTEST_USES_POSIX_RE
  773. #if !GTEST_OS_WINDOWS_MOBILE
  774. TEST(CaptureTest, CapturesStdout) {
  775. CaptureStdout();
  776. fprintf(stdout, "abc");
  777. EXPECT_STREQ("abc", GetCapturedStdout().c_str());
  778. CaptureStdout();
  779. fprintf(stdout, "def%cghi", '\0');
  780. EXPECT_EQ(::std::string("def\0ghi", 7), ::std::string(GetCapturedStdout()));
  781. }
  782. TEST(CaptureTest, CapturesStderr) {
  783. CaptureStderr();
  784. fprintf(stderr, "jkl");
  785. EXPECT_STREQ("jkl", GetCapturedStderr().c_str());
  786. CaptureStderr();
  787. fprintf(stderr, "jkl%cmno", '\0');
  788. EXPECT_EQ(::std::string("jkl\0mno", 7), ::std::string(GetCapturedStderr()));
  789. }
  790. // Tests that stdout and stderr capture don't interfere with each other.
  791. TEST(CaptureTest, CapturesStdoutAndStderr) {
  792. CaptureStdout();
  793. CaptureStderr();
  794. fprintf(stdout, "pqr");
  795. fprintf(stderr, "stu");
  796. EXPECT_STREQ("pqr", GetCapturedStdout().c_str());
  797. EXPECT_STREQ("stu", GetCapturedStderr().c_str());
  798. }
  799. TEST(CaptureDeathTest, CannotReenterStdoutCapture) {
  800. CaptureStdout();
  801. EXPECT_DEATH_IF_SUPPORTED(CaptureStdout(),
  802. "Only one stdout capturer can exist at a time");
  803. GetCapturedStdout();
  804. // We cannot test stderr capturing using death tests as they use it
  805. // themselves.
  806. }
  807. #endif // !GTEST_OS_WINDOWS_MOBILE
  808. TEST(ThreadLocalTest, DefaultConstructorInitializesToDefaultValues) {
  809. ThreadLocal<int> t1;
  810. EXPECT_EQ(0, t1.get());
  811. ThreadLocal<void*> t2;
  812. EXPECT_TRUE(t2.get() == NULL);
  813. }
  814. TEST(ThreadLocalTest, SingleParamConstructorInitializesToParam) {
  815. ThreadLocal<int> t1(123);
  816. EXPECT_EQ(123, t1.get());
  817. int i = 0;
  818. ThreadLocal<int*> t2(&i);
  819. EXPECT_EQ(&i, t2.get());
  820. }
  821. class NoDefaultContructor {
  822. public:
  823. explicit NoDefaultContructor(const char*) {}
  824. NoDefaultContructor(const NoDefaultContructor&) {}
  825. };
  826. TEST(ThreadLocalTest, ValueDefaultContructorIsNotRequiredForParamVersion) {
  827. ThreadLocal<NoDefaultContructor> bar(NoDefaultContructor("foo"));
  828. bar.pointer();
  829. }
  830. TEST(ThreadLocalTest, GetAndPointerReturnSameValue) {
  831. ThreadLocal<std::string> thread_local_string;
  832. EXPECT_EQ(thread_local_string.pointer(), &(thread_local_string.get()));
  833. // Verifies the condition still holds after calling set.
  834. thread_local_string.set("foo");
  835. EXPECT_EQ(thread_local_string.pointer(), &(thread_local_string.get()));
  836. }
  837. TEST(ThreadLocalTest, PointerAndConstPointerReturnSameValue) {
  838. ThreadLocal<std::string> thread_local_string;
  839. const ThreadLocal<std::string>& const_thread_local_string =
  840. thread_local_string;
  841. EXPECT_EQ(thread_local_string.pointer(), const_thread_local_string.pointer());
  842. thread_local_string.set("foo");
  843. EXPECT_EQ(thread_local_string.pointer(), const_thread_local_string.pointer());
  844. }
  845. #if GTEST_IS_THREADSAFE
  846. void AddTwo(int* param) { *param += 2; }
  847. TEST(ThreadWithParamTest, ConstructorExecutesThreadFunc) {
  848. int i = 40;
  849. ThreadWithParam<int*> thread(&AddTwo, &i, NULL);
  850. thread.Join();
  851. EXPECT_EQ(42, i);
  852. }
  853. TEST(MutexDeathTest, AssertHeldShouldAssertWhenNotLocked) {
  854. // AssertHeld() is flaky only in the presence of multiple threads accessing
  855. // the lock. In this case, the test is robust.
  856. EXPECT_DEATH_IF_SUPPORTED({
  857. Mutex m;
  858. { MutexLock lock(&m); }
  859. m.AssertHeld();
  860. },
  861. "thread .*hold");
  862. }
  863. TEST(MutexTest, AssertHeldShouldNotAssertWhenLocked) {
  864. Mutex m;
  865. MutexLock lock(&m);
  866. m.AssertHeld();
  867. }
  868. class AtomicCounterWithMutex {
  869. public:
  870. explicit AtomicCounterWithMutex(Mutex* mutex) :
  871. value_(0), mutex_(mutex), random_(42) {}
  872. void Increment() {
  873. MutexLock lock(mutex_);
  874. int temp = value_;
  875. {
  876. // Locking a mutex puts up a memory barrier, preventing reads and
  877. // writes to value_ rearranged when observed from other threads.
  878. //
  879. // We cannot use Mutex and MutexLock here or rely on their memory
  880. // barrier functionality as we are testing them here.
  881. pthread_mutex_t memory_barrier_mutex;
  882. GTEST_CHECK_POSIX_SUCCESS_(
  883. pthread_mutex_init(&memory_barrier_mutex, NULL));
  884. GTEST_CHECK_POSIX_SUCCESS_(pthread_mutex_lock(&memory_barrier_mutex));
  885. SleepMilliseconds(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. }
  889. value_ = temp + 1;
  890. }
  891. int value() const { return value_; }
  892. private:
  893. volatile int value_;
  894. Mutex* const mutex_; // Protects value_.
  895. Random random_;
  896. };
  897. void CountingThreadFunc(pair<AtomicCounterWithMutex*, int> param) {
  898. for (int i = 0; i < param.second; ++i)
  899. param.first->Increment();
  900. }
  901. // Tests that the mutex only lets one thread at a time to lock it.
  902. TEST(MutexTest, OnlyOneThreadCanLockAtATime) {
  903. Mutex mutex;
  904. AtomicCounterWithMutex locked_counter(&mutex);
  905. typedef ThreadWithParam<pair<AtomicCounterWithMutex*, int> > ThreadType;
  906. const int kCycleCount = 20;
  907. const int kThreadCount = 7;
  908. scoped_ptr<ThreadType> counting_threads[kThreadCount];
  909. Notification threads_can_start;
  910. // Creates and runs kThreadCount threads that increment locked_counter
  911. // kCycleCount times each.
  912. for (int i = 0; i < kThreadCount; ++i) {
  913. counting_threads[i].reset(new ThreadType(&CountingThreadFunc,
  914. make_pair(&locked_counter,
  915. kCycleCount),
  916. &threads_can_start));
  917. }
  918. threads_can_start.Notify();
  919. for (int i = 0; i < kThreadCount; ++i)
  920. counting_threads[i]->Join();
  921. // If the mutex lets more than one thread to increment the counter at a
  922. // time, they are likely to encounter a race condition and have some
  923. // increments overwritten, resulting in the lower then expected counter
  924. // value.
  925. EXPECT_EQ(kCycleCount * kThreadCount, locked_counter.value());
  926. }
  927. template <typename T>
  928. void RunFromThread(void (func)(T), T param) {
  929. ThreadWithParam<T> thread(func, param, NULL);
  930. thread.Join();
  931. }
  932. void RetrieveThreadLocalValue(
  933. pair<ThreadLocal<std::string>*, std::string*> param) {
  934. *param.second = param.first->get();
  935. }
  936. TEST(ThreadLocalTest, ParameterizedConstructorSetsDefault) {
  937. ThreadLocal<std::string> thread_local_string("foo");
  938. EXPECT_STREQ("foo", thread_local_string.get().c_str());
  939. thread_local_string.set("bar");
  940. EXPECT_STREQ("bar", thread_local_string.get().c_str());
  941. std::string result;
  942. RunFromThread(&RetrieveThreadLocalValue,
  943. make_pair(&thread_local_string, &result));
  944. EXPECT_STREQ("foo", result.c_str());
  945. }
  946. // DestructorTracker keeps track of whether its instances have been
  947. // destroyed.
  948. static std::vector<bool> g_destroyed;
  949. class DestructorTracker {
  950. public:
  951. DestructorTracker() : index_(GetNewIndex()) {}
  952. DestructorTracker(const DestructorTracker& /* rhs */)
  953. : index_(GetNewIndex()) {}
  954. ~DestructorTracker() {
  955. // We never access g_destroyed concurrently, so we don't need to
  956. // protect the write operation under a mutex.
  957. g_destroyed[index_] = true;
  958. }
  959. private:
  960. static int GetNewIndex() {
  961. g_destroyed.push_back(false);
  962. return g_destroyed.size() - 1;
  963. }
  964. const int index_;
  965. };
  966. typedef ThreadLocal<DestructorTracker>* ThreadParam;
  967. void CallThreadLocalGet(ThreadParam thread_local_param) {
  968. thread_local_param->get();
  969. }
  970. // Tests that when a ThreadLocal object dies in a thread, it destroys
  971. // the managed object for that thread.
  972. TEST(ThreadLocalTest, DestroysManagedObjectForOwnThreadWhenDying) {
  973. g_destroyed.clear();
  974. {
  975. // The next line default constructs a DestructorTracker object as
  976. // the default value of objects managed by thread_local_tracker.
  977. ThreadLocal<DestructorTracker> thread_local_tracker;
  978. ASSERT_EQ(1U, g_destroyed.size());
  979. ASSERT_FALSE(g_destroyed[0]);
  980. // This creates another DestructorTracker object for the main thread.
  981. thread_local_tracker.get();
  982. ASSERT_EQ(2U, g_destroyed.size());
  983. ASSERT_FALSE(g_destroyed[0]);
  984. ASSERT_FALSE(g_destroyed[1]);
  985. }
  986. // Now thread_local_tracker has died. It should have destroyed both the
  987. // default value shared by all threads and the value for the main
  988. // thread.
  989. ASSERT_EQ(2U, g_destroyed.size());
  990. EXPECT_TRUE(g_destroyed[0]);
  991. EXPECT_TRUE(g_destroyed[1]);
  992. g_destroyed.clear();
  993. }
  994. // Tests that when a thread exits, the thread-local object for that
  995. // thread is destroyed.
  996. TEST(ThreadLocalTest, DestroysManagedObjectAtThreadExit) {
  997. g_destroyed.clear();
  998. {
  999. // The next line default constructs a DestructorTracker object as
  1000. // the default value of objects managed by thread_local_tracker.
  1001. ThreadLocal<DestructorTracker> thread_local_tracker;
  1002. ASSERT_EQ(1U, g_destroyed.size());
  1003. ASSERT_FALSE(g_destroyed[0]);
  1004. // This creates another DestructorTracker object in the new thread.
  1005. ThreadWithParam<ThreadParam> thread(
  1006. &CallThreadLocalGet, &thread_local_tracker, NULL);
  1007. thread.Join();
  1008. // Now the new thread has exited. The per-thread object for it
  1009. // should have been destroyed.
  1010. ASSERT_EQ(2U, g_destroyed.size());
  1011. ASSERT_FALSE(g_destroyed[0]);
  1012. ASSERT_TRUE(g_destroyed[1]);
  1013. }
  1014. // Now thread_local_tracker has died. The default value should have been
  1015. // destroyed too.
  1016. ASSERT_EQ(2U, g_destroyed.size());
  1017. EXPECT_TRUE(g_destroyed[0]);
  1018. EXPECT_TRUE(g_destroyed[1]);
  1019. g_destroyed.clear();
  1020. }
  1021. TEST(ThreadLocalTest, ThreadLocalMutationsAffectOnlyCurrentThread) {
  1022. ThreadLocal<std::string> thread_local_string;
  1023. thread_local_string.set("Foo");
  1024. EXPECT_STREQ("Foo", thread_local_string.get().c_str());
  1025. std::string result;
  1026. RunFromThread(&RetrieveThreadLocalValue,
  1027. make_pair(&thread_local_string, &result));
  1028. EXPECT_TRUE(result.empty());
  1029. }
  1030. #endif // GTEST_IS_THREADSAFE
  1031. } // namespace internal
  1032. } // namespace testing