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 <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;
~Base()100 virtual ~Base() {}
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 GTEST_OS_LINUX || GTEST_OS_MAC || GTEST_OS_QNX || GTEST_OS_FUCHSIA || \
285 GTEST_OS_DRAGONFLY || GTEST_OS_FREEBSD || GTEST_OS_GNU_KFREEBSD || \
286 GTEST_OS_NETBSD || GTEST_OS_OPENBSD || GTEST_OS_GNU_HURD
ThreadFunc(void * data)287 void* ThreadFunc(void* data) {
288 internal::Mutex* mutex = static_cast<internal::Mutex*>(data);
289 mutex->Lock();
290 mutex->Unlock();
291 return nullptr;
292 }
293
TEST(GetThreadCountTest,ReturnsCorrectValue)294 TEST(GetThreadCountTest, ReturnsCorrectValue) {
295 size_t starting_count;
296 size_t thread_count_after_create;
297 size_t thread_count_after_join;
298
299 // We can't guarantee that no other thread was created or destroyed between
300 // any two calls to GetThreadCount(). We make multiple attempts, hoping that
301 // background noise is not constant and we would see the "right" values at
302 // some point.
303 for (int attempt = 0; attempt < 20; ++attempt) {
304 starting_count = GetThreadCount();
305 pthread_t thread_id;
306
307 internal::Mutex mutex;
308 {
309 internal::MutexLock lock(&mutex);
310 pthread_attr_t attr;
311 ASSERT_EQ(0, pthread_attr_init(&attr));
312 ASSERT_EQ(0, pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_JOINABLE));
313
314 const int status = pthread_create(&thread_id, &attr, &ThreadFunc, &mutex);
315 ASSERT_EQ(0, pthread_attr_destroy(&attr));
316 ASSERT_EQ(0, status);
317 }
318
319 thread_count_after_create = GetThreadCount();
320
321 void* dummy;
322 ASSERT_EQ(0, pthread_join(thread_id, &dummy));
323
324 // Join before we decide whether we need to retry the test. Retry if an
325 // arbitrary other thread was created or destroyed in the meantime.
326 if (thread_count_after_create != starting_count + 1) continue;
327
328 // The OS may not immediately report the updated thread count after
329 // joining a thread, causing flakiness in this test. To counter that, we
330 // wait for up to .5 seconds for the OS to report the correct value.
331 bool thread_count_matches = false;
332 for (int i = 0; i < 5; ++i) {
333 thread_count_after_join = GetThreadCount();
334 if (thread_count_after_join == starting_count) {
335 thread_count_matches = true;
336 break;
337 }
338
339 std::this_thread::sleep_for(std::chrono::milliseconds(100));
340 }
341
342 // Retry if an arbitrary other thread was created or destroyed.
343 if (!thread_count_matches) continue;
344
345 break;
346 }
347
348 EXPECT_EQ(thread_count_after_create, starting_count + 1);
349 EXPECT_EQ(thread_count_after_join, starting_count);
350 }
351 #else
TEST(GetThreadCountTest,ReturnsZeroWhenUnableToCountThreads)352 TEST(GetThreadCountTest, ReturnsZeroWhenUnableToCountThreads) {
353 EXPECT_EQ(0U, GetThreadCount());
354 }
355 #endif // GTEST_OS_LINUX || GTEST_OS_MAC || GTEST_OS_QNX || GTEST_OS_FUCHSIA
356
TEST(GtestCheckDeathTest,DiesWithCorrectOutputOnFailure)357 TEST(GtestCheckDeathTest, DiesWithCorrectOutputOnFailure) {
358 const bool a_false_condition = false;
359 const char regex[] =
360 #ifdef _MSC_VER
361 "googletest-port-test\\.cc\\(\\d+\\):"
362 #elif GTEST_USES_POSIX_RE
363 "googletest-port-test\\.cc:[0-9]+"
364 #else
365 "googletest-port-test\\.cc:\\d+"
366 #endif // _MSC_VER
367 ".*a_false_condition.*Extra info.*";
368
369 EXPECT_DEATH_IF_SUPPORTED(GTEST_CHECK_(a_false_condition) << "Extra info",
370 regex);
371 }
372
373 #if GTEST_HAS_DEATH_TEST
374
TEST(GtestCheckDeathTest,LivesSilentlyOnSuccess)375 TEST(GtestCheckDeathTest, LivesSilentlyOnSuccess) {
376 EXPECT_EXIT(
377 {
378 GTEST_CHECK_(true) << "Extra info";
379 ::std::cerr << "Success\n";
380 exit(0);
381 },
382 ::testing::ExitedWithCode(0), "Success");
383 }
384
385 #endif // GTEST_HAS_DEATH_TEST
386
387 // Verifies that Google Test choose regular expression engine appropriate to
388 // the platform. The test will produce compiler errors in case of failure.
389 // For simplicity, we only cover the most important platforms here.
TEST(RegexEngineSelectionTest,SelectsCorrectRegexEngine)390 TEST(RegexEngineSelectionTest, SelectsCorrectRegexEngine) {
391 #if GTEST_HAS_ABSL
392 EXPECT_TRUE(GTEST_USES_RE2);
393 #elif GTEST_HAS_POSIX_RE
394 EXPECT_TRUE(GTEST_USES_POSIX_RE);
395 #else
396 EXPECT_TRUE(GTEST_USES_SIMPLE_RE);
397 #endif
398 }
399
400 #if GTEST_USES_POSIX_RE
401
402 template <typename Str>
403 class RETest : public ::testing::Test {};
404
405 // Defines StringTypes as the list of all string types that class RE
406 // supports.
407 typedef testing::Types< ::std::string, const char*> StringTypes;
408
409 TYPED_TEST_SUITE(RETest, StringTypes);
410
411 // Tests RE's implicit constructors.
TYPED_TEST(RETest,ImplicitConstructorWorks)412 TYPED_TEST(RETest, ImplicitConstructorWorks) {
413 const RE empty(TypeParam(""));
414 EXPECT_STREQ("", empty.pattern());
415
416 const RE simple(TypeParam("hello"));
417 EXPECT_STREQ("hello", simple.pattern());
418
419 const RE normal(TypeParam(".*(\\w+)"));
420 EXPECT_STREQ(".*(\\w+)", normal.pattern());
421 }
422
423 // Tests that RE's constructors reject invalid regular expressions.
TYPED_TEST(RETest,RejectsInvalidRegex)424 TYPED_TEST(RETest, RejectsInvalidRegex) {
425 EXPECT_NONFATAL_FAILURE(
426 { const RE invalid(TypeParam("?")); },
427 "\"?\" is not a valid POSIX Extended regular expression.");
428 }
429
430 // Tests RE::FullMatch().
TYPED_TEST(RETest,FullMatchWorks)431 TYPED_TEST(RETest, FullMatchWorks) {
432 const RE empty(TypeParam(""));
433 EXPECT_TRUE(RE::FullMatch(TypeParam(""), empty));
434 EXPECT_FALSE(RE::FullMatch(TypeParam("a"), empty));
435
436 const RE re(TypeParam("a.*z"));
437 EXPECT_TRUE(RE::FullMatch(TypeParam("az"), re));
438 EXPECT_TRUE(RE::FullMatch(TypeParam("axyz"), re));
439 EXPECT_FALSE(RE::FullMatch(TypeParam("baz"), re));
440 EXPECT_FALSE(RE::FullMatch(TypeParam("azy"), re));
441 }
442
443 // Tests RE::PartialMatch().
TYPED_TEST(RETest,PartialMatchWorks)444 TYPED_TEST(RETest, PartialMatchWorks) {
445 const RE empty(TypeParam(""));
446 EXPECT_TRUE(RE::PartialMatch(TypeParam(""), empty));
447 EXPECT_TRUE(RE::PartialMatch(TypeParam("a"), empty));
448
449 const RE re(TypeParam("a.*z"));
450 EXPECT_TRUE(RE::PartialMatch(TypeParam("az"), re));
451 EXPECT_TRUE(RE::PartialMatch(TypeParam("axyz"), re));
452 EXPECT_TRUE(RE::PartialMatch(TypeParam("baz"), re));
453 EXPECT_TRUE(RE::PartialMatch(TypeParam("azy"), re));
454 EXPECT_FALSE(RE::PartialMatch(TypeParam("zza"), re));
455 }
456
457 #elif GTEST_USES_SIMPLE_RE
458
TEST(IsInSetTest,NulCharIsNotInAnySet)459 TEST(IsInSetTest, NulCharIsNotInAnySet) {
460 EXPECT_FALSE(IsInSet('\0', ""));
461 EXPECT_FALSE(IsInSet('\0', "\0"));
462 EXPECT_FALSE(IsInSet('\0', "a"));
463 }
464
TEST(IsInSetTest,WorksForNonNulChars)465 TEST(IsInSetTest, WorksForNonNulChars) {
466 EXPECT_FALSE(IsInSet('a', "Ab"));
467 EXPECT_FALSE(IsInSet('c', ""));
468
469 EXPECT_TRUE(IsInSet('b', "bcd"));
470 EXPECT_TRUE(IsInSet('b', "ab"));
471 }
472
TEST(IsAsciiDigitTest,IsFalseForNonDigit)473 TEST(IsAsciiDigitTest, IsFalseForNonDigit) {
474 EXPECT_FALSE(IsAsciiDigit('\0'));
475 EXPECT_FALSE(IsAsciiDigit(' '));
476 EXPECT_FALSE(IsAsciiDigit('+'));
477 EXPECT_FALSE(IsAsciiDigit('-'));
478 EXPECT_FALSE(IsAsciiDigit('.'));
479 EXPECT_FALSE(IsAsciiDigit('a'));
480 }
481
TEST(IsAsciiDigitTest,IsTrueForDigit)482 TEST(IsAsciiDigitTest, IsTrueForDigit) {
483 EXPECT_TRUE(IsAsciiDigit('0'));
484 EXPECT_TRUE(IsAsciiDigit('1'));
485 EXPECT_TRUE(IsAsciiDigit('5'));
486 EXPECT_TRUE(IsAsciiDigit('9'));
487 }
488
TEST(IsAsciiPunctTest,IsFalseForNonPunct)489 TEST(IsAsciiPunctTest, IsFalseForNonPunct) {
490 EXPECT_FALSE(IsAsciiPunct('\0'));
491 EXPECT_FALSE(IsAsciiPunct(' '));
492 EXPECT_FALSE(IsAsciiPunct('\n'));
493 EXPECT_FALSE(IsAsciiPunct('a'));
494 EXPECT_FALSE(IsAsciiPunct('0'));
495 }
496
TEST(IsAsciiPunctTest,IsTrueForPunct)497 TEST(IsAsciiPunctTest, IsTrueForPunct) {
498 for (const char* p = "^-!\"#$%&'()*+,./:;<=>?@[\\]_`{|}~"; *p; p++) {
499 EXPECT_PRED1(IsAsciiPunct, *p);
500 }
501 }
502
TEST(IsRepeatTest,IsFalseForNonRepeatChar)503 TEST(IsRepeatTest, IsFalseForNonRepeatChar) {
504 EXPECT_FALSE(IsRepeat('\0'));
505 EXPECT_FALSE(IsRepeat(' '));
506 EXPECT_FALSE(IsRepeat('a'));
507 EXPECT_FALSE(IsRepeat('1'));
508 EXPECT_FALSE(IsRepeat('-'));
509 }
510
TEST(IsRepeatTest,IsTrueForRepeatChar)511 TEST(IsRepeatTest, IsTrueForRepeatChar) {
512 EXPECT_TRUE(IsRepeat('?'));
513 EXPECT_TRUE(IsRepeat('*'));
514 EXPECT_TRUE(IsRepeat('+'));
515 }
516
TEST(IsAsciiWhiteSpaceTest,IsFalseForNonWhiteSpace)517 TEST(IsAsciiWhiteSpaceTest, IsFalseForNonWhiteSpace) {
518 EXPECT_FALSE(IsAsciiWhiteSpace('\0'));
519 EXPECT_FALSE(IsAsciiWhiteSpace('a'));
520 EXPECT_FALSE(IsAsciiWhiteSpace('1'));
521 EXPECT_FALSE(IsAsciiWhiteSpace('+'));
522 EXPECT_FALSE(IsAsciiWhiteSpace('_'));
523 }
524
TEST(IsAsciiWhiteSpaceTest,IsTrueForWhiteSpace)525 TEST(IsAsciiWhiteSpaceTest, IsTrueForWhiteSpace) {
526 EXPECT_TRUE(IsAsciiWhiteSpace(' '));
527 EXPECT_TRUE(IsAsciiWhiteSpace('\n'));
528 EXPECT_TRUE(IsAsciiWhiteSpace('\r'));
529 EXPECT_TRUE(IsAsciiWhiteSpace('\t'));
530 EXPECT_TRUE(IsAsciiWhiteSpace('\v'));
531 EXPECT_TRUE(IsAsciiWhiteSpace('\f'));
532 }
533
TEST(IsAsciiWordCharTest,IsFalseForNonWordChar)534 TEST(IsAsciiWordCharTest, IsFalseForNonWordChar) {
535 EXPECT_FALSE(IsAsciiWordChar('\0'));
536 EXPECT_FALSE(IsAsciiWordChar('+'));
537 EXPECT_FALSE(IsAsciiWordChar('.'));
538 EXPECT_FALSE(IsAsciiWordChar(' '));
539 EXPECT_FALSE(IsAsciiWordChar('\n'));
540 }
541
TEST(IsAsciiWordCharTest,IsTrueForLetter)542 TEST(IsAsciiWordCharTest, IsTrueForLetter) {
543 EXPECT_TRUE(IsAsciiWordChar('a'));
544 EXPECT_TRUE(IsAsciiWordChar('b'));
545 EXPECT_TRUE(IsAsciiWordChar('A'));
546 EXPECT_TRUE(IsAsciiWordChar('Z'));
547 }
548
TEST(IsAsciiWordCharTest,IsTrueForDigit)549 TEST(IsAsciiWordCharTest, IsTrueForDigit) {
550 EXPECT_TRUE(IsAsciiWordChar('0'));
551 EXPECT_TRUE(IsAsciiWordChar('1'));
552 EXPECT_TRUE(IsAsciiWordChar('7'));
553 EXPECT_TRUE(IsAsciiWordChar('9'));
554 }
555
TEST(IsAsciiWordCharTest,IsTrueForUnderscore)556 TEST(IsAsciiWordCharTest, IsTrueForUnderscore) {
557 EXPECT_TRUE(IsAsciiWordChar('_'));
558 }
559
TEST(IsValidEscapeTest,IsFalseForNonPrintable)560 TEST(IsValidEscapeTest, IsFalseForNonPrintable) {
561 EXPECT_FALSE(IsValidEscape('\0'));
562 EXPECT_FALSE(IsValidEscape('\007'));
563 }
564
TEST(IsValidEscapeTest,IsFalseForDigit)565 TEST(IsValidEscapeTest, IsFalseForDigit) {
566 EXPECT_FALSE(IsValidEscape('0'));
567 EXPECT_FALSE(IsValidEscape('9'));
568 }
569
TEST(IsValidEscapeTest,IsFalseForWhiteSpace)570 TEST(IsValidEscapeTest, IsFalseForWhiteSpace) {
571 EXPECT_FALSE(IsValidEscape(' '));
572 EXPECT_FALSE(IsValidEscape('\n'));
573 }
574
TEST(IsValidEscapeTest,IsFalseForSomeLetter)575 TEST(IsValidEscapeTest, IsFalseForSomeLetter) {
576 EXPECT_FALSE(IsValidEscape('a'));
577 EXPECT_FALSE(IsValidEscape('Z'));
578 }
579
TEST(IsValidEscapeTest,IsTrueForPunct)580 TEST(IsValidEscapeTest, IsTrueForPunct) {
581 EXPECT_TRUE(IsValidEscape('.'));
582 EXPECT_TRUE(IsValidEscape('-'));
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 }
590
TEST(IsValidEscapeTest,IsTrueForSomeLetter)591 TEST(IsValidEscapeTest, IsTrueForSomeLetter) {
592 EXPECT_TRUE(IsValidEscape('d'));
593 EXPECT_TRUE(IsValidEscape('D'));
594 EXPECT_TRUE(IsValidEscape('s'));
595 EXPECT_TRUE(IsValidEscape('S'));
596 EXPECT_TRUE(IsValidEscape('w'));
597 EXPECT_TRUE(IsValidEscape('W'));
598 }
599
TEST(AtomMatchesCharTest,EscapedPunct)600 TEST(AtomMatchesCharTest, EscapedPunct) {
601 EXPECT_FALSE(AtomMatchesChar(true, '\\', '\0'));
602 EXPECT_FALSE(AtomMatchesChar(true, '\\', ' '));
603 EXPECT_FALSE(AtomMatchesChar(true, '_', '.'));
604 EXPECT_FALSE(AtomMatchesChar(true, '.', 'a'));
605
606 EXPECT_TRUE(AtomMatchesChar(true, '\\', '\\'));
607 EXPECT_TRUE(AtomMatchesChar(true, '_', '_'));
608 EXPECT_TRUE(AtomMatchesChar(true, '+', '+'));
609 EXPECT_TRUE(AtomMatchesChar(true, '.', '.'));
610 }
611
TEST(AtomMatchesCharTest,Escaped_d)612 TEST(AtomMatchesCharTest, Escaped_d) {
613 EXPECT_FALSE(AtomMatchesChar(true, 'd', '\0'));
614 EXPECT_FALSE(AtomMatchesChar(true, 'd', 'a'));
615 EXPECT_FALSE(AtomMatchesChar(true, 'd', '.'));
616
617 EXPECT_TRUE(AtomMatchesChar(true, 'd', '0'));
618 EXPECT_TRUE(AtomMatchesChar(true, 'd', '9'));
619 }
620
TEST(AtomMatchesCharTest,Escaped_D)621 TEST(AtomMatchesCharTest, Escaped_D) {
622 EXPECT_FALSE(AtomMatchesChar(true, 'D', '0'));
623 EXPECT_FALSE(AtomMatchesChar(true, 'D', '9'));
624
625 EXPECT_TRUE(AtomMatchesChar(true, 'D', '\0'));
626 EXPECT_TRUE(AtomMatchesChar(true, 'D', 'a'));
627 EXPECT_TRUE(AtomMatchesChar(true, 'D', '-'));
628 }
629
TEST(AtomMatchesCharTest,Escaped_s)630 TEST(AtomMatchesCharTest, Escaped_s) {
631 EXPECT_FALSE(AtomMatchesChar(true, 's', '\0'));
632 EXPECT_FALSE(AtomMatchesChar(true, 's', 'a'));
633 EXPECT_FALSE(AtomMatchesChar(true, 's', '.'));
634 EXPECT_FALSE(AtomMatchesChar(true, 's', '9'));
635
636 EXPECT_TRUE(AtomMatchesChar(true, 's', ' '));
637 EXPECT_TRUE(AtomMatchesChar(true, 's', '\n'));
638 EXPECT_TRUE(AtomMatchesChar(true, 's', '\t'));
639 }
640
TEST(AtomMatchesCharTest,Escaped_S)641 TEST(AtomMatchesCharTest, Escaped_S) {
642 EXPECT_FALSE(AtomMatchesChar(true, 'S', ' '));
643 EXPECT_FALSE(AtomMatchesChar(true, 'S', '\r'));
644
645 EXPECT_TRUE(AtomMatchesChar(true, 'S', '\0'));
646 EXPECT_TRUE(AtomMatchesChar(true, 'S', 'a'));
647 EXPECT_TRUE(AtomMatchesChar(true, 'S', '9'));
648 }
649
TEST(AtomMatchesCharTest,Escaped_w)650 TEST(AtomMatchesCharTest, Escaped_w) {
651 EXPECT_FALSE(AtomMatchesChar(true, 'w', '\0'));
652 EXPECT_FALSE(AtomMatchesChar(true, 'w', '+'));
653 EXPECT_FALSE(AtomMatchesChar(true, 'w', ' '));
654 EXPECT_FALSE(AtomMatchesChar(true, 'w', '\n'));
655
656 EXPECT_TRUE(AtomMatchesChar(true, 'w', '0'));
657 EXPECT_TRUE(AtomMatchesChar(true, 'w', 'b'));
658 EXPECT_TRUE(AtomMatchesChar(true, 'w', 'C'));
659 EXPECT_TRUE(AtomMatchesChar(true, 'w', '_'));
660 }
661
TEST(AtomMatchesCharTest,Escaped_W)662 TEST(AtomMatchesCharTest, Escaped_W) {
663 EXPECT_FALSE(AtomMatchesChar(true, 'W', 'A'));
664 EXPECT_FALSE(AtomMatchesChar(true, 'W', 'b'));
665 EXPECT_FALSE(AtomMatchesChar(true, 'W', '9'));
666 EXPECT_FALSE(AtomMatchesChar(true, 'W', '_'));
667
668 EXPECT_TRUE(AtomMatchesChar(true, 'W', '\0'));
669 EXPECT_TRUE(AtomMatchesChar(true, 'W', '*'));
670 EXPECT_TRUE(AtomMatchesChar(true, 'W', '\n'));
671 }
672
TEST(AtomMatchesCharTest,EscapedWhiteSpace)673 TEST(AtomMatchesCharTest, EscapedWhiteSpace) {
674 EXPECT_FALSE(AtomMatchesChar(true, 'f', '\0'));
675 EXPECT_FALSE(AtomMatchesChar(true, 'f', '\n'));
676 EXPECT_FALSE(AtomMatchesChar(true, 'n', '\0'));
677 EXPECT_FALSE(AtomMatchesChar(true, 'n', '\r'));
678 EXPECT_FALSE(AtomMatchesChar(true, 'r', '\0'));
679 EXPECT_FALSE(AtomMatchesChar(true, 'r', 'a'));
680 EXPECT_FALSE(AtomMatchesChar(true, 't', '\0'));
681 EXPECT_FALSE(AtomMatchesChar(true, 't', 't'));
682 EXPECT_FALSE(AtomMatchesChar(true, 'v', '\0'));
683 EXPECT_FALSE(AtomMatchesChar(true, 'v', '\f'));
684
685 EXPECT_TRUE(AtomMatchesChar(true, 'f', '\f'));
686 EXPECT_TRUE(AtomMatchesChar(true, 'n', '\n'));
687 EXPECT_TRUE(AtomMatchesChar(true, 'r', '\r'));
688 EXPECT_TRUE(AtomMatchesChar(true, 't', '\t'));
689 EXPECT_TRUE(AtomMatchesChar(true, 'v', '\v'));
690 }
691
TEST(AtomMatchesCharTest,UnescapedDot)692 TEST(AtomMatchesCharTest, UnescapedDot) {
693 EXPECT_FALSE(AtomMatchesChar(false, '.', '\n'));
694
695 EXPECT_TRUE(AtomMatchesChar(false, '.', '\0'));
696 EXPECT_TRUE(AtomMatchesChar(false, '.', '.'));
697 EXPECT_TRUE(AtomMatchesChar(false, '.', 'a'));
698 EXPECT_TRUE(AtomMatchesChar(false, '.', ' '));
699 }
700
TEST(AtomMatchesCharTest,UnescapedChar)701 TEST(AtomMatchesCharTest, UnescapedChar) {
702 EXPECT_FALSE(AtomMatchesChar(false, 'a', '\0'));
703 EXPECT_FALSE(AtomMatchesChar(false, 'a', 'b'));
704 EXPECT_FALSE(AtomMatchesChar(false, '$', 'a'));
705
706 EXPECT_TRUE(AtomMatchesChar(false, '$', '$'));
707 EXPECT_TRUE(AtomMatchesChar(false, '5', '5'));
708 EXPECT_TRUE(AtomMatchesChar(false, 'Z', 'Z'));
709 }
710
TEST(ValidateRegexTest,GeneratesFailureAndReturnsFalseForInvalid)711 TEST(ValidateRegexTest, GeneratesFailureAndReturnsFalseForInvalid) {
712 EXPECT_NONFATAL_FAILURE(ASSERT_FALSE(ValidateRegex(NULL)),
713 "NULL is not a valid simple regular expression");
714 EXPECT_NONFATAL_FAILURE(
715 ASSERT_FALSE(ValidateRegex("a\\")),
716 "Syntax error at index 1 in simple regular expression \"a\\\": ");
717 EXPECT_NONFATAL_FAILURE(ASSERT_FALSE(ValidateRegex("a\\")),
718 "'\\' cannot appear at the end");
719 EXPECT_NONFATAL_FAILURE(ASSERT_FALSE(ValidateRegex("\\n\\")),
720 "'\\' cannot appear at the end");
721 EXPECT_NONFATAL_FAILURE(ASSERT_FALSE(ValidateRegex("\\s\\hb")),
722 "invalid escape sequence \"\\h\"");
723 EXPECT_NONFATAL_FAILURE(ASSERT_FALSE(ValidateRegex("^^")),
724 "'^' can only appear at the beginning");
725 EXPECT_NONFATAL_FAILURE(ASSERT_FALSE(ValidateRegex(".*^b")),
726 "'^' can only appear at the beginning");
727 EXPECT_NONFATAL_FAILURE(ASSERT_FALSE(ValidateRegex("$$")),
728 "'$' can only appear at the end");
729 EXPECT_NONFATAL_FAILURE(ASSERT_FALSE(ValidateRegex("^$a")),
730 "'$' can only appear at the end");
731 EXPECT_NONFATAL_FAILURE(ASSERT_FALSE(ValidateRegex("a(b")),
732 "'(' is unsupported");
733 EXPECT_NONFATAL_FAILURE(ASSERT_FALSE(ValidateRegex("ab)")),
734 "')' is unsupported");
735 EXPECT_NONFATAL_FAILURE(ASSERT_FALSE(ValidateRegex("[ab")),
736 "'[' is unsupported");
737 EXPECT_NONFATAL_FAILURE(ASSERT_FALSE(ValidateRegex("a{2")),
738 "'{' is unsupported");
739 EXPECT_NONFATAL_FAILURE(ASSERT_FALSE(ValidateRegex("?")),
740 "'?' can only follow a repeatable token");
741 EXPECT_NONFATAL_FAILURE(ASSERT_FALSE(ValidateRegex("^*")),
742 "'*' can only follow a repeatable token");
743 EXPECT_NONFATAL_FAILURE(ASSERT_FALSE(ValidateRegex("5*+")),
744 "'+' can only follow a repeatable token");
745 }
746
TEST(ValidateRegexTest,ReturnsTrueForValid)747 TEST(ValidateRegexTest, ReturnsTrueForValid) {
748 EXPECT_TRUE(ValidateRegex(""));
749 EXPECT_TRUE(ValidateRegex("a"));
750 EXPECT_TRUE(ValidateRegex(".*"));
751 EXPECT_TRUE(ValidateRegex("^a_+"));
752 EXPECT_TRUE(ValidateRegex("^a\\t\\&?"));
753 EXPECT_TRUE(ValidateRegex("09*$"));
754 EXPECT_TRUE(ValidateRegex("^Z$"));
755 EXPECT_TRUE(ValidateRegex("a\\^Z\\$\\(\\)\\|\\[\\]\\{\\}"));
756 }
757
TEST(MatchRepetitionAndRegexAtHeadTest,WorksForZeroOrOne)758 TEST(MatchRepetitionAndRegexAtHeadTest, WorksForZeroOrOne) {
759 EXPECT_FALSE(MatchRepetitionAndRegexAtHead(false, 'a', '?', "a", "ba"));
760 // Repeating more than once.
761 EXPECT_FALSE(MatchRepetitionAndRegexAtHead(false, 'a', '?', "b", "aab"));
762
763 // Repeating zero times.
764 EXPECT_TRUE(MatchRepetitionAndRegexAtHead(false, 'a', '?', "b", "ba"));
765 // Repeating once.
766 EXPECT_TRUE(MatchRepetitionAndRegexAtHead(false, 'a', '?', "b", "ab"));
767 EXPECT_TRUE(MatchRepetitionAndRegexAtHead(false, '#', '?', ".", "##"));
768 }
769
TEST(MatchRepetitionAndRegexAtHeadTest,WorksForZeroOrMany)770 TEST(MatchRepetitionAndRegexAtHeadTest, WorksForZeroOrMany) {
771 EXPECT_FALSE(MatchRepetitionAndRegexAtHead(false, '.', '*', "a$", "baab"));
772
773 // Repeating zero times.
774 EXPECT_TRUE(MatchRepetitionAndRegexAtHead(false, '.', '*', "b", "bc"));
775 // Repeating once.
776 EXPECT_TRUE(MatchRepetitionAndRegexAtHead(false, '.', '*', "b", "abc"));
777 // Repeating more than once.
778 EXPECT_TRUE(MatchRepetitionAndRegexAtHead(true, 'w', '*', "-", "ab_1-g"));
779 }
780
TEST(MatchRepetitionAndRegexAtHeadTest,WorksForOneOrMany)781 TEST(MatchRepetitionAndRegexAtHeadTest, WorksForOneOrMany) {
782 EXPECT_FALSE(MatchRepetitionAndRegexAtHead(false, '.', '+', "a$", "baab"));
783 // Repeating zero times.
784 EXPECT_FALSE(MatchRepetitionAndRegexAtHead(false, '.', '+', "b", "bc"));
785
786 // Repeating once.
787 EXPECT_TRUE(MatchRepetitionAndRegexAtHead(false, '.', '+', "b", "abc"));
788 // Repeating more than once.
789 EXPECT_TRUE(MatchRepetitionAndRegexAtHead(true, 'w', '+', "-", "ab_1-g"));
790 }
791
TEST(MatchRegexAtHeadTest,ReturnsTrueForEmptyRegex)792 TEST(MatchRegexAtHeadTest, ReturnsTrueForEmptyRegex) {
793 EXPECT_TRUE(MatchRegexAtHead("", ""));
794 EXPECT_TRUE(MatchRegexAtHead("", "ab"));
795 }
796
TEST(MatchRegexAtHeadTest,WorksWhenDollarIsInRegex)797 TEST(MatchRegexAtHeadTest, WorksWhenDollarIsInRegex) {
798 EXPECT_FALSE(MatchRegexAtHead("$", "a"));
799
800 EXPECT_TRUE(MatchRegexAtHead("$", ""));
801 EXPECT_TRUE(MatchRegexAtHead("a$", "a"));
802 }
803
TEST(MatchRegexAtHeadTest,WorksWhenRegexStartsWithEscapeSequence)804 TEST(MatchRegexAtHeadTest, WorksWhenRegexStartsWithEscapeSequence) {
805 EXPECT_FALSE(MatchRegexAtHead("\\w", "+"));
806 EXPECT_FALSE(MatchRegexAtHead("\\W", "ab"));
807
808 EXPECT_TRUE(MatchRegexAtHead("\\sa", "\nab"));
809 EXPECT_TRUE(MatchRegexAtHead("\\d", "1a"));
810 }
811
TEST(MatchRegexAtHeadTest,WorksWhenRegexStartsWithRepetition)812 TEST(MatchRegexAtHeadTest, WorksWhenRegexStartsWithRepetition) {
813 EXPECT_FALSE(MatchRegexAtHead(".+a", "abc"));
814 EXPECT_FALSE(MatchRegexAtHead("a?b", "aab"));
815
816 EXPECT_TRUE(MatchRegexAtHead(".*a", "bc12-ab"));
817 EXPECT_TRUE(MatchRegexAtHead("a?b", "b"));
818 EXPECT_TRUE(MatchRegexAtHead("a?b", "ab"));
819 }
820
TEST(MatchRegexAtHeadTest,WorksWhenRegexStartsWithRepetionOfEscapeSequence)821 TEST(MatchRegexAtHeadTest, WorksWhenRegexStartsWithRepetionOfEscapeSequence) {
822 EXPECT_FALSE(MatchRegexAtHead("\\.+a", "abc"));
823 EXPECT_FALSE(MatchRegexAtHead("\\s?b", " b"));
824
825 EXPECT_TRUE(MatchRegexAtHead("\\(*a", "((((ab"));
826 EXPECT_TRUE(MatchRegexAtHead("\\^?b", "^b"));
827 EXPECT_TRUE(MatchRegexAtHead("\\\\?b", "b"));
828 EXPECT_TRUE(MatchRegexAtHead("\\\\?b", "\\b"));
829 }
830
TEST(MatchRegexAtHeadTest,MatchesSequentially)831 TEST(MatchRegexAtHeadTest, MatchesSequentially) {
832 EXPECT_FALSE(MatchRegexAtHead("ab.*c", "acabc"));
833
834 EXPECT_TRUE(MatchRegexAtHead("ab.*c", "ab-fsc"));
835 }
836
TEST(MatchRegexAnywhereTest,ReturnsFalseWhenStringIsNull)837 TEST(MatchRegexAnywhereTest, ReturnsFalseWhenStringIsNull) {
838 EXPECT_FALSE(MatchRegexAnywhere("", NULL));
839 }
840
TEST(MatchRegexAnywhereTest,WorksWhenRegexStartsWithCaret)841 TEST(MatchRegexAnywhereTest, WorksWhenRegexStartsWithCaret) {
842 EXPECT_FALSE(MatchRegexAnywhere("^a", "ba"));
843 EXPECT_FALSE(MatchRegexAnywhere("^$", "a"));
844
845 EXPECT_TRUE(MatchRegexAnywhere("^a", "ab"));
846 EXPECT_TRUE(MatchRegexAnywhere("^", "ab"));
847 EXPECT_TRUE(MatchRegexAnywhere("^$", ""));
848 }
849
TEST(MatchRegexAnywhereTest,ReturnsFalseWhenNoMatch)850 TEST(MatchRegexAnywhereTest, ReturnsFalseWhenNoMatch) {
851 EXPECT_FALSE(MatchRegexAnywhere("a", "bcde123"));
852 EXPECT_FALSE(MatchRegexAnywhere("a.+a", "--aa88888888"));
853 }
854
TEST(MatchRegexAnywhereTest,ReturnsTrueWhenMatchingPrefix)855 TEST(MatchRegexAnywhereTest, ReturnsTrueWhenMatchingPrefix) {
856 EXPECT_TRUE(MatchRegexAnywhere("\\w+", "ab1_ - 5"));
857 EXPECT_TRUE(MatchRegexAnywhere(".*=", "="));
858 EXPECT_TRUE(MatchRegexAnywhere("x.*ab?.*bc", "xaaabc"));
859 }
860
TEST(MatchRegexAnywhereTest,ReturnsTrueWhenMatchingNonPrefix)861 TEST(MatchRegexAnywhereTest, ReturnsTrueWhenMatchingNonPrefix) {
862 EXPECT_TRUE(MatchRegexAnywhere("\\w+", "$$$ ab1_ - 5"));
863 EXPECT_TRUE(MatchRegexAnywhere("\\.+=", "= ...="));
864 }
865
866 // Tests RE's implicit constructors.
TEST(RETest,ImplicitConstructorWorks)867 TEST(RETest, ImplicitConstructorWorks) {
868 const RE empty("");
869 EXPECT_STREQ("", empty.pattern());
870
871 const RE simple("hello");
872 EXPECT_STREQ("hello", simple.pattern());
873 }
874
875 // Tests that RE's constructors reject invalid regular expressions.
TEST(RETest,RejectsInvalidRegex)876 TEST(RETest, RejectsInvalidRegex) {
877 EXPECT_NONFATAL_FAILURE({ const RE normal(NULL); },
878 "NULL is not a valid simple regular expression");
879
880 EXPECT_NONFATAL_FAILURE({ const RE normal(".*(\\w+"); },
881 "'(' is unsupported");
882
883 EXPECT_NONFATAL_FAILURE({ 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() == nullptr);
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, nullptr);
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 {
1028 Mutex m;
1029 { MutexLock lock(&m); }
1030 m.AssertHeld();
1031 },
1032 "thread .*hold");
1033 }
1034
TEST(MutexTest,AssertHeldShouldNotAssertWhenLocked)1035 TEST(MutexTest, AssertHeldShouldNotAssertWhenLocked) {
1036 Mutex m;
1037 MutexLock lock(&m);
1038 m.AssertHeld();
1039 }
1040
1041 class AtomicCounterWithMutex {
1042 public:
AtomicCounterWithMutex(Mutex * mutex)1043 explicit AtomicCounterWithMutex(Mutex* mutex)
1044 : value_(0), mutex_(mutex), random_(42) {}
1045
Increment()1046 void Increment() {
1047 MutexLock lock(mutex_);
1048 int temp = value_;
1049 {
1050 // We need to put up a memory barrier to prevent reads and writes to
1051 // value_ rearranged with the call to sleep_for when observed
1052 // from other threads.
1053 #if GTEST_HAS_PTHREAD
1054 // On POSIX, locking a mutex puts up a memory barrier. We cannot use
1055 // Mutex and MutexLock here or rely on their memory barrier
1056 // functionality as we are testing them here.
1057 pthread_mutex_t memory_barrier_mutex;
1058 GTEST_CHECK_POSIX_SUCCESS_(
1059 pthread_mutex_init(&memory_barrier_mutex, nullptr));
1060 GTEST_CHECK_POSIX_SUCCESS_(pthread_mutex_lock(&memory_barrier_mutex));
1061
1062 std::this_thread::sleep_for(
1063 std::chrono::milliseconds(random_.Generate(30)));
1064
1065 GTEST_CHECK_POSIX_SUCCESS_(pthread_mutex_unlock(&memory_barrier_mutex));
1066 GTEST_CHECK_POSIX_SUCCESS_(pthread_mutex_destroy(&memory_barrier_mutex));
1067 #elif GTEST_OS_WINDOWS
1068 // On Windows, performing an interlocked access puts up a memory barrier.
1069 volatile LONG dummy = 0;
1070 ::InterlockedIncrement(&dummy);
1071 std::this_thread::sleep_for(
1072 std::chrono::milliseconds(random_.Generate(30)));
1073 ::InterlockedIncrement(&dummy);
1074 #else
1075 #error "Memory barrier not implemented on this platform."
1076 #endif // GTEST_HAS_PTHREAD
1077 }
1078 value_ = temp + 1;
1079 }
value() const1080 int value() const { return value_; }
1081
1082 private:
1083 volatile int value_;
1084 Mutex* const mutex_; // Protects value_.
1085 Random random_;
1086 };
1087
CountingThreadFunc(pair<AtomicCounterWithMutex *,int> param)1088 void CountingThreadFunc(pair<AtomicCounterWithMutex*, int> param) {
1089 for (int i = 0; i < param.second; ++i) param.first->Increment();
1090 }
1091
1092 // Tests that the mutex only lets one thread at a time to lock it.
TEST(MutexTest,OnlyOneThreadCanLockAtATime)1093 TEST(MutexTest, OnlyOneThreadCanLockAtATime) {
1094 Mutex mutex;
1095 AtomicCounterWithMutex locked_counter(&mutex);
1096
1097 typedef ThreadWithParam<pair<AtomicCounterWithMutex*, int> > ThreadType;
1098 const int kCycleCount = 20;
1099 const int kThreadCount = 7;
1100 std::unique_ptr<ThreadType> counting_threads[kThreadCount];
1101 Notification threads_can_start;
1102 // Creates and runs kThreadCount threads that increment locked_counter
1103 // kCycleCount times each.
1104 for (int i = 0; i < kThreadCount; ++i) {
1105 counting_threads[i].reset(new ThreadType(
1106 &CountingThreadFunc, make_pair(&locked_counter, kCycleCount),
1107 &threads_can_start));
1108 }
1109 threads_can_start.Notify();
1110 for (int i = 0; i < kThreadCount; ++i) 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, nullptr);
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 DestructorCall(const DestructorCall&) = delete;
1187 DestructorCall& operator=(const DestructorCall&) = delete;
1188 };
1189
1190 std::vector<DestructorCall*>* const DestructorCall::list_ =
1191 new std::vector<DestructorCall*>;
1192
1193 // DestructorTracker keeps track of whether its instances have been
1194 // destroyed.
1195 class DestructorTracker {
1196 public:
DestructorTracker()1197 DestructorTracker() : index_(GetNewIndex()) {}
DestructorTracker(const DestructorTracker &)1198 DestructorTracker(const DestructorTracker& /* rhs */)
1199 : index_(GetNewIndex()) {}
~DestructorTracker()1200 ~DestructorTracker() {
1201 // We never access DestructorCall::List() concurrently, so we don't need
1202 // to protect this access with a mutex.
1203 DestructorCall::List()[index_]->ReportDestroyed();
1204 }
1205
1206 private:
GetNewIndex()1207 static size_t GetNewIndex() {
1208 DestructorCall::List().push_back(new DestructorCall);
1209 return DestructorCall::List().size() - 1;
1210 }
1211 const size_t index_;
1212 };
1213
1214 typedef ThreadLocal<DestructorTracker>* ThreadParam;
1215
CallThreadLocalGet(ThreadParam thread_local_param)1216 void CallThreadLocalGet(ThreadParam thread_local_param) {
1217 thread_local_param->get();
1218 }
1219
1220 // Tests that when a ThreadLocal object dies in a thread, it destroys
1221 // the managed object for that thread.
TEST(ThreadLocalTest,DestroysManagedObjectForOwnThreadWhenDying)1222 TEST(ThreadLocalTest, DestroysManagedObjectForOwnThreadWhenDying) {
1223 DestructorCall::ResetList();
1224
1225 {
1226 ThreadLocal<DestructorTracker> thread_local_tracker;
1227 ASSERT_EQ(0U, DestructorCall::List().size());
1228
1229 // This creates another DestructorTracker object for the main thread.
1230 thread_local_tracker.get();
1231 ASSERT_EQ(1U, DestructorCall::List().size());
1232 ASSERT_FALSE(DestructorCall::List()[0]->CheckDestroyed());
1233 }
1234
1235 // Now thread_local_tracker has died.
1236 ASSERT_EQ(1U, DestructorCall::List().size());
1237 EXPECT_TRUE(DestructorCall::List()[0]->CheckDestroyed());
1238
1239 DestructorCall::ResetList();
1240 }
1241
1242 // Tests that when a thread exits, the thread-local object for that
1243 // thread is destroyed.
TEST(ThreadLocalTest,DestroysManagedObjectAtThreadExit)1244 TEST(ThreadLocalTest, DestroysManagedObjectAtThreadExit) {
1245 DestructorCall::ResetList();
1246
1247 {
1248 ThreadLocal<DestructorTracker> thread_local_tracker;
1249 ASSERT_EQ(0U, DestructorCall::List().size());
1250
1251 // This creates another DestructorTracker object in the new thread.
1252 ThreadWithParam<ThreadParam> thread(&CallThreadLocalGet,
1253 &thread_local_tracker, nullptr);
1254 thread.Join();
1255
1256 // The thread has exited, and we should have a DestroyedTracker
1257 // instance created for it. But it may not have been destroyed yet.
1258 ASSERT_EQ(1U, DestructorCall::List().size());
1259 }
1260
1261 // The thread has exited and thread_local_tracker has died.
1262 ASSERT_EQ(1U, DestructorCall::List().size());
1263 EXPECT_TRUE(DestructorCall::List()[0]->CheckDestroyed());
1264
1265 DestructorCall::ResetList();
1266 }
1267
TEST(ThreadLocalTest,ThreadLocalMutationsAffectOnlyCurrentThread)1268 TEST(ThreadLocalTest, ThreadLocalMutationsAffectOnlyCurrentThread) {
1269 ThreadLocal<std::string> thread_local_string;
1270 thread_local_string.set("Foo");
1271 EXPECT_STREQ("Foo", thread_local_string.get().c_str());
1272
1273 std::string result;
1274 RunFromThread(&RetrieveThreadLocalValue,
1275 make_pair(&thread_local_string, &result));
1276 EXPECT_TRUE(result.empty());
1277 }
1278
1279 #endif // GTEST_IS_THREADSAFE
1280
1281 #if GTEST_OS_WINDOWS
TEST(WindowsTypesTest,HANDLEIsVoidStar)1282 TEST(WindowsTypesTest, HANDLEIsVoidStar) {
1283 StaticAssertTypeEq<HANDLE, void*>();
1284 }
1285
1286 #if GTEST_OS_WINDOWS_MINGW && !defined(__MINGW64_VERSION_MAJOR)
TEST(WindowsTypesTest,_CRITICAL_SECTIONIs_CRITICAL_SECTION)1287 TEST(WindowsTypesTest, _CRITICAL_SECTIONIs_CRITICAL_SECTION) {
1288 StaticAssertTypeEq<CRITICAL_SECTION, _CRITICAL_SECTION>();
1289 }
1290 #else
TEST(WindowsTypesTest,CRITICAL_SECTIONIs_RTL_CRITICAL_SECTION)1291 TEST(WindowsTypesTest, CRITICAL_SECTIONIs_RTL_CRITICAL_SECTION) {
1292 StaticAssertTypeEq<CRITICAL_SECTION, _RTL_CRITICAL_SECTION>();
1293 }
1294 #endif
1295
1296 #endif // GTEST_OS_WINDOWS
1297
1298 } // namespace internal
1299 } // namespace testing
1300