1 /*============================================================================
2 CMake - Cross Platform Makefile Generator
3 Copyright 2000-2009 Kitware, Inc., Insight Software Consortium
5 Distributed under the OSI-approved BSD License (the "License");
6 see accompanying file Copyright.txt for details.
8 This software is distributed WITHOUT ANY WARRANTY; without even the
9 implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
10 See the License for more information.
11 ============================================================================*/
16 #include "cmStandardIncludes.h"
17 #include "cmListFileCache.h"
22 class cmCTestGenericHandler;
23 class cmGeneratedFileStream;
25 class cmCTestScriptHandler;
26 class cmCTestStartCommand;
28 #define cmCTestLog(ctSelf, logType, msg) \
30 cmOStringStream cmCTestLog_msg; \
31 cmCTestLog_msg << msg; \
32 (ctSelf)->Log(cmCTest::logType, __FILE__, __LINE__,\
33 cmCTestLog_msg.str().c_str());\
39 #define cerr no_cerr_use_cmCTestLog
44 #define cout no_cout_use_cmCTestLog
48 friend class cmCTestRunTest;
49 friend class cmCTestMultiProcessHandler;
51 /** Enumerate parts of the testing and submission process. */
65 PartCount // Update names in constructor when adding a part
68 /** Representation of one part. */
71 PartInfo(): Enabled(false) {}
73 void SetName(const char* name) { this->Name = name; }
74 const char* GetName() const { return this->Name.c_str(); }
76 void Enable() { this->Enabled = true; }
77 operator bool() const { return this->Enabled; }
79 std::vector<std::string> SubmitFiles;
84 #ifdef CMAKE_BUILD_WITH_CMAKE
92 * Perform an HTTP request.
94 static int HTTPRequest(std::string url, HTTPMethod method,
95 std::string& response,
96 std::string fields = "",
97 std::string putFile = "", int timeout = 0);
100 /** Get a testing part id from its string name. Returns PartCount
101 if the string does not name a valid part. */
102 Part GetPartFromName(const char* name);
104 typedef std::vector<cmStdString> VectorOfStrings;
105 typedef std::set<cmStdString> SetOfStrings;
107 ///! Process Command line arguments
108 int Run(std::vector<std::string> &, std::string* output = 0);
111 * Initialize and finalize testing
113 bool InitializeFromCommand(cmCTestStartCommand* command);
117 * Process the tests. This is the main routine. The execution of the
118 * tests should look like this:
122 * // Set some things on foo
123 * foo.ProcessTests();
129 * A utility function that returns the nightly time
131 struct tm* GetNightlyTime(std::string str,
135 * Is the tomorrow tag set?
137 bool GetTomorrowTag() { return this->TomorrowTag; };
140 * Try to run tests of the project
142 int TestDirectory(bool memcheck);
144 ///! what is the configuraiton type, e.g. Debug, Release etc.
145 std::string const& GetConfigType();
146 double GetTimeOut() { return this->TimeOut; }
147 void SetTimeOut(double t) { this->TimeOut = t; }
149 double GetGlobalTimeout() { return this->GlobalTimeout; }
151 // how many test to run at the same time
152 int GetParallelLevel() { return this->ParallelLevel; }
153 void SetParallelLevel(int);
156 * Check if CTest file exists
158 bool CTestFileExists(const std::string& filename);
159 bool AddIfExists(Part part, const char* file);
164 bool SetTest(const char*, bool report = true);
167 * Set the cmake test mode (experimental, nightly, continuous).
169 void SetTestModel(int mode);
170 int GetTestModel() { return this->TestModel; };
172 std::string GetTestModelString();
173 static int GetTestModelFromString(const char* str);
174 static std::string CleanString(const std::string& str);
175 std::string GetCTestConfiguration(const char *name);
176 void SetCTestConfiguration(const char *name, const char* value);
177 void EmptyCTestConfiguration();
180 * constructor and destructor
185 //! Set the notes files to be created.
186 void SetNotesFiles(const char* notes);
188 void PopulateCustomVector(cmMakefile* mf, const char* definition,
189 VectorOfStrings& vec);
190 void PopulateCustomInteger(cmMakefile* mf, const char* def,
193 ///! Get the current time as string
194 std::string CurrentTime();
196 //! tar/gzip and then base 64 encode a file
197 std::string Base64GzipEncodeFile(std::string file);
198 //! base64 encode a file
199 std::string Base64EncodeFile(std::string file);
202 * Return the time remaining that the script is allowed to run in
203 * seconds if the user has set the variable CTEST_TIME_LIMIT. If that has
204 * not been set it returns 1e7 seconds
206 double GetRemainingTimeAllowed();
208 ///! Open file in the output directory and set the stream
209 bool OpenOutputFile(const std::string& path,
210 const std::string& name,
211 cmGeneratedFileStream& stream,
212 bool compress = false);
214 ///! Should we only show what we would do?
217 bool ShouldUseHTTP10() { return this->UseHTTP10; }
219 bool ShouldPrintLabels() { return this->PrintLabels; }
221 bool ShouldCompressTestOutput();
222 bool ShouldCompressMemCheckOutput();
223 bool CompressString(std::string& str);
225 std::string GetCDashVersion();
227 std::string GetStopTime() { return this->StopTime; }
228 void SetStopTime(std::string time);
230 //Used for parallel ctest job scheduling
231 std::string GetScheduleType() { return this->ScheduleType; }
232 void SetScheduleType(std::string type) { this->ScheduleType = type; }
234 ///! The max output width
235 int GetMaxTestNameWidth() const;
236 void SetMaxTestNameWidth(int w) { this->MaxTestNameWidth = w;}
239 * Run a single executable command and put the stdout and stderr
242 * If verbose is false, no user-viewable output from the program
243 * being run will be generated.
245 * If timeout is specified, the command will be terminated after
246 * timeout expires. Timeout is specified in seconds.
248 * Argument retVal should be a pointer to the location where the
249 * exit code will be stored. If the retVal is not specified and
250 * the program exits with a code other than 0, then the this
251 * function will return false.
253 * If the command has spaces in the path the caller MUST call
254 * cmSystemTools::ConvertToRunCommandPath on the command before passing
255 * it into this function or it will not work. The command must be correctly
256 * escaped for this to with spaces.
258 bool RunCommand(const char* command,
259 std::string* stdOut, std::string* stdErr,
260 int* retVal = 0, const char* dir = 0, double timeout = 0.0);
262 //! Clean/make safe for xml the given value such that it may be used as
263 // one of the key fields by CDash when computing the buildid.
264 static std::string SafeBuildIdField(const std::string& value);
266 //! Start CTest XML output file
267 void StartXML(std::ostream& ostr, bool append);
269 //! End CTest XML output file
270 void EndXML(std::ostream& ostr);
272 //! Run command specialized for make and configure. Returns process status
273 // and retVal is return value or exception.
274 int RunMakeCommand(const char* command, std::string* output,
275 int* retVal, const char* dir, int timeout,
279 * return the current tag
281 std::string GetCurrentTag();
283 //! Get the path to the build tree
284 std::string GetBinaryDir();
286 //! Get the short path to the file. This means if the file is in binary or
287 //source directory, it will become /.../relative/path/to/file
288 std::string GetShortPathToFile(const char* fname);
290 //! Get the path to CTest
291 const char* GetCTestExecutable() { return this->CTestSelf.c_str(); }
292 const char* GetCMakeExecutable() { return this->CMakeSelf.c_str(); }
300 // provide some more detailed info on the return code for ctest
302 UPDATE_ERRORS = 0x01,
303 CONFIGURE_ERRORS = 0x02,
306 MEMORY_ERRORS = 0x10,
307 COVERAGE_ERRORS = 0x20,
311 ///! Are we producing XML
312 bool GetProduceXML();
313 void SetProduceXML(bool v);
315 //! Run command specialized for tests. Returns process status and retVal is
316 // return value or exception. If environment is non-null, it is used to set
317 // environment variables prior to running the test. After running the test,
318 // environment variables are restored to their previous values.
319 int RunTest(std::vector<const char*> args, std::string* output, int *retVal,
320 std::ostream* logfile, double testTimeOut,
321 std::vector<std::string>* environment);
324 * Execute handler and return its result. If the handler fails, it returns
327 int ExecuteHandler(const char* handler);
330 * Get the handler object
332 cmCTestGenericHandler* GetHandler(const char* handler);
333 cmCTestGenericHandler* GetInitializedHandler(const char* handler);
336 * Set the CTest variable from CMake variable
338 bool SetCTestConfigurationFromCMakeVariable(cmMakefile* mf,
339 const char* dconfig, const char* cmake_var);
341 //! Make string safe to be send as an URL
342 static std::string MakeURLSafe(const std::string&);
344 /** Decode a URL to the original string. */
345 static std::string DecodeURL(const std::string&);
347 //! Should ctect configuration be updated. When using new style ctest
348 // script, this should be true.
349 void SetSuppressUpdatingCTestConfiguration(bool val)
351 this->SuppressUpdatingCTestConfiguration = val;
354 //! Add overwrite to ctest configuration.
355 // The format is key=value
356 void AddCTestConfigurationOverwrite(const char* encstr);
358 //! Create XML file that contains all the notes specified
359 int GenerateNotesFile(const std::vector<cmStdString> &files);
361 //! Submit extra files to the server
362 bool SubmitExtraFiles(const char* files);
363 bool SubmitExtraFiles(const std::vector<cmStdString> &files);
365 //! Set the output log file name
366 void SetOutputLogFileName(const char* name);
368 //! Set the visual studio or Xcode config type
369 void SetConfigType(const char* ct);
371 //! Various log types
376 HANDLER_VERBOSE_OUTPUT,
382 //! Add log to the output
383 void Log(int logType, const char* file, int line, const char* msg);
385 //! Get the version of dart server
386 int GetDartVersion() { return this->DartVersion; }
387 int GetDropSiteCDash() { return this->DropSiteCDash; }
389 //! Add file to be submitted
390 void AddSubmitFile(Part part, const char* name);
391 std::vector<std::string> const& GetSubmitFiles(Part part)
392 { return this->Parts[part].SubmitFiles; }
393 void ClearSubmitFiles(Part part) { this->Parts[part].SubmitFiles.clear(); }
395 //! Read the custom configuration files and apply them to the current ctest
396 int ReadCustomConfigurationFileTree(const char* dir, cmMakefile* mf);
398 std::vector<cmStdString> &GetInitialCommandLineArguments()
399 { return this->InitialCommandLineArguments; };
401 //! Set the track to submit to
402 void SetSpecificTrack(const char* track);
403 const char* GetSpecificTrack();
405 void SetFailover(bool failover) { this->Failover = failover; }
406 bool GetFailover() { return this->Failover; }
408 void SetBatchJobs(bool batch = true) { this->BatchJobs = batch; }
409 bool GetBatchJobs() { return this->BatchJobs; }
411 bool GetVerbose() { return this->Verbose;}
412 bool GetExtraVerbose() { return this->ExtraVerbose;}
414 /** Direct process output to given streams. */
415 void SetStreams(std::ostream* out, std::ostream* err)
416 { this->StreamOut = out; this->StreamErr = err; }
417 void AddSiteProperties(std::ostream& );
418 bool GetLabelSummary() { return this->LabelSummary;}
420 std::string GetCostDataFile();
422 const std::map<std::string, std::string> &GetDefinitions()
424 return this->Definitions;
428 std::string ConfigType;
429 std::string ScheduleType;
430 std::string StopTime;
431 bool NextDayStopTime;
441 bool ForceNewCTestProcess;
443 bool RunConfigurationScript;
445 //flag for lazy getter (optimization)
446 bool ComputedCompressTestOutput;
447 bool ComputedCompressMemCheckOutput;
449 int GenerateNotesFile(const char* files);
451 void DetermineNextDayStop();
453 // these are helper classes
454 typedef std::map<cmStdString,cmCTestGenericHandler*> t_TestingHandlers;
455 t_TestingHandlers TestingHandlers;
459 //! Map of configuration properties
460 typedef std::map<cmStdString, cmStdString> CTestConfigurationMap;
462 std::string CTestConfigFile;
463 // TODO: The ctest configuration should be a hierarchy of
464 // configuration option sources: command-line, script, ini file.
465 // Then the ini file can get re-loaded whenever it changes without
466 // affecting any higher-precedence settings.
467 CTestConfigurationMap CTestConfiguration;
468 CTestConfigurationMap CTestConfigurationOverwrites;
469 PartInfo Parts[PartCount];
470 typedef std::map<cmStdString, Part> PartMapType;
473 std::string CurrentTag;
477 std::string SpecificTrack;
481 double GlobalTimeout;
485 int MaxTestNameWidth;
489 int CompatibilityMode;
491 // information for the --build-and-test options
492 std::string CMakeSelf;
493 std::string CTestSelf;
494 std::string BinaryDir;
496 std::string NotesFiles;
499 bool InteractiveDebugMode;
501 bool ShortDateFormat;
503 bool CompressXMLFiles;
504 bool CompressTestOutput;
505 bool CompressMemCheckOutput;
508 std::ostream* StreamOut;
509 std::ostream* StreamErr;
511 void BlockTestErrorDiagnostics();
514 * Initialize a dashboard run in the given build tree. The "command"
515 * argument is non-NULL when running from a command-driven (ctest_start)
516 * dashboard script, and NULL when running from the CTest command
517 * line. Note that a declarative dashboard script does not actually
518 * call this method because it sets CTEST_COMMAND to drive a build
519 * through the ctest command line.
521 int Initialize(const char* binary_dir, cmCTestStartCommand* command);
523 //! parse the option after -D and convert it into the appropriate steps
524 bool AddTestsForDashboardType(std::string &targ);
526 //! read as "emit an error message for an unknown -D value"
527 void ErrorMessageUnknownDashDValue(std::string &val);
529 //! add a variable definition from a command line -D value
530 bool AddVariableDefinition(const std::string &arg);
532 //! parse and process most common command line arguments
533 void HandleCommandLineArguments(size_t &i,
534 std::vector<std::string> &args);
536 //! hande the -S -SP and -SR arguments
537 void HandleScriptArguments(size_t &i,
538 std::vector<std::string> &args,
539 bool &SRArgumentSpecified);
541 //! Reread the configuration file
542 bool UpdateCTestConfiguration();
544 //! Create note from files.
545 int GenerateCTestNotesOutput(std::ostream& os,
546 const VectorOfStrings& files);
548 ///! Find the running cmake
549 void FindRunningCMake();
551 //! Check if the argument is the one specified
552 bool CheckArgument(const std::string& arg, const char* varg1,
553 const char* varg2 = 0);
555 //! Output errors from a test
556 void OutputTestErrors(std::vector<char> const &process_output);
558 bool SuppressUpdatingCTestConfiguration;
561 bool ShowLineNumbers;
567 std::vector<cmStdString> InitialCommandLineArguments;
571 cmGeneratedFileStream* OutputLogFile;
572 int OutputLogFileLastTag;
574 bool OutputTestOutputOnTestFailure;
576 std::map<std::string, std::string> Definitions;
579 class cmCTestLogWrite
582 cmCTestLogWrite(const char* data, size_t length)
583 : Data(data), Length(length) {}
589 inline std::ostream& operator<< (std::ostream& os, const cmCTestLogWrite& c)
595 os.write(c.Data, c.Length);