cmCTestTestHandler.cxx 86 KB

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