cmCTestRunTest.cxx 29 KB

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