Lab_1 0.1.1
Matrix Library
Loading...
Searching...
No Matches
googletest-port-test.cc
1// Copyright 2008, Google Inc.
2// All rights reserved.
3//
4// Redistribution and use in source and binary forms, with or without
5// modification, are permitted provided that the following conditions are
6// met:
7//
8// * Redistributions of source code must retain the above copyright
9// notice, this list of conditions and the following disclaimer.
10// * Redistributions in binary form must reproduce the above
11// copyright notice, this list of conditions and the following disclaimer
12// in the documentation and/or other materials provided with the
13// distribution.
14// * Neither the name of Google Inc. nor the names of its
15// contributors may be used to endorse or promote products derived from
16// this software without specific prior written permission.
17//
18// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
19// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
20// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
21// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
22// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
23// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
24// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
25// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
26// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
27// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
28// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
29//
30// This file tests the internal cross-platform support utilities.
31#include <stdio.h>
32
33#include "gtest/internal/gtest-port.h"
34
35#if GTEST_OS_MAC
36#include <time.h>
37#endif // GTEST_OS_MAC
38
39#include <chrono> // NOLINT
40#include <list>
41#include <memory>
42#include <thread> // NOLINT
43#include <utility> // For std::pair and std::make_pair.
44#include <vector>
45
46#include "gtest/gtest-spi.h"
47#include "gtest/gtest.h"
48#include "src/gtest-internal-inl.h"
49
50using std::make_pair;
51using std::pair;
52
53namespace testing {
54namespace internal {
55
56TEST(IsXDigitTest, WorksForNarrowAscii) {
57 EXPECT_TRUE(IsXDigit('0'));
58 EXPECT_TRUE(IsXDigit('9'));
59 EXPECT_TRUE(IsXDigit('A'));
60 EXPECT_TRUE(IsXDigit('F'));
61 EXPECT_TRUE(IsXDigit('a'));
62 EXPECT_TRUE(IsXDigit('f'));
63
64 EXPECT_FALSE(IsXDigit('-'));
65 EXPECT_FALSE(IsXDigit('g'));
66 EXPECT_FALSE(IsXDigit('G'));
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
82 EXPECT_FALSE(IsXDigit(L'-'));
83 EXPECT_FALSE(IsXDigit(L'g'));
84 EXPECT_FALSE(IsXDigit(L'G'));
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 Base() : member_(0) {}
96 explicit Base(int n) : member_(n) {}
97 Base(const Base&) = default;
98 Base& operator=(const Base&) = default;
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);
113 EXPECT_TRUE(&derived == ::testing::internal::ImplicitCast_<Base*>(&derived));
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;
201 To to = ::testing::internal::ImplicitCast_<To>(&converted);
202 (void)to;
203 EXPECT_TRUE(converted);
204}
205
206// The following code intentionally tests a suboptimal syntax.
207#ifdef __GNUC__
208#pragma GCC diagnostic push
209#pragma GCC diagnostic ignored "-Wdangling-else"
210#pragma GCC diagnostic ignored "-Wempty-body"
211#pragma GCC diagnostic ignored "-Wpragmas"
212#endif
213TEST(GtestCheckSyntaxTest, BehavesLikeASingleStatement) {
214 if (AlwaysFalse())
215 GTEST_CHECK_(false) << "This should never be executed; "
216 "It's a compilation test only.";
217
218 if (AlwaysTrue())
219 GTEST_CHECK_(true);
220 else
221 ; // NOLINT
222
223 if (AlwaysFalse())
224 ; // NOLINT
225 else
226 GTEST_CHECK_(true) << "";
227}
228#ifdef __GNUC__
229#pragma GCC diagnostic pop
230#endif
231
232TEST(GtestCheckSyntaxTest, WorksWithSwitch) {
233 switch (0) {
234 case 1:
235 break;
236 default:
237 GTEST_CHECK_(true);
238 }
239
240 switch (0)
241 case 0:
242 GTEST_CHECK_(true) << "Check failed in switch case";
243}
244
245// Verifies behavior of FormatFileLocation.
246TEST(FormatFileLocationTest, FormatsFileLocation) {
247 EXPECT_PRED_FORMAT2(IsSubstring, "foo.cc", FormatFileLocation("foo.cc", 42));
248 EXPECT_PRED_FORMAT2(IsSubstring, "42", FormatFileLocation("foo.cc", 42));
249}
250
251TEST(FormatFileLocationTest, FormatsUnknownFile) {
252 EXPECT_PRED_FORMAT2(IsSubstring, "unknown file",
253 FormatFileLocation(nullptr, 42));
254 EXPECT_PRED_FORMAT2(IsSubstring, "42", FormatFileLocation(nullptr, 42));
255}
256
257TEST(FormatFileLocationTest, FormatsUknownLine) {
258 EXPECT_EQ("foo.cc:", FormatFileLocation("foo.cc", -1));
259}
260
261TEST(FormatFileLocationTest, FormatsUknownFileAndLine) {
262 EXPECT_EQ("unknown file:", FormatFileLocation(nullptr, -1));
263}
264
265// Verifies behavior of FormatCompilerIndependentFileLocation.
266TEST(FormatCompilerIndependentFileLocationTest, FormatsFileLocation) {
267 EXPECT_EQ("foo.cc:42", FormatCompilerIndependentFileLocation("foo.cc", 42));
268}
269
270TEST(FormatCompilerIndependentFileLocationTest, FormatsUknownFile) {
271 EXPECT_EQ("unknown file:42",
272 FormatCompilerIndependentFileLocation(nullptr, 42));
273}
274
275TEST(FormatCompilerIndependentFileLocationTest, FormatsUknownLine) {
276 EXPECT_EQ("foo.cc", FormatCompilerIndependentFileLocation("foo.cc", -1));
277}
278
279TEST(FormatCompilerIndependentFileLocationTest, FormatsUknownFileAndLine) {
280 EXPECT_EQ("unknown file", FormatCompilerIndependentFileLocation(nullptr, -1));
281}
282
283#if GTEST_OS_LINUX || GTEST_OS_MAC || GTEST_OS_QNX || GTEST_OS_FUCHSIA || \
284 GTEST_OS_DRAGONFLY || GTEST_OS_FREEBSD || GTEST_OS_GNU_KFREEBSD || \
285 GTEST_OS_NETBSD || GTEST_OS_OPENBSD || GTEST_OS_GNU_HURD
286void* ThreadFunc(void* data) {
287 internal::Mutex* mutex = static_cast<internal::Mutex*>(data);
288 mutex->Lock();
289 mutex->Unlock();
290 return nullptr;
291}
292
293TEST(GetThreadCountTest, ReturnsCorrectValue) {
294 size_t starting_count;
295 size_t thread_count_after_create;
296 size_t thread_count_after_join;
297
298 // We can't guarantee that no other thread was created or destroyed between
299 // any two calls to GetThreadCount(). We make multiple attempts, hoping that
300 // background noise is not constant and we would see the "right" values at
301 // some point.
302 for (int attempt = 0; attempt < 20; ++attempt) {
303 starting_count = GetThreadCount();
304 pthread_t thread_id;
305
306 internal::Mutex mutex;
307 {
308 internal::MutexLock lock(&mutex);
309 pthread_attr_t attr;
310 ASSERT_EQ(0, pthread_attr_init(&attr));
311 ASSERT_EQ(0, pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_JOINABLE));
312
313 const int status = pthread_create(&thread_id, &attr, &ThreadFunc, &mutex);
314 ASSERT_EQ(0, pthread_attr_destroy(&attr));
315 ASSERT_EQ(0, status);
316 }
317
318 thread_count_after_create = GetThreadCount();
319
320 void* dummy;
321 ASSERT_EQ(0, pthread_join(thread_id, &dummy));
322
323 // Join before we decide whether we need to retry the test. Retry if an
324 // arbitrary other thread was created or destroyed in the meantime.
325 if (thread_count_after_create != starting_count + 1) continue;
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 bool thread_count_matches = false;
331 for (int i = 0; i < 5; ++i) {
332 thread_count_after_join = GetThreadCount();
333 if (thread_count_after_join == starting_count) {
334 thread_count_matches = true;
335 break;
336 }
337
338 std::this_thread::sleep_for(std::chrono::milliseconds(100));
339 }
340
341 // Retry if an arbitrary other thread was created or destroyed.
342 if (!thread_count_matches) continue;
343
344 break;
345 }
346
347 EXPECT_EQ(thread_count_after_create, starting_count + 1);
348 EXPECT_EQ(thread_count_after_join, starting_count);
349}
350#else
351TEST(GetThreadCountTest, ReturnsZeroWhenUnableToCountThreads) {
352 EXPECT_EQ(0U, GetThreadCount());
353}
354#endif // GTEST_OS_LINUX || GTEST_OS_MAC || GTEST_OS_QNX || GTEST_OS_FUCHSIA
355
356TEST(GtestCheckDeathTest, DiesWithCorrectOutputOnFailure) {
357 const bool a_false_condition = false;
358 const char regex[] =
359#ifdef _MSC_VER
360 "googletest-port-test\\.cc\\(\\d+\\):"
361#elif GTEST_USES_POSIX_RE
362 "googletest-port-test\\.cc:[0-9]+"
363#else
364 "googletest-port-test\\.cc:\\d+"
365#endif // _MSC_VER
366 ".*a_false_condition.*Extra info.*";
367
368 EXPECT_DEATH_IF_SUPPORTED(GTEST_CHECK_(a_false_condition) << "Extra info",
369 regex);
370}
371
372#if GTEST_HAS_DEATH_TEST
373
374TEST(GtestCheckDeathTest, LivesSilentlyOnSuccess) {
375 EXPECT_EXIT(
376 {
377 GTEST_CHECK_(true) << "Extra info";
378 ::std::cerr << "Success\n";
379 exit(0);
380 },
381 ::testing::ExitedWithCode(0), "Success");
382}
383
384#endif // GTEST_HAS_DEATH_TEST
385
386// Verifies that Google Test choose regular expression engine appropriate to
387// the platform. The test will produce compiler errors in case of failure.
388// For simplicity, we only cover the most important platforms here.
389TEST(RegexEngineSelectionTest, SelectsCorrectRegexEngine) {
390#if GTEST_HAS_ABSL
391 EXPECT_TRUE(GTEST_USES_RE2);
392#elif GTEST_HAS_POSIX_RE
393 EXPECT_TRUE(GTEST_USES_POSIX_RE);
394#else
395 EXPECT_TRUE(GTEST_USES_SIMPLE_RE);
396#endif
397}
398
399#if GTEST_USES_POSIX_RE
400
401template <typename Str>
402class RETest : public ::testing::Test {};
403
404// Defines StringTypes as the list of all string types that class RE
405// supports.
407
408TYPED_TEST_SUITE(RETest, StringTypes);
409
410// Tests RE's implicit constructors.
411TYPED_TEST(RETest, ImplicitConstructorWorks) {
412 const RE empty(TypeParam(""));
413 EXPECT_STREQ("", empty.pattern());
414
415 const RE simple(TypeParam("hello"));
416 EXPECT_STREQ("hello", simple.pattern());
417
418 const RE normal(TypeParam(".*(\\w+)"));
419 EXPECT_STREQ(".*(\\w+)", normal.pattern());
420}
421
422// Tests that RE's constructors reject invalid regular expressions.
423TYPED_TEST(RETest, RejectsInvalidRegex) {
424 EXPECT_NONFATAL_FAILURE(
425 { const RE invalid(TypeParam("?")); },
426 "\"?\" is not a valid POSIX Extended regular expression.");
427}
428
429// Tests RE::FullMatch().
430TYPED_TEST(RETest, FullMatchWorks) {
431 const RE empty(TypeParam(""));
432 EXPECT_TRUE(RE::FullMatch(TypeParam(""), empty));
433 EXPECT_FALSE(RE::FullMatch(TypeParam("a"), empty));
434
435 const RE re(TypeParam("a.*z"));
436 EXPECT_TRUE(RE::FullMatch(TypeParam("az"), re));
437 EXPECT_TRUE(RE::FullMatch(TypeParam("axyz"), re));
438 EXPECT_FALSE(RE::FullMatch(TypeParam("baz"), re));
439 EXPECT_FALSE(RE::FullMatch(TypeParam("azy"), re));
440}
441
442// Tests RE::PartialMatch().
443TYPED_TEST(RETest, PartialMatchWorks) {
444 const RE empty(TypeParam(""));
445 EXPECT_TRUE(RE::PartialMatch(TypeParam(""), empty));
446 EXPECT_TRUE(RE::PartialMatch(TypeParam("a"), empty));
447
448 const RE re(TypeParam("a.*z"));
449 EXPECT_TRUE(RE::PartialMatch(TypeParam("az"), re));
450 EXPECT_TRUE(RE::PartialMatch(TypeParam("axyz"), re));
451 EXPECT_TRUE(RE::PartialMatch(TypeParam("baz"), re));
452 EXPECT_TRUE(RE::PartialMatch(TypeParam("azy"), re));
453 EXPECT_FALSE(RE::PartialMatch(TypeParam("zza"), re));
454}
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");
713 EXPECT_NONFATAL_FAILURE(
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, WorksWhenRegexStartsWithRepetionOfEscapeSequence) {
821 EXPECT_FALSE(MatchRegexAtHead("\\.+a", "abc"));
822 EXPECT_FALSE(MatchRegexAtHead("\\s?b", " b"));
823
824 EXPECT_TRUE(MatchRegexAtHead("\\(*a", "((((ab"));
825 EXPECT_TRUE(MatchRegexAtHead("\\^?b", "^b"));
826 EXPECT_TRUE(MatchRegexAtHead("\\\\?b", "b"));
827 EXPECT_TRUE(MatchRegexAtHead("\\\\?b", "\\b"));
828}
829
830TEST(MatchRegexAtHeadTest, MatchesSequentially) {
831 EXPECT_FALSE(MatchRegexAtHead("ab.*c", "acabc"));
832
833 EXPECT_TRUE(MatchRegexAtHead("ab.*c", "ab-fsc"));
834}
835
836TEST(MatchRegexAnywhereTest, ReturnsFalseWhenStringIsNull) {
837 EXPECT_FALSE(MatchRegexAnywhere("", NULL));
838}
839
840TEST(MatchRegexAnywhereTest, WorksWhenRegexStartsWithCaret) {
841 EXPECT_FALSE(MatchRegexAnywhere("^a", "ba"));
842 EXPECT_FALSE(MatchRegexAnywhere("^$", "a"));
843
844 EXPECT_TRUE(MatchRegexAnywhere("^a", "ab"));
845 EXPECT_TRUE(MatchRegexAnywhere("^", "ab"));
846 EXPECT_TRUE(MatchRegexAnywhere("^$", ""));
847}
848
849TEST(MatchRegexAnywhereTest, ReturnsFalseWhenNoMatch) {
850 EXPECT_FALSE(MatchRegexAnywhere("a", "bcde123"));
851 EXPECT_FALSE(MatchRegexAnywhere("a.+a", "--aa88888888"));
852}
853
854TEST(MatchRegexAnywhereTest, ReturnsTrueWhenMatchingPrefix) {
855 EXPECT_TRUE(MatchRegexAnywhere("\\w+", "ab1_ - 5"));
856 EXPECT_TRUE(MatchRegexAnywhere(".*=", "="));
857 EXPECT_TRUE(MatchRegexAnywhere("x.*ab?.*bc", "xaaabc"));
858}
859
860TEST(MatchRegexAnywhereTest, ReturnsTrueWhenMatchingNonPrefix) {
861 EXPECT_TRUE(MatchRegexAnywhere("\\w+", "$$$ ab1_ - 5"));
862 EXPECT_TRUE(MatchRegexAnywhere("\\.+=", "= ...="));
863}
864
865// Tests RE's implicit constructors.
866TEST(RETest, ImplicitConstructorWorks) {
867 const RE empty("");
868 EXPECT_STREQ("", empty.pattern());
869
870 const RE simple("hello");
871 EXPECT_STREQ("hello", simple.pattern());
872}
873
874// Tests that RE's constructors reject invalid regular expressions.
875TEST(RETest, RejectsInvalidRegex) {
876 EXPECT_NONFATAL_FAILURE({ const RE normal(NULL); },
877 "NULL is not a valid simple regular expression");
878
879 EXPECT_NONFATAL_FAILURE({ const RE normal(".*(\\w+"); },
880 "'(' is unsupported");
881
882 EXPECT_NONFATAL_FAILURE({ const RE invalid("^?"); },
883 "'?' can only follow a repeatable token");
884}
885
886// Tests RE::FullMatch().
887TEST(RETest, FullMatchWorks) {
888 const RE empty("");
889 EXPECT_TRUE(RE::FullMatch("", empty));
890 EXPECT_FALSE(RE::FullMatch("a", empty));
891
892 const RE re1("a");
893 EXPECT_TRUE(RE::FullMatch("a", re1));
894
895 const RE re("a.*z");
896 EXPECT_TRUE(RE::FullMatch("az", re));
897 EXPECT_TRUE(RE::FullMatch("axyz", re));
898 EXPECT_FALSE(RE::FullMatch("baz", re));
899 EXPECT_FALSE(RE::FullMatch("azy", re));
900}
901
902// Tests RE::PartialMatch().
903TEST(RETest, PartialMatchWorks) {
904 const RE empty("");
905 EXPECT_TRUE(RE::PartialMatch("", empty));
906 EXPECT_TRUE(RE::PartialMatch("a", empty));
907
908 const RE re("a.*z");
909 EXPECT_TRUE(RE::PartialMatch("az", re));
910 EXPECT_TRUE(RE::PartialMatch("axyz", re));
911 EXPECT_TRUE(RE::PartialMatch("baz", re));
912 EXPECT_TRUE(RE::PartialMatch("azy", re));
913 EXPECT_FALSE(RE::PartialMatch("zza", re));
914}
915
916#endif // GTEST_USES_POSIX_RE
917
918#if !GTEST_OS_WINDOWS_MOBILE
919
920TEST(CaptureTest, CapturesStdout) {
921 CaptureStdout();
922 fprintf(stdout, "abc");
923 EXPECT_STREQ("abc", GetCapturedStdout().c_str());
924
925 CaptureStdout();
926 fprintf(stdout, "def%cghi", '\0');
927 EXPECT_EQ(::std::string("def\0ghi", 7), ::std::string(GetCapturedStdout()));
928}
929
930TEST(CaptureTest, CapturesStderr) {
931 CaptureStderr();
932 fprintf(stderr, "jkl");
933 EXPECT_STREQ("jkl", GetCapturedStderr().c_str());
934
935 CaptureStderr();
936 fprintf(stderr, "jkl%cmno", '\0');
937 EXPECT_EQ(::std::string("jkl\0mno", 7), ::std::string(GetCapturedStderr()));
938}
939
940// Tests that stdout and stderr capture don't interfere with each other.
941TEST(CaptureTest, CapturesStdoutAndStderr) {
942 CaptureStdout();
943 CaptureStderr();
944 fprintf(stdout, "pqr");
945 fprintf(stderr, "stu");
946 EXPECT_STREQ("pqr", GetCapturedStdout().c_str());
947 EXPECT_STREQ("stu", GetCapturedStderr().c_str());
948}
949
950TEST(CaptureDeathTest, CannotReenterStdoutCapture) {
951 CaptureStdout();
952 EXPECT_DEATH_IF_SUPPORTED(CaptureStdout(),
953 "Only one stdout capturer can exist at a time");
954 GetCapturedStdout();
955
956 // We cannot test stderr capturing using death tests as they use it
957 // themselves.
958}
959
960#endif // !GTEST_OS_WINDOWS_MOBILE
961
962TEST(ThreadLocalTest, DefaultConstructorInitializesToDefaultValues) {
963 ThreadLocal<int> t1;
964 EXPECT_EQ(0, t1.get());
965
966 ThreadLocal<void*> t2;
967 EXPECT_TRUE(t2.get() == nullptr);
968}
969
970TEST(ThreadLocalTest, SingleParamConstructorInitializesToParam) {
971 ThreadLocal<int> t1(123);
972 EXPECT_EQ(123, t1.get());
973
974 int i = 0;
975 ThreadLocal<int*> t2(&i);
976 EXPECT_EQ(&i, t2.get());
977}
978
980 public:
981 explicit NoDefaultContructor(const char*) {}
983};
984
985TEST(ThreadLocalTest, ValueDefaultContructorIsNotRequiredForParamVersion) {
987 bar.pointer();
988}
989
990TEST(ThreadLocalTest, GetAndPointerReturnSameValue) {
991 ThreadLocal<std::string> thread_local_string;
992
993 EXPECT_EQ(thread_local_string.pointer(), &(thread_local_string.get()));
994
995 // Verifies the condition still holds after calling set.
996 thread_local_string.set("foo");
997 EXPECT_EQ(thread_local_string.pointer(), &(thread_local_string.get()));
998}
999
1000TEST(ThreadLocalTest, PointerAndConstPointerReturnSameValue) {
1001 ThreadLocal<std::string> thread_local_string;
1002 const ThreadLocal<std::string>& const_thread_local_string =
1003 thread_local_string;
1004
1005 EXPECT_EQ(thread_local_string.pointer(), const_thread_local_string.pointer());
1006
1007 thread_local_string.set("foo");
1008 EXPECT_EQ(thread_local_string.pointer(), const_thread_local_string.pointer());
1009}
1010
1011#if GTEST_IS_THREADSAFE
1012
1013void AddTwo(int* param) { *param += 2; }
1014
1015TEST(ThreadWithParamTest, ConstructorExecutesThreadFunc) {
1016 int i = 40;
1017 ThreadWithParam<int*> thread(&AddTwo, &i, nullptr);
1018 thread.Join();
1019 EXPECT_EQ(42, i);
1020}
1021
1022TEST(MutexDeathTest, AssertHeldShouldAssertWhenNotLocked) {
1023 // AssertHeld() is flaky only in the presence of multiple threads accessing
1024 // the lock. In this case, the test is robust.
1025 EXPECT_DEATH_IF_SUPPORTED(
1026 {
1027 Mutex m;
1028 { MutexLock lock(&m); }
1029 m.AssertHeld();
1030 },
1031 "thread .*hold");
1032}
1033
1034TEST(MutexTest, AssertHeldShouldNotAssertWhenLocked) {
1035 Mutex m;
1036 MutexLock lock(&m);
1037 m.AssertHeld();
1038}
1039
1040class AtomicCounterWithMutex {
1041 public:
1042 explicit AtomicCounterWithMutex(Mutex* mutex)
1043 : value_(0), mutex_(mutex), random_(42) {}
1044
1045 void Increment() {
1046 MutexLock lock(mutex_);
1047 int temp = value_;
1048 {
1049 // We need to put up a memory barrier to prevent reads and writes to
1050 // value_ rearranged with the call to sleep_for when observed
1051 // from other threads.
1052#if GTEST_HAS_PTHREAD
1053 // On POSIX, locking a mutex puts up a memory barrier. We cannot use
1054 // Mutex and MutexLock here or rely on their memory barrier
1055 // functionality as we are testing them here.
1056 pthread_mutex_t memory_barrier_mutex;
1057 GTEST_CHECK_POSIX_SUCCESS_(
1058 pthread_mutex_init(&memory_barrier_mutex, nullptr));
1059 GTEST_CHECK_POSIX_SUCCESS_(pthread_mutex_lock(&memory_barrier_mutex));
1060
1061 std::this_thread::sleep_for(
1062 std::chrono::milliseconds(random_.Generate(30)));
1063
1064 GTEST_CHECK_POSIX_SUCCESS_(pthread_mutex_unlock(&memory_barrier_mutex));
1065 GTEST_CHECK_POSIX_SUCCESS_(pthread_mutex_destroy(&memory_barrier_mutex));
1066#elif GTEST_OS_WINDOWS
1067 // On Windows, performing an interlocked access puts up a memory barrier.
1068 volatile LONG dummy = 0;
1069 ::InterlockedIncrement(&dummy);
1070 std::this_thread::sleep_for(
1071 std::chrono::milliseconds(random_.Generate(30)));
1072 ::InterlockedIncrement(&dummy);
1073#else
1074#error "Memory barrier not implemented on this platform."
1075#endif // GTEST_HAS_PTHREAD
1076 }
1077 value_ = temp + 1;
1078 }
1079 int value() const { return value_; }
1080
1081 private:
1082 volatile int value_;
1083 Mutex* const mutex_; // Protects value_.
1084 Random random_;
1085};
1086
1087void CountingThreadFunc(pair<AtomicCounterWithMutex*, int> param) {
1088 for (int i = 0; i < param.second; ++i) param.first->Increment();
1089}
1090
1091// Tests that the mutex only lets one thread at a time to lock it.
1092TEST(MutexTest, OnlyOneThreadCanLockAtATime) {
1093 Mutex mutex;
1094 AtomicCounterWithMutex locked_counter(&mutex);
1095
1096 typedef ThreadWithParam<pair<AtomicCounterWithMutex*, int> > ThreadType;
1097 const int kCycleCount = 20;
1098 const int kThreadCount = 7;
1099 std::unique_ptr<ThreadType> counting_threads[kThreadCount];
1100 Notification threads_can_start;
1101 // Creates and runs kThreadCount threads that increment locked_counter
1102 // kCycleCount times each.
1103 for (int i = 0; i < kThreadCount; ++i) {
1104 counting_threads[i].reset(new ThreadType(
1105 &CountingThreadFunc, make_pair(&locked_counter, kCycleCount),
1106 &threads_can_start));
1107 }
1108 threads_can_start.Notify();
1109 for (int i = 0; i < kThreadCount; ++i) counting_threads[i]->Join();
1110
1111 // If the mutex lets more than one thread to increment the counter at a
1112 // time, they are likely to encounter a race condition and have some
1113 // increments overwritten, resulting in the lower then expected counter
1114 // value.
1115 EXPECT_EQ(kCycleCount * kThreadCount, locked_counter.value());
1116}
1117
1118template <typename T>
1119void RunFromThread(void(func)(T), T param) {
1120 ThreadWithParam<T> thread(func, param, nullptr);
1121 thread.Join();
1122}
1123
1124void RetrieveThreadLocalValue(
1125 pair<ThreadLocal<std::string>*, std::string*> param) {
1126 *param.second = param.first->get();
1127}
1128
1129TEST(ThreadLocalTest, ParameterizedConstructorSetsDefault) {
1130 ThreadLocal<std::string> thread_local_string("foo");
1131 EXPECT_STREQ("foo", thread_local_string.get().c_str());
1132
1133 thread_local_string.set("bar");
1134 EXPECT_STREQ("bar", thread_local_string.get().c_str());
1135
1136 std::string result;
1137 RunFromThread(&RetrieveThreadLocalValue,
1138 make_pair(&thread_local_string, &result));
1139 EXPECT_STREQ("foo", result.c_str());
1140}
1141
1142// Keeps track of whether of destructors being called on instances of
1143// DestructorTracker. On Windows, waits for the destructor call reports.
1144class DestructorCall {
1145 public:
1146 DestructorCall() {
1147 invoked_ = false;
1148#if GTEST_OS_WINDOWS
1149 wait_event_.Reset(::CreateEvent(NULL, TRUE, FALSE, NULL));
1150 GTEST_CHECK_(wait_event_.Get() != NULL);
1151#endif
1152 }
1153
1154 bool CheckDestroyed() const {
1155#if GTEST_OS_WINDOWS
1156 if (::WaitForSingleObject(wait_event_.Get(), 1000) != WAIT_OBJECT_0)
1157 return false;
1158#endif
1159 return invoked_;
1160 }
1161
1162 void ReportDestroyed() {
1163 invoked_ = true;
1164#if GTEST_OS_WINDOWS
1165 ::SetEvent(wait_event_.Get());
1166#endif
1167 }
1168
1169 static std::vector<DestructorCall*>& List() { return *list_; }
1170
1171 static void ResetList() {
1172 for (size_t i = 0; i < list_->size(); ++i) {
1173 delete list_->at(i);
1174 }
1175 list_->clear();
1176 }
1177
1178 private:
1179 bool invoked_;
1180#if GTEST_OS_WINDOWS
1181 AutoHandle wait_event_;
1182#endif
1183 static std::vector<DestructorCall*>* const list_;
1184
1185 DestructorCall(const DestructorCall&) = delete;
1186 DestructorCall& operator=(const DestructorCall&) = delete;
1187};
1188
1189std::vector<DestructorCall*>* const DestructorCall::list_ =
1190 new std::vector<DestructorCall*>;
1191
1192// DestructorTracker keeps track of whether its instances have been
1193// destroyed.
1194class DestructorTracker {
1195 public:
1196 DestructorTracker() : index_(GetNewIndex()) {}
1197 DestructorTracker(const DestructorTracker& /* rhs */)
1198 : index_(GetNewIndex()) {}
1199 ~DestructorTracker() {
1200 // We never access DestructorCall::List() concurrently, so we don't need
1201 // to protect this access with a mutex.
1202 DestructorCall::List()[index_]->ReportDestroyed();
1203 }
1204
1205 private:
1206 static size_t GetNewIndex() {
1207 DestructorCall::List().push_back(new DestructorCall);
1208 return DestructorCall::List().size() - 1;
1209 }
1210 const size_t index_;
1211};
1212
1213typedef ThreadLocal<DestructorTracker>* ThreadParam;
1214
1215void CallThreadLocalGet(ThreadParam thread_local_param) {
1216 thread_local_param->get();
1217}
1218
1219// Tests that when a ThreadLocal object dies in a thread, it destroys
1220// the managed object for that thread.
1221TEST(ThreadLocalTest, DestroysManagedObjectForOwnThreadWhenDying) {
1222 DestructorCall::ResetList();
1223
1224 {
1225 ThreadLocal<DestructorTracker> thread_local_tracker;
1226 ASSERT_EQ(0U, DestructorCall::List().size());
1227
1228 // This creates another DestructorTracker object for the main thread.
1229 thread_local_tracker.get();
1230 ASSERT_EQ(1U, DestructorCall::List().size());
1231 ASSERT_FALSE(DestructorCall::List()[0]->CheckDestroyed());
1232 }
1233
1234 // Now thread_local_tracker has died.
1235 ASSERT_EQ(1U, DestructorCall::List().size());
1236 EXPECT_TRUE(DestructorCall::List()[0]->CheckDestroyed());
1237
1238 DestructorCall::ResetList();
1239}
1240
1241// Tests that when a thread exits, the thread-local object for that
1242// thread is destroyed.
1243TEST(ThreadLocalTest, DestroysManagedObjectAtThreadExit) {
1244 DestructorCall::ResetList();
1245
1246 {
1247 ThreadLocal<DestructorTracker> thread_local_tracker;
1248 ASSERT_EQ(0U, DestructorCall::List().size());
1249
1250 // This creates another DestructorTracker object in the new thread.
1251 ThreadWithParam<ThreadParam> thread(&CallThreadLocalGet,
1252 &thread_local_tracker, nullptr);
1253 thread.Join();
1254
1255 // The thread has exited, and we should have a DestroyedTracker
1256 // instance created for it. But it may not have been destroyed yet.
1257 ASSERT_EQ(1U, DestructorCall::List().size());
1258 }
1259
1260 // The thread has exited and thread_local_tracker has died.
1261 ASSERT_EQ(1U, DestructorCall::List().size());
1262 EXPECT_TRUE(DestructorCall::List()[0]->CheckDestroyed());
1263
1264 DestructorCall::ResetList();
1265}
1266
1267TEST(ThreadLocalTest, ThreadLocalMutationsAffectOnlyCurrentThread) {
1268 ThreadLocal<std::string> thread_local_string;
1269 thread_local_string.set("Foo");
1270 EXPECT_STREQ("Foo", thread_local_string.get().c_str());
1271
1272 std::string result;
1273 RunFromThread(&RetrieveThreadLocalValue,
1274 make_pair(&thread_local_string, &result));
1275 EXPECT_TRUE(result.empty());
1276}
1277
1278#endif // GTEST_IS_THREADSAFE
1279
1280#if GTEST_OS_WINDOWS
1281TEST(WindowsTypesTest, HANDLEIsVoidStar) {
1282 StaticAssertTypeEq<HANDLE, void*>();
1283}
1284
1285#if GTEST_OS_WINDOWS_MINGW && !defined(__MINGW64_VERSION_MAJOR)
1286TEST(WindowsTypesTest, _CRITICAL_SECTIONIs_CRITICAL_SECTION) {
1287 StaticAssertTypeEq<CRITICAL_SECTION, _CRITICAL_SECTION>();
1288}
1289#else
1290TEST(WindowsTypesTest, CRITICAL_SECTIONIs_RTL_CRITICAL_SECTION) {
1291 StaticAssertTypeEq<CRITICAL_SECTION, _RTL_CRITICAL_SECTION>();
1292}
1293#endif
1294
1295#endif // GTEST_OS_WINDOWS
1296
1297} // namespace internal
1298} // namespace testing
Definition gtest.h:242
Definition googletest-port-test.cc:122
Definition googletest-port-test.cc:160
Definition googletest-port-test.cc:141
Definition googletest-port-test.cc:979
Definition gtest-port.h:1868
Definition googletest-port-test.cc:194
Definition gtest-type-util.h:156