cmCTestTestHandler.cxx 84 KB

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