gtest-port_test.cc 39.5 KB
Newer Older
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
// Copyright 2008, Google Inc.
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
//     * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
//     * Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following disclaimer
// in the documentation and/or other materials provided with the
// distribution.
//     * Neither the name of Google Inc. nor the names of its
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
30
// Authors: vladl@google.com (Vlad Losev), wan@google.com (Zhanyong Wan)
31
32
33
//
// This file tests the internal cross-platform support utilities.

34
#include "gtest/internal/gtest-port.h"
35

36
37
#include <stdio.h>

38
#if GTEST_OS_MAC
39
# include <time.h>
40
41
#endif  // GTEST_OS_MAC

42
#include <list>
43
#include <utility>  // For std::pair and std::make_pair.
44
#include <vector>
45

46
47
#include "gtest/gtest.h"
#include "gtest/gtest-spi.h"
48

49
50
51
52
53
// Indicates that this translation unit is part of Google Test's
// implementation.  It must come before gtest-internal-inl.h is
// included, or there will be a compiler error.  This trick is to
// prevent a user from accidentally including gtest-internal-inl.h in
// his code.
zhanyong.wan's avatar
zhanyong.wan committed
54
#define GTEST_IMPLEMENTATION_ 1
55
#include "src/gtest-internal-inl.h"
zhanyong.wan's avatar
zhanyong.wan committed
56
#undef GTEST_IMPLEMENTATION_
57

58
59
60
using std::make_pair;
using std::pair;

61
62
63
namespace testing {
namespace internal {

64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
TEST(IsXDigitTest, WorksForNarrowAscii) {
  EXPECT_TRUE(IsXDigit('0'));
  EXPECT_TRUE(IsXDigit('9'));
  EXPECT_TRUE(IsXDigit('A'));
  EXPECT_TRUE(IsXDigit('F'));
  EXPECT_TRUE(IsXDigit('a'));
  EXPECT_TRUE(IsXDigit('f'));

  EXPECT_FALSE(IsXDigit('-'));
  EXPECT_FALSE(IsXDigit('g'));
  EXPECT_FALSE(IsXDigit('G'));
}

TEST(IsXDigitTest, ReturnsFalseForNarrowNonAscii) {
  EXPECT_FALSE(IsXDigit(static_cast<char>(0x80)));
  EXPECT_FALSE(IsXDigit(static_cast<char>('0' | 0x80)));
}

TEST(IsXDigitTest, WorksForWideAscii) {
  EXPECT_TRUE(IsXDigit(L'0'));
  EXPECT_TRUE(IsXDigit(L'9'));
  EXPECT_TRUE(IsXDigit(L'A'));
  EXPECT_TRUE(IsXDigit(L'F'));
  EXPECT_TRUE(IsXDigit(L'a'));
  EXPECT_TRUE(IsXDigit(L'f'));

  EXPECT_FALSE(IsXDigit(L'-'));
  EXPECT_FALSE(IsXDigit(L'g'));
  EXPECT_FALSE(IsXDigit(L'G'));
}

TEST(IsXDigitTest, ReturnsFalseForWideNonAscii) {
  EXPECT_FALSE(IsXDigit(static_cast<wchar_t>(0x80)));
  EXPECT_FALSE(IsXDigit(static_cast<wchar_t>(L'0' | 0x80)));
  EXPECT_FALSE(IsXDigit(static_cast<wchar_t>(L'0' | 0x100)));
}

101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
class Base {
 public:
  // Copy constructor and assignment operator do exactly what we need, so we
  // use them.
  Base() : member_(0) {}
  explicit Base(int n) : member_(n) {}
  virtual ~Base() {}
  int member() { return member_; }

 private:
  int member_;
};

class Derived : public Base {
 public:
  explicit Derived(int n) : Base(n) {}
};

TEST(ImplicitCastTest, ConvertsPointers) {
  Derived derived(0);
121
  EXPECT_TRUE(&derived == ::testing::internal::ImplicitCast_<Base*>(&derived));
122
123
124
125
}

TEST(ImplicitCastTest, CanUseInheritance) {
  Derived derived(1);
126
  Base base = ::testing::internal::ImplicitCast_<Base>(derived);
127
128
129
130
131
  EXPECT_EQ(derived.member(), base.member());
}

class Castable {
 public:
132
  explicit Castable(bool* converted) : converted_(converted) {}
133
134
135
136
137
138
139
140
141
142
143
144
  operator Base() {
    *converted_ = true;
    return Base();
  }

 private:
  bool* converted_;
};

TEST(ImplicitCastTest, CanUseNonConstCastOperator) {
  bool converted = false;
  Castable castable(&converted);
145
  Base base = ::testing::internal::ImplicitCast_<Base>(castable);
146
147
148
149
150
  EXPECT_TRUE(converted);
}

class ConstCastable {
 public:
151
  explicit ConstCastable(bool* converted) : converted_(converted) {}
152
153
154
155
156
157
158
159
160
161
162
163
  operator Base() const {
    *converted_ = true;
    return Base();
  }

 private:
  bool* converted_;
};

TEST(ImplicitCastTest, CanUseConstCastOperatorOnConstValues) {
  bool converted = false;
  const ConstCastable const_castable(&converted);
164
  Base base = ::testing::internal::ImplicitCast_<Base>(const_castable);
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
  EXPECT_TRUE(converted);
}

class ConstAndNonConstCastable {
 public:
  ConstAndNonConstCastable(bool* converted, bool* const_converted)
      : converted_(converted), const_converted_(const_converted) {}
  operator Base() {
    *converted_ = true;
    return Base();
  }
  operator Base() const {
    *const_converted_ = true;
    return Base();
  }

