cmCTestTestHandler.cxx 89 KB

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