cmCTestTestHandler.cxx 83 KB

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