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