cmCTest.h 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693
  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. PartInfo()
  54. : Enabled(false)
  55. {
  56. }
  57. void SetName(const std::string& name) { this->Name = name; }
  58. const std::string& GetName() const { return this->Name; }
  59. void Enable() { this->Enabled = true; }
  60. explicit operator bool() const { return this->Enabled; }
  61. std::vector<std::string> SubmitFiles;
  62. private:
  63. bool Enabled;
  64. std::string Name;
  65. };
  66. #ifdef CMAKE_BUILD_WITH_CMAKE
  67. enum HTTPMethod
  68. {
  69. HTTP_GET,
  70. HTTP_POST,
  71. HTTP_PUT
  72. };
  73. /**
  74. * Perform an HTTP request.
  75. */
  76. static int HTTPRequest(std::string url, HTTPMethod method,
  77. std::string& response, std::string const& fields = "",
  78. std::string const& putFile = "", int timeout = 0);
  79. #endif
  80. /** Get a testing part id from its string name. Returns PartCount
  81. if the string does not name a valid part. */
  82. Part GetPartFromName(const char* name);
  83. typedef std::vector<std::string> VectorOfStrings;
  84. typedef std::set<std::string> SetOfStrings;
  85. /** Process Command line arguments */
  86. int Run(std::vector<std::string>&, std::string* output = nullptr);
  87. /**
  88. * Initialize and finalize testing
  89. */
  90. bool InitializeFromCommand(cmCTestStartCommand* command);
  91. void Finalize();
  92. /**
  93. * Process the dashboard client steps.
  94. *
  95. * Steps are enabled using SetTest()
  96. *
  97. * The execution of the steps (or #Part) should look like this:
  98. *
  99. * /code
  100. * ctest foo;
  101. * foo.Initialize();
  102. * // Set some things on foo
  103. * foo.ProcessSteps();
  104. * foo.Finalize();
  105. * /endcode
  106. *
  107. * \sa Initialize(), Finalize(), Part, PartInfo, SetTest()
  108. */
  109. int ProcessSteps();
  110. /**
  111. * A utility function that returns the nightly time
  112. */
  113. struct tm* GetNightlyTime(std::string const& str, bool tomorrowtag);
  114. /**
  115. * Is the tomorrow tag set?
  116. */
  117. bool GetTomorrowTag() { return this->TomorrowTag; }
  118. /**
  119. * Try to run tests of the project
  120. */
  121. int TestDirectory(bool memcheck);
  122. /** what is the configuration type, e.g. Debug, Release etc. */
  123. std::string const& GetConfigType();
  124. cmDuration GetTimeOut() { return this->TimeOut; }
  125. void SetTimeOut(cmDuration t) { this->TimeOut = t; }
  126. cmDuration GetGlobalTimeout() { return this->GlobalTimeout; }
  127. /** how many test to run at the same time */
  128. int GetParallelLevel() { return this->ParallelLevel; }
  129. void SetParallelLevel(int);
  130. unsigned long GetTestLoad() { return this->TestLoad; }
  131. void SetTestLoad(unsigned long);
  132. /**
  133. * Check if CTest file exists
  134. */
  135. bool CTestFileExists(const std::string& filename);
  136. bool AddIfExists(Part part, const char* file);
  137. /**
  138. * Set the cmake test
  139. */
  140. bool SetTest(const char*, bool report = true);
  141. /**
  142. * Set the cmake test mode (experimental, nightly, continuous).
  143. */
  144. void SetTestModel(int mode);
  145. int GetTestModel() { return this->TestModel; }
  146. std::string GetTestModelString();
  147. static int GetTestModelFromString(const char* str);
  148. static std::string CleanString(const std::string& str);
  149. std::string GetCTestConfiguration(const std::string& name);
  150. void SetCTestConfiguration(const char* name, const char* value,
  151. bool suppress = false);
  152. void EmptyCTestConfiguration();
  153. /**
  154. * constructor and destructor
  155. */
  156. cmCTest();
  157. ~cmCTest();
  158. /** Set the notes files to be created. */
  159. void SetNotesFiles(const char* notes);
  160. void PopulateCustomVector(cmMakefile* mf, const std::string& definition,
  161. std::vector<std::string>& vec);
  162. void PopulateCustomInteger(cmMakefile* mf, const std::string& def, int& val);
  163. /** Get the current time as string */
  164. std::string CurrentTime();
  165. /** tar/gzip and then base 64 encode a file */
  166. std::string Base64GzipEncodeFile(std::string const& file);
  167. /** base64 encode a file */
  168. std::string Base64EncodeFile(std::string const& file);
  169. /**
  170. * Return the time remaining that the script is allowed to run in
  171. * seconds if the user has set the variable CTEST_TIME_LIMIT. If that has
  172. * not been set it returns a very large duration.
  173. */
  174. cmDuration GetRemainingTimeAllowed();
  175. static cmDuration MaxDuration();
  176. /**
  177. * Open file in the output directory and set the stream
  178. */
  179. bool OpenOutputFile(const std::string& path, const std::string& name,
  180. cmGeneratedFileStream& stream, bool compress = false);
  181. /** Should we only show what we would do? */
  182. bool GetShowOnly();
  183. bool ShouldUseHTTP10() { return this->UseHTTP10; }
  184. bool ShouldPrintLabels() { return this->PrintLabels; }
  185. bool ShouldCompressTestOutput();
  186. bool CompressString(std::string& str);
  187. std::chrono::system_clock::time_point GetStopTime()
  188. {
  189. return this->StopTime;
  190. }
  191. void SetStopTime(std::string const& time);
  192. /** Used for parallel ctest job scheduling */
  193. std::string GetScheduleType() { return this->ScheduleType; }
  194. void SetScheduleType(std::string const& type) { this->ScheduleType = type; }
  195. /** The max output width */
  196. int GetMaxTestNameWidth() const;
  197. void SetMaxTestNameWidth(int w) { this->MaxTestNameWidth = w; }
  198. /**
  199. * Run a single executable command and put the stdout and stderr
  200. * in output.
  201. *
  202. * If verbose is false, no user-viewable output from the program
  203. * being run will be generated.
  204. *
  205. * If timeout is specified, the command will be terminated after
  206. * timeout expires. Timeout is specified in seconds.
  207. *
  208. * Argument retVal should be a pointer to the location where the
  209. * exit code will be stored. If the retVal is not specified and
  210. * the program exits with a code other than 0, then the this
  211. * function will return false.
  212. */
  213. bool RunCommand(std::vector<std::string> const& args, std::string* stdOut,
  214. std::string* stdErr, int* retVal = nullptr,
  215. const char* dir = nullptr,
  216. cmDuration timeout = cmDuration::zero(),
  217. Encoding encoding = cmProcessOutput::Auto);
  218. /**
  219. * Clean/make safe for xml the given value such that it may be used as
  220. * one of the key fields by CDash when computing the buildid.
  221. */
  222. static std::string SafeBuildIdField(const std::string& value);
  223. /** Start CTest XML output file */
  224. void StartXML(cmXMLWriter& xml, bool append);
  225. /** End CTest XML output file */
  226. void EndXML(cmXMLWriter& xml);
  227. /**
  228. * Run command specialized for make and configure. Returns process status
  229. * and retVal is return value or exception.
  230. */
  231. int RunMakeCommand(const char* command, std::string& output, int* retVal,
  232. const char* dir, cmDuration timeout, std::ostream& ofs,
  233. Encoding encoding = cmProcessOutput::Auto);
  234. /** Return the current tag */
  235. std::string GetCurrentTag();
  236. /** Get the path to the build tree */
  237. std::string GetBinaryDir();
  238. /**
  239. * Get the short path to the file.
  240. *
  241. * This means if the file is in binary or
  242. * source directory, it will become /.../relative/path/to/file
  243. */
  244. std::string GetShortPathToFile(const char* fname);
  245. enum
  246. {
  247. UNKNOWN = -1,
  248. EXPERIMENTAL = 0,
  249. NIGHTLY = 1,
  250. CONTINUOUS = 2,
  251. };
  252. /** provide some more detailed info on the return code for ctest */
  253. enum
  254. {
  255. UPDATE_ERRORS = 0x01,
  256. CONFIGURE_ERRORS = 0x02,
  257. BUILD_ERRORS = 0x04,
  258. TEST_ERRORS = 0x08,
  259. MEMORY_ERRORS = 0x10,
  260. COVERAGE_ERRORS = 0x20,
  261. SUBMIT_ERRORS = 0x40
  262. };
  263. /** Are we producing XML */
  264. bool GetProduceXML();
  265. void SetProduceXML(bool v);
  266. /**
  267. * Run command specialized for tests. Returns process status and retVal is
  268. * return value or exception. If environment is non-null, it is used to set
  269. * environment variables prior to running the test. After running the test,
  270. * environment variables are restored to their previous values.
  271. */
  272. int RunTest(std::vector<const char*> args, std::string* output, int* retVal,
  273. std::ostream* logfile, cmDuration testTimeOut,
  274. std::vector<std::string>* environment,
  275. Encoding encoding = cmProcessOutput::Auto);
  276. /**
  277. * Execute handler and return its result. If the handler fails, it returns
  278. * negative value.
  279. */
  280. int ExecuteHandler(const char* handler);
  281. /**
  282. * Get the handler object
  283. */
  284. cmCTestGenericHandler* GetHandler(const char* handler);
  285. cmCTestGenericHandler* GetInitializedHandler(const char* handler);
  286. /**
  287. * Set the CTest variable from CMake variable
  288. */
  289. bool SetCTestConfigurationFromCMakeVariable(cmMakefile* mf,
  290. const char* dconfig,
  291. const std::string& cmake_var,
  292. bool suppress = false);
  293. /** Make string safe to be sent as a URL */
  294. static std::string MakeURLSafe(const std::string&);
  295. /** Decode a URL to the original string. */
  296. static std::string DecodeURL(const std::string&);
  297. /**
  298. * Should ctect configuration be updated. When using new style ctest
  299. * script, this should be true.
  300. */
  301. void SetSuppressUpdatingCTestConfiguration(bool val)
  302. {
  303. this->SuppressUpdatingCTestConfiguration = val;
  304. }
  305. /**
  306. * Add overwrite to ctest configuration.
  307. *
  308. * The format is key=value
  309. */
  310. void AddCTestConfigurationOverwrite(const std::string& encstr);
  311. /** Create XML file that contains all the notes specified */
  312. int GenerateNotesFile(const VectorOfStrings& files);
  313. /** Create XML file to indicate that build is complete */
  314. int GenerateDoneFile();
  315. /** Submit extra files to the server */
  316. bool SubmitExtraFiles(const char* files);
  317. bool SubmitExtraFiles(const VectorOfStrings& files);
  318. /** Set the output log file name */
  319. void SetOutputLogFileName(const char* name);
  320. /** Set the visual studio or Xcode config type */
  321. void SetConfigType(const char* ct);
  322. /** Various log types */
  323. enum
  324. {
  325. DEBUG = 0,
  326. OUTPUT,
  327. HANDLER_OUTPUT,
  328. HANDLER_PROGRESS_OUTPUT,
  329. HANDLER_TEST_PROGRESS_OUTPUT,
  330. HANDLER_VERBOSE_OUTPUT,
  331. WARNING,
  332. ERROR_MESSAGE,
  333. OTHER
  334. };
  335. /** Add log to the output */
  336. void Log(int logType, const char* file, int line, const char* msg,
  337. bool suppress = false);
  338. /** Color values */
  339. enum class Color
  340. {
  341. CLEAR_COLOR = 0,
  342. RED = 31,
  343. GREEN = 32,
  344. YELLOW = 33,
  345. BLUE = 34
  346. };
  347. /** Get color code characters for a specific color */
  348. std::string GetColorCode(Color color) const;
  349. /** Get the version of dart server */
  350. int GetDartVersion() { return this->DartVersion; }
  351. int GetDropSiteCDash() { return this->DropSiteCDash; }
  352. /** The Build ID is assigned by CDash */
  353. void SetBuildID(const std::string& id) { this->BuildID = id; }
  354. std::string GetBuildID() { return this->BuildID; }
  355. /** Add file to be submitted */
  356. void AddSubmitFile(Part part, const char* name);
  357. std::vector<std::string> const& GetSubmitFiles(Part part)
  358. {
  359. return this->Parts[part].SubmitFiles;
  360. }
  361. void ClearSubmitFiles(Part part) { this->Parts[part].SubmitFiles.clear(); }
  362. /**
  363. * Read the custom configuration files and apply them to the current ctest
  364. */
  365. int ReadCustomConfigurationFileTree(const char* dir, cmMakefile* mf);
  366. std::vector<std::string>& GetInitialCommandLineArguments()
  367. {
  368. return this->InitialCommandLineArguments;
  369. }
  370. /** Set the track to submit to */
  371. void SetSpecificTrack(const char* track);
  372. const char* GetSpecificTrack();
  373. void SetFailover(bool failover) { this->Failover = failover; }
  374. bool GetFailover() { return this->Failover; }
  375. bool GetTestProgressOutput() const { return this->TestProgressOutput; }
  376. bool GetVerbose() { return this->Verbose; }
  377. bool GetExtraVerbose() { return this->ExtraVerbose; }
  378. /** Direct process output to given streams. */
  379. void SetStreams(std::ostream* out, std::ostream* err)
  380. {
  381. this->StreamOut = out;
  382. this->StreamErr = err;
  383. }
  384. void AddSiteProperties(cmXMLWriter& xml);
  385. bool GetLabelSummary() { return this->LabelSummary; }
  386. bool GetSubprojectSummary() { return this->SubprojectSummary; }
  387. std::string GetCostDataFile();
  388. const std::map<std::string, std::string>& GetDefinitions()
  389. {
  390. return this->Definitions;
  391. }
  392. /** Return the number of times a test should be run */
  393. int GetTestRepeat() { return this->RepeatTests; }
  394. /** Return true if test should run until fail */
  395. bool GetRepeatUntilFail() { return this->RepeatUntilFail; }
  396. void GenerateSubprojectsOutput(cmXMLWriter& xml);
  397. std::vector<std::string> GetLabelsForSubprojects();
  398. void SetRunCurrentScript(bool value);
  399. private:
  400. int RepeatTests;
  401. bool RepeatUntilFail;
  402. std::string ConfigType;
  403. std::string ScheduleType;
  404. std::chrono::system_clock::time_point StopTime;
  405. bool TestProgressOutput;
  406. bool Verbose;
  407. bool ExtraVerbose;
  408. bool ProduceXML;
  409. bool LabelSummary;
  410. bool SubprojectSummary;
  411. bool UseHTTP10;
  412. bool PrintLabels;
  413. bool Failover;
  414. bool FlushTestProgressLine;
  415. bool ForceNewCTestProcess;
  416. bool RunConfigurationScript;
  417. int GenerateNotesFile(const char* files);
  418. // these are helper classes
  419. typedef std::map<std::string, cmCTestGenericHandler*> t_TestingHandlers;
  420. t_TestingHandlers TestingHandlers;
  421. bool ShowOnly;
  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. int DartVersion;
  506. bool DropSiteCDash;
  507. std::string BuildID;
  508. std::vector<std::string> InitialCommandLineArguments;
  509. int SubmitIndex;
  510. cmGeneratedFileStream* OutputLogFile;
  511. int OutputLogFileLastTag;
  512. bool OutputTestOutputOnTestFailure;
  513. bool OutputColorCode;
  514. std::map<std::string, std::string> Definitions;
  515. };
  516. class cmCTestLogWrite
  517. {
  518. public:
  519. cmCTestLogWrite(const char* data, size_t length)
  520. : Data(data)
  521. , Length(length)
  522. {
  523. }
  524. const char* Data;
  525. size_t Length;
  526. };
  527. inline std::ostream& operator<<(std::ostream& os, const cmCTestLogWrite& c)
  528. {
  529. if (!c.Length) {
  530. return os;
  531. }
  532. os.write(c.Data, c.Length);
  533. os.flush();
  534. return os;
  535. }
  536. #define cmCTestLog(ctSelf, logType, msg) \
  537. do { \
  538. std::ostringstream cmCTestLog_msg; \
  539. cmCTestLog_msg << msg; \
  540. (ctSelf)->Log(cmCTest::logType, __FILE__, __LINE__, \
  541. cmCTestLog_msg.str().c_str()); \
  542. } while (false)
  543. #define cmCTestOptionalLog(ctSelf, logType, msg, suppress) \
  544. do { \
  545. std::ostringstream cmCTestLog_msg; \
  546. cmCTestLog_msg << msg; \
  547. (ctSelf)->Log(cmCTest::logType, __FILE__, __LINE__, \
  548. cmCTestLog_msg.str().c_str(), suppress); \
  549. } while (false)
  550. #endif