cmCTest.h 17 KB

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