 private:
  bool* converted_;
  bool* const_converted_;
};

TEST(ImplicitCastTest, CanSelectBetweenConstAndNonConstCasrAppropriately) {
  bool converted = false;
  bool const_converted = false;
  ConstAndNonConstCastable castable(&converted, &const_converted);
190
  Base base = ::testing::internal::ImplicitCast_<Base>(castable);
191
192
193
194
195
196
  EXPECT_TRUE(converted);
  EXPECT_FALSE(const_converted);

  converted = false;
  const_converted = false;
  const ConstAndNonConstCastable const_castable(&converted, &const_converted);
197
  base = ::testing::internal::ImplicitCast_<Base>(const_castable);
198
199
200
201
202
203
204
205
206
207
208
  EXPECT_FALSE(converted);
  EXPECT_TRUE(const_converted);
}

class To {
 public:
  To(bool* converted) { *converted = true; }  // NOLINT
};

TEST(ImplicitCastTest, CanUseImplicitConstructor) {
  bool converted = false;
209
  To to = ::testing::internal::ImplicitCast_<To>(&converted);
210
  (void)to;
211
212
213
  EXPECT_TRUE(converted);
}

214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
TEST(IteratorTraitsTest, WorksForSTLContainerIterators) {
  StaticAssertTypeEq<int,
      IteratorTraits< ::std::vector<int>::const_iterator>::value_type>();
  StaticAssertTypeEq<bool,
      IteratorTraits< ::std::list<bool>::iterator>::value_type>();
}

TEST(IteratorTraitsTest, WorksForPointerToNonConst) {
  StaticAssertTypeEq<char, IteratorTraits<char*>::value_type>();
  StaticAssertTypeEq<const void*, IteratorTraits<const void**>::value_type>();
}

TEST(IteratorTraitsTest, WorksForPointerToConst) {
  StaticAssertTypeEq<char, IteratorTraits<const char*>::value_type>();
  StaticAssertTypeEq<const void*,
      IteratorTraits<const void* const*>::value_type>();
}

232
233
234
235
236
237
238
239
// Tests that the element_type typedef is available in scoped_ptr and refers
// to the parameter type.
TEST(ScopedPtrTest, DefinesElementType) {
  StaticAssertTypeEq<int, ::testing::internal::scoped_ptr<int>::element_type>();
}

// TODO(vladl@google.com): Implement THE REST of scoped_ptr tests.

240
TEST(GtestCheckSyntaxTest, BehavesLikeASingleStatement) {
241
  if (AlwaysFalse())
242
243
244
    GTEST_CHECK_(false) << "This should never be executed; "
                           "It's a compilation test only.";

245
  if (AlwaysTrue())
246
247
248
249
    GTEST_CHECK_(true);
  else
    ;  // NOLINT

250
  if (AlwaysFalse())
251
252
253
254
255
256
257
258
259
260
261
262
263
    ;  // NOLINT
  else
    GTEST_CHECK_(true) << "";
}

TEST(GtestCheckSyntaxTest, WorksWithSwitch) {
  switch (0) {
    case 1:
      break;
    default:
      GTEST_CHECK_(true);
  }

264
  switch (0)
265
266
267
268
    case 0:
      GTEST_CHECK_(true) << "Check failed in switch case";
}

269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
// Verifies behavior of FormatFileLocation.
TEST(FormatFileLocationTest, FormatsFileLocation) {
  EXPECT_PRED_FORMAT2(IsSubstring, "foo.cc", FormatFileLocation("foo.cc", 42));
  EXPECT_PRED_FORMAT2(IsSubstring, "42", FormatFileLocation("foo.cc", 42));
}

TEST(FormatFileLocationTest, FormatsUnknownFile) {
  EXPECT_PRED_FORMAT2(
      IsSubstring, "unknown file", FormatFileLocation(NULL, 42));
  EXPECT_PRED_FORMAT2(IsSubstring, "42", FormatFileLocation(NULL, 42));
}

TEST(FormatFileLocationTest, FormatsUknownLine) {
  EXPECT_EQ("foo.cc:", FormatFileLocation("foo.cc", -1));
}

TEST(FormatFileLocationTest, FormatsUknownFileAndLine) {
  EXPECT_EQ("unknown file:", FormatFileLocation(NULL, -1));
}

// Verifies behavior of FormatCompilerIndependentFileLocation.
TEST(FormatCompilerIndependentFileLocationTest, FormatsFileLocation) {
  EXPECT_EQ("foo.cc:42", FormatCompilerIndependentFileLocation("foo.cc", 42));
}

TEST(FormatCompilerIndependentFileLocationTest, FormatsUknownFile) {
  EXPECT_EQ("unknown file:42",
            FormatCompilerIndependentFileLocation(NULL, 42));
}

TEST(FormatCompilerIndependentFileLocationTest, FormatsUknownLine) {
  EXPECT_EQ("foo.cc", FormatCompilerIndependentFileLocation("foo.cc", -1));
}

TEST(FormatCompilerIndependentFileLocationTest, FormatsUknownFileAndLine) {
  EXPECT_EQ("unknown file", FormatCompilerIndependentFileLocation(NULL, -1));
}

kosak's avatar
kosak committed
307
#if GTEST_OS_LINUX || GTEST_OS_MAC || GTEST_OS_QNX
308
void* ThreadFunc(void* data) {
kosak's avatar
kosak committed
309
310
311
  internal::Mutex* mutex = static_cast<internal::Mutex*>(data);
  mutex->Lock();
  mutex->Unlock();
312
313
314
315
  return NULL;
}

TEST(GetThreadCountTest, ReturnsCorrectValue) {
kosak's avatar
kosak committed
316
  const size_t starting_count = GetThreadCount();
317
318
  pthread_t       thread_id;

kosak's avatar
kosak committed
319
320
321
322
323
324
325
326
327
328
329
330
  internal::Mutex mutex;
  {
    internal::MutexLock lock(&mutex);
    pthread_attr_t  attr;
    ASSERT_EQ(0, pthread_attr_init(&attr));
    ASSERT_EQ(0, pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_JOINABLE));

    const int status = pthread_create(&thread_id, &attr, &ThreadFunc, &mutex);
    ASSERT_EQ(0, pthread_attr_destroy(&attr));
    ASSERT_EQ(0, status);
    EXPECT_EQ(starting_count + 1, GetThreadCount());
  }
331
332
333

