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


grpc
Author(s):
autogenerated on Fri May 16 2025 02:58:42