cmCTestTestHandler.cxx 84 KB

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