/src/3rdparty/webkit/Source/ThirdParty/gtest/test/gtest_unittest.cc

https://bitbucket.org/ultra_iter/qt-vtl · C++ · 6718 lines · 4544 code · 1109 blank · 1065 comment · 137 complexity · 2a2fb6867b2f677bf95a2910c435ca59 MD5 · raw file

Large files are truncated click here to view the full file

  1. // Copyright 2005, 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. // Author: wan@google.com (Zhanyong Wan)
  31. //
  32. // Tests for Google Test itself. This verifies that the basic constructs of
  33. // Google Test work.
  34. #include <gtest/gtest.h>
  35. #include <vector>
  36. // Verifies that the command line flag variables can be accessed
  37. // in code once <gtest/gtest.h> has been #included.
  38. // Do not move it after other #includes.
  39. TEST(CommandLineFlagsTest, CanBeAccessedInCodeOnceGTestHIsIncluded) {
  40. bool dummy = testing::GTEST_FLAG(also_run_disabled_tests)
  41. || testing::GTEST_FLAG(break_on_failure)
  42. || testing::GTEST_FLAG(catch_exceptions)
  43. || testing::GTEST_FLAG(color) != "unknown"
  44. || testing::GTEST_FLAG(filter) != "unknown"
  45. || testing::GTEST_FLAG(list_tests)
  46. || testing::GTEST_FLAG(output) != "unknown"
  47. || testing::GTEST_FLAG(print_time)
  48. || testing::GTEST_FLAG(random_seed)
  49. || testing::GTEST_FLAG(repeat) > 0
  50. || testing::GTEST_FLAG(show_internal_stack_frames)
  51. || testing::GTEST_FLAG(shuffle)
  52. || testing::GTEST_FLAG(stack_trace_depth) > 0
  53. || testing::GTEST_FLAG(throw_on_failure);
  54. EXPECT_TRUE(dummy || !dummy); // Suppresses warning that dummy is unused.
  55. }
  56. #include <gtest/gtest-spi.h>
  57. // Indicates that this translation unit is part of Google Test's
  58. // implementation. It must come before gtest-internal-inl.h is
  59. // included, or there will be a compiler error. This trick is to
  60. // prevent a user from accidentally including gtest-internal-inl.h in
  61. // his code.
  62. #define GTEST_IMPLEMENTATION_ 1
  63. #include "src/gtest-internal-inl.h"
  64. #undef GTEST_IMPLEMENTATION_
  65. #include <limits.h> // For INT_MAX.
  66. #include <stdlib.h>
  67. #include <time.h>
  68. #include <map>
  69. namespace testing {
  70. namespace internal {
  71. // Provides access to otherwise private parts of the TestEventListeners class
  72. // that are needed to test it.
  73. class TestEventListenersAccessor {
  74. public:
  75. static TestEventListener* GetRepeater(TestEventListeners* listeners) {
  76. return listeners->repeater();
  77. }
  78. static void SetDefaultResultPrinter(TestEventListeners* listeners,
  79. TestEventListener* listener) {
  80. listeners->SetDefaultResultPrinter(listener);
  81. }
  82. static void SetDefaultXmlGenerator(TestEventListeners* listeners,
  83. TestEventListener* listener) {
  84. listeners->SetDefaultXmlGenerator(listener);
  85. }
  86. static bool EventForwardingEnabled(const TestEventListeners& listeners) {
  87. return listeners.EventForwardingEnabled();
  88. }
  89. static void SuppressEventForwarding(TestEventListeners* listeners) {
  90. listeners->SuppressEventForwarding();
  91. }
  92. };
  93. } // namespace internal
  94. } // namespace testing
  95. using testing::AssertionFailure;
  96. using testing::AssertionResult;
  97. using testing::AssertionSuccess;
  98. using testing::DoubleLE;
  99. using testing::EmptyTestEventListener;
  100. using testing::FloatLE;
  101. using testing::GTEST_FLAG(also_run_disabled_tests);
  102. using testing::GTEST_FLAG(break_on_failure);
  103. using testing::GTEST_FLAG(catch_exceptions);
  104. using testing::GTEST_FLAG(color);
  105. using testing::GTEST_FLAG(death_test_use_fork);
  106. using testing::GTEST_FLAG(filter);
  107. using testing::GTEST_FLAG(list_tests);
  108. using testing::GTEST_FLAG(output);
  109. using testing::GTEST_FLAG(print_time);
  110. using testing::GTEST_FLAG(random_seed);
  111. using testing::GTEST_FLAG(repeat);
  112. using testing::GTEST_FLAG(show_internal_stack_frames);
  113. using testing::GTEST_FLAG(shuffle);
  114. using testing::GTEST_FLAG(stack_trace_depth);
  115. using testing::GTEST_FLAG(throw_on_failure);
  116. using testing::IsNotSubstring;
  117. using testing::IsSubstring;
  118. using testing::Message;
  119. using testing::ScopedFakeTestPartResultReporter;
  120. using testing::StaticAssertTypeEq;
  121. using testing::Test;
  122. using testing::TestEventListeners;
  123. using testing::TestCase;
  124. using testing::TestPartResult;
  125. using testing::TestPartResultArray;
  126. using testing::TestProperty;
  127. using testing::TestResult;
  128. using testing::UnitTest;
  129. using testing::kMaxStackTraceDepth;
  130. using testing::internal::AlwaysFalse;
  131. using testing::internal::AlwaysTrue;
  132. using testing::internal::AppendUserMessage;
  133. using testing::internal::CodePointToUtf8;
  134. using testing::internal::CountIf;
  135. using testing::internal::EqFailure;
  136. using testing::internal::FloatingPoint;
  137. using testing::internal::FormatTimeInMillisAsSeconds;
  138. using testing::internal::ForEach;
  139. using testing::internal::GTestFlagSaver;
  140. using testing::internal::GetCurrentOsStackTraceExceptTop;
  141. using testing::internal::GetElementOr;
  142. using testing::internal::GetNextRandomSeed;
  143. using testing::internal::GetRandomSeedFromFlag;
  144. using testing::internal::GetTestTypeId;
  145. using testing::internal::GetTypeId;
  146. using testing::internal::GetUnitTestImpl;
  147. using testing::internal::Int32;
  148. using testing::internal::Int32FromEnvOrDie;
  149. using testing::internal::ParseInt32Flag;
  150. using testing::internal::ShouldRunTestOnShard;
  151. using testing::internal::ShouldShard;
  152. using testing::internal::ShouldUseColor;
  153. using testing::internal::Shuffle;
  154. using testing::internal::ShuffleRange;
  155. using testing::internal::StreamableToString;
  156. using testing::internal::String;
  157. using testing::internal::TestEventListenersAccessor;
  158. using testing::internal::TestResultAccessor;
  159. using testing::internal::UInt32;
  160. using testing::internal::WideStringToUtf8;
  161. using testing::internal::kMaxRandomSeed;
  162. using testing::internal::kTestTypeIdInGoogleTest;
  163. using testing::internal::scoped_ptr;
  164. #if GTEST_HAS_STREAM_REDIRECTION_
  165. using testing::internal::CaptureStdout;
  166. using testing::internal::GetCapturedStdout;
  167. #endif // GTEST_HAS_STREAM_REDIRECTION_
  168. #if GTEST_IS_THREADSAFE
  169. using testing::internal::ThreadWithParam;
  170. #endif
  171. class TestingVector : public std::vector<int> {
  172. };
  173. ::std::ostream& operator<<(::std::ostream& os,
  174. const TestingVector& vector) {
  175. os << "{ ";
  176. for (size_t i = 0; i < vector.size(); i++) {
  177. os << vector[i] << " ";
  178. }
  179. os << "}";
  180. return os;
  181. }
  182. // This line tests that we can define tests in an unnamed namespace.
  183. namespace {
  184. TEST(GetRandomSeedFromFlagTest, HandlesZero) {
  185. const int seed = GetRandomSeedFromFlag(0);
  186. EXPECT_LE(1, seed);
  187. EXPECT_LE(seed, static_cast<int>(kMaxRandomSeed));
  188. }
  189. TEST(GetRandomSeedFromFlagTest, PreservesValidSeed) {
  190. EXPECT_EQ(1, GetRandomSeedFromFlag(1));
  191. EXPECT_EQ(2, GetRandomSeedFromFlag(2));
  192. EXPECT_EQ(kMaxRandomSeed - 1, GetRandomSeedFromFlag(kMaxRandomSeed - 1));
  193. EXPECT_EQ(static_cast<int>(kMaxRandomSeed),
  194. GetRandomSeedFromFlag(kMaxRandomSeed));
  195. }
  196. TEST(GetRandomSeedFromFlagTest, NormalizesInvalidSeed) {
  197. const int seed1 = GetRandomSeedFromFlag(-1);
  198. EXPECT_LE(1, seed1);
  199. EXPECT_LE(seed1, static_cast<int>(kMaxRandomSeed));
  200. const int seed2 = GetRandomSeedFromFlag(kMaxRandomSeed + 1);
  201. EXPECT_LE(1, seed2);
  202. EXPECT_LE(seed2, static_cast<int>(kMaxRandomSeed));
  203. }
  204. TEST(GetNextRandomSeedTest, WorksForValidInput) {
  205. EXPECT_EQ(2, GetNextRandomSeed(1));
  206. EXPECT_EQ(3, GetNextRandomSeed(2));
  207. EXPECT_EQ(static_cast<int>(kMaxRandomSeed),
  208. GetNextRandomSeed(kMaxRandomSeed - 1));
  209. EXPECT_EQ(1, GetNextRandomSeed(kMaxRandomSeed));
  210. // We deliberately don't test GetNextRandomSeed() with invalid
  211. // inputs, as that requires death tests, which are expensive. This
  212. // is fine as GetNextRandomSeed() is internal and has a
  213. // straightforward definition.
  214. }
  215. static void ClearCurrentTestPartResults() {
  216. TestResultAccessor::ClearTestPartResults(
  217. GetUnitTestImpl()->current_test_result());
  218. }
  219. // Tests GetTypeId.
  220. TEST(GetTypeIdTest, ReturnsSameValueForSameType) {
  221. EXPECT_EQ(GetTypeId<int>(), GetTypeId<int>());
  222. EXPECT_EQ(GetTypeId<Test>(), GetTypeId<Test>());
  223. }
  224. class SubClassOfTest : public Test {};
  225. class AnotherSubClassOfTest : public Test {};
  226. TEST(GetTypeIdTest, ReturnsDifferentValuesForDifferentTypes) {
  227. EXPECT_NE(GetTypeId<int>(), GetTypeId<const int>());
  228. EXPECT_NE(GetTypeId<int>(), GetTypeId<char>());
  229. EXPECT_NE(GetTypeId<int>(), GetTestTypeId());
  230. EXPECT_NE(GetTypeId<SubClassOfTest>(), GetTestTypeId());
  231. EXPECT_NE(GetTypeId<AnotherSubClassOfTest>(), GetTestTypeId());
  232. EXPECT_NE(GetTypeId<AnotherSubClassOfTest>(), GetTypeId<SubClassOfTest>());
  233. }
  234. // Verifies that GetTestTypeId() returns the same value, no matter it
  235. // is called from inside Google Test or outside of it.
  236. TEST(GetTestTypeIdTest, ReturnsTheSameValueInsideOrOutsideOfGoogleTest) {
  237. EXPECT_EQ(kTestTypeIdInGoogleTest, GetTestTypeId());
  238. }
  239. // Tests FormatTimeInMillisAsSeconds().
  240. TEST(FormatTimeInMillisAsSecondsTest, FormatsZero) {
  241. EXPECT_EQ("0", FormatTimeInMillisAsSeconds(0));
  242. }
  243. TEST(FormatTimeInMillisAsSecondsTest, FormatsPositiveNumber) {
  244. EXPECT_EQ("0.003", FormatTimeInMillisAsSeconds(3));
  245. EXPECT_EQ("0.01", FormatTimeInMillisAsSeconds(10));
  246. EXPECT_EQ("0.2", FormatTimeInMillisAsSeconds(200));
  247. EXPECT_EQ("1.2", FormatTimeInMillisAsSeconds(1200));
  248. EXPECT_EQ("3", FormatTimeInMillisAsSeconds(3000));
  249. }
  250. TEST(FormatTimeInMillisAsSecondsTest, FormatsNegativeNumber) {
  251. EXPECT_EQ("-0.003", FormatTimeInMillisAsSeconds(-3));
  252. EXPECT_EQ("-0.01", FormatTimeInMillisAsSeconds(-10));
  253. EXPECT_EQ("-0.2", FormatTimeInMillisAsSeconds(-200));
  254. EXPECT_EQ("-1.2", FormatTimeInMillisAsSeconds(-1200));
  255. EXPECT_EQ("-3", FormatTimeInMillisAsSeconds(-3000));
  256. }
  257. #if GTEST_CAN_COMPARE_NULL
  258. #ifdef __BORLANDC__
  259. // Silences warnings: "Condition is always true", "Unreachable code"
  260. #pragma option push -w-ccc -w-rch
  261. #endif
  262. // Tests that GTEST_IS_NULL_LITERAL_(x) is true when x is a null
  263. // pointer literal.
  264. TEST(NullLiteralTest, IsTrueForNullLiterals) {
  265. EXPECT_TRUE(GTEST_IS_NULL_LITERAL_(NULL));
  266. EXPECT_TRUE(GTEST_IS_NULL_LITERAL_(0));
  267. EXPECT_TRUE(GTEST_IS_NULL_LITERAL_(0U));
  268. EXPECT_TRUE(GTEST_IS_NULL_LITERAL_(0L));
  269. EXPECT_TRUE(GTEST_IS_NULL_LITERAL_(false));
  270. #ifndef __BORLANDC__
  271. // Some compilers may fail to detect some null pointer literals;
  272. // as long as users of the framework don't use such literals, this
  273. // is harmless.
  274. EXPECT_TRUE(GTEST_IS_NULL_LITERAL_(1 - 1));
  275. EXPECT_TRUE(GTEST_IS_NULL_LITERAL_(true && false));
  276. #endif
  277. }
  278. // Tests that GTEST_IS_NULL_LITERAL_(x) is false when x is not a null
  279. // pointer literal.
  280. TEST(NullLiteralTest, IsFalseForNonNullLiterals) {
  281. EXPECT_FALSE(GTEST_IS_NULL_LITERAL_(1));
  282. EXPECT_FALSE(GTEST_IS_NULL_LITERAL_(0.0));
  283. EXPECT_FALSE(GTEST_IS_NULL_LITERAL_('a'));
  284. EXPECT_FALSE(GTEST_IS_NULL_LITERAL_(static_cast<void*>(NULL)));
  285. }
  286. #ifdef __BORLANDC__
  287. // Restores warnings after previous "#pragma option push" suppressed them.
  288. #pragma option pop
  289. #endif
  290. #endif // GTEST_CAN_COMPARE_NULL
  291. //
  292. // Tests CodePointToUtf8().
  293. // Tests that the NUL character L'\0' is encoded correctly.
  294. TEST(CodePointToUtf8Test, CanEncodeNul) {
  295. char buffer[32];
  296. EXPECT_STREQ("", CodePointToUtf8(L'\0', buffer));
  297. }
  298. // Tests that ASCII characters are encoded correctly.
  299. TEST(CodePointToUtf8Test, CanEncodeAscii) {
  300. char buffer[32];
  301. EXPECT_STREQ("a", CodePointToUtf8(L'a', buffer));
  302. EXPECT_STREQ("Z", CodePointToUtf8(L'Z', buffer));
  303. EXPECT_STREQ("&", CodePointToUtf8(L'&', buffer));
  304. EXPECT_STREQ("\x7F", CodePointToUtf8(L'\x7F', buffer));
  305. }
  306. // Tests that Unicode code-points that have 8 to 11 bits are encoded
  307. // as 110xxxxx 10xxxxxx.
  308. TEST(CodePointToUtf8Test, CanEncode8To11Bits) {
  309. char buffer[32];
  310. // 000 1101 0011 => 110-00011 10-010011
  311. EXPECT_STREQ("\xC3\x93", CodePointToUtf8(L'\xD3', buffer));
  312. // 101 0111 0110 => 110-10101 10-110110
  313. EXPECT_STREQ("\xD5\xB6", CodePointToUtf8(L'\x576', buffer));
  314. }
  315. // Tests that Unicode code-points that have 12 to 16 bits are encoded
  316. // as 1110xxxx 10xxxxxx 10xxxxxx.
  317. TEST(CodePointToUtf8Test, CanEncode12To16Bits) {
  318. char buffer[32];
  319. // 0000 1000 1101 0011 => 1110-0000 10-100011 10-010011
  320. EXPECT_STREQ("\xE0\xA3\x93", CodePointToUtf8(L'\x8D3', buffer));
  321. // 1100 0111 0100 1101 => 1110-1100 10-011101 10-001101
  322. EXPECT_STREQ("\xEC\x9D\x8D", CodePointToUtf8(L'\xC74D', buffer));
  323. }
  324. #if !GTEST_WIDE_STRING_USES_UTF16_
  325. // Tests in this group require a wchar_t to hold > 16 bits, and thus
  326. // are skipped on Windows, Cygwin, and Symbian, where a wchar_t is
  327. // 16-bit wide. This code may not compile on those systems.
  328. // Tests that Unicode code-points that have 17 to 21 bits are encoded
  329. // as 11110xxx 10xxxxxx 10xxxxxx 10xxxxxx.
  330. TEST(CodePointToUtf8Test, CanEncode17To21Bits) {
  331. char buffer[32];
  332. // 0 0001 0000 1000 1101 0011 => 11110-000 10-010000 10-100011 10-010011
  333. EXPECT_STREQ("\xF0\x90\xA3\x93", CodePointToUtf8(L'\x108D3', buffer));
  334. // 0 0001 0000 0100 0000 0000 => 11110-000 10-010000 10-010000 10-000000
  335. EXPECT_STREQ("\xF0\x90\x90\x80", CodePointToUtf8(L'\x10400', buffer));
  336. // 1 0000 1000 0110 0011 0100 => 11110-100 10-001000 10-011000 10-110100
  337. EXPECT_STREQ("\xF4\x88\x98\xB4", CodePointToUtf8(L'\x108634', buffer));
  338. }
  339. // Tests that encoding an invalid code-point generates the expected result.
  340. TEST(CodePointToUtf8Test, CanEncodeInvalidCodePoint) {
  341. char buffer[32];
  342. EXPECT_STREQ("(Invalid Unicode 0x1234ABCD)",
  343. CodePointToUtf8(L'\x1234ABCD', buffer));
  344. }
  345. #endif // !GTEST_WIDE_STRING_USES_UTF16_
  346. // Tests WideStringToUtf8().
  347. // Tests that the NUL character L'\0' is encoded correctly.
  348. TEST(WideStringToUtf8Test, CanEncodeNul) {
  349. EXPECT_STREQ("", WideStringToUtf8(L"", 0).c_str());
  350. EXPECT_STREQ("", WideStringToUtf8(L"", -1).c_str());
  351. }
  352. // Tests that ASCII strings are encoded correctly.
  353. TEST(WideStringToUtf8Test, CanEncodeAscii) {
  354. EXPECT_STREQ("a", WideStringToUtf8(L"a", 1).c_str());
  355. EXPECT_STREQ("ab", WideStringToUtf8(L"ab", 2).c_str());
  356. EXPECT_STREQ("a", WideStringToUtf8(L"a", -1).c_str());
  357. EXPECT_STREQ("ab", WideStringToUtf8(L"ab", -1).c_str());
  358. }
  359. // Tests that Unicode code-points that have 8 to 11 bits are encoded
  360. // as 110xxxxx 10xxxxxx.
  361. TEST(WideStringToUtf8Test, CanEncode8To11Bits) {
  362. // 000 1101 0011 => 110-00011 10-010011
  363. EXPECT_STREQ("\xC3\x93", WideStringToUtf8(L"\xD3", 1).c_str());
  364. EXPECT_STREQ("\xC3\x93", WideStringToUtf8(L"\xD3", -1).c_str());
  365. // 101 0111 0110 => 110-10101 10-110110
  366. EXPECT_STREQ("\xD5\xB6", WideStringToUtf8(L"\x576", 1).c_str());
  367. EXPECT_STREQ("\xD5\xB6", WideStringToUtf8(L"\x576", -1).c_str());
  368. }
  369. // Tests that Unicode code-points that have 12 to 16 bits are encoded
  370. // as 1110xxxx 10xxxxxx 10xxxxxx.
  371. TEST(WideStringToUtf8Test, CanEncode12To16Bits) {
  372. // 0000 1000 1101 0011 => 1110-0000 10-100011 10-010011
  373. EXPECT_STREQ("\xE0\xA3\x93", WideStringToUtf8(L"\x8D3", 1).c_str());
  374. EXPECT_STREQ("\xE0\xA3\x93", WideStringToUtf8(L"\x8D3", -1).c_str());
  375. // 1100 0111 0100 1101 => 1110-1100 10-011101 10-001101
  376. EXPECT_STREQ("\xEC\x9D\x8D", WideStringToUtf8(L"\xC74D", 1).c_str());
  377. EXPECT_STREQ("\xEC\x9D\x8D", WideStringToUtf8(L"\xC74D", -1).c_str());
  378. }
  379. // Tests that the conversion stops when the function encounters \0 character.
  380. TEST(WideStringToUtf8Test, StopsOnNulCharacter) {
  381. EXPECT_STREQ("ABC", WideStringToUtf8(L"ABC\0XYZ", 100).c_str());
  382. }
  383. // Tests that the conversion stops when the function reaches the limit
  384. // specified by the 'length' parameter.
  385. TEST(WideStringToUtf8Test, StopsWhenLengthLimitReached) {
  386. EXPECT_STREQ("ABC", WideStringToUtf8(L"ABCDEF", 3).c_str());
  387. }
  388. #if !GTEST_WIDE_STRING_USES_UTF16_
  389. // Tests that Unicode code-points that have 17 to 21 bits are encoded
  390. // as 11110xxx 10xxxxxx 10xxxxxx 10xxxxxx. This code may not compile
  391. // on the systems using UTF-16 encoding.
  392. TEST(WideStringToUtf8Test, CanEncode17To21Bits) {
  393. // 0 0001 0000 1000 1101 0011 => 11110-000 10-010000 10-100011 10-010011
  394. EXPECT_STREQ("\xF0\x90\xA3\x93", WideStringToUtf8(L"\x108D3", 1).c_str());
  395. EXPECT_STREQ("\xF0\x90\xA3\x93", WideStringToUtf8(L"\x108D3", -1).c_str());
  396. // 1 0000 1000 0110 0011 0100 => 11110-100 10-001000 10-011000 10-110100
  397. EXPECT_STREQ("\xF4\x88\x98\xB4", WideStringToUtf8(L"\x108634", 1).c_str());
  398. EXPECT_STREQ("\xF4\x88\x98\xB4", WideStringToUtf8(L"\x108634", -1).c_str());
  399. }
  400. // Tests that encoding an invalid code-point generates the expected result.
  401. TEST(WideStringToUtf8Test, CanEncodeInvalidCodePoint) {
  402. EXPECT_STREQ("(Invalid Unicode 0xABCDFF)",
  403. WideStringToUtf8(L"\xABCDFF", -1).c_str());
  404. }
  405. #else // !GTEST_WIDE_STRING_USES_UTF16_
  406. // Tests that surrogate pairs are encoded correctly on the systems using
  407. // UTF-16 encoding in the wide strings.
  408. TEST(WideStringToUtf8Test, CanEncodeValidUtf16SUrrogatePairs) {
  409. EXPECT_STREQ("\xF0\x90\x90\x80",
  410. WideStringToUtf8(L"\xD801\xDC00", -1).c_str());
  411. }
  412. // Tests that encoding an invalid UTF-16 surrogate pair
  413. // generates the expected result.
  414. TEST(WideStringToUtf8Test, CanEncodeInvalidUtf16SurrogatePair) {
  415. // Leading surrogate is at the end of the string.
  416. EXPECT_STREQ("\xED\xA0\x80", WideStringToUtf8(L"\xD800", -1).c_str());
  417. // Leading surrogate is not followed by the trailing surrogate.
  418. EXPECT_STREQ("\xED\xA0\x80$", WideStringToUtf8(L"\xD800$", -1).c_str());
  419. // Trailing surrogate appearas without a leading surrogate.
  420. EXPECT_STREQ("\xED\xB0\x80PQR", WideStringToUtf8(L"\xDC00PQR", -1).c_str());
  421. }
  422. #endif // !GTEST_WIDE_STRING_USES_UTF16_
  423. // Tests that codepoint concatenation works correctly.
  424. #if !GTEST_WIDE_STRING_USES_UTF16_
  425. TEST(WideStringToUtf8Test, ConcatenatesCodepointsCorrectly) {
  426. EXPECT_STREQ(
  427. "\xF4\x88\x98\xB4"
  428. "\xEC\x9D\x8D"
  429. "\n"
  430. "\xD5\xB6"
  431. "\xE0\xA3\x93"
  432. "\xF4\x88\x98\xB4",
  433. WideStringToUtf8(L"\x108634\xC74D\n\x576\x8D3\x108634", -1).c_str());
  434. }
  435. #else
  436. TEST(WideStringToUtf8Test, ConcatenatesCodepointsCorrectly) {
  437. EXPECT_STREQ(
  438. "\xEC\x9D\x8D" "\n" "\xD5\xB6" "\xE0\xA3\x93",
  439. WideStringToUtf8(L"\xC74D\n\x576\x8D3", -1).c_str());
  440. }
  441. #endif // !GTEST_WIDE_STRING_USES_UTF16_
  442. // Tests the Random class.
  443. TEST(RandomDeathTest, GeneratesCrashesOnInvalidRange) {
  444. testing::internal::Random random(42);
  445. EXPECT_DEATH_IF_SUPPORTED(
  446. random.Generate(0),
  447. "Cannot generate a number in the range \\[0, 0\\)");
  448. EXPECT_DEATH_IF_SUPPORTED(
  449. random.Generate(testing::internal::Random::kMaxRange + 1),
  450. "Generation of a number in \\[0, 2147483649\\) was requested, "
  451. "but this can only generate numbers in \\[0, 2147483648\\)");
  452. }
  453. TEST(RandomTest, GeneratesNumbersWithinRange) {
  454. const UInt32 kRange = 10000;
  455. testing::internal::Random random(12345);
  456. for (int i = 0; i < 10; i++) {
  457. EXPECT_LT(random.Generate(kRange), kRange) << " for iteration " << i;
  458. }
  459. testing::internal::Random random2(testing::internal::Random::kMaxRange);
  460. for (int i = 0; i < 10; i++) {
  461. EXPECT_LT(random2.Generate(kRange), kRange) << " for iteration " << i;
  462. }
  463. }
  464. TEST(RandomTest, RepeatsWhenReseeded) {
  465. const int kSeed = 123;
  466. const int kArraySize = 10;
  467. const UInt32 kRange = 10000;
  468. UInt32 values[kArraySize];
  469. testing::internal::Random random(kSeed);
  470. for (int i = 0; i < kArraySize; i++) {
  471. values[i] = random.Generate(kRange);
  472. }
  473. random.Reseed(kSeed);
  474. for (int i = 0; i < kArraySize; i++) {
  475. EXPECT_EQ(values[i], random.Generate(kRange)) << " for iteration " << i;
  476. }
  477. }
  478. // Tests STL container utilities.
  479. // Tests CountIf().
  480. static bool IsPositive(int n) { return n > 0; }
  481. TEST(ContainerUtilityTest, CountIf) {
  482. std::vector<int> v;
  483. EXPECT_EQ(0, CountIf(v, IsPositive)); // Works for an empty container.
  484. v.push_back(-1);
  485. v.push_back(0);
  486. EXPECT_EQ(0, CountIf(v, IsPositive)); // Works when no value satisfies.
  487. v.push_back(2);
  488. v.push_back(-10);
  489. v.push_back(10);
  490. EXPECT_EQ(2, CountIf(v, IsPositive));
  491. }
  492. // Tests ForEach().
  493. static int g_sum = 0;
  494. static void Accumulate(int n) { g_sum += n; }
  495. TEST(ContainerUtilityTest, ForEach) {
  496. std::vector<int> v;
  497. g_sum = 0;
  498. ForEach(v, Accumulate);
  499. EXPECT_EQ(0, g_sum); // Works for an empty container;
  500. g_sum = 0;
  501. v.push_back(1);
  502. ForEach(v, Accumulate);
  503. EXPECT_EQ(1, g_sum); // Works for a container with one element.
  504. g_sum = 0;
  505. v.push_back(20);
  506. v.push_back(300);
  507. ForEach(v, Accumulate);
  508. EXPECT_EQ(321, g_sum);
  509. }
  510. // Tests GetElementOr().
  511. TEST(ContainerUtilityTest, GetElementOr) {
  512. std::vector<char> a;
  513. EXPECT_EQ('x', GetElementOr(a, 0, 'x'));
  514. a.push_back('a');
  515. a.push_back('b');
  516. EXPECT_EQ('a', GetElementOr(a, 0, 'x'));
  517. EXPECT_EQ('b', GetElementOr(a, 1, 'x'));
  518. EXPECT_EQ('x', GetElementOr(a, -2, 'x'));
  519. EXPECT_EQ('x', GetElementOr(a, 2, 'x'));
  520. }
  521. TEST(ContainerUtilityDeathTest, ShuffleRange) {
  522. std::vector<int> a;
  523. a.push_back(0);
  524. a.push_back(1);
  525. a.push_back(2);
  526. testing::internal::Random random(1);
  527. EXPECT_DEATH_IF_SUPPORTED(
  528. ShuffleRange(&random, -1, 1, &a),
  529. "Invalid shuffle range start -1: must be in range \\[0, 3\\]");
  530. EXPECT_DEATH_IF_SUPPORTED(
  531. ShuffleRange(&random, 4, 4, &a),
  532. "Invalid shuffle range start 4: must be in range \\[0, 3\\]");
  533. EXPECT_DEATH_IF_SUPPORTED(
  534. ShuffleRange(&random, 3, 2, &a),
  535. "Invalid shuffle range finish 2: must be in range \\[3, 3\\]");
  536. EXPECT_DEATH_IF_SUPPORTED(
  537. ShuffleRange(&random, 3, 4, &a),
  538. "Invalid shuffle range finish 4: must be in range \\[3, 3\\]");
  539. }
  540. class VectorShuffleTest : public Test {
  541. protected:
  542. static const int kVectorSize = 20;
  543. VectorShuffleTest() : random_(1) {
  544. for (int i = 0; i < kVectorSize; i++) {
  545. vector_.push_back(i);
  546. }
  547. }
  548. static bool VectorIsCorrupt(const TestingVector& vector) {
  549. if (kVectorSize != static_cast<int>(vector.size())) {
  550. return true;
  551. }
  552. bool found_in_vector[kVectorSize] = { false };
  553. for (size_t i = 0; i < vector.size(); i++) {
  554. const int e = vector[i];
  555. if (e < 0 || e >= kVectorSize || found_in_vector[e]) {
  556. return true;
  557. }
  558. found_in_vector[e] = true;
  559. }
  560. // Vector size is correct, elements' range is correct, no
  561. // duplicate elements. Therefore no corruption has occurred.
  562. return false;
  563. }
  564. static bool VectorIsNotCorrupt(const TestingVector& vector) {
  565. return !VectorIsCorrupt(vector);
  566. }
  567. static bool RangeIsShuffled(const TestingVector& vector, int begin, int end) {
  568. for (int i = begin; i < end; i++) {
  569. if (i != vector[i]) {
  570. return true;
  571. }
  572. }
  573. return false;
  574. }
  575. static bool RangeIsUnshuffled(
  576. const TestingVector& vector, int begin, int end) {
  577. return !RangeIsShuffled(vector, begin, end);
  578. }
  579. static bool VectorIsShuffled(const TestingVector& vector) {
  580. return RangeIsShuffled(vector, 0, static_cast<int>(vector.size()));
  581. }
  582. static bool VectorIsUnshuffled(const TestingVector& vector) {
  583. return !VectorIsShuffled(vector);
  584. }
  585. testing::internal::Random random_;
  586. TestingVector vector_;
  587. }; // class VectorShuffleTest
  588. const int VectorShuffleTest::kVectorSize;
  589. TEST_F(VectorShuffleTest, HandlesEmptyRange) {
  590. // Tests an empty range at the beginning...
  591. ShuffleRange(&random_, 0, 0, &vector_);
  592. ASSERT_PRED1(VectorIsNotCorrupt, vector_);
  593. ASSERT_PRED1(VectorIsUnshuffled, vector_);
  594. // ...in the middle...
  595. ShuffleRange(&random_, kVectorSize/2, kVectorSize/2, &vector_);
  596. ASSERT_PRED1(VectorIsNotCorrupt, vector_);
  597. ASSERT_PRED1(VectorIsUnshuffled, vector_);
  598. // ...at the end...
  599. ShuffleRange(&random_, kVectorSize - 1, kVectorSize - 1, &vector_);
  600. ASSERT_PRED1(VectorIsNotCorrupt, vector_);
  601. ASSERT_PRED1(VectorIsUnshuffled, vector_);
  602. // ...and past the end.
  603. ShuffleRange(&random_, kVectorSize, kVectorSize, &vector_);
  604. ASSERT_PRED1(VectorIsNotCorrupt, vector_);
  605. ASSERT_PRED1(VectorIsUnshuffled, vector_);
  606. }
  607. TEST_F(VectorShuffleTest, HandlesRangeOfSizeOne) {
  608. // Tests a size one range at the beginning...
  609. ShuffleRange(&random_, 0, 1, &vector_);
  610. ASSERT_PRED1(VectorIsNotCorrupt, vector_);
  611. ASSERT_PRED1(VectorIsUnshuffled, vector_);
  612. // ...in the middle...
  613. ShuffleRange(&random_, kVectorSize/2, kVectorSize/2 + 1, &vector_);
  614. ASSERT_PRED1(VectorIsNotCorrupt, vector_);
  615. ASSERT_PRED1(VectorIsUnshuffled, vector_);
  616. // ...and at the end.
  617. ShuffleRange(&random_, kVectorSize - 1, kVectorSize, &vector_);
  618. ASSERT_PRED1(VectorIsNotCorrupt, vector_);
  619. ASSERT_PRED1(VectorIsUnshuffled, vector_);
  620. }
  621. // Because we use our own random number generator and a fixed seed,
  622. // we can guarantee that the following "random" tests will succeed.
  623. TEST_F(VectorShuffleTest, ShufflesEntireVector) {
  624. Shuffle(&random_, &vector_);
  625. ASSERT_PRED1(VectorIsNotCorrupt, vector_);
  626. EXPECT_FALSE(VectorIsUnshuffled(vector_)) << vector_;
  627. // Tests the first and last elements in particular to ensure that
  628. // there are no off-by-one problems in our shuffle algorithm.
  629. EXPECT_NE(0, vector_[0]);
  630. EXPECT_NE(kVectorSize - 1, vector_[kVectorSize - 1]);
  631. }
  632. TEST_F(VectorShuffleTest, ShufflesStartOfVector) {
  633. const int kRangeSize = kVectorSize/2;
  634. ShuffleRange(&random_, 0, kRangeSize, &vector_);
  635. ASSERT_PRED1(VectorIsNotCorrupt, vector_);
  636. EXPECT_PRED3(RangeIsShuffled, vector_, 0, kRangeSize);
  637. EXPECT_PRED3(RangeIsUnshuffled, vector_, kRangeSize, kVectorSize);
  638. }
  639. TEST_F(VectorShuffleTest, ShufflesEndOfVector) {
  640. const int kRangeSize = kVectorSize / 2;
  641. ShuffleRange(&random_, kRangeSize, kVectorSize, &vector_);
  642. ASSERT_PRED1(VectorIsNotCorrupt, vector_);
  643. EXPECT_PRED3(RangeIsUnshuffled, vector_, 0, kRangeSize);
  644. EXPECT_PRED3(RangeIsShuffled, vector_, kRangeSize, kVectorSize);
  645. }
  646. TEST_F(VectorShuffleTest, ShufflesMiddleOfVector) {
  647. int kRangeSize = kVectorSize/3;
  648. ShuffleRange(&random_, kRangeSize, 2*kRangeSize, &vector_);
  649. ASSERT_PRED1(VectorIsNotCorrupt, vector_);
  650. EXPECT_PRED3(RangeIsUnshuffled, vector_, 0, kRangeSize);
  651. EXPECT_PRED3(RangeIsShuffled, vector_, kRangeSize, 2*kRangeSize);
  652. EXPECT_PRED3(RangeIsUnshuffled, vector_, 2*kRangeSize, kVectorSize);
  653. }
  654. TEST_F(VectorShuffleTest, ShufflesRepeatably) {
  655. TestingVector vector2;
  656. for (int i = 0; i < kVectorSize; i++) {
  657. vector2.push_back(i);
  658. }
  659. random_.Reseed(1234);
  660. Shuffle(&random_, &vector_);
  661. random_.Reseed(1234);
  662. Shuffle(&random_, &vector2);
  663. ASSERT_PRED1(VectorIsNotCorrupt, vector_);
  664. ASSERT_PRED1(VectorIsNotCorrupt, vector2);
  665. for (int i = 0; i < kVectorSize; i++) {
  666. EXPECT_EQ(vector_[i], vector2[i]) << " where i is " << i;
  667. }
  668. }
  669. // Tests the size of the AssertHelper class.
  670. TEST(AssertHelperTest, AssertHelperIsSmall) {
  671. // To avoid breaking clients that use lots of assertions in one
  672. // function, we cannot grow the size of AssertHelper.
  673. EXPECT_LE(sizeof(testing::internal::AssertHelper), sizeof(void*));
  674. }
  675. // Tests the String class.
  676. // Tests String's constructors.
  677. TEST(StringTest, Constructors) {
  678. // Default ctor.
  679. String s1;
  680. // We aren't using EXPECT_EQ(NULL, s1.c_str()) because comparing
  681. // pointers with NULL isn't supported on all platforms.
  682. EXPECT_EQ(0U, s1.length());
  683. EXPECT_TRUE(NULL == s1.c_str());
  684. // Implicitly constructs from a C-string.
  685. String s2 = "Hi";
  686. EXPECT_EQ(2U, s2.length());
  687. EXPECT_STREQ("Hi", s2.c_str());
  688. // Constructs from a C-string and a length.
  689. String s3("hello", 3);
  690. EXPECT_EQ(3U, s3.length());
  691. EXPECT_STREQ("hel", s3.c_str());
  692. // The empty String should be created when String is constructed with
  693. // a NULL pointer and length 0.
  694. EXPECT_EQ(0U, String(NULL, 0).length());
  695. EXPECT_FALSE(String(NULL, 0).c_str() == NULL);
  696. // Constructs a String that contains '\0'.
  697. String s4("a\0bcd", 4);
  698. EXPECT_EQ(4U, s4.length());
  699. EXPECT_EQ('a', s4.c_str()[0]);
  700. EXPECT_EQ('\0', s4.c_str()[1]);
  701. EXPECT_EQ('b', s4.c_str()[2]);
  702. EXPECT_EQ('c', s4.c_str()[3]);
  703. // Copy ctor where the source is NULL.
  704. const String null_str;
  705. String s5 = null_str;
  706. EXPECT_TRUE(s5.c_str() == NULL);
  707. // Copy ctor where the source isn't NULL.
  708. String s6 = s3;
  709. EXPECT_EQ(3U, s6.length());
  710. EXPECT_STREQ("hel", s6.c_str());
  711. // Copy ctor where the source contains '\0'.
  712. String s7 = s4;
  713. EXPECT_EQ(4U, s7.length());
  714. EXPECT_EQ('a', s7.c_str()[0]);
  715. EXPECT_EQ('\0', s7.c_str()[1]);
  716. EXPECT_EQ('b', s7.c_str()[2]);
  717. EXPECT_EQ('c', s7.c_str()[3]);
  718. }
  719. TEST(StringTest, ConvertsFromStdString) {
  720. // An empty std::string.
  721. const std::string src1("");
  722. const String dest1 = src1;
  723. EXPECT_EQ(0U, dest1.length());
  724. EXPECT_STREQ("", dest1.c_str());
  725. // A normal std::string.
  726. const std::string src2("Hi");
  727. const String dest2 = src2;
  728. EXPECT_EQ(2U, dest2.length());
  729. EXPECT_STREQ("Hi", dest2.c_str());
  730. // An std::string with an embedded NUL character.
  731. const char src3[] = "a\0b";
  732. const String dest3 = std::string(src3, sizeof(src3));
  733. EXPECT_EQ(sizeof(src3), dest3.length());
  734. EXPECT_EQ('a', dest3.c_str()[0]);
  735. EXPECT_EQ('\0', dest3.c_str()[1]);
  736. EXPECT_EQ('b', dest3.c_str()[2]);
  737. }
  738. TEST(StringTest, ConvertsToStdString) {
  739. // An empty String.
  740. const String src1("");
  741. const std::string dest1 = src1;
  742. EXPECT_EQ("", dest1);
  743. // A normal String.
  744. const String src2("Hi");
  745. const std::string dest2 = src2;
  746. EXPECT_EQ("Hi", dest2);
  747. // A String containing a '\0'.
  748. const String src3("x\0y", 3);
  749. const std::string dest3 = src3;
  750. EXPECT_EQ(std::string("x\0y", 3), dest3);
  751. }
  752. #if GTEST_HAS_GLOBAL_STRING
  753. TEST(StringTest, ConvertsFromGlobalString) {
  754. // An empty ::string.
  755. const ::string src1("");
  756. const String dest1 = src1;
  757. EXPECT_EQ(0U, dest1.length());
  758. EXPECT_STREQ("", dest1.c_str());
  759. // A normal ::string.
  760. const ::string src2("Hi");
  761. const String dest2 = src2;
  762. EXPECT_EQ(2U, dest2.length());
  763. EXPECT_STREQ("Hi", dest2.c_str());
  764. // An ::string with an embedded NUL character.
  765. const char src3[] = "x\0y";
  766. const String dest3 = ::string(src3, sizeof(src3));
  767. EXPECT_EQ(sizeof(src3), dest3.length());
  768. EXPECT_EQ('x', dest3.c_str()[0]);
  769. EXPECT_EQ('\0', dest3.c_str()[1]);
  770. EXPECT_EQ('y', dest3.c_str()[2]);
  771. }
  772. TEST(StringTest, ConvertsToGlobalString) {
  773. // An empty String.
  774. const String src1("");
  775. const ::string dest1 = src1;
  776. EXPECT_EQ("", dest1);
  777. // A normal String.
  778. const String src2("Hi");
  779. const ::string dest2 = src2;
  780. EXPECT_EQ("Hi", dest2);
  781. const String src3("x\0y", 3);
  782. const ::string dest3 = src3;
  783. EXPECT_EQ(::string("x\0y", 3), dest3);
  784. }
  785. #endif // GTEST_HAS_GLOBAL_STRING
  786. // Tests String::ShowCStringQuoted().
  787. TEST(StringTest, ShowCStringQuoted) {
  788. EXPECT_STREQ("(null)",
  789. String::ShowCStringQuoted(NULL).c_str());
  790. EXPECT_STREQ("\"\"",
  791. String::ShowCStringQuoted("").c_str());
  792. EXPECT_STREQ("\"foo\"",
  793. String::ShowCStringQuoted("foo").c_str());
  794. }
  795. // Tests String::empty().
  796. TEST(StringTest, Empty) {
  797. EXPECT_TRUE(String("").empty());
  798. EXPECT_FALSE(String().empty());
  799. EXPECT_FALSE(String(NULL).empty());
  800. EXPECT_FALSE(String("a").empty());
  801. EXPECT_FALSE(String("\0", 1).empty());
  802. }
  803. // Tests String::Compare().
  804. TEST(StringTest, Compare) {
  805. // NULL vs NULL.
  806. EXPECT_EQ(0, String().Compare(String()));
  807. // NULL vs non-NULL.
  808. EXPECT_EQ(-1, String().Compare(String("")));
  809. // Non-NULL vs NULL.
  810. EXPECT_EQ(1, String("").Compare(String()));
  811. // The following covers non-NULL vs non-NULL.
  812. // "" vs "".
  813. EXPECT_EQ(0, String("").Compare(String("")));
  814. // "" vs non-"".
  815. EXPECT_EQ(-1, String("").Compare(String("\0", 1)));
  816. EXPECT_EQ(-1, String("").Compare(" "));
  817. // Non-"" vs "".
  818. EXPECT_EQ(1, String("a").Compare(String("")));
  819. // The following covers non-"" vs non-"".
  820. // Same length and equal.
  821. EXPECT_EQ(0, String("a").Compare(String("a")));
  822. // Same length and different.
  823. EXPECT_EQ(-1, String("a\0b", 3).Compare(String("a\0c", 3)));
  824. EXPECT_EQ(1, String("b").Compare(String("a")));
  825. // Different lengths.
  826. EXPECT_EQ(-1, String("a").Compare(String("ab")));
  827. EXPECT_EQ(-1, String("a").Compare(String("a\0", 2)));
  828. EXPECT_EQ(1, String("abc").Compare(String("aacd")));
  829. }
  830. // Tests String::operator==().
  831. TEST(StringTest, Equals) {
  832. const String null(NULL);
  833. EXPECT_TRUE(null == NULL); // NOLINT
  834. EXPECT_FALSE(null == ""); // NOLINT
  835. EXPECT_FALSE(null == "bar"); // NOLINT
  836. const String empty("");
  837. EXPECT_FALSE(empty == NULL); // NOLINT
  838. EXPECT_TRUE(empty == ""); // NOLINT
  839. EXPECT_FALSE(empty == "bar"); // NOLINT
  840. const String foo("foo");
  841. EXPECT_FALSE(foo == NULL); // NOLINT
  842. EXPECT_FALSE(foo == ""); // NOLINT
  843. EXPECT_FALSE(foo == "bar"); // NOLINT
  844. EXPECT_TRUE(foo == "foo"); // NOLINT
  845. const String bar("x\0y", 3);
  846. EXPECT_FALSE(bar == "x");
  847. }
  848. // Tests String::operator!=().
  849. TEST(StringTest, NotEquals) {
  850. const String null(NULL);
  851. EXPECT_FALSE(null != NULL); // NOLINT
  852. EXPECT_TRUE(null != ""); // NOLINT
  853. EXPECT_TRUE(null != "bar"); // NOLINT
  854. const String empty("");
  855. EXPECT_TRUE(empty != NULL); // NOLINT
  856. EXPECT_FALSE(empty != ""); // NOLINT
  857. EXPECT_TRUE(empty != "bar"); // NOLINT
  858. const String foo("foo");
  859. EXPECT_TRUE(foo != NULL); // NOLINT
  860. EXPECT_TRUE(foo != ""); // NOLINT
  861. EXPECT_TRUE(foo != "bar"); // NOLINT
  862. EXPECT_FALSE(foo != "foo"); // NOLINT
  863. const String bar("x\0y", 3);
  864. EXPECT_TRUE(bar != "x");
  865. }
  866. // Tests String::length().
  867. TEST(StringTest, Length) {
  868. EXPECT_EQ(0U, String().length());
  869. EXPECT_EQ(0U, String("").length());
  870. EXPECT_EQ(2U, String("ab").length());
  871. EXPECT_EQ(3U, String("a\0b", 3).length());
  872. }
  873. // Tests String::EndsWith().
  874. TEST(StringTest, EndsWith) {
  875. EXPECT_TRUE(String("foobar").EndsWith("bar"));
  876. EXPECT_TRUE(String("foobar").EndsWith(""));
  877. EXPECT_TRUE(String("").EndsWith(""));
  878. EXPECT_FALSE(String("foobar").EndsWith("foo"));
  879. EXPECT_FALSE(String("").EndsWith("foo"));
  880. }
  881. // Tests String::EndsWithCaseInsensitive().
  882. TEST(StringTest, EndsWithCaseInsensitive) {
  883. EXPECT_TRUE(String("foobar").EndsWithCaseInsensitive("BAR"));
  884. EXPECT_TRUE(String("foobaR").EndsWithCaseInsensitive("bar"));
  885. EXPECT_TRUE(String("foobar").EndsWithCaseInsensitive(""));
  886. EXPECT_TRUE(String("").EndsWithCaseInsensitive(""));
  887. EXPECT_FALSE(String("Foobar").EndsWithCaseInsensitive("foo"));
  888. EXPECT_FALSE(String("foobar").EndsWithCaseInsensitive("Foo"));
  889. EXPECT_FALSE(String("").EndsWithCaseInsensitive("foo"));
  890. }
  891. // C++Builder's preprocessor is buggy; it fails to expand macros that
  892. // appear in macro parameters after wide char literals. Provide an alias
  893. // for NULL as a workaround.
  894. static const wchar_t* const kNull = NULL;
  895. // Tests String::CaseInsensitiveWideCStringEquals
  896. TEST(StringTest, CaseInsensitiveWideCStringEquals) {
  897. EXPECT_TRUE(String::CaseInsensitiveWideCStringEquals(NULL, NULL));
  898. EXPECT_FALSE(String::CaseInsensitiveWideCStringEquals(kNull, L""));
  899. EXPECT_FALSE(String::CaseInsensitiveWideCStringEquals(L"", kNull));
  900. EXPECT_FALSE(String::CaseInsensitiveWideCStringEquals(kNull, L"foobar"));
  901. EXPECT_FALSE(String::CaseInsensitiveWideCStringEquals(L"foobar", kNull));
  902. EXPECT_TRUE(String::CaseInsensitiveWideCStringEquals(L"foobar", L"foobar"));
  903. EXPECT_TRUE(String::CaseInsensitiveWideCStringEquals(L"foobar", L"FOOBAR"));
  904. EXPECT_TRUE(String::CaseInsensitiveWideCStringEquals(L"FOOBAR", L"foobar"));
  905. }
  906. // Tests that NULL can be assigned to a String.
  907. TEST(StringTest, CanBeAssignedNULL) {
  908. const String src(NULL);
  909. String dest;
  910. dest = src;
  911. EXPECT_STREQ(NULL, dest.c_str());
  912. }
  913. // Tests that the empty string "" can be assigned to a String.
  914. TEST(StringTest, CanBeAssignedEmpty) {
  915. const String src("");
  916. String dest;
  917. dest = src;
  918. EXPECT_STREQ("", dest.c_str());
  919. }
  920. // Tests that a non-empty string can be assigned to a String.
  921. TEST(StringTest, CanBeAssignedNonEmpty) {
  922. const String src("hello");
  923. String dest;
  924. dest = src;
  925. EXPECT_EQ(5U, dest.length());
  926. EXPECT_STREQ("hello", dest.c_str());
  927. const String src2("x\0y", 3);
  928. String dest2;
  929. dest2 = src2;
  930. EXPECT_EQ(3U, dest2.length());
  931. EXPECT_EQ('x', dest2.c_str()[0]);
  932. EXPECT_EQ('\0', dest2.c_str()[1]);
  933. EXPECT_EQ('y', dest2.c_str()[2]);
  934. }
  935. // Tests that a String can be assigned to itself.
  936. TEST(StringTest, CanBeAssignedSelf) {
  937. String dest("hello");
  938. dest = dest;
  939. EXPECT_STREQ("hello", dest.c_str());
  940. }
  941. // Sun Studio < 12 incorrectly rejects this code due to an overloading
  942. // ambiguity.
  943. #if !(defined(__SUNPRO_CC) && __SUNPRO_CC < 0x590)
  944. // Tests streaming a String.
  945. TEST(StringTest, Streams) {
  946. EXPECT_EQ(StreamableToString(String()), "(null)");
  947. EXPECT_EQ(StreamableToString(String("")), "");
  948. EXPECT_EQ(StreamableToString(String("a\0b", 3)), "a\\0b");
  949. }
  950. #endif
  951. // Tests that String::Format() works.
  952. TEST(StringTest, FormatWorks) {
  953. // Normal case: the format spec is valid, the arguments match the
  954. // spec, and the result is < 4095 characters.
  955. EXPECT_STREQ("Hello, 42", String::Format("%s, %d", "Hello", 42).c_str());
  956. // Edge case: the result is 4095 characters.
  957. char buffer[4096];
  958. const size_t kSize = sizeof(buffer);
  959. memset(buffer, 'a', kSize - 1);
  960. buffer[kSize - 1] = '\0';
  961. EXPECT_STREQ(buffer, String::Format("%s", buffer).c_str());
  962. // The result needs to be 4096 characters, exceeding Format()'s limit.
  963. EXPECT_STREQ("<formatting error or buffer exceeded>",
  964. String::Format("x%s", buffer).c_str());
  965. #if GTEST_OS_LINUX
  966. // On Linux, invalid format spec should lead to an error message.
  967. // In other environment (e.g. MSVC on Windows), String::Format() may
  968. // simply ignore a bad format spec, so this assertion is run on
  969. // Linux only.
  970. EXPECT_STREQ("<formatting error or buffer exceeded>",
  971. String::Format("%").c_str());
  972. #endif
  973. }
  974. #if GTEST_OS_WINDOWS
  975. // Tests String::ShowWideCString().
  976. TEST(StringTest, ShowWideCString) {
  977. EXPECT_STREQ("(null)",
  978. String::ShowWideCString(NULL).c_str());
  979. EXPECT_STREQ("", String::ShowWideCString(L"").c_str());
  980. EXPECT_STREQ("foo", String::ShowWideCString(L"foo").c_str());
  981. }
  982. // Tests String::ShowWideCStringQuoted().
  983. TEST(StringTest, ShowWideCStringQuoted) {
  984. EXPECT_STREQ("(null)",
  985. String::ShowWideCStringQuoted(NULL).c_str());
  986. EXPECT_STREQ("L\"\"",
  987. String::ShowWideCStringQuoted(L"").c_str());
  988. EXPECT_STREQ("L\"foo\"",
  989. String::ShowWideCStringQuoted(L"foo").c_str());
  990. }
  991. #if GTEST_OS_WINDOWS_MOBILE
  992. TEST(StringTest, AnsiAndUtf16Null) {
  993. EXPECT_EQ(NULL, String::AnsiToUtf16(NULL));
  994. EXPECT_EQ(NULL, String::Utf16ToAnsi(NULL));
  995. }
  996. TEST(StringTest, AnsiAndUtf16ConvertBasic) {
  997. const char* ansi = String::Utf16ToAnsi(L"str");
  998. EXPECT_STREQ("str", ansi);
  999. delete [] ansi;
  1000. const WCHAR* utf16 = String::AnsiToUtf16("str");
  1001. EXPECT_EQ(0, wcsncmp(L"str", utf16, 3));
  1002. delete [] utf16;
  1003. }
  1004. TEST(StringTest, AnsiAndUtf16ConvertPathChars) {
  1005. const char* ansi = String::Utf16ToAnsi(L".:\\ \"*?");
  1006. EXPECT_STREQ(".:\\ \"*?", ansi);
  1007. delete [] ansi;
  1008. const WCHAR* utf16 = String::AnsiToUtf16(".:\\ \"*?");
  1009. EXPECT_EQ(0, wcsncmp(L".:\\ \"*?", utf16, 3));
  1010. delete [] utf16;
  1011. }
  1012. #endif // GTEST_OS_WINDOWS_MOBILE
  1013. #endif // GTEST_OS_WINDOWS
  1014. // Tests TestProperty construction.
  1015. TEST(TestPropertyTest, StringValue) {
  1016. TestProperty property("key", "1");
  1017. EXPECT_STREQ("key", property.key());
  1018. EXPECT_STREQ("1", property.value());
  1019. }
  1020. // Tests TestProperty replacing a value.
  1021. TEST(TestPropertyTest, ReplaceStringValue) {
  1022. TestProperty property("key", "1");
  1023. EXPECT_STREQ("1", property.value());
  1024. property.SetValue("2");
  1025. EXPECT_STREQ("2", property.value());
  1026. }
  1027. // AddFatalFailure() and AddNonfatalFailure() must be stand-alone
  1028. // functions (i.e. their definitions cannot be inlined at the call
  1029. // sites), or C++Builder won't compile the code.
  1030. static void AddFatalFailure() {
  1031. FAIL() << "Expected fatal failure.";
  1032. }
  1033. static void AddNonfatalFailure() {
  1034. ADD_FAILURE() << "Expected non-fatal failure.";
  1035. }
  1036. class ScopedFakeTestPartResultReporterTest : public Test {
  1037. public: // Must be public and not protected due to a bug in g++ 3.4.2.
  1038. enum FailureMode {
  1039. FATAL_FAILURE,
  1040. NONFATAL_FAILURE
  1041. };
  1042. static void AddFailure(FailureMode failure) {
  1043. if (failure == FATAL_FAILURE) {
  1044. AddFatalFailure();
  1045. } else {
  1046. AddNonfatalFailure();
  1047. }
  1048. }
  1049. };
  1050. // Tests that ScopedFakeTestPartResultReporter intercepts test
  1051. // failures.
  1052. TEST_F(ScopedFakeTestPartResultReporterTest, InterceptsTestFailures) {
  1053. TestPartResultArray results;
  1054. {
  1055. ScopedFakeTestPartResultReporter reporter(
  1056. ScopedFakeTestPartResultReporter::INTERCEPT_ONLY_CURRENT_THREAD,
  1057. &results);
  1058. AddFailure(NONFATAL_FAILURE);
  1059. AddFailure(FATAL_FAILURE);
  1060. }
  1061. EXPECT_EQ(2, results.size());
  1062. EXPECT_TRUE(results.GetTestPartResult(0).nonfatally_failed());
  1063. EXPECT_TRUE(results.GetTestPartResult(1).fatally_failed());
  1064. }
  1065. TEST_F(ScopedFakeTestPartResultReporterTest, DeprecatedConstructor) {
  1066. TestPartResultArray results;
  1067. {
  1068. // Tests, that the deprecated constructor still works.
  1069. ScopedFakeTestPartResultReporter reporter(&results);
  1070. AddFailure(NONFATAL_FAILURE);
  1071. }
  1072. EXPECT_EQ(1, results.size());
  1073. }
  1074. #if GTEST_IS_THREADSAFE
  1075. class ScopedFakeTestPartResultReporterWithThreadsTest
  1076. : public ScopedFakeTestPartResultReporterTest {
  1077. protected:
  1078. static void AddFailureInOtherThread(FailureMode failure) {
  1079. ThreadWithParam<FailureMode> thread(&AddFailure, failure, NULL);
  1080. thread.Join();
  1081. }
  1082. };
  1083. TEST_F(ScopedFakeTestPartResultReporterWithThreadsTest,
  1084. InterceptsTestFailuresInAllThreads) {
  1085. TestPartResultArray results;
  1086. {
  1087. ScopedFakeTestPartResultReporter reporter(
  1088. ScopedFakeTestPartResultReporter::INTERCEPT_ALL_THREADS, &results);
  1089. AddFailure(NONFATAL_FAILURE);
  1090. AddFailure(FATAL_FAILURE);
  1091. AddFailureInOtherThread(NONFATAL_FAILURE);
  1092. AddFailureInOtherThread(FATAL_FAILURE);
  1093. }
  1094. EXPECT_EQ(4, results.size());
  1095. EXPECT_TRUE(results.GetTestPartResult(0).nonfatally_failed());
  1096. EXPECT_TRUE(results.GetTestPartResult(1).fatally_failed());
  1097. EXPECT_TRUE(results.GetTestPartResult(2).nonfatally_failed());
  1098. EXPECT_TRUE(results.GetTestPartResult(3).fatally_failed());
  1099. }
  1100. #endif // GTEST_IS_THREADSAFE
  1101. // Tests EXPECT_FATAL_FAILURE{,ON_ALL_THREADS}. Makes sure that they
  1102. // work even if the failure is generated in a called function rather than
  1103. // the current context.
  1104. typedef ScopedFakeTestPartResultReporterTest ExpectFatalFailureTest;
  1105. TEST_F(ExpectFatalFailureTest, CatchesFatalFaliure) {
  1106. EXPECT_FATAL_FAILURE(AddFatalFailure(), "Expected fatal failure.");
  1107. }
  1108. TEST_F(ExpectFatalFailureTest, CatchesFatalFailureOnAllThreads) {
  1109. // We have another test below to verify that the macro catches fatal
  1110. // failures generated on another thread.
  1111. EXPECT_FATAL_FAILURE_ON_ALL_THREADS(AddFatalFailure(),
  1112. "Expected fatal failure.");
  1113. }
  1114. #ifdef __BORLANDC__
  1115. // Silences warnings: "Condition is always true"
  1116. #pragma option push -w-ccc
  1117. #endif
  1118. // Tests that EXPECT_FATAL_FAILURE() can be used in a non-void
  1119. // function even when the statement in it contains ASSERT_*.
  1120. int NonVoidFunction() {
  1121. EXPECT_FATAL_FAILURE(ASSERT_TRUE(false), "");
  1122. EXPECT_FATAL_FAILURE_ON_ALL_THREADS(FAIL(), "");
  1123. return 0;
  1124. }
  1125. TEST_F(ExpectFatalFailureTest, CanBeUsedInNonVoidFunction) {
  1126. NonVoidFunction();
  1127. }
  1128. // Tests that EXPECT_FATAL_FAILURE(statement, ...) doesn't abort the
  1129. // current function even though 'statement' generates a fatal failure.
  1130. void DoesNotAbortHelper(bool* aborted) {
  1131. EXPECT_FATAL_FAILURE(ASSERT_TRUE(false), "");
  1132. EXPECT_FATAL_FAILURE_ON_ALL_THREADS(FAIL(), "");
  1133. *aborted = false;
  1134. }
  1135. #ifdef __BORLANDC__
  1136. // Restores warnings after previous "#pragma option push" suppressed them.
  1137. #pragma option pop
  1138. #endif
  1139. TEST_F(ExpectFatalFailureTest, DoesNotAbort) {
  1140. bool aborted = true;
  1141. DoesNotAbortHelper(&aborted);
  1142. EXPECT_FALSE(aborted);
  1143. }
  1144. // Tests that the EXPECT_FATAL_FAILURE{,_ON_ALL_THREADS} accepts a
  1145. // statement that contains a macro which expands to code containing an
  1146. // unprotected comma.
  1147. static int global_var = 0;
  1148. #define GTEST_USE_UNPROTECTED_COMMA_ global_var++, global_var++
  1149. TEST_F(ExpectFatalFailureTest, AcceptsMacroThatExpandsToUnprotectedComma) {
  1150. #if !defined(__BORLANDC__) || __BORLANDC__ >= 0x600
  1151. // ICE's in C++Builder 2007.
  1152. EXPECT_FATAL_FAILURE({
  1153. GTEST_USE_UNPROTECTED_COMMA_;
  1154. AddFatalFailure();
  1155. }, "");
  1156. #endif
  1157. EXPECT_FATAL_FAILURE_ON_ALL_THREADS({
  1158. GTEST_USE_UNPROTECTED_COMMA_;
  1159. AddFatalFailure();
  1160. }, "");
  1161. }
  1162. // Tests EXPECT_NONFATAL_FAILURE{,ON_ALL_THREADS}.
  1163. typedef ScopedFakeTestPartResultReporterTest ExpectNonfatalFailureTest;
  1164. TEST_F(ExpectNonfatalFailureTest, CatchesNonfatalFailure) {
  1165. EXPECT_NONFATAL_FAILURE(AddNonfatalFailure(),
  1166. "Expected non-fatal failure.");
  1167. }
  1168. TEST_F(ExpectNonfatalFailureTest, CatchesNonfatalFailureOnAllThreads) {
  1169. // We have another test below to verify that the macro catches
  1170. // non-fatal failures generated on another thread.
  1171. EXPECT_NONFATAL_FAILURE_ON_ALL_THREADS(AddNonfatalFailure(),
  1172. "Expected non-fatal failure.");
  1173. }
  1174. // Tests that the EXPECT_NONFATAL_FAILURE{,_ON_ALL_THREADS} accepts a
  1175. // statement that contains a macro which expands to code containing an
  1176. // unprotected comma.
  1177. TEST_F(ExpectNonfatalFailureTest, AcceptsMacroThatExpandsToUnprotectedComma) {
  1178. EXPECT_NONFATAL_FAILURE({
  1179. GTEST_USE_UNPROTECTED_COMMA_;
  1180. AddNonfatalFailure();
  1181. }, "");
  1182. EXPECT_NONFATAL_FAILURE_ON_ALL_THREADS({
  1183. GTEST_USE_UNPROTECTED_COMMA_;
  1184. AddNonfatalFailure();
  1185. }, "");
  1186. }
  1187. #if GTEST_IS_THREADSAFE
  1188. typedef ScopedFakeTestPartResultReporterWithThreadsTest
  1189. ExpectFailureWithThreadsTest;
  1190. TEST_F(ExpectFailureWithThreadsTest, ExpectFatalFailureOnAllThreads) {
  1191. EXPECT_FATAL_FAILURE_ON_ALL_THREADS(AddFailureInOtherThread(FATAL_FAILURE),
  1192. "Expected fatal failure.");
  1193. }
  1194. TEST_F(ExpectFailureWithThreadsTest, ExpectNonFatalFailureOnAllThreads) {
  1195. EXPECT_NONFATAL_FAILURE_ON_ALL_THREADS(
  1196. AddFailureInOtherThread(NONFATAL_FAILURE), "Expected non-fatal failure.");
  1197. }
  1198. #endif // GTEST_IS_THREADSAFE
  1199. // Tests the TestProperty class.
  1200. TEST(TestPropertyTest, ConstructorWorks) {
  1201. const TestProperty property("key", "value");
  1202. EXPECT_STREQ("key", property.key());
  1203. EXPECT_STREQ("value", property.value());
  1204. }
  1205. TEST(TestPropertyTest, SetValue) {
  1206. TestProperty property("key", "value_1");
  1207. EXPECT_STREQ("key", property.key());
  1208. property.SetValue("value_2");
  1209. EXPECT_STREQ("key", property.key());
  1210. EXPECT_STREQ("value_2", property.value());
  1211. }
  1212. // Tests the TestResult class
  1213. // The test fixture for testing TestResult.
  1214. class TestResultTest : public Test {
  1215. protected:
  1216. typedef std::vector<TestPartResult> TPRVector;
  1217. // We make use of 2 TestPartResult objects,
  1218. TestPartResult * pr1, * pr2;
  1219. // ... and 3 TestResult objects.
  1220. TestResult * r0, * r1, * r2;
  1221. virtual void SetUp() {
  1222. // pr1 is for success.
  1223. pr1 = new TestPartResult(TestPartResult::kSuccess,
  1224. "foo/bar.cc",
  1225. 10,
  1226. "Success!");
  1227. // pr2 is for fatal failure.
  1228. pr2 = new TestPartResult(TestPartResult::kFatalFailure,
  1229. "foo/bar.cc",
  1230. -1, // This line number means "unknown"
  1231. "Failure!");
  1232. // Creates the TestResult objects.
  1233. r0 = new TestResult();
  1234. r1 = new TestResult();
  1235. r2 = new TestResult();
  1236. // In order to test TestResult, we need to modify its internal
  1237. // state, in particular the TestPartResult vector it holds.
  1238. // test_part_results() returns a const reference to this vector.
  1239. // We cast it to a non-const object s.t. it can be modified (yes,
  1240. // this is a hack).
  1241. TPRVector* results1 = const_cast<TPRVector*>(
  1242. &TestResultAccessor::test_part_results(*r1));
  1243. TPRVector* results2 = const_cast<TPRVector*>(
  1244. &TestResultAccessor::test_part_results(*r2));
  1245. // r0 is an empty TestResult.
  1246. // r1 contains a single SUCCESS TestPartResult.
  1247. results1->push_back(*pr1);
  1248. // r2 contains a SUCCESS, and a FAILURE.
  1249. results2->push_back(*pr1);
  1250. results2->push_back(*pr2);
  1251. }
  1252. virtual void TearDown() {
  1253. delete pr1;
  1254. delete pr2;
  1255. delete r0;
  1256. delete r1;
  1257. delete r2;
  1258. }
  1259. // Helper that compares two two TestPartResults.
  1260. static void CompareTestPartResult(const TestPartResult& expected,
  1261. const TestPartResult& actual) {
  1262. EXPECT_EQ(expected.type(), actual.type());
  1263. EXPECT_STREQ(expected.file_name(), actual.file_name());
  1264. EXPECT_EQ(expected.line_number(), actual.line_number());
  1265. EXPECT_STREQ(expected.summary(), actual.summary());
  1266. EXPECT_STREQ(expected.message(), actual.message());
  1267. EXPECT_EQ(expected.passed(), actual.passed());
  1268. EXPECT_EQ(expected.failed(), actual.failed());
  1269. EXPECT_EQ(expected.nonfatally_failed(), actual.nonfatally_failed());
  1270. EXPECT_EQ(expected.fatally_failed(), actual.fatally_failed());
  1271. }
  1272. };
  1273. // Tests TestResult::total_part_count().
  1274. TEST_F(TestResultTest, total_part_count) {
  1275. ASSERT_EQ(0, r0->total_part_count());
  1276. ASSERT_EQ(1, r1->total_part_count());
  1277. ASSERT_EQ(2, r2->total_part_count());
  1278. }
  1279. // Tests TestResult::Passed().
  1280. TEST_F(TestResultTes