cmCTest.h 17 KB

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