cmCTest.h 18 KB

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