cmCTestTestHandler.cxx 88 KB

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