Update bundled GoogleTest to current HEAD
[alexxy/gromacs.git] / src / external / googletest / googletest / test / 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 <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"
46 #include "src/gtest-internal-inl.h"
47
48 using std::make_pair;
49 using std::pair;
50
51 namespace testing {
52 namespace internal {
53
54 TEST(IsXDigitTest, WorksForNarrowAscii) {
55   EXPECT_TRUE(IsXDigit('0'));
56   EXPECT_TRUE(IsXDigit('9'));
57   EXPECT_TRUE(IsXDigit('A'));
58   EXPECT_TRUE(IsXDigit('F'));
59   EXPECT_TRUE(IsXDigit('a'));
60   EXPECT_TRUE(IsXDigit('f'));
61
62   EXPECT_FALSE(IsXDigit('-'));
63   EXPECT_FALSE(IsXDigit('g'));
64   EXPECT_FALSE(IsXDigit('G'));
65 }
66
67 TEST(IsXDigitTest, ReturnsFalseForNarrowNonAscii) {
68   EXPECT_FALSE(IsXDigit(static_cast<char>('\x80')));
69   EXPECT_FALSE(IsXDigit(static_cast<char>('0' | '\x80')));
70 }
71
72 TEST(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
80   EXPECT_FALSE(IsXDigit(L'-'));
81   EXPECT_FALSE(IsXDigit(L'g'));
82   EXPECT_FALSE(IsXDigit(L'G'));
83 }
84
85 TEST(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
91 class 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:
101   int member_;
102 };
103
104 class Derived : public Base {
105  public:
106   explicit Derived(int n) : Base(n) {}
107 };
108
109 TEST(ImplicitCastTest, ConvertsPointers) {
110   Derived derived(0);
111   EXPECT_TRUE(&derived == ::testing::internal::ImplicitCast_<Base*>(&derived));
112 }
113
114 TEST(ImplicitCastTest, CanUseInheritance) {
115   Derived derived(1);
116   Base base = ::testing::internal::ImplicitCast_<Base>(derived);
117   EXPECT_EQ(derived.member(), base.member());
118 }
119
120 class Castable {
121  public:
122   explicit Castable(bool* converted) : converted_(converted) {}
123   operator Base() {
124     *converted_ = true;
125     return Base();
126   }
127
128  private:
129   bool* converted_;
130 };
131
132 TEST(ImplicitCastTest, CanUseNonConstCastOperator) {
133   bool converted = false;
134   Castable castable(&converted);
135   Base base = ::testing::internal::ImplicitCast_<Base>(castable);
136   EXPECT_TRUE(converted);
137 }
138
139 class ConstCastable {
140  public:
141   explicit ConstCastable(bool* converted) : converted_(converted) {}
142   operator Base() const {
143     *converted_ = true;
144     return Base();
145   }
146
147  private:
148   bool* converted_;
149 };
150
151 TEST(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
158 class ConstAndNonConstCastable {
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:
172   bool* converted_;
173   bool* const_converted_;
174 };
175
176 TEST(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
192 class To {
193  public:
194   To(bool* converted) { *converted = true; }  // NOLINT
195 };
196
197 TEST(ImplicitCastTest, CanUseImplicitConstructor) {
198   bool converted = false;
199   To to = ::testing::internal::ImplicitCast_<To>(&converted);
200   (void)to;
201   EXPECT_TRUE(converted);
202 }
203
204 // The following code intentionally tests a suboptimal syntax.
205 #ifdef __GNUC__
206 #pragma GCC diagnostic push
207 #pragma GCC diagnostic ignored "-Wdangling-else"
208 #pragma GCC diagnostic ignored "-Wempty-body"
209 #pragma GCC diagnostic ignored "-Wpragmas"
210 #endif
211 TEST(GtestCheckSyntaxTest, BehavesLikeASingleStatement) {
212   if (AlwaysFalse())
213     GTEST_CHECK_(false) << "This should never be executed; "
214                            "It's a compilation test only.";
215
216   if (AlwaysTrue())
217     GTEST_CHECK_(true);
218   else
219     ;  // NOLINT
220
221   if (AlwaysFalse())
222     ;  // NOLINT
223   else
224     GTEST_CHECK_(true) << "";
225 }
226 #ifdef __GNUC__
227 #pragma GCC diagnostic pop
228 #endif
229
230 TEST(GtestCheckSyntaxTest, WorksWithSwitch) {
231   switch (0) {
232     case 1:
233       break;
234     default:
235       GTEST_CHECK_(true);
236   }
237
238   switch (0)
239     case 0:
240       GTEST_CHECK_(true) << "Check failed in switch case";
241 }
242
243 // Verifies behavior of FormatFileLocation.
244 TEST(FormatFileLocationTest, FormatsFileLocation) {
245   EXPECT_PRED_FORMAT2(IsSubstring, "foo.cc", FormatFileLocation("foo.cc", 42));
246   EXPECT_PRED_FORMAT2(IsSubstring, "42", FormatFileLocation("foo.cc", 42));
247 }
248
249 TEST(FormatFileLocationTest, FormatsUnknownFile) {
250   EXPECT_PRED_FORMAT2(IsSubstring, "unknown file",
251                       FormatFileLocation(nullptr, 42));
252   EXPECT_PRED_FORMAT2(IsSubstring, "42", FormatFileLocation(nullptr, 42));
253 }
254
255 TEST(FormatFileLocationTest, FormatsUknownLine) {
256   EXPECT_EQ("foo.cc:", FormatFileLocation("foo.cc", -1));
257 }
258
259 TEST(FormatFileLocationTest, FormatsUknownFileAndLine) {
260   EXPECT_EQ("unknown file:", FormatFileLocation(nullptr, -1));
261 }
262
263 // Verifies behavior of FormatCompilerIndependentFileLocation.
264 TEST(FormatCompilerIndependentFileLocationTest, FormatsFileLocation) {
265   EXPECT_EQ("foo.cc:42", FormatCompilerIndependentFileLocation("foo.cc", 42));
266 }
267
268 TEST(FormatCompilerIndependentFileLocationTest, FormatsUknownFile) {
269   EXPECT_EQ("unknown file:42",
270             FormatCompilerIndependentFileLocation(nullptr, 42));
271 }
272
273 TEST(FormatCompilerIndependentFileLocationTest, FormatsUknownLine) {
274   EXPECT_EQ("foo.cc", FormatCompilerIndependentFileLocation("foo.cc", -1));
275 }
276
277 TEST(FormatCompilerIndependentFileLocationTest, FormatsUknownFileAndLine) {
278   EXPECT_EQ("unknown file", FormatCompilerIndependentFileLocation(nullptr, -1));
279 }
280
281 #if GTEST_OS_LINUX || GTEST_OS_MAC || GTEST_OS_QNX || GTEST_OS_FUCHSIA || \
282     GTEST_OS_DRAGONFLY || GTEST_OS_FREEBSD || GTEST_OS_GNU_KFREEBSD || \
283     GTEST_OS_NETBSD || GTEST_OS_OPENBSD || GTEST_OS_GNU_HURD
284 void* ThreadFunc(void* data) {
285   internal::Mutex* mutex = static_cast<internal::Mutex*>(data);
286   mutex->Lock();
287   mutex->Unlock();
288   return nullptr;
289 }
290
291 TEST(GetThreadCountTest, ReturnsCorrectValue) {
292   size_t starting_count;
293   size_t thread_count_after_create;
294   size_t thread_count_after_join;
295
296   // We can't guarantee that no other thread was created or destroyed between
297   // any two calls to GetThreadCount(). We make multiple attempts, hoping that
298   // background noise is not constant and we would see the "right" values at
299   // some point.
300   for (int attempt = 0; attempt < 20; ++attempt) {
301     starting_count = GetThreadCount();
302     pthread_t thread_id;
303
304     internal::Mutex mutex;
305     {
306       internal::MutexLock lock(&mutex);
307       pthread_attr_t attr;
308       ASSERT_EQ(0, pthread_attr_init(&attr));
309       ASSERT_EQ(0, pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_JOINABLE));
310
311       const int status = pthread_create(&thread_id, &attr, &ThreadFunc, &mutex);
312       ASSERT_EQ(0, pthread_attr_destroy(&attr));
313       ASSERT_EQ(0, status);
314     }
315
316     thread_count_after_create = GetThreadCount();
317
318     void* dummy;
319     ASSERT_EQ(0, pthread_join(thread_id, &dummy));
320
321     // Join before we decide whether we need to retry the test. Retry if an
322     // arbitrary other thread was created or destroyed in the meantime.
323     if (thread_count_after_create != starting_count + 1) continue;
324
325     // The OS may not immediately report the updated thread count after
326     // joining a thread, causing flakiness in this test. To counter that, we
327     // wait for up to .5 seconds for the OS to report the correct value.
328     bool thread_count_matches = false;
329     for (int i = 0; i < 5; ++i) {
330       thread_count_after_join = GetThreadCount();
331       if (thread_count_after_join == starting_count) {
332         thread_count_matches = true;
333         break;
334       }
335
336       SleepMilliseconds(100);
337     }
338
339     // Retry if an arbitrary other thread was created or destroyed.
340     if (!thread_count_matches) continue;
341
342     break;
343   }
344
345   EXPECT_EQ(thread_count_after_create, starting_count + 1);
346   EXPECT_EQ(thread_count_after_join, starting_count);
347 }
348 #else
349 TEST(GetThreadCountTest, ReturnsZeroWhenUnableToCountThreads) {
350   EXPECT_EQ(0U, GetThreadCount());
351 }
352 #endif  // GTEST_OS_LINUX || GTEST_OS_MAC || GTEST_OS_QNX || GTEST_OS_FUCHSIA
353
354 TEST(GtestCheckDeathTest, DiesWithCorrectOutputOnFailure) {
355   const bool a_false_condition = false;
356   const char regex[] =
357 #ifdef _MSC_VER
358      "googletest-port-test\\.cc\\(\\d+\\):"
359 #elif GTEST_USES_POSIX_RE
360      "googletest-port-test\\.cc:[0-9]+"
361 #else
362      "googletest-port-test\\.cc:\\d+"
363 #endif  // _MSC_VER
364      ".*a_false_condition.*Extra info.*";
365
366   EXPECT_DEATH_IF_SUPPORTED(GTEST_CHECK_(a_false_condition) << "Extra info",
367                             regex);
368 }
369
370 #if GTEST_HAS_DEATH_TEST
371
372 TEST(GtestCheckDeathTest, LivesSilentlyOnSuccess) {
373   EXPECT_EXIT({
374       GTEST_CHECK_(true) << "Extra info";
375       ::std::cerr << "Success\n";
376       exit(0); },
377       ::testing::ExitedWithCode(0), "Success");
378 }
379
380 #endif  // GTEST_HAS_DEATH_TEST
381
382 // Verifies that Google Test choose regular expression engine appropriate to
383 // the platform. The test will produce compiler errors in case of failure.
384 // For simplicity, we only cover the most important platforms here.
385 TEST(RegexEngineSelectionTest, SelectsCorrectRegexEngine) {
386 #if !GTEST_USES_PCRE
387 # if GTEST_HAS_POSIX_RE
388
389   EXPECT_TRUE(GTEST_USES_POSIX_RE);
390
391 # else
392
393   EXPECT_TRUE(GTEST_USES_SIMPLE_RE);
394
395 # endif
396 #endif  // !GTEST_USES_PCRE
397 }
398
399 #if GTEST_USES_POSIX_RE
400
401 template <typename Str>
402 class RETest : public ::testing::Test {};
403
404 // Defines StringTypes as the list of all string types that class RE
405 // supports.
406 typedef testing::Types< ::std::string, const char*> StringTypes;
407
408 TYPED_TEST_SUITE(RETest, StringTypes);
409
410 // Tests RE's implicit constructors.
411 TYPED_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.
423 TYPED_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().
430 TYPED_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().
443 TYPED_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
458 TEST(IsInSetTest, NulCharIsNotInAnySet) {
459   EXPECT_FALSE(IsInSet('\0', ""));
460   EXPECT_FALSE(IsInSet('\0', "\0"));
461   EXPECT_FALSE(IsInSet('\0', "a"));
462 }
463
464 TEST(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
472 TEST(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
481 TEST(IsAsciiDigitTest, IsTrueForDigit) {
482   EXPECT_TRUE(IsAsciiDigit('0'));
483   EXPECT_TRUE(IsAsciiDigit('1'));
484   EXPECT_TRUE(IsAsciiDigit('5'));
485   EXPECT_TRUE(IsAsciiDigit('9'));
486 }
487
488 TEST(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
496 TEST(IsAsciiPunctTest, IsTrueForPunct) {
497   for (const char* p = "^-!\"#$%&'()*+,./:;<=>?@[\\]_`{|}~"; *p; p++) {
498     EXPECT_PRED1(IsAsciiPunct, *p);
499   }
500 }
501
502 TEST(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
510 TEST(IsRepeatTest, IsTrueForRepeatChar) {
511   EXPECT_TRUE(IsRepeat('?'));
512   EXPECT_TRUE(IsRepeat('*'));
513   EXPECT_TRUE(IsRepeat('+'));
514 }
515
516 TEST(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
524 TEST(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
533 TEST(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
541 TEST(IsAsciiWordCharTest, IsTrueForLetter) {
542   EXPECT_TRUE(IsAsciiWordChar('a'));
543   EXPECT_TRUE(IsAsciiWordChar('b'));
544   EXPECT_TRUE(IsAsciiWordChar('A'));
545   EXPECT_TRUE(IsAsciiWordChar('Z'));
546 }
547
548 TEST(IsAsciiWordCharTest, IsTrueForDigit) {
549   EXPECT_TRUE(IsAsciiWordChar('0'));
550   EXPECT_TRUE(IsAsciiWordChar('1'));
551   EXPECT_TRUE(IsAsciiWordChar('7'));
552   EXPECT_TRUE(IsAsciiWordChar('9'));
553 }
554
555 TEST(IsAsciiWordCharTest, IsTrueForUnderscore) {
556   EXPECT_TRUE(IsAsciiWordChar('_'));
557 }
558
559 TEST(IsValidEscapeTest, IsFalseForNonPrintable) {
560   EXPECT_FALSE(IsValidEscape('\0'));
561   EXPECT_FALSE(IsValidEscape('\007'));
562 }
563
564 TEST(IsValidEscapeTest, IsFalseForDigit) {
565   EXPECT_FALSE(IsValidEscape('0'));
566   EXPECT_FALSE(IsValidEscape('9'));
567 }
568
569 TEST(IsValidEscapeTest, IsFalseForWhiteSpace) {
570   EXPECT_FALSE(IsValidEscape(' '));
571   EXPECT_FALSE(IsValidEscape('\n'));
572 }
573
574 TEST(IsValidEscapeTest, IsFalseForSomeLetter) {
575   EXPECT_FALSE(IsValidEscape('a'));
576   EXPECT_FALSE(IsValidEscape('Z'));
577 }
578
579 TEST(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
590 TEST(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
599 TEST(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
611 TEST(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
620 TEST(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
629 TEST(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
640 TEST(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
649 TEST(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
661 TEST(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
672 TEST(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
691 TEST(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
700 TEST(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
710 TEST(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
746 TEST(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
757 TEST(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
769 TEST(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
780 TEST(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
791 TEST(MatchRegexAtHeadTest, ReturnsTrueForEmptyRegex) {
792   EXPECT_TRUE(MatchRegexAtHead("", ""));
793   EXPECT_TRUE(MatchRegexAtHead("", "ab"));
794 }
795
796 TEST(MatchRegexAtHeadTest, WorksWhenDollarIsInRegex) {
797   EXPECT_FALSE(MatchRegexAtHead("$", "a"));
798
799   EXPECT_TRUE(MatchRegexAtHead("$", ""));
800   EXPECT_TRUE(MatchRegexAtHead("a$", "a"));
801 }
802
803 TEST(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
811 TEST(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
820 TEST(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
831 TEST(MatchRegexAtHeadTest, MatchesSequentially) {
832   EXPECT_FALSE(MatchRegexAtHead("ab.*c", "acabc"));
833
834   EXPECT_TRUE(MatchRegexAtHead("ab.*c", "ab-fsc"));
835 }
836
837 TEST(MatchRegexAnywhereTest, ReturnsFalseWhenStringIsNull) {
838   EXPECT_FALSE(MatchRegexAnywhere("", NULL));
839 }
840
841 TEST(MatchRegexAnywhereTest, WorksWhenRegexStartsWithCaret) {
842   EXPECT_FALSE(MatchRegexAnywhere("^a", "ba"));
843   EXPECT_FALSE(MatchRegexAnywhere("^$", "a"));
844
845   EXPECT_TRUE(MatchRegexAnywhere("^a", "ab"));
846   EXPECT_TRUE(MatchRegexAnywhere("^", "ab"));
847   EXPECT_TRUE(MatchRegexAnywhere("^$", ""));
848 }
849
850 TEST(MatchRegexAnywhereTest, ReturnsFalseWhenNoMatch) {
851   EXPECT_FALSE(MatchRegexAnywhere("a", "bcde123"));
852   EXPECT_FALSE(MatchRegexAnywhere("a.+a", "--aa88888888"));
853 }
854
855 TEST(MatchRegexAnywhereTest, ReturnsTrueWhenMatchingPrefix) {
856   EXPECT_TRUE(MatchRegexAnywhere("\\w+", "ab1_ - 5"));
857   EXPECT_TRUE(MatchRegexAnywhere(".*=", "="));
858   EXPECT_TRUE(MatchRegexAnywhere("x.*ab?.*bc", "xaaabc"));
859 }
860
861 TEST(MatchRegexAnywhereTest, ReturnsTrueWhenMatchingNonPrefix) {
862   EXPECT_TRUE(MatchRegexAnywhere("\\w+", "$$$ ab1_ - 5"));
863   EXPECT_TRUE(MatchRegexAnywhere("\\.+=", "=  ...="));
864 }
865
866 // Tests RE's implicit constructors.
867 TEST(RETest, ImplicitConstructorWorks) {
868   const RE empty("");
869   EXPECT_STREQ("", empty.pattern());
870
871   const RE simple("hello");
872   EXPECT_STREQ("hello", simple.pattern());
873 }
874
875 // Tests that RE's constructors reject invalid regular expressions.
876 TEST(RETest, RejectsInvalidRegex) {
877   EXPECT_NONFATAL_FAILURE({
878     const RE normal(NULL);
879   }, "NULL is not a valid simple regular expression");
880
881   EXPECT_NONFATAL_FAILURE({
882     const RE normal(".*(\\w+");
883   }, "'(' is unsupported");
884
885   EXPECT_NONFATAL_FAILURE({
886     const RE invalid("^?");
887   }, "'?' can only follow a repeatable token");
888 }
889
890 // Tests RE::FullMatch().
891 TEST(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().
907 TEST(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
924 TEST(CaptureTest, CapturesStdout) {
925   CaptureStdout();
926   fprintf(stdout, "abc");
927   EXPECT_STREQ("abc", GetCapturedStdout().c_str());
928
929   CaptureStdout();
930   fprintf(stdout, "def%cghi", '\0');
931   EXPECT_EQ(::std::string("def\0ghi", 7), ::std::string(GetCapturedStdout()));
932 }
933
934 TEST(CaptureTest, CapturesStderr) {
935   CaptureStderr();
936   fprintf(stderr, "jkl");
937   EXPECT_STREQ("jkl", GetCapturedStderr().c_str());
938
939   CaptureStderr();
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.
945 TEST(CaptureTest, CapturesStdoutAndStderr) {
946   CaptureStdout();
947   CaptureStderr();
948   fprintf(stdout, "pqr");
949   fprintf(stderr, "stu");
950   EXPECT_STREQ("pqr", GetCapturedStdout().c_str());
951   EXPECT_STREQ("stu", GetCapturedStderr().c_str());
952 }
953
954 TEST(CaptureDeathTest, CannotReenterStdoutCapture) {
955   CaptureStdout();
956   EXPECT_DEATH_IF_SUPPORTED(CaptureStdout(),
957                             "Only one stdout capturer can exist at a time");
958   GetCapturedStdout();
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
966 TEST(ThreadLocalTest, DefaultConstructorInitializesToDefaultValues) {
967   ThreadLocal<int> t1;
968   EXPECT_EQ(0, t1.get());
969
970   ThreadLocal<void*> t2;
971   EXPECT_TRUE(t2.get() == nullptr);
972 }
973
974 TEST(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
983 class NoDefaultContructor {
984  public:
985   explicit NoDefaultContructor(const char*) {}
986   NoDefaultContructor(const NoDefaultContructor&) {}
987 };
988
989 TEST(ThreadLocalTest, ValueDefaultContructorIsNotRequiredForParamVersion) {
990   ThreadLocal<NoDefaultContructor> bar(NoDefaultContructor("foo"));
991   bar.pointer();
992 }
993
994 TEST(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
1004 TEST(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
1017 void AddTwo(int* param) { *param += 2; }
1018
1019 TEST(ThreadWithParamTest, ConstructorExecutesThreadFunc) {
1020   int i = 40;
1021   ThreadWithParam<int*> thread(&AddTwo, &i, nullptr);
1022   thread.Join();
1023   EXPECT_EQ(42, i);
1024 }
1025
1026 TEST(MutexDeathTest, AssertHeldShouldAssertWhenNotLocked) {
1027   // AssertHeld() is flaky only in the presence of multiple threads accessing
1028   // the lock. In this case, the test is robust.
1029   EXPECT_DEATH_IF_SUPPORTED({
1030     Mutex m;
1031     { MutexLock lock(&m); }
1032     m.AssertHeld();
1033   },
1034   "thread .*hold");
1035 }
1036
1037 TEST(MutexTest, AssertHeldShouldNotAssertWhenLocked) {
1038   Mutex m;
1039   MutexLock lock(&m);
1040   m.AssertHeld();
1041 }
1042
1043 class 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;
1060       GTEST_CHECK_POSIX_SUCCESS_(
1061           pthread_mutex_init(&memory_barrier_mutex, nullptr));
1062       GTEST_CHECK_POSIX_SUCCESS_(pthread_mutex_lock(&memory_barrier_mutex));
1063
1064       SleepMilliseconds(static_cast<int>(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(static_cast<int>(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
1088 void 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.
1094 TEST(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   std::unique_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
1122 template <typename T>
1123 void RunFromThread(void (func)(T), T param) {
1124   ThreadWithParam<T> thread(func, param, nullptr);
1125   thread.Join();
1126 }
1127
1128 void RetrieveThreadLocalValue(
1129     pair<ThreadLocal<std::string>*, std::string*> param) {
1130   *param.second = param.first->get();
1131 }
1132
1133 TEST(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.
1148 class 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
1192 std::vector<DestructorCall*>* const DestructorCall::list_ =
1193     new std::vector<DestructorCall*>;
1194
1195 // DestructorTracker keeps track of whether its instances have been
1196 // destroyed.
1197 class 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
1216 typedef ThreadLocal<DestructorTracker>* ThreadParam;
1217
1218 void CallThreadLocalGet(ThreadParam thread_local_param) {
1219   thread_local_param->get();
1220 }
1221
1222 // Tests that when a ThreadLocal object dies in a thread, it destroys
1223 // the managed object for that thread.
1224 TEST(ThreadLocalTest, DestroysManagedObjectForOwnThreadWhenDying) {
1225   DestructorCall::ResetList();
1226
1227   {
1228     ThreadLocal<DestructorTracker> thread_local_tracker;
1229     ASSERT_EQ(0U, DestructorCall::List().size());
1230
1231     // This creates another DestructorTracker object for the main thread.
1232     thread_local_tracker.get();
1233     ASSERT_EQ(1U, DestructorCall::List().size());
1234     ASSERT_FALSE(DestructorCall::List()[0]->CheckDestroyed());
1235   }
1236
1237   // Now thread_local_tracker has died.
1238   ASSERT_EQ(1U, DestructorCall::List().size());
1239   EXPECT_TRUE(DestructorCall::List()[0]->CheckDestroyed());
1240
1241   DestructorCall::ResetList();
1242 }
1243
1244 // Tests that when a thread exits, the thread-local object for that
1245 // thread is destroyed.
1246 TEST(ThreadLocalTest, DestroysManagedObjectAtThreadExit) {
1247   DestructorCall::ResetList();
1248
1249   {
1250     ThreadLocal<DestructorTracker> thread_local_tracker;
1251     ASSERT_EQ(0U, DestructorCall::List().size());
1252
1253     // This creates another DestructorTracker object in the new thread.
1254     ThreadWithParam<ThreadParam> thread(&CallThreadLocalGet,
1255                                         &thread_local_tracker, nullptr);
1256     thread.Join();
1257
1258     // The thread has exited, and we should have a DestroyedTracker
1259     // instance created for it. But it may not have been destroyed yet.
1260     ASSERT_EQ(1U, DestructorCall::List().size());
1261   }
1262
1263   // The thread has exited and thread_local_tracker has died.
1264   ASSERT_EQ(1U, DestructorCall::List().size());
1265   EXPECT_TRUE(DestructorCall::List()[0]->CheckDestroyed());
1266
1267   DestructorCall::ResetList();
1268 }
1269
1270 TEST(ThreadLocalTest, ThreadLocalMutationsAffectOnlyCurrentThread) {
1271   ThreadLocal<std::string> thread_local_string;
1272   thread_local_string.set("Foo");
1273   EXPECT_STREQ("Foo", thread_local_string.get().c_str());
1274
1275   std::string result;
1276   RunFromThread(&RetrieveThreadLocalValue,
1277                 make_pair(&thread_local_string, &result));
1278   EXPECT_TRUE(result.empty());
1279 }
1280
1281 #endif  // GTEST_IS_THREADSAFE
1282
1283 #if GTEST_OS_WINDOWS
1284 TEST(WindowsTypesTest, HANDLEIsVoidStar) {
1285   StaticAssertTypeEq<HANDLE, void*>();
1286 }
1287
1288 #if GTEST_OS_WINDOWS_MINGW && !defined(__MINGW64_VERSION_MAJOR)
1289 TEST(WindowsTypesTest, _CRITICAL_SECTIONIs_CRITICAL_SECTION) {
1290   StaticAssertTypeEq<CRITICAL_SECTION, _CRITICAL_SECTION>();
1291 }
1292 #else
1293 TEST(WindowsTypesTest, CRITICAL_SECTIONIs_RTL_CRITICAL_SECTION) {
1294   StaticAssertTypeEq<CRITICAL_SECTION, _RTL_CRITICAL_SECTION>();
1295 }
1296 #endif
1297
1298 #endif  // GTEST_OS_WINDOWS
1299
1300 }  // namespace internal
1301 }  // namespace testing