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