cmCTest.h 17 KB

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