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