1 /* Distributed under the OSI-approved BSD 3-Clause License. See accompanying
2 file Copyright.txt or https://cmake.org/licensing for details. */
5 #include "cmConfigure.h" // IWYU pragma: keep
15 #include <cm/string_view>
17 #include "cmDuration.h"
18 #include "cmProcessOutput.h"
20 class cmCTestBuildHandler;
21 class cmCTestBuildAndTestHandler;
22 class cmCTestCoverageHandler;
23 class cmCTestScriptHandler;
24 class cmCTestTestHandler;
25 class cmCTestUpdateHandler;
26 class cmCTestConfigureHandler;
27 class cmCTestMemCheckHandler;
28 class cmCTestSubmitHandler;
29 class cmCTestUploadHandler;
30 class cmCTestStartCommand;
31 class cmGeneratedFileStream;
36 * \brief Represents a ctest invocation.
38 * This class represents a ctest invocation. It is the top level class when
45 using Encoding = cmProcessOutput::Encoding;
46 /** Enumerate parts of the testing and submission process. */
61 PartCount // Update names in constructor when adding a part
64 /** Get a testing part id from its string name. Returns PartCount
65 if the string does not name a valid part. */
66 Part GetPartFromName(const std::string& name);
68 /** Process Command line arguments */
69 int Run(std::vector<std::string>&, std::string* output = nullptr);
72 * Initialize and finalize testing
74 bool InitializeFromCommand(cmCTestStartCommand* command);
78 * Process the dashboard client steps.
80 * Steps are enabled using SetTest()
82 * The execution of the steps (or #Part) should look like this:
87 * // Set some things on foo
92 * \sa Initialize(), Finalize(), Part, PartInfo, SetTest()
97 * A utility function that returns the nightly time
99 struct tm* GetNightlyTime(std::string const& str, bool tomorrowtag);
102 * Is the tomorrow tag set?
104 bool GetTomorrowTag() const;
107 * Try to run tests of the project
109 int TestDirectory(bool memcheck);
111 /** what is the configuration type, e.g. Debug, Release etc. */
112 std::string const& GetConfigType();
113 cmDuration GetTimeOut() const;
114 void SetTimeOut(cmDuration t);
116 cmDuration GetGlobalTimeout() const;
118 /** how many test to run at the same time */
119 int GetParallelLevel() const;
120 void SetParallelLevel(int);
122 unsigned long GetTestLoad() const;
123 void SetTestLoad(unsigned long);
126 * Check if CTest file exists
128 bool CTestFileExists(const std::string& filename);
129 bool AddIfExists(Part part, const std::string& file);
134 bool SetTest(const std::string&, bool report = true);
137 * Set the cmake test mode (experimental, nightly, continuous).
139 void SetTestModel(int mode);
140 int GetTestModel() const;
142 std::string GetTestModelString();
143 static int GetTestModelFromString(const std::string& str);
144 static std::string CleanString(const std::string& str,
145 std::string::size_type spos = 0);
146 std::string GetCTestConfiguration(const std::string& name);
147 void SetCTestConfiguration(const char* name, const std::string& value,
148 bool suppress = false);
149 void EmptyCTestConfiguration();
151 std::string GetSubmitURL();
154 * constructor and destructor
159 cmCTest(const cmCTest&) = delete;
160 cmCTest& operator=(const cmCTest&) = delete;
162 /** Set the notes files to be created. */
163 void SetNotesFiles(const std::string& notes);
165 void PopulateCustomVector(cmMakefile* mf, const std::string& definition,
166 std::vector<std::string>& vec);
167 void PopulateCustomInteger(cmMakefile* mf, const std::string& def, int& val);
169 /** Get the current time as string */
170 std::string CurrentTime();
172 /** tar/gzip and then base 64 encode a file */
173 std::string Base64GzipEncodeFile(std::string const& file);
174 /** base64 encode a file */
175 std::string Base64EncodeFile(std::string const& file);
178 * Return the time remaining that the script is allowed to run in
179 * seconds if the user has set the variable CTEST_TIME_LIMIT. If that has
180 * not been set it returns a very large duration.
182 cmDuration GetRemainingTimeAllowed();
184 static cmDuration MaxDuration();
187 * Open file in the output directory and set the stream
189 bool OpenOutputFile(const std::string& path, const std::string& name,
190 cmGeneratedFileStream& stream, bool compress = false);
192 /** Should we only show what we would do? */
195 bool GetOutputAsJson();
197 int GetOutputAsJsonVersion();
199 bool ShouldUseHTTP10() const;
201 bool ShouldPrintLabels() const;
203 bool ShouldCompressTestOutput();
204 bool CompressString(std::string& str);
206 bool GetStopOnFailure() const;
207 void SetStopOnFailure(bool stop);
209 std::chrono::system_clock::time_point GetStopTime() const;
210 void SetStopTime(std::string const& time);
212 /** Used for parallel ctest job scheduling */
213 std::string GetScheduleType() const;
214 void SetScheduleType(std::string const& type);
216 /** The max output width */
217 int GetMaxTestNameWidth() const;
218 void SetMaxTestNameWidth(int w);
221 * Run a single executable command and put the stdout and stderr
224 * If verbose is false, no user-viewable output from the program
225 * being run will be generated.
227 * If timeout is specified, the command will be terminated after
228 * timeout expires. Timeout is specified in seconds.
230 * Argument retVal should be a pointer to the location where the
231 * exit code will be stored. If the retVal is not specified and
232 * the program exits with a code other than 0, then the this
233 * function will return false.
235 bool RunCommand(std::vector<std::string> const& args, std::string* stdOut,
236 std::string* stdErr, int* retVal = nullptr,
237 const char* dir = nullptr,
238 cmDuration timeout = cmDuration::zero(),
239 Encoding encoding = cmProcessOutput::Auto);
242 * Clean/make safe for xml the given value such that it may be used as
243 * one of the key fields by CDash when computing the buildid.
245 static std::string SafeBuildIdField(const std::string& value);
247 /** Start CTest XML output file */
248 void StartXML(cmXMLWriter& xml, bool append);
250 /** End CTest XML output file */
251 void EndXML(cmXMLWriter& xml);
254 * Run command specialized for make and configure. Returns process status
255 * and retVal is return value or exception.
257 int RunMakeCommand(const std::string& command, std::string& output,
258 int* retVal, const char* dir, cmDuration timeout,
260 Encoding encoding = cmProcessOutput::Auto);
262 /** Return the current tag */
263 std::string GetCurrentTag();
265 /** Get the path to the build tree */
266 std::string GetBinaryDir();
269 * Get the short path to the file.
271 * This means if the file is in binary or
272 * source directory, it will become /.../relative/path/to/file
274 std::string GetShortPathToFile(const std::string& fname);
284 /** provide some more detailed info on the return code for ctest */
287 UPDATE_ERRORS = 0x01,
288 CONFIGURE_ERRORS = 0x02,
291 MEMORY_ERRORS = 0x10,
292 COVERAGE_ERRORS = 0x20,
296 /** Are we producing XML */
297 bool GetProduceXML();
298 void SetProduceXML(bool v);
301 * Run command specialized for tests. Returns process status and retVal is
302 * return value or exception. If environment is non-null, it is used to set
303 * environment variables prior to running the test. After running the test,
304 * environment variables are restored to their previous values.
306 int RunTest(std::vector<const char*> args, std::string* output, int* retVal,
307 std::ostream* logfile, cmDuration testTimeOut,
308 std::vector<std::string>* environment,
309 Encoding encoding = cmProcessOutput::Auto);
312 * Get the handler object
314 cmCTestBuildHandler* GetBuildHandler();
315 cmCTestBuildAndTestHandler* GetBuildAndTestHandler();
316 cmCTestCoverageHandler* GetCoverageHandler();
317 cmCTestScriptHandler* GetScriptHandler();
318 cmCTestTestHandler* GetTestHandler();
319 cmCTestUpdateHandler* GetUpdateHandler();
320 cmCTestConfigureHandler* GetConfigureHandler();
321 cmCTestMemCheckHandler* GetMemCheckHandler();
322 cmCTestSubmitHandler* GetSubmitHandler();
323 cmCTestUploadHandler* GetUploadHandler();
326 * Set the CTest variable from CMake variable
328 bool SetCTestConfigurationFromCMakeVariable(cmMakefile* mf,
330 const std::string& cmake_var,
331 bool suppress = false);
333 /** Decode a URL to the original string. */
334 static std::string DecodeURL(const std::string&);
337 * Should ctect configuration be updated. When using new style ctest
338 * script, this should be true.
340 void SetSuppressUpdatingCTestConfiguration(bool val);
343 * Add overwrite to ctest configuration.
345 * The format is key=value
347 void AddCTestConfigurationOverwrite(const std::string& encstr);
349 /** Create XML file that contains all the notes specified */
350 int GenerateNotesFile(std::vector<std::string> const& files);
352 /** Create XML file to indicate that build is complete */
353 int GenerateDoneFile();
355 /** Submit extra files to the server */
356 bool SubmitExtraFiles(const std::string& files);
357 bool SubmitExtraFiles(std::vector<std::string> const& files);
359 /** Set the output log file name */
360 void SetOutputLogFileName(const std::string& name);
362 /** Set the output JUnit file name */
363 void SetOutputJUnitFileName(const std::string& name);
365 /** Set the visual studio or Xcode config type */
366 void SetConfigType(const std::string& ct);
368 /** Various log types */
374 HANDLER_PROGRESS_OUTPUT,
375 HANDLER_TEST_PROGRESS_OUTPUT,
376 HANDLER_VERBOSE_OUTPUT,
382 /** Add log to the output */
383 void Log(int logType, const char* file, int line, const char* msg,
384 bool suppress = false);
396 /** Get color code characters for a specific color */
397 std::string GetColorCode(Color color) const;
399 /** The Build ID is assigned by CDash */
400 void SetBuildID(const std::string& id);
401 std::string GetBuildID() const;
403 /** Add file to be submitted */
404 void AddSubmitFile(Part part, const std::string& name);
405 std::vector<std::string> const& GetSubmitFiles(Part part) const;
406 void ClearSubmitFiles(Part part);
409 * Read the custom configuration files and apply them to the current ctest
411 int ReadCustomConfigurationFileTree(const std::string& dir, cmMakefile* mf);
413 std::vector<std::string>& GetInitialCommandLineArguments();
415 /** Set the group to submit to */
416 void SetSpecificGroup(const char* group);
417 const char* GetSpecificGroup();
419 void SetFailover(bool failover);
420 bool GetFailover() const;
422 bool GetTestProgressOutput() const;
424 bool GetVerbose() const;
425 bool GetExtraVerbose() const;
427 /** Direct process output to given streams. */
428 void SetStreams(std::ostream* out, std::ostream* err);
430 void AddSiteProperties(cmXMLWriter& xml);
432 bool GetLabelSummary() const;
433 bool GetSubprojectSummary() const;
435 std::string GetCostDataFile();
437 bool GetOutputTestOutputOnTestFailure() const;
439 const std::map<std::string, std::string>& GetDefinitions() const;
441 /** Return the number of times a test should be run */
442 int GetRepeatCount() const;
451 Repeat GetRepeatMode() const;
459 NoTests GetNoTestsMode() const;
461 void GenerateSubprojectsOutput(cmXMLWriter& xml);
462 std::vector<std::string> GetLabelsForSubprojects();
464 void SetRunCurrentScript(bool value);
467 void SetPersistentOptionIfNotEmpty(const std::string& value,
468 const std::string& optionName);
469 void AddPersistentMultiOptionIfNotEmpty(const std::string& value,
470 const std::string& optionName);
472 int GenerateNotesFile(const std::string& files);
474 void BlockTestErrorDiagnostics();
477 * Initialize a dashboard run in the given build tree. The "command"
478 * argument is non-NULL when running from a command-driven (ctest_start)
479 * dashboard script, and NULL when running from the CTest command
480 * line. Note that a declarative dashboard script does not actually
481 * call this method because it sets CTEST_COMMAND to drive a build
482 * through the ctest command line.
484 int Initialize(const char* binary_dir, cmCTestStartCommand* command);
486 /** parse the option after -D and convert it into the appropriate steps */
487 bool AddTestsForDashboardType(std::string& targ);
489 /** read as "emit an error message for an unknown -D value" */
490 void ErrorMessageUnknownDashDValue(std::string& val);
492 /** add a variable definition from a command line -D value */
493 bool AddVariableDefinition(const std::string& arg);
495 /** set command line arguments read from a test preset */
496 bool SetArgsFromPreset(const std::string& presetName, bool listPresets);
498 /** parse and process most common command line arguments */
499 bool HandleCommandLineArguments(size_t& i, std::vector<std::string>& args,
500 std::string& errormsg);
503 /** returns true iff the console supports progress output */
504 static bool ConsoleIsNotDumb();
507 /** returns true iff the console supports progress output */
508 static bool ProgressOutputSupportedByConsole();
510 /** returns true iff the console supports colored output */
511 static bool ColoredOutputSupportedByConsole();
513 /** handle the -S -SP and -SR arguments */
514 void HandleScriptArguments(size_t& i, std::vector<std::string>& args,
515 bool& SRArgumentSpecified);
517 /** Reread the configuration file */
518 bool UpdateCTestConfiguration();
520 /** Create note from files. */
521 int GenerateCTestNotesOutput(cmXMLWriter& xml,
522 std::vector<std::string> const& files);
524 /** Check if the argument is the one specified */
525 static bool CheckArgument(const std::string& arg, cm::string_view varg1,
526 const char* varg2 = nullptr);
528 /** Output errors from a test */
529 void OutputTestErrors(std::vector<char> const& process_output);
531 /** Handle the --test-action command line argument */
532 bool HandleTestActionArgument(const char* ctestExec, size_t& i,
533 const std::vector<std::string>& args);
535 /** Handle the --test-model command line argument */
536 bool HandleTestModelArgument(const char* ctestExec, size_t& i,
537 const std::vector<std::string>& args);
539 int RunCMakeAndTest(std::string* output);
542 /** return true iff change directory was successful */
543 bool TryToChangeDirectory(std::string const& dir);
546 std::unique_ptr<Private> Impl;
549 class cmCTestLogWrite
552 cmCTestLogWrite(const char* data, size_t length)
562 inline std::ostream& operator<<(std::ostream& os, const cmCTestLogWrite& c)
567 os.write(c.Data, c.Length);
572 #define cmCTestLog(ctSelf, logType, msg) \
574 std::ostringstream cmCTestLog_msg; \
575 cmCTestLog_msg << msg; \
576 (ctSelf)->Log(cmCTest::logType, __FILE__, __LINE__, \
577 cmCTestLog_msg.str().c_str()); \
580 #define cmCTestOptionalLog(ctSelf, logType, msg, suppress) \
582 std::ostringstream cmCTestLog_msg; \
583 cmCTestLog_msg << msg; \
584 (ctSelf)->Log(cmCTest::logType, __FILE__, __LINE__, \
585 cmCTestLog_msg.str().c_str(), suppress); \