/thirdparty/breakpad/third_party/protobuf/protobuf/gtest/test/gtest-port_test.cc

http://github.com/tomahawk-player/tomahawk · C++ · 1018 lines · 736 code · 179 blank · 103 comment · 14 complexity · 3d56b57c2a8054d00bc4d5c5b370329b MD5 · raw file

  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 <utility> // For std::pair and std::make_pair.
  39. #include <gtest/gtest.h>
  40. #include <gtest/gtest-spi.h>
  41. // Indicates that this translation unit is part of Google Test's
  42. // implementation. It must come before gtest-internal-inl.h is
  43. // included, or there will be a compiler error. This trick is to
  44. // prevent a user from accidentally including gtest-internal-inl.h in
  45. // his code.
  46. #define GTEST_IMPLEMENTATION_ 1
  47. #include "src/gtest-internal-inl.h"
  48. #undef GTEST_IMPLEMENTATION_
  49. using std::make_pair;
  50. using std::pair;
  51. namespace testing {
  52. namespace internal {
  53. // Tests that the element_type typedef is available in scoped_ptr and refers
  54. // to the parameter type.
  55. TEST(ScopedPtrTest, DefinesElementType) {
  56. StaticAssertTypeEq<int, ::testing::internal::scoped_ptr<int>::element_type>();
  57. }
  58. // TODO(vladl@google.com): Implement THE REST of scoped_ptr tests.
  59. TEST(GtestCheckSyntaxTest, BehavesLikeASingleStatement) {
  60. if (AlwaysFalse())
  61. GTEST_CHECK_(false) << "This should never be executed; "
  62. "It's a compilation test only.";
  63. if (AlwaysTrue())
  64. GTEST_CHECK_(true);
  65. else
  66. ; // NOLINT
  67. if (AlwaysFalse())
  68. ; // NOLINT
  69. else
  70. GTEST_CHECK_(true) << "";
  71. }
  72. TEST(GtestCheckSyntaxTest, WorksWithSwitch) {
  73. switch (0) {
  74. case 1:
  75. break;
  76. default:
  77. GTEST_CHECK_(true);
  78. }
  79. switch(0)
  80. case 0:
  81. GTEST_CHECK_(true) << "Check failed in switch case";
  82. }
  83. #if GTEST_OS_MAC
  84. void* ThreadFunc(void* data) {
  85. pthread_mutex_t* mutex = static_cast<pthread_mutex_t*>(data);
  86. pthread_mutex_lock(mutex);
  87. pthread_mutex_unlock(mutex);
  88. return NULL;
  89. }
  90. TEST(GetThreadCountTest, ReturnsCorrectValue) {
  91. EXPECT_EQ(1U, GetThreadCount());
  92. pthread_mutex_t mutex;
  93. pthread_attr_t attr;
  94. pthread_t thread_id;
  95. // TODO(vladl@google.com): turn mutex into internal::Mutex for automatic
  96. // destruction.
  97. pthread_mutex_init(&mutex, NULL);
  98. pthread_mutex_lock(&mutex);
  99. ASSERT_EQ(0, pthread_attr_init(&attr));
  100. ASSERT_EQ(0, pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_JOINABLE));
  101. const int status = pthread_create(&thread_id, &attr, &ThreadFunc, &mutex);
  102. ASSERT_EQ(0, pthread_attr_destroy(&attr));
  103. ASSERT_EQ(0, status);
  104. EXPECT_EQ(2U, GetThreadCount());
  105. pthread_mutex_unlock(&mutex);
  106. void* dummy;
  107. ASSERT_EQ(0, pthread_join(thread_id, &dummy));
  108. // MacOS X may not immediately report the updated thread count after
  109. // joining a thread, causing flakiness in this test. To counter that, we
  110. // wait for up to .5 seconds for the OS to report the correct value.
  111. for (int i = 0; i < 5; ++i) {
  112. if (GetThreadCount() == 1)
  113. break;
  114. SleepMilliseconds(100);
  115. }
  116. EXPECT_EQ(1U, GetThreadCount());
  117. pthread_mutex_destroy(&mutex);
  118. }
  119. #else
  120. TEST(GetThreadCountTest, ReturnsZeroWhenUnableToCountThreads) {
  121. EXPECT_EQ(0U, GetThreadCount());
  122. }
  123. #endif // GTEST_OS_MAC
  124. TEST(GtestCheckDeathTest, DiesWithCorrectOutputOnFailure) {
  125. const bool a_false_condition = false;
  126. const char regex[] =
  127. #ifdef _MSC_VER
  128. "gtest-port_test\\.cc\\(\\d+\\):"
  129. #else
  130. "gtest-port_test\\.cc:[0-9]+"
  131. #endif // _MSC_VER
  132. ".*a_false_condition.*Extra info.*";
  133. EXPECT_DEATH_IF_SUPPORTED(GTEST_CHECK_(a_false_condition) << "Extra info",
  134. regex);
  135. }
  136. #if GTEST_HAS_DEATH_TEST
  137. TEST(GtestCheckDeathTest, LivesSilentlyOnSuccess) {
  138. EXPECT_EXIT({
  139. GTEST_CHECK_(true) << "Extra info";
  140. ::std::cerr << "Success\n";
  141. exit(0); },
  142. ::testing::ExitedWithCode(0), "Success");
  143. }
  144. #endif // GTEST_HAS_DEATH_TEST
  145. #if GTEST_USES_POSIX_RE
  146. #if GTEST_HAS_TYPED_TEST
  147. template <typename Str>
  148. class RETest : public ::testing::Test {};
  149. // Defines StringTypes as the list of all string types that class RE
  150. // supports.
  151. typedef testing::Types<
  152. ::std::string,
  153. #if GTEST_HAS_GLOBAL_STRING
  154. ::string,
  155. #endif // GTEST_HAS_GLOBAL_STRING
  156. const char*> StringTypes;
  157. TYPED_TEST_CASE(RETest, StringTypes);
  158. // Tests RE's implicit constructors.
  159. TYPED_TEST(RETest, ImplicitConstructorWorks) {
  160. const RE empty(TypeParam(""));
  161. EXPECT_STREQ("", empty.pattern());
  162. const RE simple(TypeParam("hello"));
  163. EXPECT_STREQ("hello", simple.pattern());
  164. const RE normal(TypeParam(".*(\\w+)"));
  165. EXPECT_STREQ(".*(\\w+)", normal.pattern());
  166. }
  167. // Tests that RE's constructors reject invalid regular expressions.
  168. TYPED_TEST(RETest, RejectsInvalidRegex) {
  169. EXPECT_NONFATAL_FAILURE({
  170. const RE invalid(TypeParam("?"));
  171. }, "\"?\" is not a valid POSIX Extended regular expression.");
  172. }
  173. // Tests RE::FullMatch().
  174. TYPED_TEST(RETest, FullMatchWorks) {
  175. const RE empty(TypeParam(""));
  176. EXPECT_TRUE(RE::FullMatch(TypeParam(""), empty));
  177. EXPECT_FALSE(RE::FullMatch(TypeParam("a"), empty));
  178. const RE re(TypeParam("a.*z"));
  179. EXPECT_TRUE(RE::FullMatch(TypeParam("az"), re));
  180. EXPECT_TRUE(RE::FullMatch(TypeParam("axyz"), re));
  181. EXPECT_FALSE(RE::FullMatch(TypeParam("baz"), re));
  182. EXPECT_FALSE(RE::FullMatch(TypeParam("azy"), re));
  183. }
  184. // Tests RE::PartialMatch().
  185. TYPED_TEST(RETest, PartialMatchWorks) {
  186. const RE empty(TypeParam(""));
  187. EXPECT_TRUE(RE::PartialMatch(TypeParam(""), empty));
  188. EXPECT_TRUE(RE::PartialMatch(TypeParam("a"), empty));
  189. const RE re(TypeParam("a.*z"));
  190. EXPECT_TRUE(RE::PartialMatch(TypeParam("az"), re));
  191. EXPECT_TRUE(RE::PartialMatch(TypeParam("axyz"), re));
  192. EXPECT_TRUE(RE::PartialMatch(TypeParam("baz"), re));
  193. EXPECT_TRUE(RE::PartialMatch(TypeParam("azy"), re));
  194. EXPECT_FALSE(RE::PartialMatch(TypeParam("zza"), re));
  195. }
  196. #endif // GTEST_HAS_TYPED_TEST
  197. #elif GTEST_USES_SIMPLE_RE
  198. TEST(IsInSetTest, NulCharIsNotInAnySet) {
  199. EXPECT_FALSE(IsInSet('\0', ""));
  200. EXPECT_FALSE(IsInSet('\0', "\0"));
  201. EXPECT_FALSE(IsInSet('\0', "a"));
  202. }
  203. TEST(IsInSetTest, WorksForNonNulChars) {
  204. EXPECT_FALSE(IsInSet('a', "Ab"));
  205. EXPECT_FALSE(IsInSet('c', ""));
  206. EXPECT_TRUE(IsInSet('b', "bcd"));
  207. EXPECT_TRUE(IsInSet('b', "ab"));
  208. }
  209. TEST(IsDigitTest, IsFalseForNonDigit) {
  210. EXPECT_FALSE(IsDigit('\0'));
  211. EXPECT_FALSE(IsDigit(' '));
  212. EXPECT_FALSE(IsDigit('+'));
  213. EXPECT_FALSE(IsDigit('-'));
  214. EXPECT_FALSE(IsDigit('.'));
  215. EXPECT_FALSE(IsDigit('a'));
  216. }
  217. TEST(IsDigitTest, IsTrueForDigit) {
  218. EXPECT_TRUE(IsDigit('0'));
  219. EXPECT_TRUE(IsDigit('1'));
  220. EXPECT_TRUE(IsDigit('5'));
  221. EXPECT_TRUE(IsDigit('9'));
  222. }
  223. TEST(IsPunctTest, IsFalseForNonPunct) {
  224. EXPECT_FALSE(IsPunct('\0'));
  225. EXPECT_FALSE(IsPunct(' '));
  226. EXPECT_FALSE(IsPunct('\n'));
  227. EXPECT_FALSE(IsPunct('a'));
  228. EXPECT_FALSE(IsPunct('0'));
  229. }
  230. TEST(IsPunctTest, IsTrueForPunct) {
  231. for (const char* p = "^-!\"#$%&'()*+,./:;<=>?@[\\]_`{|}~"; *p; p++) {
  232. EXPECT_PRED1(IsPunct, *p);
  233. }
  234. }
  235. TEST(IsRepeatTest, IsFalseForNonRepeatChar) {
  236. EXPECT_FALSE(IsRepeat('\0'));
  237. EXPECT_FALSE(IsRepeat(' '));
  238. EXPECT_FALSE(IsRepeat('a'));
  239. EXPECT_FALSE(IsRepeat('1'));
  240. EXPECT_FALSE(IsRepeat('-'));
  241. }
  242. TEST(IsRepeatTest, IsTrueForRepeatChar) {
  243. EXPECT_TRUE(IsRepeat('?'));
  244. EXPECT_TRUE(IsRepeat('*'));
  245. EXPECT_TRUE(IsRepeat('+'));
  246. }
  247. TEST(IsWhiteSpaceTest, IsFalseForNonWhiteSpace) {
  248. EXPECT_FALSE(IsWhiteSpace('\0'));
  249. EXPECT_FALSE(IsWhiteSpace('a'));
  250. EXPECT_FALSE(IsWhiteSpace('1'));
  251. EXPECT_FALSE(IsWhiteSpace('+'));
  252. EXPECT_FALSE(IsWhiteSpace('_'));
  253. }
  254. TEST(IsWhiteSpaceTest, IsTrueForWhiteSpace) {
  255. EXPECT_TRUE(IsWhiteSpace(' '));
  256. EXPECT_TRUE(IsWhiteSpace('\n'));
  257. EXPECT_TRUE(IsWhiteSpace('\r'));
  258. EXPECT_TRUE(IsWhiteSpace('\t'));
  259. EXPECT_TRUE(IsWhiteSpace('\v'));
  260. EXPECT_TRUE(IsWhiteSpace('\f'));
  261. }
  262. TEST(IsWordCharTest, IsFalseForNonWordChar) {
  263. EXPECT_FALSE(IsWordChar('\0'));
  264. EXPECT_FALSE(IsWordChar('+'));
  265. EXPECT_FALSE(IsWordChar('.'));
  266. EXPECT_FALSE(IsWordChar(' '));
  267. EXPECT_FALSE(IsWordChar('\n'));
  268. }
  269. TEST(IsWordCharTest, IsTrueForLetter) {
  270. EXPECT_TRUE(IsWordChar('a'));
  271. EXPECT_TRUE(IsWordChar('b'));
  272. EXPECT_TRUE(IsWordChar('A'));
  273. EXPECT_TRUE(IsWordChar('Z'));
  274. }
  275. TEST(IsWordCharTest, IsTrueForDigit) {
  276. EXPECT_TRUE(IsWordChar('0'));
  277. EXPECT_TRUE(IsWordChar('1'));
  278. EXPECT_TRUE(IsWordChar('7'));
  279. EXPECT_TRUE(IsWordChar('9'));
  280. }
  281. TEST(IsWordCharTest, IsTrueForUnderscore) {
  282. EXPECT_TRUE(IsWordChar('_'));
  283. }
  284. TEST(IsValidEscapeTest, IsFalseForNonPrintable) {
  285. EXPECT_FALSE(IsValidEscape('\0'));
  286. EXPECT_FALSE(IsValidEscape('\007'));
  287. }
  288. TEST(IsValidEscapeTest, IsFalseForDigit) {
  289. EXPECT_FALSE(IsValidEscape('0'));
  290. EXPECT_FALSE(IsValidEscape('9'));
  291. }
  292. TEST(IsValidEscapeTest, IsFalseForWhiteSpace) {
  293. EXPECT_FALSE(IsValidEscape(' '));
  294. EXPECT_FALSE(IsValidEscape('\n'));
  295. }
  296. TEST(IsValidEscapeTest, IsFalseForSomeLetter) {
  297. EXPECT_FALSE(IsValidEscape('a'));
  298. EXPECT_FALSE(IsValidEscape('Z'));
  299. }
  300. TEST(IsValidEscapeTest, IsTrueForPunct) {
  301. EXPECT_TRUE(IsValidEscape('.'));
  302. EXPECT_TRUE(IsValidEscape('-'));
  303. EXPECT_TRUE(IsValidEscape('^'));
  304. EXPECT_TRUE(IsValidEscape('$'));
  305. EXPECT_TRUE(IsValidEscape('('));
  306. EXPECT_TRUE(IsValidEscape(']'));
  307. EXPECT_TRUE(IsValidEscape('{'));
  308. EXPECT_TRUE(IsValidEscape('|'));
  309. }
  310. TEST(IsValidEscapeTest, IsTrueForSomeLetter) {
  311. EXPECT_TRUE(IsValidEscape('d'));
  312. EXPECT_TRUE(IsValidEscape('D'));
  313. EXPECT_TRUE(IsValidEscape('s'));
  314. EXPECT_TRUE(IsValidEscape('S'));
  315. EXPECT_TRUE(IsValidEscape('w'));
  316. EXPECT_TRUE(IsValidEscape('W'));
  317. }
  318. TEST(AtomMatchesCharTest, EscapedPunct) {
  319. EXPECT_FALSE(AtomMatchesChar(true, '\\', '\0'));
  320. EXPECT_FALSE(AtomMatchesChar(true, '\\', ' '));
  321. EXPECT_FALSE(AtomMatchesChar(true, '_', '.'));
  322. EXPECT_FALSE(AtomMatchesChar(true, '.', 'a'));
  323. EXPECT_TRUE(AtomMatchesChar(true, '\\', '\\'));
  324. EXPECT_TRUE(AtomMatchesChar(true, '_', '_'));
  325. EXPECT_TRUE(AtomMatchesChar(true, '+', '+'));
  326. EXPECT_TRUE(AtomMatchesChar(true, '.', '.'));
  327. }
  328. TEST(AtomMatchesCharTest, Escaped_d) {
  329. EXPECT_FALSE(AtomMatchesChar(true, 'd', '\0'));
  330. EXPECT_FALSE(AtomMatchesChar(true, 'd', 'a'));
  331. EXPECT_FALSE(AtomMatchesChar(true, 'd', '.'));
  332. EXPECT_TRUE(AtomMatchesChar(true, 'd', '0'));
  333. EXPECT_TRUE(AtomMatchesChar(true, 'd', '9'));
  334. }
  335. TEST(AtomMatchesCharTest, Escaped_D) {
  336. EXPECT_FALSE(AtomMatchesChar(true, 'D', '0'));
  337. EXPECT_FALSE(AtomMatchesChar(true, 'D', '9'));
  338. EXPECT_TRUE(AtomMatchesChar(true, 'D', '\0'));
  339. EXPECT_TRUE(AtomMatchesChar(true, 'D', 'a'));
  340. EXPECT_TRUE(AtomMatchesChar(true, 'D', '-'));
  341. }
  342. TEST(AtomMatchesCharTest, Escaped_s) {
  343. EXPECT_FALSE(AtomMatchesChar(true, 's', '\0'));
  344. EXPECT_FALSE(AtomMatchesChar(true, 's', 'a'));
  345. EXPECT_FALSE(AtomMatchesChar(true, 's', '.'));
  346. EXPECT_FALSE(AtomMatchesChar(true, 's', '9'));
  347. EXPECT_TRUE(AtomMatchesChar(true, 's', ' '));
  348. EXPECT_TRUE(AtomMatchesChar(true, 's', '\n'));
  349. EXPECT_TRUE(AtomMatchesChar(true, 's', '\t'));
  350. }
  351. TEST(AtomMatchesCharTest, Escaped_S) {
  352. EXPECT_FALSE(AtomMatchesChar(true, 'S', ' '));
  353. EXPECT_FALSE(AtomMatchesChar(true, 'S', '\r'));
  354. EXPECT_TRUE(AtomMatchesChar(true, 'S', '\0'));
  355. EXPECT_TRUE(AtomMatchesChar(true, 'S', 'a'));
  356. EXPECT_TRUE(AtomMatchesChar(true, 'S', '9'));
  357. }
  358. TEST(AtomMatchesCharTest, Escaped_w) {
  359. EXPECT_FALSE(AtomMatchesChar(true, 'w', '\0'));
  360. EXPECT_FALSE(AtomMatchesChar(true, 'w', '+'));
  361. EXPECT_FALSE(AtomMatchesChar(true, 'w', ' '));
  362. EXPECT_FALSE(AtomMatchesChar(true, 'w', '\n'));
  363. EXPECT_TRUE(AtomMatchesChar(true, 'w', '0'));
  364. EXPECT_TRUE(AtomMatchesChar(true, 'w', 'b'));
  365. EXPECT_TRUE(AtomMatchesChar(true, 'w', 'C'));
  366. EXPECT_TRUE(AtomMatchesChar(true, 'w', '_'));
  367. }
  368. TEST(AtomMatchesCharTest, Escaped_W) {
  369. EXPECT_FALSE(AtomMatchesChar(true, 'W', 'A'));
  370. EXPECT_FALSE(AtomMatchesChar(true, 'W', 'b'));
  371. EXPECT_FALSE(AtomMatchesChar(true, 'W', '9'));
  372. EXPECT_FALSE(AtomMatchesChar(true, 'W', '_'));
  373. EXPECT_TRUE(AtomMatchesChar(true, 'W', '\0'));
  374. EXPECT_TRUE(AtomMatchesChar(true, 'W', '*'));
  375. EXPECT_TRUE(AtomMatchesChar(true, 'W', '\n'));
  376. }
  377. TEST(AtomMatchesCharTest, EscapedWhiteSpace) {
  378. EXPECT_FALSE(AtomMatchesChar(true, 'f', '\0'));
  379. EXPECT_FALSE(AtomMatchesChar(true, 'f', '\n'));
  380. EXPECT_FALSE(AtomMatchesChar(true, 'n', '\0'));
  381. EXPECT_FALSE(AtomMatchesChar(true, 'n', '\r'));
  382. EXPECT_FALSE(AtomMatchesChar(true, 'r', '\0'));
  383. EXPECT_FALSE(AtomMatchesChar(true, 'r', 'a'));
  384. EXPECT_FALSE(AtomMatchesChar(true, 't', '\0'));
  385. EXPECT_FALSE(AtomMatchesChar(true, 't', 't'));
  386. EXPECT_FALSE(AtomMatchesChar(true, 'v', '\0'));
  387. EXPECT_FALSE(AtomMatchesChar(true, 'v', '\f'));
  388. EXPECT_TRUE(AtomMatchesChar(true, 'f', '\f'));
  389. EXPECT_TRUE(AtomMatchesChar(true, 'n', '\n'));
  390. EXPECT_TRUE(AtomMatchesChar(true, 'r', '\r'));
  391. EXPECT_TRUE(AtomMatchesChar(true, 't', '\t'));
  392. EXPECT_TRUE(AtomMatchesChar(true, 'v', '\v'));
  393. }
  394. TEST(AtomMatchesCharTest, UnescapedDot) {
  395. EXPECT_FALSE(AtomMatchesChar(false, '.', '\n'));
  396. EXPECT_TRUE(AtomMatchesChar(false, '.', '\0'));
  397. EXPECT_TRUE(AtomMatchesChar(false, '.', '.'));
  398. EXPECT_TRUE(AtomMatchesChar(false, '.', 'a'));
  399. EXPECT_TRUE(AtomMatchesChar(false, '.', ' '));
  400. }
  401. TEST(AtomMatchesCharTest, UnescapedChar) {
  402. EXPECT_FALSE(AtomMatchesChar(false, 'a', '\0'));
  403. EXPECT_FALSE(AtomMatchesChar(false, 'a', 'b'));
  404. EXPECT_FALSE(AtomMatchesChar(false, '$', 'a'));
  405. EXPECT_TRUE(AtomMatchesChar(false, '$', '$'));
  406. EXPECT_TRUE(AtomMatchesChar(false, '5', '5'));
  407. EXPECT_TRUE(AtomMatchesChar(false, 'Z', 'Z'));
  408. }
  409. TEST(ValidateRegexTest, GeneratesFailureAndReturnsFalseForInvalid) {
  410. EXPECT_NONFATAL_FAILURE(ASSERT_FALSE(ValidateRegex(NULL)),
  411. "NULL is not a valid simple regular expression");
  412. EXPECT_NONFATAL_FAILURE(
  413. ASSERT_FALSE(ValidateRegex("a\\")),
  414. "Syntax error at index 1 in simple regular expression \"a\\\": ");
  415. EXPECT_NONFATAL_FAILURE(ASSERT_FALSE(ValidateRegex("a\\")),
  416. "'\\' cannot appear at the end");
  417. EXPECT_NONFATAL_FAILURE(ASSERT_FALSE(ValidateRegex("\\n\\")),
  418. "'\\' cannot appear at the end");
  419. EXPECT_NONFATAL_FAILURE(ASSERT_FALSE(ValidateRegex("\\s\\hb")),
  420. "invalid escape sequence \"\\h\"");
  421. EXPECT_NONFATAL_FAILURE(ASSERT_FALSE(ValidateRegex("^^")),
  422. "'^' can only appear at the beginning");
  423. EXPECT_NONFATAL_FAILURE(ASSERT_FALSE(ValidateRegex(".*^b")),
  424. "'^' can only appear at the beginning");
  425. EXPECT_NONFATAL_FAILURE(ASSERT_FALSE(ValidateRegex("$$")),
  426. "'$' can only appear at the end");
  427. EXPECT_NONFATAL_FAILURE(ASSERT_FALSE(ValidateRegex("^$a")),
  428. "'$' can only appear at the end");
  429. EXPECT_NONFATAL_FAILURE(ASSERT_FALSE(ValidateRegex("a(b")),
  430. "'(' is unsupported");
  431. EXPECT_NONFATAL_FAILURE(ASSERT_FALSE(ValidateRegex("ab)")),
  432. "')' is unsupported");
  433. EXPECT_NONFATAL_FAILURE(ASSERT_FALSE(ValidateRegex("[ab")),
  434. "'[' is unsupported");
  435. EXPECT_NONFATAL_FAILURE(ASSERT_FALSE(ValidateRegex("a{2")),
  436. "'{' is unsupported");
  437. EXPECT_NONFATAL_FAILURE(ASSERT_FALSE(ValidateRegex("?")),
  438. "'?' can only follow a repeatable token");
  439. EXPECT_NONFATAL_FAILURE(ASSERT_FALSE(ValidateRegex("^*")),
  440. "'*' can only follow a repeatable token");
  441. EXPECT_NONFATAL_FAILURE(ASSERT_FALSE(ValidateRegex("5*+")),
  442. "'+' can only follow a repeatable token");
  443. }
  444. TEST(ValidateRegexTest, ReturnsTrueForValid) {
  445. EXPECT_TRUE(ValidateRegex(""));
  446. EXPECT_TRUE(ValidateRegex("a"));
  447. EXPECT_TRUE(ValidateRegex(".*"));
  448. EXPECT_TRUE(ValidateRegex("^a_+"));
  449. EXPECT_TRUE(ValidateRegex("^a\\t\\&?"));
  450. EXPECT_TRUE(ValidateRegex("09*$"));
  451. EXPECT_TRUE(ValidateRegex("^Z$"));
  452. EXPECT_TRUE(ValidateRegex("a\\^Z\\$\\(\\)\\|\\[\\]\\{\\}"));
  453. }
  454. TEST(MatchRepetitionAndRegexAtHeadTest, WorksForZeroOrOne) {
  455. EXPECT_FALSE(MatchRepetitionAndRegexAtHead(false, 'a', '?', "a", "ba"));
  456. // Repeating more than once.
  457. EXPECT_FALSE(MatchRepetitionAndRegexAtHead(false, 'a', '?', "b", "aab"));
  458. // Repeating zero times.
  459. EXPECT_TRUE(MatchRepetitionAndRegexAtHead(false, 'a', '?', "b", "ba"));
  460. // Repeating once.
  461. EXPECT_TRUE(MatchRepetitionAndRegexAtHead(false, 'a', '?', "b", "ab"));
  462. EXPECT_TRUE(MatchRepetitionAndRegexAtHead(false, '#', '?', ".", "##"));
  463. }
  464. TEST(MatchRepetitionAndRegexAtHeadTest, WorksForZeroOrMany) {
  465. EXPECT_FALSE(MatchRepetitionAndRegexAtHead(false, '.', '*', "a$", "baab"));
  466. // Repeating zero times.
  467. EXPECT_TRUE(MatchRepetitionAndRegexAtHead(false, '.', '*', "b", "bc"));
  468. // Repeating once.
  469. EXPECT_TRUE(MatchRepetitionAndRegexAtHead(false, '.', '*', "b", "abc"));
  470. // Repeating more than once.
  471. EXPECT_TRUE(MatchRepetitionAndRegexAtHead(true, 'w', '*', "-", "ab_1-g"));
  472. }
  473. TEST(MatchRepetitionAndRegexAtHeadTest, WorksForOneOrMany) {
  474. EXPECT_FALSE(MatchRepetitionAndRegexAtHead(false, '.', '+', "a$", "baab"));
  475. // Repeating zero times.
  476. EXPECT_FALSE(MatchRepetitionAndRegexAtHead(false, '.', '+', "b", "bc"));
  477. // Repeating once.
  478. EXPECT_TRUE(MatchRepetitionAndRegexAtHead(false, '.', '+', "b", "abc"));
  479. // Repeating more than once.
  480. EXPECT_TRUE(MatchRepetitionAndRegexAtHead(true, 'w', '+', "-", "ab_1-g"));
  481. }
  482. TEST(MatchRegexAtHeadTest, ReturnsTrueForEmptyRegex) {
  483. EXPECT_TRUE(MatchRegexAtHead("", ""));
  484. EXPECT_TRUE(MatchRegexAtHead("", "ab"));
  485. }
  486. TEST(MatchRegexAtHeadTest, WorksWhenDollarIsInRegex) {
  487. EXPECT_FALSE(MatchRegexAtHead("$", "a"));
  488. EXPECT_TRUE(MatchRegexAtHead("$", ""));
  489. EXPECT_TRUE(MatchRegexAtHead("a$", "a"));
  490. }
  491. TEST(MatchRegexAtHeadTest, WorksWhenRegexStartsWithEscapeSequence) {
  492. EXPECT_FALSE(MatchRegexAtHead("\\w", "+"));
  493. EXPECT_FALSE(MatchRegexAtHead("\\W", "ab"));
  494. EXPECT_TRUE(MatchRegexAtHead("\\sa", "\nab"));
  495. EXPECT_TRUE(MatchRegexAtHead("\\d", "1a"));
  496. }
  497. TEST(MatchRegexAtHeadTest, WorksWhenRegexStartsWithRepetition) {
  498. EXPECT_FALSE(MatchRegexAtHead(".+a", "abc"));
  499. EXPECT_FALSE(MatchRegexAtHead("a?b", "aab"));
  500. EXPECT_TRUE(MatchRegexAtHead(".*a", "bc12-ab"));
  501. EXPECT_TRUE(MatchRegexAtHead("a?b", "b"));
  502. EXPECT_TRUE(MatchRegexAtHead("a?b", "ab"));
  503. }
  504. TEST(MatchRegexAtHeadTest,
  505. WorksWhenRegexStartsWithRepetionOfEscapeSequence) {
  506. EXPECT_FALSE(MatchRegexAtHead("\\.+a", "abc"));
  507. EXPECT_FALSE(MatchRegexAtHead("\\s?b", " b"));
  508. EXPECT_TRUE(MatchRegexAtHead("\\(*a", "((((ab"));
  509. EXPECT_TRUE(MatchRegexAtHead("\\^?b", "^b"));
  510. EXPECT_TRUE(MatchRegexAtHead("\\\\?b", "b"));
  511. EXPECT_TRUE(MatchRegexAtHead("\\\\?b", "\\b"));
  512. }
  513. TEST(MatchRegexAtHeadTest, MatchesSequentially) {
  514. EXPECT_FALSE(MatchRegexAtHead("ab.*c", "acabc"));
  515. EXPECT_TRUE(MatchRegexAtHead("ab.*c", "ab-fsc"));
  516. }
  517. TEST(MatchRegexAnywhereTest, ReturnsFalseWhenStringIsNull) {
  518. EXPECT_FALSE(MatchRegexAnywhere("", NULL));
  519. }
  520. TEST(MatchRegexAnywhereTest, WorksWhenRegexStartsWithCaret) {
  521. EXPECT_FALSE(MatchRegexAnywhere("^a", "ba"));
  522. EXPECT_FALSE(MatchRegexAnywhere("^$", "a"));
  523. EXPECT_TRUE(MatchRegexAnywhere("^a", "ab"));
  524. EXPECT_TRUE(MatchRegexAnywhere("^", "ab"));
  525. EXPECT_TRUE(MatchRegexAnywhere("^$", ""));
  526. }
  527. TEST(MatchRegexAnywhereTest, ReturnsFalseWhenNoMatch) {
  528. EXPECT_FALSE(MatchRegexAnywhere("a", "bcde123"));
  529. EXPECT_FALSE(MatchRegexAnywhere("a.+a", "--aa88888888"));
  530. }
  531. TEST(MatchRegexAnywhereTest, ReturnsTrueWhenMatchingPrefix) {
  532. EXPECT_TRUE(MatchRegexAnywhere("\\w+", "ab1_ - 5"));
  533. EXPECT_TRUE(MatchRegexAnywhere(".*=", "="));
  534. EXPECT_TRUE(MatchRegexAnywhere("x.*ab?.*bc", "xaaabc"));
  535. }
  536. TEST(MatchRegexAnywhereTest, ReturnsTrueWhenMatchingNonPrefix) {
  537. EXPECT_TRUE(MatchRegexAnywhere("\\w+", "$$$ ab1_ - 5"));
  538. EXPECT_TRUE(MatchRegexAnywhere("\\.+=", "= ...="));
  539. }
  540. // Tests RE's implicit constructors.
  541. TEST(RETest, ImplicitConstructorWorks) {
  542. const RE empty("");
  543. EXPECT_STREQ("", empty.pattern());
  544. const RE simple("hello");
  545. EXPECT_STREQ("hello", simple.pattern());
  546. }
  547. // Tests that RE's constructors reject invalid regular expressions.
  548. TEST(RETest, RejectsInvalidRegex) {
  549. EXPECT_NONFATAL_FAILURE({
  550. const RE normal(NULL);
  551. }, "NULL is not a valid simple regular expression");
  552. EXPECT_NONFATAL_FAILURE({
  553. const RE normal(".*(\\w+");
  554. }, "'(' is unsupported");
  555. EXPECT_NONFATAL_FAILURE({
  556. const RE invalid("^?");
  557. }, "'?' can only follow a repeatable token");
  558. }
  559. // Tests RE::FullMatch().
  560. TEST(RETest, FullMatchWorks) {
  561. const RE empty("");
  562. EXPECT_TRUE(RE::FullMatch("", empty));
  563. EXPECT_FALSE(RE::FullMatch("a", empty));
  564. const RE re1("a");
  565. EXPECT_TRUE(RE::FullMatch("a", re1));
  566. const RE re("a.*z");
  567. EXPECT_TRUE(RE::FullMatch("az", re));
  568. EXPECT_TRUE(RE::FullMatch("axyz", re));
  569. EXPECT_FALSE(RE::FullMatch("baz", re));
  570. EXPECT_FALSE(RE::FullMatch("azy", re));
  571. }
  572. // Tests RE::PartialMatch().
  573. TEST(RETest, PartialMatchWorks) {
  574. const RE empty("");
  575. EXPECT_TRUE(RE::PartialMatch("", empty));
  576. EXPECT_TRUE(RE::PartialMatch("a", empty));
  577. const RE re("a.*z");
  578. EXPECT_TRUE(RE::PartialMatch("az", re));
  579. EXPECT_TRUE(RE::PartialMatch("axyz", re));
  580. EXPECT_TRUE(RE::PartialMatch("baz", re));
  581. EXPECT_TRUE(RE::PartialMatch("azy", re));
  582. EXPECT_FALSE(RE::PartialMatch("zza", re));
  583. }
  584. #endif // GTEST_USES_POSIX_RE
  585. #if !GTEST_OS_WINDOWS_MOBILE
  586. TEST(CaptureTest, CapturesStdout) {
  587. CaptureStdout();
  588. fprintf(stdout, "abc");
  589. EXPECT_STREQ("abc", GetCapturedStdout().c_str());
  590. CaptureStdout();
  591. fprintf(stdout, "def%cghi", '\0');
  592. EXPECT_EQ(::std::string("def\0ghi", 7), ::std::string(GetCapturedStdout()));
  593. }
  594. TEST(CaptureTest, CapturesStderr) {
  595. CaptureStderr();
  596. fprintf(stderr, "jkl");
  597. EXPECT_STREQ("jkl", GetCapturedStderr().c_str());
  598. CaptureStderr();
  599. fprintf(stderr, "jkl%cmno", '\0');
  600. EXPECT_EQ(::std::string("jkl\0mno", 7), ::std::string(GetCapturedStderr()));
  601. }
  602. // Tests that stdout and stderr capture don't interfere with each other.
  603. TEST(CaptureTest, CapturesStdoutAndStderr) {
  604. CaptureStdout();
  605. CaptureStderr();
  606. fprintf(stdout, "pqr");
  607. fprintf(stderr, "stu");
  608. EXPECT_STREQ("pqr", GetCapturedStdout().c_str());
  609. EXPECT_STREQ("stu", GetCapturedStderr().c_str());
  610. }
  611. TEST(CaptureDeathTest, CannotReenterStdoutCapture) {
  612. CaptureStdout();
  613. EXPECT_DEATH_IF_SUPPORTED(CaptureStdout();,
  614. "Only one stdout capturer can exist at a time");
  615. GetCapturedStdout();
  616. // We cannot test stderr capturing using death tests as they use it
  617. // themselves.
  618. }
  619. #endif // !GTEST_OS_WINDOWS_MOBILE
  620. TEST(ThreadLocalTest, DefaultConstructorInitializesToDefaultValues) {
  621. ThreadLocal<int> t1;
  622. EXPECT_EQ(0, t1.get());
  623. ThreadLocal<void*> t2;
  624. EXPECT_TRUE(t2.get() == NULL);
  625. }
  626. TEST(ThreadLocalTest, SingleParamConstructorInitializesToParam) {
  627. ThreadLocal<int> t1(123);
  628. EXPECT_EQ(123, t1.get());
  629. int i = 0;
  630. ThreadLocal<int*> t2(&i);
  631. EXPECT_EQ(&i, t2.get());
  632. }
  633. class NoDefaultContructor {
  634. public:
  635. explicit NoDefaultContructor(const char*) {}
  636. NoDefaultContructor(const NoDefaultContructor&) {}
  637. };
  638. TEST(ThreadLocalTest, ValueDefaultContructorIsNotRequiredForParamVersion) {
  639. ThreadLocal<NoDefaultContructor> bar(NoDefaultContructor("foo"));
  640. bar.pointer();
  641. }
  642. TEST(ThreadLocalTest, GetAndPointerReturnSameValue) {
  643. ThreadLocal<String> thread_local;
  644. EXPECT_EQ(thread_local.pointer(), &(thread_local.get()));
  645. // Verifies the condition still holds after calling set.
  646. thread_local.set("foo");
  647. EXPECT_EQ(thread_local.pointer(), &(thread_local.get()));
  648. }
  649. TEST(ThreadLocalTest, PointerAndConstPointerReturnSameValue) {
  650. ThreadLocal<String> thread_local;
  651. const ThreadLocal<String>& const_thread_local = thread_local;
  652. EXPECT_EQ(thread_local.pointer(), const_thread_local.pointer());
  653. thread_local.set("foo");
  654. EXPECT_EQ(thread_local.pointer(), const_thread_local.pointer());
  655. }
  656. #if GTEST_IS_THREADSAFE
  657. void AddTwo(int* param) { *param += 2; }
  658. TEST(ThreadWithParamTest, ConstructorExecutesThreadFunc) {
  659. int i = 40;
  660. ThreadWithParam<int*> thread(&AddTwo, &i, NULL);
  661. thread.Join();
  662. EXPECT_EQ(42, i);
  663. }
  664. TEST(MutexDeathTest, AssertHeldShouldAssertWhenNotLocked) {
  665. // AssertHeld() is flaky only in the presence of multiple threads accessing
  666. // the lock. In this case, the test is robust.
  667. EXPECT_DEATH_IF_SUPPORTED({
  668. Mutex m;
  669. { MutexLock lock(&m); }
  670. m.AssertHeld();
  671. },
  672. "thread .*hold");
  673. }
  674. TEST(MutexTest, AssertHeldShouldNotAssertWhenLocked) {
  675. Mutex m;
  676. MutexLock lock(&m);
  677. m.AssertHeld();
  678. }
  679. class AtomicCounterWithMutex {
  680. public:
  681. explicit AtomicCounterWithMutex(Mutex* mutex) :
  682. value_(0), mutex_(mutex), random_(42) {}
  683. void Increment() {
  684. MutexLock lock(mutex_);
  685. int temp = value_;
  686. {
  687. // Locking a mutex puts up a memory barrier, preventing reads and
  688. // writes to value_ rearranged when observed from other threads.
  689. //
  690. // We cannot use Mutex and MutexLock here or rely on their memory
  691. // barrier functionality as we are testing them here.
  692. pthread_mutex_t memory_barrier_mutex;
  693. GTEST_CHECK_POSIX_SUCCESS_(
  694. pthread_mutex_init(&memory_barrier_mutex, NULL));
  695. GTEST_CHECK_POSIX_SUCCESS_(pthread_mutex_lock(&memory_barrier_mutex));
  696. SleepMilliseconds(random_.Generate(30));
  697. GTEST_CHECK_POSIX_SUCCESS_(pthread_mutex_unlock(&memory_barrier_mutex));
  698. }
  699. value_ = temp + 1;
  700. }
  701. int value() const { return value_; }
  702. private:
  703. volatile int value_;
  704. Mutex* const mutex_; // Protects value_.
  705. Random random_;
  706. };
  707. void CountingThreadFunc(pair<AtomicCounterWithMutex*, int> param) {
  708. for (int i = 0; i < param.second; ++i)
  709. param.first->Increment();
  710. }
  711. // Tests that the mutex only lets one thread at a time to lock it.
  712. TEST(MutexTest, OnlyOneThreadCanLockAtATime) {
  713. Mutex mutex;
  714. AtomicCounterWithMutex locked_counter(&mutex);
  715. typedef ThreadWithParam<pair<AtomicCounterWithMutex*, int> > ThreadType;
  716. const int kCycleCount = 20;
  717. const int kThreadCount = 7;
  718. scoped_ptr<ThreadType> counting_threads[kThreadCount];
  719. Notification threads_can_start;
  720. // Creates and runs kThreadCount threads that increment locked_counter
  721. // kCycleCount times each.
  722. for (int i = 0; i < kThreadCount; ++i) {
  723. counting_threads[i].reset(new ThreadType(&CountingThreadFunc,
  724. make_pair(&locked_counter,
  725. kCycleCount),
  726. &threads_can_start));
  727. }
  728. threads_can_start.Notify();
  729. for (int i = 0; i < kThreadCount; ++i)
  730. counting_threads[i]->Join();
  731. // If the mutex lets more than one thread to increment the counter at a
  732. // time, they are likely to encounter a race condition and have some
  733. // increments overwritten, resulting in the lower then expected counter
  734. // value.
  735. EXPECT_EQ(kCycleCount * kThreadCount, locked_counter.value());
  736. }
  737. template <typename T>
  738. void RunFromThread(void (func)(T), T param) {
  739. ThreadWithParam<T> thread(func, param, NULL);
  740. thread.Join();
  741. }
  742. void RetrieveThreadLocalValue(pair<ThreadLocal<String>*, String*> param) {
  743. *param.second = param.first->get();
  744. }
  745. TEST(ThreadLocalTest, ParameterizedConstructorSetsDefault) {
  746. ThreadLocal<String> thread_local("foo");
  747. EXPECT_STREQ("foo", thread_local.get().c_str());
  748. thread_local.set("bar");
  749. EXPECT_STREQ("bar", thread_local.get().c_str());
  750. String result;
  751. RunFromThread(&RetrieveThreadLocalValue, make_pair(&thread_local, &result));
  752. EXPECT_STREQ("foo", result.c_str());
  753. }
  754. // DestructorTracker keeps track of whether its instances have been
  755. // destroyed.
  756. static std::vector<bool> g_destroyed;
  757. class DestructorTracker {
  758. public:
  759. DestructorTracker() : index_(GetNewIndex()) {}
  760. DestructorTracker(const DestructorTracker& /* rhs */)
  761. : index_(GetNewIndex()) {}
  762. ~DestructorTracker() {
  763. // We never access g_destroyed concurrently, so we don't need to
  764. // protect the write operation under a mutex.
  765. g_destroyed[index_] = true;
  766. }
  767. private:
  768. static int GetNewIndex() {
  769. g_destroyed.push_back(false);
  770. return g_destroyed.size() - 1;
  771. }
  772. const int index_;
  773. };
  774. typedef ThreadLocal<DestructorTracker>* ThreadParam;
  775. void CallThreadLocalGet(ThreadParam thread_local) {
  776. thread_local->get();
  777. }
  778. // Tests that when a ThreadLocal object dies in a thread, it destroys
  779. // the managed object for that thread.
  780. TEST(ThreadLocalTest, DestroysManagedObjectForOwnThreadWhenDying) {
  781. g_destroyed.clear();
  782. {
  783. // The next line default constructs a DestructorTracker object as
  784. // the default value of objects managed by thread_local.
  785. ThreadLocal<DestructorTracker> thread_local;
  786. ASSERT_EQ(1U, g_destroyed.size());
  787. ASSERT_FALSE(g_destroyed[0]);
  788. // This creates another DestructorTracker object for the main thread.
  789. thread_local.get();
  790. ASSERT_EQ(2U, g_destroyed.size());
  791. ASSERT_FALSE(g_destroyed[0]);
  792. ASSERT_FALSE(g_destroyed[1]);
  793. }
  794. // Now thread_local has died. It should have destroyed both the
  795. // default value shared by all threads and the value for the main
  796. // thread.
  797. ASSERT_EQ(2U, g_destroyed.size());
  798. EXPECT_TRUE(g_destroyed[0]);
  799. EXPECT_TRUE(g_destroyed[1]);
  800. g_destroyed.clear();
  801. }
  802. // Tests that when a thread exits, the thread-local object for that
  803. // thread is destroyed.
  804. TEST(ThreadLocalTest, DestroysManagedObjectAtThreadExit) {
  805. g_destroyed.clear();
  806. {
  807. // The next line default constructs a DestructorTracker object as
  808. // the default value of objects managed by thread_local.
  809. ThreadLocal<DestructorTracker> thread_local;
  810. ASSERT_EQ(1U, g_destroyed.size());
  811. ASSERT_FALSE(g_destroyed[0]);
  812. // This creates another DestructorTracker object in the new thread.
  813. ThreadWithParam<ThreadParam> thread(
  814. &CallThreadLocalGet, &thread_local, NULL);
  815. thread.Join();
  816. // Now the new thread has exited. The per-thread object for it
  817. // should have been destroyed.
  818. ASSERT_EQ(2U, g_destroyed.size());
  819. ASSERT_FALSE(g_destroyed[0]);
  820. ASSERT_TRUE(g_destroyed[1]);
  821. }
  822. // Now thread_local has died. The default value should have been
  823. // destroyed too.
  824. ASSERT_EQ(2U, g_destroyed.size());
  825. EXPECT_TRUE(g_destroyed[0]);
  826. EXPECT_TRUE(g_destroyed[1]);
  827. g_destroyed.clear();
  828. }
  829. TEST(ThreadLocalTest, ThreadLocalMutationsAffectOnlyCurrentThread) {
  830. ThreadLocal<String> thread_local;
  831. thread_local.set("Foo");
  832. EXPECT_STREQ("Foo", thread_local.get().c_str());
  833. String result;
  834. RunFromThread(&RetrieveThreadLocalValue, make_pair(&thread_local, &result));
  835. EXPECT_TRUE(result.c_str() == NULL);
  836. }
  837. #endif // GTEST_IS_THREADSAFE
  838. } // namespace internal
  839. } // namespace testing