cmCTestRunTest.cxx 39 KB

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