cmCTest.h 16 KB

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