cmCTestRunTest.cxx 33 KB

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