cmCTestRunTest.cxx 29 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808
  1. /* Distributed under the OSI-approved BSD 3-Clause License. See accompanying
  2. file Copyright.txt or https://cmake.org/licensing for details. */
  3. #ifdef _WIN32
  4. /* windows.h defines min() and max() macros that interfere. */
  5. #define NOMINMAX
  6. #endif
  7. #include "cmCTestRunTest.h"
  8. #include "cmCTest.h"
  9. #include "cmCTestMemCheckHandler.h"
  10. #include "cmCTestTestHandler.h"
  11. #include "cmProcess.h"
  12. #include "cmSystemTools.h"
  13. #include "cmWorkingDirectory.h"
  14. #include "cm_curl.h"
  15. #include "cm_zlib.h"
  16. #include "cmsys/Base64.h"
  17. #include "cmsys/Process.h"
  18. #include "cmsys/RegularExpression.hxx"
  19. #include <chrono>
  20. #include <iomanip>
  21. #include <sstream>
  22. #include <stdio.h>
  23. #include <time.h>
  24. #include <utility>
  25. cmCTestRunTest::cmCTestRunTest(cmCTestTestHandler* handler)
  26. {
  27. this->CTest = handler->CTest;
  28. this->TestHandler = handler;
  29. this->TestProcess = nullptr;
  30. this->TestResult.ExecutionTime = std::chrono::duration<double>::zero();
  31. this->TestResult.ReturnValue = 0;
  32. this->TestResult.Status = cmCTestTestHandler::NOT_RUN;
  33. this->TestResult.TestCount = 0;
  34. this->TestResult.Properties = nullptr;
  35. this->ProcessOutput.clear();
  36. this->CompressedOutput.clear();
  37. this->CompressionRatio = 2;
  38. this->StopTimePassed = false;
  39. this->NumberOfRunsLeft = 1; // default to 1 run of the test
  40. this->RunUntilFail = false; // default to run the test once
  41. this->RunAgain = false; // default to not having to run again
  42. }
  43. cmCTestRunTest::~cmCTestRunTest()
  44. {
  45. }
  46. bool cmCTestRunTest::CheckOutput()
  47. {
  48. // Read lines for up to 0.1 seconds of total time.
  49. std::chrono::duration<double> timeout = std::chrono::milliseconds(100);
  50. auto timeEnd = std::chrono::steady_clock::now() + timeout;
  51. std::string line;
  52. while ((timeout = timeEnd - std::chrono::steady_clock::now(),
  53. timeout > std::chrono::seconds(0))) {
  54. int p = this->TestProcess->GetNextOutputLine(line, timeout);
  55. if (p == cmsysProcess_Pipe_None) {
  56. // Process has terminated and all output read.
  57. return false;
  58. }
  59. if (p == cmsysProcess_Pipe_STDOUT) {
  60. // Store this line of output.
  61. cmCTestLog(this->CTest, HANDLER_VERBOSE_OUTPUT, this->GetIndex()
  62. << ": " << line << std::endl);
  63. this->ProcessOutput += line;
  64. this->ProcessOutput += "\n";
  65. // Check for TIMEOUT_AFTER_MATCH property.
  66. if (!this->TestProperties->TimeoutRegularExpressions.empty()) {
  67. for (auto& reg : this->TestProperties->TimeoutRegularExpressions) {
  68. if (reg.first.find(this->ProcessOutput.c_str())) {
  69. cmCTestLog(this->CTest, HANDLER_VERBOSE_OUTPUT, this->GetIndex()
  70. << ": "
  71. << "Test timeout changed to "
  72. << std::chrono::duration_cast<std::chrono::seconds>(
  73. this->TestProperties->AlternateTimeout)
  74. .count()
  75. << std::endl);
  76. this->TestProcess->ResetStartTime();
  77. this->TestProcess->ChangeTimeout(
  78. this->TestProperties->AlternateTimeout);
  79. this->TestProperties->TimeoutRegularExpressions.clear();
  80. break;
  81. }
  82. }
  83. }
  84. } else { // if(p == cmsysProcess_Pipe_Timeout)
  85. break;
  86. }
  87. }
  88. return true;
  89. }
  90. // Streamed compression of test output. The compressed data
  91. // is appended to this->CompressedOutput
  92. void cmCTestRunTest::CompressOutput()
  93. {
  94. int ret;
  95. z_stream strm;
  96. unsigned char* in = reinterpret_cast<unsigned char*>(
  97. const_cast<char*>(this->ProcessOutput.c_str()));
  98. // zlib makes the guarantee that this is the maximum output size
  99. int outSize = static_cast<int>(
  100. static_cast<double>(this->ProcessOutput.size()) * 1.001 + 13.0);
  101. unsigned char* out = new unsigned char[outSize];
  102. strm.zalloc = Z_NULL;
  103. strm.zfree = Z_NULL;
  104. strm.opaque = Z_NULL;
  105. ret = deflateInit(&strm, -1); // default compression level
  106. if (ret != Z_OK) {
  107. delete[] out;
  108. return;
  109. }
  110. strm.avail_in = static_cast<uInt>(this->ProcessOutput.size());
  111. strm.next_in = in;
  112. strm.avail_out = outSize;
  113. strm.next_out = out;
  114. ret = deflate(&strm, Z_FINISH);
  115. if (ret != Z_STREAM_END) {
  116. cmCTestLog(this->CTest, ERROR_MESSAGE,
  117. "Error during output compression. Sending uncompressed output."
  118. << std::endl);
  119. delete[] out;
  120. return;
  121. }
  122. (void)deflateEnd(&strm);
  123. unsigned char* encoded_buffer =
  124. new unsigned char[static_cast<int>(outSize * 1.5)];
  125. size_t rlen = cmsysBase64_Encode(out, strm.total_out, encoded_buffer, 1);
  126. this->CompressedOutput.clear();
  127. for (size_t i = 0; i < rlen; i++) {
  128. this->CompressedOutput += encoded_buffer[i];
  129. }
  130. if (strm.total_in) {
  131. this->CompressionRatio =
  132. static_cast<double>(strm.total_out) / static_cast<double>(strm.total_in);
  133. }
  134. delete[] encoded_buffer;
  135. delete[] out;
  136. }
  137. bool cmCTestRunTest::EndTest(size_t completed, size_t total, bool started)
  138. {
  139. if ((!this->TestHandler->MemCheck &&
  140. this->CTest->ShouldCompressTestOutput()) ||
  141. (this->TestHandler->MemCheck &&
  142. this->CTest->ShouldCompressTestOutput())) {
  143. this->CompressOutput();
  144. }
  145. this->WriteLogOutputTop(completed, total);
  146. std::string reason;
  147. bool passed = true;
  148. int res =
  149. started ? this->TestProcess->GetProcessStatus() : cmsysProcess_State_Error;
  150. int retVal = this->TestProcess->GetExitValue();
  151. bool forceFail = false;
  152. bool skipped = false;
  153. bool outputTestErrorsToConsole = false;
  154. if (!this->TestProperties->RequiredRegularExpressions.empty() &&
  155. this->FailedDependencies.empty()) {
  156. bool found = false;
  157. for (auto& pass : this->TestProperties->RequiredRegularExpressions) {
  158. if (pass.first.find(this->ProcessOutput.c_str())) {
  159. found = true;
  160. reason = "Required regular expression found.";
  161. break;
  162. }
  163. }
  164. if (!found) {
  165. reason = "Required regular expression not found.";
  166. forceFail = true;
  167. }
  168. reason += "Regex=[";
  169. for (auto& pass : this->TestProperties->RequiredRegularExpressions) {
  170. reason += pass.second;
  171. reason += "\n";
  172. }
  173. reason += "]";
  174. }
  175. if (!this->TestProperties->ErrorRegularExpressions.empty() &&
  176. this->FailedDependencies.empty()) {
  177. for (auto& pass : this->TestProperties->ErrorRegularExpressions) {
  178. if (pass.first.find(this->ProcessOutput.c_str())) {
  179. reason = "Error regular expression found in output.";
  180. reason += " Regex=[";
  181. reason += pass.second;
  182. reason += "]";
  183. forceFail = true;
  184. break;
  185. }
  186. }
  187. }
  188. if (res == cmsysProcess_State_Exited) {
  189. bool success = !forceFail &&
  190. (retVal == 0 ||
  191. !this->TestProperties->RequiredRegularExpressions.empty());
  192. if (this->TestProperties->SkipReturnCode >= 0 &&
  193. this->TestProperties->SkipReturnCode == retVal) {
  194. this->TestResult.Status = cmCTestTestHandler::NOT_RUN;
  195. std::ostringstream s;
  196. s << "SKIP_RETURN_CODE=" << this->TestProperties->SkipReturnCode;
  197. this->TestResult.CompletionStatus = s.str();
  198. cmCTestLog(this->CTest, HANDLER_OUTPUT, "***Skipped ");
  199. skipped = true;
  200. } else if ((success && !this->TestProperties->WillFail) ||
  201. (!success && this->TestProperties->WillFail)) {
  202. this->TestResult.Status = cmCTestTestHandler::COMPLETED;
  203. cmCTestLog(this->CTest, HANDLER_OUTPUT, " Passed ");
  204. } else {
  205. this->TestResult.Status = cmCTestTestHandler::FAILED;
  206. cmCTestLog(this->CTest, HANDLER_OUTPUT, "***Failed " << reason);
  207. outputTestErrorsToConsole = this->CTest->OutputTestOutputOnTestFailure;
  208. }
  209. } else if (res == cmsysProcess_State_Expired) {
  210. cmCTestLog(this->CTest, HANDLER_OUTPUT, "***Timeout ");
  211. this->TestResult.Status = cmCTestTestHandler::TIMEOUT;
  212. outputTestErrorsToConsole = this->CTest->OutputTestOutputOnTestFailure;
  213. } else if (res == cmsysProcess_State_Exception) {
  214. outputTestErrorsToConsole = this->CTest->OutputTestOutputOnTestFailure;
  215. cmCTestLog(this->CTest, HANDLER_OUTPUT, "***Exception: ");
  216. this->TestResult.ExceptionStatus =
  217. this->TestProcess->GetExitExceptionString();
  218. switch (this->TestProcess->GetExitException()) {
  219. case cmsysProcess_Exception_Fault:
  220. cmCTestLog(this->CTest, HANDLER_OUTPUT, "SegFault");
  221. this->TestResult.Status = cmCTestTestHandler::SEGFAULT;
  222. break;
  223. case cmsysProcess_Exception_Illegal:
  224. cmCTestLog(this->CTest, HANDLER_OUTPUT, "Illegal");
  225. this->TestResult.Status = cmCTestTestHandler::ILLEGAL;
  226. break;
  227. case cmsysProcess_Exception_Interrupt:
  228. cmCTestLog(this->CTest, HANDLER_OUTPUT, "Interrupt");
  229. this->TestResult.Status = cmCTestTestHandler::INTERRUPT;
  230. break;
  231. case cmsysProcess_Exception_Numerical:
  232. cmCTestLog(this->CTest, HANDLER_OUTPUT, "Numerical");
  233. this->TestResult.Status = cmCTestTestHandler::NUMERICAL;
  234. break;
  235. default:
  236. cmCTestLog(this->CTest, HANDLER_OUTPUT,
  237. this->TestResult.ExceptionStatus);
  238. this->TestResult.Status = cmCTestTestHandler::OTHER_FAULT;
  239. }
  240. } else if ("Disabled" == this->TestResult.CompletionStatus) {
  241. cmCTestLog(this->CTest, HANDLER_OUTPUT, "***Not Run (Disabled) ");
  242. } else // cmsysProcess_State_Error
  243. {
  244. cmCTestLog(this->CTest, HANDLER_OUTPUT, "***Not Run ");
  245. }
  246. passed = this->TestResult.Status == cmCTestTestHandler::COMPLETED;
  247. char buf[1024];
  248. sprintf(buf, "%6.2f sec",
  249. double(std::chrono::duration_cast<std::chrono::milliseconds>(
  250. this->TestProcess->GetTotalTime())
  251. .count()) /
  252. 1000.0);
  253. cmCTestLog(this->CTest, HANDLER_OUTPUT, buf << "\n");
  254. if (outputTestErrorsToConsole) {
  255. cmCTestLog(this->CTest, HANDLER_OUTPUT, this->ProcessOutput << std::endl);
  256. }
  257. if (this->TestHandler->LogFile) {
  258. *this->TestHandler->LogFile << "Test time = " << buf << std::endl;
  259. }
  260. // Set the working directory to the tests directory to process Dart files.
  261. {
  262. cmWorkingDirectory workdir(this->TestProperties->Directory);
  263. this->DartProcessing();
  264. }
  265. // if this is doing MemCheck then all the output needs to be put into
  266. // Output since that is what is parsed by cmCTestMemCheckHandler
  267. if (!this->TestHandler->MemCheck && started) {
  268. this->TestHandler->CleanTestOutput(
  269. this->ProcessOutput,
  270. static_cast<size_t>(
  271. this->TestResult.Status == cmCTestTestHandler::COMPLETED
  272. ? this->TestHandler->CustomMaximumPassedTestOutputSize
  273. : this->TestHandler->CustomMaximumFailedTestOutputSize));
  274. }
  275. this->TestResult.Reason = reason;
  276. if (this->TestHandler->LogFile) {
  277. bool pass = true;
  278. const char* reasonType = "Test Pass Reason";
  279. if (this->TestResult.Status != cmCTestTestHandler::COMPLETED &&
  280. this->TestResult.Status != cmCTestTestHandler::NOT_RUN) {
  281. reasonType = "Test Fail Reason";
  282. pass = false;
  283. }
  284. auto ttime = this->TestProcess->GetTotalTime();
  285. auto hours = std::chrono::duration_cast<std::chrono::hours>(ttime);
  286. ttime -= hours;
  287. auto minutes = std::chrono::duration_cast<std::chrono::minutes>(ttime);
  288. ttime -= minutes;
  289. auto seconds = std::chrono::duration_cast<std::chrono::seconds>(ttime);
  290. char buffer[100];
  291. sprintf(buffer, "%02d:%02d:%02d", static_cast<unsigned>(hours.count()),
  292. static_cast<unsigned>(minutes.count()),
  293. static_cast<unsigned>(seconds.count()));
  294. *this->TestHandler->LogFile
  295. << "----------------------------------------------------------"
  296. << std::endl;
  297. if (!this->TestResult.Reason.empty()) {
  298. *this->TestHandler->LogFile << reasonType << ":\n"
  299. << this->TestResult.Reason << "\n";
  300. } else {
  301. if (pass) {
  302. *this->TestHandler->LogFile << "Test Passed.\n";
  303. } else {
  304. *this->TestHandler->LogFile << "Test Failed.\n";
  305. }
  306. }
  307. *this->TestHandler->LogFile
  308. << "\"" << this->TestProperties->Name
  309. << "\" end time: " << this->CTest->CurrentTime() << std::endl
  310. << "\"" << this->TestProperties->Name << "\" time elapsed: " << buffer
  311. << std::endl
  312. << "----------------------------------------------------------"
  313. << std::endl
  314. << std::endl;
  315. }
  316. // if the test actually started and ran
  317. // record the results in TestResult
  318. if (started) {
  319. bool compress = !this->TestHandler->MemCheck &&
  320. this->CompressionRatio < 1 && this->CTest->ShouldCompressTestOutput();
  321. this->TestResult.Output =
  322. compress ? this->CompressedOutput : this->ProcessOutput;
  323. this->TestResult.CompressOutput = compress;
  324. this->TestResult.ReturnValue = this->TestProcess->GetExitValue();
  325. if (!skipped) {
  326. this->TestResult.CompletionStatus = "Completed";
  327. }
  328. this->TestResult.ExecutionTime = this->TestProcess->GetTotalTime();
  329. this->MemCheckPostProcess();
  330. this->ComputeWeightedCost();
  331. }
  332. // If the test does not need to rerun push the current TestResult onto the
  333. // TestHandler vector
  334. if (!this->NeedsToRerun()) {
  335. this->TestHandler->TestResults.push_back(this->TestResult);
  336. }
  337. delete this->TestProcess;
  338. return passed || skipped;
  339. }
  340. bool cmCTestRunTest::StartAgain()
  341. {
  342. if (!this->RunAgain) {
  343. return false;
  344. }
  345. this->RunAgain = false; // reset
  346. // change to tests directory
  347. cmWorkingDirectory workdir(this->TestProperties->Directory);
  348. this->StartTest(this->TotalNumberOfTests);
  349. return true;
  350. }
  351. bool cmCTestRunTest::NeedsToRerun()
  352. {
  353. this->NumberOfRunsLeft--;
  354. if (this->NumberOfRunsLeft == 0) {
  355. return false;
  356. }
  357. // if number of runs left is not 0, and we are running until
  358. // we find a failed test, then return true so the test can be
  359. // restarted
  360. if (this->RunUntilFail &&
  361. this->TestResult.Status == cmCTestTestHandler::COMPLETED) {
  362. this->RunAgain = true;
  363. return true;
  364. }
  365. return false;
  366. }
  367. void cmCTestRunTest::ComputeWeightedCost()
  368. {
  369. double prev = static_cast<double>(this->TestProperties->PreviousRuns);
  370. double avgcost = static_cast<double>(this->TestProperties->Cost);
  371. double current =
  372. double(std::chrono::duration_cast<std::chrono::milliseconds>(
  373. this->TestResult.ExecutionTime)
  374. .count()) /
  375. 1000.0;
  376. if (this->TestResult.Status == cmCTestTestHandler::COMPLETED) {
  377. this->TestProperties->Cost =
  378. static_cast<float>(((prev * avgcost) + current) / (prev + 1.0));
  379. this->TestProperties->PreviousRuns++;
  380. }
  381. }
  382. void cmCTestRunTest::MemCheckPostProcess()
  383. {
  384. if (!this->TestHandler->MemCheck) {
  385. return;
  386. }
  387. cmCTestOptionalLog(this->CTest, HANDLER_VERBOSE_OUTPUT, this->Index
  388. << ": process test output now: "
  389. << this->TestProperties->Name << " "
  390. << this->TestResult.Name << std::endl,
  391. this->TestHandler->GetQuiet());
  392. cmCTestMemCheckHandler* handler =
  393. static_cast<cmCTestMemCheckHandler*>(this->TestHandler);
  394. handler->PostProcessTest(this->TestResult, this->Index);
  395. }
  396. // Starts the execution of a test. Returns once it has started
  397. bool cmCTestRunTest::StartTest(size_t total)
  398. {
  399. this->TotalNumberOfTests = total; // save for rerun case
  400. cmCTestLog(this->CTest, HANDLER_OUTPUT, std::setw(2 * getNumWidth(total) + 8)
  401. << "Start "
  402. << std::setw(getNumWidth(this->TestHandler->GetMaxIndex()))
  403. << this->TestProperties->Index << ": "
  404. << this->TestProperties->Name << std::endl);
  405. this->ProcessOutput.clear();
  406. // Return immediately if test is disabled
  407. if (this->TestProperties->Disabled) {
  408. this->TestResult.Properties = this->TestProperties;
  409. this->TestResult.ExecutionTime = std::chrono::duration<double>::zero();
  410. this->TestResult.CompressOutput = false;
  411. this->TestResult.ReturnValue = -1;
  412. this->TestResult.CompletionStatus = "Disabled";
  413. this->TestResult.Status = cmCTestTestHandler::NOT_RUN;
  414. this->TestResult.TestCount = this->TestProperties->Index;
  415. this->TestResult.Name = this->TestProperties->Name;
  416. this->TestResult.Path = this->TestProperties->Directory;
  417. this->TestProcess = new cmProcess;
  418. this->TestResult.Output = "Disabled";
  419. this->TestResult.FullCommandLine.clear();
  420. return false;
  421. }
  422. this->TestResult.Properties = this->TestProperties;
  423. this->TestResult.ExecutionTime = std::chrono::duration<double>::zero();
  424. this->TestResult.CompressOutput = false;
  425. this->TestResult.ReturnValue = -1;
  426. this->TestResult.CompletionStatus = "Failed to start";
  427. this->TestResult.Status = cmCTestTestHandler::BAD_COMMAND;
  428. this->TestResult.TestCount = this->TestProperties->Index;
  429. this->TestResult.Name = this->TestProperties->Name;
  430. this->TestResult.Path = this->TestProperties->Directory;
  431. // Check for failed fixture dependencies before we even look at the command
  432. // arguments because if we are not going to run the test, the command and
  433. // its arguments are irrelevant. This matters for the case where a fixture
  434. // dependency might be creating the executable we want to run.
  435. if (!this->FailedDependencies.empty()) {
  436. this->TestProcess = new cmProcess;
  437. std::string msg = "Failed test dependencies:";
  438. for (std::string const& failedDep : this->FailedDependencies) {
  439. msg += " " + failedDep;
  440. }
  441. *this->TestHandler->LogFile << msg << std::endl;
  442. cmCTestLog(this->CTest, HANDLER_OUTPUT, msg << std::endl);
  443. this->TestResult.Output = msg;
  444. this->TestResult.FullCommandLine.clear();
  445. this->TestResult.CompletionStatus = "Fixture dependency failed";
  446. this->TestResult.Status = cmCTestTestHandler::NOT_RUN;
  447. return false;
  448. }
  449. this->ComputeArguments();
  450. std::vector<std::string>& args = this->TestProperties->Args;
  451. if (args.size() >= 2 && args[1] == "NOT_AVAILABLE") {
  452. this->TestProcess = new cmProcess;
  453. std::string msg;
  454. if (this->CTest->GetConfigType().empty()) {
  455. msg = "Test not available without configuration.";
  456. msg += " (Missing \"-C <config>\"?)";
  457. } else {
  458. msg = "Test not available in configuration \"";
  459. msg += this->CTest->GetConfigType();
  460. msg += "\".";
  461. }
  462. *this->TestHandler->LogFile << msg << std::endl;
  463. cmCTestLog(this->CTest, ERROR_MESSAGE, msg << std::endl);
  464. this->TestResult.Output = msg;
  465. this->TestResult.FullCommandLine.clear();
  466. this->TestResult.CompletionStatus = "Missing Configuration";
  467. this->TestResult.Status = cmCTestTestHandler::NOT_RUN;
  468. return false;
  469. }
  470. // Check if all required files exist
  471. for (std::string const& file : this->TestProperties->RequiredFiles) {
  472. if (!cmSystemTools::FileExists(file.c_str())) {
  473. // Required file was not found
  474. this->TestProcess = new cmProcess;
  475. *this->TestHandler->LogFile << "Unable to find required file: " << file
  476. << std::endl;
  477. cmCTestLog(this->CTest, ERROR_MESSAGE,
  478. "Unable to find required file: " << file << std::endl);
  479. this->TestResult.Output = "Unable to find required file: " + file;
  480. this->TestResult.FullCommandLine.clear();
  481. this->TestResult.CompletionStatus = "Required Files Missing";
  482. this->TestResult.Status = cmCTestTestHandler::NOT_RUN;
  483. return false;
  484. }
  485. }
  486. // log and return if we did not find the executable
  487. if (this->ActualCommand.empty()) {
  488. // if the command was not found create a TestResult object
  489. // that has that information
  490. this->TestProcess = new cmProcess;
  491. *this->TestHandler->LogFile << "Unable to find executable: " << args[1]
  492. << std::endl;
  493. cmCTestLog(this->CTest, ERROR_MESSAGE,
  494. "Unable to find executable: " << args[1] << std::endl);
  495. this->TestResult.Output = "Unable to find executable: " + args[1];
  496. this->TestResult.FullCommandLine.clear();
  497. this->TestResult.CompletionStatus = "Unable to find executable";
  498. this->TestResult.Status = cmCTestTestHandler::NOT_RUN;
  499. return false;
  500. }
  501. this->StartTime = this->CTest->CurrentTime();
  502. auto timeout = this->ResolveTimeout();
  503. if (this->StopTimePassed) {
  504. return false;
  505. }
  506. return this->ForkProcess(timeout, this->TestProperties->ExplicitTimeout,
  507. &this->TestProperties->Environment);
  508. }
  509. void cmCTestRunTest::ComputeArguments()
  510. {
  511. this->Arguments.clear(); // reset becaue this might be a rerun
  512. std::vector<std::string>::const_iterator j =
  513. this->TestProperties->Args.begin();
  514. ++j; // skip test name
  515. // find the test executable
  516. if (this->TestHandler->MemCheck) {
  517. cmCTestMemCheckHandler* handler =
  518. static_cast<cmCTestMemCheckHandler*>(this->TestHandler);
  519. this->ActualCommand = handler->MemoryTester;
  520. this->TestProperties->Args[1] = this->TestHandler->FindTheExecutable(
  521. this->TestProperties->Args[1].c_str());
  522. } else {
  523. this->ActualCommand = this->TestHandler->FindTheExecutable(
  524. this->TestProperties->Args[1].c_str());
  525. ++j; // skip the executable (it will be actualCommand)
  526. }
  527. std::string testCommand =
  528. cmSystemTools::ConvertToOutputPath(this->ActualCommand.c_str());
  529. // Prepends memcheck args to our command string
  530. this->TestHandler->GenerateTestCommand(this->Arguments, this->Index);
  531. for (std::string const& arg : this->Arguments) {
  532. testCommand += " \"";
  533. testCommand += arg;
  534. testCommand += "\"";
  535. }
  536. for (; j != this->TestProperties->Args.end(); ++j) {
  537. testCommand += " \"";
  538. testCommand += *j;
  539. testCommand += "\"";
  540. this->Arguments.push_back(*j);
  541. }
  542. this->TestResult.FullCommandLine = testCommand;
  543. // Print the test command in verbose mode
  544. cmCTestLog(this->CTest, HANDLER_VERBOSE_OUTPUT, std::endl
  545. << this->Index << ": "
  546. << (this->TestHandler->MemCheck ? "MemCheck" : "Test")
  547. << " command: " << testCommand << std::endl);
  548. // Print any test-specific env vars in verbose mode
  549. if (!this->TestProperties->Environment.empty()) {
  550. cmCTestLog(this->CTest, HANDLER_VERBOSE_OUTPUT, this->Index
  551. << ": "
  552. << "Environment variables: " << std::endl);
  553. }
  554. for (std::string const& env : this->TestProperties->Environment) {
  555. cmCTestLog(this->CTest, HANDLER_VERBOSE_OUTPUT, this->Index << ": " << env
  556. << std::endl);
  557. }
  558. }
  559. void cmCTestRunTest::DartProcessing()
  560. {
  561. if (!this->ProcessOutput.empty() &&
  562. this->ProcessOutput.find("<DartMeasurement") != std::string::npos) {
  563. if (this->TestHandler->DartStuff.find(this->ProcessOutput.c_str())) {
  564. this->TestResult.DartString = this->TestHandler->DartStuff.match(1);
  565. // keep searching and replacing until none are left
  566. while (this->TestHandler->DartStuff1.find(this->ProcessOutput.c_str())) {
  567. // replace the exact match for the string
  568. cmSystemTools::ReplaceString(
  569. this->ProcessOutput, this->TestHandler->DartStuff1.match(1).c_str(),
  570. "");
  571. }
  572. }
  573. }
  574. }
  575. std::chrono::duration<double> cmCTestRunTest::ResolveTimeout()
  576. {
  577. auto timeout = this->TestProperties->Timeout;
  578. if (this->CTest->GetStopTime().empty()) {
  579. return timeout;
  580. }
  581. struct tm* lctime;
  582. time_t current_time = time(nullptr);
  583. lctime = gmtime(&current_time);
  584. int gm_hour = lctime->tm_hour;
  585. time_t gm_time = mktime(lctime);
  586. lctime = localtime(&current_time);
  587. int local_hour = lctime->tm_hour;
  588. int tzone_offset = local_hour - gm_hour;
  589. if (gm_time > current_time && gm_hour < local_hour) {
  590. // this means gm_time is on the next day
  591. tzone_offset -= 24;
  592. } else if (gm_time < current_time && gm_hour > local_hour) {
  593. // this means gm_time is on the previous day
  594. tzone_offset += 24;
  595. }
  596. tzone_offset *= 100;
  597. char buf[1024];
  598. // add todays year day and month to the time in str because
  599. // curl_getdate no longer assumes the day is today
  600. sprintf(buf, "%d%02d%02d %s %+05i", lctime->tm_year + 1900,
  601. lctime->tm_mon + 1, lctime->tm_mday,
  602. this->CTest->GetStopTime().c_str(), tzone_offset);
  603. time_t stop_time_t = curl_getdate(buf, &current_time);
  604. if (stop_time_t == -1) {
  605. return timeout;
  606. }
  607. auto stop_time = std::chrono::system_clock::from_time_t(stop_time_t);
  608. // the stop time refers to the next day
  609. if (this->CTest->NextDayStopTime) {
  610. stop_time += std::chrono::hours(24);
  611. }
  612. auto stop_timeout =
  613. (stop_time - std::chrono::system_clock::from_time_t(current_time)) %
  614. std::chrono::hours(24);
  615. this->CTest->LastStopTimeout = stop_timeout;
  616. if (stop_timeout <= std::chrono::duration<double>::zero() ||
  617. stop_timeout > this->CTest->LastStopTimeout) {
  618. cmCTestLog(this->CTest, ERROR_MESSAGE, "The stop time has been passed. "
  619. "Stopping all tests."
  620. << std::endl);
  621. this->StopTimePassed = true;
  622. return std::chrono::duration<double>::zero();
  623. }
  624. return timeout == std::chrono::duration<double>::zero()
  625. ? stop_timeout
  626. : (timeout < stop_timeout ? timeout : stop_timeout);
  627. }
  628. bool cmCTestRunTest::ForkProcess(std::chrono::duration<double> testTimeOut,
  629. bool explicitTimeout,
  630. std::vector<std::string>* environment)
  631. {
  632. this->TestProcess = new cmProcess;
  633. this->TestProcess->SetId(this->Index);
  634. this->TestProcess->SetWorkingDirectory(
  635. this->TestProperties->Directory.c_str());
  636. this->TestProcess->SetCommand(this->ActualCommand.c_str());
  637. this->TestProcess->SetCommandArguments(this->Arguments);
  638. // determine how much time we have
  639. std::chrono::duration<double> timeout =
  640. this->CTest->GetRemainingTimeAllowed();
  641. if (timeout != std::chrono::duration<double>::max()) {
  642. timeout -= std::chrono::minutes(2);
  643. }
  644. if (this->CTest->GetTimeOut() > std::chrono::duration<double>::zero() &&
  645. this->CTest->GetTimeOut() < timeout) {
  646. timeout = this->CTest->GetTimeOut();
  647. }
  648. if (testTimeOut > std::chrono::duration<double>::zero() &&
  649. testTimeOut < this->CTest->GetRemainingTimeAllowed()) {
  650. timeout = testTimeOut;
  651. }
  652. // always have at least 1 second if we got to here
  653. if (timeout <= std::chrono::duration<double>::zero()) {
  654. timeout = std::chrono::seconds(1);
  655. }
  656. // handle timeout explicitly set to 0
  657. if (testTimeOut == std::chrono::duration<double>::zero() &&
  658. explicitTimeout) {
  659. timeout = std::chrono::duration<double>::zero();
  660. }
  661. cmCTestOptionalLog(
  662. this->CTest, HANDLER_VERBOSE_OUTPUT, this->Index
  663. << ": "
  664. << "Test timeout computed to be: "
  665. << (timeout == std::chrono::duration<double>::max()
  666. ? std::string("infinite")
  667. : std::to_string(
  668. std::chrono::duration_cast<std::chrono::seconds>(timeout)
  669. .count()))
  670. << "\n",
  671. this->TestHandler->GetQuiet());
  672. this->TestProcess->SetTimeout(timeout);
  673. #ifdef CMAKE_BUILD_WITH_CMAKE
  674. cmSystemTools::SaveRestoreEnvironment sre;
  675. #endif
  676. if (environment && !environment->empty()) {
  677. cmSystemTools::AppendEnv(*environment);
  678. }
  679. return this->TestProcess->StartProcess();
  680. }
  681. void cmCTestRunTest::WriteLogOutputTop(size_t completed, size_t total)
  682. {
  683. // if this is the last or only run of this test
  684. // then print out completed / total
  685. // Only issue is if a test fails and we are running until fail
  686. // then it will never print out the completed / total, same would
  687. // got for run until pass. Trick is when this is called we don't
  688. // yet know if we are passing or failing.
  689. if (this->NumberOfRunsLeft == 1) {
  690. cmCTestLog(this->CTest, HANDLER_OUTPUT, std::setw(getNumWidth(total))
  691. << completed << "/");
  692. cmCTestLog(this->CTest, HANDLER_OUTPUT, std::setw(getNumWidth(total))
  693. << total << " ");
  694. }
  695. // if this is one of several runs of a test just print blank space
  696. // to keep things neat
  697. else {
  698. cmCTestLog(this->CTest, HANDLER_OUTPUT, std::setw(getNumWidth(total))
  699. << " "
  700. << " ");
  701. cmCTestLog(this->CTest, HANDLER_OUTPUT, std::setw(getNumWidth(total))
  702. << " "
  703. << " ");
  704. }
  705. if (this->TestHandler->MemCheck) {
  706. cmCTestLog(this->CTest, HANDLER_OUTPUT, "MemCheck");
  707. } else {
  708. cmCTestLog(this->CTest, HANDLER_OUTPUT, "Test");
  709. }
  710. std::ostringstream indexStr;
  711. indexStr << " #" << this->Index << ":";
  712. cmCTestLog(this->CTest, HANDLER_OUTPUT,
  713. std::setw(3 + getNumWidth(this->TestHandler->GetMaxIndex()))
  714. << indexStr.str());
  715. cmCTestLog(this->CTest, HANDLER_OUTPUT, " ");
  716. const int maxTestNameWidth = this->CTest->GetMaxTestNameWidth();
  717. std::string outname = this->TestProperties->Name + " ";
  718. outname.resize(maxTestNameWidth + 4, '.');
  719. *this->TestHandler->LogFile << this->TestProperties->Index << "/"
  720. << this->TestHandler->TotalNumberOfTests
  721. << " Testing: " << this->TestProperties->Name
  722. << std::endl;
  723. *this->TestHandler->LogFile << this->TestProperties->Index << "/"
  724. << this->TestHandler->TotalNumberOfTests
  725. << " Test: " << this->TestProperties->Name
  726. << std::endl;
  727. *this->TestHandler->LogFile << "Command: \"" << this->ActualCommand << "\"";
  728. for (std::string const& arg : this->Arguments) {
  729. *this->TestHandler->LogFile << " \"" << arg << "\"";
  730. }
  731. *this->TestHandler->LogFile
  732. << std::endl
  733. << "Directory: " << this->TestProperties->Directory << std::endl
  734. << "\"" << this->TestProperties->Name
  735. << "\" start time: " << this->StartTime << std::endl;
  736. *this->TestHandler->LogFile
  737. << "Output:" << std::endl
  738. << "----------------------------------------------------------"
  739. << std::endl;
  740. *this->TestHandler->LogFile << this->ProcessOutput << "<end of output>"
  741. << std::endl;
  742. cmCTestLog(this->CTest, HANDLER_OUTPUT, outname.c_str());
  743. cmCTestLog(this->CTest, DEBUG, "Testing " << this->TestProperties->Name
  744. << " ... ");
  745. }