  void* dummy;
  ASSERT_EQ(0, pthread_join(thread_id, &dummy));
334

kosak's avatar
kosak committed
335
  // The OS may not immediately report the updated thread count after
336
337
338
  // joining a thread, causing flakiness in this test. To counter that, we
  // wait for up to .5 seconds for the OS to report the correct value.
  for (int i = 0; i < 5; ++i) {
kosak's avatar
kosak committed
339
    if (GetThreadCount() == starting_count)
340
341
      break;

342
    SleepMilliseconds(100);
343
  }
344

kosak's avatar
kosak committed
345
  EXPECT_EQ(starting_count, GetThreadCount());
346
347
348
}
#else
TEST(GetThreadCountTest, ReturnsZeroWhenUnableToCountThreads) {
349
  EXPECT_EQ(0U, GetThreadCount());
350
}
kosak's avatar
kosak committed
351
#endif  // GTEST_OS_LINUX || GTEST_OS_MAC || GTEST_OS_QNX
352

353
354
TEST(GtestCheckDeathTest, DiesWithCorrectOutputOnFailure) {
  const bool a_false_condition = false;
355
  const char regex[] =
356
#ifdef _MSC_VER
357
     "gtest-port_test\\.cc\\(\\d+\\):"
vladlosev's avatar
vladlosev committed
358
#elif GTEST_USES_POSIX_RE
359
     "gtest-port_test\\.cc:[0-9]+"
vladlosev's avatar
vladlosev committed
360
361
#else
     "gtest-port_test\\.cc:\\d+"
362
#endif  // _MSC_VER
363
364
     ".*a_false_condition.*Extra info.*";

365
366
  EXPECT_DEATH_IF_SUPPORTED(GTEST_CHECK_(a_false_condition) << "Extra info",
                            regex);
367
368
}

369
370
#if GTEST_HAS_DEATH_TEST

371
372
373
374
375
376
377
378
379
380
TEST(GtestCheckDeathTest, LivesSilentlyOnSuccess) {
  EXPECT_EXIT({
      GTEST_CHECK_(true) << "Extra info";
      ::std::cerr << "Success\n";
      exit(0); },
      ::testing::ExitedWithCode(0), "Success");
}

#endif  // GTEST_HAS_DEATH_TEST

381
382
383
384
385
// Verifies that Google Test choose regular expression engine appropriate to
// the platform. The test will produce compiler errors in case of failure.
// For simplicity, we only cover the most important platforms here.
TEST(RegexEngineSelectionTest, SelectsCorrectRegexEngine) {
#if GTEST_HAS_POSIX_RE
386

387
  EXPECT_TRUE(GTEST_USES_POSIX_RE);
388

389
#else
390

391
  EXPECT_TRUE(GTEST_USES_SIMPLE_RE);
392

393
394
395
#endif
}

396
#if GTEST_USES_POSIX_RE
397

398
# if GTEST_HAS_TYPED_TEST
399

400
401
402
403
404
405
406
template <typename Str>
class RETest : public ::testing::Test {};

// Defines StringTypes as the list of all string types that class RE
// supports.
typedef testing::Types<
    ::std::string,
407
#  if GTEST_HAS_GLOBAL_STRING
408
    ::string,
409
#  endif  // GTEST_HAS_GLOBAL_STRING
410
411
412
413
414
415
    const char*> StringTypes;

TYPED_TEST_CASE(RETest, StringTypes);

// Tests RE's implicit constructors.
TYPED_TEST(RETest, ImplicitConstructorWorks) {
416
  const RE empty(TypeParam(""));
417
418
  EXPECT_STREQ("", empty.pattern());

419
  const RE simple(TypeParam("hello"));
420
421
  EXPECT_STREQ("hello", simple.pattern());

422
  const RE normal(TypeParam(".*(\\w+)"));
423
424
425
426
427
428
  EXPECT_STREQ(".*(\\w+)", normal.pattern());
}

// Tests that RE's constructors reject invalid regular expressions.
TYPED_TEST(RETest, RejectsInvalidRegex) {
  EXPECT_NONFATAL_FAILURE({
429
    const RE invalid(TypeParam("?"));
430
431
432
433
434
  }, "\"?\" is not a valid POSIX Extended regular expression.");
}

// Tests RE::FullMatch().
TYPED_TEST(RETest, FullMatchWorks) {
435
  const RE empty(TypeParam(""));
436
437
438
  EXPECT_TRUE(RE::FullMatch(TypeParam(""), empty));
  EXPECT_FALSE(RE::FullMatch(TypeParam("a"), empty));

439
  const RE re(TypeParam("a.*z"));
440
441
442
443
444
445
446
447
  EXPECT_TRUE(RE::FullMatch(TypeParam("az"), re));
  EXPECT_TRUE(RE::FullMatch(TypeParam("axyz"), re));
  EXPECT_FALSE(RE::FullMatch(TypeParam("baz"), re));
  EXPECT_FALSE(RE::FullMatch(TypeParam("azy"), re));
}

// Tests RE::PartialMatch().
TYPED_TEST(RETest, PartialMatchWorks) {
448
  const RE empty(TypeParam(""));
449
450
451
  EXPECT_TRUE(RE::PartialMatch(TypeParam(""), empty));
  EXPECT_TRUE(RE::PartialMatch(TypeParam("a"), empty));

452
  const RE re(TypeParam("a.*z"));
453
454
455
456
457
458
459
  EXPECT_TRUE(RE::PartialMatch(TypeParam("az"), re));
  EXPECT_TRUE(RE::PartialMatch(TypeParam("axyz"), re));
  EXPECT_TRUE(RE::PartialMatch(TypeParam("baz"), re));
  EXPECT_TRUE(RE::PartialMatch(TypeParam("azy"), re));
  EXPECT_FALSE(RE::PartialMatch(TypeParam("zza"), re));
}

460
# endif  // GTEST_HAS_TYPED_TEST
461

462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
#elif GTEST_USES_SIMPLE_RE

TEST(IsInSetTest, NulCharIsNotInAnySet) {
  EXPECT_FALSE(IsInSet('\0', ""));
  EXPECT_FALSE(IsInSet('\0', "\0"));
  EXPECT_FALSE(IsInSet('\0', "a"));
}

TEST(IsInSetTest, WorksForNonNulChars) {
  EXPECT_FALSE(IsInSet('a', "Ab"));
  EXPECT_FALSE(IsInSet('c', ""));

  EXPECT_TRUE(IsInSet('b', "bcd"));
  EXPECT_TRUE(IsInSet('b', "ab"));
}

478
479
480
481
482
483
484
TEST(IsAsciiDigitTest, IsFalseForNonDigit) {
  EXPECT_FALSE(IsAsciiDigit('\0'));
  EXPECT_FALSE(IsAsciiDigit(' '));
  EXPECT_FALSE(IsAsciiDigit('+'));
  EXPECT_FALSE(IsAsciiDigit('-'));
  EXPECT_FALSE(IsAsciiDigit('.'));
  EXPECT_FALSE(IsAsciiDigit('a'));
485
486
}

487
488
489
490
491
TEST(IsAsciiDigitTest, IsTrueForDigit) {
  EXPECT_TRUE(IsAsciiDigit('0'));
  EXPECT_TRUE(IsAsciiDigit('1'));
  EXPECT_TRUE(IsAsciiDigit('5'));
  EXPECT_TRUE(IsAsciiDigit('9'));
492
493
}

494
495
496
497
498
499
TEST(IsAsciiPunctTest, IsFalseForNonPunct) {
  EXPECT_FALSE(IsAsciiPunct('\0'));
  EXPECT_FALSE(IsAsciiPunct(' '));
  EXPECT_FALSE(IsAsciiPunct('\n'));
  EXPECT_FALSE(IsAsciiPunct('a'));
  EXPECT_FALSE(IsAsciiPunct('0'));
500
501
}

502
TEST(IsAsciiPunctTest, IsTrueForPunct) {
503
  for (const char* p = "^-!\"#$%&'()*+,./:;<=>?@[\\]_`{|}~"; *p; p++) {
504
    EXPECT_PRED1(IsAsciiPunct, *p);
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
  }
}

TEST(IsRepeatTest, IsFalseForNonRepeatChar) {
  EXPECT_FALSE(IsRepeat('\0'));
  EXPECT_FALSE(IsRepeat(' '));
  EXPECT_FALSE(IsRepeat('a'));
  EXPECT_FALSE(IsRepeat('1'));
  EXPECT_FALSE(IsRepeat('-'));
}

TEST(IsRepeatTest, IsTrueForRepeatChar) {
  EXPECT_TRUE(IsRepeat('?'));
  EXPECT_TRUE(IsRepeat('*'));
  EXPECT_TRUE(IsRepeat('+'));
}

522
523
524
525
526
527
TEST(IsAsciiWhiteSpaceTest, IsFalseForNonWhiteSpace) {
  EXPECT_FALSE(IsAsciiWhiteSpace('\0'));
  EXPECT_FALSE(IsAsciiWhiteSpace('a'));
  EXPECT_FALSE(IsAsciiWhiteSpace('1'));
  EXPECT_FALSE(IsAsciiWhiteSpace('+'));
  EXPECT_FALSE(IsAsciiWhiteSpace('_'));
528
529
}

530
531
532
533
534
535
536
TEST(IsAsciiWhiteSpaceTest, IsTrueForWhiteSpace) {
  EXPECT_TRUE(IsAsciiWhiteSpace(' '));
  EXPECT_TRUE(IsAsciiWhiteSpace('\n'));
  EXPECT_TRUE(IsAsciiWhiteSpace('\r'));
  EXPECT_TRUE(IsAsciiWhiteSpace('\t'));
  EXPECT_TRUE(IsAsciiWhiteSpace('\v'));
  EXPECT_TRUE(IsAsciiWhiteSpace('\f'));
537
538
}

539
540
541
542
543
544
TEST(IsAsciiWordCharTest, IsFalseForNonWordChar) {
  EXPECT_FALSE(IsAsciiWordChar('\0'));
  EXPECT_FALSE(IsAsciiWordChar('+'));
  EXPECT_FALSE(IsAsciiWordChar('.'));
  EXPECT_FALSE(IsAsciiWordChar(' '));
  EXPECT_FALSE(IsAsciiWordChar('\n'));
545
546
}

547
548
549
550
551
TEST(IsAsciiWordCharTest, IsTrueForLetter) {
  EXPECT_TRUE(IsAsciiWordChar('a'));
  EXPECT_TRUE(IsAsciiWordChar('b'));
  EXPECT_TRUE(IsAsciiWordChar('A'));
  EXPECT_TRUE(IsAsciiWordChar('Z'));
552
553
}

554
555
556
557
558
TEST(IsAsciiWordCharTest, IsTrueForDigit) {
  EXPECT_TRUE(IsAsciiWordChar('0'));
  EXPECT_TRUE(IsAsciiWordChar('1'));
  EXPECT_TRUE(IsAsciiWordChar('7'));
  EXPECT_TRUE(IsAsciiWordChar('9'));
559
560
}

561
562
TEST(IsAsciiWordCharTest, IsTrueForUnderscore) {
  EXPECT_TRUE(IsAsciiWordChar('_'));
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
}

TEST(IsValidEscapeTest, IsFalseForNonPrintable) {
  EXPECT_FALSE(IsValidEscape('\0'));
  EXPECT_FALSE(IsValidEscape('\007'));
}

TEST(IsValidEscapeTest, IsFalseForDigit) {
  EXPECT_FALSE(IsValidEscape('0'));
  EXPECT_FALSE(IsValidEscape('9'));
}

TEST(IsValidEscapeTest, IsFalseForWhiteSpace) {
  EXPECT_FALSE(IsValidEscape(' '));
  EXPECT_FALSE(IsValidEscape('\n'));
}

TEST(IsValidEscapeTest, IsFalseForSomeLetter) {
  EXPECT_FALSE(IsValidEscape('a'));
  EXPECT_FALSE(IsValidEscape('Z'));
}

TEST(IsValidEscapeTest, IsTrueForPunct) {
  EXPECT_TRUE(IsValidEscape('.'));
  EXPECT_TRUE(IsValidEscape('-'));
  EXPECT_TRUE(IsValidEscape('^'));
  EXPECT_TRUE(IsValidEscape('$'));
  EXPECT_TRUE(IsValidEscape('('));
  EXPECT_TRUE(IsValidEscape(']'));
  EXPECT_TRUE(IsValidEscape('{'));
  EXPECT_TRUE(IsValidEscape('|'));
}

TEST(IsValidEscapeTest, IsTrueForSomeLetter) {
  EXPECT_TRUE(IsValidEscape('d'));
  EXPECT_TRUE(IsValidEscape('D'));
  EXPECT_TRUE(IsValidEscape('s'));
  EXPECT_TRUE(IsValidEscape('S'));
  EXPECT_TRUE(IsValidEscape('w'));
  EXPECT_TRUE(IsValidEscape('W'));
}

TEST(AtomMatchesCharTest, EscapedPunct) {
  EXPECT_FALSE(AtomMatchesChar(true, '\\', '\0'));
  EXPECT_FALSE(AtomMatchesChar(true, '\\', ' '));
  EXPECT_FALSE(AtomMatchesChar(true, '_', '.'));
  EXPECT_FALSE(AtomMatchesChar(true, '.', 'a'));

  EXPECT_TRUE(AtomMatchesChar(true, '\\', '\\'));
  EXPECT_TRUE(AtomMatchesChar(true, '_', '_'));
  EXPECT_TRUE(AtomMatchesChar(true, '+', '+'));
  EXPECT_TRUE(AtomMatchesChar(true, '.', '.'));
}

TEST(AtomMatchesCharTest, Escaped_d) {
  EXPECT_FALSE(AtomMatchesChar(true, 'd', '\0'));
  EXPECT_FALSE(AtomMatchesChar(true, 'd', 'a'));
  EXPECT_FALSE(AtomMatchesChar(true, 'd', '.'));

  EXPECT_TRUE(AtomMatchesChar(true, 'd', '0'));
  EXPECT_TRUE(AtomMatchesChar(true, 'd', '9'));
}

TEST(AtomMatchesCharTest, Escaped_D) {
  EXPECT_FALSE(AtomMatchesChar(true, 'D', '0'));
  EXPECT_FALSE(AtomMatchesChar(true, 'D', '9'));

  EXPECT_TRUE(AtomMatchesChar(true, 'D', '\0'));
  EXPECT_TRUE(AtomMatchesChar(true, 'D', 'a'));
  EXPECT_TRUE(AtomMatchesChar(true, 'D', '-'));
}

TEST(AtomMatchesCharTest, Escaped_s) {
  EXPECT_FALSE(AtomMatchesChar(true, 's', '\0'));
  EXPECT_FALSE(AtomMatchesChar(true, 's', 'a'));
  EXPECT_FALSE(AtomMatchesChar(true, 's', '.'));
  EXPECT_FALSE(AtomMatchesChar(true, 's', '9'));

  EXPECT_TRUE(AtomMatchesChar(true, 's', ' '));
  EXPECT_TRUE(AtomMatchesChar(true, 's', '\n'));
  EXPECT_TRUE(AtomMatchesChar(true, 's', '\t'));
}

TEST(AtomMatchesCharTest, Escaped_S) {
  EXPECT_FALSE(AtomMatchesChar(true, 'S', ' '));
  EXPECT_FALSE(AtomMatchesChar(true, 'S', '\r'));

  EXPECT_TRUE(AtomMatchesChar(true, 'S', '\0'));
  EXPECT_TRUE(AtomMatchesChar(true, 'S', 'a'));
  EXPECT_TRUE(AtomMatchesChar(true, 'S', '9'));
}

TEST(AtomMatchesCharTest, Escaped_w) {
  EXPECT_FALSE(AtomMatchesChar(true, 'w', '\0'));
  EXPECT_FALSE(AtomMatchesChar(true, 'w', '+'));
  EXPECT_FALSE(AtomMatchesChar(true, 'w', ' '));
  EXPECT_FALSE(AtomMatchesChar(true, 'w', '\n'));

  EXPECT_TRUE(AtomMatchesChar(true, 'w', '0'));
  EXPECT_TRUE(AtomMatchesChar(true, 'w', 'b'));
  EXPECT_TRUE(AtomMatchesChar(true, 'w', 'C'));
  EXPECT_TRUE(AtomMatchesChar(true, 'w', '_'));
}

TEST(AtomMatchesCharTest, Escaped_W) {
  EXPECT_FALSE(AtomMatchesChar(true, 'W', 'A'));
  EXPECT_FALSE(AtomMatchesChar(true, 'W', 'b'));
  EXPECT_FALSE(AtomMatchesChar(true, 'W', '9'));
  EXPECT_FALSE(AtomMatchesChar(true, 'W', '_'));

  EXPECT_TRUE(AtomMatchesChar(true, 'W', '\0'));
  EXPECT_TRUE(AtomMatchesChar(true, 'W', '*'));
  EXPECT_TRUE(AtomMatchesChar(true, 'W', '\n'));
}

TEST(AtomMatchesCharTest, EscapedWhiteSpace) {
  EXPECT_FALSE(AtomMatchesChar(true, 'f', '\0'));
  EXPECT_FALSE(AtomMatchesChar(true, 'f', '\n'));
  EXPECT_FALSE(AtomMatchesChar(true, 'n', '\0'));
  EXPECT_FALSE(AtomMatchesChar(true, 'n', '\r'));
  EXPECT_FALSE(AtomMatchesChar(true, 'r', '\0'));
  EXPECT_FALSE(AtomMatchesChar(true, 'r', 'a'));
  EXPECT_FALSE(AtomMatchesChar(true, 't', '\0'));
  EXPECT_FALSE(AtomMatchesChar(true, 't', 't'));
  EXPECT_FALSE(AtomMatchesChar(true, 'v', '\0'));
  EXPECT_FALSE(AtomMatchesChar(true, 'v', '\f'));

  EXPECT_TRUE(AtomMatchesChar(true, 'f', '\f'));
  EXPECT_TRUE(AtomMatchesChar(true, 'n', '\n'));
  EXPECT_TRUE(AtomMatchesChar(true, 'r', '\r'));
  EXPECT_TRUE(AtomMatchesChar(true, 't', '\t'));
  EXPECT_TRUE(AtomMatchesChar(true, 'v', '\v'));
}

TEST(AtomMatchesCharTest, UnescapedDot) {
  EXPECT_FALSE(AtomMatchesChar(false, '.', '\n'));

  EXPECT_TRUE(AtomMatchesChar(false, '.', '\0'));
  EXPECT_TRUE(AtomMatchesChar(false, '.', '.'));
  EXPECT_TRUE(AtomMatchesChar(false, '.', 'a'));
  EXPECT_TRUE(AtomMatchesChar(false, '.', ' '));
}

TEST(AtomMatchesCharTest, UnescapedChar) {
  EXPECT_FALSE(AtomMatchesChar(false, 'a', '\0'));
  EXPECT_FALSE(AtomMatchesChar(false, 'a', 'b'));
  EXPECT_FALSE(AtomMatchesChar(false, '$', 'a'));

  EXPECT_TRUE(AtomMatchesChar(false, '$', '$'));
  EXPECT_TRUE(AtomMatchesChar(false, '5', '5'));
  EXPECT_TRUE(AtomMatchesChar(false, 'Z', 'Z'));
}

TEST(ValidateRegexTest, GeneratesFailureAndReturnsFalseForInvalid) {
  EXPECT_NONFATAL_FAILURE(ASSERT_FALSE(ValidateRegex(NULL)),
                          "NULL is not a valid simple regular expression");
  EXPECT_NONFATAL_FAILURE(
      ASSERT_FALSE(ValidateRegex("a\\")),
      "Syntax error at index 1 in simple regular expression \"a\\\": ");
  EXPECT_NONFATAL_FAILURE(ASSERT_FALSE(ValidateRegex("a\\")),
                          "'\\' cannot appear at the end");
  EXPECT_NONFATAL_FAILURE(ASSERT_FALSE(ValidateRegex("\\n\\")),
                          "'\\' cannot appear at the end");
  EXPECT_NONFATAL_FAILURE(ASSERT_FALSE(ValidateRegex("\\s\\hb")),
                          "invalid escape sequence \"\\h\"");
  EXPECT_NONFATAL_FAILURE(ASSERT_FALSE(ValidateRegex("^^")),
                          "'^' can only appear at the beginning");
  EXPECT_NONFATAL_FAILURE(ASSERT_FALSE(ValidateRegex(".*^b")),
                          "'^' can only appear at the beginning");
  EXPECT_NONFATAL_FAILURE(ASSERT_FALSE(ValidateRegex("$$")),
                          "'$' can only appear at the end");
  EXPECT_NONFATAL_FAILURE(ASSERT_FALSE(ValidateRegex("^$a")),
                          "'$' can only appear at the end");
  EXPECT_NONFATAL_FAILURE(ASSERT_FALSE(ValidateRegex("a(b")),
                          "'(' is unsupported");
  EXPECT_NONFATAL_FAILURE(ASSERT_FALSE(ValidateRegex("ab)")),
                          "')' is unsupported");
  EXPECT_NONFATAL_FAILURE(ASSERT_FALSE(ValidateRegex("[ab")),
                          "'[' is unsupported");
  EXPECT_NONFATAL_FAILURE(ASSERT_FALSE(ValidateRegex("a{2")),
                          "'{' is unsupported");
  EXPECT_NONFATAL_FAILURE(ASSERT_FALSE(ValidateRegex("?")),
                          "'?' can only follow a repeatable token");
  EXPECT_NONFATAL_FAILURE(ASSERT_FALSE(ValidateRegex("^*")),
                          "'*' can only follow a repeatable token");
  EXPECT_NONFATAL_FAILURE(ASSERT_FALSE(ValidateRegex("5*+")),
                          "'+' can only follow a repeatable token");
}

TEST(ValidateRegexTest, ReturnsTrueForValid) {
  EXPECT_TRUE(ValidateRegex(""));
  EXPECT_TRUE(ValidateRegex("a"));
  EXPECT_TRUE(ValidateRegex(".*"));
  EXPECT_TRUE(ValidateRegex("^a_+"));
  EXPECT_TRUE(ValidateRegex("^a\\t\\&?"));
  EXPECT_TRUE(ValidateRegex("09*$"));
  EXPECT_TRUE(ValidateRegex("^Z$"));
  EXPECT_TRUE(ValidateRegex("a\\^Z\\$\\(\\)\\|\\[\\]\\{\\}"));
}

TEST(MatchRepetitionAndRegexAtHeadTest, WorksForZeroOrOne) {
  EXPECT_FALSE(MatchRepetitionAndRegexAtHead(false, 'a', '?', "a", "ba"));
  // Repeating more than once.
  EXPECT_FALSE(MatchRepetitionAndRegexAtHead(false, 'a', '?', "b", "aab"));

  // Repeating zero times.
  EXPECT_TRUE(MatchRepetitionAndRegexAtHead(false, 'a', '?', "b", "ba"));
  // Repeating once.
  EXPECT_TRUE(MatchRepetitionAndRegexAtHead(false, 'a', '?', "b", "ab"));
  EXPECT_TRUE(MatchRepetitionAndRegexAtHead(false, '#', '?', ".", "##"));
}

TEST(MatchRepetitionAndRegexAtHeadTest, WorksForZeroOrMany) {
  EXPECT_FALSE(MatchRepetitionAndRegexAtHead(false, '.', '*', "a$", "baab"));

  // Repeating zero times.
  EXPECT_TRUE(MatchRepetitionAndRegexAtHead(false, '.', '*', "b", "bc"));
  // Repeating once.
  EXPECT_TRUE(MatchRepetitionAndRegexAtHead(false, '.', '*', "b", "abc"));
  // Repeating more than once.
  EXPECT_TRUE(MatchRepetitionAndRegexAtHead(true, 'w', '*', "-", "ab_1-g"));
}

TEST(MatchRepetitionAndRegexAtHeadTest, WorksForOneOrMany) {
  EXPECT_FALSE(MatchRepetitionAndRegexAtHead(false, '.', '+', "a$", "baab"));
  // Repeating zero times.
  EXPECT_FALSE(MatchRepetitionAndRegexAtHead(false, '.', '+', "b", "bc"));

  // Repeating once.
  EXPECT_TRUE(MatchRepetitionAndRegexAtHead(false, '.', '+', "b", "abc"));
  // Repeating more than once.
  EXPECT_TRUE(MatchRepetitionAndRegexAtHead(true, 'w', '+', "-", "ab_1-g"));
}

TEST(MatchRegexAtHeadTest, ReturnsTrueForEmptyRegex) {
  EXPECT_TRUE(MatchRegexAtHead("", ""));
  EXPECT_TRUE(MatchRegexAtHead("", "ab"));
}

TEST(MatchRegexAtHeadTest, WorksWhenDollarIsInRegex) {
  EXPECT_FALSE(MatchRegexAtHead("$", "a"));

  EXPECT_TRUE(MatchRegexAtHead("$", ""));
  EXPECT_TRUE(MatchRegexAtHead("a$", "a"));
}

TEST(MatchRegexAtHeadTest, WorksWhenRegexStartsWithEscapeSequence) {
  EXPECT_FALSE(MatchRegexAtHead("\\w", "+"));
  EXPECT_FALSE(MatchRegexAtHead("\\W", "ab"));

  EXPECT_TRUE(MatchRegexAtHead("\\sa", "\nab"));
  EXPECT_TRUE(MatchRegexAtHead("\\d", "1a"));
}

TEST(MatchRegexAtHeadTest, WorksWhenRegexStartsWithRepetition) {
  EXPECT_FALSE(MatchRegexAtHead(".+a", "abc"));
  EXPECT_FALSE(MatchRegexAtHead("a?b", "aab"));

  EXPECT_TRUE(MatchRegexAtHead(".*a", "bc12-ab"));
  EXPECT_TRUE(MatchRegexAtHead("a?b", "b"));
  EXPECT_TRUE(MatchRegexAtHead("a?b", "ab"));
}

TEST(MatchRegexAtHeadTest,
     WorksWhenRegexStartsWithRepetionOfEscapeSequence) {
  EXPECT_FALSE(MatchRegexAtHead("\\.+a", "abc"));
  EXPECT_FALSE(MatchRegexAtHead("\\s?b", "  b"));

  EXPECT_TRUE(MatchRegexAtHead("\\(*a", "((((ab"));
  EXPECT_TRUE(MatchRegexAtHead("\\^?b", "^b"));
  EXPECT_TRUE(MatchRegexAtHead("\\\\?b", "b"));
  EXPECT_TRUE(MatchRegexAtHead("\\\\?b", "\\b"));
}

TEST(MatchRegexAtHeadTest, MatchesSequentially) {
  EXPECT_FALSE(MatchRegexAtHead("ab.*c", "acabc"));

  EXPECT_TRUE(MatchRegexAtHead("ab.*c", "ab-fsc"));
}

TEST(MatchRegexAnywhereTest, ReturnsFalseWhenStringIsNull) {
  EXPECT_FALSE(MatchRegexAnywhere("", NULL));
}

TEST(MatchRegexAnywhereTest, WorksWhenRegexStartsWithCaret) {
  EXPECT_FALSE(MatchRegexAnywhere("^a", "ba"));
  EXPECT_FALSE(MatchRegexAnywhere("^$", "a"));

  EXPECT_TRUE(MatchRegexAnywhere("^a", "ab"));
  EXPECT_TRUE(MatchRegexAnywhere("^", "ab"));
  EXPECT_TRUE(MatchRegexAnywhere("^$", ""));
}

TEST(MatchRegexAnywhereTest, ReturnsFalseWhenNoMatch) {
  EXPECT_FALSE(MatchRegexAnywhere("a", "bcde123"));
  EXPECT_FALSE(MatchRegexAnywhere("a.+a", "--aa88888888"));
}

TEST(MatchRegexAnywhereTest, ReturnsTrueWhenMatchingPrefix) {
  EXPECT_TRUE(MatchRegexAnywhere("\\w+", "ab1_ - 5"));
  EXPECT_TRUE(MatchRegexAnywhere(".*=", "="));
  EXPECT_TRUE(MatchRegexAnywhere("x.*ab?.*bc", "xaaabc"));
}

TEST(MatchRegexAnywhereTest, ReturnsTrueWhenMatchingNonPrefix) {
  EXPECT_TRUE(MatchRegexAnywhere("\\w+", "$$$ ab1_ - 5"));
  EXPECT_TRUE(MatchRegexAnywhere("\\.+=", "=  ...="));
}

// Tests RE's implicit constructors.
TEST(RETest, ImplicitConstructorWorks) {
874
  const RE empty("");
875
876
  EXPECT_STREQ("", empty.pattern());

877
  const RE simple("hello");
878
879
880
881
882
883
  EXPECT_STREQ("hello", simple.pattern());
}

// Tests that RE's constructors reject invalid regular expressions.
TEST(RETest, RejectsInvalidRegex) {
  EXPECT_NONFATAL_FAILURE({
884
    const RE normal(NULL);
885
886
887
  }, "NULL is not a valid simple regular expression");

  EXPECT_NONFATAL_FAILURE({
888
    const RE normal(".*(\\w+");
889
890
891
  }, "'(' is unsupported");

  EXPECT_NONFATAL_FAILURE({
892
    const RE invalid("^?");
893
894
895
896
897
898
899
900
901
  }, "'?' can only follow a repeatable token");
}

// Tests RE::FullMatch().
TEST(RETest, FullMatchWorks) {
  const RE empty("");
  EXPECT_TRUE(RE::FullMatch("", empty));
  EXPECT_FALSE(RE::FullMatch("a", empty));

902
  const RE re1("a");
903
904
  EXPECT_TRUE(RE::FullMatch("a", re1));

905
  const RE re("a.*z");
906
907
908
909
910
911
912
913
  EXPECT_TRUE(RE::FullMatch("az", re));
  EXPECT_TRUE(RE::FullMatch("axyz", re));
  EXPECT_FALSE(RE::FullMatch("baz", re));
  EXPECT_FALSE(RE::FullMatch("azy", re));
}

// Tests RE::PartialMatch().
TEST(RETest, PartialMatchWorks) {
914
  const RE empty("");
915
916
917
  EXPECT_TRUE(RE::PartialMatch("", empty));
  EXPECT_TRUE(RE::PartialMatch("a", empty));

918
  const RE re("a.*z");
919
920
921
922
923
924
925
  EXPECT_TRUE(RE::PartialMatch("az", re));
  EXPECT_TRUE(RE::PartialMatch("axyz", re));
  EXPECT_TRUE(RE::PartialMatch("baz", re));
  EXPECT_TRUE(RE::PartialMatch("azy", re));
  EXPECT_FALSE(RE::PartialMatch("zza", re));
}

926
#endif  // GTEST_USES_POSIX_RE
927

928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
#if !GTEST_OS_WINDOWS_MOBILE

TEST(CaptureTest, CapturesStdout) {
  CaptureStdout();
  fprintf(stdout, "abc");
  EXPECT_STREQ("abc", GetCapturedStdout().c_str());

  CaptureStdout();
  fprintf(stdout, "def%cghi", '\0');
  EXPECT_EQ(::std::string("def\0ghi", 7), ::std::string(GetCapturedStdout()));
}

TEST(CaptureTest, CapturesStderr) {
  CaptureStderr();
  fprintf(stderr, "jkl");
  EXPECT_STREQ("jkl", GetCapturedStderr().c_str());

945
  CaptureStderr();
946
947
  fprintf(stderr, "jkl%cmno", '\0');
  EXPECT_EQ(::std::string("jkl\0mno", 7), ::std::string(GetCapturedStderr()));
948
949
}

950
951
952
953
954
955
956
957
958
959
960
961
// Tests that stdout and stderr capture don't interfere with each other.
TEST(CaptureTest, CapturesStdoutAndStderr) {
  CaptureStdout();
  CaptureStderr();
  fprintf(stdout, "pqr");
  fprintf(stderr, "stu");
  EXPECT_STREQ("pqr", GetCapturedStdout().c_str());
  EXPECT_STREQ("stu", GetCapturedStderr().c_str());
}

TEST(CaptureDeathTest, CannotReenterStdoutCapture) {
  CaptureStdout();
962
  EXPECT_DEATH_IF_SUPPORTED(CaptureStdout(),
963
964
965
966
967
968
969
970
971
                            "Only one stdout capturer can exist at a time");
  GetCapturedStdout();

  // We cannot test stderr capturing using death tests as they use it
  // themselves.
}

#endif  // !GTEST_OS_WINDOWS_MOBILE

972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
TEST(ThreadLocalTest, DefaultConstructorInitializesToDefaultValues) {
  ThreadLocal<int> t1;
  EXPECT_EQ(0, t1.get());

  ThreadLocal<void*> t2;
  EXPECT_TRUE(t2.get() == NULL);
}

TEST(ThreadLocalTest, SingleParamConstructorInitializesToParam) {
  ThreadLocal<int> t1(123);
  EXPECT_EQ(123, t1.get());

  int i = 0;
  ThreadLocal<int*> t2(&i);
  EXPECT_EQ(&i, t2.get());
}

class NoDefaultContructor {
 public:
  explicit NoDefaultContructor(const char*) {}
  NoDefaultContructor(const NoDefaultContructor&) {}
};

TEST(ThreadLocalTest, ValueDefaultContructorIsNotRequiredForParamVersion) {
  ThreadLocal<NoDefaultContructor> bar(NoDefaultContructor("foo"));
  bar.pointer();
}

TEST(ThreadLocalTest, GetAndPointerReturnSameValue) {
1001
  ThreadLocal<std::string> thread_local_string;
1002

1003
  EXPECT_EQ(thread_local_string.pointer(), &(thread_local_string.get()));
1004
1005

  // Verifies the condition still holds after calling set.
1006
1007
  thread_local_string.set("foo");
  EXPECT_EQ(thread_local_string.pointer(), &(thread_local_string.get()));
1008
1009
1010
}

TEST(ThreadLocalTest, PointerAndConstPointerReturnSameValue) {
1011
1012
1013
  ThreadLocal<std::string> thread_local_string;
  const ThreadLocal<std::string>& const_thread_local_string =
      thread_local_string;
1014

1015
  EXPECT_EQ(thread_local_string.pointer(), const_thread_local_string.pointer());
1016

1017
1018
  thread_local_string.set("foo");
  EXPECT_EQ(thread_local_string.pointer(), const_thread_local_string.pointer());
1019
1020
1021
}

#if GTEST_IS_THREADSAFE
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031

void AddTwo(int* param) { *param += 2; }

TEST(ThreadWithParamTest, ConstructorExecutesThreadFunc) {
  int i = 40;
  ThreadWithParam<int*> thread(&AddTwo, &i, NULL);
  thread.Join();
  EXPECT_EQ(42, i);
}

1032
TEST(MutexDeathTest, AssertHeldShouldAssertWhenNotLocked) {
1033
1034
1035
1036
1037
1038
1039
  // AssertHeld() is flaky only in the presence of multiple threads accessing
  // the lock. In this case, the test is robust.
  EXPECT_DEATH_IF_SUPPORTED({
    Mutex m;
    { MutexLock lock(&m); }
    m.AssertHeld();
  },
1040
  "thread .*hold");
1041
1042
}

1043
1044
1045
1046
TEST(MutexTest, AssertHeldShouldNotAssertWhenLocked) {
  Mutex m;
  MutexLock lock(&m);
  m.AssertHeld();
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
}

class AtomicCounterWithMutex {
 public:
  explicit AtomicCounterWithMutex(Mutex* mutex) :
    value_(0), mutex_(mutex), random_(42) {}

