unitTesting.cpp 7.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237
  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. #include "memoryTester.h"
  29. //-----------------------------------------------------------------------------
  30. class TorqueUnitTestListener : public ::testing::EmptyTestEventListener
  31. {
  32. // Called before a test starts.
  33. virtual void OnTestStart(const ::testing::TestInfo& testInfo)
  34. {
  35. if (mVerbose)
  36. Con::printf("> Starting Test '%s.%s'",
  37. testInfo.test_case_name(), testInfo.name());
  38. }
  39. // Called after a failed assertion or a SUCCEED() invocation.
  40. virtual void OnTestPartResult(const ::testing::TestPartResult& testPartResult)
  41. {
  42. if (testPartResult.failed())
  43. {
  44. Con::warnf(">> Failed with '%s' in '%s' at (line:%d)\n",
  45. testPartResult.summary(),
  46. testPartResult.file_name(),
  47. testPartResult.line_number()
  48. );
  49. }
  50. else if (mVerbose)
  51. {
  52. Con::printf(">> Passed with '%s' in '%s' at (line:%d)",
  53. testPartResult.summary(),
  54. testPartResult.file_name(),
  55. testPartResult.line_number()
  56. );
  57. }
  58. }
  59. // Called after a test ends.
  60. virtual void OnTestEnd(const ::testing::TestInfo& testInfo)
  61. {
  62. if (testInfo.result()->Failed())
  63. {
  64. Con::printf("TestClass:%s Test:%s Failed!",
  65. testInfo.test_case_name(), testInfo.name());
  66. }
  67. else if(testInfo.result()->Passed())
  68. {
  69. Con::printf("TestClass:%s Test:%s Succeeded!",
  70. testInfo.test_case_name(), testInfo.name());
  71. }
  72. else
  73. {
  74. Con::printf("TestClass:%s Test:%s Skipped!",
  75. testInfo.test_case_name(), testInfo.name());
  76. }
  77. Con::printf("> Ending Test\n");
  78. }
  79. bool mVerbose;
  80. public:
  81. TorqueUnitTestListener(bool verbose) : mVerbose(verbose) {}
  82. };
  83. class TorqueScriptFixture : public testing::Test {};
  84. class TorqueScriptTest : public TorqueScriptFixture {
  85. public:
  86. explicit TorqueScriptTest(const char* pFunctionName) : mFunctionName(pFunctionName) {}
  87. void TestBody() override
  88. {
  89. Con::executef(mFunctionName);
  90. }
  91. private:
  92. const char* mFunctionName;
  93. };
  94. // uncomment to debug tests and use the test explorer.
  95. //#define TEST_EXPLORER
  96. #if !defined(TEST_EXPLORER)
  97. int main(int argc, char** argv)
  98. {
  99. StandardMainLoop::init();
  100. StandardMainLoop::handleCommandLine(argc, (const char**)argv);
  101. StandardMainLoop::shutdown();
  102. return StandardMainLoop::getReturnStatus();
  103. }
  104. #else
  105. int main(int argc, char** argv)
  106. {
  107. StandardMainLoop::init();
  108. printf("Running main() from %s\n", __FILE__);
  109. // setup simular to runTests
  110. Con::evaluate("GFXInit::createNullDevice();");
  111. Con::evaluate("if (!isObject(GuiDefaultProfile)) new GuiControlProfile(GuiDefaultProfile){}; if (!isObject(GuiTooltipProfile)) new GuiControlProfile(GuiTooltipProfile){};");
  112. testing::InitGoogleTest(&argc, argv);
  113. int res = RUN_ALL_TESTS();
  114. StandardMainLoop::shutdown();
  115. return res;
  116. }
  117. #endif
  118. DefineEngineFunction(addUnitTest, void, (const char* function), ,
  119. "Add a TorqueScript function as a GTest unit test.\n"
  120. "@note This is only implemented rudimentarily to open the door for future development in unit-testing the engine.\n"
  121. "@tsexample\n"
  122. "function MyTest() {\n"
  123. " expectTrue(2+2 == 4, \"basic math should work\");\n"
  124. "}\n"
  125. "addUnitTest(MyTest);\n"
  126. "@endtsexample\n"
  127. "@see expectTrue")
  128. {
  129. Namespace::Entry* entry = Namespace::global()->lookup(StringTable->insert(function));
  130. const char* file = __FILE__;
  131. U32 ln = __LINE__;
  132. if (entry != NULL)
  133. {
  134. file = entry->mCode->name;
  135. U32 inst;
  136. entry->mCode->findBreakLine(entry->mFunctionOffset, ln, inst);
  137. }
  138. else
  139. {
  140. Con::warnf("failed to register unit test %s, could not find the function", function);
  141. }
  142. testing::RegisterTest("TorqueScriptFixture", function, NULL, NULL, file, ln,
  143. [=]() -> TorqueScriptFixture* { return new TorqueScriptTest(function); });
  144. }
  145. String scriptFileMessage(const char* message)
  146. {
  147. Dictionary* frame = &gEvalState.getCurrentFrame();
  148. CodeBlock* code = frame->code;
  149. const char* scriptLine = code->getFileLine(frame->ip);
  150. return String::ToString("at %s: %s", scriptLine, message);
  151. }
  152. DefineEngineFunction(expectTrue, void, (bool test, const char* message), (""),
  153. "TorqueScript wrapper around the EXPECT_TRUE assertion in GTest.\n"
  154. "@tsexample\n"
  155. "expectTrue(2+2 == 4, \"basic math should work\");\n"
  156. "@endtsexample")
  157. {
  158. EXPECT_TRUE(test) << scriptFileMessage(message).c_str();
  159. }
  160. DefineEngineFunction(runAllUnitTests, int, (const char* testSpecs, const char* reportFormat), (""),
  161. "Runs engine unit tests. Some tests are marked as 'stress' tests which do not "
  162. "necessarily check correctness, just performance or possible nondeterministic "
  163. "glitches. There may also be interactive or networking tests which may be "
  164. "excluded by using the testSpecs argument.\n"
  165. "This function should only be called once per executable run, because of "
  166. "googletest's design.\n\n"
  167. "@param testSpecs A space-sepatated list of filters for test cases. "
  168. "See https://code.google.com/p/googletest/wiki/AdvancedGuide#Running_a_Subset_of_the_Tests "
  169. "and http://stackoverflow.com/a/14021997/945863 "
  170. "for a description of the flag format.")
  171. {
  172. Vector<char*> args;
  173. args.push_back(NULL); // Program name is unused by googletest.
  174. String specsArg;
  175. if (dStrlen(testSpecs) > 0)
  176. {
  177. specsArg = testSpecs;
  178. specsArg.replace(' ', ':');
  179. specsArg.insert(0, "--gtest_filter=");
  180. args.push_back(const_cast<char*>(specsArg.c_str()));
  181. }
  182. String reportFormatArg;
  183. if (dStrlen(reportFormat) > 0)
  184. {
  185. reportFormatArg = String::ToString("--gtest_output=%s", reportFormat);
  186. args.push_back(const_cast<char*>(reportFormatArg.c_str()));
  187. }
  188. S32 argc = args.size();
  189. // Initialize Google Test.
  190. testing::InitGoogleTest(&argc, args.address());
  191. // Fetch the unit test instance.
  192. testing::UnitTest& unitTest = *testing::UnitTest::GetInstance();
  193. // Fetch the unit test event listeners.
  194. testing::TestEventListeners& listeners = unitTest.listeners();
  195. // Release the default listener.
  196. delete listeners.Release(listeners.default_result_printer());
  197. if (Con::getBoolVariable("$Testing::CheckMemoryLeaks", false)) {
  198. // Add the memory leak tester.
  199. listeners.Append(new testing::MemoryLeakDetector);
  200. }
  201. // Add the Torque unit test listener.
  202. listeners.Append(new TorqueUnitTestListener(true));
  203. // Perform googletest run.
  204. Con::printf("\nUnit Tests Starting...\n");
  205. const S32 result = RUN_ALL_TESTS();
  206. Con::printf("... Unit Tests Ended.\n");
  207. return result;
  208. }