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