cmCTest.h 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692
  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. cmCTest(const cmCTest&) = delete;
  156. cmCTest& operator=(const cmCTest&) = delete;
  157. /** Set the notes files to be created. */
  158. void SetNotesFiles(const char* notes);
  159. void PopulateCustomVector(cmMakefile* mf, const std::string& definition,
  160. std::vector<std::string>& vec);
  161. void PopulateCustomInteger(cmMakefile* mf, const std::string& def, int& val);
  162. /** Get the current time as string */
  163. std::string CurrentTime();
  164. /** tar/gzip and then base 64 encode a file */
  165. std::string Base64GzipEncodeFile(std::string const& file);
  166. /** base64 encode a file */
  167. std::string Base64EncodeFile(std::string const& file);
  168. /**
  169. * Return the time remaining that the script is allowed to run in
  170. * seconds if the user has set the variable CTEST_TIME_LIMIT. If that has
  171. * not been set it returns a very large duration.
  172. */
  173. cmDuration GetRemainingTimeAllowed();
  174. static cmDuration MaxDuration();
  175. /**
  176. * Open file in the output directory and set the stream
  177. */
  178. bool OpenOutputFile(const std::string& path, const std::string& name,
  179. cmGeneratedFileStream& stream, bool compress = false);
  180. /** Should we only show what we would do? */
  181. bool GetShowOnly();
  182. bool GetOutputAsJson();
  183. int GetOutputAsJsonVersion();
  184. bool ShouldUseHTTP10() { return this->UseHTTP10; }
  185. bool ShouldPrintLabels() { return this->PrintLabels; }
  186. bool ShouldCompressTestOutput();
  187. bool CompressString(std::string& str);
  188. std::chrono::system_clock::time_point GetStopTime()
  189. {
  190. return this->StopTime;
  191. }
  192. void SetStopTime(std::string const& time);
  193. /** Used for parallel ctest job scheduling */
  194. std::string GetScheduleType() { return this->ScheduleType; }
  195. void SetScheduleType(std::string const& type) { this->ScheduleType = type; }
  196. /** The max output width */
  197. int GetMaxTestNameWidth() const;
  198. void SetMaxTestNameWidth(int w) { this->MaxTestNameWidth = w; }
  199. /**
  200. * Run a single executable command and put the stdout and stderr
  201. * in output.
  202. *
  203. * If verbose is false, no user-viewable output from the program
  204. * being run will be generated.
  205. *
  206. * If timeout is specified, the command will be terminated after
  207. * timeout expires. Timeout is specified in seconds.
  208. *
  209. * Argument retVal should be a pointer to the location where the
  210. * exit code will be stored. If the retVal is not specified and
  211. * the program exits with a code other than 0, then the this
  212. * function will return false.
  213. */
  214. bool RunCommand(std::vector<std::string> const& args, std::string* stdOut,
  215. std::string* stdErr, int* retVal = nullptr,
  216. const char* dir = nullptr,
  217. cmDuration timeout = cmDuration::zero(),
  218. Encoding encoding = cmProcessOutput::Auto);
  219. /**
  220. * Clean/make safe for xml the given value such that it may be used as
  221. * one of the key fields by CDash when computing the buildid.
  222. */
  223. static std::string SafeBuildIdField(const std::string& value);
  224. /** Start CTest XML output file */
  225. void StartXML(cmXMLWriter& xml, bool append);
  226. /** End CTest XML output file */
  227. void EndXML(cmXMLWriter& xml);
  228. /**
  229. * Run command specialized for make and configure. Returns process status
  230. * and retVal is return value or exception.
  231. */
  232. int RunMakeCommand(const char* command, std::string& output, int* retVal,
  233. const char* dir, cmDuration timeout, std::ostream& ofs,
  234. Encoding encoding = cmProcessOutput::Auto);
  235. /** Return the current tag */
  236. std::string GetCurrentTag();
  237. /** Get the path to the build tree */
  238. std::string GetBinaryDir();
  239. /**
  240. * Get the short path to the file.
  241. *
  242. * This means if the file is in binary or
  243. * source directory, it will become /.../relative/path/to/file
  244. */
  245. std::string GetShortPathToFile(const char* fname);
  246. enum
  247. {
  248. UNKNOWN = -1,
  249. EXPERIMENTAL = 0,
  250. NIGHTLY = 1,
  251. CONTINUOUS = 2,
  252. };
  253. /** provide some more detailed info on the return code for ctest */
  254. enum
  255. {
  256. UPDATE_ERRORS = 0x01,
  257. CONFIGURE_ERRORS = 0x02,
  258. BUILD_ERRORS = 0x04,
  259. TEST_ERRORS = 0x08,
  260. MEMORY_ERRORS = 0x10,
  261. COVERAGE_ERRORS = 0x20,
  262. SUBMIT_ERRORS = 0x40
  263. };
  264. /** Are we producing XML */
  265. bool GetProduceXML();
  266. void SetProduceXML(bool v);
  267. /**
  268. * Run command specialized for tests. Returns process status and retVal is
  269. * return value or exception. If environment is non-null, it is used to set
  270. * environment variables prior to running the test. After running the test,
  271. * environment variables are restored to their previous values.
  272. */
  273. int RunTest(std::vector<const char*> args, std::string* output, int* retVal,
  274. std::ostream* logfile, cmDuration testTimeOut,
  275. std::vector<std::string>* environment,
  276. Encoding encoding = cmProcessOutput::Auto);
  277. /**
  278. * Execute handler and return its result. If the handler fails, it returns
  279. * negative value.
  280. */
  281. int ExecuteHandler(const char* handler);
  282. /**
  283. * Get the handler object
  284. */
  285. cmCTestGenericHandler* GetHandler(const char* handler);
  286. cmCTestGenericHandler* GetInitializedHandler(const char* handler);
  287. /**
  288. * Set the CTest variable from CMake variable
  289. */
  290. bool SetCTestConfigurationFromCMakeVariable(cmMakefile* mf,
  291. const char* dconfig,
  292. const std::string& cmake_var,
  293. bool suppress = false);
  294. /** Make string safe to be sent as a URL */
  295. static std::string MakeURLSafe(const std::string&);
  296. /** Decode a URL to the original string. */
  297. static std::string DecodeURL(const std::string&);
  298. /**
  299. * Should ctect configuration be updated. When using new style ctest
  300. * script, this should be true.
  301. */
  302. void SetSuppressUpdatingCTestConfiguration(bool val)
  303. {
  304. this->SuppressUpdatingCTestConfiguration = val;
  305. }
  306. /**
  307. * Add overwrite to ctest configuration.
  308. *
  309. * The format is key=value
  310. */
  311. void AddCTestConfigurationOverwrite(const std::string& encstr);
  312. /** Create XML file that contains all the notes specified */
  313. int GenerateNotesFile(const VectorOfStrings& files);
  314. /** Create XML file to indicate that build is complete */
  315. int GenerateDoneFile();
  316. /** Submit extra files to the server */
  317. bool SubmitExtraFiles(const char* files);
  318. bool SubmitExtraFiles(const VectorOfStrings& files);
  319. /** Set the output log file name */
  320. void SetOutputLogFileName(const char* name);
  321. /** Set the visual studio or Xcode config type */
  322. void SetConfigType(const char* ct);
  323. /** Various log types */
  324. enum
  325. {
  326. DEBUG = 0,
  327. OUTPUT,
  328. HANDLER_OUTPUT,
  329. HANDLER_PROGRESS_OUTPUT,
  330. HANDLER_TEST_PROGRESS_OUTPUT,
  331. HANDLER_VERBOSE_OUTPUT,
  332. WARNING,
  333. ERROR_MESSAGE,
  334. OTHER
  335. };
  336. /** Add log to the output */
  337. void Log(int logType, const char* file, int line, const char* msg,
  338. bool suppress = false);
  339. /** Color values */
  340. enum class Color
  341. {
  342. CLEAR_COLOR = 0,
  343. RED = 31,
  344. GREEN = 32,
  345. YELLOW = 33,
  346. BLUE = 34
  347. };
  348. /** Get color code characters for a specific color */
  349. std::string GetColorCode(Color color) const;
  350. /** The Build ID is assigned by CDash */
  351. void SetBuildID(const std::string& id) { this->BuildID = id; }
  352. std::string GetBuildID() { return this->BuildID; }
  353. /** Add file to be submitted */
  354. void AddSubmitFile(Part part, const char* name);
  355. std::vector<std::string> const& GetSubmitFiles(Part part)
  356. {
  357. return this->Parts[part].SubmitFiles;
  358. }
  359. void ClearSubmitFiles(Part part) { this->Parts[part].SubmitFiles.clear(); }
  360. /**
  361. * Read the custom configuration files and apply them to the current ctest
  362. */
  363. int ReadCustomConfigurationFileTree(const char* dir, cmMakefile* mf);
  364. std::vector<std::string>& GetInitialCommandLineArguments()
  365. {
  366. return this->InitialCommandLineArguments;
  367. }
  368. /** Set the track to submit to */
  369. void SetSpecificTrack(const char* track);
  370. const char* GetSpecificTrack();
  371. void SetFailover(bool failover) { this->Failover = failover; }
  372. bool GetFailover() { return this->Failover; }
  373. bool GetTestProgressOutput() const { return this->TestProgressOutput; }
  374. bool GetVerbose() { return this->Verbose; }
  375. bool GetExtraVerbose() { return this->ExtraVerbose; }
  376. /** Direct process output to given streams. */
  377. void SetStreams(std::ostream* out, std::ostream* err)
  378. {
  379. this->StreamOut = out;
  380. this->StreamErr = err;
  381. }
  382. void AddSiteProperties(cmXMLWriter& xml);
  383. bool GetLabelSummary() { return this->LabelSummary; }
  384. bool GetSubprojectSummary() { return this->SubprojectSummary; }
  385. std::string GetCostDataFile();
  386. const std::map<std::string, std::string>& GetDefinitions()
  387. {
  388. return this->Definitions;
  389. }
  390. /** Return the number of times a test should be run */
  391. int GetTestRepeat() { return this->RepeatTests; }
  392. /** Return true if test should run until fail */
  393. bool GetRepeatUntilFail() { return this->RepeatUntilFail; }
  394. void GenerateSubprojectsOutput(cmXMLWriter& xml);
  395. std::vector<std::string> GetLabelsForSubprojects();
  396. void SetRunCurrentScript(bool value);
  397. private:
  398. int RepeatTests;
  399. bool RepeatUntilFail;
  400. std::string ConfigType;
  401. std::string ScheduleType;
  402. std::chrono::system_clock::time_point StopTime;
  403. bool TestProgressOutput;
  404. bool Verbose;
  405. bool ExtraVerbose;
  406. bool ProduceXML;
  407. bool LabelSummary;
  408. bool SubprojectSummary;
  409. bool UseHTTP10;
  410. bool PrintLabels;
  411. bool Failover;
  412. bool FlushTestProgressLine;
  413. bool ForceNewCTestProcess;
  414. bool RunConfigurationScript;
  415. int GenerateNotesFile(const char* files);
  416. // these are helper classes
  417. typedef std::map<std::string, cmCTestGenericHandler*> t_TestingHandlers;
  418. t_TestingHandlers TestingHandlers;
  419. bool ShowOnly;
  420. bool OutputAsJson;
  421. int OutputAsJsonVersion;
  422. /** Map of configuration properties */
  423. typedef std::map<std::string, std::string> CTestConfigurationMap;
  424. // TODO: The ctest configuration should be a hierarchy of
  425. // configuration option sources: command-line, script, ini file.
  426. // Then the ini file can get re-loaded whenever it changes without
  427. // affecting any higher-precedence settings.
  428. CTestConfigurationMap CTestConfiguration;
  429. CTestConfigurationMap CTestConfigurationOverwrites;
  430. PartInfo Parts[PartCount];
  431. typedef std::map<std::string, Part> PartMapType;
  432. PartMapType PartMap;
  433. std::string CurrentTag;
  434. bool TomorrowTag;
  435. int TestModel;
  436. std::string SpecificTrack;
  437. cmDuration TimeOut;
  438. cmDuration GlobalTimeout;
  439. int MaxTestNameWidth;
  440. int ParallelLevel;
  441. bool ParallelLevelSetInCli;
  442. unsigned long TestLoad;
  443. int CompatibilityMode;
  444. // information for the --build-and-test options
  445. std::string BinaryDir;
  446. std::string NotesFiles;
  447. bool InteractiveDebugMode;
  448. bool ShortDateFormat;
  449. bool CompressXMLFiles;
  450. bool CompressTestOutput;
  451. void InitStreams();
  452. std::ostream* StreamOut;
  453. std::ostream* StreamErr;
  454. void BlockTestErrorDiagnostics();
  455. /**
  456. * Initialize a dashboard run in the given build tree. The "command"
  457. * argument is non-NULL when running from a command-driven (ctest_start)
  458. * dashboard script, and NULL when running from the CTest command
  459. * line. Note that a declarative dashboard script does not actually
  460. * call this method because it sets CTEST_COMMAND to drive a build
  461. * through the ctest command line.
  462. */
  463. int Initialize(const char* binary_dir, cmCTestStartCommand* command);
  464. /** parse the option after -D and convert it into the appropriate steps */
  465. bool AddTestsForDashboardType(std::string& targ);
  466. /** read as "emit an error message for an unknown -D value" */
  467. void ErrorMessageUnknownDashDValue(std::string& val);
  468. /** add a variable definition from a command line -D value */
  469. bool AddVariableDefinition(const std::string& arg);
  470. /** parse and process most common command line arguments */
  471. bool HandleCommandLineArguments(size_t& i, std::vector<std::string>& args,
  472. std::string& errormsg);
  473. #if !defined(_WIN32)
  474. /** returns true iff the console supports progress output */
  475. static bool ConsoleIsNotDumb();
  476. #endif
  477. /** returns true iff the console supports progress output */
  478. static bool ProgressOutputSupportedByConsole();
  479. /** returns true iff the console supports colored output */
  480. static bool ColoredOutputSupportedByConsole();
  481. /** handle the -S -SP and -SR arguments */
  482. void HandleScriptArguments(size_t& i, std::vector<std::string>& args,
  483. bool& SRArgumentSpecified);
  484. /** Reread the configuration file */
  485. bool UpdateCTestConfiguration();
  486. /** Create note from files. */
  487. int GenerateCTestNotesOutput(cmXMLWriter& xml, const VectorOfStrings& files);
  488. /** Check if the argument is the one specified */
  489. bool CheckArgument(const std::string& arg, const char* varg1,
  490. const char* varg2 = nullptr);
  491. /** Output errors from a test */
  492. void OutputTestErrors(std::vector<char> const& process_output);
  493. /** Handle the --test-action command line argument */
  494. bool HandleTestActionArgument(const char* ctestExec, size_t& i,
  495. const std::vector<std::string>& args);
  496. /** Handle the --test-model command line argument */
  497. bool HandleTestModelArgument(const char* ctestExec, size_t& i,
  498. const std::vector<std::string>& args);
  499. int RunCMakeAndTest(std::string* output);
  500. int ExecuteTests();
  501. bool SuppressUpdatingCTestConfiguration;
  502. bool Debug;
  503. bool ShowLineNumbers;
  504. bool Quiet;
  505. std::string BuildID;
  506. std::vector<std::string> InitialCommandLineArguments;
  507. int SubmitIndex;
  508. cmGeneratedFileStream* OutputLogFile;
  509. int OutputLogFileLastTag;
  510. bool OutputTestOutputOnTestFailure;
  511. bool OutputColorCode;
  512. std::map<std::string, std::string> Definitions;
  513. };
  514. class cmCTestLogWrite
  515. {
  516. public:
  517. cmCTestLogWrite(const char* data, size_t length)
  518. : Data(data)
  519. , Length(length)
  520. {
  521. }
  522. const char* Data;
  523. size_t Length;
  524. };
  525. inline std::ostream& operator<<(std::ostream& os, const cmCTestLogWrite& c)
  526. {
  527. if (!c.Length) {
  528. return os;
  529. }
  530. os.write(c.Data, c.Length);
  531. os.flush();
  532. return os;
  533. }
  534. #define cmCTestLog(ctSelf, logType, msg) \
  535. do { \
  536. std::ostringstream cmCTestLog_msg; \
  537. cmCTestLog_msg << msg; \
  538. (ctSelf)->Log(cmCTest::logType, __FILE__, __LINE__, \
  539. cmCTestLog_msg.str().c_str()); \
  540. } while (false)
  541. #define cmCTestOptionalLog(ctSelf, logType, msg, suppress) \
  542. do { \
  543. std::ostringstream cmCTestLog_msg; \
  544. cmCTestLog_msg << msg; \
  545. (ctSelf)->Log(cmCTest::logType, __FILE__, __LINE__, \
  546. cmCTestLog_msg.str().c_str(), suppress); \
  547. } while (false)
  548. #endif