cmCTest.h 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601
  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. cmOStringStream 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 char* name) { this->Name = name; }
  63. const char* GetName() const { return this->Name.c_str(); }
  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<cmStdString> VectorOfStrings;
  89. typedef std::set<cmStdString> 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 char *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 char* definition,
  157. VectorOfStrings& vec);
  158. void PopulateCustomInteger(cmMakefile* mf, const char* 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::ofstream& 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. //! Get the path to CTest
  238. const char* GetCTestExecutable() { return this->CTestSelf.c_str(); }
  239. const char* GetCMakeExecutable() { return this->CMakeSelf.c_str(); }
  240. enum {
  241. EXPERIMENTAL,
  242. NIGHTLY,
  243. CONTINUOUS
  244. };
  245. // provide some more detailed info on the return code for ctest
  246. enum {
  247. UPDATE_ERRORS = 0x01,
  248. CONFIGURE_ERRORS = 0x02,
  249. BUILD_ERRORS = 0x04,
  250. TEST_ERRORS = 0x08,
  251. MEMORY_ERRORS = 0x10,
  252. COVERAGE_ERRORS = 0x20,
  253. SUBMIT_ERRORS = 0x40
  254. };
  255. ///! Are we producing XML
  256. bool GetProduceXML();
  257. void SetProduceXML(bool v);
  258. //! Run command specialized for tests. Returns process status and retVal is
  259. // return value or exception. If environment is non-null, it is used to set
  260. // environment variables prior to running the test. After running the test,
  261. // environment variables are restored to their previous values.
  262. int RunTest(std::vector<const char*> args, std::string* output, int *retVal,
  263. std::ostream* logfile, double testTimeOut,
  264. std::vector<std::string>* environment);
  265. /**
  266. * Execute handler and return its result. If the handler fails, it returns
  267. * negative value.
  268. */
  269. int ExecuteHandler(const char* handler);
  270. /*
  271. * Get the handler object
  272. */
  273. cmCTestGenericHandler* GetHandler(const char* handler);
  274. cmCTestGenericHandler* GetInitializedHandler(const char* handler);
  275. /*
  276. * Set the CTest variable from CMake variable
  277. */
  278. bool SetCTestConfigurationFromCMakeVariable(cmMakefile* mf,
  279. const char* dconfig, const char* cmake_var);
  280. //! Make string safe to be send as an URL
  281. static std::string MakeURLSafe(const std::string&);
  282. /** Decode a URL to the original string. */
  283. static std::string DecodeURL(const std::string&);
  284. //! Should ctect configuration be updated. When using new style ctest
  285. // script, this should be true.
  286. void SetSuppressUpdatingCTestConfiguration(bool val)
  287. {
  288. this->SuppressUpdatingCTestConfiguration = val;
  289. }
  290. //! Add overwrite to ctest configuration.
  291. // The format is key=value
  292. void AddCTestConfigurationOverwrite(const char* encstr);
  293. //! Create XML file that contains all the notes specified
  294. int GenerateNotesFile(const std::vector<cmStdString> &files);
  295. //! Submit extra files to the server
  296. bool SubmitExtraFiles(const char* files);
  297. bool SubmitExtraFiles(const std::vector<cmStdString> &files);
  298. //! Set the output log file name
  299. void SetOutputLogFileName(const char* name);
  300. //! Set the visual studio or Xcode config type
  301. void SetConfigType(const char* ct);
  302. //! Various log types
  303. enum {
  304. DEBUG = 0,
  305. OUTPUT,
  306. HANDLER_OUTPUT,
  307. HANDLER_VERBOSE_OUTPUT,
  308. WARNING,
  309. ERROR_MESSAGE,
  310. OTHER
  311. };
  312. //! Add log to the output
  313. void Log(int logType, const char* file, int line, const char* msg);
  314. //! Get the version of dart server
  315. int GetDartVersion() { return this->DartVersion; }
  316. int GetDropSiteCDash() { return this->DropSiteCDash; }
  317. //! Add file to be submitted
  318. void AddSubmitFile(Part part, const char* name);
  319. std::vector<std::string> const& GetSubmitFiles(Part part)
  320. { return this->Parts[part].SubmitFiles; }
  321. void ClearSubmitFiles(Part part) { this->Parts[part].SubmitFiles.clear(); }
  322. //! Read the custom configuration files and apply them to the current ctest
  323. int ReadCustomConfigurationFileTree(const char* dir, cmMakefile* mf);
  324. std::vector<cmStdString> &GetInitialCommandLineArguments()
  325. { return this->InitialCommandLineArguments; };
  326. //! Set the track to submit to
  327. void SetSpecificTrack(const char* track);
  328. const char* GetSpecificTrack();
  329. void SetFailover(bool failover) { this->Failover = failover; }
  330. bool GetFailover() { return this->Failover; }
  331. void SetBatchJobs(bool batch = true) { this->BatchJobs = batch; }
  332. bool GetBatchJobs() { return this->BatchJobs; }
  333. bool GetVerbose() { return this->Verbose;}
  334. bool GetExtraVerbose() { return this->ExtraVerbose;}
  335. /** Direct process output to given streams. */
  336. void SetStreams(std::ostream* out, std::ostream* err)
  337. { this->StreamOut = out; this->StreamErr = err; }
  338. void AddSiteProperties(std::ostream& );
  339. bool GetLabelSummary() { return this->LabelSummary;}
  340. std::string GetCostDataFile();
  341. const std::map<std::string, std::string> &GetDefinitions()
  342. {
  343. return this->Definitions;
  344. }
  345. private:
  346. std::string ConfigType;
  347. std::string ScheduleType;
  348. std::string StopTime;
  349. bool NextDayStopTime;
  350. bool Verbose;
  351. bool ExtraVerbose;
  352. bool ProduceXML;
  353. bool LabelSummary;
  354. bool UseHTTP10;
  355. bool PrintLabels;
  356. bool Failover;
  357. bool BatchJobs;
  358. bool ForceNewCTestProcess;
  359. bool RunConfigurationScript;
  360. //flag for lazy getter (optimization)
  361. bool ComputedCompressTestOutput;
  362. bool ComputedCompressMemCheckOutput;
  363. int GenerateNotesFile(const char* files);
  364. void DetermineNextDayStop();
  365. // these are helper classes
  366. typedef std::map<cmStdString,cmCTestGenericHandler*> t_TestingHandlers;
  367. t_TestingHandlers TestingHandlers;
  368. bool ShowOnly;
  369. //! Map of configuration properties
  370. typedef std::map<cmStdString, cmStdString> CTestConfigurationMap;
  371. std::string CTestConfigFile;
  372. // TODO: The ctest configuration should be a hierarchy of
  373. // configuration option sources: command-line, script, ini file.
  374. // Then the ini file can get re-loaded whenever it changes without
  375. // affecting any higher-precedence settings.
  376. CTestConfigurationMap CTestConfiguration;
  377. CTestConfigurationMap CTestConfigurationOverwrites;
  378. PartInfo Parts[PartCount];
  379. typedef std::map<cmStdString, Part> PartMapType;
  380. PartMapType PartMap;
  381. std::string CurrentTag;
  382. bool TomorrowTag;
  383. int TestModel;
  384. std::string SpecificTrack;
  385. double TimeOut;
  386. double GlobalTimeout;
  387. int LastStopTimeout;
  388. int MaxTestNameWidth;
  389. int ParallelLevel;
  390. bool ParallelLevelSetInCli;
  391. int CompatibilityMode;
  392. // information for the --build-and-test options
  393. std::string CMakeSelf;
  394. std::string CTestSelf;
  395. std::string BinaryDir;
  396. std::string NotesFiles;
  397. bool InteractiveDebugMode;
  398. bool ShortDateFormat;
  399. bool CompressXMLFiles;
  400. bool CompressTestOutput;
  401. bool CompressMemCheckOutput;
  402. void InitStreams();
  403. std::ostream* StreamOut;
  404. std::ostream* StreamErr;
  405. void BlockTestErrorDiagnostics();
  406. /**
  407. * Initialize a dashboard run in the given build tree. The "command"
  408. * argument is non-NULL when running from a command-driven (ctest_start)
  409. * dashboard script, and NULL when running from the CTest command
  410. * line. Note that a declarative dashboard script does not actually
  411. * call this method because it sets CTEST_COMMAND to drive a build
  412. * through the ctest command line.
  413. */
  414. int Initialize(const char* binary_dir, cmCTestStartCommand* command);
  415. //! parse the option after -D and convert it into the appropriate steps
  416. bool AddTestsForDashboardType(std::string &targ);
  417. //! read as "emit an error message for an unknown -D value"
  418. void ErrorMessageUnknownDashDValue(std::string &val);
  419. //! add a variable definition from a command line -D value
  420. bool AddVariableDefinition(const std::string &arg);
  421. //! parse and process most common command line arguments
  422. void HandleCommandLineArguments(size_t &i,
  423. std::vector<std::string> &args);
  424. //! hande the -S -SP and -SR arguments
  425. void HandleScriptArguments(size_t &i,
  426. std::vector<std::string> &args,
  427. bool &SRArgumentSpecified);
  428. //! Reread the configuration file
  429. bool UpdateCTestConfiguration();
  430. //! Create note from files.
  431. int GenerateCTestNotesOutput(std::ostream& os,
  432. const VectorOfStrings& files);
  433. ///! Find the running cmake
  434. void FindRunningCMake();
  435. //! Check if the argument is the one specified
  436. bool CheckArgument(const std::string& arg, const char* varg1,
  437. const char* varg2 = 0);
  438. //! Output errors from a test
  439. void OutputTestErrors(std::vector<char> const &process_output);
  440. bool SuppressUpdatingCTestConfiguration;
  441. bool Debug;
  442. bool ShowLineNumbers;
  443. bool Quiet;
  444. int DartVersion;
  445. bool DropSiteCDash;
  446. std::vector<cmStdString> InitialCommandLineArguments;
  447. int SubmitIndex;
  448. cmGeneratedFileStream* OutputLogFile;
  449. int OutputLogFileLastTag;
  450. bool OutputTestOutputOnTestFailure;
  451. std::map<std::string, std::string> Definitions;
  452. };
  453. class cmCTestLogWrite
  454. {
  455. public:
  456. cmCTestLogWrite(const char* data, size_t length)
  457. : Data(data), Length(length) {}
  458. const char* Data;
  459. size_t Length;
  460. };
  461. inline std::ostream& operator<< (std::ostream& os, const cmCTestLogWrite& c)
  462. {
  463. if (!c.Length)
  464. {
  465. return os;
  466. }
  467. os.write(c.Data, c.Length);
  468. os.flush();
  469. return os;
  470. }
  471. #endif