cmCTestTestHandler.cxx 86 KB

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