cmCTestTestHandler.cxx 87 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626
  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 "cmCTestTestHandler.h"
  4. #include <algorithm>
  5. #include <chrono>
  6. #include <cmath>
  7. #include <cstddef> // IWYU pragma: keep
  8. #include <cstdio>
  9. #include <cstdlib>
  10. #include <ctime>
  11. #include <functional>
  12. #include <iomanip>
  13. #include <iterator>
  14. #include <ratio>
  15. #include <set>
  16. #include <sstream>
  17. #include <utility>
  18. #ifndef _WIN32
  19. # include <csignal>
  20. #endif
  21. #include <cm/memory>
  22. #include <cm/string_view>
  23. #include <cmext/algorithm>
  24. #include <cmext/string_view>
  25. #include "cmsys/FStream.hxx"
  26. #include <cmsys/Base64.h>
  27. #include <cmsys/Directory.hxx>
  28. #include <cmsys/RegularExpression.hxx>
  29. #include "cm_utf8.h"
  30. #include "cmCTest.h"
  31. #include "cmCTestMultiProcessHandler.h"
  32. #include "cmCTestResourceGroupsLexerHelper.h"
  33. #include "cmCTestTestMeasurementXMLParser.h"
  34. #include "cmDuration.h"
  35. #include "cmExecutionStatus.h"
  36. #include "cmGeneratedFileStream.h"
  37. #include "cmGlobalGenerator.h"
  38. #include "cmInstrumentation.h"
  39. #include "cmInstrumentationQuery.h"
  40. #include "cmList.h"
  41. #include "cmMakefile.h"
  42. #include "cmState.h"
  43. #include "cmStateSnapshot.h"
  44. #include "cmStringAlgorithms.h"
  45. #include "cmSystemTools.h"
  46. #include "cmTimestamp.h"
  47. #include "cmValue.h"
  48. #include "cmWorkingDirectory.h"
  49. #include "cmXMLWriter.h"
  50. #include "cmake.h"
  51. namespace {
  52. class cmCTestCommand
  53. {
  54. public:
  55. cmCTestCommand(cmCTestTestHandler* testHandler)
  56. : TestHandler(testHandler)
  57. {
  58. }
  59. virtual ~cmCTestCommand() = default;
  60. cmCTestCommand(cmCTestCommand const&) = default;
  61. cmCTestCommand& operator=(cmCTestCommand const&) = default;
  62. bool operator()(std::vector<cmListFileArgument> const& args,
  63. cmExecutionStatus& status)
  64. {
  65. cmMakefile& mf = status.GetMakefile();
  66. std::vector<std::string> expandedArguments;
  67. if (!mf.ExpandArguments(args, expandedArguments)) {
  68. // There was an error expanding arguments. It was already
  69. // reported, so we can skip this command without error.
  70. return true;
  71. }
  72. return this->InitialPass(expandedArguments, status);
  73. }
  74. virtual bool InitialPass(std::vector<std::string> const& args,
  75. cmExecutionStatus& status) = 0;
  76. cmCTestTestHandler* TestHandler;
  77. };
  78. bool ReadSubdirectory(std::string fname, cmExecutionStatus& status)
  79. {
  80. if (!cmSystemTools::FileExists(fname)) {
  81. // No subdirectory? So what...
  82. return true;
  83. }
  84. bool readit = false;
  85. {
  86. cmWorkingDirectory workdir(fname);
  87. if (workdir.Failed()) {
  88. status.SetError(workdir.GetError());
  89. return false;
  90. }
  91. char const* testFilename;
  92. if (cmSystemTools::FileExists("CTestTestfile.cmake")) {
  93. // does the CTestTestfile.cmake exist ?
  94. testFilename = "CTestTestfile.cmake";
  95. } else if (cmSystemTools::FileExists("DartTestfile.txt")) {
  96. // does the DartTestfile.txt exist ?
  97. testFilename = "DartTestfile.txt";
  98. } else {
  99. // No CTestTestfile? Who cares...
  100. return true;
  101. }
  102. fname += "/";
  103. fname += testFilename;
  104. readit = status.GetMakefile().ReadDependentFile(fname);
  105. }
  106. if (!readit) {
  107. status.SetError(cmStrCat("Could not find include file: ", fname));
  108. return false;
  109. }
  110. return true;
  111. }
  112. bool cmCTestSubdirCommand(std::vector<std::string> const& args,
  113. cmExecutionStatus& status)
  114. {
  115. if (args.empty()) {
  116. status.SetError("called with incorrect number of arguments");
  117. return false;
  118. }
  119. std::string cwd = cmSystemTools::GetLogicalWorkingDirectory();
  120. for (std::string const& arg : args) {
  121. std::string fname;
  122. if (cmSystemTools::FileIsFullPath(arg)) {
  123. fname = arg;
  124. } else {
  125. fname = cmStrCat(cwd, '/', arg);
  126. }
  127. if (!ReadSubdirectory(std::move(fname), status)) {
  128. return false;
  129. }
  130. }
  131. return true;
  132. }
  133. bool cmCTestAddSubdirectoryCommand(std::vector<std::string> const& args,
  134. cmExecutionStatus& status)
  135. {
  136. if (args.empty()) {
  137. status.SetError("called with incorrect number of arguments");
  138. return false;
  139. }
  140. std::string fname =
  141. cmStrCat(cmSystemTools::GetLogicalWorkingDirectory(), '/', args[0]);
  142. return ReadSubdirectory(std::move(fname), status);
  143. }
  144. class cmCTestAddTestCommand : public cmCTestCommand
  145. {
  146. public:
  147. using cmCTestCommand::cmCTestCommand;
  148. /**
  149. * This is called when the command is first encountered in
  150. * the CMakeLists.txt file.
  151. */
  152. bool InitialPass(std::vector<std::string> const& /*args*/,
  153. cmExecutionStatus& /*unused*/) override;
  154. };
  155. bool cmCTestAddTestCommand::InitialPass(std::vector<std::string> const& args,
  156. cmExecutionStatus& status)
  157. {
  158. if (args.size() < 2) {
  159. status.SetError("called with incorrect number of arguments");
  160. return false;
  161. }
  162. return this->TestHandler->AddTest(args);
  163. }
  164. class cmCTestSetTestsPropertiesCommand : public cmCTestCommand
  165. {
  166. public:
  167. using cmCTestCommand::cmCTestCommand;
  168. /**
  169. * This is called when the command is first encountered in
  170. * the CMakeLists.txt file.
  171. */
  172. bool InitialPass(std::vector<std::string> const& /*args*/,
  173. cmExecutionStatus& /*unused*/) override;
  174. };
  175. bool cmCTestSetTestsPropertiesCommand::InitialPass(
  176. std::vector<std::string> const& args, cmExecutionStatus& /*unused*/)
  177. {
  178. return this->TestHandler->SetTestsProperties(args);
  179. }
  180. class cmCTestSetDirectoryPropertiesCommand : public cmCTestCommand
  181. {
  182. public:
  183. using cmCTestCommand::cmCTestCommand;
  184. /**
  185. * This is called when the command is first encountered in
  186. * the CMakeLists.txt file.
  187. */
  188. bool InitialPass(std::vector<std::string> const& /*unused*/,
  189. cmExecutionStatus& /*unused*/) override;
  190. };
  191. bool cmCTestSetDirectoryPropertiesCommand::InitialPass(
  192. std::vector<std::string> const& args, cmExecutionStatus&)
  193. {
  194. return this->TestHandler->SetDirectoryProperties(args);
  195. }
  196. // get the next number in a string with numbers separated by ,
  197. // pos is the start of the search and pos2 is the end of the search
  198. // pos becomes pos2 after a call to GetNextNumber.
  199. // -1 is returned at the end of the list.
  200. inline int GetNextNumber(std::string const& in, int& val,
  201. std::string::size_type& pos,
  202. std::string::size_type& pos2)
  203. {
  204. pos2 = in.find(',', pos);
  205. if (pos2 != std::string::npos) {
  206. if (pos2 - pos == 0) {
  207. val = -1;
  208. } else {
  209. val = atoi(in.substr(pos, pos2 - pos).c_str());
  210. }
  211. pos = pos2 + 1;
  212. return 1;
  213. }
  214. if (in.size() - pos == 0) {
  215. val = -1;
  216. } else {
  217. val = atoi(in.substr(pos, in.size() - pos).c_str());
  218. }
  219. return 0;
  220. }
  221. // get the next number in a string with numbers separated by ,
  222. // pos is the start of the search and pos2 is the end of the search
  223. // pos becomes pos2 after a call to GetNextNumber.
  224. // -1 is returned at the end of the list.
  225. inline int GetNextRealNumber(std::string const& in, double& val,
  226. std::string::size_type& pos,
  227. std::string::size_type& pos2)
  228. {
  229. pos2 = in.find(',', pos);
  230. if (pos2 != std::string::npos) {
  231. if (pos2 - pos == 0) {
  232. val = -1;
  233. } else {
  234. val = atof(in.substr(pos, pos2 - pos).c_str());
  235. }
  236. pos = pos2 + 1;
  237. return 1;
  238. }
  239. if (in.size() - pos == 0) {
  240. val = -1;
  241. } else {
  242. val = atof(in.substr(pos, in.size() - pos).c_str());
  243. }
  244. return 0;
  245. }
  246. } // namespace
  247. cmCTestTestHandler::cmCTestTestHandler(cmCTest* ctest)
  248. : Superclass(ctest)
  249. , TestOptions(ctest->GetTestOptions())
  250. {
  251. // Regular expressions to scan test output for custom measurements.
  252. // Capture the whole section of test output from the first opening
  253. // <(CTest|Dart)Measurement*> tag to the last </(CTest|Dart)Measurement*>
  254. // closing tag.
  255. this->AllTestMeasurementsRegex.compile(
  256. "(<(CTest|Dart)Measurement.*/(CTest|Dart)Measurement[a-zA-Z]*>)");
  257. // Capture a single <(CTest|Dart)Measurement*> XML element.
  258. this->SingleTestMeasurementRegex.compile(
  259. "(<(CTest|Dart)Measurement[^<]*</(CTest|Dart)Measurement[a-zA-Z]*>)");
  260. // Capture content from <CTestDetails>...</CTestDetails>
  261. this->CustomCompletionStatusRegex.compile(
  262. "<CTestDetails>(.*)</CTestDetails>");
  263. // Capture content from <CTestLabel>...</CTestLabel>
  264. this->CustomLabelRegex.compile("<CTestLabel>(.*)</CTestLabel>");
  265. }
  266. void cmCTestTestHandler::PopulateCustomVectors(cmMakefile* mf)
  267. {
  268. this->CTest->PopulateCustomVector(mf, "CTEST_CUSTOM_PRE_TEST",
  269. this->CustomPreTest);
  270. this->CTest->PopulateCustomVector(mf, "CTEST_CUSTOM_POST_TEST",
  271. this->CustomPostTest);
  272. this->CTest->PopulateCustomVector(mf, "CTEST_CUSTOM_TESTS_IGNORE",
  273. this->CustomTestsIgnore);
  274. this->CTest->PopulateCustomInteger(
  275. mf, "CTEST_CUSTOM_MAXIMUM_PASSED_TEST_OUTPUT_SIZE",
  276. this->TestOptions.OutputSizePassed);
  277. this->CTest->PopulateCustomInteger(
  278. mf, "CTEST_CUSTOM_MAXIMUM_FAILED_TEST_OUTPUT_SIZE",
  279. this->TestOptions.OutputSizeFailed);
  280. cmValue dval = mf->GetDefinition("CTEST_CUSTOM_TEST_OUTPUT_TRUNCATION");
  281. if (dval) {
  282. if (!SetTruncationMode(this->TestOptions.OutputTruncation, *dval)) {
  283. cmCTestLog(this->CTest, ERROR_MESSAGE,
  284. "Invalid value for CTEST_CUSTOM_TEST_OUTPUT_TRUNCATION: "
  285. << *dval << std::endl);
  286. }
  287. }
  288. }
  289. int cmCTestTestHandler::PreProcessHandler()
  290. {
  291. if (!this->ExecuteCommands(this->CustomPreTest)) {
  292. cmCTestLog(this->CTest, ERROR_MESSAGE,
  293. "Problem executing pre-test command(s)." << std::endl);
  294. return 0;
  295. }
  296. return 1;
  297. }
  298. int cmCTestTestHandler::PostProcessHandler()
  299. {
  300. if (!this->ExecuteCommands(this->CustomPostTest)) {
  301. cmCTestLog(this->CTest, ERROR_MESSAGE,
  302. "Problem executing post-test command(s)." << std::endl);
  303. return 0;
  304. }
  305. return 1;
  306. }
  307. int cmCTestTestHandler::ProcessHandler()
  308. {
  309. if (!this->ProcessOptions()) {
  310. return -1;
  311. }
  312. this->TestResults.clear();
  313. cmCTestOptionalLog(this->CTest, HANDLER_OUTPUT,
  314. (this->MemCheck ? "Memory check" : "Test")
  315. << " project "
  316. << cmSystemTools::GetLogicalWorkingDirectory()
  317. << std::endl,
  318. this->Quiet);
  319. if (!this->PreProcessHandler()) {
  320. return -1;
  321. }
  322. cmGeneratedFileStream mLogFile;
  323. this->StartLogFile((this->MemCheck ? "DynamicAnalysis" : "Test"), mLogFile);
  324. this->LogFile = &mLogFile;
  325. std::vector<std::string> passed;
  326. std::vector<std::string> failed;
  327. // start the real time clock
  328. auto clock_start = std::chrono::steady_clock::now();
  329. if (!this->ProcessDirectory(passed, failed)) {
  330. return -1;
  331. }
  332. auto clock_finish = std::chrono::steady_clock::now();
  333. bool noTestsFoundError = false;
  334. if (passed.size() + failed.size() == 0) {
  335. if (!this->CTest->GetShowOnly() && !this->CTest->ShouldPrintLabels() &&
  336. this->CTest->GetNoTestsMode() != cmCTest::NoTests::Ignore) {
  337. cmCTestLog(this->CTest, ERROR_MESSAGE,
  338. "No tests were found!!!" << std::endl);
  339. if (this->CTest->GetNoTestsMode() == cmCTest::NoTests::Error) {
  340. noTestsFoundError = true;
  341. }
  342. }
  343. } else {
  344. if (this->HandlerVerbose && !passed.empty() &&
  345. (this->UseIncludeRegExpFlag || this->UseExcludeRegExpFlag)) {
  346. cmCTestOptionalLog(this->CTest, HANDLER_VERBOSE_OUTPUT,
  347. std::endl
  348. << "The following tests passed:" << std::endl,
  349. this->Quiet);
  350. for (std::string const& j : passed) {
  351. cmCTestOptionalLog(this->CTest, HANDLER_VERBOSE_OUTPUT,
  352. "\t" << j << std::endl, this->Quiet);
  353. }
  354. }
  355. SetOfTests resultsSet(this->TestResults.begin(), this->TestResults.end());
  356. std::vector<cmCTestTestHandler::cmCTestTestResult> disabledTests;
  357. for (cmCTestTestResult const& ft : resultsSet) {
  358. if (cmHasLiteralPrefix(ft.CompletionStatus, "SKIP_") ||
  359. ft.CompletionStatus == "Disabled") {
  360. disabledTests.push_back(ft);
  361. }
  362. }
  363. cmDuration durationInSecs = clock_finish - clock_start;
  364. this->LogTestSummary(passed, failed, durationInSecs);
  365. this->LogDisabledTests(disabledTests);
  366. this->LogFailedTests(failed, resultsSet);
  367. }
  368. if (!this->GenerateXML()) {
  369. return 1;
  370. }
  371. if (!this->WriteJUnitXML()) {
  372. return 1;
  373. }
  374. if (!this->PostProcessHandler()) {
  375. this->LogFile = nullptr;
  376. return -1;
  377. }
  378. if (!failed.empty()) {
  379. this->LogFile = nullptr;
  380. return -1;
  381. }
  382. if (noTestsFoundError) {
  383. this->LogFile = nullptr;
  384. return -1;
  385. }
  386. this->LogFile = nullptr;
  387. return 0;
  388. }
  389. /* Given a multi-option value `parts`, compile those parts into
  390. * regular expressions in `expressions`. Skip empty values.
  391. * Returns true if there were any expressions.
  392. */
  393. static bool BuildLabelRE(std::vector<std::string> const& parts,
  394. std::vector<cmsys::RegularExpression>& expressions)
  395. {
  396. expressions.clear();
  397. for (auto const& p : parts) {
  398. if (!p.empty()) {
  399. expressions.emplace_back(p);
  400. }
  401. }
  402. return !expressions.empty();
  403. }
  404. bool cmCTestTestHandler::ProcessOptions()
  405. {
  406. // Update internal data structure from generic one
  407. this->SetTestsToRunInformation(this->TestOptions.TestsToRunInformation);
  408. if (this->TestOptions.ScheduleRandom) {
  409. this->CTest->SetScheduleType("Random");
  410. }
  411. if (auto repeat = this->Repeat) {
  412. cmsys::RegularExpression repeatRegex(
  413. "^(UNTIL_FAIL|UNTIL_PASS|AFTER_TIMEOUT):([0-9]+)$");
  414. if (repeatRegex.find(*repeat)) {
  415. std::string const& count = repeatRegex.match(2);
  416. unsigned long n = 1;
  417. cmStrToULong(count, &n); // regex guarantees success
  418. this->RepeatCount = static_cast<int>(n);
  419. if (this->RepeatCount > 1) {
  420. std::string const& mode = repeatRegex.match(1);
  421. if (mode == "UNTIL_FAIL") {
  422. this->RepeatMode = cmCTest::Repeat::UntilFail;
  423. } else if (mode == "UNTIL_PASS") {
  424. this->RepeatMode = cmCTest::Repeat::UntilPass;
  425. } else if (mode == "AFTER_TIMEOUT") {
  426. this->RepeatMode = cmCTest::Repeat::AfterTimeout;
  427. }
  428. }
  429. } else {
  430. cmCTestLog(this->CTest, ERROR_MESSAGE,
  431. "Repeat option invalid value: " << *repeat << std::endl);
  432. return false;
  433. }
  434. }
  435. if (auto parallelLevel = this->ParallelLevel) {
  436. if (parallelLevel->empty()) {
  437. // An empty value tells ctest to choose a default.
  438. this->CTest->SetParallelLevel(cm::nullopt);
  439. } else {
  440. // A non-empty value must be a non-negative integer.
  441. unsigned long plevel = 0;
  442. if (!cmStrToULong(*parallelLevel, &plevel)) {
  443. cmCTestLog(this->CTest, ERROR_MESSAGE,
  444. "ParallelLevel invalid value: " << *parallelLevel
  445. << std::endl);
  446. return false;
  447. }
  448. this->CTest->SetParallelLevel(plevel);
  449. }
  450. }
  451. if (this->TestOptions.StopOnFailure) {
  452. this->CTest->SetStopOnFailure(true);
  453. }
  454. BuildLabelRE(this->TestOptions.LabelRegularExpression,
  455. this->IncludeLabelRegularExpressions);
  456. BuildLabelRE(this->TestOptions.ExcludeLabelRegularExpression,
  457. this->ExcludeLabelRegularExpressions);
  458. if (!this->TestOptions.IncludeRegularExpression.empty()) {
  459. this->UseIncludeRegExp();
  460. }
  461. if (!this->TestOptions.ExcludeRegularExpression.empty()) {
  462. this->UseExcludeRegExp();
  463. }
  464. return true;
  465. }
  466. void cmCTestTestHandler::LogTestSummary(std::vector<std::string> const& passed,
  467. std::vector<std::string> const& failed,
  468. cmDuration const& durationInSecs)
  469. {
  470. std::size_t total = passed.size() + failed.size();
  471. float percent =
  472. static_cast<float>(passed.size()) * 100.0f / static_cast<float>(total);
  473. if (!failed.empty() && percent > 99) {
  474. percent = 99;
  475. }
  476. std::string passColorCode;
  477. std::string failedColorCode;
  478. if (failed.empty()) {
  479. passColorCode = this->CTest->GetColorCode(cmCTest::Color::GREEN);
  480. } else {
  481. failedColorCode = this->CTest->GetColorCode(cmCTest::Color::RED);
  482. }
  483. cmCTestLog(this->CTest, HANDLER_OUTPUT,
  484. std::endl
  485. << passColorCode << std::lround(percent) << "% tests passed"
  486. << this->CTest->GetColorCode(cmCTest::Color::CLEAR_COLOR)
  487. << ", " << failedColorCode << failed.size() << " tests failed"
  488. << this->CTest->GetColorCode(cmCTest::Color::CLEAR_COLOR)
  489. << " out of " << total << std::endl);
  490. if ((!this->CTest->GetLabelsForSubprojects().empty() &&
  491. this->CTest->GetSubprojectSummary())) {
  492. this->PrintLabelOrSubprojectSummary(true);
  493. }
  494. if (this->CTest->GetLabelSummary()) {
  495. this->PrintLabelOrSubprojectSummary(false);
  496. }
  497. char realBuf[1024];
  498. snprintf(realBuf, sizeof(realBuf), "%6.2f sec", durationInSecs.count());
  499. cmCTestOptionalLog(this->CTest, HANDLER_OUTPUT,
  500. "\nTotal Test time (real) = " << realBuf << "\n",
  501. this->Quiet);
  502. }
  503. void cmCTestTestHandler::LogDisabledTests(
  504. std::vector<cmCTestTestResult> const& disabledTests)
  505. {
  506. if (!disabledTests.empty()) {
  507. cmGeneratedFileStream ofs;
  508. cmCTestLog(this->CTest, HANDLER_OUTPUT,
  509. std::endl
  510. << "The following tests did not run:" << std::endl);
  511. this->StartLogFile("TestsDisabled", ofs);
  512. char const* disabled_reason;
  513. cmCTestLog(this->CTest, HANDLER_OUTPUT,
  514. this->CTest->GetColorCode(cmCTest::Color::BLUE));
  515. for (cmCTestTestResult const& dt : disabledTests) {
  516. ofs << dt.TestCount << ":" << dt.Name << std::endl;
  517. if (dt.CompletionStatus == "Disabled") {
  518. disabled_reason = "Disabled";
  519. } else {
  520. disabled_reason = "Skipped";
  521. }
  522. cmCTestLog(this->CTest, HANDLER_OUTPUT,
  523. "\t" << std::setw(3) << dt.TestCount << " - " << dt.Name
  524. << " (" << disabled_reason << ")" << std::endl);
  525. }
  526. cmCTestLog(this->CTest, HANDLER_OUTPUT,
  527. this->CTest->GetColorCode(cmCTest::Color::CLEAR_COLOR));
  528. }
  529. }
  530. void cmCTestTestHandler::LogFailedTests(std::vector<std::string> const& failed,
  531. SetOfTests const& resultsSet)
  532. {
  533. if (!failed.empty()) {
  534. cmGeneratedFileStream ofs;
  535. cmCTestLog(this->CTest, HANDLER_OUTPUT,
  536. std::endl
  537. << "The following tests FAILED:" << std::endl);
  538. this->StartLogFile("TestsFailed", ofs);
  539. for (cmCTestTestResult const& ft : resultsSet) {
  540. if (ft.Status != cmCTestTestHandler::COMPLETED &&
  541. !cmHasLiteralPrefix(ft.CompletionStatus, "SKIP_") &&
  542. ft.CompletionStatus != "Disabled") {
  543. ofs << ft.TestCount << ":" << ft.Name << std::endl;
  544. auto testColor = cmCTest::Color::RED;
  545. if (this->GetTestStatus(ft) == "Not Run") {
  546. testColor = cmCTest::Color::YELLOW;
  547. }
  548. std::string ft_name_and_status =
  549. cmStrCat(ft.Name, " (", this->GetTestStatus(ft), ")");
  550. std::string labels;
  551. cmCTestTestProperties const& p = *ft.Properties;
  552. if (!p.Labels.empty()) {
  553. static size_t const maxLen = 50;
  554. size_t const ns = ft_name_and_status.size() >= maxLen
  555. ? 1
  556. : maxLen - ft_name_and_status.size();
  557. labels = cmStrCat(std::string(ns, ' '), cmJoin(p.Labels, " "));
  558. }
  559. cmCTestLog(
  560. this->CTest, HANDLER_OUTPUT,
  561. "\t" << this->CTest->GetColorCode(testColor) << std::setw(3)
  562. << ft.TestCount << " - " << ft_name_and_status
  563. << this->CTest->GetColorCode(cmCTest::Color::CLEAR_COLOR)
  564. << labels << std::endl);
  565. }
  566. }
  567. }
  568. }
  569. bool cmCTestTestHandler::GenerateXML()
  570. {
  571. if (this->CTest->GetProduceXML()) {
  572. cmGeneratedFileStream xmlfile;
  573. if (!this->StartResultingXML(
  574. (this->MemCheck ? cmCTest::PartMemCheck : cmCTest::PartTest),
  575. (this->MemCheck ? "DynamicAnalysis" : "Test"), xmlfile)) {
  576. cmCTestLog(this->CTest, ERROR_MESSAGE,
  577. "Cannot create "
  578. << (this->MemCheck ? "memory check" : "testing")
  579. << " XML file" << std::endl);
  580. this->LogFile = nullptr;
  581. return false;
  582. }
  583. cmXMLWriter xml(xmlfile);
  584. this->GenerateCTestXML(xml);
  585. }
  586. if (this->MemCheck) {
  587. cmGeneratedFileStream xmlfile;
  588. if (!this->StartResultingXML(cmCTest::PartTest, "DynamicAnalysis-Test",
  589. xmlfile)) {
  590. cmCTestLog(this->CTest, ERROR_MESSAGE,
  591. "Cannot create testing XML file" << std::endl);
  592. this->LogFile = nullptr;
  593. return false;
  594. }
  595. cmXMLWriter xml(xmlfile);
  596. // Explicitly call this class' `GenerateCTestXML` method to make `Test.xml`
  597. // as well.
  598. this->cmCTestTestHandler::GenerateCTestXML(xml);
  599. }
  600. return true;
  601. }
  602. void cmCTestTestHandler::PrintLabelOrSubprojectSummary(bool doSubProject)
  603. {
  604. // collect subproject labels
  605. std::vector<std::string> subprojects =
  606. this->CTest->GetLabelsForSubprojects();
  607. std::map<std::string, double> labelTimes;
  608. std::map<std::string, int> labelCounts;
  609. std::set<std::string> labels;
  610. std::string::size_type maxlen = 0;
  611. // initialize maps
  612. for (cmCTestTestProperties& p : this->TestList) {
  613. for (std::string const& l : p.Labels) {
  614. // first check to see if the current label is a subproject label
  615. bool isSubprojectLabel = false;
  616. auto subproject = std::find(subprojects.begin(), subprojects.end(), l);
  617. if (subproject != subprojects.end()) {
  618. isSubprojectLabel = true;
  619. }
  620. // if we are doing sub projects and this label is one, then use it
  621. // if we are not doing sub projects and the label is not one use it
  622. if (doSubProject == isSubprojectLabel) {
  623. if (l.size() > maxlen) {
  624. maxlen = l.size();
  625. }
  626. labels.insert(l);
  627. labelTimes[l] = 0;
  628. labelCounts[l] = 0;
  629. }
  630. }
  631. }
  632. // fill maps
  633. for (cmCTestTestResult& result : this->TestResults) {
  634. cmCTestTestProperties& p = *result.Properties;
  635. for (std::string const& l : p.Labels) {
  636. // only use labels found in labels
  637. if (cm::contains(labels, l)) {
  638. labelTimes[l] +=
  639. result.ExecutionTime.count() * result.Properties->Processors;
  640. ++labelCounts[l];
  641. }
  642. }
  643. }
  644. // if no labels are found return and print nothing
  645. if (labels.empty()) {
  646. return;
  647. }
  648. // now print times
  649. if (doSubProject) {
  650. cmCTestOptionalLog(this->CTest, HANDLER_OUTPUT,
  651. "\nSubproject Time Summary:", this->Quiet);
  652. } else {
  653. cmCTestOptionalLog(this->CTest, HANDLER_OUTPUT,
  654. "\nLabel Time Summary:", this->Quiet);
  655. }
  656. for (std::string const& i : labels) {
  657. std::string label = i;
  658. label.resize(maxlen + 3, ' ');
  659. char buf[1024];
  660. snprintf(buf, sizeof(buf), "%6.2f sec*proc", labelTimes[i]);
  661. std::ostringstream labelCountStr;
  662. labelCountStr << "(" << labelCounts[i] << " test";
  663. if (labelCounts[i] > 1) {
  664. labelCountStr << "s";
  665. }
  666. labelCountStr << ")";
  667. cmCTestOptionalLog(this->CTest, HANDLER_OUTPUT,
  668. "\n"
  669. << label << " = " << buf << " "
  670. << labelCountStr.str(),
  671. this->Quiet);
  672. if (this->LogFile) {
  673. *this->LogFile << "\n" << i << " = " << buf << "\n";
  674. }
  675. }
  676. if (this->LogFile) {
  677. *this->LogFile << "\n";
  678. }
  679. cmCTestOptionalLog(this->CTest, HANDLER_OUTPUT, "\n", this->Quiet);
  680. }
  681. /**
  682. * Check if the labels (from a test) match all the expressions.
  683. *
  684. * Each of the RE's must match at least one label
  685. * (e.g. all of the REs must match **some** label,
  686. * in order for the filter to apply to the test).
  687. */
  688. static bool MatchLabelsAgainstFilterRE(
  689. std::vector<std::string> const& labels,
  690. std::vector<cmsys::RegularExpression> const& expressions)
  691. {
  692. for (auto const& re : expressions) {
  693. // check to see if the label regular expression matches
  694. bool found = false; // assume it does not match
  695. cmsys::RegularExpressionMatch match;
  696. // loop over all labels and look for match
  697. for (std::string const& l : labels) {
  698. if (re.find(l.c_str(), match)) {
  699. found = true;
  700. break;
  701. }
  702. }
  703. // if no match was found, exclude the test
  704. if (!found) {
  705. return false;
  706. }
  707. }
  708. return true;
  709. }
  710. void cmCTestTestHandler::CheckLabelFilterInclude(cmCTestTestProperties& it)
  711. {
  712. // if not using Labels to filter then return
  713. if (this->IncludeLabelRegularExpressions.empty()) {
  714. return;
  715. }
  716. // if there are no labels and we are filtering by labels
  717. // then exclude the test as it does not have the label
  718. if (it.Labels.empty()) {
  719. it.IsInBasedOnREOptions = false;
  720. return;
  721. }
  722. // if no match was found, exclude the test
  723. if (!MatchLabelsAgainstFilterRE(it.Labels,
  724. this->IncludeLabelRegularExpressions)) {
  725. it.IsInBasedOnREOptions = false;
  726. }
  727. }
  728. void cmCTestTestHandler::CheckLabelFilterExclude(cmCTestTestProperties& it)
  729. {
  730. // if not using Labels to filter then return
  731. if (this->ExcludeLabelRegularExpressions.empty()) {
  732. return;
  733. }
  734. // if there are no labels and we are excluding by labels
  735. // then do nothing as a no label can not be a match
  736. if (it.Labels.empty()) {
  737. return;
  738. }
  739. // if match was found, exclude the test
  740. if (MatchLabelsAgainstFilterRE(it.Labels,
  741. this->ExcludeLabelRegularExpressions)) {
  742. it.IsInBasedOnREOptions = false;
  743. }
  744. }
  745. void cmCTestTestHandler::CheckLabelFilter(cmCTestTestProperties& it)
  746. {
  747. this->CheckLabelFilterInclude(it);
  748. this->CheckLabelFilterExclude(it);
  749. }
  750. bool cmCTestTestHandler::ComputeTestList()
  751. {
  752. this->TestList.clear(); // clear list of test
  753. if (!this->GetListOfTests()) {
  754. return false;
  755. }
  756. if (this->TestOptions.RerunFailed) {
  757. return this->ComputeTestListForRerunFailed();
  758. }
  759. cmCTestTestHandler::ListOfTests::size_type tmsize = this->TestList.size();
  760. // how many tests are in based on RegExp?
  761. int inREcnt = 0;
  762. for (cmCTestTestProperties& tp : this->TestList) {
  763. this->CheckLabelFilter(tp);
  764. if (tp.IsInBasedOnREOptions) {
  765. inREcnt++;
  766. }
  767. }
  768. // expand the test list based on the union flag
  769. if (this->TestOptions.UseUnion) {
  770. this->ExpandTestsToRunInformation(static_cast<int>(tmsize));
  771. } else {
  772. this->ExpandTestsToRunInformation(inREcnt);
  773. }
  774. // Now create a final list of tests to run
  775. int cnt = 0;
  776. inREcnt = 0;
  777. ListOfTests finalList;
  778. for (cmCTestTestProperties& tp : this->TestList) {
  779. cnt++;
  780. if (tp.IsInBasedOnREOptions) {
  781. inREcnt++;
  782. }
  783. if (this->TestOptions.UseUnion) {
  784. // if it is not in the list and not in the regexp then skip
  785. if ((!this->TestsToRun.empty() &&
  786. !cm::contains(this->TestsToRun, cnt)) &&
  787. !tp.IsInBasedOnREOptions) {
  788. continue;
  789. }
  790. } else {
  791. // is this test in the list of tests to run? If not then skip it
  792. if ((!this->TestsToRun.empty() &&
  793. !cm::contains(this->TestsToRun, inREcnt)) ||
  794. !tp.IsInBasedOnREOptions) {
  795. continue;
  796. }
  797. }
  798. if (this->TestsToRunByName) {
  799. if (this->TestsToRunByName->find(tp.Name) ==
  800. this->TestsToRunByName->end()) {
  801. continue;
  802. }
  803. }
  804. if (this->TestsToExcludeByName) {
  805. if (this->TestsToExcludeByName->find(tp.Name) !=
  806. this->TestsToExcludeByName->end()) {
  807. continue;
  808. }
  809. }
  810. tp.Index = cnt; // save the index into the test list for this test
  811. finalList.push_back(tp);
  812. }
  813. this->UpdateForFixtures(finalList);
  814. // Save the total number of tests before exclusions
  815. this->TotalNumberOfTests = this->TestList.size();
  816. // Set the TestList to the final list of all test
  817. this->TestList = finalList;
  818. this->UpdateMaxTestNameWidth();
  819. return true;
  820. }
  821. bool cmCTestTestHandler::ComputeTestListForRerunFailed()
  822. {
  823. this->ExpandTestsToRunInformationForRerunFailed();
  824. ListOfTests finalList;
  825. int cnt = 0;
  826. for (cmCTestTestProperties& tp : this->TestList) {
  827. cnt++;
  828. // if this test is not in our list of tests to run, then skip it.
  829. if (!this->TestsToRun.empty() && !cm::contains(this->TestsToRun, cnt)) {
  830. continue;
  831. }
  832. tp.Index = cnt;
  833. finalList.push_back(tp);
  834. }
  835. this->UpdateForFixtures(finalList);
  836. // Save the total number of tests before exclusions
  837. this->TotalNumberOfTests = this->TestList.size();
  838. // Set the TestList to the list of failed tests to rerun
  839. this->TestList = finalList;
  840. this->UpdateMaxTestNameWidth();
  841. return true;
  842. }
  843. void cmCTestTestHandler::UpdateForFixtures(ListOfTests& tests) const
  844. {
  845. cmCTestOptionalLog(this->CTest, HANDLER_VERBOSE_OUTPUT,
  846. "Updating test list for fixtures" << std::endl,
  847. this->Quiet);
  848. // Prepare regular expression evaluators
  849. std::string setupRegExp(this->TestOptions.ExcludeFixtureRegularExpression);
  850. std::string cleanupRegExp(this->TestOptions.ExcludeFixtureRegularExpression);
  851. if (!this->TestOptions.ExcludeFixtureSetupRegularExpression.empty()) {
  852. if (setupRegExp.empty()) {
  853. setupRegExp = this->TestOptions.ExcludeFixtureSetupRegularExpression;
  854. } else {
  855. setupRegExp.append(
  856. "(" + setupRegExp + ")|(" +
  857. this->TestOptions.ExcludeFixtureSetupRegularExpression + ")");
  858. }
  859. }
  860. if (!this->TestOptions.ExcludeFixtureCleanupRegularExpression.empty()) {
  861. if (cleanupRegExp.empty()) {
  862. cleanupRegExp = this->TestOptions.ExcludeFixtureCleanupRegularExpression;
  863. } else {
  864. cleanupRegExp.append(
  865. "(" + cleanupRegExp + ")|(" +
  866. this->TestOptions.ExcludeFixtureCleanupRegularExpression + ")");
  867. }
  868. }
  869. cmsys::RegularExpression excludeSetupRegex(setupRegExp);
  870. cmsys::RegularExpression excludeCleanupRegex(cleanupRegExp);
  871. // Prepare some maps to help us find setup and cleanup tests for
  872. // any given fixture
  873. using TestIterator = ListOfTests::const_iterator;
  874. using FixtureDependencies = std::multimap<std::string, TestIterator>;
  875. using FixtureDepsIterator = FixtureDependencies::const_iterator;
  876. FixtureDependencies fixtureSetups;
  877. FixtureDependencies fixtureCleanups;
  878. for (auto it = this->TestList.begin(); it != this->TestList.end(); ++it) {
  879. cmCTestTestProperties const& p = *it;
  880. for (std::string const& deps : p.FixturesSetup) {
  881. fixtureSetups.insert(std::make_pair(deps, it));
  882. }
  883. for (std::string const& deps : p.FixturesCleanup) {
  884. fixtureCleanups.insert(std::make_pair(deps, it));
  885. }
  886. }
  887. // Prepare fast lookup of tests already included in our list of tests
  888. std::set<std::string> addedTests;
  889. for (cmCTestTestProperties const& p : tests) {
  890. addedTests.insert(p.Name);
  891. }
  892. // These are lookups of fixture name to a list of indices into the final
  893. // tests array for tests which require that fixture and tests which are
  894. // setups for that fixture. They are needed at the end to populate
  895. // dependencies of the cleanup tests in our final list of tests.
  896. std::map<std::string, std::vector<size_t>> fixtureRequirements;
  897. std::map<std::string, std::vector<size_t>> setupFixturesAdded;
  898. // Use integer index for iteration because we append to
  899. // the tests vector as we go
  900. size_t fixtureTestsAdded = 0;
  901. std::set<std::string> addedFixtures;
  902. for (size_t i = 0; i < tests.size(); ++i) {
  903. // Skip disabled tests
  904. if (tests[i].Disabled) {
  905. continue;
  906. }
  907. // There are two things to do for each test:
  908. // 1. For every fixture required by this test, record that fixture as
  909. // being required and create dependencies on that fixture's setup
  910. // tests.
  911. // 2. Record all setup tests in the final test list so we can later make
  912. // cleanup tests in the test list depend on their associated setup
  913. // tests to enforce correct ordering.
  914. // 1. Handle fixture requirements
  915. //
  916. // Must copy the set of fixtures required because we may invalidate
  917. // the tests array by appending to it
  918. std::set<std::string> fixtures = tests[i].FixturesRequired;
  919. for (std::string const& requiredFixtureName : fixtures) {
  920. if (requiredFixtureName.empty()) {
  921. continue;
  922. }
  923. fixtureRequirements[requiredFixtureName].push_back(i);
  924. // Add dependencies to this test for all of the setup tests
  925. // associated with the required fixture. If any of those setup
  926. // tests fail, this test should not run. We make the fixture's
  927. // cleanup tests depend on this test case later.
  928. std::pair<FixtureDepsIterator, FixtureDepsIterator> setupRange =
  929. fixtureSetups.equal_range(requiredFixtureName);
  930. for (auto sIt = setupRange.first; sIt != setupRange.second; ++sIt) {
  931. std::string const& setupTestName = sIt->second->Name;
  932. tests[i].RequireSuccessDepends.insert(setupTestName);
  933. if (!cm::contains(tests[i].Depends, setupTestName)) {
  934. tests[i].Depends.push_back(setupTestName);
  935. }
  936. }
  937. // Append any fixture setup/cleanup tests to our test list if they
  938. // are not already in it (they could have been in the original
  939. // set of tests passed to us at the outset or have already been
  940. // added from a previously checked test). A fixture isn't required
  941. // to have setup/cleanup tests.
  942. if (!addedFixtures.insert(requiredFixtureName).second) {
  943. // Already seen this fixture, no need to check it again
  944. continue;
  945. }
  946. // Only add setup tests if this fixture has not been excluded
  947. if (setupRegExp.empty() ||
  948. !excludeSetupRegex.find(requiredFixtureName)) {
  949. std::pair<FixtureDepsIterator, FixtureDepsIterator> fixtureRange =
  950. fixtureSetups.equal_range(requiredFixtureName);
  951. for (auto it = fixtureRange.first; it != fixtureRange.second; ++it) {
  952. ListOfTests::const_iterator lotIt = it->second;
  953. cmCTestTestProperties const& p = *lotIt;
  954. if (!addedTests.insert(p.Name).second) {
  955. // Already have p in our test list
  956. continue;
  957. }
  958. // This is a test not yet in our list, so add it and
  959. // update its index to reflect where it was in the original
  960. // full list of all tests (needed to track individual tests
  961. // across ctest runs for re-run failed, etc.)
  962. tests.push_back(p);
  963. tests.back().Index =
  964. 1 + static_cast<int>(std::distance(this->TestList.begin(), lotIt));
  965. ++fixtureTestsAdded;
  966. cmCTestOptionalLog(this->CTest, HANDLER_VERBOSE_OUTPUT,
  967. "Added setup test "
  968. << p.Name << " required by fixture "
  969. << requiredFixtureName << std::endl,
  970. this->Quiet);
  971. }
  972. }
  973. // Only add cleanup tests if this fixture has not been excluded
  974. if (cleanupRegExp.empty() ||
  975. !excludeCleanupRegex.find(requiredFixtureName)) {
  976. std::pair<FixtureDepsIterator, FixtureDepsIterator> fixtureRange =
  977. fixtureCleanups.equal_range(requiredFixtureName);
  978. for (auto it = fixtureRange.first; it != fixtureRange.second; ++it) {
  979. ListOfTests::const_iterator lotIt = it->second;
  980. cmCTestTestProperties const& p = *lotIt;
  981. if (!addedTests.insert(p.Name).second) {
  982. // Already have p in our test list
  983. continue;
  984. }
  985. // This is a test not yet in our list, so add it and
  986. // update its index to reflect where it was in the original
  987. // full list of all tests (needed to track individual tests
  988. // across ctest runs for re-run failed, etc.)
  989. tests.push_back(p);
  990. tests.back().Index =
  991. 1 + static_cast<int>(std::distance(this->TestList.begin(), lotIt));
  992. ++fixtureTestsAdded;
  993. cmCTestOptionalLog(this->CTest, HANDLER_VERBOSE_OUTPUT,
  994. "Added cleanup test "
  995. << p.Name << " required by fixture "
  996. << requiredFixtureName << std::endl,
  997. this->Quiet);
  998. }
  999. }
  1000. }
  1001. // 2. Record all setup fixtures included in the final list of tests
  1002. for (std::string const& setupFixtureName : tests[i].FixturesSetup) {
  1003. if (setupFixtureName.empty()) {
  1004. continue;
  1005. }
  1006. setupFixturesAdded[setupFixtureName].push_back(i);
  1007. }
  1008. }
  1009. // Now that we have the final list of tests, we can update all cleanup
  1010. // tests to depend on those tests which require that fixture and on any
  1011. // setup tests for that fixture. The latter is required to handle the
  1012. // pathological case where setup and cleanup tests are in the test set
  1013. // but no other test has that fixture as a requirement.
  1014. for (cmCTestTestProperties& p : tests) {
  1015. std::set<std::string> const& cleanups = p.FixturesCleanup;
  1016. for (std::string const& fixture : cleanups) {
  1017. // This cleanup test could be part of the original test list that was
  1018. // passed in. It is then possible that no other test requires the
  1019. // fIt fixture, so we have to check for this.
  1020. auto cIt = fixtureRequirements.find(fixture);
  1021. if (cIt != fixtureRequirements.end()) {
  1022. std::vector<size_t> const& indices = cIt->second;
  1023. for (size_t index : indices) {
  1024. std::string const& reqTestName = tests[index].Name;
  1025. if (!cm::contains(p.Depends, reqTestName)) {
  1026. p.Depends.push_back(reqTestName);
  1027. }
  1028. }
  1029. }
  1030. // Ensure fixture cleanup tests always run after their setup tests, even
  1031. // if no other test cases require the fixture
  1032. cIt = setupFixturesAdded.find(fixture);
  1033. if (cIt != setupFixturesAdded.end()) {
  1034. std::vector<size_t> const& indices = cIt->second;
  1035. for (size_t index : indices) {
  1036. std::string const& setupTestName = tests[index].Name;
  1037. if (!cm::contains(p.Depends, setupTestName)) {
  1038. p.Depends.push_back(setupTestName);
  1039. }
  1040. }
  1041. }
  1042. }
  1043. }
  1044. cmCTestOptionalLog(this->CTest, HANDLER_VERBOSE_OUTPUT,
  1045. "Added " << fixtureTestsAdded
  1046. << " tests to meet fixture requirements"
  1047. << std::endl,
  1048. this->Quiet);
  1049. }
  1050. void cmCTestTestHandler::UpdateMaxTestNameWidth()
  1051. {
  1052. std::string::size_type max = this->CTest->GetMaxTestNameWidth();
  1053. for (cmCTestTestProperties& p : this->TestList) {
  1054. if (max < p.Name.size()) {
  1055. max = p.Name.size();
  1056. }
  1057. }
  1058. if (static_cast<std::string::size_type>(
  1059. this->CTest->GetMaxTestNameWidth()) != max) {
  1060. this->CTest->SetMaxTestNameWidth(static_cast<int>(max));
  1061. }
  1062. }
  1063. bool cmCTestTestHandler::GetValue(char const* tag, int& value,
  1064. std::istream& fin)
  1065. {
  1066. std::string line;
  1067. bool ret = true;
  1068. cmSystemTools::GetLineFromStream(fin, line);
  1069. if (line == tag) {
  1070. fin >> value;
  1071. ret = cmSystemTools::GetLineFromStream(fin, line); // read blank line
  1072. } else {
  1073. cmCTestLog(this->CTest, ERROR_MESSAGE,
  1074. "parse error: missing tag: " << tag << " found [" << line << "]"
  1075. << std::endl);
  1076. ret = false;
  1077. }
  1078. return ret;
  1079. }
  1080. bool cmCTestTestHandler::GetValue(char const* tag, double& value,
  1081. std::istream& fin)
  1082. {
  1083. std::string line;
  1084. cmSystemTools::GetLineFromStream(fin, line);
  1085. bool ret = true;
  1086. if (line == tag) {
  1087. fin >> value;
  1088. ret = cmSystemTools::GetLineFromStream(fin, line); // read blank line
  1089. } else {
  1090. cmCTestLog(this->CTest, ERROR_MESSAGE,
  1091. "parse error: missing tag: " << tag << " found [" << line << "]"
  1092. << std::endl);
  1093. ret = false;
  1094. }
  1095. return ret;
  1096. }
  1097. bool cmCTestTestHandler::GetValue(char const* tag, bool& value,
  1098. std::istream& fin)
  1099. {
  1100. std::string line;
  1101. cmSystemTools::GetLineFromStream(fin, line);
  1102. bool ret = true;
  1103. if (line == tag) {
  1104. #ifdef __HAIKU__
  1105. int tmp = 0;
  1106. fin >> tmp;
  1107. value = false;
  1108. if (tmp) {
  1109. value = true;
  1110. }
  1111. #else
  1112. fin >> value;
  1113. #endif
  1114. ret = cmSystemTools::GetLineFromStream(fin, line); // read blank line
  1115. } else {
  1116. cmCTestLog(this->CTest, ERROR_MESSAGE,
  1117. "parse error: missing tag: " << tag << " found [" << line << "]"
  1118. << std::endl);
  1119. ret = false;
  1120. }
  1121. return ret;
  1122. }
  1123. bool cmCTestTestHandler::GetValue(char const* tag, size_t& value,
  1124. std::istream& fin)
  1125. {
  1126. std::string line;
  1127. cmSystemTools::GetLineFromStream(fin, line);
  1128. bool ret = true;
  1129. if (line == tag) {
  1130. fin >> value;
  1131. ret = cmSystemTools::GetLineFromStream(fin, line); // read blank line
  1132. } else {
  1133. cmCTestLog(this->CTest, ERROR_MESSAGE,
  1134. "parse error: missing tag: " << tag << " found [" << line << "]"
  1135. << std::endl);
  1136. ret = false;
  1137. }
  1138. return ret;
  1139. }
  1140. bool cmCTestTestHandler::GetValue(char const* tag, std::string& value,
  1141. std::istream& fin)
  1142. {
  1143. std::string line;
  1144. cmSystemTools::GetLineFromStream(fin, line);
  1145. bool ret = true;
  1146. if (line == tag) {
  1147. ret = cmSystemTools::GetLineFromStream(fin, value);
  1148. } else {
  1149. cmCTestLog(this->CTest, ERROR_MESSAGE,
  1150. "parse error: missing tag: " << tag << " found [" << line << "]"
  1151. << std::endl);
  1152. ret = false;
  1153. }
  1154. return ret;
  1155. }
  1156. bool cmCTestTestHandler::ProcessDirectory(std::vector<std::string>& passed,
  1157. std::vector<std::string>& failed)
  1158. {
  1159. if (!this->ComputeTestList()) {
  1160. return false;
  1161. }
  1162. this->StartTest = this->CTest->CurrentTime();
  1163. this->StartTestTime = std::chrono::system_clock::now();
  1164. auto elapsed_time_start = std::chrono::steady_clock::now();
  1165. auto parallel =
  1166. cm::make_unique<cmCTestMultiProcessHandler>(this->CTest, this);
  1167. parallel->SetParallelLevel(this->CTest->GetParallelLevel());
  1168. if (this->RepeatMode != cmCTest::Repeat::Never) {
  1169. parallel->SetRepeatMode(this->RepeatMode, this->RepeatCount);
  1170. } else {
  1171. parallel->SetRepeatMode(this->CTest->GetRepeatMode(),
  1172. this->CTest->GetRepeatCount());
  1173. }
  1174. parallel->SetQuiet(this->Quiet);
  1175. if (this->TestLoad > 0) {
  1176. parallel->SetTestLoad(this->TestLoad);
  1177. } else {
  1178. parallel->SetTestLoad(this->CTest->GetTestLoad());
  1179. }
  1180. *this->LogFile
  1181. << "Start testing: " << this->CTest->CurrentTime() << std::endl
  1182. << "----------------------------------------------------------"
  1183. << std::endl;
  1184. cmCTestMultiProcessHandler::TestMap tests;
  1185. cmCTestMultiProcessHandler::PropertiesMap properties;
  1186. bool randomSchedule = this->CTest->GetScheduleType() == "Random";
  1187. if (randomSchedule) {
  1188. srand(static_cast<unsigned>(time(nullptr)));
  1189. }
  1190. for (cmCTestTestProperties& p : this->TestList) {
  1191. cmCTestMultiProcessHandler::TestSet depends;
  1192. if (randomSchedule) {
  1193. p.Cost = static_cast<float>(rand());
  1194. }
  1195. if (!p.Depends.empty()) {
  1196. for (std::string const& i : p.Depends) {
  1197. for (cmCTestTestProperties const& it2 : this->TestList) {
  1198. if (it2.Name == i) {
  1199. depends.insert(it2.Index);
  1200. break; // break out of test loop as name can only match 1
  1201. }
  1202. }
  1203. }
  1204. }
  1205. tests[p.Index].Depends = depends;
  1206. properties[p.Index] = &p;
  1207. }
  1208. parallel->SetResourceSpecFile(this->TestOptions.ResourceSpecFile);
  1209. if (!parallel->SetTests(std::move(tests), std::move(properties))) {
  1210. return false;
  1211. }
  1212. parallel->SetPassFailVectors(&passed, &failed);
  1213. this->TestResults.clear();
  1214. parallel->SetTestResults(&this->TestResults);
  1215. parallel->CheckResourceAvailability();
  1216. if (this->CTest->ShouldPrintLabels()) {
  1217. parallel->PrintLabels();
  1218. } else if (this->CTest->GetShowOnly()) {
  1219. parallel->PrintTestList();
  1220. } else {
  1221. parallel->RunTests();
  1222. }
  1223. this->EndTest = this->CTest->CurrentTime();
  1224. this->EndTestTime = std::chrono::system_clock::now();
  1225. this->ElapsedTestingTime =
  1226. std::chrono::steady_clock::now() - elapsed_time_start;
  1227. *this->LogFile << "End testing: " << this->CTest->CurrentTime() << std::endl;
  1228. return true;
  1229. }
  1230. void cmCTestTestHandler::GenerateTestCommand(
  1231. std::vector<std::string>& /*unused*/, int /*unused*/)
  1232. {
  1233. }
  1234. void cmCTestTestHandler::GenerateCTestXML(cmXMLWriter& xml)
  1235. {
  1236. if (!this->CTest->GetProduceXML()) {
  1237. return;
  1238. }
  1239. this->CTest->GetInstrumentation().CollectTimingData(
  1240. cmInstrumentationQuery::Hook::PrepareForCDash);
  1241. this->CTest->StartXML(xml, this->CMake, this->AppendXML);
  1242. this->CTest->GenerateSubprojectsOutput(xml);
  1243. xml.StartElement("Testing");
  1244. xml.Element("StartDateTime", this->StartTest);
  1245. xml.Element("StartTestTime", this->StartTestTime);
  1246. xml.StartElement("TestList");
  1247. for (cmCTestTestResult const& result : this->TestResults) {
  1248. std::string testPath = result.Path + "/" + result.Name;
  1249. xml.Element("Test", this->CTest->GetShortPathToFile(testPath));
  1250. }
  1251. xml.EndElement(); // TestList
  1252. for (cmCTestTestResult& result : this->TestResults) {
  1253. this->WriteTestResultHeader(xml, result);
  1254. xml.StartElement("Results");
  1255. if (result.Status != cmCTestTestHandler::NOT_RUN) {
  1256. if (result.Status != cmCTestTestHandler::COMPLETED ||
  1257. result.ReturnValue) {
  1258. xml.StartElement("NamedMeasurement");
  1259. xml.Attribute("type", "text/string");
  1260. xml.Attribute("name", "Exit Code");
  1261. xml.Element("Value", this->GetTestStatus(result));
  1262. xml.EndElement(); // NamedMeasurement
  1263. xml.StartElement("NamedMeasurement");
  1264. xml.Attribute("type", "text/string");
  1265. xml.Attribute("name", "Exit Value");
  1266. xml.Element("Value", result.ReturnValue);
  1267. xml.EndElement(); // NamedMeasurement
  1268. }
  1269. this->RecordCustomTestMeasurements(xml, result.TestMeasurementsOutput);
  1270. xml.StartElement("NamedMeasurement");
  1271. xml.Attribute("type", "numeric/double");
  1272. xml.Attribute("name", "Execution Time");
  1273. xml.Element("Value", result.ExecutionTime.count());
  1274. xml.EndElement(); // NamedMeasurement
  1275. if (!result.Reason.empty()) {
  1276. char const* reasonType = "Pass Reason";
  1277. if (result.Status != cmCTestTestHandler::COMPLETED) {
  1278. reasonType = "Fail Reason";
  1279. }
  1280. xml.StartElement("NamedMeasurement");
  1281. xml.Attribute("type", "text/string");
  1282. xml.Attribute("name", reasonType);
  1283. xml.Element("Value", result.Reason);
  1284. xml.EndElement(); // NamedMeasurement
  1285. }
  1286. }
  1287. xml.StartElement("NamedMeasurement");
  1288. xml.Attribute("type", "numeric/double");
  1289. xml.Attribute("name", "Processors");
  1290. xml.Element("Value", result.Properties->Processors);
  1291. xml.EndElement(); // NamedMeasurement
  1292. xml.StartElement("NamedMeasurement");
  1293. xml.Attribute("type", "text/string");
  1294. xml.Attribute("name", "Completion Status");
  1295. if (result.CustomCompletionStatus.empty()) {
  1296. xml.Element("Value", result.CompletionStatus);
  1297. } else {
  1298. xml.Element("Value", result.CustomCompletionStatus);
  1299. }
  1300. xml.EndElement(); // NamedMeasurement
  1301. xml.StartElement("NamedMeasurement");
  1302. xml.Attribute("type", "text/string");
  1303. xml.Attribute("name", "Command Line");
  1304. xml.Element("Value", result.FullCommandLine);
  1305. xml.EndElement(); // NamedMeasurement
  1306. xml.StartElement("NamedMeasurement");
  1307. xml.Attribute("type", "text/string");
  1308. xml.Attribute("name", "Environment");
  1309. xml.Element("Value", result.Environment);
  1310. xml.EndElement(); // NamedMeasurement
  1311. for (auto const& measure : result.Properties->Measurements) {
  1312. xml.StartElement("NamedMeasurement");
  1313. xml.Attribute("type", "text/string");
  1314. xml.Attribute("name", measure.first);
  1315. xml.Element("Value", measure.second);
  1316. xml.EndElement(); // NamedMeasurement
  1317. }
  1318. xml.StartElement("Measurement");
  1319. xml.StartElement("Value");
  1320. if (result.CompressOutput) {
  1321. xml.Attribute("encoding", "base64");
  1322. xml.Attribute("compression", "gzip");
  1323. }
  1324. xml.Content(result.Output);
  1325. xml.EndElement(); // Value
  1326. xml.EndElement(); // Measurement
  1327. if (!result.InstrumentationFile.empty()) {
  1328. std::string instrument_file_path =
  1329. cmStrCat(this->CTest->GetInstrumentation().GetCDashDir(), "/test/",
  1330. result.InstrumentationFile);
  1331. this->CTest->ConvertInstrumentationJSONFileToXML(instrument_file_path,
  1332. xml);
  1333. }
  1334. xml.EndElement(); // Results
  1335. this->AttachFiles(xml, result);
  1336. this->WriteTestResultFooter(xml, result);
  1337. }
  1338. xml.Element("EndDateTime", this->EndTest);
  1339. xml.Element("EndTestTime", this->EndTestTime);
  1340. xml.Element(
  1341. "ElapsedMinutes",
  1342. std::chrono::duration_cast<std::chrono::minutes>(this->ElapsedTestingTime)
  1343. .count());
  1344. xml.EndElement(); // Testing
  1345. this->CTest->EndXML(xml);
  1346. }
  1347. void cmCTestTestHandler::WriteTestResultHeader(cmXMLWriter& xml,
  1348. cmCTestTestResult const& result)
  1349. {
  1350. xml.StartElement("Test");
  1351. if (result.Status == cmCTestTestHandler::COMPLETED) {
  1352. xml.Attribute("Status", "passed");
  1353. } else if (result.Status == cmCTestTestHandler::NOT_RUN) {
  1354. xml.Attribute("Status", "notrun");
  1355. } else {
  1356. xml.Attribute("Status", "failed");
  1357. }
  1358. std::string testPath = result.Path + "/" + result.Name;
  1359. xml.Element("Name", result.Name);
  1360. xml.Element("Path", this->CTest->GetShortPathToFile(result.Path));
  1361. xml.Element("FullName", this->CTest->GetShortPathToFile(testPath));
  1362. xml.Element("FullCommandLine", result.FullCommandLine);
  1363. }
  1364. void cmCTestTestHandler::WriteTestResultFooter(cmXMLWriter& xml,
  1365. cmCTestTestResult const& result)
  1366. {
  1367. if (!result.Properties->Labels.empty()) {
  1368. xml.StartElement("Labels");
  1369. std::vector<std::string> const& labels = result.Properties->Labels;
  1370. for (std::string const& label : labels) {
  1371. xml.Element("Label", label);
  1372. }
  1373. xml.EndElement(); // Labels
  1374. }
  1375. xml.EndElement(); // Test
  1376. }
  1377. void cmCTestTestHandler::AttachFiles(cmXMLWriter& xml,
  1378. cmCTestTestResult& result)
  1379. {
  1380. if (result.Status != cmCTestTestHandler::COMPLETED &&
  1381. !result.Properties->AttachOnFail.empty()) {
  1382. result.Properties->AttachedFiles.insert(
  1383. result.Properties->AttachedFiles.end(),
  1384. result.Properties->AttachOnFail.begin(),
  1385. result.Properties->AttachOnFail.end());
  1386. }
  1387. for (std::string const& file : result.Properties->AttachedFiles) {
  1388. this->AttachFile(xml, file, "");
  1389. }
  1390. }
  1391. void cmCTestTestHandler::AttachFile(cmXMLWriter& xml, std::string const& file,
  1392. std::string const& name)
  1393. {
  1394. std::string const& base64 = this->CTest->Base64GzipEncodeFile(file);
  1395. std::string const fname = cmSystemTools::GetFilenameName(file);
  1396. xml.StartElement("NamedMeasurement");
  1397. std::string measurement_name = name;
  1398. if (measurement_name.empty()) {
  1399. measurement_name = "Attached File";
  1400. }
  1401. xml.Attribute("name", measurement_name);
  1402. xml.Attribute("encoding", "base64");
  1403. xml.Attribute("compression", "tar/gzip");
  1404. xml.Attribute("filename", fname);
  1405. xml.Attribute("type", "file");
  1406. xml.Element("Value", base64);
  1407. xml.EndElement(); // NamedMeasurement
  1408. }
  1409. int cmCTestTestHandler::ExecuteCommands(std::vector<std::string>& vec)
  1410. {
  1411. for (std::string const& it : vec) {
  1412. int retVal = 0;
  1413. cmCTestOptionalLog(this->CTest, HANDLER_VERBOSE_OUTPUT,
  1414. "Run command: " << it << std::endl, this->Quiet);
  1415. if (!cmSystemTools::RunSingleCommand(it, nullptr, nullptr, &retVal,
  1416. nullptr, cmSystemTools::OUTPUT_MERGE
  1417. /*this->Verbose*/) ||
  1418. retVal != 0) {
  1419. cmCTestLog(this->CTest, ERROR_MESSAGE,
  1420. "Problem running command: " << it << std::endl);
  1421. return 0;
  1422. }
  1423. }
  1424. return 1;
  1425. }
  1426. // Find the appropriate executable to run for a test
  1427. std::string cmCTestTestHandler::FindTheExecutable(std::string const& exe)
  1428. {
  1429. std::string resConfig;
  1430. std::vector<std::string> extraPaths;
  1431. std::vector<std::string> failedPaths;
  1432. if (exe == "NOT_AVAILABLE") {
  1433. return exe;
  1434. }
  1435. return cmCTestTestHandler::FindExecutable(this->CTest, exe, resConfig,
  1436. extraPaths, failedPaths);
  1437. }
  1438. // add additional configurations to the search path
  1439. void cmCTestTestHandler::AddConfigurations(
  1440. cmCTest* ctest, std::vector<std::string>& attempted,
  1441. std::vector<std::string>& attemptedConfigs, std::string filepath,
  1442. std::string& filename)
  1443. {
  1444. std::string tempPath;
  1445. if (!filepath.empty() && filepath[filepath.size() - 1] != '/') {
  1446. filepath += "/";
  1447. }
  1448. tempPath = filepath + filename;
  1449. attempted.push_back(tempPath);
  1450. attemptedConfigs.emplace_back();
  1451. if (!ctest->GetConfigType().empty()) {
  1452. tempPath = cmStrCat(filepath, ctest->GetConfigType(), '/', filename);
  1453. attempted.push_back(tempPath);
  1454. attemptedConfigs.push_back(ctest->GetConfigType());
  1455. // If the file is an OSX bundle then the configtype
  1456. // will be at the start of the path
  1457. tempPath = cmStrCat(ctest->GetConfigType(), '/', filepath, filename);
  1458. attempted.push_back(tempPath);
  1459. attemptedConfigs.push_back(ctest->GetConfigType());
  1460. } else {
  1461. // no config specified - try some options...
  1462. tempPath = cmStrCat(filepath, "Release/", filename);
  1463. attempted.push_back(tempPath);
  1464. attemptedConfigs.emplace_back("Release");
  1465. tempPath = cmStrCat(filepath, "Debug/", filename);
  1466. attempted.push_back(tempPath);
  1467. attemptedConfigs.emplace_back("Debug");
  1468. tempPath = cmStrCat(filepath, "MinSizeRel/", filename);
  1469. attempted.push_back(tempPath);
  1470. attemptedConfigs.emplace_back("MinSizeRel");
  1471. tempPath = cmStrCat(filepath, "RelWithDebInfo/", filename);
  1472. attempted.push_back(tempPath);
  1473. attemptedConfigs.emplace_back("RelWithDebInfo");
  1474. tempPath = cmStrCat(filepath, "Deployment/", filename);
  1475. attempted.push_back(tempPath);
  1476. attemptedConfigs.emplace_back("Deployment");
  1477. tempPath = cmStrCat(filepath, "Development/", filename);
  1478. attempted.push_back(tempPath);
  1479. attemptedConfigs.emplace_back("Deployment");
  1480. }
  1481. }
  1482. // Find the appropriate executable to run for a test
  1483. std::string cmCTestTestHandler::FindExecutable(
  1484. cmCTest* ctest, std::string const& testCommand, std::string& resultingConfig,
  1485. std::vector<std::string>& extraPaths, std::vector<std::string>& failed)
  1486. {
  1487. // now run the compiled test if we can find it
  1488. std::vector<std::string> attempted;
  1489. std::vector<std::string> attemptedConfigs;
  1490. std::string tempPath;
  1491. std::string filepath = cmSystemTools::GetFilenamePath(testCommand);
  1492. std::string filename = cmSystemTools::GetFilenameName(testCommand);
  1493. cmCTestTestHandler::AddConfigurations(ctest, attempted, attemptedConfigs,
  1494. filepath, filename);
  1495. // even if a fullpath was specified also try it relative to the current
  1496. // directory
  1497. if (!filepath.empty() && filepath[0] == '/') {
  1498. std::string localfilepath = filepath.substr(1, filepath.size() - 1);
  1499. cmCTestTestHandler::AddConfigurations(ctest, attempted, attemptedConfigs,
  1500. localfilepath, filename);
  1501. }
  1502. // if extraPaths are provided and we were not passed a full path, try them,
  1503. // try any extra paths
  1504. if (filepath.empty()) {
  1505. for (std::string const& extraPath : extraPaths) {
  1506. std::string filepathExtra = cmSystemTools::GetFilenamePath(extraPath);
  1507. std::string filenameExtra = cmSystemTools::GetFilenameName(extraPath);
  1508. cmCTestTestHandler::AddConfigurations(ctest, attempted, attemptedConfigs,
  1509. filepathExtra, filenameExtra);
  1510. }
  1511. }
  1512. // store the final location in fullPath
  1513. std::string fullPath;
  1514. // now look in the paths we specified above
  1515. for (unsigned int ai = 0; ai < attempted.size() && fullPath.empty(); ++ai) {
  1516. // first check without exe extension
  1517. if (cmSystemTools::FileExists(attempted[ai], true)) {
  1518. fullPath = cmSystemTools::ToNormalizedPathOnDisk(attempted[ai]);
  1519. resultingConfig = attemptedConfigs[ai];
  1520. }
  1521. // then try with the exe extension
  1522. else {
  1523. failed.push_back(attempted[ai]);
  1524. tempPath =
  1525. cmStrCat(attempted[ai], cmSystemTools::GetExecutableExtension());
  1526. if (cmSystemTools::FileExists(tempPath, true)) {
  1527. fullPath = cmSystemTools::ToNormalizedPathOnDisk(tempPath);
  1528. resultingConfig = attemptedConfigs[ai];
  1529. } else {
  1530. failed.push_back(tempPath);
  1531. }
  1532. }
  1533. }
  1534. // if everything else failed, check the users path, but only if a full path
  1535. // wasn't specified
  1536. if (fullPath.empty() && filepath.empty()) {
  1537. std::string path = cmSystemTools::FindProgram(filename.c_str());
  1538. if (!path.empty()) {
  1539. resultingConfig.clear();
  1540. return path;
  1541. }
  1542. }
  1543. if (fullPath.empty()) {
  1544. cmCTestLog(ctest, HANDLER_OUTPUT,
  1545. "Could not find executable "
  1546. << testCommand << "\n"
  1547. << "Looked in the following places:\n");
  1548. for (std::string const& f : failed) {
  1549. cmCTestLog(ctest, HANDLER_OUTPUT, f << "\n");
  1550. }
  1551. }
  1552. return fullPath;
  1553. }
  1554. bool cmCTestTestHandler::ParseResourceGroupsProperty(
  1555. std::string const& val,
  1556. std::vector<std::vector<cmCTestTestResourceRequirement>>& resourceGroups)
  1557. {
  1558. cmCTestResourceGroupsLexerHelper lexer(resourceGroups);
  1559. return lexer.ParseString(val);
  1560. }
  1561. bool cmCTestTestHandler::GetListOfTests()
  1562. {
  1563. if (!this->TestOptions.IncludeRegularExpression.empty()) {
  1564. this->IncludeTestsRegularExpression.compile(
  1565. this->TestOptions.IncludeRegularExpression);
  1566. }
  1567. if (!this->TestOptions.ExcludeRegularExpression.empty()) {
  1568. this->ExcludeTestsRegularExpression.compile(
  1569. this->TestOptions.ExcludeRegularExpression);
  1570. }
  1571. cmCTestOptionalLog(this->CTest, HANDLER_VERBOSE_OUTPUT,
  1572. "Constructing a list of tests" << std::endl, this->Quiet);
  1573. cmake cm(cmake::RoleScript, cmState::CTest);
  1574. cm.SetHomeDirectory("");
  1575. cm.SetHomeOutputDirectory("");
  1576. cm.GetCurrentSnapshot().SetDefaultDefinitions();
  1577. cmGlobalGenerator gg(&cm);
  1578. cmMakefile mf(&gg, cm.GetCurrentSnapshot());
  1579. mf.AddDefinition("CTEST_CONFIGURATION_TYPE", this->CTest->GetConfigType());
  1580. // Add handler for ADD_TEST
  1581. cm.GetState()->AddBuiltinCommand("add_test", cmCTestAddTestCommand(this));
  1582. // Add handler for SUBDIRS
  1583. cm.GetState()->AddBuiltinCommand("subdirs", cmCTestSubdirCommand);
  1584. // Add handler for ADD_SUBDIRECTORY
  1585. cm.GetState()->AddBuiltinCommand("add_subdirectory",
  1586. cmCTestAddSubdirectoryCommand);
  1587. // Add handler for SET_TESTS_PROPERTIES
  1588. cm.GetState()->AddBuiltinCommand("set_tests_properties",
  1589. cmCTestSetTestsPropertiesCommand(this));
  1590. // Add handler for SET_DIRECTORY_PROPERTIES
  1591. cm.GetState()->RemoveBuiltinCommand("set_directory_properties");
  1592. cm.GetState()->AddBuiltinCommand("set_directory_properties",
  1593. cmCTestSetDirectoryPropertiesCommand(this));
  1594. char const* testFilename;
  1595. if (cmSystemTools::FileExists("CTestTestfile.cmake")) {
  1596. // does the CTestTestfile.cmake exist ?
  1597. testFilename = "CTestTestfile.cmake";
  1598. } else if (cmSystemTools::FileExists("DartTestfile.txt")) {
  1599. // does the DartTestfile.txt exist ?
  1600. testFilename = "DartTestfile.txt";
  1601. } else {
  1602. return true;
  1603. }
  1604. if (!mf.ReadListFile(testFilename)) {
  1605. return false;
  1606. }
  1607. if (cmSystemTools::GetErrorOccurredFlag()) {
  1608. // SEND_ERROR or FATAL_ERROR in CTestTestfile or TEST_INCLUDE_FILES
  1609. return false;
  1610. }
  1611. cmValue specFile = mf.GetDefinition("CTEST_RESOURCE_SPEC_FILE");
  1612. if (this->TestOptions.ResourceSpecFile.empty() && specFile) {
  1613. this->TestOptions.ResourceSpecFile = *specFile;
  1614. }
  1615. if (!this->TestOptions.TestListFile.empty()) {
  1616. this->TestsToRunByName =
  1617. this->ReadTestListFile(this->TestOptions.TestListFile);
  1618. if (!this->TestsToRunByName) {
  1619. return false;
  1620. }
  1621. }
  1622. if (!this->TestOptions.ExcludeTestListFile.empty()) {
  1623. this->TestsToExcludeByName =
  1624. this->ReadTestListFile(this->TestOptions.ExcludeTestListFile);
  1625. if (!this->TestsToExcludeByName) {
  1626. return false;
  1627. }
  1628. }
  1629. cmCTestOptionalLog(this->CTest, HANDLER_VERBOSE_OUTPUT,
  1630. "Done constructing a list of tests" << std::endl,
  1631. this->Quiet);
  1632. return true;
  1633. }
  1634. void cmCTestTestHandler::UseIncludeRegExp()
  1635. {
  1636. this->UseIncludeRegExpFlag = true;
  1637. }
  1638. void cmCTestTestHandler::UseExcludeRegExp()
  1639. {
  1640. this->UseExcludeRegExpFlag = true;
  1641. this->UseExcludeRegExpFirst = !this->UseIncludeRegExpFlag;
  1642. }
  1643. std::string cmCTestTestHandler::GetTestStatus(cmCTestTestResult const& result)
  1644. {
  1645. static char const* statuses[] = { "Not Run", "Timeout", "SEGFAULT",
  1646. "ILLEGAL", "INTERRUPT", "NUMERICAL",
  1647. "OTHER_FAULT", "Failed", "BAD_COMMAND",
  1648. "Completed" };
  1649. int status = result.Status;
  1650. if (status < cmCTestTestHandler::NOT_RUN ||
  1651. status > cmCTestTestHandler::COMPLETED) {
  1652. return "No Status";
  1653. }
  1654. if (status == cmCTestTestHandler::OTHER_FAULT) {
  1655. return result.ExceptionStatus;
  1656. }
  1657. return statuses[status];
  1658. }
  1659. void cmCTestTestHandler::ExpandTestsToRunInformation(size_t numTests)
  1660. {
  1661. if (this->TestsToRunString.empty()) {
  1662. return;
  1663. }
  1664. int start;
  1665. int end = -1;
  1666. double stride = -1;
  1667. std::string::size_type pos = 0;
  1668. std::string::size_type pos2;
  1669. // read start
  1670. if (GetNextNumber(this->TestsToRunString, start, pos, pos2)) {
  1671. // read end
  1672. if (GetNextNumber(this->TestsToRunString, end, pos, pos2)) {
  1673. // read stride
  1674. if (GetNextRealNumber(this->TestsToRunString, stride, pos, pos2)) {
  1675. int val = 0;
  1676. // now read specific numbers
  1677. while (GetNextNumber(this->TestsToRunString, val, pos, pos2)) {
  1678. this->TestsToRun.push_back(val);
  1679. }
  1680. this->TestsToRun.push_back(val);
  1681. }
  1682. }
  1683. }
  1684. // if start is not specified then we assume we start at 1
  1685. if (start == -1) {
  1686. start = 1;
  1687. }
  1688. // if end isnot specified then we assume we end with the last test
  1689. if (end == -1) {
  1690. end = static_cast<int>(numTests);
  1691. }
  1692. // if the stride wasn't specified then it defaults to 1
  1693. if (stride == -1) {
  1694. stride = 1;
  1695. }
  1696. // if we have a range then add it
  1697. if (end != -1 && start != -1 && stride > 0) {
  1698. int i = 0;
  1699. while (i * stride + start <= end) {
  1700. this->TestsToRun.push_back(static_cast<int>(i * stride + start));
  1701. ++i;
  1702. }
  1703. }
  1704. // sort the array
  1705. std::sort(this->TestsToRun.begin(), this->TestsToRun.end(),
  1706. std::less<int>());
  1707. // remove duplicates
  1708. auto new_end = std::unique(this->TestsToRun.begin(), this->TestsToRun.end());
  1709. this->TestsToRun.erase(new_end, this->TestsToRun.end());
  1710. }
  1711. void cmCTestTestHandler::ExpandTestsToRunInformationForRerunFailed()
  1712. {
  1713. std::string dirName = this->CTest->GetBinaryDir() + "/Testing/Temporary";
  1714. cmsys::Directory directory;
  1715. if (!directory.Load(dirName)) {
  1716. cmCTestLog(this->CTest, ERROR_MESSAGE,
  1717. "Unable to read the contents of " << dirName << std::endl);
  1718. return;
  1719. }
  1720. int numFiles =
  1721. static_cast<int>(cmsys::Directory::GetNumberOfFilesInDirectory(dirName));
  1722. std::string pattern = "LastTestsFailed";
  1723. std::string logName;
  1724. for (int i = 0; i < numFiles; ++i) {
  1725. std::string fileName = directory.GetFile(i);
  1726. // bcc crashes if we attempt a normal substring comparison,
  1727. // hence the following workaround
  1728. std::string fileNameSubstring = fileName.substr(0, pattern.length());
  1729. if (fileNameSubstring != pattern) {
  1730. continue;
  1731. }
  1732. if (logName.empty()) {
  1733. logName = fileName;
  1734. } else {
  1735. // if multiple matching logs were found we use the most recently
  1736. // modified one.
  1737. int res;
  1738. cmSystemTools::FileTimeCompare(logName, fileName, &res);
  1739. if (res == -1) {
  1740. logName = fileName;
  1741. }
  1742. }
  1743. }
  1744. std::string lastTestsFailedLog =
  1745. this->CTest->GetBinaryDir() + "/Testing/Temporary/" + logName;
  1746. if (!cmSystemTools::FileExists(lastTestsFailedLog)) {
  1747. if (!this->CTest->GetShowOnly() && !this->CTest->ShouldPrintLabels()) {
  1748. cmCTestLog(this->CTest, ERROR_MESSAGE,
  1749. lastTestsFailedLog << " does not exist!" << std::endl);
  1750. }
  1751. return;
  1752. }
  1753. // parse the list of tests to rerun from LastTestsFailed.log
  1754. cmsys::ifstream ifs(lastTestsFailedLog.c_str());
  1755. if (ifs) {
  1756. std::string line;
  1757. std::string::size_type pos;
  1758. while (cmSystemTools::GetLineFromStream(ifs, line)) {
  1759. pos = line.find(':', 0);
  1760. if (pos == std::string::npos) {
  1761. continue;
  1762. }
  1763. line.erase(pos);
  1764. int val = atoi(line.c_str());
  1765. this->TestsToRun.push_back(val);
  1766. }
  1767. ifs.close();
  1768. } else if (!this->CTest->GetShowOnly() &&
  1769. !this->CTest->ShouldPrintLabels()) {
  1770. cmCTestLog(this->CTest, ERROR_MESSAGE,
  1771. "Problem reading file: "
  1772. << lastTestsFailedLog
  1773. << " while generating list of previously failed tests."
  1774. << std::endl);
  1775. }
  1776. }
  1777. cm::optional<std::set<std::string>> cmCTestTestHandler::ReadTestListFile(
  1778. std::string const& testListFileName) const
  1779. {
  1780. cm::optional<std::set<std::string>> result;
  1781. cmsys::ifstream ifs(testListFileName.c_str());
  1782. if (ifs) {
  1783. std::set<std::string> testNames;
  1784. std::string line;
  1785. while (cmSystemTools::GetLineFromStream(ifs, line)) {
  1786. if (!line.empty()) {
  1787. testNames.insert(line);
  1788. }
  1789. }
  1790. result = std::move(testNames);
  1791. } else {
  1792. cmCTestLog(this->CTest, ERROR_MESSAGE,
  1793. "Problem reading test list file: "
  1794. << testListFileName
  1795. << " while generating list of tests to run." << std::endl);
  1796. }
  1797. return result;
  1798. }
  1799. void cmCTestTestHandler::RecordCustomTestMeasurements(cmXMLWriter& xml,
  1800. std::string content)
  1801. {
  1802. while (this->SingleTestMeasurementRegex.find(content)) {
  1803. // Extract regex match from content and parse it as an XML element.
  1804. auto measurement_str = this->SingleTestMeasurementRegex.match(1);
  1805. auto parser = cmCTestTestMeasurementXMLParser();
  1806. parser.Parse(measurement_str.c_str());
  1807. if (parser.ElementName == "CTestMeasurement" ||
  1808. parser.ElementName == "DartMeasurement") {
  1809. xml.StartElement("NamedMeasurement");
  1810. xml.Attribute("type", parser.MeasurementType);
  1811. xml.Attribute("name", parser.MeasurementName);
  1812. xml.Element("Value", parser.CharacterData);
  1813. xml.EndElement();
  1814. } else if (parser.ElementName == "CTestMeasurementFile" ||
  1815. parser.ElementName == "DartMeasurementFile") {
  1816. std::string const& filename = cmCTest::CleanString(parser.CharacterData);
  1817. if (!cmSystemTools::FileExists(filename)) {
  1818. xml.StartElement("NamedMeasurement");
  1819. xml.Attribute("name", parser.MeasurementName);
  1820. xml.Attribute("text", "text/string");
  1821. xml.Element("Value", "File " + filename + " not found");
  1822. xml.EndElement();
  1823. cmCTestOptionalLog(
  1824. this->CTest, HANDLER_OUTPUT,
  1825. "File \"" << filename << "\" not found." << std::endl, this->Quiet);
  1826. } else {
  1827. long len = cmSystemTools::FileLength(filename);
  1828. if (len == 0) {
  1829. xml.StartElement("NamedMeasurement");
  1830. xml.Attribute("name", parser.MeasurementName);
  1831. xml.Attribute("type", "text/string");
  1832. xml.Attribute("encoding", "none");
  1833. xml.Element("Value", "Image " + filename + " is empty");
  1834. xml.EndElement();
  1835. } else {
  1836. if (parser.MeasurementType == "file") {
  1837. // Treat this measurement like an "ATTACHED_FILE" when the type
  1838. // is explicitly "file" (not an image).
  1839. this->AttachFile(xml, filename, parser.MeasurementName);
  1840. } else {
  1841. cmsys::ifstream ifs(filename.c_str(),
  1842. std::ios::in
  1843. #ifdef _WIN32
  1844. | std::ios::binary
  1845. #endif
  1846. );
  1847. auto file_buffer = cm::make_unique<unsigned char[]>(len + 1);
  1848. ifs.read(reinterpret_cast<char*>(file_buffer.get()), len);
  1849. auto encoded_buffer = cm::make_unique<unsigned char[]>(
  1850. static_cast<int>(static_cast<double>(len) * 1.5 + 5.0));
  1851. size_t rlen = cmsysBase64_Encode(file_buffer.get(), len,
  1852. encoded_buffer.get(), 1);
  1853. xml.StartElement("NamedMeasurement");
  1854. xml.Attribute("name", parser.MeasurementName);
  1855. xml.Attribute("type", parser.MeasurementType);
  1856. xml.Attribute("encoding", "base64");
  1857. std::ostringstream ostr;
  1858. for (size_t cc = 0; cc < rlen; cc++) {
  1859. ostr << encoded_buffer[cc];
  1860. if (cc % 60 == 0 && cc) {
  1861. ostr << std::endl;
  1862. }
  1863. }
  1864. xml.Element("Value", ostr.str());
  1865. xml.EndElement(); // NamedMeasurement
  1866. }
  1867. }
  1868. }
  1869. }
  1870. // Remove this element from content.
  1871. cmSystemTools::ReplaceString(content, measurement_str.c_str(), "");
  1872. }
  1873. }
  1874. void cmCTestTestHandler::SetTestsToRunInformation(std::string const& in)
  1875. {
  1876. this->TestsToRunString = in;
  1877. // if the argument is a file, then read it and use the contents as the
  1878. // string
  1879. if (cmSystemTools::FileExists(in)) {
  1880. cmsys::ifstream fin(in.c_str());
  1881. unsigned long filelen = cmSystemTools::FileLength(in);
  1882. auto buff = cm::make_unique<char[]>(filelen + 1);
  1883. fin.getline(buff.get(), filelen);
  1884. buff[fin.gcount()] = 0;
  1885. this->TestsToRunString = buff.get();
  1886. }
  1887. }
  1888. void cmCTestTestHandler::CleanTestOutput(std::string& output, size_t length,
  1889. cmCTestTypes::TruncationMode truncate)
  1890. {
  1891. if (!length || length >= output.size() ||
  1892. output.find("CTEST_FULL_OUTPUT") != std::string::npos) {
  1893. return;
  1894. }
  1895. // Advance n bytes in string delimited by begin/end but do not break in the
  1896. // middle of a multi-byte UTF-8 encoding.
  1897. auto utf8_advance = [](char const* const begin, char const* const end,
  1898. size_t n) -> char const* {
  1899. char const* const stop = begin + n;
  1900. char const* current = begin;
  1901. while (current < stop) {
  1902. unsigned int ch;
  1903. if (char const* next = cm_utf8_decode_character(current, end, &ch)) {
  1904. if (next > stop) {
  1905. break;
  1906. }
  1907. current = next;
  1908. } else // Bad byte will be handled by cmXMLWriter.
  1909. {
  1910. ++current;
  1911. }
  1912. }
  1913. return current;
  1914. };
  1915. // Truncation message.
  1916. std::string const msg =
  1917. cmStrCat("\n[This part of the test output was removed since it exceeds "
  1918. "the threshold of ",
  1919. length, " bytes.]\n");
  1920. char const* const begin = output.c_str();
  1921. char const* const end = begin + output.size();
  1922. // Erase head, middle or tail of output.
  1923. if (truncate == cmCTestTypes::TruncationMode::Head) {
  1924. char const* current = utf8_advance(begin, end, output.size() - length);
  1925. output.erase(0, current - begin);
  1926. output.insert(0, msg + "...");
  1927. } else if (truncate == cmCTestTypes::TruncationMode::Middle) {
  1928. char const* current = utf8_advance(begin, end, length / 2);
  1929. output.erase(current - begin, output.size() - length);
  1930. output.insert(current - begin, "..." + msg + "...");
  1931. } else { // default or "tail"
  1932. char const* current = utf8_advance(begin, end, length);
  1933. output.erase(current - begin);
  1934. output += ("..." + msg);
  1935. }
  1936. }
  1937. void cmCTestTestHandler::cmCTestTestProperties::AppendError(
  1938. cm::string_view err)
  1939. {
  1940. if (this->Error) {
  1941. *this->Error = cmStrCat(*this->Error, '\n', err);
  1942. } else {
  1943. this->Error = err;
  1944. }
  1945. }
  1946. bool cmCTestTestHandler::SetTestsProperties(
  1947. std::vector<std::string> const& args)
  1948. {
  1949. std::vector<std::string>::const_iterator it;
  1950. std::vector<std::string> tests;
  1951. bool found = false;
  1952. for (it = args.begin(); it != args.end(); ++it) {
  1953. if (*it == "PROPERTIES") {
  1954. found = true;
  1955. break;
  1956. }
  1957. tests.push_back(*it);
  1958. }
  1959. if (!found) {
  1960. return false;
  1961. }
  1962. ++it; // skip PROPERTIES
  1963. for (; it != args.end(); ++it) {
  1964. std::string const& key = *it;
  1965. ++it;
  1966. if (it == args.end()) {
  1967. break;
  1968. }
  1969. std::string const& val = *it;
  1970. for (std::string const& t : tests) {
  1971. for (cmCTestTestProperties& rt : this->TestList) {
  1972. if (t == rt.Name) {
  1973. if (key == "_BACKTRACE_TRIPLES"_s) {
  1974. // allow empty args in the triples
  1975. cmList triples{ val, cmList::EmptyElements::Yes };
  1976. // Ensure we have complete triples otherwise the data is corrupt.
  1977. if (triples.size() % 3 == 0) {
  1978. cmState state(cmState::Unknown);
  1979. rt.Backtrace = cmListFileBacktrace();
  1980. // the first entry represents the top of the trace so we need to
  1981. // reconstruct the backtrace in reverse
  1982. for (auto i = triples.size(); i >= 3; i -= 3) {
  1983. cmListFileContext fc;
  1984. fc.FilePath = triples[i - 3];
  1985. long line = 0;
  1986. if (!cmStrToLong(triples[i - 2], &line)) {
  1987. line = 0;
  1988. }
  1989. fc.Line = line;
  1990. fc.Name = triples[i - 1];
  1991. rt.Backtrace = rt.Backtrace.Push(fc);
  1992. }
  1993. }
  1994. } else if (key == "WILL_FAIL"_s) {
  1995. rt.WillFail = cmIsOn(val);
  1996. } else if (key == "DISABLED"_s) {
  1997. rt.Disabled = cmIsOn(val);
  1998. } else if (key == "ATTACHED_FILES"_s) {
  1999. cmExpandList(val, rt.AttachedFiles);
  2000. } else if (key == "ATTACHED_FILES_ON_FAIL"_s) {
  2001. cmExpandList(val, rt.AttachOnFail);
  2002. } else if (key == "RESOURCE_LOCK"_s) {
  2003. cmList lval{ val };
  2004. rt.ProjectResources.insert(lval.begin(), lval.end());
  2005. } else if (key == "FIXTURES_SETUP"_s) {
  2006. cmList lval{ val };
  2007. rt.FixturesSetup.insert(lval.begin(), lval.end());
  2008. } else if (key == "FIXTURES_CLEANUP"_s) {
  2009. cmList lval{ val };
  2010. rt.FixturesCleanup.insert(lval.begin(), lval.end());
  2011. } else if (key == "FIXTURES_REQUIRED"_s) {
  2012. cmList lval{ val };
  2013. rt.FixturesRequired.insert(lval.begin(), lval.end());
  2014. } else if (key == "TIMEOUT"_s) {
  2015. rt.Timeout = cmDuration(atof(val.c_str()));
  2016. } else if (key == "TIMEOUT_SIGNAL_NAME"_s) {
  2017. #ifdef _WIN32
  2018. rt.AppendError("TIMEOUT_SIGNAL_NAME is not supported on Windows.");
  2019. #else
  2020. std::string const& signalName = val;
  2021. Signal s;
  2022. if (signalName == "SIGINT"_s) {
  2023. s.Number = SIGINT;
  2024. } else if (signalName == "SIGQUIT"_s) {
  2025. s.Number = SIGQUIT;
  2026. } else if (signalName == "SIGTERM"_s) {
  2027. s.Number = SIGTERM;
  2028. } else if (signalName == "SIGUSR1"_s) {
  2029. s.Number = SIGUSR1;
  2030. } else if (signalName == "SIGUSR2"_s) {
  2031. s.Number = SIGUSR2;
  2032. }
  2033. if (s.Number) {
  2034. s.Name = signalName;
  2035. rt.TimeoutSignal = std::move(s);
  2036. } else {
  2037. rt.AppendError(cmStrCat("TIMEOUT_SIGNAL_NAME \"", signalName,
  2038. "\" not supported on this platform."));
  2039. }
  2040. #endif
  2041. } else if (key == "TIMEOUT_SIGNAL_GRACE_PERIOD"_s) {
  2042. #ifdef _WIN32
  2043. rt.AppendError(
  2044. "TIMEOUT_SIGNAL_GRACE_PERIOD is not supported on Windows.");
  2045. #else
  2046. std::string const& gracePeriod = val;
  2047. static cmDuration minGracePeriod{ 0 };
  2048. static cmDuration maxGracePeriod{ 60 };
  2049. cmDuration gp = cmDuration(atof(gracePeriod.c_str()));
  2050. if (gp <= minGracePeriod) {
  2051. rt.AppendError(cmStrCat("TIMEOUT_SIGNAL_GRACE_PERIOD \"",
  2052. gracePeriod, "\" is not greater than \"",
  2053. minGracePeriod.count(), "\" seconds."));
  2054. } else if (gp > maxGracePeriod) {
  2055. rt.AppendError(cmStrCat("TIMEOUT_SIGNAL_GRACE_PERIOD \"",
  2056. gracePeriod,
  2057. "\" is not less than the maximum of \"",
  2058. maxGracePeriod.count(), "\" seconds."));
  2059. } else {
  2060. rt.TimeoutGracePeriod = gp;
  2061. }
  2062. #endif
  2063. } else if (key == "COST"_s) {
  2064. rt.Cost = static_cast<float>(atof(val.c_str()));
  2065. } else if (key == "REQUIRED_FILES"_s) {
  2066. cmExpandList(val, rt.RequiredFiles);
  2067. } else if (key == "RUN_SERIAL"_s) {
  2068. rt.RunSerial = cmIsOn(val);
  2069. } else if (key == "FAIL_REGULAR_EXPRESSION"_s) {
  2070. cmList lval{ val };
  2071. for (std::string const& cr : lval) {
  2072. rt.ErrorRegularExpressions.emplace_back(cr, cr);
  2073. }
  2074. } else if (key == "SKIP_REGULAR_EXPRESSION"_s) {
  2075. cmList lval{ val };
  2076. for (std::string const& cr : lval) {
  2077. rt.SkipRegularExpressions.emplace_back(cr, cr);
  2078. }
  2079. } else if (key == "PROCESSORS"_s) {
  2080. rt.Processors = atoi(val.c_str());
  2081. if (rt.Processors < 1) {
  2082. rt.Processors = 1;
  2083. }
  2084. } else if (key == "PROCESSOR_AFFINITY"_s) {
  2085. rt.WantAffinity = cmIsOn(val);
  2086. } else if (key == "RESOURCE_GROUPS"_s) {
  2087. if (!ParseResourceGroupsProperty(val, rt.ResourceGroups)) {
  2088. return false;
  2089. }
  2090. } else if (key == "GENERATED_RESOURCE_SPEC_FILE"_s) {
  2091. rt.GeneratedResourceSpecFile = val;
  2092. } else if (key == "SKIP_RETURN_CODE"_s) {
  2093. rt.SkipReturnCode = atoi(val.c_str());
  2094. if (rt.SkipReturnCode < 0 || rt.SkipReturnCode > 255) {
  2095. rt.SkipReturnCode = -1;
  2096. }
  2097. } else if (key == "DEPENDS"_s) {
  2098. cmExpandList(val, rt.Depends);
  2099. } else if (key == "ENVIRONMENT"_s) {
  2100. cmExpandList(val, rt.Environment);
  2101. } else if (key == "ENVIRONMENT_MODIFICATION"_s) {
  2102. cmExpandList(val, rt.EnvironmentModification);
  2103. } else if (key == "LABELS"_s) {
  2104. cmList Labels{ val };
  2105. rt.Labels.insert(rt.Labels.end(), Labels.begin(), Labels.end());
  2106. // sort the array
  2107. std::sort(rt.Labels.begin(), rt.Labels.end());
  2108. // remove duplicates
  2109. auto new_end = std::unique(rt.Labels.begin(), rt.Labels.end());
  2110. rt.Labels.erase(new_end, rt.Labels.end());
  2111. } else if (key == "MEASUREMENT"_s) {
  2112. size_t pos = val.find_first_of('=');
  2113. if (pos != std::string::npos) {
  2114. std::string mKey = val.substr(0, pos);
  2115. std::string mVal = val.substr(pos + 1);
  2116. rt.Measurements[mKey] = std::move(mVal);
  2117. } else {
  2118. rt.Measurements[val] = "1";
  2119. }
  2120. } else if (key == "PASS_REGULAR_EXPRESSION"_s) {
  2121. cmList lval{ val };
  2122. for (std::string const& cr : lval) {
  2123. rt.RequiredRegularExpressions.emplace_back(cr, cr);
  2124. }
  2125. } else if (key == "WORKING_DIRECTORY"_s) {
  2126. rt.Directory = val;
  2127. } else if (key == "TIMEOUT_AFTER_MATCH"_s) {
  2128. cmList propArgs{ val };
  2129. if (propArgs.size() != 2) {
  2130. cmCTestLog(this->CTest, WARNING,
  2131. "TIMEOUT_AFTER_MATCH expects two arguments, found "
  2132. << propArgs.size() << std::endl);
  2133. } else {
  2134. rt.AlternateTimeout = cmDuration(atof(propArgs[0].c_str()));
  2135. cmList lval{ propArgs[1] };
  2136. for (std::string const& cr : lval) {
  2137. rt.TimeoutRegularExpressions.emplace_back(cr, cr);
  2138. }
  2139. }
  2140. } else {
  2141. rt.CustomProperties[key] = val;
  2142. }
  2143. }
  2144. }
  2145. }
  2146. }
  2147. return true;
  2148. }
  2149. bool cmCTestTestHandler::SetDirectoryProperties(
  2150. std::vector<std::string> const& args)
  2151. {
  2152. std::vector<std::string>::const_iterator it;
  2153. std::vector<std::string> tests;
  2154. bool found = false;
  2155. for (it = args.begin(); it != args.end(); ++it) {
  2156. if (*it == "PROPERTIES") {
  2157. found = true;
  2158. break;
  2159. }
  2160. tests.push_back(*it);
  2161. }
  2162. if (!found) {
  2163. return false;
  2164. }
  2165. ++it; // skip PROPERTIES
  2166. for (; it != args.end(); ++it) {
  2167. std::string const& key = *it;
  2168. ++it;
  2169. if (it == args.end()) {
  2170. break;
  2171. }
  2172. std::string const& val = *it;
  2173. for (cmCTestTestProperties& rt : this->TestList) {
  2174. std::string cwd = cmSystemTools::GetLogicalWorkingDirectory();
  2175. if (cwd == rt.Directory) {
  2176. if (key == "LABELS"_s) {
  2177. cmList DirectoryLabels{ val };
  2178. rt.Labels.insert(rt.Labels.end(), DirectoryLabels.begin(),
  2179. DirectoryLabels.end());
  2180. // sort the array
  2181. std::sort(rt.Labels.begin(), rt.Labels.end());
  2182. // remove duplicates
  2183. auto new_end = std::unique(rt.Labels.begin(), rt.Labels.end());
  2184. rt.Labels.erase(new_end, rt.Labels.end());
  2185. }
  2186. }
  2187. }
  2188. }
  2189. return true;
  2190. }
  2191. bool cmCTestTestHandler::AddTest(std::vector<std::string> const& args)
  2192. {
  2193. std::string const& testname = args[0];
  2194. cmCTestOptionalLog(this->CTest, DEBUG, "Add test: " << args[0] << std::endl,
  2195. this->Quiet);
  2196. if (this->UseExcludeRegExpFlag && this->UseExcludeRegExpFirst &&
  2197. this->ExcludeTestsRegularExpression.find(testname)) {
  2198. return true;
  2199. }
  2200. if (this->MemCheck) {
  2201. std::vector<std::string>::iterator it;
  2202. bool found = false;
  2203. for (it = this->CustomTestsIgnore.begin();
  2204. it != this->CustomTestsIgnore.end(); ++it) {
  2205. if (*it == testname) {
  2206. found = true;
  2207. break;
  2208. }
  2209. }
  2210. if (found) {
  2211. cmCTestOptionalLog(this->CTest, HANDLER_VERBOSE_OUTPUT,
  2212. "Ignore memcheck: " << *it << std::endl, this->Quiet);
  2213. return true;
  2214. }
  2215. } else {
  2216. std::vector<std::string>::iterator it;
  2217. bool found = false;
  2218. for (it = this->CustomTestsIgnore.begin();
  2219. it != this->CustomTestsIgnore.end(); ++it) {
  2220. if (*it == testname) {
  2221. found = true;
  2222. break;
  2223. }
  2224. }
  2225. if (found) {
  2226. cmCTestOptionalLog(this->CTest, HANDLER_VERBOSE_OUTPUT,
  2227. "Ignore test: " << *it << std::endl, this->Quiet);
  2228. return true;
  2229. }
  2230. }
  2231. cmCTestTestProperties test;
  2232. test.Name = testname;
  2233. test.Args = args;
  2234. test.Directory = cmSystemTools::GetLogicalWorkingDirectory();
  2235. cmCTestOptionalLog(this->CTest, DEBUG,
  2236. "Set test directory: " << test.Directory << std::endl,
  2237. this->Quiet);
  2238. if (this->UseIncludeRegExpFlag &&
  2239. (!this->IncludeTestsRegularExpression.find(testname) ||
  2240. (!this->UseExcludeRegExpFirst &&
  2241. this->ExcludeTestsRegularExpression.find(testname)))) {
  2242. test.IsInBasedOnREOptions = false;
  2243. }
  2244. this->TestList.push_back(test);
  2245. return true;
  2246. }
  2247. bool cmCTestTestHandler::cmCTestTestResourceRequirement::operator==(
  2248. cmCTestTestResourceRequirement const& other) const
  2249. {
  2250. return this->ResourceType == other.ResourceType &&
  2251. this->SlotsNeeded == other.SlotsNeeded &&
  2252. this->UnitsNeeded == other.UnitsNeeded;
  2253. }
  2254. bool cmCTestTestHandler::cmCTestTestResourceRequirement::operator!=(
  2255. cmCTestTestResourceRequirement const& other) const
  2256. {
  2257. return !(*this == other);
  2258. }
  2259. void cmCTestTestHandler::SetJUnitXMLFileName(std::string const& filename)
  2260. {
  2261. this->TestOptions.JUnitXMLFileName = filename;
  2262. }
  2263. bool cmCTestTestHandler::WriteJUnitXML()
  2264. {
  2265. if (this->TestOptions.JUnitXMLFileName.empty()) {
  2266. return true;
  2267. }
  2268. // Open new XML file for writing.
  2269. cmGeneratedFileStream xmlfile;
  2270. xmlfile.SetTempExt("tmp");
  2271. xmlfile.Open(this->TestOptions.JUnitXMLFileName);
  2272. if (!xmlfile) {
  2273. cmCTestLog(this->CTest, ERROR_MESSAGE,
  2274. "Problem opening file: " << this->TestOptions.JUnitXMLFileName
  2275. << std::endl);
  2276. return false;
  2277. }
  2278. cmXMLWriter xml(xmlfile);
  2279. // Iterate over the test results to get the number of tests that
  2280. // passed, failed, etc.
  2281. auto num_tests = 0;
  2282. auto num_failed = 0;
  2283. auto num_notrun = 0;
  2284. auto num_disabled = 0;
  2285. SetOfTests resultsSet(this->TestResults.begin(), this->TestResults.end());
  2286. for (cmCTestTestResult const& result : resultsSet) {
  2287. num_tests++;
  2288. if (result.Status == cmCTestTestHandler::NOT_RUN) {
  2289. if (result.CompletionStatus == "Disabled") {
  2290. num_disabled++;
  2291. } else {
  2292. num_notrun++;
  2293. }
  2294. } else if (result.Status != cmCTestTestHandler::COMPLETED) {
  2295. num_failed++;
  2296. }
  2297. }
  2298. // Write <testsuite> element.
  2299. xml.StartDocument();
  2300. xml.StartElement("testsuite");
  2301. xml.Attribute("name",
  2302. cmCTest::SafeBuildIdField(
  2303. this->CTest->GetCTestConfiguration("BuildName")));
  2304. xml.BreakAttributes();
  2305. xml.Attribute("tests", num_tests);
  2306. xml.Attribute("failures", num_failed);
  2307. // CTest disabled => JUnit disabled
  2308. xml.Attribute("disabled", num_disabled);
  2309. // Otherwise, CTest notrun => JUnit skipped.
  2310. // The distinction between JUnit disabled vs. skipped is that
  2311. // skipped tests can have a message associated with them
  2312. // (why the test was skipped).
  2313. xml.Attribute("skipped", num_notrun);
  2314. xml.Attribute("hostname", this->CTest->GetCTestConfiguration("Site"));
  2315. xml.Attribute(
  2316. "time",
  2317. std::chrono::duration_cast<std::chrono::seconds>(this->ElapsedTestingTime)
  2318. .count());
  2319. std::time_t const start_test_time_t =
  2320. std::chrono::system_clock::to_time_t(this->StartTestTime);
  2321. cmTimestamp cmts;
  2322. xml.Attribute("timestamp",
  2323. cmts.CreateTimestampFromTimeT(start_test_time_t,
  2324. "%Y-%m-%dT%H:%M:%S", false));
  2325. // Write <testcase> elements.
  2326. for (cmCTestTestResult const& result : resultsSet) {
  2327. xml.StartElement("testcase");
  2328. xml.Attribute("name", result.Name);
  2329. xml.Attribute("classname", result.Name);
  2330. xml.Attribute("time", result.ExecutionTime.count());
  2331. std::string status;
  2332. if (result.Status == cmCTestTestHandler::COMPLETED) {
  2333. status = "run";
  2334. } else if (result.Status == cmCTestTestHandler::NOT_RUN) {
  2335. if (result.CompletionStatus == "Disabled") {
  2336. status = "disabled";
  2337. } else {
  2338. status = "notrun";
  2339. }
  2340. } else {
  2341. status = "fail";
  2342. }
  2343. xml.Attribute("status", status);
  2344. if (status == "notrun") {
  2345. xml.StartElement("skipped");
  2346. xml.Attribute("message", result.CompletionStatus);
  2347. xml.EndElement(); // </skipped>
  2348. } else if (status == "fail") {
  2349. xml.StartElement("failure");
  2350. xml.Attribute("message", this->GetTestStatus(result));
  2351. xml.EndElement(); // </failure>
  2352. }
  2353. xml.StartElement("properties");
  2354. if ((result.Properties) && (!result.Properties->Labels.empty())) {
  2355. xml.StartElement("property");
  2356. xml.Attribute("name", "cmake_labels");
  2357. // Pass the property as a cmake-formatted list, consumers will know
  2358. // anyway that this information is coming from cmake, so it should
  2359. // be ok to put it here as a cmake-list.
  2360. xml.Attribute("value", cmList::to_string(result.Properties->Labels));
  2361. // if we export more properties, this should be done the same way,
  2362. // i.e. prefix the property name with "cmake_", and it it can be
  2363. // a list, write it cmake-formatted.
  2364. xml.EndElement(); // </property>
  2365. }
  2366. xml.EndElement(); // </properties>
  2367. // Note: compressed test output is unconditionally disabled when
  2368. // --output-junit is specified.
  2369. xml.Element("system-out", result.Output);
  2370. xml.EndElement(); // </testcase>
  2371. }
  2372. xml.EndElement(); // </testsuite>
  2373. xml.EndDocument();
  2374. return true;
  2375. }