cmCTest.h 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651
  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 "cmsys/String.hxx"
  9. #include <chrono>
  10. #include <map>
  11. #include <set>
  12. #include <sstream>
  13. #include <string>
  14. #include <time.h>
  15. #include <vector>
  16. class cmCTestGenericHandler;
  17. class cmCTestStartCommand;
  18. class cmGeneratedFileStream;
  19. class cmMakefile;
  20. class cmXMLWriter;
  21. /** \class cmCTest
  22. * \brief Represents a ctest invocation.
  23. *
  24. * This class represents a ctest invocation. It is the top level class when
  25. * running ctest.
  26. *
  27. */
  28. class cmCTest
  29. {
  30. friend class cmCTestRunTest;
  31. friend class cmCTestMultiProcessHandler;
  32. public:
  33. typedef cmProcessOutput::Encoding Encoding;
  34. /** Enumerate parts of the testing and submission process. */
  35. enum Part
  36. {
  37. PartStart,
  38. PartUpdate,
  39. PartConfigure,
  40. PartBuild,
  41. PartTest,
  42. PartCoverage,
  43. PartMemCheck,
  44. PartSubmit,
  45. PartNotes,
  46. PartExtraFiles,
  47. PartUpload,
  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. 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<cmsys::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 configuraiton 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. 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, cmDuration 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. bool GetVerbose() { return this->Verbose; }
  358. bool GetExtraVerbose() { return this->ExtraVerbose; }
  359. /** Direct process output to given streams. */
  360. void SetStreams(std::ostream* out, std::ostream* err)
  361. {
  362. this->StreamOut = out;
  363. this->StreamErr = err;
  364. }
  365. void AddSiteProperties(cmXMLWriter& xml);
  366. bool GetLabelSummary() { return this->LabelSummary; }
  367. bool GetSubprojectSummary() { return this->SubprojectSummary; }
  368. std::string GetCostDataFile();
  369. const std::map<std::string, std::string>& GetDefinitions()
  370. {
  371. return this->Definitions;
  372. }
  373. /** Return the number of times a test should be run */
  374. int GetTestRepeat() { return this->RepeatTests; }
  375. /** Return true if test should run until fail */
  376. bool GetRepeatUntilFail() { return this->RepeatUntilFail; }
  377. void GenerateSubprojectsOutput(cmXMLWriter& xml);
  378. std::vector<std::string> GetLabelsForSubprojects();
  379. void SetRunCurrentScript(bool value);
  380. private:
  381. int RepeatTests;
  382. bool RepeatUntilFail;
  383. std::string ConfigType;
  384. std::string ScheduleType;
  385. std::chrono::system_clock::time_point StopTime;
  386. bool Verbose;
  387. bool ExtraVerbose;
  388. bool ProduceXML;
  389. bool LabelSummary;
  390. bool SubprojectSummary;
  391. bool UseHTTP10;
  392. bool PrintLabels;
  393. bool Failover;
  394. bool ForceNewCTestProcess;
  395. bool RunConfigurationScript;
  396. int GenerateNotesFile(const char* files);
  397. // these are helper classes
  398. typedef std::map<std::string, cmCTestGenericHandler*> t_TestingHandlers;
  399. t_TestingHandlers TestingHandlers;
  400. bool ShowOnly;
  401. /** Map of configuration properties */
  402. typedef std::map<std::string, std::string> CTestConfigurationMap;
  403. // TODO: The ctest configuration should be a hierarchy of
  404. // configuration option sources: command-line, script, ini file.
  405. // Then the ini file can get re-loaded whenever it changes without
  406. // affecting any higher-precedence settings.
  407. CTestConfigurationMap CTestConfiguration;
  408. CTestConfigurationMap CTestConfigurationOverwrites;
  409. PartInfo Parts[PartCount];
  410. typedef std::map<std::string, Part> PartMapType;
  411. PartMapType PartMap;
  412. std::string CurrentTag;
  413. bool TomorrowTag;
  414. int TestModel;
  415. std::string SpecificTrack;
  416. cmDuration TimeOut;
  417. cmDuration GlobalTimeout;
  418. int MaxTestNameWidth;
  419. int ParallelLevel;
  420. bool ParallelLevelSetInCli;
  421. unsigned long TestLoad;
  422. int CompatibilityMode;
  423. // information for the --build-and-test options
  424. std::string BinaryDir;
  425. std::string NotesFiles;
  426. bool InteractiveDebugMode;
  427. bool ShortDateFormat;
  428. bool CompressXMLFiles;
  429. bool CompressTestOutput;
  430. void InitStreams();
  431. std::ostream* StreamOut;
  432. std::ostream* StreamErr;
  433. void BlockTestErrorDiagnostics();
  434. /**
  435. * Initialize a dashboard run in the given build tree. The "command"
  436. * argument is non-NULL when running from a command-driven (ctest_start)
  437. * dashboard script, and NULL when running from the CTest command
  438. * line. Note that a declarative dashboard script does not actually
  439. * call this method because it sets CTEST_COMMAND to drive a build
  440. * through the ctest command line.
  441. */
  442. int Initialize(const char* binary_dir, cmCTestStartCommand* command);
  443. /** parse the option after -D and convert it into the appropriate steps */
  444. bool AddTestsForDashboardType(std::string& targ);
  445. /** read as "emit an error message for an unknown -D value" */
  446. void ErrorMessageUnknownDashDValue(std::string& val);
  447. /** add a variable definition from a command line -D value */
  448. bool AddVariableDefinition(const std::string& arg);
  449. /** parse and process most common command line arguments */
  450. bool HandleCommandLineArguments(size_t& i, std::vector<std::string>& args,
  451. std::string& errormsg);
  452. /** hande the -S -SP and -SR arguments */
  453. void HandleScriptArguments(size_t& i, std::vector<std::string>& args,
  454. bool& SRArgumentSpecified);
  455. /** Reread the configuration file */
  456. bool UpdateCTestConfiguration();
  457. /** Create note from files. */
  458. int GenerateCTestNotesOutput(cmXMLWriter& xml, const VectorOfStrings& files);
  459. /** Check if the argument is the one specified */
  460. bool CheckArgument(const std::string& arg, const char* varg1,
  461. const char* varg2 = nullptr);
  462. /** Output errors from a test */
  463. void OutputTestErrors(std::vector<char> const& process_output);
  464. /** Handle the --test-action command line argument */
  465. bool HandleTestActionArgument(const char* ctestExec, size_t& i,
  466. const std::vector<std::string>& args);
  467. /** Handle the --test-model command line argument */
  468. bool HandleTestModelArgument(const char* ctestExec, size_t& i,
  469. const std::vector<std::string>& args);
  470. int RunCMakeAndTest(std::string* output);
  471. int ExecuteTests();
  472. bool SuppressUpdatingCTestConfiguration;
  473. bool Debug;
  474. bool ShowLineNumbers;
  475. bool Quiet;
  476. int DartVersion;
  477. bool DropSiteCDash;
  478. std::vector<std::string> InitialCommandLineArguments;
  479. int SubmitIndex;
  480. cmGeneratedFileStream* OutputLogFile;
  481. int OutputLogFileLastTag;
  482. bool OutputTestOutputOnTestFailure;
  483. std::map<std::string, std::string> Definitions;
  484. };
  485. class cmCTestLogWrite
  486. {
  487. public:
  488. cmCTestLogWrite(const char* data, size_t length)
  489. : Data(data)
  490. , Length(length)
  491. {
  492. }
  493. const char* Data;
  494. size_t Length;
  495. };
  496. inline std::ostream& operator<<(std::ostream& os, const cmCTestLogWrite& c)
  497. {
  498. if (!c.Length) {
  499. return os;
  500. }
  501. os.write(c.Data, c.Length);
  502. os.flush();
  503. return os;
  504. }
  505. #define cmCTestLog(ctSelf, logType, msg) \
  506. do { \
  507. std::ostringstream cmCTestLog_msg; \
  508. cmCTestLog_msg << msg; \
  509. (ctSelf)->Log(cmCTest::logType, __FILE__, __LINE__, \
  510. cmCTestLog_msg.str().c_str()); \
  511. } while (false)
  512. #define cmCTestOptionalLog(ctSelf, logType, msg, suppress) \
  513. do { \
  514. std::ostringstream cmCTestLog_msg; \
  515. cmCTestLog_msg << msg; \
  516. (ctSelf)->Log(cmCTest::logType, __FILE__, __LINE__, \
  517. cmCTestLog_msg.str().c_str(), suppress); \
  518. } while (false)
  519. #endif