cmCTest.h 19 KB

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