cmCTest.h 19 KB

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