cmCTest.h 18 KB

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