cmCTestRunTest.cxx 37 KB

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