unitTesting.cpp 9.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280
  1. //-----------------------------------------------------------------------------
  2. // Copyright (c) 2014 GarageGames, LLC
  3. //
  4. // Permission is hereby granted, free of charge, to any person obtaining a copy
  5. // of this software and associated documentation files (the "Software"), to
  6. // deal in the Software without restriction, including without limitation the
  7. // rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
  8. // sell copies of the Software, and to permit persons to whom the Software is
  9. // furnished to do so, subject to the following conditions:
  10. //
  11. // The above copyright notice and this permission notice shall be included in
  12. // all copies or substantial portions of the Software.
  13. //
  14. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  15. // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  16. // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  17. // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  18. // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
  19. // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
  20. // IN THE SOFTWARE.
  21. //-----------------------------------------------------------------------------
  22. #include "unitTesting.h"
  23. #include "app/mainLoop.h"
  24. #include "console/console.h"
  25. #include "console/codeBlock.h"
  26. #include "console/engineAPI.h"
  27. #include "console/consoleInternal.h"
  28. #if defined(TORQUE_OS_WIN)
  29. #define _CRTDBG_MAP_ALLOC
  30. #include <crtdbg.h>
  31. #endif
  32. //-----------------------------------------------------------------------------
  33. class TorqueUnitTestListener : public ::testing::EmptyTestEventListener
  34. {
  35. // Called before a test starts.
  36. virtual void OnTestStart(const ::testing::TestInfo& testInfo)
  37. {
  38. if (mVerbose)
  39. Con::printf("> Starting Test '%s.%s'",
  40. testInfo.test_case_name(), testInfo.name());
  41. }
  42. // Called after a failed assertion or a SUCCEED() invocation.
  43. virtual void OnTestPartResult(const ::testing::TestPartResult& testPartResult)
  44. {
  45. if (testPartResult.failed())
  46. {
  47. Con::warnf(">> Failed with '%s' in '%s' at (line:%d)\n",
  48. testPartResult.summary(),
  49. testPartResult.file_name(),
  50. testPartResult.line_number()
  51. );
  52. }
  53. else if (mVerbose)
  54. {
  55. Con::printf(">> Passed with '%s' in '%s' at (line:%d)",
  56. testPartResult.summary(),
  57. testPartResult.file_name(),
  58. testPartResult.line_number()
  59. );
  60. }
  61. }
  62. // Called after a test ends.
  63. virtual void OnTestEnd(const ::testing::TestInfo& testInfo)
  64. {
  65. if (testInfo.result()->Failed())
  66. {
  67. Con::printf("TestClass:%s Test:%s Failed!",
  68. testInfo.test_case_name(), testInfo.name());
  69. }
  70. else if(testInfo.result()->Passed())
  71. {
  72. Con::printf("TestClass:%s Test:%s Succeeded!",
  73. testInfo.test_case_name(), testInfo.name());
  74. }
  75. else
  76. {
  77. Con::printf("TestClass:%s Test:%s Skipped!",
  78. testInfo.test_case_name(), testInfo.name());
  79. }
  80. Con::printf("> Ending Test\n");
  81. }
  82. bool mVerbose;
  83. public:
  84. TorqueUnitTestListener(bool verbose) : mVerbose(verbose) {}
  85. };
  86. class MemoryLeakDetector : public ::testing::EmptyTestEventListener
  87. {
  88. public:
  89. virtual void OnTestStart(const ::testing::TestInfo& testInfo)
  90. {
  91. #if defined(TORQUE_OS_WIN)
  92. _CrtMemCheckpoint(&memState_);
  93. #endif
  94. }
  95. virtual void OnTestEnd(const ::testing::TestInfo& testInfo)
  96. {
  97. if (testInfo.result()->Passed())
  98. {
  99. #if defined(TORQUE_OS_WIN)
  100. _CrtMemState stateNow, stateDiff;
  101. _CrtMemCheckpoint(&stateNow);
  102. int diffResult = _CrtMemDifference(&stateDiff, &memState_, &stateNow);
  103. if (diffResult)
  104. {
  105. FAIL() << "Memory leak of " << stateDiff.lSizes[1] << " byte(s) detected.";
  106. }
  107. #endif
  108. }
  109. }
  110. private:
  111. #if defined(TORQUE_OS_WIN)
  112. _CrtMemState memState_;
  113. #endif
  114. public:
  115. MemoryLeakDetector() {}
  116. };
  117. class TorqueScriptFixture : public testing::Test {};
  118. class TorqueScriptTest : public TorqueScriptFixture {
  119. public:
  120. explicit TorqueScriptTest(const char* pFunctionName) : mFunctionName(pFunctionName) {}
  121. void TestBody() override
  122. {
  123. Con::executef(mFunctionName);
  124. }
  125. private:
  126. const char* mFunctionName;
  127. };
  128. // uncomment to debug tests and use the test explorer.
  129. #define TEST_EXPLORER
  130. #if !defined(TEST_EXPLORER)
  131. int main(int argc, char** argv)
  132. {
  133. StandardMainLoop::init();
  134. StandardMainLoop::handleCommandLine(argc, (const char**)argv);
  135. StandardMainLoop::shutdown();
  136. return StandardMainLoop::getReturnStatus();
  137. }
  138. #else
  139. int main(int argc, char** argv)
  140. {
  141. StandardMainLoop::init();
  142. printf("Running main() from %s\n", __FILE__);
  143. // setup simular to runTests
  144. Con::evaluate("GFXInit::createNullDevice();");
  145. Con::evaluate("if (!isObject(GuiDefaultProfile)) new GuiControlProfile(GuiDefaultProfile){}; if (!isObject(GuiTooltipProfile)) new GuiControlProfile(GuiTooltipProfile){};");
  146. testing::InitGoogleTest(&argc, argv);
  147. // Fetch the unit test instance.
  148. testing::UnitTest& unitTest = *testing::UnitTest::GetInstance();
  149. // Fetch the unit test event listeners.
  150. testing::TestEventListeners& listeners = unitTest.listeners();
  151. listeners.Append(new MemoryLeakDetector());
  152. // Add the Torque unit test listener.
  153. listeners.Append(new TorqueUnitTestListener(true));
  154. int res = RUN_ALL_TESTS();
  155. StandardMainLoop::shutdown();
  156. return res;
  157. }
  158. #endif
  159. DefineEngineFunction(addUnitTest, void, (const char* function), ,
  160. "Add a TorqueScript function as a GTest unit test.\n"
  161. "@note This is only implemented rudimentarily to open the door for future development in unit-testing the engine.\n"
  162. "@tsexample\n"
  163. "function MyTest() {\n"
  164. " expectTrue(2+2 == 4, \"basic math should work\");\n"
  165. "}\n"
  166. "addUnitTest(MyTest);\n"
  167. "@endtsexample\n"
  168. "@see expectTrue")
  169. {
  170. Namespace::Entry* entry = Namespace::global()->lookup(StringTable->insert(function));
  171. const char* file = __FILE__;
  172. U32 ln = __LINE__;
  173. if (entry != NULL)
  174. {
  175. file = entry->mCode->name;
  176. U32 inst;
  177. entry->mCode->findBreakLine(entry->mFunctionOffset, ln, inst);
  178. }
  179. else
  180. {
  181. Con::warnf("failed to register unit test %s, could not find the function", function);
  182. }
  183. testing::RegisterTest("TorqueScriptFixture", function, NULL, NULL, file, ln,
  184. [=]() -> TorqueScriptFixture* { return new TorqueScriptTest(function); });
  185. }
  186. String scriptFileMessage(const char* message)
  187. {
  188. Dictionary* frame = &gEvalState.getCurrentFrame();
  189. CodeBlock* code = frame->code;
  190. const char* scriptLine = code->getFileLine(frame->ip);
  191. return String::ToString("at %s: %s", scriptLine, message);
  192. }
  193. DefineEngineFunction(expectTrue, void, (bool test, const char* message), (""),
  194. "TorqueScript wrapper around the EXPECT_TRUE assertion in GTest.\n"
  195. "@tsexample\n"
  196. "expectTrue(2+2 == 4, \"basic math should work\");\n"
  197. "@endtsexample")
  198. {
  199. EXPECT_TRUE(test) << scriptFileMessage(message).c_str();
  200. }
  201. DefineEngineFunction(runAllUnitTests, int, (const char* testSpecs, const char* reportFormat), (""),
  202. "Runs engine unit tests. Some tests are marked as 'stress' tests which do not "
  203. "necessarily check correctness, just performance or possible nondeterministic "
  204. "glitches. There may also be interactive or networking tests which may be "
  205. "excluded by using the testSpecs argument.\n"
  206. "This function should only be called once per executable run, because of "
  207. "googletest's design.\n\n"
  208. "@param testSpecs A space-sepatated list of filters for test cases. "
  209. "See https://code.google.com/p/googletest/wiki/AdvancedGuide#Running_a_Subset_of_the_Tests "
  210. "and http://stackoverflow.com/a/14021997/945863 "
  211. "for a description of the flag format.")
  212. {
  213. Vector<char*> args;
  214. args.push_back(NULL); // Program name is unused by googletest.
  215. String specsArg;
  216. if (dStrlen(testSpecs) > 0)
  217. {
  218. specsArg = testSpecs;
  219. specsArg.replace(' ', ':');
  220. specsArg.insert(0, "--gtest_filter=");
  221. args.push_back(const_cast<char*>(specsArg.c_str()));
  222. }
  223. String reportFormatArg;
  224. if (dStrlen(reportFormat) > 0)
  225. {
  226. reportFormatArg = String::ToString("--gtest_output=%s", reportFormat);
  227. args.push_back(const_cast<char*>(reportFormatArg.c_str()));
  228. }
  229. S32 argc = args.size();
  230. // Initialize Google Test.
  231. testing::InitGoogleTest(&argc, args.address());
  232. // Fetch the unit test instance.
  233. testing::UnitTest& unitTest = *testing::UnitTest::GetInstance();
  234. // Fetch the unit test event listeners.
  235. testing::TestEventListeners& listeners = unitTest.listeners();
  236. // Release the default listener.
  237. delete listeners.Release(listeners.default_result_printer());
  238. // Add the Torque unit test listener.
  239. listeners.Append(new TorqueUnitTestListener(true));
  240. // Perform googletest run.
  241. Con::printf("\nUnit Tests Starting...\n");
  242. const S32 result = RUN_ALL_TESTS();
  243. Con::printf("... Unit Tests Ended.\n");
  244. return result;
  245. }