  void Increment() {
    MutexLock lock(mutex_);
    int temp = value_;
    {
1058
1059
1060
1061
1062
1063
1064
      // We need to put up a memory barrier to prevent reads and writes to
      // value_ rearranged with the call to SleepMilliseconds when observed
      // from other threads.
#if GTEST_HAS_PTHREAD
      // On POSIX, locking a mutex puts up a memory barrier.  We cannot use
      // Mutex and MutexLock here or rely on their memory barrier
      // functionality as we are testing them here.
1065
      pthread_mutex_t memory_barrier_mutex;
1066
1067
1068
      GTEST_CHECK_POSIX_SUCCESS_(
          pthread_mutex_init(&memory_barrier_mutex, NULL));
      GTEST_CHECK_POSIX_SUCCESS_(pthread_mutex_lock(&memory_barrier_mutex));
1069
1070
1071

      SleepMilliseconds(random_.Generate(30));

1072
      GTEST_CHECK_POSIX_SUCCESS_(pthread_mutex_unlock(&memory_barrier_mutex));
1073
      GTEST_CHECK_POSIX_SUCCESS_(pthread_mutex_destroy(&memory_barrier_mutex));
1074
1075
1076
1077
1078
1079
1080
1081
1082
#elif GTEST_OS_WINDOWS
      // On Windows, performing an interlocked access puts up a memory barrier.
      volatile LONG dummy = 0;
      ::InterlockedIncrement(&dummy);
      SleepMilliseconds(random_.Generate(30));
      ::InterlockedIncrement(&dummy);
#else
# error "Memory barrier not implemented on this platform."
#endif  // GTEST_HAS_PTHREAD
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
    }
    value_ = temp + 1;
  }
  int value() const { return value_; }

