cmCTestRunTest.cxx 32 KB

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