cmCTestTestHandler.cxx 86 KB

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