cmCTestTestHandler.cxx 86 KB

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