cmCTestBuildAndTest.cxx 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366
  1. /* Distributed under the OSI-approved BSD 3-Clause License. See accompanying
  2. file Copyright.txt or https://cmake.org/licensing for details. */
  3. #include "cmCTestBuildAndTest.h"
  4. #include <chrono>
  5. #include <cstdint>
  6. #include <cstring>
  7. #include <iostream>
  8. #include <ratio>
  9. #include <utility>
  10. #include <cmext/algorithm>
  11. #include <cm3p/uv.h>
  12. #include "cmBuildOptions.h"
  13. #include "cmCTest.h"
  14. #include "cmCTestTestHandler.h"
  15. #include "cmGlobalGenerator.h"
  16. #include "cmMakefile.h"
  17. #include "cmProcessOutput.h"
  18. #include "cmState.h"
  19. #include "cmStringAlgorithms.h"
  20. #include "cmSystemTools.h"
  21. #include "cmUVHandlePtr.h"
  22. #include "cmUVProcessChain.h"
  23. #include "cmUVStream.h"
  24. #include "cmWorkingDirectory.h"
  25. #include "cmake.h"
  26. struct cmMessageMetadata;
  27. cmCTestBuildAndTest::cmCTestBuildAndTest(cmCTest* ctest)
  28. : CTest(ctest)
  29. {
  30. }
  31. int cmCTestBuildAndTest::RunCMake(cmake* cm)
  32. {
  33. std::vector<std::string> args;
  34. args.push_back(cmSystemTools::GetCMakeCommand());
  35. args.push_back(this->SourceDir);
  36. if (!this->BuildGenerator.empty()) {
  37. args.push_back("-G" + this->BuildGenerator);
  38. }
  39. if (!this->BuildGeneratorPlatform.empty()) {
  40. args.push_back("-A" + this->BuildGeneratorPlatform);
  41. }
  42. if (!this->BuildGeneratorToolset.empty()) {
  43. args.push_back("-T" + this->BuildGeneratorToolset);
  44. }
  45. const char* config = nullptr;
  46. if (!this->CTest->GetConfigType().empty()) {
  47. config = this->CTest->GetConfigType().c_str();
  48. }
  49. if (config) {
  50. args.push_back("-DCMAKE_BUILD_TYPE:STRING=" + std::string(config));
  51. }
  52. if (!this->BuildMakeProgram.empty() &&
  53. (this->BuildGenerator.find("Make") != std::string::npos ||
  54. this->BuildGenerator.find("Ninja") != std::string::npos)) {
  55. args.push_back("-DCMAKE_MAKE_PROGRAM:FILEPATH=" + this->BuildMakeProgram);
  56. }
  57. for (std::string const& opt : this->BuildOptions) {
  58. args.push_back(opt);
  59. }
  60. std::cout << "======== CMake output ======\n";
  61. if (cm->Run(args) != 0) {
  62. std::cout << "======== End CMake output ======\n";
  63. std::cout << "Error: cmake execution failed\n";
  64. return 1;
  65. }
  66. // do another config?
  67. if (this->BuildTwoConfig) {
  68. if (cm->Run(args) != 0) {
  69. std::cout << "======== End CMake output ======\n";
  70. std::cout << "Error: cmake execution failed\n";
  71. return 1;
  72. }
  73. }
  74. std::cout << "======== End CMake output ======\n";
  75. return 0;
  76. }
  77. bool cmCTestBuildAndTest::RunTest(std::vector<std::string> const& argv,
  78. std::string* output, int* retVal,
  79. cmDuration timeout)
  80. {
  81. std::vector<char> tempOutput;
  82. if (output) {
  83. output->clear();
  84. }
  85. cmUVProcessChainBuilder builder;
  86. builder.AddCommand(argv).SetMergedBuiltinStreams();
  87. auto chain = builder.Start();
  88. cmProcessOutput processOutput(cmProcessOutput::Auto);
  89. cm::uv_pipe_ptr outputStream;
  90. outputStream.init(chain.GetLoop(), 0);
  91. uv_pipe_open(outputStream, chain.OutputStream());
  92. auto outputHandle = cmUVStreamRead(
  93. outputStream,
  94. [&output, &tempOutput](std::vector<char> data) {
  95. if (output) {
  96. cm::append(tempOutput, data.data(), data.data() + data.size());
  97. }
  98. },
  99. []() {});
  100. bool complete = chain.Wait(static_cast<uint64_t>(timeout.count() * 1000.0));
  101. processOutput.DecodeText(tempOutput, tempOutput);
  102. if (output && tempOutput.begin() != tempOutput.end()) {
  103. output->append(tempOutput.data(), tempOutput.size());
  104. }
  105. bool result = false;
  106. if (complete) {
  107. auto const& status = chain.GetStatus(0);
  108. auto exception = status.GetException();
  109. switch (exception.first) {
  110. case cmUVProcessChain::ExceptionCode::None:
  111. *retVal = static_cast<int>(status.ExitStatus);
  112. result = true;
  113. break;
  114. case cmUVProcessChain::ExceptionCode::Spawn: {
  115. if (output) {
  116. std::string outerr =
  117. cmStrCat("\n*** ERROR executing: ", exception.second);
  118. *output += outerr;
  119. }
  120. } break;
  121. default: {
  122. *retVal = status.TermSignal;
  123. if (output) {
  124. std::string outerr =
  125. cmStrCat("\n*** Exception executing: ", exception.second);
  126. *output += outerr;
  127. }
  128. } break;
  129. }
  130. }
  131. return result;
  132. }
  133. class cmCTestBuildAndTestCaptureRAII
  134. {
  135. cmake& CM;
  136. public:
  137. cmCTestBuildAndTestCaptureRAII(cmake& cm)
  138. : CM(cm)
  139. {
  140. cmSystemTools::SetMessageCallback(
  141. [](const std::string& msg, const cmMessageMetadata& /* unused */) {
  142. std::cout << msg << std::endl;
  143. });
  144. cmSystemTools::SetStdoutCallback(
  145. [](std::string const& m) { std::cout << m << std::flush; });
  146. cmSystemTools::SetStderrCallback(
  147. [](std::string const& m) { std::cout << m << std::flush; });
  148. this->CM.SetProgressCallback([](const std::string& msg, float prog) {
  149. if (prog < 0) {
  150. std::cout << msg << std::endl;
  151. }
  152. });
  153. }
  154. ~cmCTestBuildAndTestCaptureRAII()
  155. {
  156. this->CM.SetProgressCallback(nullptr);
  157. cmSystemTools::SetStderrCallback(nullptr);
  158. cmSystemTools::SetStdoutCallback(nullptr);
  159. cmSystemTools::SetMessageCallback(nullptr);
  160. }
  161. cmCTestBuildAndTestCaptureRAII(const cmCTestBuildAndTestCaptureRAII&) =
  162. delete;
  163. cmCTestBuildAndTestCaptureRAII& operator=(
  164. const cmCTestBuildAndTestCaptureRAII&) = delete;
  165. };
  166. int cmCTestBuildAndTest::Run()
  167. {
  168. // if the generator and make program are not specified then it is an error
  169. if (this->BuildGenerator.empty()) {
  170. std::cout << "--build-and-test requires that the generator "
  171. "be provided using the --build-generator "
  172. "command line option.\n";
  173. return 1;
  174. }
  175. cmake cm(cmake::RoleProject, cmState::Project);
  176. cm.SetHomeDirectory("");
  177. cm.SetHomeOutputDirectory("");
  178. cmCTestBuildAndTestCaptureRAII captureRAII(cm);
  179. static_cast<void>(captureRAII);
  180. if (this->CTest->GetConfigType().empty() && !this->ConfigSample.empty()) {
  181. // use the config sample to set the ConfigType
  182. std::string fullPath;
  183. std::string resultingConfig;
  184. std::vector<std::string> extraPaths;
  185. std::vector<std::string> failed;
  186. fullPath = cmCTestTestHandler::FindExecutable(
  187. this->CTest, this->ConfigSample, resultingConfig, extraPaths, failed);
  188. if (!fullPath.empty() && !resultingConfig.empty()) {
  189. this->CTest->SetConfigType(resultingConfig);
  190. }
  191. std::cout << "Using config sample with results: " << fullPath << " and "
  192. << resultingConfig << std::endl;
  193. }
  194. // we need to honor the timeout specified, the timeout include cmake, build
  195. // and test time
  196. auto clock_start = std::chrono::steady_clock::now();
  197. // make sure the binary dir is there
  198. std::cout << "Internal cmake changing into directory: " << this->BinaryDir
  199. << std::endl;
  200. if (!cmSystemTools::FileIsDirectory(this->BinaryDir)) {
  201. cmSystemTools::MakeDirectory(this->BinaryDir);
  202. }
  203. cmWorkingDirectory workdir(this->BinaryDir);
  204. if (workdir.Failed()) {
  205. std::cout << "Failed to change working directory to " << this->BinaryDir
  206. << " : " << std::strerror(workdir.GetLastResult()) << '\n';
  207. return 1;
  208. }
  209. if (this->BuildNoCMake) {
  210. // Make the generator available for the Build call below.
  211. cm.SetGlobalGenerator(cm.CreateGlobalGenerator(this->BuildGenerator));
  212. if (!this->BuildGeneratorPlatform.empty()) {
  213. cmMakefile mf(cm.GetGlobalGenerator(), cm.GetCurrentSnapshot());
  214. if (!cm.GetGlobalGenerator()->SetGeneratorPlatform(
  215. this->BuildGeneratorPlatform, &mf)) {
  216. return 1;
  217. }
  218. }
  219. // Load the cache to make CMAKE_MAKE_PROGRAM available.
  220. cm.LoadCache(this->BinaryDir);
  221. } else {
  222. // do the cmake step, no timeout here since it is not a sub process
  223. if (this->RunCMake(&cm)) {
  224. return 1;
  225. }
  226. }
  227. // do the build
  228. if (this->BuildTargets.empty()) {
  229. this->BuildTargets.emplace_back();
  230. }
  231. for (std::string const& tar : this->BuildTargets) {
  232. cmDuration remainingTime = std::chrono::seconds(0);
  233. if (this->Timeout > cmDuration::zero()) {
  234. remainingTime =
  235. this->Timeout - (std::chrono::steady_clock::now() - clock_start);
  236. if (remainingTime <= std::chrono::seconds(0)) {
  237. std::cout << "--build-and-test timeout exceeded. ";
  238. return 1;
  239. }
  240. }
  241. const char* config = nullptr;
  242. if (!this->CTest->GetConfigType().empty()) {
  243. config = this->CTest->GetConfigType().c_str();
  244. }
  245. if (!config) {
  246. config = "Debug";
  247. }
  248. cmBuildOptions buildOptions(!this->BuildNoClean, false,
  249. PackageResolveMode::Disable);
  250. int retVal = cm.GetGlobalGenerator()->Build(
  251. cmake::NO_BUILD_PARALLEL_LEVEL, this->SourceDir, this->BinaryDir,
  252. this->BuildProject, { tar }, std::cout, this->BuildMakeProgram, config,
  253. buildOptions, false, remainingTime, cmSystemTools::OUTPUT_PASSTHROUGH);
  254. // if the build failed then return
  255. if (retVal) {
  256. return 1;
  257. }
  258. }
  259. // if no test was specified then we are done
  260. if (this->TestCommand.empty()) {
  261. return 0;
  262. }
  263. // now run the compiled test if we can find it
  264. // store the final location in fullPath
  265. std::string fullPath;
  266. std::string resultingConfig;
  267. std::vector<std::string> extraPaths;
  268. // if this->ExecutableDirectory is set try that as well
  269. if (!this->ExecutableDirectory.empty()) {
  270. std::string tempPath =
  271. cmStrCat(this->ExecutableDirectory, '/', this->TestCommand);
  272. extraPaths.push_back(tempPath);
  273. }
  274. std::vector<std::string> failed;
  275. fullPath = cmCTestTestHandler::FindExecutable(
  276. this->CTest, this->TestCommand, resultingConfig, extraPaths, failed);
  277. if (!cmSystemTools::FileExists(fullPath)) {
  278. std::cout
  279. << "Could not find path to executable, perhaps it was not built: "
  280. << this->TestCommand << "\n"
  281. << "tried to find it in these places:\n"
  282. << fullPath << "\n";
  283. for (std::string const& fail : failed) {
  284. std::cout << fail << "\n";
  285. }
  286. return 1;
  287. }
  288. std::vector<std::string> testCommand;
  289. testCommand.push_back(fullPath);
  290. for (std::string const& testCommandArg : this->TestCommandArgs) {
  291. testCommand.push_back(testCommandArg);
  292. }
  293. int retval = 0;
  294. // run the test from the this->BuildRunDir if set
  295. if (!this->BuildRunDir.empty()) {
  296. std::cout << "Run test in directory: " << this->BuildRunDir << "\n";
  297. if (!workdir.SetDirectory(this->BuildRunDir)) {
  298. std::cout << "Failed to change working directory : "
  299. << std::strerror(workdir.GetLastResult()) << "\n";
  300. return 1;
  301. }
  302. }
  303. std::cout << "Running test command: \"" << fullPath << "\"";
  304. for (std::string const& testCommandArg : this->TestCommandArgs) {
  305. std::cout << " \"" << testCommandArg << "\"";
  306. }
  307. std::cout << "\n";
  308. // how much time is remaining
  309. cmDuration remainingTime = std::chrono::seconds(0);
  310. if (this->Timeout > cmDuration::zero()) {
  311. remainingTime =
  312. this->Timeout - (std::chrono::steady_clock::now() - clock_start);
  313. if (remainingTime <= std::chrono::seconds(0)) {
  314. std::cout << "--build-and-test timeout exceeded. ";
  315. return 1;
  316. }
  317. }
  318. std::string outs;
  319. bool runTestRes = this->RunTest(testCommand, &outs, &retval, remainingTime);
  320. if (!runTestRes || retval != 0) {
  321. std::cout << "Test command failed: " << testCommand[0] << "\n";
  322. retval = 1;
  323. }
  324. std::cout << outs << "\n";
  325. return retval;
  326. }