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