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