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


libaditof
Author(s):
autogenerated on Wed May 21 2025 02:06:52