cmCTest.h 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659
  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. static std::chrono::duration<double> MaxDuration();
  178. /**
  179. * Open file in the output directory and set the stream
  180. */
  181. bool OpenOutputFile(const std::string& path, const std::string& name,
  182. cmGeneratedFileStream& stream, bool compress = false);
  183. /** Should we only show what we would do? */
  184. bool GetShowOnly();
  185. bool ShouldUseHTTP10() { return this->UseHTTP10; }
  186. bool ShouldPrintLabels() { return this->PrintLabels; }
  187. bool ShouldCompressTestOutput();
  188. bool CompressString(std::string& str);
  189. std::string GetStopTime() { return this->StopTime; }
  190. void SetStopTime(std::string const& time);
  191. /** Used for parallel ctest job scheduling */
  192. std::string GetScheduleType() { return this->ScheduleType; }
  193. void SetScheduleType(std::string const& type) { this->ScheduleType = type; }
  194. /** The max output width */
  195. int GetMaxTestNameWidth() const;
  196. void SetMaxTestNameWidth(int w) { this->MaxTestNameWidth = w; }
  197. /**
  198. * Run a single executable command and put the stdout and stderr
  199. * in output.
  200. *
  201. * If verbose is false, no user-viewable output from the program
  202. * being run will be generated.
  203. *
  204. * If timeout is specified, the command will be terminated after
  205. * timeout expires. Timeout is specified in seconds.
  206. *
  207. * Argument retVal should be a pointer to the location where the
  208. * exit code will be stored. If the retVal is not specified and
  209. * the program exits with a code other than 0, then the this
  210. * function will return false.
  211. */
  212. bool RunCommand(std::vector<std::string> const& args, std::string* stdOut,
  213. std::string* stdErr, int* retVal = nullptr,
  214. const char* dir = nullptr,
  215. std::chrono::duration<double> timeout =
  216. std::chrono::duration<double>::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, std::chrono::duration<double> timeout,
  233. 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. EXPERIMENTAL,
  249. NIGHTLY,
  250. CONTINUOUS
  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, std::chrono::duration<double> 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 send as an 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. /** Submit extra files to the server */
  314. bool SubmitExtraFiles(const char* files);
  315. bool SubmitExtraFiles(const VectorOfStrings& files);
  316. /** Set the output log file name */
  317. void SetOutputLogFileName(const char* name);
  318. /** Set the visual studio or Xcode config type */
  319. void SetConfigType(const char* ct);
  320. /** Various log types */
  321. enum
  322. {
  323. DEBUG = 0,
  324. OUTPUT,
  325. HANDLER_OUTPUT,
  326. HANDLER_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. /** Get the version of dart server */
  336. int GetDartVersion() { return this->DartVersion; }
  337. int GetDropSiteCDash() { return this->DropSiteCDash; }
  338. /** Add file to be submitted */
  339. void AddSubmitFile(Part part, const char* name);
  340. std::vector<std::string> const& GetSubmitFiles(Part part)
  341. {
  342. return this->Parts[part].SubmitFiles;
  343. }
  344. void ClearSubmitFiles(Part part) { this->Parts[part].SubmitFiles.clear(); }
  345. /**
  346. * Read the custom configuration files and apply them to the current ctest
  347. */
  348. int ReadCustomConfigurationFileTree(const char* dir, cmMakefile* mf);
  349. std::vector<std::string>& GetInitialCommandLineArguments()
  350. {
  351. return this->InitialCommandLineArguments;
  352. }
  353. /** Set the track to submit to */
  354. void SetSpecificTrack(const char* track);
  355. const char* GetSpecificTrack();
  356. void SetFailover(bool failover) { this->Failover = failover; }
  357. bool GetFailover() { return this->Failover; }
  358. void SetBatchJobs(bool batch = true) { this->BatchJobs = batch; }
  359. bool GetBatchJobs() { return this->BatchJobs; }
  360. bool GetVerbose() { return this->Verbose; }
  361. bool GetExtraVerbose() { return this->ExtraVerbose; }
  362. /** Direct process output to given streams. */
  363. void SetStreams(std::ostream* out, std::ostream* err)
  364. {
  365. this->StreamOut = out;
  366. this->StreamErr = err;
  367. }
  368. void AddSiteProperties(cmXMLWriter& xml);
  369. bool GetLabelSummary() { return this->LabelSummary; }
  370. bool GetSubprojectSummary() { return this->SubprojectSummary; }
  371. std::string GetCostDataFile();
  372. const std::map<std::string, std::string>& GetDefinitions()
  373. {
  374. return this->Definitions;
  375. }
  376. /** Return the number of times a test should be run */
  377. int GetTestRepeat() { return this->RepeatTests; }
  378. /** Return true if test should run until fail */
  379. bool GetRepeatUntilFail() { return this->RepeatUntilFail; }
  380. void GenerateSubprojectsOutput(cmXMLWriter& xml);
  381. std::vector<std::string> GetLabelsForSubprojects();
  382. private:
  383. int RepeatTests;
  384. bool RepeatUntilFail;
  385. std::string ConfigType;
  386. std::string ScheduleType;
  387. std::string StopTime;
  388. bool NextDayStopTime;
  389. bool Verbose;
  390. bool ExtraVerbose;
  391. bool ProduceXML;
  392. bool LabelSummary;
  393. bool SubprojectSummary;
  394. bool UseHTTP10;
  395. bool PrintLabels;
  396. bool Failover;
  397. bool BatchJobs;
  398. bool ForceNewCTestProcess;
  399. bool RunConfigurationScript;
  400. int GenerateNotesFile(const char* files);
  401. void DetermineNextDayStop();
  402. // these are helper classes
  403. typedef std::map<std::string, cmCTestGenericHandler*> t_TestingHandlers;
  404. t_TestingHandlers TestingHandlers;
  405. bool ShowOnly;
  406. /** Map of configuration properties */
  407. typedef std::map<std::string, std::string> CTestConfigurationMap;
  408. // TODO: The ctest configuration should be a hierarchy of
  409. // configuration option sources: command-line, script, ini file.
  410. // Then the ini file can get re-loaded whenever it changes without
  411. // affecting any higher-precedence settings.
  412. CTestConfigurationMap CTestConfiguration;
  413. CTestConfigurationMap CTestConfigurationOverwrites;
  414. PartInfo Parts[PartCount];
  415. typedef std::map<std::string, Part> PartMapType;
  416. PartMapType PartMap;
  417. std::string CurrentTag;
  418. bool TomorrowTag;
  419. int TestModel;
  420. std::string SpecificTrack;
  421. std::chrono::duration<double> TimeOut;
  422. std::chrono::duration<double> GlobalTimeout;
  423. std::chrono::duration<double> LastStopTimeout;
  424. int MaxTestNameWidth;
  425. int ParallelLevel;
  426. bool ParallelLevelSetInCli;
  427. unsigned long TestLoad;
  428. int CompatibilityMode;
  429. // information for the --build-and-test options
  430. std::string BinaryDir;
  431. std::string NotesFiles;
  432. bool InteractiveDebugMode;
  433. bool ShortDateFormat;
  434. bool CompressXMLFiles;
  435. bool CompressTestOutput;
  436. void InitStreams();
  437. std::ostream* StreamOut;
  438. std::ostream* StreamErr;
  439. void BlockTestErrorDiagnostics();
  440. /**
  441. * Initialize a dashboard run in the given build tree. The "command"
  442. * argument is non-NULL when running from a command-driven (ctest_start)
  443. * dashboard script, and NULL when running from the CTest command
  444. * line. Note that a declarative dashboard script does not actually
  445. * call this method because it sets CTEST_COMMAND to drive a build
  446. * through the ctest command line.
  447. */
  448. int Initialize(const char* binary_dir, cmCTestStartCommand* command);
  449. /** parse the option after -D and convert it into the appropriate steps */
  450. bool AddTestsForDashboardType(std::string& targ);
  451. /** read as "emit an error message for an unknown -D value" */
  452. void ErrorMessageUnknownDashDValue(std::string& val);
  453. /** add a variable definition from a command line -D value */
  454. bool AddVariableDefinition(const std::string& arg);
  455. /** parse and process most common command line arguments */
  456. bool HandleCommandLineArguments(size_t& i, std::vector<std::string>& args,
  457. std::string& errormsg);
  458. /** hande the -S -SP and -SR arguments */
  459. void HandleScriptArguments(size_t& i, std::vector<std::string>& args,
  460. bool& SRArgumentSpecified);
  461. /** Reread the configuration file */
  462. bool UpdateCTestConfiguration();
  463. /** Create note from files. */
  464. int GenerateCTestNotesOutput(cmXMLWriter& xml, const VectorOfStrings& files);
  465. /** Check if the argument is the one specified */
  466. bool CheckArgument(const std::string& arg, const char* varg1,
  467. const char* varg2 = nullptr);
  468. /** Output errors from a test */
  469. void OutputTestErrors(std::vector<char> const& process_output);
  470. /** Handle the --test-action command line argument */
  471. bool HandleTestActionArgument(const char* ctestExec, size_t& i,
  472. const std::vector<std::string>& args);
  473. /** Handle the --test-model command line argument */
  474. bool HandleTestModelArgument(const char* ctestExec, size_t& i,
  475. const std::vector<std::string>& args);
  476. int RunCMakeAndTest(std::string* output);
  477. int ExecuteTests();
  478. bool SuppressUpdatingCTestConfiguration;
  479. bool Debug;
  480. bool ShowLineNumbers;
  481. bool Quiet;
  482. int DartVersion;
  483. bool DropSiteCDash;
  484. std::vector<std::string> InitialCommandLineArguments;
  485. int SubmitIndex;
  486. cmGeneratedFileStream* OutputLogFile;
  487. int OutputLogFileLastTag;
  488. bool OutputTestOutputOnTestFailure;
  489. std::map<std::string, std::string> Definitions;
  490. };
  491. class cmCTestLogWrite
  492. {
  493. public:
  494. cmCTestLogWrite(const char* data, size_t length)
  495. : Data(data)
  496. , Length(length)
  497. {
  498. }
  499. const char* Data;
  500. size_t Length;
  501. };
  502. inline std::ostream& operator<<(std::ostream& os, const cmCTestLogWrite& c)
  503. {
  504. if (!c.Length) {
  505. return os;
  506. }
  507. os.write(c.Data, c.Length);
  508. os.flush();
  509. return os;
  510. }
  511. #define cmCTestLog(ctSelf, logType, msg) \
  512. do { \
  513. std::ostringstream cmCTestLog_msg; \
  514. cmCTestLog_msg << msg; \
  515. (ctSelf)->Log(cmCTest::logType, __FILE__, __LINE__, \
  516. cmCTestLog_msg.str().c_str()); \
  517. } while (false)
  518. #define cmCTestOptionalLog(ctSelf, logType, msg, suppress) \
  519. do { \
  520. std::ostringstream cmCTestLog_msg; \
  521. cmCTestLog_msg << msg; \
  522. (ctSelf)->Log(cmCTest::logType, __FILE__, __LINE__, \
  523. cmCTestLog_msg.str().c_str(), suppress); \
  524. } while (false)
  525. #endif