unitTesting.cpp 6.9 KB

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