33 #include "gtest/internal/gtest-port.h"
37 #endif // GTEST_OS_MAC
46 #include "gtest/gtest.h"
47 #include "gtest/gtest-spi.h"
48 #include "src/gtest-internal-inl.h"
56 TEST(IsXDigitTest, WorksForNarrowAscii) {
69 TEST(IsXDigitTest, ReturnsFalseForNarrowNonAscii) {
74 TEST(IsXDigitTest, WorksForWideAscii) {
87 TEST(IsXDigitTest, ReturnsFalseForWideNonAscii) {
97 Base(
const Base&) =
default;
98 Base& operator=(
const Base&) =
default;
106 class Derived :
public Base {
111 TEST(ImplicitCastTest, ConvertsPointers) {
113 EXPECT_TRUE(&derived == ::testing::internal::ImplicitCast_<Base*>(&derived));
116 TEST(ImplicitCastTest, CanUseInheritance) {
118 Base
base = ::testing::internal::ImplicitCast_<Base>(derived);
134 TEST(ImplicitCastTest, CanUseNonConstCastOperator) {
135 bool converted =
false;
136 Castable castable(&converted);
137 Base
base = ::testing::internal::ImplicitCast_<Base>(castable);
141 class ConstCastable {
144 operator Base()
const {
153 TEST(ImplicitCastTest, CanUseConstCastOperatorOnConstValues) {
154 bool converted =
false;
155 const ConstCastable const_castable(&converted);
156 Base
base = ::testing::internal::ImplicitCast_<Base>(const_castable);
160 class ConstAndNonConstCastable {
168 operator Base()
const {
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);
187 const_converted =
false;
188 const ConstAndNonConstCastable const_castable(&converted, &const_converted);
189 base = ::testing::internal::ImplicitCast_<Base>(const_castable);
196 To(
bool* converted) { *converted =
true; }
199 TEST(ImplicitCastTest, CanUseImplicitConstructor) {
200 bool converted =
false;
201 To
to = ::testing::internal::ImplicitCast_<To>(&converted);
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"
213 TEST(GtestCheckSyntaxTest, BehavesLikeASingleStatement) {
215 GTEST_CHECK_(
false) <<
"This should never be executed; "
216 "It's a compilation test only.";
229 #pragma GCC diagnostic pop
232 TEST(GtestCheckSyntaxTest, WorksWithSwitch) {
246 TEST(FormatFileLocationTest, FormatsFileLocation) {
251 TEST(FormatFileLocationTest, FormatsUnknownFile) {
257 TEST(FormatFileLocationTest, FormatsUknownLine) {
261 TEST(FormatFileLocationTest, FormatsUknownFileAndLine) {
266 TEST(FormatCompilerIndependentFileLocationTest, FormatsFileLocation) {
270 TEST(FormatCompilerIndependentFileLocationTest, FormatsUknownFile) {
275 TEST(FormatCompilerIndependentFileLocationTest, FormatsUknownLine) {
279 TEST(FormatCompilerIndependentFileLocationTest, FormatsUknownFileAndLine) {
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) {
293 TEST(GetThreadCountTest, ReturnsCorrectValue) {
294 size_t starting_count;
295 size_t thread_count_after_create;
296 size_t thread_count_after_join;
302 for (
int attempt = 0; attempt < 20; ++attempt) {
311 ASSERT_EQ(0, pthread_attr_setdetachstate(&
attr, PTHREAD_CREATE_JOINABLE));
325 if (thread_count_after_create != starting_count + 1)
continue;
330 bool thread_count_matches =
false;
331 for (
int i = 0;
i < 5; ++
i) {
333 if (thread_count_after_join == starting_count) {
334 thread_count_matches =
true;
338 std::this_thread::sleep_for(std::chrono::milliseconds(100));
342 if (!thread_count_matches)
continue;
347 EXPECT_EQ(thread_count_after_create, starting_count + 1);
348 EXPECT_EQ(thread_count_after_join, starting_count);
351 TEST(GetThreadCountTest, ReturnsZeroWhenUnableToCountThreads) {
354 #endif // GTEST_OS_LINUX || GTEST_OS_MAC || GTEST_OS_QNX || GTEST_OS_FUCHSIA
356 TEST(GtestCheckDeathTest, DiesWithCorrectOutputOnFailure) {
357 const bool a_false_condition =
false;
360 "googletest-port-test\\.cc\\(\\d+\\):"
361 #elif GTEST_USES_POSIX_RE
362 "googletest-port-test\\.cc:[0-9]+"
364 "googletest-port-test\\.cc:\\d+"
366 ".*a_false_condition.*Extra info.*";
372 #if GTEST_HAS_DEATH_TEST
374 TEST(GtestCheckDeathTest, LivesSilentlyOnSuccess) {
377 ::std::cerr <<
"Success\n";
379 ::testing::ExitedWithCode(0),
"Success");
382 #endif // GTEST_HAS_DEATH_TEST
387 TEST(RegexEngineSelectionTest, SelectsCorrectRegexEngine) {
389 # if GTEST_HAS_POSIX_RE
398 #endif // !GTEST_USES_PCRE
401 #if GTEST_USES_POSIX_RE
403 template <
typename Str>
413 TYPED_TEST(RETest, ImplicitConstructorWorks) {
414 const RE
empty(TypeParam(
""));
417 const RE simple(TypeParam(
"hello"));
420 const RE normal(TypeParam(
".*(\\w+)"));
427 const RE
invalid(TypeParam(
"?"));
428 },
"\"?\" is not a valid POSIX Extended regular expression.");
433 const RE
empty(TypeParam(
""));
437 const RE re(TypeParam(
"a.*z"));
446 const RE
empty(TypeParam(
""));
450 const RE re(TypeParam(
"a.*z"));
458 #elif GTEST_USES_SIMPLE_RE
460 TEST(IsInSetTest, NulCharIsNotInAnySet) {
466 TEST(IsInSetTest, WorksForNonNulChars) {
474 TEST(IsAsciiDigitTest, IsFalseForNonDigit) {
483 TEST(IsAsciiDigitTest, IsTrueForDigit) {
490 TEST(IsAsciiPunctTest, IsFalseForNonPunct) {
498 TEST(IsAsciiPunctTest, IsTrueForPunct) {
499 for (
const char* p =
"^-!\"#$%&'()*+,./:;<=>?@[\\]_`{|}~"; *
p;
p++) {
504 TEST(IsRepeatTest, IsFalseForNonRepeatChar) {
512 TEST(IsRepeatTest, IsTrueForRepeatChar) {
518 TEST(IsAsciiWhiteSpaceTest, IsFalseForNonWhiteSpace) {
526 TEST(IsAsciiWhiteSpaceTest, IsTrueForWhiteSpace) {
535 TEST(IsAsciiWordCharTest, IsFalseForNonWordChar) {
543 TEST(IsAsciiWordCharTest, IsTrueForLetter) {
550 TEST(IsAsciiWordCharTest, IsTrueForDigit) {
557 TEST(IsAsciiWordCharTest, IsTrueForUnderscore) {
561 TEST(IsValidEscapeTest, IsFalseForNonPrintable) {
566 TEST(IsValidEscapeTest, IsFalseForDigit) {
571 TEST(IsValidEscapeTest, IsFalseForWhiteSpace) {
576 TEST(IsValidEscapeTest, IsFalseForSomeLetter) {
581 TEST(IsValidEscapeTest, IsTrueForPunct) {
592 TEST(IsValidEscapeTest, IsTrueForSomeLetter) {
601 TEST(AtomMatchesCharTest, EscapedPunct) {
613 TEST(AtomMatchesCharTest, Escaped_d) {
622 TEST(AtomMatchesCharTest, Escaped_D) {
631 TEST(AtomMatchesCharTest, Escaped_s) {
642 TEST(AtomMatchesCharTest, Escaped_S) {
651 TEST(AtomMatchesCharTest, Escaped_w) {
663 TEST(AtomMatchesCharTest, Escaped_W) {
674 TEST(AtomMatchesCharTest, EscapedWhiteSpace) {
693 TEST(AtomMatchesCharTest, UnescapedDot) {
702 TEST(AtomMatchesCharTest, UnescapedChar) {
712 TEST(ValidateRegexTest, GeneratesFailureAndReturnsFalseForInvalid) {
714 "NULL is not a valid simple regular expression");
717 "Syntax error at index 1 in simple regular expression \"a\\\": ");
719 "'\\' cannot appear at the end");
721 "'\\' cannot appear at the end");
723 "invalid escape sequence \"\\h\"");
725 "'^' can only appear at the beginning");
727 "'^' can only appear at the beginning");
729 "'$' can only appear at the end");
731 "'$' can only appear at the end");
733 "'(' is unsupported");
735 "')' is unsupported");
737 "'[' is unsupported");
739 "'{' is unsupported");
741 "'?' can only follow a repeatable token");
743 "'*' can only follow a repeatable token");
745 "'+' can only follow a repeatable token");
748 TEST(ValidateRegexTest, ReturnsTrueForValid) {
756 EXPECT_TRUE(ValidateRegex(
"a\\^Z\\$\\(\\)\\|\\[\\]\\{\\}"));
759 TEST(MatchRepetitionAndRegexAtHeadTest, WorksForZeroOrOne) {
760 EXPECT_FALSE(MatchRepetitionAndRegexAtHead(
false,
'a',
'?',
"a",
"ba"));
762 EXPECT_FALSE(MatchRepetitionAndRegexAtHead(
false,
'a',
'?',
"b",
"aab"));
765 EXPECT_TRUE(MatchRepetitionAndRegexAtHead(
false,
'a',
'?',
"b",
"ba"));
767 EXPECT_TRUE(MatchRepetitionAndRegexAtHead(
false,
'a',
'?',
"b",
"ab"));
768 EXPECT_TRUE(MatchRepetitionAndRegexAtHead(
false,
'#',
'?',
".",
"##"));
771 TEST(MatchRepetitionAndRegexAtHeadTest, WorksForZeroOrMany) {
772 EXPECT_FALSE(MatchRepetitionAndRegexAtHead(
false,
'.',
'*',
"a$",
"baab"));
775 EXPECT_TRUE(MatchRepetitionAndRegexAtHead(
false,
'.',
'*',
"b",
"bc"));
777 EXPECT_TRUE(MatchRepetitionAndRegexAtHead(
false,
'.',
'*',
"b",
"abc"));
779 EXPECT_TRUE(MatchRepetitionAndRegexAtHead(
true,
'w',
'*',
"-",
"ab_1-g"));
782 TEST(MatchRepetitionAndRegexAtHeadTest, WorksForOneOrMany) {
783 EXPECT_FALSE(MatchRepetitionAndRegexAtHead(
false,
'.',
'+',
"a$",
"baab"));
785 EXPECT_FALSE(MatchRepetitionAndRegexAtHead(
false,
'.',
'+',
"b",
"bc"));
788 EXPECT_TRUE(MatchRepetitionAndRegexAtHead(
false,
'.',
'+',
"b",
"abc"));
790 EXPECT_TRUE(MatchRepetitionAndRegexAtHead(
true,
'w',
'+',
"-",
"ab_1-g"));
793 TEST(MatchRegexAtHeadTest, ReturnsTrueForEmptyRegex) {
798 TEST(MatchRegexAtHeadTest, WorksWhenDollarIsInRegex) {
805 TEST(MatchRegexAtHeadTest, WorksWhenRegexStartsWithEscapeSequence) {
813 TEST(MatchRegexAtHeadTest, WorksWhenRegexStartsWithRepetition) {
822 TEST(MatchRegexAtHeadTest,
823 WorksWhenRegexStartsWithRepetionOfEscapeSequence) {
833 TEST(MatchRegexAtHeadTest, MatchesSequentially) {
839 TEST(MatchRegexAnywhereTest, ReturnsFalseWhenStringIsNull) {
843 TEST(MatchRegexAnywhereTest, WorksWhenRegexStartsWithCaret) {
852 TEST(MatchRegexAnywhereTest, ReturnsFalseWhenNoMatch) {
854 EXPECT_FALSE(MatchRegexAnywhere(
"a.+a",
"--aa88888888"));
857 TEST(MatchRegexAnywhereTest, ReturnsTrueWhenMatchingPrefix) {
858 EXPECT_TRUE(MatchRegexAnywhere(
"\\w+",
"ab1_ - 5"));
860 EXPECT_TRUE(MatchRegexAnywhere(
"x.*ab?.*bc",
"xaaabc"));
863 TEST(MatchRegexAnywhereTest, ReturnsTrueWhenMatchingNonPrefix) {
864 EXPECT_TRUE(MatchRegexAnywhere(
"\\w+",
"$$$ ab1_ - 5"));
865 EXPECT_TRUE(MatchRegexAnywhere(
"\\.+=",
"= ...="));
869 TEST(RETest, ImplicitConstructorWorks) {
873 const RE simple(
"hello");
878 TEST(RETest, RejectsInvalidRegex) {
880 const RE normal(NULL);
881 },
"NULL is not a valid simple regular expression");
884 const RE normal(
".*(\\w+");
885 },
"'(' is unsupported");
889 },
"'?' can only follow a repeatable token");
893 TEST(RETest, FullMatchWorks) {
909 TEST(RETest, PartialMatchWorks) {
922 #endif // GTEST_USES_POSIX_RE
924 #if !GTEST_OS_WINDOWS_MOBILE
926 TEST(CaptureTest, CapturesStdout) {
932 fprintf(
stdout,
"def%cghi",
'\0');
936 TEST(CaptureTest, CapturesStderr) {
942 fprintf(
stderr,
"jkl%cmno",
'\0');
947 TEST(CaptureTest, CapturesStdoutAndStderr) {
956 TEST(CaptureDeathTest, CannotReenterStdoutCapture) {
959 "Only one stdout capturer can exist at a time");
966 #endif // !GTEST_OS_WINDOWS_MOBILE
968 TEST(ThreadLocalTest, DefaultConstructorInitializesToDefaultValues) {
972 ThreadLocal<void*> t2;
976 TEST(ThreadLocalTest, SingleParamConstructorInitializesToParam) {
977 ThreadLocal<int>
t1(123);
981 ThreadLocal<int*> t2(&i);
985 class NoDefaultContructor {
991 TEST(ThreadLocalTest, ValueDefaultContructorIsNotRequiredForParamVersion) {
992 ThreadLocal<NoDefaultContructor>
bar(NoDefaultContructor(
"foo"));
996 TEST(ThreadLocalTest, GetAndPointerReturnSameValue) {
997 ThreadLocal<std::string> thread_local_string;
999 EXPECT_EQ(thread_local_string.pointer(), &(thread_local_string.get()));
1002 thread_local_string.set(
"foo");
1003 EXPECT_EQ(thread_local_string.pointer(), &(thread_local_string.get()));
1006 TEST(ThreadLocalTest, PointerAndConstPointerReturnSameValue) {
1007 ThreadLocal<std::string> thread_local_string;
1008 const ThreadLocal<std::string>& const_thread_local_string =
1009 thread_local_string;
1011 EXPECT_EQ(thread_local_string.pointer(), const_thread_local_string.pointer());
1013 thread_local_string.set(
"foo");
1014 EXPECT_EQ(thread_local_string.pointer(), const_thread_local_string.pointer());
1017 #if GTEST_IS_THREADSAFE
1019 void AddTwo(
int* param) { *param += 2; }
1021 TEST(ThreadWithParamTest, ConstructorExecutesThreadFunc) {
1023 ThreadWithParam<int*>
thread(&AddTwo, &i,
nullptr);
1028 TEST(MutexDeathTest, AssertHeldShouldAssertWhenNotLocked) {
1039 TEST(MutexTest, AssertHeldShouldNotAssertWhenLocked) {
1045 class AtomicCounterWithMutex {
1047 explicit AtomicCounterWithMutex(
Mutex*
mutex) :
1057 #if GTEST_HAS_PTHREAD
1061 pthread_mutex_t memory_barrier_mutex;
1063 pthread_mutex_init(&memory_barrier_mutex,
nullptr));
1066 std::this_thread::sleep_for(
1067 std::chrono::milliseconds(random_.Generate(30)));
1071 #elif GTEST_OS_WINDOWS
1074 ::InterlockedIncrement(&
dummy);
1075 std::this_thread::sleep_for(
1076 std::chrono::milliseconds(random_.Generate(30)));
1077 ::InterlockedIncrement(&
dummy);
1079 # error "Memory barrier not implemented on this platform."
1080 #endif // GTEST_HAS_PTHREAD
1092 void CountingThreadFunc(pair<AtomicCounterWithMutex*, int> param) {
1093 for (
int i = 0;
i < param.second; ++
i)
1094 param.first->Increment();
1098 TEST(MutexTest, OnlyOneThreadCanLockAtATime) {
1100 AtomicCounterWithMutex locked_counter(&
mutex);
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;
1109 for (
int i = 0;
i < kThreadCount; ++
i) {
1110 counting_threads[
i].reset(
new ThreadType(&CountingThreadFunc,
1111 make_pair(&locked_counter,
1113 &threads_can_start));
1115 threads_can_start.Notify();
1116 for (
int i = 0;
i < kThreadCount; ++
i)
1117 counting_threads[i]->
Join();
1123 EXPECT_EQ(kCycleCount * kThreadCount, locked_counter.value());
1126 template <
typename T>
1127 void RunFromThread(
void (
func)(
T),
T param) {
1128 ThreadWithParam<T>
thread(
func, param,
nullptr);
1132 void RetrieveThreadLocalValue(
1134 *param.second = param.first->get();
1137 TEST(ThreadLocalTest, ParameterizedConstructorSetsDefault) {
1138 ThreadLocal<std::string> thread_local_string(
"foo");
1139 EXPECT_STREQ(
"foo", thread_local_string.get().c_str());
1141 thread_local_string.set(
"bar");
1142 EXPECT_STREQ(
"bar", thread_local_string.get().c_str());
1145 RunFromThread(&RetrieveThreadLocalValue,
1146 make_pair(&thread_local_string, &
result));
1152 class DestructorCall {
1156 #if GTEST_OS_WINDOWS
1157 wait_event_.Reset(::CreateEvent(NULL, TRUE, FALSE, NULL));
1162 bool CheckDestroyed()
const {
1163 #if GTEST_OS_WINDOWS
1164 if (::WaitForSingleObject(wait_event_.Get(), 1000) != WAIT_OBJECT_0)
1170 void ReportDestroyed() {
1172 #if GTEST_OS_WINDOWS
1173 ::SetEvent(wait_event_.Get());
1177 static std::vector<DestructorCall*>& List() {
return *list_; }
1179 static void ResetList() {
1180 for (
size_t i = 0;
i < list_->size(); ++
i) {
1181 delete list_->at(i);
1188 #if GTEST_OS_WINDOWS
1189 AutoHandle wait_event_;
1191 static std::vector<DestructorCall*>*
const list_;
1196 std::vector<DestructorCall*>*
const DestructorCall::list_ =
1197 new std::vector<DestructorCall*>;
1201 class DestructorTracker {
1203 DestructorTracker() :
index_(GetNewIndex()) {}
1204 DestructorTracker(
const DestructorTracker& )
1205 :
index_(GetNewIndex()) {}
1206 ~DestructorTracker() {
1209 DestructorCall::List()[
index_]->ReportDestroyed();
1213 static size_t GetNewIndex() {
1214 DestructorCall::List().push_back(
new DestructorCall);
1215 return DestructorCall::List().size() - 1;
1220 typedef ThreadLocal<DestructorTracker>* ThreadParam;
1222 void CallThreadLocalGet(ThreadParam thread_local_param) {
1223 thread_local_param->get();
1228 TEST(ThreadLocalTest, DestroysManagedObjectForOwnThreadWhenDying) {
1229 DestructorCall::ResetList();
1232 ThreadLocal<DestructorTracker> thread_local_tracker;
1236 thread_local_tracker.get();
1238 ASSERT_FALSE(DestructorCall::List()[0]->CheckDestroyed());
1243 EXPECT_TRUE(DestructorCall::List()[0]->CheckDestroyed());
1245 DestructorCall::ResetList();
1250 TEST(ThreadLocalTest, DestroysManagedObjectAtThreadExit) {
1251 DestructorCall::ResetList();
1254 ThreadLocal<DestructorTracker> thread_local_tracker;
1258 ThreadWithParam<ThreadParam>
thread(&CallThreadLocalGet,
1259 &thread_local_tracker,
nullptr);
1269 EXPECT_TRUE(DestructorCall::List()[0]->CheckDestroyed());
1271 DestructorCall::ResetList();
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());
1280 RunFromThread(&RetrieveThreadLocalValue,
1281 make_pair(&thread_local_string, &
result));
1285 #endif // GTEST_IS_THREADSAFE
1287 #if GTEST_OS_WINDOWS
1288 TEST(WindowsTypesTest, HANDLEIsVoidStar) {
1289 StaticAssertTypeEq<HANDLE, void*>();
1292 #if GTEST_OS_WINDOWS_MINGW && !defined(__MINGW64_VERSION_MAJOR)
1293 TEST(WindowsTypesTest, _CRITICAL_SECTIONIs_CRITICAL_SECTION) {
1294 StaticAssertTypeEq<CRITICAL_SECTION, _CRITICAL_SECTION>();
1297 TEST(WindowsTypesTest, CRITICAL_SECTIONIs_RTL_CRITICAL_SECTION) {
1298 StaticAssertTypeEq<CRITICAL_SECTION, _RTL_CRITICAL_SECTION>();
1302 #endif // GTEST_OS_WINDOWS