cmCTest.h 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653
  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"
  6. #include "cmProcessOutput.h"
  7. #include "cmsys/String.hxx"
  8. #include <map>
  9. #include <set>
  10. #include <sstream>
  11. #include <string>
  12. #include <time.h>
  13. #include <vector>
  14. class cmCTestGenericHandler;
  15. class cmCTestStartCommand;
  16. class cmGeneratedFileStream;
  17. class cmMakefile;
  18. class cmXMLWriter;
  19. /** \class cmCTest
  20. * \brief Represents a ctest invocation.
  21. *
  22. * This class represents a ctest invocation. It is the top level class when
  23. * running ctest.
  24. *
  25. */
  26. class cmCTest
  27. {
  28. friend class cmCTestRunTest;
  29. friend class cmCTestMultiProcessHandler;
  30. public:
  31. typedef cmProcessOutput::Encoding Encoding;
  32. /** Enumerate parts of the testing and submission process. */
  33. enum Part
  34. {
  35. PartStart,
  36. PartUpdate,
  37. PartConfigure,
  38. PartBuild,
  39. PartTest,
  40. PartCoverage,
  41. PartMemCheck,
  42. PartSubmit,
  43. PartNotes,
  44. PartExtraFiles,
  45. PartUpload,
  46. PartCount // Update names in constructor when adding a part
  47. };
  48. /** Representation of one part. */
  49. struct PartInfo
  50. {
  51. PartInfo()
  52. : Enabled(false)
  53. {
  54. }
  55. void SetName(const std::string& name) { this->Name = name; }
  56. const std::string& GetName() const { return this->Name; }
  57. void Enable() { this->Enabled = true; }
  58. operator bool() const { return this->Enabled; }
  59. std::vector<std::string> SubmitFiles;
  60. private:
  61. bool Enabled;
  62. std::string Name;
  63. };
  64. #ifdef CMAKE_BUILD_WITH_CMAKE
  65. enum HTTPMethod
  66. {
  67. HTTP_GET,
  68. HTTP_POST,
  69. HTTP_PUT
  70. };
  71. /**
  72. * Perform an HTTP request.
  73. */
  74. static int HTTPRequest(std::string url, HTTPMethod method,
  75. std::string& response, std::string const& fields = "",
  76. std::string const& putFile = "", int timeout = 0);
  77. #endif
  78. /** Get a testing part id from its string name. Returns PartCount
  79. if the string does not name a valid part. */
  80. Part GetPartFromName(const char* name);
  81. typedef std::vector<cmsys::String> VectorOfStrings;
  82. typedef std::set<std::string> SetOfStrings;
  83. /** Process Command line arguments */
  84. int Run(std::vector<std::string>&, std::string* output = CM_NULLPTR);
  85. /**
  86. * Initialize and finalize testing
  87. */
  88. bool InitializeFromCommand(cmCTestStartCommand* command);
  89. void Finalize();
  90. /**
  91. * Process the dashboard client steps.
  92. *
  93. * Steps are enabled using SetTest()
  94. *
  95. * The execution of the steps (or #Part) should look like this:
  96. *
  97. * /code
  98. * ctest foo;
  99. * foo.Initialize();
  100. * // Set some things on foo
  101. * foo.ProcessSteps();
  102. * foo.Finalize();
  103. * /endcode
  104. *
  105. * \sa Initialize(), Finalize(), Part, PartInfo, SetTest()
  106. */
  107. int ProcessSteps();
  108. /**
  109. * A utility function that returns the nightly time
  110. */
  111. struct tm* GetNightlyTime(std::string const& str, bool tomorrowtag);
  112. /**
  113. * Is the tomorrow tag set?
  114. */
  115. bool GetTomorrowTag() { return this->TomorrowTag; }
  116. /**
  117. * Try to run tests of the project
  118. */
  119. int TestDirectory(bool memcheck);
  120. /** what is the configuraiton type, e.g. Debug, Release etc. */
  121. std::string const& GetConfigType();
  122. double GetTimeOut() { return this->TimeOut; }
  123. void SetTimeOut(double t) { this->TimeOut = t; }
  124. double GetGlobalTimeout() { return this->GlobalTimeout; }
  125. /** how many test to run at the same time */
  126. int GetParallelLevel() { return this->ParallelLevel; }
  127. void SetParallelLevel(int);
  128. unsigned long GetTestLoad() { return this->TestLoad; }
  129. void SetTestLoad(unsigned long);
  130. /**
  131. * Check if CTest file exists
  132. */
  133. bool CTestFileExists(const std::string& filename);
  134. bool AddIfExists(Part part, const char* file);
  135. /**
  136. * Set the cmake test
  137. */
  138. bool SetTest(const char*, bool report = true);
  139. /**
  140. * Set the cmake test mode (experimental, nightly, continuous).
  141. */
  142. void SetTestModel(int mode);
  143. int GetTestModel() { return this->TestModel; }
  144. std::string GetTestModelString();
  145. static int GetTestModelFromString(const char* str);
  146. static std::string CleanString(const std::string& str);
  147. std::string GetCTestConfiguration(const std::string& name);
  148. void SetCTestConfiguration(const char* name, const char* value,
  149. bool suppress = false);
  150. void EmptyCTestConfiguration();
  151. /**
  152. * constructor and destructor
  153. */
  154. cmCTest();
  155. ~cmCTest();
  156. /** Set the notes files to be created. */
  157. void SetNotesFiles(const char* notes);
  158. void PopulateCustomVector(cmMakefile* mf, const std::string& definition,
  159. std::vector<std::string>& vec);
  160. void PopulateCustomInteger(cmMakefile* mf, const std::string& def, int& val);
  161. /** Get the current time as string */
  162. std::string CurrentTime();
  163. /** tar/gzip and then base 64 encode a file */
  164. std::string Base64GzipEncodeFile(std::string const& file);
  165. /** base64 encode a file */
  166. std::string Base64EncodeFile(std::string const& file);
  167. /**
  168. * Return the time remaining that the script is allowed to run in
  169. * seconds if the user has set the variable CTEST_TIME_LIMIT. If that has
  170. * not been set it returns 1e7 seconds
  171. */
  172. double GetRemainingTimeAllowed();
  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::string GetStopTime() { return this->StopTime; }
  185. void SetStopTime(std::string const& time);
  186. /** Used for parallel ctest job scheduling */
  187. std::string GetScheduleType() { return this->ScheduleType; }
  188. void SetScheduleType(std::string const& type) { this->ScheduleType = type; }
  189. /** The max output width */
  190. int GetMaxTestNameWidth() const;
  191. void SetMaxTestNameWidth(int w) { this->MaxTestNameWidth = w; }
  192. /**
  193. * Run a single executable command and put the stdout and stderr
  194. * in output.
  195. *
  196. * If verbose is false, no user-viewable output from the program
  197. * being run will be generated.
  198. *
  199. * If timeout is specified, the command will be terminated after
  200. * timeout expires. Timeout is specified in seconds.
  201. *
  202. * Argument retVal should be a pointer to the location where the
  203. * exit code will be stored. If the retVal is not specified and
  204. * the program exits with a code other than 0, then the this
  205. * function will return false.
  206. *
  207. * If the command has spaces in the path the caller MUST call
  208. * cmSystemTools::ConvertToRunCommandPath on the command before passing
  209. * it into this function or it will not work. The command must be correctly
  210. * escaped for this to with spaces.
  211. */
  212. bool RunCommand(const char* command, std::string* stdOut,
  213. std::string* stdErr, int* retVal = CM_NULLPTR,
  214. const char* dir = CM_NULLPTR, double timeout = 0.0,
  215. Encoding encoding = cmProcessOutput::Auto);
  216. /**
  217. * Clean/make safe for xml the given value such that it may be used as
  218. * one of the key fields by CDash when computing the buildid.
  219. */
  220. static std::string SafeBuildIdField(const std::string& value);
  221. /** Start CTest XML output file */
  222. void StartXML(cmXMLWriter& xml, bool append);
  223. /** End CTest XML output file */
  224. void EndXML(cmXMLWriter& xml);
  225. /**
  226. * Run command specialized for make and configure. Returns process status
  227. * and retVal is return value or exception.
  228. */
  229. int RunMakeCommand(const char* command, std::string& output, int* retVal,
  230. const char* dir, int timeout, std::ostream& ofs,
  231. Encoding encoding = cmProcessOutput::Auto);
  232. /** Return the current tag */
  233. std::string GetCurrentTag();
  234. /** Get the path to the build tree */
  235. std::string GetBinaryDir();
  236. /**
  237. * Get the short path to the file.
  238. *
  239. * This means if the file is in binary or
  240. * source directory, it will become /.../relative/path/to/file
  241. */
  242. std::string GetShortPathToFile(const char* fname);
  243. enum
  244. {
  245. EXPERIMENTAL,
  246. NIGHTLY,
  247. CONTINUOUS
  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, double 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 send as an 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. /** Submit extra files to the server */
  311. bool SubmitExtraFiles(const char* files);
  312. bool SubmitExtraFiles(const VectorOfStrings& files);
  313. /** Set the output log file name */
  314. void SetOutputLogFileName(const char* name);
  315. /** Set the visual studio or Xcode config type */
  316. void SetConfigType(const char* ct);
  317. /** Various log types */
  318. enum
  319. {
  320. DEBUG = 0,
  321. OUTPUT,
  322. HANDLER_OUTPUT,
  323. HANDLER_PROGRESS_OUTPUT,
  324. HANDLER_VERBOSE_OUTPUT,
  325. WARNING,
  326. ERROR_MESSAGE,
  327. OTHER
  328. };
  329. /** Add log to the output */
  330. void Log(int logType, const char* file, int line, const char* msg,
  331. bool suppress = false);
  332. /** Get the version of dart server */
  333. int GetDartVersion() { return this->DartVersion; }
  334. int GetDropSiteCDash() { return this->DropSiteCDash; }
  335. /** Add file to be submitted */
  336. void AddSubmitFile(Part part, const char* name);
  337. std::vector<std::string> const& GetSubmitFiles(Part part)
  338. {
  339. return this->Parts[part].SubmitFiles;
  340. }
  341. void ClearSubmitFiles(Part part) { this->Parts[part].SubmitFiles.clear(); }
  342. /**
  343. * Read the custom configuration files and apply them to the current ctest
  344. */
  345. int ReadCustomConfigurationFileTree(const char* dir, cmMakefile* mf);
  346. std::vector<std::string>& GetInitialCommandLineArguments()
  347. {
  348. return this->InitialCommandLineArguments;
  349. }
  350. /** Set the track to submit to */
  351. void SetSpecificTrack(const char* track);
  352. const char* GetSpecificTrack();
  353. void SetFailover(bool failover) { this->Failover = failover; }
  354. bool GetFailover() { return this->Failover; }
  355. void SetBatchJobs(bool batch = true) { this->BatchJobs = batch; }
  356. bool GetBatchJobs() { return this->BatchJobs; }
  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. std::string GetCostDataFile();
  368. const std::map<std::string, std::string>& GetDefinitions()
  369. {
  370. return this->Definitions;
  371. }
  372. /** Return the number of times a test should be run */
  373. int GetTestRepeat() { return this->RepeatTests; }
  374. /** Return true if test should run until fail */
  375. bool GetRepeatUntilFail() { return this->RepeatUntilFail; }
  376. void GenerateSubprojectsOutput(cmXMLWriter& xml);
  377. std::vector<std::string> GetLabelsForSubprojects();
  378. private:
  379. int RepeatTests;
  380. bool RepeatUntilFail;
  381. std::string ConfigType;
  382. std::string ScheduleType;
  383. std::string StopTime;
  384. bool NextDayStopTime;
  385. bool Verbose;
  386. bool ExtraVerbose;
  387. bool ProduceXML;
  388. bool LabelSummary;
  389. bool UseHTTP10;
  390. bool PrintLabels;
  391. bool Failover;
  392. bool BatchJobs;
  393. bool ForceNewCTestProcess;
  394. bool RunConfigurationScript;
  395. int GenerateNotesFile(const char* files);
  396. void DetermineNextDayStop();
  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. std::string CTestConfigFile;
  404. // TODO: The ctest configuration should be a hierarchy of
  405. // configuration option sources: command-line, script, ini file.
  406. // Then the ini file can get re-loaded whenever it changes without
  407. // affecting any higher-precedence settings.
  408. CTestConfigurationMap CTestConfiguration;
  409. CTestConfigurationMap CTestConfigurationOverwrites;
  410. PartInfo Parts[PartCount];
  411. typedef std::map<std::string, Part> PartMapType;
  412. PartMapType PartMap;
  413. std::string CurrentTag;
  414. bool TomorrowTag;
  415. int TestModel;
  416. std::string SpecificTrack;
  417. double TimeOut;
  418. double GlobalTimeout;
  419. int LastStopTimeout;
  420. int MaxTestNameWidth;
  421. int ParallelLevel;
  422. bool ParallelLevelSetInCli;
  423. unsigned long TestLoad;
  424. int CompatibilityMode;
  425. // information for the --build-and-test options
  426. std::string BinaryDir;
  427. std::string NotesFiles;
  428. bool InteractiveDebugMode;
  429. bool ShortDateFormat;
  430. bool CompressXMLFiles;
  431. bool CompressTestOutput;
  432. void InitStreams();
  433. std::ostream* StreamOut;
  434. std::ostream* StreamErr;
  435. void BlockTestErrorDiagnostics();
  436. /**
  437. * Initialize a dashboard run in the given build tree. The "command"
  438. * argument is non-NULL when running from a command-driven (ctest_start)
  439. * dashboard script, and NULL when running from the CTest command
  440. * line. Note that a declarative dashboard script does not actually
  441. * call this method because it sets CTEST_COMMAND to drive a build
  442. * through the ctest command line.
  443. */
  444. int Initialize(const char* binary_dir, cmCTestStartCommand* command);
  445. /** parse the option after -D and convert it into the appropriate steps */
  446. bool AddTestsForDashboardType(std::string& targ);
  447. /** read as "emit an error message for an unknown -D value" */
  448. void ErrorMessageUnknownDashDValue(std::string& val);
  449. /** add a variable definition from a command line -D value */
  450. bool AddVariableDefinition(const std::string& arg);
  451. /** parse and process most common command line arguments */
  452. bool HandleCommandLineArguments(size_t& i, std::vector<std::string>& args,
  453. std::string& errormsg);
  454. /** hande the -S -SP and -SR arguments */
  455. void HandleScriptArguments(size_t& i, std::vector<std::string>& args,
  456. bool& SRArgumentSpecified);
  457. /** Reread the configuration file */
  458. bool UpdateCTestConfiguration();
  459. /** Create note from files. */
  460. int GenerateCTestNotesOutput(cmXMLWriter& xml, const VectorOfStrings& files);
  461. /** Check if the argument is the one specified */
  462. bool CheckArgument(const std::string& arg, const char* varg1,
  463. const char* varg2 = CM_NULLPTR);
  464. /** Output errors from a test */
  465. void OutputTestErrors(std::vector<char> const& process_output);
  466. /** Handle the --test-action command line argument */
  467. bool HandleTestActionArgument(const char* ctestExec, size_t& i,
  468. const std::vector<std::string>& args);
  469. /** Handle the --test-model command line argument */
  470. bool HandleTestModelArgument(const char* ctestExec, size_t& i,
  471. const std::vector<std::string>& args);
  472. int RunCMakeAndTest(std::string* output);
  473. int ExecuteTests();
  474. bool SuppressUpdatingCTestConfiguration;
  475. bool Debug;
  476. bool ShowLineNumbers;
  477. bool Quiet;
  478. int DartVersion;
  479. bool DropSiteCDash;
  480. std::vector<std::string> InitialCommandLineArguments;
  481. int SubmitIndex;
  482. cmGeneratedFileStream* OutputLogFile;
  483. int OutputLogFileLastTag;
  484. bool OutputTestOutputOnTestFailure;
  485. std::map<std::string, std::string> Definitions;
  486. };
  487. class cmCTestLogWrite
  488. {
  489. public:
  490. cmCTestLogWrite(const char* data, size_t length)
  491. : Data(data)
  492. , Length(length)
  493. {
  494. }
  495. const char* Data;
  496. size_t Length;
  497. };
  498. inline std::ostream& operator<<(std::ostream& os, const cmCTestLogWrite& c)
  499. {
  500. if (!c.Length) {
  501. return os;
  502. }
  503. os.write(c.Data, c.Length);
  504. os.flush();
  505. return os;
  506. }
  507. #define cmCTestLog(ctSelf, logType, msg) \
  508. do { \
  509. std::ostringstream cmCTestLog_msg; \
  510. cmCTestLog_msg << msg; \
  511. (ctSelf)->Log(cmCTest::logType, __FILE__, __LINE__, \
  512. cmCTestLog_msg.str().c_str()); \
  513. } while (false)
  514. #define cmCTestOptionalLog(ctSelf, logType, msg, suppress) \
  515. do { \
  516. std::ostringstream cmCTestLog_msg; \
  517. cmCTestLog_msg << msg; \
  518. (ctSelf)->Log(cmCTest::logType, __FILE__, __LINE__, \
  519. cmCTestLog_msg.str().c_str(), suppress); \
  520. } while (false)
  521. #endif