cMHN 1.2
C++ library for learning MHNs with pRC
Loading...
Searching...
No Matches
googletest-port-test.cc
Go to the documentation of this file.
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
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"
50
51using std::make_pair;
52using std::pair;
53
54namespace testing {
55namespace internal {
56
57TEST(IsXDigitTest, WorksForNarrowAscii) {
64
68}
69
70TEST(IsXDigitTest, ReturnsFalseForNarrowNonAscii) {
71 EXPECT_FALSE(IsXDigit(static_cast<char>('\x80')));
72 EXPECT_FALSE(IsXDigit(static_cast<char>('0' | '\x80')));
73}
74
75TEST(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
86}
87
88TEST(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
94class Base {
95 public:
96 Base() : member_(0) {}
97 explicit Base(int n) : member_(n) {}
98 Base(const Base&) = default;
99 Base& operator=(const Base&) = default;
100 virtual ~Base() = default;
101 int member() { return member_; }
102
103 private:
104 int member_;
105};
106
107class Derived : public Base {
108 public:
109 explicit Derived(int n) : Base(n) {}
110};
111
112TEST(ImplicitCastTest, ConvertsPointers) {
113 Derived derived(0);
115}
116
117TEST(ImplicitCastTest, CanUseInheritance) {
118 Derived derived(1);
119 Base base = ::testing::internal::ImplicitCast_<Base>(derived);
120 EXPECT_EQ(derived.member(), base.member());
121}
122
123class Castable {
124 public:
125 explicit Castable(bool* converted) : converted_(converted) {}
126 operator Base() {
127 *converted_ = true;
128 return Base();
129 }
130
131 private:
132 bool* converted_;
133};
134
135TEST(ImplicitCastTest, CanUseNonConstCastOperator) {
136 bool converted = false;
137 Castable castable(&converted);
138 Base base = ::testing::internal::ImplicitCast_<Base>(castable);
139 EXPECT_TRUE(converted);
140}
141
143 public:
144 explicit ConstCastable(bool* converted) : converted_(converted) {}
145 operator Base() const {
146 *converted_ = true;
147 return Base();
148 }
149
150 private:
151 bool* converted_;
152};
153
154TEST(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
162 public:
163 ConstAndNonConstCastable(bool* converted, bool* const_converted)
164 : converted_(converted), const_converted_(const_converted) {}
165 operator Base() {
166 *converted_ = true;
167 return Base();
168 }
169 operator Base() const {
170 *const_converted_ = true;
171 return Base();
172 }
173
174 private:
175 bool* converted_;
176 bool* const_converted_;
177};
178
179TEST(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
195class To {
196 public:
197 To(bool* converted) { *converted = true; } // NOLINT
198};
199
200TEST(ImplicitCastTest, CanUseImplicitConstructor) {
201 bool converted = false;
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
214TEST(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
233TEST(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.
247TEST(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
252TEST(FormatFileLocationTest, FormatsUnknownFile) {
253 EXPECT_PRED_FORMAT2(IsSubstring, "unknown file",
254 FormatFileLocation(nullptr, 42));
255 EXPECT_PRED_FORMAT2(IsSubstring, "42", FormatFileLocation(nullptr, 42));
256}
257
258TEST(FormatFileLocationTest, FormatsUknownLine) {
259 EXPECT_EQ("foo.cc:", FormatFileLocation("foo.cc", -1));
260}
261
262TEST(FormatFileLocationTest, FormatsUknownFileAndLine) {
263 EXPECT_EQ("unknown file:", FormatFileLocation(nullptr, -1));
264}
265
266// Verifies behavior of FormatCompilerIndependentFileLocation.
267TEST(FormatCompilerIndependentFileLocationTest, FormatsFileLocation) {
268 EXPECT_EQ("foo.cc:42", FormatCompilerIndependentFileLocation("foo.cc", 42));
269}
270
271TEST(FormatCompilerIndependentFileLocationTest, FormatsUknownFile) {
272 EXPECT_EQ("unknown file:42",
274}
275
276TEST(FormatCompilerIndependentFileLocationTest, FormatsUknownLine) {
277 EXPECT_EQ("foo.cc", FormatCompilerIndependentFileLocation("foo.cc", -1));
278}
279
280TEST(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)
289void* ThreadFunc(void* data) {
290 internal::Mutex* mutex = static_cast<internal::Mutex*>(data);
291 mutex->Lock();
292 mutex->Unlock();
293 return nullptr;
294}
295
296TEST(GetThreadCountTest, ReturnsCorrectValue) {
297 size_t starting_count;
298 size_t thread_count_after_create;
299 size_t thread_count_after_join;
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
321 thread_count_after_create = GetThreadCount();
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
354TEST(GetThreadCountTest, ReturnsZeroWhenUnableToCountThreads) {
356}
357#endif // GTEST_OS_LINUX || GTEST_OS_MAC || GTEST_OS_QNX || GTEST_OS_FUCHSIA
358
359TEST(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
377TEST(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.
392TEST(RegexEngineSelectionTest, SelectsCorrectRegexEngine) {
393#ifdef GTEST_HAS_ABSL
394 EXPECT_TRUE(GTEST_USES_RE2);
395#elif GTEST_HAS_POSIX_RE
397#else
398 EXPECT_TRUE(GTEST_USES_SIMPLE_RE);
399#endif
400}
401
402#ifdef GTEST_USES_POSIX_RE
403
404template <typename Str>
405class RETest : public ::testing::Test {};
406
407// Defines StringTypes as the list of all string types that class RE
408// supports.
410
411TYPED_TEST_SUITE(RETest, StringTypes);
412
413// Tests RE's implicit constructors.
414TYPED_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.
426TYPED_TEST(RETest, RejectsInvalidRegex) {
428 { const RE invalid(TypeParam("?")); },
429 "\"?\" is not a valid POSIX Extended regular expression.");
430}
431
432// Tests RE::FullMatch().
433TYPED_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().
446TYPED_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
461TEST(IsInSetTest, NulCharIsNotInAnySet) {
462 EXPECT_FALSE(IsInSet('\0', ""));
463 EXPECT_FALSE(IsInSet('\0', "\0"));
464 EXPECT_FALSE(IsInSet('\0', "a"));
465}
466
467TEST(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
475TEST(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
484TEST(IsAsciiDigitTest, IsTrueForDigit) {
485 EXPECT_TRUE(IsAsciiDigit('0'));
486 EXPECT_TRUE(IsAsciiDigit('1'));
487 EXPECT_TRUE(IsAsciiDigit('5'));
488 EXPECT_TRUE(IsAsciiDigit('9'));
489}
490
491TEST(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
499TEST(IsAsciiPunctTest, IsTrueForPunct) {
500 for (const char* p = "^-!\"#$%&'()*+,./:;<=>?@[\\]_`{|}~"; *p; p++) {
501 EXPECT_PRED1(IsAsciiPunct, *p);
502 }
503}
504
505TEST(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
513TEST(IsRepeatTest, IsTrueForRepeatChar) {
514 EXPECT_TRUE(IsRepeat('?'));
515 EXPECT_TRUE(IsRepeat('*'));
516 EXPECT_TRUE(IsRepeat('+'));
517}
518
519TEST(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
527TEST(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
536TEST(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
544TEST(IsAsciiWordCharTest, IsTrueForLetter) {
545 EXPECT_TRUE(IsAsciiWordChar('a'));
546 EXPECT_TRUE(IsAsciiWordChar('b'));
547 EXPECT_TRUE(IsAsciiWordChar('A'));
548 EXPECT_TRUE(IsAsciiWordChar('Z'));
549}
550
551TEST(IsAsciiWordCharTest, IsTrueForDigit) {
552 EXPECT_TRUE(IsAsciiWordChar('0'));
553 EXPECT_TRUE(IsAsciiWordChar('1'));
554 EXPECT_TRUE(IsAsciiWordChar('7'));
555 EXPECT_TRUE(IsAsciiWordChar('9'));
556}
557
558TEST(IsAsciiWordCharTest, IsTrueForUnderscore) {
559 EXPECT_TRUE(IsAsciiWordChar('_'));
560}
561
562TEST(IsValidEscapeTest, IsFalseForNonPrintable) {
563 EXPECT_FALSE(IsValidEscape('\0'));
564 EXPECT_FALSE(IsValidEscape('\007'));
565}
566
567TEST(IsValidEscapeTest, IsFalseForDigit) {
568 EXPECT_FALSE(IsValidEscape('0'));
569 EXPECT_FALSE(IsValidEscape('9'));
570}
571
572TEST(IsValidEscapeTest, IsFalseForWhiteSpace) {
573 EXPECT_FALSE(IsValidEscape(' '));
574 EXPECT_FALSE(IsValidEscape('\n'));
575}
576
577TEST(IsValidEscapeTest, IsFalseForSomeLetter) {
578 EXPECT_FALSE(IsValidEscape('a'));
579 EXPECT_FALSE(IsValidEscape('Z'));
580}
581
582TEST(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
593TEST(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
602TEST(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
614TEST(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
623TEST(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
632TEST(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
643TEST(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
652TEST(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
664TEST(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
675TEST(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
694TEST(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
703TEST(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
713TEST(ValidateRegexTest, GeneratesFailureAndReturnsFalseForInvalid) {
714 EXPECT_NONFATAL_FAILURE(ASSERT_FALSE(ValidateRegex(NULL)),
715 "NULL is not a valid simple regular expression");
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
749TEST(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
760TEST(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
772TEST(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
783TEST(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
794TEST(MatchRegexAtHeadTest, ReturnsTrueForEmptyRegex) {
795 EXPECT_TRUE(MatchRegexAtHead("", ""));
796 EXPECT_TRUE(MatchRegexAtHead("", "ab"));
797}
798
799TEST(MatchRegexAtHeadTest, WorksWhenDollarIsInRegex) {
800 EXPECT_FALSE(MatchRegexAtHead("$", "a"));
801
802 EXPECT_TRUE(MatchRegexAtHead("$", ""));
803 EXPECT_TRUE(MatchRegexAtHead("a$", "a"));
804}
805
806TEST(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
814TEST(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
823TEST(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
833TEST(MatchRegexAtHeadTest, MatchesSequentially) {
834 EXPECT_FALSE(MatchRegexAtHead("ab.*c", "acabc"));
835
836 EXPECT_TRUE(MatchRegexAtHead("ab.*c", "ab-fsc"));
837}
838
839TEST(MatchRegexAnywhereTest, ReturnsFalseWhenStringIsNull) {
840 EXPECT_FALSE(MatchRegexAnywhere("", NULL));
841}
842
843TEST(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
852TEST(MatchRegexAnywhereTest, ReturnsFalseWhenNoMatch) {
853 EXPECT_FALSE(MatchRegexAnywhere("a", "bcde123"));
854 EXPECT_FALSE(MatchRegexAnywhere("a.+a", "--aa88888888"));
855}
856
857TEST(MatchRegexAnywhereTest, ReturnsTrueWhenMatchingPrefix) {
858 EXPECT_TRUE(MatchRegexAnywhere("\\w+", "ab1_ - 5"));
859 EXPECT_TRUE(MatchRegexAnywhere(".*=", "="));
860 EXPECT_TRUE(MatchRegexAnywhere("x.*ab?.*bc", "xaaabc"));
861}
862
863TEST(MatchRegexAnywhereTest, ReturnsTrueWhenMatchingNonPrefix) {
864 EXPECT_TRUE(MatchRegexAnywhere("\\w+", "$$$ ab1_ - 5"));
865 EXPECT_TRUE(MatchRegexAnywhere("\\.+=", "= ...="));
866}
867
868// Tests RE's implicit constructors.
869TEST(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.
878TEST(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().
890TEST(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().
906TEST(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
923TEST(CaptureTest, CapturesStdout) {
925 fprintf(stdout, "abc");
926 EXPECT_STREQ("abc", GetCapturedStdout().c_str());
927
929 fprintf(stdout, "def%cghi", '\0');
930 EXPECT_EQ(::std::string("def\0ghi", 7), ::std::string(GetCapturedStdout()));
931}
932
933TEST(CaptureTest, CapturesStderr) {
935 fprintf(stderr, "jkl");
936 EXPECT_STREQ("jkl", GetCapturedStderr().c_str());
937
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.
944TEST(CaptureTest, CapturesStdoutAndStderr) {
947 fprintf(stdout, "pqr");
948 fprintf(stderr, "stu");
949 EXPECT_STREQ("pqr", GetCapturedStdout().c_str());
950 EXPECT_STREQ("stu", GetCapturedStderr().c_str());
951}
952
953TEST(CaptureDeathTest, CannotReenterStdoutCapture) {
956 "Only one stdout capturer can exist at a time");
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
965TEST(ThreadLocalTest, DefaultConstructorInitializesToDefaultValues) {
967 EXPECT_EQ(0, t1.get());
968
970 EXPECT_TRUE(t2.get() == nullptr);
971}
972
973TEST(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
983 public:
984 explicit NoDefaultConstructor(const char*) {}
986};
987
988TEST(ThreadLocalTest, ValueDefaultContructorIsNotRequiredForParamVersion) {
990 bar.pointer();
991}
992
993TEST(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
1003TEST(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
1016void AddTwo(int* param) { *param += 2; }
1017
1018TEST(ThreadWithParamTest, ConstructorExecutesThreadFunc) {
1019 int i = 40;
1020 ThreadWithParam<int*> thread(&AddTwo, &i, nullptr);
1021 thread.Join();
1022 EXPECT_EQ(42, i);
1023}
1024
1025TEST(MutexDeathTest, AssertHeldShouldAssertWhenNotLocked) {
1026 // AssertHeld() is flaky only in the presence of multiple threads accessing
1027 // the lock. In this case, the test is robust.
1029 {
1030 Mutex m;
1031 { MutexLock lock(&m); }
1032 m.AssertHeld();
1033 },
1034 "thread .*hold");
1035}
1036
1037TEST(MutexTest, AssertHeldShouldNotAssertWhenLocked) {
1038 Mutex m;
1039 MutexLock lock(&m);
1040 m.AssertHeld();
1041}
1042
1043class AtomicCounterWithMutex {
1044 public:
1045 explicit AtomicCounterWithMutex(Mutex* mutex)
1046 : value_(0), mutex_(mutex), random_(42) {}
1047
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;
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 }
1082 int value() const { return value_; }
1083
1084 private:
1085 volatile int value_;
1086 Mutex* const mutex_; // Protects value_.
1087 Random random_;
1088};
1089
1090void 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.
1095TEST(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
1121template <typename T>
1122void RunFromThread(void(func)(T), T param) {
1123 ThreadWithParam<T> thread(func, param, nullptr);
1124 thread.Join();
1125}
1126
1127void RetrieveThreadLocalValue(
1128 pair<ThreadLocal<std::string>*, std::string*> param) {
1129 *param.second = param.first->get();
1130}
1131
1132TEST(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.
1147class DestructorCall {
1148 public:
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
1157 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
1165 void ReportDestroyed() {
1166 invoked_ = true;
1167#ifdef GTEST_OS_WINDOWS
1168 ::SetEvent(wait_event_.Get());
1169#endif
1170 }
1171
1172 static std::vector<DestructorCall*>& List() { return *list_; }
1173
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
1192std::vector<DestructorCall*>* const DestructorCall::list_ =
1193 new std::vector<DestructorCall*>;
1194
1195// DestructorTracker keeps track of whether its instances have been
1196// destroyed.
1197class DestructorTracker {
1198 public:
1199 DestructorTracker() : index_(GetNewIndex()) {}
1200 DestructorTracker(const DestructorTracker& /* rhs */)
1201 : index_(GetNewIndex()) {}
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:
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
1216typedef ThreadLocal<DestructorTracker>* ThreadParam;
1217
1218void 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.
1224TEST(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.
1246TEST(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
1270TEST(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
1284TEST(WindowsTypesTest, HANDLEIsVoidStar) {
1286}
1287
1288#if defined(GTEST_OS_WINDOWS_MINGW) && !defined(__MINGW64_VERSION_MAJOR)
1289TEST(WindowsTypesTest, _CRITICAL_SECTIONIs_CRITICAL_SECTION) {
1291}
1292#else
1293TEST(WindowsTypesTest, CRITICAL_SECTIONIs_RTL_CRITICAL_SECTION) {
1295}
1296#endif
1297
1298#endif // GTEST_OS_WINDOWS
1299
1300} // namespace internal
1301} // namespace testing
Definition value.hpp:12
Definition gtest.h:243
virtual ~Base()=default
Base(int n)
Definition googletest-port-test.cc:97
Base()
Definition googletest-port-test.cc:96
Base(const Base &)=default
int member()
Definition googletest-port-test.cc:101
Base & operator=(const Base &)=default
Definition googletest-port-test.cc:123
Castable(bool *converted)
Definition googletest-port-test.cc:125
Definition googletest-port-test.cc:161
ConstAndNonConstCastable(bool *converted, bool *const_converted)
Definition googletest-port-test.cc:163
Definition googletest-port-test.cc:142
ConstCastable(bool *converted)
Definition googletest-port-test.cc:144
Derived(int n)
Definition googletest-port-test.cc:109
Definition gtest-port.h:1869
void Unlock()
Definition gtest-port.h:1873
void Lock()
Definition gtest-port.h:1872
Definition googletest-port-test.cc:982
NoDefaultConstructor(const char *)
Definition googletest-port-test.cc:984
NoDefaultConstructor(const NoDefaultConstructor &)=default
Definition gtest-port.h:1895
T * pointer()
Definition gtest-port.h:1899
void set(const T &value)
Definition gtest-port.h:1902
const T & get() const
Definition gtest-port.h:1901
Definition googletest-port-test.cc:195
To(bool *converted)
Definition googletest-port-test.cc:197
int value
Definition gmock-actions_test.cc:1714
int i
Definition gmock-matchers-comparisons_test.cc:603
const char * p
Definition gmock-matchers-containers_test.cc:379
#define EXPECT_DEATH_IF_SUPPORTED(statement, regex)
Definition gtest-death-test.h:337
#define GTEST_CHECK_POSIX_SUCCESS_(posix_call)
Definition gtest-port.h:1091
#define GTEST_CHECK_(condition)
Definition gtest-port.h:1078
#define GTEST_USES_POSIX_RE
Definition gtest-port.h:438
#define EXPECT_NONFATAL_FAILURE(statement, substr)
Definition gtest-spi.h:217
#define TYPED_TEST(CaseName, TestName)
Definition gtest-typed-test.h:197
#define TYPED_TEST_SUITE(CaseName, Types,...)
Definition gtest-typed-test.h:191
#define ASSERT_EQ(val1, val2)
Definition gtest.h:1898
#define EXPECT_EQ(val1, val2)
Definition gtest.h:1868
#define ASSERT_FALSE(condition)
Definition gtest.h:1819
#define TEST(test_suite_name, test_name)
Definition gtest.h:2176
#define EXPECT_TRUE(condition)
Definition gtest.h:1807
#define EXPECT_STREQ(s1, s2)
Definition gtest.h:1937
#define EXPECT_FALSE(condition)
Definition gtest.h:1811
#define EXPECT_PRED1(pred, v1)
Definition gtest_pred_impl.h:110
#define EXPECT_PRED_FORMAT2(pred_format, v1, v2)
Definition gtest_pred_impl.h:143
Definition googletest-output-test_.cc:485
std::mutex Mutex
Definition lock.hpp:10
GTestMutexLock MutexLock
Definition gtest-port.h:1892
GTEST_API_::std::string FormatCompilerIndependentFileLocation(const char *file, int line)
Definition gtest-port.cc:995
GTEST_API_::std::string FormatFileLocation(const char *file, int line)
Definition gtest-port.cc:977
GTEST_API_ std::string GetCapturedStderr()
GTEST_API_ size_t GetThreadCount()
Definition gtest-port.cc:265
bool AlwaysFalse()
Definition gtest-internal.h:829
GTEST_API_ void CaptureStderr()
GTEST_API_ bool AlwaysTrue()
Definition gtest.cc:6312
To ImplicitCast_(To x)
Definition gtest-port.h:1140
bool IsXDigit(char ch)
Definition gtest-port.h:1947
GTEST_API_ void CaptureStdout()
GTEST_API_ std::string GetCapturedStdout()
Definition gmock-actions.h:151
constexpr bool StaticAssertTypeEq() noexcept
Definition gtest.h:2139
Definition gtest-type-util.h:190