unitTesting.cpp 9.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283
  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. if (!mVerbose)
  71. return;
  72. else if(testInfo.result()->Passed())
  73. {
  74. Con::printf("TestClass:%s Test:%s Succeeded!",
  75. testInfo.test_case_name(), testInfo.name());
  76. }
  77. else
  78. {
  79. Con::printf("TestClass:%s Test:%s Skipped!",
  80. testInfo.test_case_name(), testInfo.name());
  81. }
  82. Con::printf("> Ending Test\n");
  83. }
  84. bool mVerbose;
  85. public:
  86. TorqueUnitTestListener(bool verbose) : mVerbose(verbose) {}
  87. };
  88. class MemoryLeakDetector : public ::testing::EmptyTestEventListener
  89. {
  90. public:
  91. virtual void OnTestStart(const ::testing::TestInfo& testInfo)
  92. {
  93. #if defined(TORQUE_OS_WIN)
  94. _CrtMemCheckpoint(&memState_);
  95. #endif
  96. }
  97. virtual void OnTestEnd(const ::testing::TestInfo& testInfo)
  98. {
  99. if (testInfo.result()->Passed())
  100. {
  101. #if defined(TORQUE_OS_WIN)
  102. _CrtMemState stateNow, stateDiff;
  103. _CrtMemCheckpoint(&stateNow);
  104. int diffResult = _CrtMemDifference(&stateDiff, &memState_, &stateNow);
  105. if (diffResult)
  106. {
  107. FAIL() << "Memory leak of " << stateDiff.lSizes[1] << " byte(s) detected.";
  108. }
  109. #endif
  110. }
  111. }
  112. private:
  113. #if defined(TORQUE_OS_WIN)
  114. _CrtMemState memState_;
  115. #endif
  116. public:
  117. MemoryLeakDetector() {}
  118. };
  119. class TorqueScriptFixture : public testing::Test {};
  120. class TorqueScriptTest : public TorqueScriptFixture {
  121. public:
  122. explicit TorqueScriptTest(const char* pFunctionName) : mFunctionName(pFunctionName) {}
  123. void TestBody() override
  124. {
  125. Con::executef(mFunctionName);
  126. }
  127. private:
  128. const char* mFunctionName;
  129. };
  130. // uncomment to debug tests and use the test explorer.
  131. //#define TEST_EXPLORER
  132. #if !defined(TEST_EXPLORER)
  133. int main(int argc, char** argv)
  134. {
  135. StandardMainLoop::init();
  136. StandardMainLoop::handleCommandLine(argc, (const char**)argv);
  137. StandardMainLoop::shutdown();
  138. return StandardMainLoop::getReturnStatus();
  139. }
  140. #else
  141. int main(int argc, char** argv)
  142. {
  143. StandardMainLoop::init();
  144. printf("Running main() from %s\n", __FILE__);
  145. // setup simular to runTests
  146. Con::evaluate("GFXInit::createNullDevice();");
  147. Con::evaluate("if (!isObject(GuiDefaultProfile)) new GuiControlProfile(GuiDefaultProfile){}; if (!isObject(GuiTooltipProfile)) new GuiControlProfile(GuiTooltipProfile){};");
  148. testing::InitGoogleTest(&argc, argv);
  149. // Fetch the unit test instance.
  150. testing::UnitTest& unitTest = *testing::UnitTest::GetInstance();
  151. // Fetch the unit test event listeners.
  152. testing::TestEventListeners& listeners = unitTest.listeners();
  153. listeners.Append(new MemoryLeakDetector());
  154. // Add the Torque unit test listener.
  155. listeners.Append(new TorqueUnitTestListener(true));
  156. int res = RUN_ALL_TESTS();
  157. StandardMainLoop::shutdown();
  158. return res;
  159. }
  160. #endif
  161. DefineEngineFunction(addUnitTest, void, (const char* function), ,
  162. "Add a TorqueScript function as a GTest unit test.\n"
  163. "@note This is only implemented rudimentarily to open the door for future development in unit-testing the engine.\n"
  164. "@tsexample\n"
  165. "function MyTest() {\n"
  166. " expectTrue(2+2 == 4, \"basic math should work\");\n"
  167. "}\n"
  168. "addUnitTest(MyTest);\n"
  169. "@endtsexample\n"
  170. "@see expectTrue")
  171. {
  172. Namespace::Entry* entry = Namespace::global()->lookup(StringTable->insert(function));
  173. const char* file = __FILE__;
  174. U32 ln = __LINE__;
  175. if (entry != NULL)
  176. {
  177. file = entry->mCode->name;
  178. U32 inst;
  179. entry->mCode->findBreakLine(entry->mFunctionOffset, ln, inst);
  180. }
  181. else
  182. {
  183. Con::warnf("failed to register unit test %s, could not find the function", function);
  184. }
  185. testing::RegisterTest("TorqueScriptFixture", function, NULL, NULL, file, ln,
  186. [=]() -> TorqueScriptFixture* { return new TorqueScriptTest(function); });
  187. }
  188. String scriptFileMessage(const char* message)
  189. {
  190. Dictionary* frame = &gEvalState.getCurrentFrame();
  191. CodeBlock* code = frame->code;
  192. const char* scriptLine = code->getFileLine(frame->ip);
  193. return String::ToString("at %s: %s", scriptLine, message);
  194. }
  195. DefineEngineFunction(expectTrue, void, (bool test, const char* message), (""),
  196. "TorqueScript wrapper around the EXPECT_TRUE assertion in GTest.\n"
  197. "@tsexample\n"
  198. "expectTrue(2+2 == 4, \"basic math should work\");\n"
  199. "@endtsexample")
  200. {
  201. EXPECT_TRUE(test) << scriptFileMessage(message).c_str();
  202. }
  203. DefineEngineFunction(runAllUnitTests, int, (const char* testSpecs, const char* reportFormat), (""),
  204. "Runs engine unit tests. Some tests are marked as 'stress' tests which do not "
  205. "necessarily check correctness, just performance or possible nondeterministic "
  206. "glitches. There may also be interactive or networking tests which may be "
  207. "excluded by using the testSpecs argument.\n"
  208. "This function should only be called once per executable run, because of "
  209. "googletest's design.\n\n"
  210. "@param testSpecs A space-sepatated list of filters for test cases. "
  211. "See https://code.google.com/p/googletest/wiki/AdvancedGuide#Running_a_Subset_of_the_Tests "
  212. "and http://stackoverflow.com/a/14021997/945863 "
  213. "for a description of the flag format.")
  214. {
  215. Vector<char*> args;
  216. args.push_back(NULL); // Program name is unused by googletest.
  217. String specsArg;
  218. if (dStrlen(testSpecs) > 0)
  219. {
  220. specsArg = testSpecs;
  221. specsArg.replace(' ', ':');
  222. specsArg.insert(0, "--gtest_filter=");
  223. args.push_back(const_cast<char*>(specsArg.c_str()));
  224. }
  225. String reportFormatArg;
  226. if (dStrlen(reportFormat) > 0)
  227. {
  228. reportFormatArg = String::ToString("--gtest_output=%s", reportFormat);
  229. args.push_back(const_cast<char*>(reportFormatArg.c_str()));
  230. }
  231. S32 argc = args.size();
  232. // Initialize Google Test.
  233. testing::InitGoogleTest(&argc, args.address());
  234. // Fetch the unit test instance.
  235. testing::UnitTest& unitTest = *testing::UnitTest::GetInstance();
  236. // Fetch the unit test event listeners.
  237. testing::TestEventListeners& listeners = unitTest.listeners();
  238. // Release the default listener.
  239. delete listeners.Release(listeners.default_result_printer());
  240. // Add the Torque unit test listener.
  241. listeners.Append(new TorqueUnitTestListener(false));
  242. // Perform googletest run.
  243. Con::printf("\nUnit Tests Starting...\n");
  244. const S32 result = RUN_ALL_TESTS();
  245. Con::printf("... Unit Tests Ended.\n");
  246. return result;
  247. }