/Unittests/googletest/test/gtest_unittest.cc

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