cmCTest.h 19 KB

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