cmCTestTestHandler.cxx 87 KB

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