Imported Upstream version 2.8.11.2
[platform/upstream/cmake.git] / Source / cmCTest.h
1 /*============================================================================
2   CMake - Cross Platform Makefile Generator
3   Copyright 2000-2009 Kitware, Inc., Insight Software Consortium
4
5   Distributed under the OSI-approved BSD License (the "License");
6   see accompanying file Copyright.txt for details.
7
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 ============================================================================*/
12
13 #ifndef cmCTest_h
14 #define cmCTest_h
15
16 #include "cmStandardIncludes.h"
17 #include "cmListFileCache.h"
18 #include <time.h>
19
20 class cmake;
21 class cmMakefile;
22 class cmCTestGenericHandler;
23 class cmGeneratedFileStream;
24 class cmCTestCommand;
25 class cmCTestScriptHandler;
26 class cmCTestStartCommand;
27
28 #define cmCTestLog(ctSelf, logType, msg) \
29   do { \
30   cmOStringStream cmCTestLog_msg; \
31   cmCTestLog_msg << msg; \
32   (ctSelf)->Log(cmCTest::logType, __FILE__, __LINE__,\
33                 cmCTestLog_msg.str().c_str());\
34   } while ( 0 )
35
36 #ifdef cerr
37 #  undef cerr
38 #endif
39 #define cerr no_cerr_use_cmCTestLog
40
41 #ifdef cout
42 #  undef cout
43 #endif
44 #define cout no_cout_use_cmCTestLog
45
46 class cmCTest
47 {
48   friend class cmCTestRunTest;
49   friend class cmCTestMultiProcessHandler;
50 public:
51   /** Enumerate parts of the testing and submission process.  */
52   enum Part
53   {
54     PartStart,
55     PartUpdate,
56     PartConfigure,
57     PartBuild,
58     PartTest,
59     PartCoverage,
60     PartMemCheck,
61     PartSubmit,
62     PartNotes,
63     PartExtraFiles,
64     PartUpload,
65     PartCount // Update names in constructor when adding a part
66   };
67
68   /** Representation of one part.  */
69   struct PartInfo
70   {
71     PartInfo(): Enabled(false) {}
72
73     void SetName(const char* name) { this->Name = name; }
74     const char* GetName() const { return this->Name.c_str(); }
75
76     void Enable() { this->Enabled = true; }
77     operator bool() const { return this->Enabled; }
78
79     std::vector<std::string> SubmitFiles;
80   private:
81     bool Enabled;
82     std::string Name;
83   };
84 #ifdef CMAKE_BUILD_WITH_CMAKE
85   enum HTTPMethod {
86     HTTP_GET,
87     HTTP_POST,
88     HTTP_PUT
89   };
90
91   /**
92    * Perform an HTTP request.
93    */
94   static int HTTPRequest(std::string url, HTTPMethod method,
95                           std::string& response,
96                           std::string fields = "",
97                           std::string putFile = "", int timeout = 0);
98 #endif
99
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);
103
104   typedef std::vector<cmStdString> VectorOfStrings;
105   typedef std::set<cmStdString> SetOfStrings;
106
107   ///! Process Command line arguments
108   int Run(std::vector<std::string> &, std::string* output = 0);
109
110   /**
111    * Initialize and finalize testing
112    */
113   bool InitializeFromCommand(cmCTestStartCommand* command);
114   void Finalize();
115
116   /**
117    * Process the tests. This is the main routine. The execution of the
118    * tests should look like this:
119    *
120    * ctest foo;
121    * foo.Initialize();
122    * // Set some things on foo
123    * foo.ProcessTests();
124    * foo.Finalize();
125    */
126   int ProcessTests();
127
128   /*
129    * A utility function that returns the nightly time
130    */
131   struct tm* GetNightlyTime(std::string str,
132     bool tomorrowtag);
133
134   /*
135    * Is the tomorrow tag set?
136    */
137   bool GetTomorrowTag() { return this->TomorrowTag; };
138
139   /**
140    * Try to run tests of the project
141    */
142   int TestDirectory(bool memcheck);
143
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; }
148
149   double GetGlobalTimeout() { return this->GlobalTimeout; }
150
151   // how many test to run at the same time
152   int GetParallelLevel() { return this->ParallelLevel; }
153   void SetParallelLevel(int);
154
155   /**
156    * Check if CTest file exists
157    */
158   bool CTestFileExists(const std::string& filename);
159   bool AddIfExists(Part part, const char* file);
160
161   /**
162    * Set the cmake test
163    */
164   bool SetTest(const char*, bool report = true);
165
166   /**
167    * Set the cmake test mode (experimental, nightly, continuous).
168    */
169   void SetTestModel(int mode);
170   int GetTestModel() { return this->TestModel; };
171
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();
178
179   /**
180    * constructor and destructor
181    */
182   cmCTest();
183   ~cmCTest();
184
185   //! Set the notes files to be created.
186   void SetNotesFiles(const char* notes);
187
188   void PopulateCustomVector(cmMakefile* mf, const char* definition,
189     VectorOfStrings& vec);
190   void PopulateCustomInteger(cmMakefile* mf, const char* def,
191     int& val);
192
193   ///! Get the current time as string
194   std::string CurrentTime();
195
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);
200
201   /**
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
205    */
206   double GetRemainingTimeAllowed();
207
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);
213
214   ///! Should we only show what we would do?
215   bool GetShowOnly();
216
217   bool ShouldUseHTTP10() { return this->UseHTTP10; }
218
219   bool ShouldPrintLabels() { return this->PrintLabels; }
220
221   bool ShouldCompressTestOutput();
222   bool ShouldCompressMemCheckOutput();
223   bool CompressString(std::string& str);
224
225   std::string GetCDashVersion();
226
227   std::string GetStopTime() { return this->StopTime; }
228   void SetStopTime(std::string time);
229
230   //Used for parallel ctest job scheduling
231   std::string GetScheduleType() { return this->ScheduleType; }
232   void SetScheduleType(std::string type) { this->ScheduleType = type; }
233
234   ///! The max output width
235   int GetMaxTestNameWidth() const;
236   void SetMaxTestNameWidth(int w) { this->MaxTestNameWidth = w;}
237
238   /**
239    * Run a single executable command and put the stdout and stderr
240    * in output.
241    *
242    * If verbose is false, no user-viewable output from the program
243    * being run will be generated.
244    *
245    * If timeout is specified, the command will be terminated after
246    * timeout expires. Timeout is specified in seconds.
247    *
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.
252    *
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.
257    */
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);
261
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);
265
266   //! Start CTest XML output file
267   void StartXML(std::ostream& ostr, bool append);
268
269   //! End CTest XML output file
270   void EndXML(std::ostream& ostr);
271
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,
276     std::ofstream& ofs);
277
278   /*
279    * return the current tag
280    */
281   std::string GetCurrentTag();
282
283   //! Get the path to the build tree
284   std::string GetBinaryDir();
285
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);
289
290   //! Get the path to CTest
291   const char* GetCTestExecutable() { return this->CTestSelf.c_str(); }
292   const char* GetCMakeExecutable() { return this->CMakeSelf.c_str(); }
293
294   enum {
295     EXPERIMENTAL,
296     NIGHTLY,
297     CONTINUOUS
298   };
299
300   // provide some more detailed info on the return code for ctest
301   enum {
302     UPDATE_ERRORS    = 0x01,
303     CONFIGURE_ERRORS = 0x02,
304     BUILD_ERRORS     = 0x04,
305     TEST_ERRORS      = 0x08,
306     MEMORY_ERRORS    = 0x10,
307     COVERAGE_ERRORS  = 0x20,
308     SUBMIT_ERRORS    = 0x40
309   };
310
311   ///! Are we producing XML
312   bool GetProduceXML();
313   void SetProduceXML(bool v);
314
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);
322
323   /**
324    * Execute handler and return its result. If the handler fails, it returns
325    * negative value.
326    */
327   int ExecuteHandler(const char* handler);
328
329   /*
330    * Get the handler object
331    */
332   cmCTestGenericHandler* GetHandler(const char* handler);
333   cmCTestGenericHandler* GetInitializedHandler(const char* handler);
334
335   /*
336    * Set the CTest variable from CMake variable
337    */
338   bool SetCTestConfigurationFromCMakeVariable(cmMakefile* mf,
339     const char* dconfig, const char* cmake_var);
340
341   //! Make string safe to be send as an URL
342   static std::string MakeURLSafe(const std::string&);
343
344   /** Decode a URL to the original string.  */
345   static std::string DecodeURL(const std::string&);
346
347   //! Should ctect configuration be updated. When using new style ctest
348   // script, this should be true.
349   void SetSuppressUpdatingCTestConfiguration(bool val)
350     {
351     this->SuppressUpdatingCTestConfiguration = val;
352     }
353
354   //! Add overwrite to ctest configuration.
355   // The format is key=value
356   void AddCTestConfigurationOverwrite(const char* encstr);
357
358   //! Create XML file that contains all the notes specified
359   int GenerateNotesFile(const std::vector<cmStdString> &files);
360
361   //! Submit extra files to the server
362   bool SubmitExtraFiles(const char* files);
363   bool SubmitExtraFiles(const std::vector<cmStdString> &files);
364
365   //! Set the output log file name
366   void SetOutputLogFileName(const char* name);
367
368   //! Set the visual studio or Xcode config type
369   void SetConfigType(const char* ct);
370
371   //! Various log types
372   enum {
373     DEBUG = 0,
374     OUTPUT,
375     HANDLER_OUTPUT,
376     HANDLER_VERBOSE_OUTPUT,
377     WARNING,
378     ERROR_MESSAGE,
379     OTHER
380   };
381
382   //! Add log to the output
383   void Log(int logType, const char* file, int line, const char* msg);
384
385   //! Get the version of dart server
386   int GetDartVersion() { return this->DartVersion; }
387   int GetDropSiteCDash() { return this->DropSiteCDash; }
388
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(); }
394
395   //! Read the custom configuration files and apply them to the current ctest
396   int ReadCustomConfigurationFileTree(const char* dir, cmMakefile* mf);
397
398   std::vector<cmStdString> &GetInitialCommandLineArguments()
399   { return this->InitialCommandLineArguments; };
400
401   //! Set the track to submit to
402   void SetSpecificTrack(const char* track);
403   const char* GetSpecificTrack();
404
405   void SetFailover(bool failover) { this->Failover = failover; }
406   bool GetFailover() { return this->Failover; }
407
408   void SetBatchJobs(bool batch = true) { this->BatchJobs = batch; }
409   bool GetBatchJobs() { return this->BatchJobs; }
410
411   bool GetVerbose() { return this->Verbose;}
412   bool GetExtraVerbose() { return this->ExtraVerbose;}
413
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;}
419
420   std::string GetCostDataFile();
421
422   const std::map<std::string, std::string> &GetDefinitions()
423     {
424     return this->Definitions;
425     }
426
427 private:
428   std::string ConfigType;
429   std::string ScheduleType;
430   std::string StopTime;
431   bool NextDayStopTime;
432   bool Verbose;
433   bool ExtraVerbose;
434   bool ProduceXML;
435   bool LabelSummary;
436   bool UseHTTP10;
437   bool PrintLabels;
438   bool Failover;
439   bool BatchJobs;
440
441   bool ForceNewCTestProcess;
442
443   bool RunConfigurationScript;
444
445   //flag for lazy getter (optimization)
446   bool ComputedCompressTestOutput;
447   bool ComputedCompressMemCheckOutput;
448
449   int GenerateNotesFile(const char* files);
450
451   void DetermineNextDayStop();
452
453   // these are helper classes
454   typedef std::map<cmStdString,cmCTestGenericHandler*> t_TestingHandlers;
455   t_TestingHandlers TestingHandlers;
456
457   bool ShowOnly;
458
459   //! Map of configuration properties
460   typedef std::map<cmStdString, cmStdString> CTestConfigurationMap;
461
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;
471   PartMapType             PartMap;
472
473   std::string             CurrentTag;
474   bool                    TomorrowTag;
475
476   int                     TestModel;
477   std::string             SpecificTrack;
478
479   double                  TimeOut;
480
481   double                  GlobalTimeout;
482
483   int                     LastStopTimeout;
484
485   int                     MaxTestNameWidth;
486
487   int                     ParallelLevel;
488
489   int                     CompatibilityMode;
490
491   // information for the --build-and-test options
492   std::string              CMakeSelf;
493   std::string              CTestSelf;
494   std::string              BinaryDir;
495
496   std::string              NotesFiles;
497
498
499   bool                     InteractiveDebugMode;
500
501   bool                     ShortDateFormat;
502
503   bool                     CompressXMLFiles;
504   bool                     CompressTestOutput;
505   bool                     CompressMemCheckOutput;
506
507   void InitStreams();
508   std::ostream* StreamOut;
509   std::ostream* StreamErr;
510
511   void BlockTestErrorDiagnostics();
512
513   /**
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.
520    */
521   int Initialize(const char* binary_dir, cmCTestStartCommand* command);
522
523   //! parse the option after -D and convert it into the appropriate steps
524   bool AddTestsForDashboardType(std::string &targ);
525
526   //! read as "emit an error message for an unknown -D value"
527   void ErrorMessageUnknownDashDValue(std::string &val);
528
529   //! add a variable definition from a command line -D value
530   bool AddVariableDefinition(const std::string &arg);
531
532   //! parse and process most common command line arguments
533   void HandleCommandLineArguments(size_t &i,
534                                   std::vector<std::string> &args);
535
536   //! hande the -S -SP and -SR arguments
537   void HandleScriptArguments(size_t &i,
538                              std::vector<std::string> &args,
539                              bool &SRArgumentSpecified);
540
541   //! Reread the configuration file
542   bool UpdateCTestConfiguration();
543
544   //! Create note from files.
545   int GenerateCTestNotesOutput(std::ostream& os,
546     const VectorOfStrings& files);
547
548   ///! Find the running cmake
549   void FindRunningCMake();
550
551   //! Check if the argument is the one specified
552   bool CheckArgument(const std::string& arg, const char* varg1,
553     const char* varg2 = 0);
554
555   //! Output errors from a test
556   void OutputTestErrors(std::vector<char> const &process_output);
557
558   bool                      SuppressUpdatingCTestConfiguration;
559
560   bool Debug;
561   bool ShowLineNumbers;
562   bool Quiet;
563
564   int  DartVersion;
565   bool DropSiteCDash;
566
567   std::vector<cmStdString> InitialCommandLineArguments;
568
569   int SubmitIndex;
570
571   cmGeneratedFileStream* OutputLogFile;
572   int OutputLogFileLastTag;
573
574   bool OutputTestOutputOnTestFailure;
575
576   std::map<std::string, std::string> Definitions;
577 };
578
579 class cmCTestLogWrite
580 {
581 public:
582   cmCTestLogWrite(const char* data, size_t length)
583     : Data(data), Length(length) {}
584
585   const char* Data;
586   size_t Length;
587 };
588
589 inline std::ostream& operator<< (std::ostream& os, const cmCTestLogWrite& c)
590 {
591   if (!c.Length)
592     {
593     return os;
594     }
595   os.write(c.Data, c.Length);
596   os.flush();
597   return os;
598 }
599
600 #endif