cmCTestTestHandler.cxx 86 KB

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