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