cmCTestTestHandler.cxx 88 KB

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