 private:
  volatile int value_;
  Mutex* const mutex_;  // Protects value_.
  Random       random_;
};

void CountingThreadFunc(pair<AtomicCounterWithMutex*, int> param) {
  for (int i = 0; i < param.second; ++i)
      param.first->Increment();
}

// Tests that the mutex only lets one thread at a time to lock it.
TEST(MutexTest, OnlyOneThreadCanLockAtATime) {
  Mutex mutex;
  AtomicCounterWithMutex locked_counter(&mutex);

  typedef ThreadWithParam<pair<AtomicCounterWithMutex*, int> > ThreadType;
  const int kCycleCount = 20;
  const int kThreadCount = 7;
  scoped_ptr<ThreadType> counting_threads[kThreadCount];
1108
  Notification threads_can_start;
1109
1110
1111
1112
1113
1114
  // Creates and runs kThreadCount threads that increment locked_counter
  // kCycleCount times each.
  for (int i = 0; i < kThreadCount; ++i) {
    counting_threads[i].reset(new ThreadType(&CountingThreadFunc,
                                             make_pair(&locked_counter,
                                                       kCycleCount),
1115
                                             &threads_can_start));
1116
  }
1117
  threads_can_start.Notify();
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
  for (int i = 0; i < kThreadCount; ++i)
    counting_threads[i]->Join();

  // If the mutex lets more than one thread to increment the counter at a
  // time, they are likely to encounter a race condition and have some
  // increments overwritten, resulting in the lower then expected counter
  // value.
  EXPECT_EQ(kCycleCount * kThreadCount, locked_counter.value());
}

template <typename T>
void RunFromThread(void (func)(T), T param) {
  ThreadWithParam<T> thread(func, param, NULL);
  thread.Join();
}

1134
1135
void RetrieveThreadLocalValue(
    pair<ThreadLocal<std::string>*, std::string*> param) {
1136
1137
1138
1139
  *param.second = param.first->get();
}

TEST(ThreadLocalTest, ParameterizedConstructorSetsDefault) {
1140
  ThreadLocal<std::string> thread_local_string("foo");
1141
  EXPECT_STREQ("foo", thread_local_string.get().c_str());
1142

1143
1144
  thread_local_string.set("bar");
  EXPECT_STREQ("bar", thread_local_string.get().c_str());
1145

1146
  std::string result;
1147
1148
  RunFromThread(&RetrieveThreadLocalValue,
                make_pair(&thread_local_string, &result));
1149
1150
1151
  EXPECT_STREQ("foo", result.c_str());
}

1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
// Keeps track of whether of destructors being called on instances of
// DestructorTracker.  On Windows, waits for the destructor call reports.
class DestructorCall {
 public:
  DestructorCall() {
    invoked_ = false;
#if GTEST_OS_WINDOWS
    wait_event_.Reset(::CreateEvent(NULL, TRUE, FALSE, NULL));
    GTEST_CHECK_(wait_event_.Get() != NULL);
#endif
  }

