cmCTestTestHandler.cxx 87 KB

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