cmCTestTestHandler.cxx 84 KB

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