  bool CheckDestroyed() const {
#if GTEST_OS_WINDOWS
    if (::WaitForSingleObject(wait_event_.Get(), 1000) != WAIT_OBJECT_0)
      return false;
#endif
    return invoked_;
  }

  void ReportDestroyed() {
    invoked_ = true;
#if GTEST_OS_WINDOWS
    ::SetEvent(wait_event_.Get());
#endif
  }

  static std::vector<DestructorCall*>& List() { return *list_; }

  static void ResetList() {
    for (size_t i = 0; i < list_->size(); ++i) {
      delete list_->at(i);
    }
    list_->clear();
  }

 private:
  bool invoked_;
#if GTEST_OS_WINDOWS
  AutoHandle wait_event_;
#endif
  static std::vector<DestructorCall*>* const list_;

  GTEST_DISALLOW_COPY_AND_ASSIGN_(DestructorCall);
};

std::vector<DestructorCall*>* const DestructorCall::list_ =
    new std::vector<DestructorCall*>;

zhanyong.wan's avatar
zhanyong.wan committed
1201
1202
// DestructorTracker keeps track of whether its instances have been
// destroyed.
1203
class DestructorTracker {
1204
 public:
1205
  DestructorTracker() : index_(GetNewIndex()) {}
zhanyong.wan's avatar
zhanyong.wan committed
1206
1207
  DestructorTracker(const DestructorTracker& /* rhs */)
      : index_(GetNewIndex()) {}
1208
  ~DestructorTracker() {
1209
1210
1211
    // We never access DestructorCall::List() concurrently, so we don't need
    // to protect this acccess with a mutex.
    DestructorCall::List()[index_]->ReportDestroyed();
1212
  }
1213
1214

