cmCTest.h 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561
  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 "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 char* 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 char* file);
  112. /**
  113. * Set the cmake test
  114. */
  115. bool SetTest(const char*, 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 char* str);
  123. static std::string CleanString(const std::string& str);
  124. std::string GetCTestConfiguration(const std::string& name);
  125. void SetCTestConfiguration(const char* name, const char* value,
  126. bool suppress = false);
  127. void EmptyCTestConfiguration();
  128. std::string GetSubmitURL();
  129. /**
  130. * constructor and destructor
  131. */
  132. cmCTest();
  133. ~cmCTest();
  134. cmCTest(const cmCTest&) = delete;
  135. cmCTest& operator=(const cmCTest&) = delete;
  136. /** Set the notes files to be created. */
  137. void SetNotesFiles(const char* notes);
  138. void PopulateCustomVector(cmMakefile* mf, const std::string& definition,
  139. std::vector<std::string>& vec);
  140. void PopulateCustomInteger(cmMakefile* mf, const std::string& def, int& val);
  141. /** Get the current time as string */
  142. std::string CurrentTime();
  143. /** tar/gzip and then base 64 encode a file */
  144. std::string Base64GzipEncodeFile(std::string const& file);
  145. /** base64 encode a file */
  146. std::string Base64EncodeFile(std::string const& file);
  147. /**
  148. * Return the time remaining that the script is allowed to run in
  149. * seconds if the user has set the variable CTEST_TIME_LIMIT. If that has
  150. * not been set it returns a very large duration.
  151. */
  152. cmDuration GetRemainingTimeAllowed();
  153. static cmDuration MaxDuration();
  154. /**
  155. * Open file in the output directory and set the stream
  156. */
  157. bool OpenOutputFile(const std::string& path, const std::string& name,
  158. cmGeneratedFileStream& stream, bool compress = false);
  159. /** Should we only show what we would do? */
  160. bool GetShowOnly();
  161. bool GetOutputAsJson();
  162. int GetOutputAsJsonVersion();
  163. bool ShouldUseHTTP10() const;
  164. bool ShouldPrintLabels() const;
  165. bool ShouldCompressTestOutput();
  166. bool CompressString(std::string& str);
  167. std::chrono::system_clock::time_point GetStopTime() const;
  168. void SetStopTime(std::string const& time);
  169. /** Used for parallel ctest job scheduling */
  170. std::string GetScheduleType() const;
  171. void SetScheduleType(std::string const& type);
  172. /** The max output width */
  173. int GetMaxTestNameWidth() const;
  174. void SetMaxTestNameWidth(int w);
  175. /**
  176. * Run a single executable command and put the stdout and stderr
  177. * in output.
  178. *
  179. * If verbose is false, no user-viewable output from the program
  180. * being run will be generated.
  181. *
  182. * If timeout is specified, the command will be terminated after
  183. * timeout expires. Timeout is specified in seconds.
  184. *
  185. * Argument retVal should be a pointer to the location where the
  186. * exit code will be stored. If the retVal is not specified and
  187. * the program exits with a code other than 0, then the this
  188. * function will return false.
  189. */
  190. bool RunCommand(std::vector<std::string> const& args, std::string* stdOut,
  191. std::string* stdErr, int* retVal = nullptr,
  192. const char* dir = nullptr,
  193. cmDuration timeout = cmDuration::zero(),
  194. Encoding encoding = cmProcessOutput::Auto);
  195. /**
  196. * Clean/make safe for xml the given value such that it may be used as
  197. * one of the key fields by CDash when computing the buildid.
  198. */
  199. static std::string SafeBuildIdField(const std::string& value);
  200. /** Start CTest XML output file */
  201. void StartXML(cmXMLWriter& xml, bool append);
  202. /** End CTest XML output file */
  203. void EndXML(cmXMLWriter& xml);
  204. /**
  205. * Run command specialized for make and configure. Returns process status
  206. * and retVal is return value or exception.
  207. */
  208. int RunMakeCommand(const std::string& command, std::string& output,
  209. int* retVal, const char* dir, cmDuration timeout,
  210. std::ostream& ofs,
  211. Encoding encoding = cmProcessOutput::Auto);
  212. /** Return the current tag */
  213. std::string GetCurrentTag();
  214. /** Get the path to the build tree */
  215. std::string GetBinaryDir();
  216. /**
  217. * Get the short path to the file.
  218. *
  219. * This means if the file is in binary or
  220. * source directory, it will become /.../relative/path/to/file
  221. */
  222. std::string GetShortPathToFile(const char* fname);
  223. enum
  224. {
  225. UNKNOWN = -1,
  226. EXPERIMENTAL = 0,
  227. NIGHTLY = 1,
  228. CONTINUOUS = 2,
  229. };
  230. /** provide some more detailed info on the return code for ctest */
  231. enum
  232. {
  233. UPDATE_ERRORS = 0x01,
  234. CONFIGURE_ERRORS = 0x02,
  235. BUILD_ERRORS = 0x04,
  236. TEST_ERRORS = 0x08,
  237. MEMORY_ERRORS = 0x10,
  238. COVERAGE_ERRORS = 0x20,
  239. SUBMIT_ERRORS = 0x40
  240. };
  241. /** Are we producing XML */
  242. bool GetProduceXML();
  243. void SetProduceXML(bool v);
  244. /**
  245. * Run command specialized for tests. Returns process status and retVal is
  246. * return value or exception. If environment is non-null, it is used to set
  247. * environment variables prior to running the test. After running the test,
  248. * environment variables are restored to their previous values.
  249. */
  250. int RunTest(std::vector<const char*> args, std::string* output, int* retVal,
  251. std::ostream* logfile, cmDuration testTimeOut,
  252. std::vector<std::string>* environment,
  253. Encoding encoding = cmProcessOutput::Auto);
  254. /**
  255. * Get the handler object
  256. */
  257. cmCTestBuildHandler* GetBuildHandler();
  258. cmCTestBuildAndTestHandler* GetBuildAndTestHandler();
  259. cmCTestCoverageHandler* GetCoverageHandler();
  260. cmCTestScriptHandler* GetScriptHandler();
  261. cmCTestTestHandler* GetTestHandler();
  262. cmCTestUpdateHandler* GetUpdateHandler();
  263. cmCTestConfigureHandler* GetConfigureHandler();
  264. cmCTestMemCheckHandler* GetMemCheckHandler();
  265. cmCTestSubmitHandler* GetSubmitHandler();
  266. cmCTestUploadHandler* GetUploadHandler();
  267. /**
  268. * Set the CTest variable from CMake variable
  269. */
  270. bool SetCTestConfigurationFromCMakeVariable(cmMakefile* mf,
  271. const char* dconfig,
  272. const std::string& cmake_var,
  273. bool suppress = false);
  274. /** Decode a URL to the original string. */
  275. static std::string DecodeURL(const std::string&);
  276. /**
  277. * Should ctect configuration be updated. When using new style ctest
  278. * script, this should be true.
  279. */
  280. void SetSuppressUpdatingCTestConfiguration(bool val);
  281. /**
  282. * Add overwrite to ctest configuration.
  283. *
  284. * The format is key=value
  285. */
  286. void AddCTestConfigurationOverwrite(const std::string& encstr);
  287. /** Create XML file that contains all the notes specified */
  288. int GenerateNotesFile(std::vector<std::string> const& files);
  289. /** Create XML file to indicate that build is complete */
  290. int GenerateDoneFile();
  291. /** Submit extra files to the server */
  292. bool SubmitExtraFiles(const char* files);
  293. bool SubmitExtraFiles(std::vector<std::string> const& files);
  294. /** Set the output log file name */
  295. void SetOutputLogFileName(const char* name);
  296. /** Set the visual studio or Xcode config type */
  297. void SetConfigType(const char* ct);
  298. /** Various log types */
  299. enum
  300. {
  301. DEBUG = 0,
  302. OUTPUT,
  303. HANDLER_OUTPUT,
  304. HANDLER_PROGRESS_OUTPUT,
  305. HANDLER_TEST_PROGRESS_OUTPUT,
  306. HANDLER_VERBOSE_OUTPUT,
  307. WARNING,
  308. ERROR_MESSAGE,
  309. OTHER
  310. };
  311. /** Add log to the output */
  312. void Log(int logType, const char* file, int line, const char* msg,
  313. bool suppress = false);
  314. /** Color values */
  315. enum class Color
  316. {
  317. CLEAR_COLOR = 0,
  318. RED = 31,
  319. GREEN = 32,
  320. YELLOW = 33,
  321. BLUE = 34
  322. };
  323. /** Get color code characters for a specific color */
  324. std::string GetColorCode(Color color) const;
  325. /** The Build ID is assigned by CDash */
  326. void SetBuildID(const std::string& id);
  327. std::string GetBuildID() const;
  328. /** Add file to be submitted */
  329. void AddSubmitFile(Part part, const char* name);
  330. std::vector<std::string> const& GetSubmitFiles(Part part) const;
  331. void ClearSubmitFiles(Part part);
  332. /**
  333. * Read the custom configuration files and apply them to the current ctest
  334. */
  335. int ReadCustomConfigurationFileTree(const char* dir, cmMakefile* mf);
  336. std::vector<std::string>& GetInitialCommandLineArguments();
  337. /** Set the group to submit to */
  338. void SetSpecificGroup(const char* group);
  339. const char* GetSpecificGroup();
  340. void SetFailover(bool failover);
  341. bool GetFailover() const;
  342. bool GetTestProgressOutput() const;
  343. bool GetVerbose() const;
  344. bool GetExtraVerbose() const;
  345. /** Direct process output to given streams. */
  346. void SetStreams(std::ostream* out, std::ostream* err);
  347. void AddSiteProperties(cmXMLWriter& xml);
  348. bool GetLabelSummary() const;
  349. bool GetSubprojectSummary() const;
  350. std::string GetCostDataFile();
  351. bool GetOutputTestOutputOnTestFailure() const;
  352. const std::map<std::string, std::string>& GetDefinitions() const;
  353. /** Return the number of times a test should be run */
  354. int GetRepeatCount() const;
  355. enum class Repeat
  356. {
  357. Never,
  358. UntilFail,
  359. UntilPass,
  360. AfterTimeout,
  361. };
  362. Repeat GetRepeatMode() const;
  363. void GenerateSubprojectsOutput(cmXMLWriter& xml);
  364. std::vector<std::string> GetLabelsForSubprojects();
  365. void SetRunCurrentScript(bool value);
  366. private:
  367. int GenerateNotesFile(const char* files);
  368. void BlockTestErrorDiagnostics();
  369. /**
  370. * Initialize a dashboard run in the given build tree. The "command"
  371. * argument is non-NULL when running from a command-driven (ctest_start)
  372. * dashboard script, and NULL when running from the CTest command
  373. * line. Note that a declarative dashboard script does not actually
  374. * call this method because it sets CTEST_COMMAND to drive a build
  375. * through the ctest command line.
  376. */
  377. int Initialize(const char* binary_dir, cmCTestStartCommand* command);
  378. /** parse the option after -D and convert it into the appropriate steps */
  379. bool AddTestsForDashboardType(std::string& targ);
  380. /** read as "emit an error message for an unknown -D value" */
  381. void ErrorMessageUnknownDashDValue(std::string& val);
  382. /** add a variable definition from a command line -D value */
  383. bool AddVariableDefinition(const std::string& arg);
  384. /** parse and process most common command line arguments */
  385. bool HandleCommandLineArguments(size_t& i, std::vector<std::string>& args,
  386. std::string& errormsg);
  387. #if !defined(_WIN32)
  388. /** returns true iff the console supports progress output */
  389. static bool ConsoleIsNotDumb();
  390. #endif
  391. /** returns true iff the console supports progress output */
  392. static bool ProgressOutputSupportedByConsole();
  393. /** returns true iff the console supports colored output */
  394. static bool ColoredOutputSupportedByConsole();
  395. /** handle the -S -SP and -SR arguments */
  396. void HandleScriptArguments(size_t& i, std::vector<std::string>& args,
  397. bool& SRArgumentSpecified);
  398. /** Reread the configuration file */
  399. bool UpdateCTestConfiguration();
  400. /** Create note from files. */
  401. int GenerateCTestNotesOutput(cmXMLWriter& xml,
  402. std::vector<std::string> const& files);
  403. /** Check if the argument is the one specified */
  404. bool CheckArgument(const std::string& arg, const char* varg1,
  405. const char* varg2 = nullptr);
  406. /** Output errors from a test */
  407. void OutputTestErrors(std::vector<char> const& process_output);
  408. /** Handle the --test-action command line argument */
  409. bool HandleTestActionArgument(const char* ctestExec, size_t& i,
  410. const std::vector<std::string>& args);
  411. /** Handle the --test-model command line argument */
  412. bool HandleTestModelArgument(const char* ctestExec, size_t& i,
  413. const std::vector<std::string>& args);
  414. int RunCMakeAndTest(std::string* output);
  415. int ExecuteTests();
  416. struct Private;
  417. std::unique_ptr<Private> Impl;
  418. };
  419. class cmCTestLogWrite
  420. {
  421. public:
  422. cmCTestLogWrite(const char* data, size_t length)
  423. : Data(data)
  424. , Length(length)
  425. {
  426. }
  427. const char* Data;
  428. size_t Length;
  429. };
  430. inline std::ostream& operator<<(std::ostream& os, const cmCTestLogWrite& c)
  431. {
  432. if (!c.Length) {
  433. return os;
  434. }
  435. os.write(c.Data, c.Length);
  436. os.flush();
  437. return os;
  438. }
  439. #define cmCTestLog(ctSelf, logType, msg) \
  440. do { \
  441. std::ostringstream cmCTestLog_msg; \
  442. cmCTestLog_msg << msg; \
  443. (ctSelf)->Log(cmCTest::logType, __FILE__, __LINE__, \
  444. cmCTestLog_msg.str().c_str()); \
  445. } while (false)
  446. #define cmCTestOptionalLog(ctSelf, logType, msg, suppress) \
  447. do { \
  448. std::ostringstream cmCTestLog_msg; \
  449. cmCTestLog_msg << msg; \
  450. (ctSelf)->Log(cmCTest::logType, __FILE__, __LINE__, \
  451. cmCTestLog_msg.str().c_str(), suppress); \
  452. } while (false)
  453. #endif