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