 private:
1215
  static size_t GetNewIndex() {
1216
1217
    DestructorCall::List().push_back(new DestructorCall);
    return DestructorCall::List().size() - 1;
1218
  }
1219
  const size_t index_;
1220
1221

  GTEST_DISALLOW_ASSIGN_(DestructorTracker);
1222
1223
};

zhanyong.wan's avatar
zhanyong.wan committed
1224
1225
typedef ThreadLocal<DestructorTracker>* ThreadParam;

1226
1227
void CallThreadLocalGet(ThreadParam thread_local_param) {
  thread_local_param->get();
zhanyong.wan's avatar
zhanyong.wan committed
1228
1229
1230
1231
1232
}

// Tests that when a ThreadLocal object dies in a thread, it destroys
// the managed object for that thread.
TEST(ThreadLocalTest, DestroysManagedObjectForOwnThreadWhenDying) {
1233
  DestructorCall::ResetList();
zhanyong.wan's avatar
zhanyong.wan committed
1234
1235

  {
1236
    ThreadLocal<DestructorTracker> thread_local_tracker;
1237
    ASSERT_EQ(0U, DestructorCall::List().size());
zhanyong.wan's avatar
zhanyong.wan committed
1238
1239

    // This creates another DestructorTracker object for the main thread.
1240
    thread_local_tracker.get();
1241
    ASSERT_EQ(1U, DestructorCall::List().size());
1242
    ASSERT_FALSE(DestructorCall::List()[0]->CheckDestroyed());
zhanyong.wan's avatar
zhanyong.wan committed
1243
1244
  }

1245
1246
  // Now thread_local_tracker has died.
  ASSERT_EQ(1U, DestructorCall::List().size());
1247
  EXPECT_TRUE(DestructorCall::List()[0]->CheckDestroyed());
zhanyong.wan's avatar
zhanyong.wan committed
1248

1249
  DestructorCall::ResetList();
1250
1251
}

zhanyong.wan's avatar
zhanyong.wan committed
1252
1253
1254
// Tests that when a thread exits, the thread-local object for that
// thread is destroyed.
TEST(ThreadLocalTest, DestroysManagedObjectAtThreadExit) {
1255
  DestructorCall::ResetList();
zhanyong.wan's avatar
zhanyong.wan committed
1256

1257
  {
1258
    ThreadLocal<DestructorTracker> thread_local_tracker;
1259
    ASSERT_EQ(0U, DestructorCall::List().size());
zhanyong.wan's avatar
zhanyong.wan committed
1260
1261
1262

    // This creates another DestructorTracker object in the new thread.
    ThreadWithParam<ThreadParam> thread(
1263
        &CallThreadLocalGet, &thread_local_tracker, NULL);
1264
    thread.Join();
zhanyong.wan's avatar
zhanyong.wan committed
1265

1266
    // The thread has exited, and we should have a DestroyedTracker
1267
    // instance created for it. But it may not have been destroyed yet.
1268
    ASSERT_EQ(1U, DestructorCall::List().size());
1269
  }
zhanyong.wan's avatar
zhanyong.wan committed
1270

1271
1272
  // The thread has exited and thread_local_tracker has died.
  ASSERT_EQ(1U, DestructorCall::List().size());
1273
  EXPECT_TRUE(DestructorCall::List()[0]->CheckDestroyed());
1274

1275
  DestructorCall::ResetList();
1276
1277
1278
}

TEST(ThreadLocalTest, ThreadLocalMutationsAffectOnlyCurrentThread) {
1279
  ThreadLocal<std::string> thread_local_string;
1280
1281
  thread_local_string.set("Foo");
  EXPECT_STREQ("Foo", thread_local_string.get().c_str());
1282

1283
  std::string result;
1284
1285
  RunFromThread(&RetrieveThreadLocalValue,
                make_pair(&thread_local_string, &result));
1286
  EXPECT_TRUE(result.empty());
1287
}
zhanyong.wan's avatar
zhanyong.wan committed
1288

1289
1290
#endif  // GTEST_IS_THREADSAFE

1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
#if GTEST_OS_WINDOWS
TEST(WindowsTypesTest, HANDLEIsVoidStar) {
  StaticAssertTypeEq<HANDLE, void*>();
}

TEST(WindowsTypesTest, CRITICAL_SECTIONIs_RTL_CRITICAL_SECTION) {
  StaticAssertTypeEq<CRITICAL_SECTION, _RTL_CRITICAL_SECTION>();
}
#endif  // GTEST_OS_WINDOWS

1301
1302
}  // namespace internal
}  // namespace testing