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