cmCTestRunTest.cxx 33 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920
  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 <algorithm>
  5. #include <chrono>
  6. #include <cstddef> // IWYU pragma: keep
  7. #include <cstdint>
  8. #include <cstdio>
  9. #include <cstring>
  10. #include <iomanip>
  11. #include <ratio>
  12. #include <sstream>
  13. #include <utility>
  14. #include <cm/memory>
  15. #include "cmsys/RegularExpression.hxx"
  16. #include "cmCTest.h"
  17. #include "cmCTestMemCheckHandler.h"
  18. #include "cmCTestMultiProcessHandler.h"
  19. #include "cmProcess.h"
  20. #include "cmStringAlgorithms.h"
  21. #include "cmSystemTools.h"
  22. #include "cmWorkingDirectory.h"
  23. cmCTestRunTest::cmCTestRunTest(cmCTestMultiProcessHandler& multiHandler)
  24. : MultiTestHandler(multiHandler)
  25. {
  26. this->CTest = multiHandler.CTest;
  27. this->TestHandler = multiHandler.TestHandler;
  28. this->TestResult.ExecutionTime = cmDuration::zero();
  29. this->TestResult.ReturnValue = 0;
  30. this->TestResult.Status = cmCTestTestHandler::NOT_RUN;
  31. this->TestResult.TestCount = 0;
  32. this->TestResult.Properties = nullptr;
  33. }
  34. void cmCTestRunTest::CheckOutput(std::string const& line)
  35. {
  36. cmCTestLog(this->CTest, HANDLER_VERBOSE_OUTPUT,
  37. this->GetIndex() << ": " << line << std::endl);
  38. // Check for special CTest XML tags in this line of output.
  39. // If any are found, this line is excluded from ProcessOutput.
  40. if (!line.empty() && line.find("<CTest") != std::string::npos) {
  41. bool ctest_tag_found = false;
  42. if (this->TestHandler->CustomCompletionStatusRegex.find(line)) {
  43. ctest_tag_found = true;
  44. this->TestResult.CustomCompletionStatus =
  45. this->TestHandler->CustomCompletionStatusRegex.match(1);
  46. cmCTestLog(this->CTest, HANDLER_VERBOSE_OUTPUT,
  47. this->GetIndex() << ": "
  48. << "Test Details changed to '"
  49. << this->TestResult.CustomCompletionStatus
  50. << "'" << std::endl);
  51. } else if (this->TestHandler->CustomLabelRegex.find(line)) {
  52. ctest_tag_found = true;
  53. auto label = this->TestHandler->CustomLabelRegex.match(1);
  54. auto& labels = this->TestProperties->Labels;
  55. if (std::find(labels.begin(), labels.end(), label) == labels.end()) {
  56. labels.push_back(label);
  57. std::sort(labels.begin(), labels.end());
  58. cmCTestLog(this->CTest, HANDLER_VERBOSE_OUTPUT,
  59. this->GetIndex()
  60. << ": "
  61. << "Test Label added: '" << label << "'" << std::endl);
  62. }
  63. }
  64. if (ctest_tag_found) {
  65. return;
  66. }
  67. }
  68. this->ProcessOutput += line;
  69. this->ProcessOutput += "\n";
  70. // Check for TIMEOUT_AFTER_MATCH property.
  71. if (!this->TestProperties->TimeoutRegularExpressions.empty()) {
  72. for (auto& reg : this->TestProperties->TimeoutRegularExpressions) {
  73. if (reg.first.find(this->ProcessOutput)) {
  74. cmCTestLog(this->CTest, HANDLER_VERBOSE_OUTPUT,
  75. this->GetIndex()
  76. << ": "
  77. << "Test timeout changed to "
  78. << std::chrono::duration_cast<std::chrono::seconds>(
  79. this->TestProperties->AlternateTimeout)
  80. .count()
  81. << std::endl);
  82. this->TestProcess->ResetStartTime();
  83. this->TestProcess->ChangeTimeout(
  84. this->TestProperties->AlternateTimeout);
  85. this->TestProperties->TimeoutRegularExpressions.clear();
  86. break;
  87. }
  88. }
  89. }
  90. }
  91. bool cmCTestRunTest::EndTest(size_t completed, size_t total, bool started)
  92. {
  93. this->WriteLogOutputTop(completed, total);
  94. std::string reason;
  95. bool passed = true;
  96. cmProcess::State res =
  97. started ? this->TestProcess->GetProcessStatus() : cmProcess::State::Error;
  98. if (res != cmProcess::State::Expired) {
  99. this->TimeoutIsForStopTime = false;
  100. }
  101. std::int64_t retVal = this->TestProcess->GetExitValue();
  102. bool forceFail = false;
  103. bool forceSkip = false;
  104. bool skipped = false;
  105. bool outputTestErrorsToConsole = false;
  106. if (!this->TestProperties->RequiredRegularExpressions.empty() &&
  107. this->FailedDependencies.empty()) {
  108. bool found = false;
  109. for (auto& pass : this->TestProperties->RequiredRegularExpressions) {
  110. if (pass.first.find(this->ProcessOutput)) {
  111. found = true;
  112. reason = cmStrCat("Required regular expression found. Regex=[",
  113. pass.second, ']');
  114. break;
  115. }
  116. }
  117. if (!found) {
  118. reason = "Required regular expression not found. Regex=[";
  119. for (auto& pass : this->TestProperties->RequiredRegularExpressions) {
  120. reason += pass.second;
  121. reason += "\n";
  122. }
  123. reason += "]";
  124. forceFail = true;
  125. }
  126. }
  127. if (!this->TestProperties->ErrorRegularExpressions.empty() &&
  128. this->FailedDependencies.empty()) {
  129. for (auto& fail : this->TestProperties->ErrorRegularExpressions) {
  130. if (fail.first.find(this->ProcessOutput)) {
  131. reason = cmStrCat("Error regular expression found in output. Regex=[",
  132. fail.second, ']');
  133. forceFail = true;
  134. break;
  135. }
  136. }
  137. }
  138. if (!this->TestProperties->SkipRegularExpressions.empty() &&
  139. this->FailedDependencies.empty()) {
  140. for (auto& skip : this->TestProperties->SkipRegularExpressions) {
  141. if (skip.first.find(this->ProcessOutput)) {
  142. reason = cmStrCat("Skip regular expression found in output. Regex=[",
  143. skip.second, ']');
  144. forceSkip = true;
  145. break;
  146. }
  147. }
  148. }
  149. std::ostringstream outputStream;
  150. if (res == cmProcess::State::Exited) {
  151. bool success = !forceFail &&
  152. (retVal == 0 ||
  153. !this->TestProperties->RequiredRegularExpressions.empty());
  154. if ((this->TestProperties->SkipReturnCode >= 0 &&
  155. this->TestProperties->SkipReturnCode == retVal) ||
  156. forceSkip) {
  157. this->TestResult.Status = cmCTestTestHandler::NOT_RUN;
  158. std::ostringstream s;
  159. if (forceSkip) {
  160. s << "SKIP_REGULAR_EXPRESSION_MATCHED";
  161. } else {
  162. s << "SKIP_RETURN_CODE=" << this->TestProperties->SkipReturnCode;
  163. }
  164. this->TestResult.CompletionStatus = s.str();
  165. outputStream << "***Skipped ";
  166. skipped = true;
  167. } else if (success != this->TestProperties->WillFail) {
  168. this->TestResult.Status = cmCTestTestHandler::COMPLETED;
  169. outputStream << " Passed ";
  170. } else {
  171. this->TestResult.Status = cmCTestTestHandler::FAILED;
  172. outputStream << "***Failed " << reason;
  173. outputTestErrorsToConsole =
  174. this->CTest->GetOutputTestOutputOnTestFailure();
  175. }
  176. } else if (res == cmProcess::State::Expired) {
  177. outputStream << "***Timeout ";
  178. this->TestResult.Status = cmCTestTestHandler::TIMEOUT;
  179. outputTestErrorsToConsole =
  180. this->CTest->GetOutputTestOutputOnTestFailure();
  181. } else if (res == cmProcess::State::Exception) {
  182. outputTestErrorsToConsole =
  183. this->CTest->GetOutputTestOutputOnTestFailure();
  184. outputStream << "***Exception: ";
  185. this->TestResult.ExceptionStatus =
  186. this->TestProcess->GetExitExceptionString();
  187. switch (this->TestProcess->GetExitException()) {
  188. case cmProcess::Exception::Fault:
  189. outputStream << "SegFault";
  190. this->TestResult.Status = cmCTestTestHandler::SEGFAULT;
  191. break;
  192. case cmProcess::Exception::Illegal:
  193. outputStream << "Illegal";
  194. this->TestResult.Status = cmCTestTestHandler::ILLEGAL;
  195. break;
  196. case cmProcess::Exception::Interrupt:
  197. outputStream << "Interrupt";
  198. this->TestResult.Status = cmCTestTestHandler::INTERRUPT;
  199. break;
  200. case cmProcess::Exception::Numerical:
  201. outputStream << "Numerical";
  202. this->TestResult.Status = cmCTestTestHandler::NUMERICAL;
  203. break;
  204. default:
  205. cmCTestLog(this->CTest, HANDLER_OUTPUT,
  206. this->TestResult.ExceptionStatus);
  207. this->TestResult.Status = cmCTestTestHandler::OTHER_FAULT;
  208. }
  209. } else if ("Disabled" == this->TestResult.CompletionStatus) {
  210. outputStream << "***Not Run (Disabled) ";
  211. } else // cmProcess::State::Error
  212. {
  213. outputStream << "***Not Run ";
  214. }
  215. passed = this->TestResult.Status == cmCTestTestHandler::COMPLETED;
  216. char buf[1024];
  217. sprintf(buf, "%6.2f sec", this->TestProcess->GetTotalTime().count());
  218. outputStream << buf << "\n";
  219. bool passedOrSkipped = passed || skipped;
  220. if (this->CTest->GetTestProgressOutput()) {
  221. if (!passedOrSkipped) {
  222. // If the test did not pass, reprint test name and error
  223. std::string output = this->GetTestPrefix(completed, total);
  224. std::string testName = this->TestProperties->Name;
  225. const int maxTestNameWidth = this->CTest->GetMaxTestNameWidth();
  226. testName.resize(maxTestNameWidth + 4, '.');
  227. output += testName;
  228. output += outputStream.str();
  229. outputStream.str("");
  230. outputStream.clear();
  231. outputStream << output;
  232. cmCTestLog(this->CTest, HANDLER_TEST_PROGRESS_OUTPUT, "\n"); // flush
  233. }
  234. if (completed == total) {
  235. std::string testName = this->GetTestPrefix(completed, total) +
  236. this->TestProperties->Name + "\n";
  237. cmCTestLog(this->CTest, HANDLER_TEST_PROGRESS_OUTPUT, testName);
  238. }
  239. }
  240. if (!this->CTest->GetTestProgressOutput() || !passedOrSkipped) {
  241. cmCTestLog(this->CTest, HANDLER_OUTPUT, outputStream.str());
  242. }
  243. if (outputTestErrorsToConsole) {
  244. cmCTestLog(this->CTest, HANDLER_OUTPUT, this->ProcessOutput << std::endl);
  245. }
  246. if (this->TestHandler->LogFile) {
  247. *this->TestHandler->LogFile << "Test time = " << buf << std::endl;
  248. }
  249. this->ParseOutputForMeasurements();
  250. // if this is doing MemCheck then all the output needs to be put into
  251. // Output since that is what is parsed by cmCTestMemCheckHandler
  252. if (!this->TestHandler->MemCheck && started) {
  253. this->TestHandler->CleanTestOutput(
  254. this->ProcessOutput,
  255. static_cast<size_t>(
  256. this->TestResult.Status == cmCTestTestHandler::COMPLETED
  257. ? this->TestHandler->CustomMaximumPassedTestOutputSize
  258. : this->TestHandler->CustomMaximumFailedTestOutputSize));
  259. }
  260. this->TestResult.Reason = reason;
  261. if (this->TestHandler->LogFile) {
  262. bool pass = true;
  263. const char* reasonType = "Test Pass Reason";
  264. if (this->TestResult.Status != cmCTestTestHandler::COMPLETED &&
  265. this->TestResult.Status != cmCTestTestHandler::NOT_RUN) {
  266. reasonType = "Test Fail Reason";
  267. pass = false;
  268. }
  269. auto ttime = this->TestProcess->GetTotalTime();
  270. auto hours = std::chrono::duration_cast<std::chrono::hours>(ttime);
  271. ttime -= hours;
  272. auto minutes = std::chrono::duration_cast<std::chrono::minutes>(ttime);
  273. ttime -= minutes;
  274. auto seconds = std::chrono::duration_cast<std::chrono::seconds>(ttime);
  275. char buffer[100];
  276. sprintf(buffer, "%02d:%02d:%02d", static_cast<unsigned>(hours.count()),
  277. static_cast<unsigned>(minutes.count()),
  278. static_cast<unsigned>(seconds.count()));
  279. *this->TestHandler->LogFile
  280. << "----------------------------------------------------------"
  281. << std::endl;
  282. if (!this->TestResult.Reason.empty()) {
  283. *this->TestHandler->LogFile << reasonType << ":\n"
  284. << this->TestResult.Reason << "\n";
  285. } else {
  286. if (pass) {
  287. *this->TestHandler->LogFile << "Test Passed.\n";
  288. } else {
  289. *this->TestHandler->LogFile << "Test Failed.\n";
  290. }
  291. }
  292. *this->TestHandler->LogFile
  293. << "\"" << this->TestProperties->Name
  294. << "\" end time: " << this->CTest->CurrentTime() << std::endl
  295. << "\"" << this->TestProperties->Name << "\" time elapsed: " << buffer
  296. << std::endl
  297. << "----------------------------------------------------------"
  298. << std::endl
  299. << std::endl;
  300. }
  301. // if the test actually started and ran
  302. // record the results in TestResult
  303. if (started) {
  304. std::string compressedOutput;
  305. if (!this->TestHandler->MemCheck &&
  306. this->CTest->ShouldCompressTestOutput()) {
  307. std::string str = this->ProcessOutput;
  308. if (this->CTest->CompressString(str)) {
  309. compressedOutput = std::move(str);
  310. }
  311. }
  312. bool compress = !compressedOutput.empty() &&
  313. compressedOutput.length() < this->ProcessOutput.length();
  314. this->TestResult.Output =
  315. compress ? compressedOutput : this->ProcessOutput;
  316. this->TestResult.CompressOutput = compress;
  317. this->TestResult.ReturnValue = this->TestProcess->GetExitValue();
  318. if (!skipped) {
  319. this->TestResult.CompletionStatus = "Completed";
  320. }
  321. this->TestResult.ExecutionTime = this->TestProcess->GetTotalTime();
  322. this->MemCheckPostProcess();
  323. this->ComputeWeightedCost();
  324. }
  325. // If the test does not need to rerun push the current TestResult onto the
  326. // TestHandler vector
  327. if (!this->NeedsToRepeat()) {
  328. this->TestHandler->TestResults.push_back(this->TestResult);
  329. }
  330. this->TestProcess.reset();
  331. return passed || skipped;
  332. }
  333. bool cmCTestRunTest::StartAgain(std::unique_ptr<cmCTestRunTest> runner,
  334. size_t completed)
  335. {
  336. auto* testRun = runner.get();
  337. if (!testRun->RunAgain) {
  338. return false;
  339. }
  340. testRun->RunAgain = false; // reset
  341. testRun->TestProcess = cm::make_unique<cmProcess>(std::move(runner));
  342. // change to tests directory
  343. cmWorkingDirectory workdir(testRun->TestProperties->Directory);
  344. if (workdir.Failed()) {
  345. testRun->StartFailure("Failed to change working directory to " +
  346. testRun->TestProperties->Directory + " : " +
  347. std::strerror(workdir.GetLastResult()),
  348. "Failed to change working directory");
  349. return true;
  350. }
  351. testRun->StartTest(completed, testRun->TotalNumberOfTests);
  352. return true;
  353. }
  354. bool cmCTestRunTest::NeedsToRepeat()
  355. {
  356. this->NumberOfRunsLeft--;
  357. if (this->NumberOfRunsLeft == 0) {
  358. return false;
  359. }
  360. // If a test is marked as NOT_RUN it will not be repeated
  361. // no matter the repeat settings, so just record it as-is.
  362. if (this->TestResult.Status == cmCTestTestHandler::NOT_RUN) {
  363. return false;
  364. }
  365. // if number of runs left is not 0, and we are running until
  366. // we find a failed (or passed) test, then return true so the test can be
  367. // restarted
  368. if ((this->RepeatMode == cmCTest::Repeat::UntilFail &&
  369. this->TestResult.Status == cmCTestTestHandler::COMPLETED) ||
  370. (this->RepeatMode == cmCTest::Repeat::UntilPass &&
  371. this->TestResult.Status != cmCTestTestHandler::COMPLETED) ||
  372. (this->RepeatMode == cmCTest::Repeat::AfterTimeout &&
  373. this->TestResult.Status == cmCTestTestHandler::TIMEOUT)) {
  374. this->RunAgain = true;
  375. return true;
  376. }
  377. return false;
  378. }
  379. void cmCTestRunTest::ComputeWeightedCost()
  380. {
  381. double prev = static_cast<double>(this->TestProperties->PreviousRuns);
  382. double avgcost = static_cast<double>(this->TestProperties->Cost);
  383. double current = this->TestResult.ExecutionTime.count();
  384. if (this->TestResult.Status == cmCTestTestHandler::COMPLETED) {
  385. this->TestProperties->Cost =
  386. static_cast<float>(((prev * avgcost) + current) / (prev + 1.0));
  387. this->TestProperties->PreviousRuns++;
  388. }
  389. }
  390. void cmCTestRunTest::MemCheckPostProcess()
  391. {
  392. if (!this->TestHandler->MemCheck) {
  393. return;
  394. }
  395. cmCTestOptionalLog(this->CTest, HANDLER_VERBOSE_OUTPUT,
  396. this->Index << ": process test output now: "
  397. << this->TestProperties->Name << " "
  398. << this->TestResult.Name << std::endl,
  399. this->TestHandler->GetQuiet());
  400. cmCTestMemCheckHandler* handler =
  401. static_cast<cmCTestMemCheckHandler*>(this->TestHandler);
  402. handler->PostProcessTest(this->TestResult, this->Index);
  403. }
  404. void cmCTestRunTest::StartFailure(std::unique_ptr<cmCTestRunTest> runner,
  405. std::string const& output,
  406. std::string const& detail)
  407. {
  408. auto* testRun = runner.get();
  409. testRun->TestProcess = cm::make_unique<cmProcess>(std::move(runner));
  410. testRun->StartFailure(output, detail);
  411. testRun->FinalizeTest(false);
  412. }
  413. void cmCTestRunTest::StartFailure(std::string const& output,
  414. std::string const& detail)
  415. {
  416. // Still need to log the Start message so the test summary records our
  417. // attempt to start this test
  418. if (!this->CTest->GetTestProgressOutput()) {
  419. cmCTestLog(this->CTest, HANDLER_OUTPUT,
  420. std::setw(2 * getNumWidth(this->TotalNumberOfTests) + 8)
  421. << "Start "
  422. << std::setw(getNumWidth(this->TestHandler->GetMaxIndex()))
  423. << this->TestProperties->Index << ": "
  424. << this->TestProperties->Name << std::endl);
  425. }
  426. this->ProcessOutput.clear();
  427. if (!output.empty()) {
  428. *this->TestHandler->LogFile << output << std::endl;
  429. cmCTestLog(this->CTest, ERROR_MESSAGE, output << std::endl);
  430. }
  431. this->TestResult.Properties = this->TestProperties;
  432. this->TestResult.ExecutionTime = cmDuration::zero();
  433. this->TestResult.CompressOutput = false;
  434. this->TestResult.ReturnValue = -1;
  435. this->TestResult.CompletionStatus = detail;
  436. this->TestResult.Status = cmCTestTestHandler::NOT_RUN;
  437. this->TestResult.TestCount = this->TestProperties->Index;
  438. this->TestResult.Name = this->TestProperties->Name;
  439. this->TestResult.Path = this->TestProperties->Directory;
  440. this->TestResult.Output = output;
  441. this->TestResult.FullCommandLine.clear();
  442. this->TestResult.Environment.clear();
  443. }
  444. std::string cmCTestRunTest::GetTestPrefix(size_t completed, size_t total) const
  445. {
  446. std::ostringstream outputStream;
  447. outputStream << std::setw(getNumWidth(total)) << completed << "/";
  448. outputStream << std::setw(getNumWidth(total)) << total << " ";
  449. if (this->TestHandler->MemCheck) {
  450. outputStream << "MemCheck";
  451. } else {
  452. outputStream << "Test";
  453. }
  454. std::ostringstream indexStr;
  455. indexStr << " #" << this->Index << ":";
  456. outputStream << std::setw(3 + getNumWidth(this->TestHandler->GetMaxIndex()))
  457. << indexStr.str();
  458. outputStream << " ";
  459. return outputStream.str();
  460. }
  461. bool cmCTestRunTest::StartTest(std::unique_ptr<cmCTestRunTest> runner,
  462. size_t completed, size_t total)
  463. {
  464. auto* testRun = runner.get();
  465. testRun->TestProcess = cm::make_unique<cmProcess>(std::move(runner));
  466. if (!testRun->StartTest(completed, total)) {
  467. testRun->FinalizeTest(false);
  468. return false;
  469. }
  470. return true;
  471. }
  472. // Starts the execution of a test. Returns once it has started
  473. bool cmCTestRunTest::StartTest(size_t completed, size_t total)
  474. {
  475. this->TotalNumberOfTests = total; // save for rerun case
  476. if (!this->CTest->GetTestProgressOutput()) {
  477. cmCTestLog(this->CTest, HANDLER_OUTPUT,
  478. std::setw(2 * getNumWidth(total) + 8)
  479. << "Start "
  480. << std::setw(getNumWidth(this->TestHandler->GetMaxIndex()))
  481. << this->TestProperties->Index << ": "
  482. << this->TestProperties->Name << std::endl);
  483. } else {
  484. std::string testName = this->GetTestPrefix(completed, total) +
  485. this->TestProperties->Name + "\n";
  486. cmCTestLog(this->CTest, HANDLER_TEST_PROGRESS_OUTPUT, testName);
  487. }
  488. this->ProcessOutput.clear();
  489. this->TestResult.Properties = this->TestProperties;
  490. this->TestResult.ExecutionTime = cmDuration::zero();
  491. this->TestResult.CompressOutput = false;
  492. this->TestResult.ReturnValue = -1;
  493. this->TestResult.TestCount = this->TestProperties->Index;
  494. this->TestResult.Name = this->TestProperties->Name;
  495. this->TestResult.Path = this->TestProperties->Directory;
  496. // Return immediately if test is disabled
  497. if (this->TestProperties->Disabled) {
  498. this->TestResult.CompletionStatus = "Disabled";
  499. this->TestResult.Status = cmCTestTestHandler::NOT_RUN;
  500. this->TestResult.Output = "Disabled";
  501. this->TestResult.FullCommandLine.clear();
  502. this->TestResult.Environment.clear();
  503. return false;
  504. }
  505. this->TestResult.CompletionStatus = "Failed to start";
  506. this->TestResult.Status = cmCTestTestHandler::BAD_COMMAND;
  507. // Check for failed fixture dependencies before we even look at the command
  508. // arguments because if we are not going to run the test, the command and
  509. // its arguments are irrelevant. This matters for the case where a fixture
  510. // dependency might be creating the executable we want to run.
  511. if (!this->FailedDependencies.empty()) {
  512. std::string msg = "Failed test dependencies:";
  513. for (std::string const& failedDep : this->FailedDependencies) {
  514. msg += " " + failedDep;
  515. }
  516. *this->TestHandler->LogFile << msg << std::endl;
  517. cmCTestLog(this->CTest, HANDLER_OUTPUT, msg << std::endl);
  518. this->TestResult.Output = msg;
  519. this->TestResult.FullCommandLine.clear();
  520. this->TestResult.Environment.clear();
  521. this->TestResult.CompletionStatus = "Fixture dependency failed";
  522. this->TestResult.Status = cmCTestTestHandler::NOT_RUN;
  523. return false;
  524. }
  525. this->ComputeArguments();
  526. std::vector<std::string>& args = this->TestProperties->Args;
  527. if (args.size() >= 2 && args[1] == "NOT_AVAILABLE") {
  528. std::string msg;
  529. if (this->CTest->GetConfigType().empty()) {
  530. msg = "Test not available without configuration. (Missing \"-C "
  531. "<config>\"?)";
  532. } else {
  533. msg = cmStrCat("Test not available in configuration \"",
  534. this->CTest->GetConfigType(), "\".");
  535. }
  536. *this->TestHandler->LogFile << msg << std::endl;
  537. cmCTestLog(this->CTest, ERROR_MESSAGE, msg << std::endl);
  538. this->TestResult.Output = msg;
  539. this->TestResult.FullCommandLine.clear();
  540. this->TestResult.Environment.clear();
  541. this->TestResult.CompletionStatus = "Missing Configuration";
  542. this->TestResult.Status = cmCTestTestHandler::NOT_RUN;
  543. return false;
  544. }
  545. // Check if all required files exist
  546. for (std::string const& file : this->TestProperties->RequiredFiles) {
  547. if (!cmSystemTools::FileExists(file)) {
  548. // Required file was not found
  549. *this->TestHandler->LogFile << "Unable to find required file: " << file
  550. << std::endl;
  551. cmCTestLog(this->CTest, ERROR_MESSAGE,
  552. "Unable to find required file: " << file << std::endl);
  553. this->TestResult.Output = "Unable to find required file: " + file;
  554. this->TestResult.FullCommandLine.clear();
  555. this->TestResult.Environment.clear();
  556. this->TestResult.CompletionStatus = "Required Files Missing";
  557. this->TestResult.Status = cmCTestTestHandler::NOT_RUN;
  558. return false;
  559. }
  560. }
  561. // log and return if we did not find the executable
  562. if (this->ActualCommand.empty()) {
  563. // if the command was not found create a TestResult object
  564. // that has that information
  565. *this->TestHandler->LogFile << "Unable to find executable: " << args[1]
  566. << std::endl;
  567. cmCTestLog(this->CTest, ERROR_MESSAGE,
  568. "Unable to find executable: " << args[1] << std::endl);
  569. this->TestResult.Output = "Unable to find executable: " + args[1];
  570. this->TestResult.FullCommandLine.clear();
  571. this->TestResult.Environment.clear();
  572. this->TestResult.CompletionStatus = "Unable to find executable";
  573. this->TestResult.Status = cmCTestTestHandler::NOT_RUN;
  574. return false;
  575. }
  576. this->StartTime = this->CTest->CurrentTime();
  577. auto timeout = this->TestProperties->Timeout;
  578. this->TimeoutIsForStopTime = false;
  579. std::chrono::system_clock::time_point stop_time = this->CTest->GetStopTime();
  580. if (stop_time != std::chrono::system_clock::time_point()) {
  581. std::chrono::duration<double> stop_timeout =
  582. (stop_time - std::chrono::system_clock::now()) % std::chrono::hours(24);
  583. if (stop_timeout <= std::chrono::duration<double>::zero()) {
  584. stop_timeout = std::chrono::duration<double>::zero();
  585. }
  586. if (timeout == std::chrono::duration<double>::zero() ||
  587. stop_timeout < timeout) {
  588. this->TimeoutIsForStopTime = true;
  589. timeout = stop_timeout;
  590. }
  591. }
  592. return this->ForkProcess(timeout, this->TestProperties->ExplicitTimeout,
  593. &this->TestProperties->Environment,
  594. &this->TestProperties->Affinity);
  595. }
  596. void cmCTestRunTest::ComputeArguments()
  597. {
  598. this->Arguments.clear(); // reset because this might be a rerun
  599. auto j = this->TestProperties->Args.begin();
  600. ++j; // skip test name
  601. // find the test executable
  602. if (this->TestHandler->MemCheck) {
  603. cmCTestMemCheckHandler* handler =
  604. static_cast<cmCTestMemCheckHandler*>(this->TestHandler);
  605. this->ActualCommand = handler->MemoryTester;
  606. this->TestProperties->Args[1] =
  607. this->TestHandler->FindTheExecutable(this->TestProperties->Args[1]);
  608. } else {
  609. this->ActualCommand =
  610. this->TestHandler->FindTheExecutable(this->TestProperties->Args[1]);
  611. ++j; // skip the executable (it will be actualCommand)
  612. }
  613. std::string testCommand =
  614. cmSystemTools::ConvertToOutputPath(this->ActualCommand);
  615. // Prepends memcheck args to our command string
  616. this->TestHandler->GenerateTestCommand(this->Arguments, this->Index);
  617. for (std::string const& arg : this->Arguments) {
  618. testCommand += " \"";
  619. testCommand += arg;
  620. testCommand += "\"";
  621. }
  622. for (; j != this->TestProperties->Args.end(); ++j) {
  623. testCommand += " \"";
  624. testCommand += *j;
  625. testCommand += "\"";
  626. this->Arguments.push_back(*j);
  627. }
  628. this->TestResult.FullCommandLine = testCommand;
  629. // Print the test command in verbose mode
  630. cmCTestLog(this->CTest, HANDLER_VERBOSE_OUTPUT,
  631. std::endl
  632. << this->Index << ": "
  633. << (this->TestHandler->MemCheck ? "MemCheck" : "Test")
  634. << " command: " << testCommand << std::endl);
  635. // Print any test-specific env vars in verbose mode
  636. if (!this->TestProperties->Environment.empty()) {
  637. cmCTestLog(this->CTest, HANDLER_VERBOSE_OUTPUT,
  638. this->Index << ": "
  639. << "Environment variables: " << std::endl);
  640. }
  641. for (std::string const& env : this->TestProperties->Environment) {
  642. cmCTestLog(this->CTest, HANDLER_VERBOSE_OUTPUT,
  643. this->Index << ": " << env << std::endl);
  644. }
  645. }
  646. void cmCTestRunTest::ParseOutputForMeasurements()
  647. {
  648. if (!this->ProcessOutput.empty() &&
  649. (this->ProcessOutput.find("<DartMeasurement") != std::string::npos ||
  650. this->ProcessOutput.find("<CTestMeasurement") != std::string::npos)) {
  651. if (this->TestHandler->AllTestMeasurementsRegex.find(
  652. this->ProcessOutput)) {
  653. this->TestResult.TestMeasurementsOutput =
  654. this->TestHandler->AllTestMeasurementsRegex.match(1);
  655. // keep searching and replacing until none are left
  656. while (this->TestHandler->SingleTestMeasurementRegex.find(
  657. this->ProcessOutput)) {
  658. // replace the exact match for the string
  659. cmSystemTools::ReplaceString(
  660. this->ProcessOutput,
  661. this->TestHandler->SingleTestMeasurementRegex.match(1).c_str(), "");
  662. }
  663. }
  664. }
  665. }
  666. bool cmCTestRunTest::ForkProcess(cmDuration testTimeOut, bool explicitTimeout,
  667. std::vector<std::string>* environment,
  668. std::vector<size_t>* affinity)
  669. {
  670. this->TestProcess->SetId(this->Index);
  671. this->TestProcess->SetWorkingDirectory(this->TestProperties->Directory);
  672. this->TestProcess->SetCommand(this->ActualCommand);
  673. this->TestProcess->SetCommandArguments(this->Arguments);
  674. // determine how much time we have
  675. cmDuration timeout = this->CTest->GetRemainingTimeAllowed();
  676. if (timeout != cmCTest::MaxDuration()) {
  677. timeout -= std::chrono::minutes(2);
  678. }
  679. if (this->CTest->GetTimeOut() > cmDuration::zero() &&
  680. this->CTest->GetTimeOut() < timeout) {
  681. timeout = this->CTest->GetTimeOut();
  682. }
  683. if (testTimeOut > cmDuration::zero() &&
  684. testTimeOut < this->CTest->GetRemainingTimeAllowed()) {
  685. timeout = testTimeOut;
  686. }
  687. // always have at least 1 second if we got to here
  688. if (timeout <= cmDuration::zero()) {
  689. timeout = std::chrono::seconds(1);
  690. }
  691. // handle timeout explicitly set to 0
  692. if (testTimeOut == cmDuration::zero() && explicitTimeout) {
  693. timeout = cmDuration::zero();
  694. }
  695. cmCTestOptionalLog(this->CTest, HANDLER_VERBOSE_OUTPUT,
  696. this->Index << ": "
  697. << "Test timeout computed to be: "
  698. << cmDurationTo<unsigned int>(timeout)
  699. << "\n",
  700. this->TestHandler->GetQuiet());
  701. this->TestProcess->SetTimeout(timeout);
  702. #ifndef CMAKE_BOOTSTRAP
  703. cmSystemTools::SaveRestoreEnvironment sre;
  704. #endif
  705. std::ostringstream envMeasurement;
  706. if (environment && !environment->empty()) {
  707. cmSystemTools::AppendEnv(*environment);
  708. for (auto const& var : *environment) {
  709. envMeasurement << var << std::endl;
  710. }
  711. }
  712. if (this->UseAllocatedResources) {
  713. std::vector<std::string> envLog;
  714. this->SetupResourcesEnvironment(&envLog);
  715. for (auto const& var : envLog) {
  716. envMeasurement << var << std::endl;
  717. }
  718. } else {
  719. cmSystemTools::UnsetEnv("CTEST_RESOURCE_GROUP_COUNT");
  720. // Signify that this variable is being actively unset
  721. envMeasurement << "#CTEST_RESOURCE_GROUP_COUNT=" << std::endl;
  722. }
  723. this->TestResult.Environment = envMeasurement.str();
  724. // Remove last newline
  725. this->TestResult.Environment.erase(this->TestResult.Environment.length() -
  726. 1);
  727. return this->TestProcess->StartProcess(this->MultiTestHandler.Loop,
  728. affinity);
  729. }
  730. void cmCTestRunTest::SetupResourcesEnvironment(std::vector<std::string>* log)
  731. {
  732. std::string processCount = "CTEST_RESOURCE_GROUP_COUNT=";
  733. processCount += std::to_string(this->AllocatedResources.size());
  734. cmSystemTools::PutEnv(processCount);
  735. if (log) {
  736. log->push_back(processCount);
  737. }
  738. std::size_t i = 0;
  739. for (auto const& process : this->AllocatedResources) {
  740. std::string prefix = "CTEST_RESOURCE_GROUP_";
  741. prefix += std::to_string(i);
  742. std::string resourceList = prefix + '=';
  743. prefix += '_';
  744. bool firstType = true;
  745. for (auto const& it : process) {
  746. if (!firstType) {
  747. resourceList += ',';
  748. }
  749. firstType = false;
  750. auto resourceType = it.first;
  751. resourceList += resourceType;
  752. std::string var = prefix + cmSystemTools::UpperCase(resourceType) + '=';
  753. bool firstName = true;
  754. for (auto const& it2 : it.second) {
  755. if (!firstName) {
  756. var += ';';
  757. }
  758. firstName = false;
  759. var += "id:" + it2.Id + ",slots:" + std::to_string(it2.Slots);
  760. }
  761. cmSystemTools::PutEnv(var);
  762. if (log) {
  763. log->push_back(var);
  764. }
  765. }
  766. cmSystemTools::PutEnv(resourceList);
  767. if (log) {
  768. log->push_back(resourceList);
  769. }
  770. ++i;
  771. }
  772. }
  773. void cmCTestRunTest::WriteLogOutputTop(size_t completed, size_t total)
  774. {
  775. std::ostringstream outputStream;
  776. // If this is the last or only run of this test, or progress output is
  777. // requested, then print out completed / total.
  778. // Only issue is if a test fails and we are running until fail
  779. // then it will never print out the completed / total, same would
  780. // got for run until pass. Trick is when this is called we don't
  781. // yet know if we are passing or failing.
  782. bool const progressOnLast =
  783. (this->RepeatMode != cmCTest::Repeat::UntilPass &&
  784. this->RepeatMode != cmCTest::Repeat::AfterTimeout);
  785. if ((progressOnLast && this->NumberOfRunsLeft == 1) ||
  786. (!progressOnLast && this->NumberOfRunsLeft == this->NumberOfRunsTotal) ||
  787. this->CTest->GetTestProgressOutput()) {
  788. outputStream << std::setw(getNumWidth(total)) << completed << "/";
  789. outputStream << std::setw(getNumWidth(total)) << total << " ";
  790. }
  791. // if this is one of several runs of a test just print blank space
  792. // to keep things neat
  793. else {
  794. outputStream << std::setw(getNumWidth(total)) << " ";
  795. outputStream << std::setw(getNumWidth(total)) << " ";
  796. }
  797. if (this->TestHandler->MemCheck) {
  798. outputStream << "MemCheck";
  799. } else {
  800. outputStream << "Test";
  801. }
  802. std::ostringstream indexStr;
  803. indexStr << " #" << this->Index << ":";
  804. outputStream << std::setw(3 + getNumWidth(this->TestHandler->GetMaxIndex()))
  805. << indexStr.str();
  806. outputStream << " ";
  807. const int maxTestNameWidth = this->CTest->GetMaxTestNameWidth();
  808. std::string outname = this->TestProperties->Name + " ";
  809. outname.resize(maxTestNameWidth + 4, '.');
  810. outputStream << outname;
  811. *this->TestHandler->LogFile << this->TestProperties->Index << "/"
  812. << this->TestHandler->TotalNumberOfTests
  813. << " Testing: " << this->TestProperties->Name
  814. << std::endl;
  815. *this->TestHandler->LogFile << this->TestProperties->Index << "/"
  816. << this->TestHandler->TotalNumberOfTests
  817. << " Test: " << this->TestProperties->Name
  818. << std::endl;
  819. *this->TestHandler->LogFile << "Command: \"" << this->ActualCommand << "\"";
  820. for (std::string const& arg : this->Arguments) {
  821. *this->TestHandler->LogFile << " \"" << arg << "\"";
  822. }
  823. *this->TestHandler->LogFile
  824. << std::endl
  825. << "Directory: " << this->TestProperties->Directory << std::endl
  826. << "\"" << this->TestProperties->Name
  827. << "\" start time: " << this->StartTime << std::endl;
  828. *this->TestHandler->LogFile
  829. << "Output:" << std::endl
  830. << "----------------------------------------------------------"
  831. << std::endl;
  832. *this->TestHandler->LogFile << this->ProcessOutput << "<end of output>"
  833. << std::endl;
  834. if (!this->CTest->GetTestProgressOutput()) {
  835. cmCTestLog(this->CTest, HANDLER_OUTPUT, outputStream.str());
  836. }
  837. cmCTestLog(this->CTest, DEBUG,
  838. "Testing " << this->TestProperties->Name << " ... ");
  839. }
  840. void cmCTestRunTest::FinalizeTest(bool started)
  841. {
  842. this->MultiTestHandler.FinishTestProcess(this->TestProcess->GetRunner(),
  843. started);
  844. }