cmCTest.h 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689
  1. /* Distributed under the OSI-approved BSD 3-Clause License. See accompanying
  2. file Copyright.txt or https://cmake.org/licensing for details. */
  3. #ifndef cmCTest_h
  4. #define cmCTest_h
  5. #include "cmConfigure.h" // IWYU pragma: keep
  6. #include "cmDuration.h"
  7. #include "cmProcessOutput.h"
  8. #include <chrono>
  9. #include <map>
  10. #include <set>
  11. #include <sstream>
  12. #include <string>
  13. #include <time.h>
  14. #include <vector>
  15. class cmCTestGenericHandler;
  16. class cmCTestStartCommand;
  17. class cmGeneratedFileStream;
  18. class cmMakefile;
  19. class cmXMLWriter;
  20. /** \class cmCTest
  21. * \brief Represents a ctest invocation.
  22. *
  23. * This class represents a ctest invocation. It is the top level class when
  24. * running ctest.
  25. *
  26. */
  27. class cmCTest
  28. {
  29. friend class cmCTestRunTest;
  30. friend class cmCTestMultiProcessHandler;
  31. public:
  32. typedef cmProcessOutput::Encoding Encoding;
  33. /** Enumerate parts of the testing and submission process. */
  34. enum Part
  35. {
  36. PartStart,
  37. PartUpdate,
  38. PartConfigure,
  39. PartBuild,
  40. PartTest,
  41. PartCoverage,
  42. PartMemCheck,
  43. PartSubmit,
  44. PartNotes,
  45. PartExtraFiles,
  46. PartUpload,
  47. PartDone,
  48. PartCount // Update names in constructor when adding a part
  49. };
  50. /** Representation of one part. */
  51. struct PartInfo
  52. {
  53. void SetName(const std::string& name) { this->Name = name; }
  54. const std::string& GetName() const { return this->Name; }
  55. void Enable() { this->Enabled = true; }
  56. explicit operator bool() const { return this->Enabled; }
  57. std::vector<std::string> SubmitFiles;
  58. private:
  59. bool Enabled = false;
  60. std::string Name;
  61. };
  62. #ifdef CMAKE_BUILD_WITH_CMAKE
  63. enum HTTPMethod
  64. {
  65. HTTP_GET,
  66. HTTP_POST,
  67. HTTP_PUT
  68. };
  69. /**
  70. * Perform an HTTP request.
  71. */
  72. static int HTTPRequest(std::string url, HTTPMethod method,
  73. std::string& response, std::string const& fields = "",
  74. std::string const& putFile = "", int timeout = 0);
  75. #endif
  76. /** Get a testing part id from its string name. Returns PartCount
  77. if the string does not name a valid part. */
  78. Part GetPartFromName(const char* name);
  79. typedef std::vector<std::string> VectorOfStrings;
  80. typedef std::set<std::string> SetOfStrings;
  81. /** Process Command line arguments */
  82. int Run(std::vector<std::string>&, std::string* output = nullptr);
  83. /**
  84. * Initialize and finalize testing
  85. */
  86. bool InitializeFromCommand(cmCTestStartCommand* command);
  87. void Finalize();
  88. /**
  89. * Process the dashboard client steps.
  90. *
  91. * Steps are enabled using SetTest()
  92. *
  93. * The execution of the steps (or #Part) should look like this:
  94. *
  95. * /code
  96. * ctest foo;
  97. * foo.Initialize();
  98. * // Set some things on foo
  99. * foo.ProcessSteps();
  100. * foo.Finalize();
  101. * /endcode
  102. *
  103. * \sa Initialize(), Finalize(), Part, PartInfo, SetTest()
  104. */
  105. int ProcessSteps();
  106. /**
  107. * A utility function that returns the nightly time
  108. */
  109. struct tm* GetNightlyTime(std::string const& str, bool tomorrowtag);
  110. /**
  111. * Is the tomorrow tag set?
  112. */
  113. bool GetTomorrowTag() { return this->TomorrowTag; }
  114. /**
  115. * Try to run tests of the project
  116. */
  117. int TestDirectory(bool memcheck);
  118. /** what is the configuration type, e.g. Debug, Release etc. */
  119. std::string const& GetConfigType();
  120. cmDuration GetTimeOut() { return this->TimeOut; }
  121. void SetTimeOut(cmDuration t) { this->TimeOut = t; }
  122. cmDuration GetGlobalTimeout() { return this->GlobalTimeout; }
  123. /** how many test to run at the same time */
  124. int GetParallelLevel() { return this->ParallelLevel; }
  125. void SetParallelLevel(int);
  126. unsigned long GetTestLoad() { return this->TestLoad; }
  127. void SetTestLoad(unsigned long);
  128. /**
  129. * Check if CTest file exists
  130. */
  131. bool CTestFileExists(const std::string& filename);
  132. bool AddIfExists(Part part, const char* file);
  133. /**
  134. * Set the cmake test
  135. */
  136. bool SetTest(const char*, bool report = true);
  137. /**
  138. * Set the cmake test mode (experimental, nightly, continuous).
  139. */
  140. void SetTestModel(int mode);
  141. int GetTestModel() { return this->TestModel; }
  142. std::string GetTestModelString();
  143. static int GetTestModelFromString(const char* str);
  144. static std::string CleanString(const std::string& str);
  145. std::string GetCTestConfiguration(const std::string& name);
  146. void SetCTestConfiguration(const char* name, const char* value,
  147. bool suppress = false);
  148. void EmptyCTestConfiguration();
  149. std::string GetSubmitURL();
  150. /**
  151. * constructor and destructor
  152. */
  153. cmCTest();
  154. ~cmCTest();
  155. /** Set the notes files to be created. */
  156. void SetNotesFiles(const char* notes);
  157. void PopulateCustomVector(cmMakefile* mf, const std::string& definition,
  158. std::vector<std::string>& vec);
  159. void PopulateCustomInteger(cmMakefile* mf, const std::string& def, int& val);
  160. /** Get the current time as string */
  161. std::string CurrentTime();
  162. /** tar/gzip and then base 64 encode a file */
  163. std::string Base64GzipEncodeFile(std::string const& file);
  164. /** base64 encode a file */
  165. std::string Base64EncodeFile(std::string const& file);
  166. /**
  167. * Return the time remaining that the script is allowed to run in
  168. * seconds if the user has set the variable CTEST_TIME_LIMIT. If that has
  169. * not been set it returns a very large duration.
  170. */
  171. cmDuration GetRemainingTimeAllowed();
  172. static cmDuration MaxDuration();
  173. /**
  174. * Open file in the output directory and set the stream
  175. */
  176. bool OpenOutputFile(const std::string& path, const std::string& name,
  177. cmGeneratedFileStream& stream, bool compress = false);
  178. /** Should we only show what we would do? */
  179. bool GetShowOnly();
  180. bool GetOutputAsJson();
  181. int GetOutputAsJsonVersion();
  182. bool ShouldUseHTTP10() { return this->UseHTTP10; }
  183. bool ShouldPrintLabels() { return this->PrintLabels; }
  184. bool ShouldCompressTestOutput();
  185. bool CompressString(std::string& str);
  186. std::chrono::system_clock::time_point GetStopTime()
  187. {
  188. return this->StopTime;
  189. }
  190. void SetStopTime(std::string const& time);
  191. /** Used for parallel ctest job scheduling */
  192. std::string GetScheduleType() { return this->ScheduleType; }
  193. void SetScheduleType(std::string const& type) { this->ScheduleType = type; }
  194. /** The max output width */
  195. int GetMaxTestNameWidth() const;
  196. void SetMaxTestNameWidth(int w) { this->MaxTestNameWidth = w; }
  197. /**
  198. * Run a single executable command and put the stdout and stderr
  199. * in output.
  200. *
  201. * If verbose is false, no user-viewable output from the program
  202. * being run will be generated.
  203. *
  204. * If timeout is specified, the command will be terminated after
  205. * timeout expires. Timeout is specified in seconds.
  206. *
  207. * Argument retVal should be a pointer to the location where the
  208. * exit code will be stored. If the retVal is not specified and
  209. * the program exits with a code other than 0, then the this
  210. * function will return false.
  211. */
  212. bool RunCommand(std::vector<std::string> const& args, std::string* stdOut,
  213. std::string* stdErr, int* retVal = nullptr,
  214. const char* dir = nullptr,
  215. cmDuration timeout = cmDuration::zero(),
  216. Encoding encoding = cmProcessOutput::Auto);
  217. /**
  218. * Clean/make safe for xml the given value such that it may be used as
  219. * one of the key fields by CDash when computing the buildid.
  220. */
  221. static std::string SafeBuildIdField(const std::string& value);
  222. /** Start CTest XML output file */
  223. void StartXML(cmXMLWriter& xml, bool append);
  224. /** End CTest XML output file */
  225. void EndXML(cmXMLWriter& xml);
  226. /**
  227. * Run command specialized for make and configure. Returns process status
  228. * and retVal is return value or exception.
  229. */
  230. int RunMakeCommand(const char* command, std::string& output, int* retVal,
  231. const char* dir, cmDuration timeout, std::ostream& ofs,
  232. Encoding encoding = cmProcessOutput::Auto);
  233. /** Return the current tag */
  234. std::string GetCurrentTag();
  235. /** Get the path to the build tree */
  236. std::string GetBinaryDir();
  237. /**
  238. * Get the short path to the file.
  239. *
  240. * This means if the file is in binary or
  241. * source directory, it will become /.../relative/path/to/file
  242. */
  243. std::string GetShortPathToFile(const char* fname);
  244. enum
  245. {
  246. UNKNOWN = -1,
  247. EXPERIMENTAL = 0,
  248. NIGHTLY = 1,
  249. CONTINUOUS = 2,
  250. };
  251. /** provide some more detailed info on the return code for ctest */
  252. enum
  253. {
  254. UPDATE_ERRORS = 0x01,
  255. CONFIGURE_ERRORS = 0x02,
  256. BUILD_ERRORS = 0x04,
  257. TEST_ERRORS = 0x08,
  258. MEMORY_ERRORS = 0x10,
  259. COVERAGE_ERRORS = 0x20,
  260. SUBMIT_ERRORS = 0x40
  261. };
  262. /** Are we producing XML */
  263. bool GetProduceXML();
  264. void SetProduceXML(bool v);
  265. /**
  266. * Run command specialized for tests. Returns process status and retVal is
  267. * return value or exception. If environment is non-null, it is used to set
  268. * environment variables prior to running the test. After running the test,
  269. * environment variables are restored to their previous values.
  270. */
  271. int RunTest(std::vector<const char*> args, std::string* output, int* retVal,
  272. std::ostream* logfile, cmDuration testTimeOut,
  273. std::vector<std::string>* environment,
  274. Encoding encoding = cmProcessOutput::Auto);
  275. /**
  276. * Execute handler and return its result. If the handler fails, it returns
  277. * negative value.
  278. */
  279. int ExecuteHandler(const char* handler);
  280. /**
  281. * Get the handler object
  282. */
  283. cmCTestGenericHandler* GetHandler(const char* handler);
  284. cmCTestGenericHandler* GetInitializedHandler(const char* handler);
  285. /**
  286. * Set the CTest variable from CMake variable
  287. */
  288. bool SetCTestConfigurationFromCMakeVariable(cmMakefile* mf,
  289. const char* dconfig,
  290. const std::string& cmake_var,
  291. bool suppress = false);
  292. /** Make string safe to be sent as a URL */
  293. static std::string MakeURLSafe(const std::string&);
  294. /** Decode a URL to the original string. */
  295. static std::string DecodeURL(const std::string&);
  296. /**
  297. * Should ctect configuration be updated. When using new style ctest
  298. * script, this should be true.
  299. */
  300. void SetSuppressUpdatingCTestConfiguration(bool val)
  301. {
  302. this->SuppressUpdatingCTestConfiguration = val;
  303. }
  304. /**
  305. * Add overwrite to ctest configuration.
  306. *
  307. * The format is key=value
  308. */
  309. void AddCTestConfigurationOverwrite(const std::string& encstr);
  310. /** Create XML file that contains all the notes specified */
  311. int GenerateNotesFile(const VectorOfStrings& files);
  312. /** Create XML file to indicate that build is complete */
  313. int GenerateDoneFile();
  314. /** Submit extra files to the server */
  315. bool SubmitExtraFiles(const char* files);
  316. bool SubmitExtraFiles(const VectorOfStrings& files);
  317. /** Set the output log file name */
  318. void SetOutputLogFileName(const char* name);
  319. /** Set the visual studio or Xcode config type */
  320. void SetConfigType(const char* ct);
  321. /** Various log types */
  322. enum
  323. {
  324. DEBUG = 0,
  325. OUTPUT,
  326. HANDLER_OUTPUT,
  327. HANDLER_PROGRESS_OUTPUT,
  328. HANDLER_TEST_PROGRESS_OUTPUT,
  329. HANDLER_VERBOSE_OUTPUT,
  330. WARNING,
  331. ERROR_MESSAGE,
  332. OTHER
  333. };
  334. /** Add log to the output */
  335. void Log(int logType, const char* file, int line, const char* msg,
  336. bool suppress = false);
  337. /** Color values */
  338. enum class Color
  339. {
  340. CLEAR_COLOR = 0,
  341. RED = 31,
  342. GREEN = 32,
  343. YELLOW = 33,
  344. BLUE = 34
  345. };
  346. /** Get color code characters for a specific color */
  347. std::string GetColorCode(Color color) const;
  348. /** The Build ID is assigned by CDash */
  349. void SetBuildID(const std::string& id) { this->BuildID = id; }
  350. std::string GetBuildID() { return this->BuildID; }
  351. /** Add file to be submitted */
  352. void AddSubmitFile(Part part, const char* name);
  353. std::vector<std::string> const& GetSubmitFiles(Part part)
  354. {
  355. return this->Parts[part].SubmitFiles;
  356. }
  357. void ClearSubmitFiles(Part part) { this->Parts[part].SubmitFiles.clear(); }
  358. /**
  359. * Read the custom configuration files and apply them to the current ctest
  360. */
  361. int ReadCustomConfigurationFileTree(const char* dir, cmMakefile* mf);
  362. std::vector<std::string>& GetInitialCommandLineArguments()
  363. {
  364. return this->InitialCommandLineArguments;
  365. }
  366. /** Set the track to submit to */
  367. void SetSpecificTrack(const char* track);
  368. const char* GetSpecificTrack();
  369. void SetFailover(bool failover) { this->Failover = failover; }
  370. bool GetFailover() { return this->Failover; }
  371. bool GetTestProgressOutput() const { return this->TestProgressOutput; }
  372. bool GetVerbose() { return this->Verbose; }
  373. bool GetExtraVerbose() { return this->ExtraVerbose; }
  374. /** Direct process output to given streams. */
  375. void SetStreams(std::ostream* out, std::ostream* err)
  376. {
  377. this->StreamOut = out;
  378. this->StreamErr = err;
  379. }
  380. void AddSiteProperties(cmXMLWriter& xml);
  381. bool GetLabelSummary() { return this->LabelSummary; }
  382. bool GetSubprojectSummary() { return this->SubprojectSummary; }
  383. std::string GetCostDataFile();
  384. const std::map<std::string, std::string>& GetDefinitions()
  385. {
  386. return this->Definitions;
  387. }
  388. /** Return the number of times a test should be run */
  389. int GetTestRepeat() { return this->RepeatTests; }
  390. /** Return true if test should run until fail */
  391. bool GetRepeatUntilFail() { return this->RepeatUntilFail; }
  392. void GenerateSubprojectsOutput(cmXMLWriter& xml);
  393. std::vector<std::string> GetLabelsForSubprojects();
  394. void SetRunCurrentScript(bool value);
  395. private:
  396. int RepeatTests;
  397. bool RepeatUntilFail;
  398. std::string ConfigType;
  399. std::string ScheduleType;
  400. std::chrono::system_clock::time_point StopTime;
  401. bool TestProgressOutput;
  402. bool Verbose;
  403. bool ExtraVerbose;
  404. bool ProduceXML;
  405. bool LabelSummary;
  406. bool SubprojectSummary;
  407. bool UseHTTP10;
  408. bool PrintLabels;
  409. bool Failover;
  410. bool FlushTestProgressLine;
  411. bool ForceNewCTestProcess;
  412. bool RunConfigurationScript;
  413. int GenerateNotesFile(const char* files);
  414. // these are helper classes
  415. typedef std::map<std::string, cmCTestGenericHandler*> t_TestingHandlers;
  416. t_TestingHandlers TestingHandlers;
  417. bool ShowOnly;
  418. bool OutputAsJson;
  419. int OutputAsJsonVersion;
  420. /** Map of configuration properties */
  421. typedef std::map<std::string, std::string> CTestConfigurationMap;
  422. // TODO: The ctest configuration should be a hierarchy of
  423. // configuration option sources: command-line, script, ini file.
  424. // Then the ini file can get re-loaded whenever it changes without
  425. // affecting any higher-precedence settings.
  426. CTestConfigurationMap CTestConfiguration;
  427. CTestConfigurationMap CTestConfigurationOverwrites;
  428. PartInfo Parts[PartCount];
  429. typedef std::map<std::string, Part> PartMapType;
  430. PartMapType PartMap;
  431. std::string CurrentTag;
  432. bool TomorrowTag;
  433. int TestModel;
  434. std::string SpecificTrack;
  435. cmDuration TimeOut;
  436. cmDuration GlobalTimeout;
  437. int MaxTestNameWidth;
  438. int ParallelLevel;
  439. bool ParallelLevelSetInCli;
  440. unsigned long TestLoad;
  441. int CompatibilityMode;
  442. // information for the --build-and-test options
  443. std::string BinaryDir;
  444. std::string NotesFiles;
  445. bool InteractiveDebugMode;
  446. bool ShortDateFormat;
  447. bool CompressXMLFiles;
  448. bool CompressTestOutput;
  449. void InitStreams();
  450. std::ostream* StreamOut;
  451. std::ostream* StreamErr;
  452. void BlockTestErrorDiagnostics();
  453. /**
  454. * Initialize a dashboard run in the given build tree. The "command"
  455. * argument is non-NULL when running from a command-driven (ctest_start)
  456. * dashboard script, and NULL when running from the CTest command
  457. * line. Note that a declarative dashboard script does not actually
  458. * call this method because it sets CTEST_COMMAND to drive a build
  459. * through the ctest command line.
  460. */
  461. int Initialize(const char* binary_dir, cmCTestStartCommand* command);
  462. /** parse the option after -D and convert it into the appropriate steps */
  463. bool AddTestsForDashboardType(std::string& targ);
  464. /** read as "emit an error message for an unknown -D value" */
  465. void ErrorMessageUnknownDashDValue(std::string& val);
  466. /** add a variable definition from a command line -D value */
  467. bool AddVariableDefinition(const std::string& arg);
  468. /** parse and process most common command line arguments */
  469. bool HandleCommandLineArguments(size_t& i, std::vector<std::string>& args,
  470. std::string& errormsg);
  471. #if !defined(_WIN32)
  472. /** returns true iff the console supports progress output */
  473. static bool ConsoleIsNotDumb();
  474. #endif
  475. /** returns true iff the console supports progress output */
  476. static bool ProgressOutputSupportedByConsole();
  477. /** returns true iff the console supports colored output */
  478. static bool ColoredOutputSupportedByConsole();
  479. /** handle the -S -SP and -SR arguments */
  480. void HandleScriptArguments(size_t& i, std::vector<std::string>& args,
  481. bool& SRArgumentSpecified);
  482. /** Reread the configuration file */
  483. bool UpdateCTestConfiguration();
  484. /** Create note from files. */
  485. int GenerateCTestNotesOutput(cmXMLWriter& xml, const VectorOfStrings& files);
  486. /** Check if the argument is the one specified */
  487. bool CheckArgument(const std::string& arg, const char* varg1,
  488. const char* varg2 = nullptr);
  489. /** Output errors from a test */
  490. void OutputTestErrors(std::vector<char> const& process_output);
  491. /** Handle the --test-action command line argument */
  492. bool HandleTestActionArgument(const char* ctestExec, size_t& i,
  493. const std::vector<std::string>& args);
  494. /** Handle the --test-model command line argument */
  495. bool HandleTestModelArgument(const char* ctestExec, size_t& i,
  496. const std::vector<std::string>& args);
  497. int RunCMakeAndTest(std::string* output);
  498. int ExecuteTests();
  499. bool SuppressUpdatingCTestConfiguration;
  500. bool Debug;
  501. bool ShowLineNumbers;
  502. bool Quiet;
  503. std::string BuildID;
  504. std::vector<std::string> InitialCommandLineArguments;
  505. int SubmitIndex;
  506. cmGeneratedFileStream* OutputLogFile;
  507. int OutputLogFileLastTag;
  508. bool OutputTestOutputOnTestFailure;
  509. bool OutputColorCode;
  510. std::map<std::string, std::string> Definitions;
  511. };
  512. class cmCTestLogWrite
  513. {
  514. public:
  515. cmCTestLogWrite(const char* data, size_t length)
  516. : Data(data)
  517. , Length(length)
  518. {
  519. }
  520. const char* Data;
  521. size_t Length;
  522. };
  523. inline std::ostream& operator<<(std::ostream& os, const cmCTestLogWrite& c)
  524. {
  525. if (!c.Length) {
  526. return os;
  527. }
  528. os.write(c.Data, c.Length);
  529. os.flush();
  530. return os;
  531. }
  532. #define cmCTestLog(ctSelf, logType, msg) \
  533. do { \
  534. std::ostringstream cmCTestLog_msg; \
  535. cmCTestLog_msg << msg; \
  536. (ctSelf)->Log(cmCTest::logType, __FILE__, __LINE__, \
  537. cmCTestLog_msg.str().c_str()); \
  538. } while (false)
  539. #define cmCTestOptionalLog(ctSelf, logType, msg, suppress) \
  540. do { \
  541. std::ostringstream cmCTestLog_msg; \
  542. cmCTestLog_msg << msg; \
  543. (ctSelf)->Log(cmCTest::logType, __FILE__, __LINE__, \
  544. cmCTestLog_msg.str().c_str(), suppress); \
  545. } while (false)
  546. #endif