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