15#include <initializer_list>
19#ifdef CPP_UTILITIES_USE_STANDARD_FILESYSTEM
28#ifdef PLATFORM_WINDOWS
29#ifdef CPP_UTILITIES_USE_STANDARD_FILESYSTEM
34#ifdef CPP_UTILITIES_BOOST_PROCESS
35#include <boost/asio/buffers_iterator.hpp>
36#include <boost/asio/io_context.hpp>
37#include <boost/asio/streambuf.hpp>
38#if BOOST_VERSION >= 108600
39#include <boost/process/v1/async.hpp>
40#include <boost/process/v1/child.hpp>
41#include <boost/process/v1/env.hpp>
42#include <boost/process/v1/environment.hpp>
43#include <boost/process/v1/group.hpp>
44#include <boost/process/v1/io.hpp>
45#include <boost/process/v1/search_path.hpp>
47#include <boost/process/async.hpp>
48#include <boost/process/child.hpp>
49#include <boost/process/env.hpp>
50#include <boost/process/environment.hpp>
51#include <boost/process/group.hpp>
52#include <boost/process/io.hpp>
53#include <boost/process/search_path.hpp>
54namespace boost::process {
55namespace v1 = boost::process;
60#ifdef PLATFORM_WINDOWS
73static bool fileSystemItemExists(
const string &path)
77 return stat(path.data(), &res) == 0;
79 const auto widePath(convertMultiByteToWide(path));
80 if (!widePath.first) {
83 const auto fileType(GetFileAttributesW(widePath.first.get()));
84 return fileType != INVALID_FILE_ATTRIBUTES;
88static bool fileExists(
const string &path)
92 return stat(path.data(), &res) == 0 && !S_ISDIR(res.st_mode);
94 const auto widePath(convertMultiByteToWide(path));
95 if (!widePath.first) {
98 const auto fileType(GetFileAttributesW(widePath.first.get()));
99 return (fileType != INVALID_FILE_ATTRIBUTES) && !(fileType & FILE_ATTRIBUTE_DIRECTORY) && !(fileType & FILE_ATTRIBUTE_DEVICE);
103static bool dirExists(
const string &path)
107 return stat(path.data(), &res) == 0 && S_ISDIR(res.st_mode);
109 const auto widePath(convertMultiByteToWide(path));
110 if (!widePath.first) {
113 const auto fileType(GetFileAttributesW(widePath.first.get()));
114 return (fileType != INVALID_FILE_ATTRIBUTES) && (fileType & FILE_ATTRIBUTE_DIRECTORY);
118static bool makeDir(
const string &path)
121 return mkdir(path.data(), S_IRWXU | S_IRWXG | S_IROTH | S_IXOTH) == 0;
123 const auto widePath(convertMultiByteToWide(path));
124 if (!widePath.first) {
127 return CreateDirectoryW(widePath.first.get(),
nullptr) || GetLastError() == ERROR_ALREADY_EXISTS;
156 : m_listArg(
"list",
'l',
"lists available test units")
157 , m_runArg(
"run",
'r',
"runs the tests")
158 , m_testFilesPathArg(
"test-files-path",
'p',
"specifies the path of the directory with test files", {
"path" })
159 , m_applicationPathArg(
"app-path",
'a',
"specifies the path of the application to be tested", {
"path" })
160 , m_workingDirArg(
"working-dir",
'w',
"specifies the directory to store working copies of test files", {
"path" })
161 , m_unitsArg(
"units",
'u',
"specifies the units to test; omit to test all units", {
"unit1",
"unit2",
"unit3" })
165 throw runtime_error(
"only one TestApplication instance allowed at a time");
174 m_runArg.setImplicit(
true);
175 m_runArg.setSubArguments({ &m_testFilesPathArg, &m_applicationPathArg, &m_workingDirArg, &m_unitsArg });
176 m_parser.setMainArguments({ &m_runArg, &m_listArg, &m_parser.noColorArg(), &m_parser.helpArg() });
188 if (m_parser.helpArg().isPresent()) {
195 if (m_testFilesPathArg.isPresent()) {
196 for (
const char *
const testFilesPath : m_testFilesPathArg.values()) {
197 if (*testFilesPath) {
198 m_testFilesPaths.emplace_back(
argsToString(testFilesPath,
'/'));
200 m_testFilesPaths.emplace_back(
"./");
205 bool hasTestFilePathFromEnv;
206 if (
auto testFilePathFromEnv = readTestfilePathFromEnv(); (hasTestFilePathFromEnv = !testFilePathFromEnv.empty())) {
207 m_testFilesPaths.emplace_back(std::move(testFilePathFromEnv));
210 if (
auto testFilePathFromSrcDirRef = readTestfilePathFromSrcRef(); !testFilePathFromSrcDirRef.empty()) {
211 m_testFilesPaths.insert(m_testFilesPaths.end(), std::make_move_iterator(testFilePathFromSrcDirRef.begin()),
212 std::make_move_iterator(testFilePathFromSrcDirRef.end()));
215 m_testFilesPaths.emplace_back(
"./testfiles/");
216 for (
const auto &testFilesPath : m_testFilesPaths) {
217 cerr << testFilesPath <<
'\n';
221 if (m_workingDirArg.isPresent()) {
222 if (*m_workingDirArg.values().front()) {
223 (m_workingDir = m_workingDirArg.values().front()) +=
'/';
227 }
else if (
const char *
const workingDirEnv = getenv(
"WORKING_DIR")) {
228 if (*workingDirEnv) {
232 if ((m_testFilesPathArg.isPresent() && !m_testFilesPathArg.values().empty()) || hasTestFilePathFromEnv) {
233 m_workingDir = m_testFilesPaths.front() +
"workingdir/";
235 m_workingDir =
"./testfiles/workingdir/";
238 cerr <<
"Directory used to store working copies:\n" << m_workingDir <<
'\n';
241 if (
const char *
const profrawListFile = getenv(
"LLVM_PROFILE_LIST_FILE")) {
242 ofstream(profrawListFile, ios_base::trunc);
253 s_instance =
nullptr;
271 for (
const auto &testFilesPath : m_testFilesPaths) {
272 if (fileExists(path = testFilesPath + relativeTestFilePath)) {
276 throw std::runtime_error(
"The test file \"" % relativeTestFilePath %
"\" can not be located. Was looking under:\n"
277 +
joinStrings(m_testFilesPaths,
"\n",
false,
" - ", relativeTestFilePath));
289 for (
const auto &testFilesPath : m_testFilesPaths) {
290 if (dirExists(path = testFilesPath + relativeTestDirPath)) {
294 throw std::runtime_error(
"The test directory \"" % relativeTestDirPath %
"\" can not be located. Was looking under:\n"
295 +
joinStrings(m_testFilesPaths,
"\n",
false,
" - ", relativeTestDirPath));
325 const std::string &relativeTestFilePath,
const std::string &relativeWorkingCopyPath,
WorkingCopyMode mode)
const
329 if (!dirExists(m_workingDir) && !makeDir(m_workingDir)) {
330 cerr <<
Phrases::Error <<
"Unable to create working copy for \"" << relativeTestFilePath <<
"\": can't create working directory \""
337 if (!parts.empty()) {
340 currentLevel.reserve(m_workingDir.size() + relativeWorkingCopyPath.size() + 1);
341 currentLevel.assign(m_workingDir);
342 for (
auto i = parts.cbegin(), end = parts.end() - 1;
i != end; ++
i) {
343 if (currentLevel.back() !=
'/') {
349 if (dirExists(currentLevel) || makeDir(currentLevel)) {
353 cerr <<
Phrases::Error <<
"Unable to create working copy for \"" << relativeWorkingCopyPath <<
"\": can't create directory \""
367 const auto error = std::strerror(errno);
376 const auto origFilePath =
testFilePath(relativeTestFilePath);
377 size_t workingCopyPathAttempt = 0;
379 origFile.open(origFilePath, ios_base::in | ios_base::binary);
380 if (origFile.fail()) {
381 cerr <<
Phrases::Error <<
"Unable to create working copy for \"" << relativeTestFilePath
382 <<
"\": an IO error occurred when opening original file \"" << origFilePath <<
"\"." <<
Phrases::EndFlush;
383 cerr <<
"error: " << std::strerror(errno) << endl;
387 workingCopy.open(
workingCopyPath, ios_base::out | ios_base::binary | ios_base::trunc);
392 workingCopy.open(
workingCopyPath, ios_base::out | ios_base::binary | ios_base::trunc);
394 if (workingCopy.fail()) {
395 cerr <<
Phrases::Error <<
"Unable to create working copy for \"" << relativeTestFilePath
397 cerr <<
"error: " << strerror(errno) << endl;
401 workingCopy << origFile.rdbuf();
403 if (!origFile.fail() && !workingCopy.fail()) {
407 cerr <<
Phrases::Error <<
"Unable to create working copy for \"" << relativeTestFilePath <<
"\": ";
408 if (origFile.fail()) {
409 cerr <<
"an IO error occurred when reading original file \"" << origFilePath <<
"\"";
413 if (workingCopy.fail()) {
414 if (origFile.fail()) {
417 cerr <<
" an IO error occurred when writing to target file \"" <<
workingCopyPath <<
"\".";
419 cerr <<
"error: " << strerror(errno) << endl;
424#ifdef CPP_UTILITIES_HAS_EXEC_APP
426#if defined(CPP_UTILITIES_BOOST_PROCESS)
427inline static std::string streambufToString(boost::asio::streambuf &buf)
429 const auto begin = boost::asio::buffers_begin(buf.data());
430 return std::string(begin, begin +
static_cast<std::ptrdiff_t
>(buf.size()));
438static int execAppInternal(
const char *appPath,
const char *
const *args, std::string &output, std::string &errors,
bool suppressLogging,
int timeout,
439 const std::string &newProfilingPath,
bool enableSearchPath =
false)
442 if (!suppressLogging) {
444 cout <<
'-' <<
' ' << appPath;
446 for (
const char *
const *
i = args + 1; *
i; ++
i) {
453#if defined(CPP_UTILITIES_BOOST_PROCESS)
454 auto path = enableSearchPath ? boost::process::v1::search_path(appPath) : boost::process::v1::filesystem::path(appPath);
455 auto ctx = boost::asio::io_context();
456 auto group = boost::process::v1::group();
458#if defined(PLATFORM_WINDOWS)
459 std::vector<std::wstring>();
461 std::vector<std::string>();
464 for (
const char *
const *arg = args + 1; *arg; ++arg) {
465#if defined(PLATFORM_WINDOWS)
466 auto ec = std::error_code();
467 argsAsVector.emplace_back(convertMultiByteToWide(ec, std::string_view(*arg)));
469 throw std::runtime_error(
argsToString(
"unable to convert arg \"", *arg,
"\" to wide string"));
472 argsAsVector.emplace_back(*arg);
476 auto outputBuffer = boost::asio::streambuf(), errorBuffer = boost::asio::streambuf();
477 auto env = boost::process::v1::environment(boost::this_process::environment());
478 if (!newProfilingPath.empty()) {
479 env[
"LLVM_PROFILE_FILE"] = newProfilingPath;
481 auto child = boost::process::v1::child(
482 ctx, group, path, argsAsVector, env, boost::process::v1::std_out > outputBuffer, boost::process::v1::std_err > errorBuffer);
484 ctx.run_for(std::chrono::milliseconds(timeout));
488 output = streambufToString(outputBuffer);
489 errors = streambufToString(errorBuffer);
492 return child.exit_code();
494#elif defined(PLATFORM_UNIX)
496 int coutPipes[2], cerrPipes[2];
497 if (pipe(coutPipes) != 0 || pipe(cerrPipes) != 0) {
498 throw std::runtime_error(
argsToString(
"Unable to create pipe: ", std::strerror(errno)));
500 const auto readCoutPipe = coutPipes[0], writeCoutPipe = coutPipes[1];
501 const auto readCerrPipe = cerrPipes[0], writeCerrPipe = cerrPipes[1];
504 if (
const auto child = fork()) {
506 close(writeCoutPipe);
507 close(writeCerrPipe);
511 throw std::runtime_error(
argsToString(
"Unable to create fork: ", std::strerror(errno)));
515 struct pollfd fileDescriptorSet[2];
516 fileDescriptorSet[0].fd = readCoutPipe;
517 fileDescriptorSet[1].fd = readCerrPipe;
518 fileDescriptorSet[0].events = fileDescriptorSet[1].events = POLLIN;
527 const auto retpoll = poll(fileDescriptorSet, 2, timeout);
529 throw std::runtime_error(
"Poll timed out");
532 throw std::runtime_error(
argsToString(
"Poll failed: ", std::strerror(errno)));
534 if (fileDescriptorSet[0].revents & POLLIN) {
535 const auto count = read(readCoutPipe, buffer,
sizeof(buffer));
537 output.append(buffer,
static_cast<size_t>(count));
539 }
else if (fileDescriptorSet[0].revents & POLLHUP) {
541 fileDescriptorSet[0].fd = -1;
543 if (fileDescriptorSet[1].revents & POLLIN) {
544 const auto count = read(readCerrPipe, buffer,
sizeof(buffer));
546 errors.append(buffer,
static_cast<size_t>(count));
548 }
else if (fileDescriptorSet[1].revents & POLLHUP) {
550 fileDescriptorSet[1].fd = -1;
552 }
while (fileDescriptorSet[0].fd >= 0 || fileDescriptorSet[1].fd >= 0);
562 waitpid(child, &childReturnCode, 0);
563 waitpid(-child,
nullptr, 0);
564 return childReturnCode;
568 if (dup2(writeCoutPipe, STDOUT_FILENO) == -1 || dup2(writeCerrPipe, STDERR_FILENO) == -1) {
569 std::cerr << Phrases::Error <<
"Unable to duplicate file descriptor: " << std::strerror(errno) << Phrases::EndFlush;
570 std::exit(EXIT_FAILURE);
573 close(writeCoutPipe);
575 close(writeCerrPipe);
579 cerr << Phrases::Error <<
"Unable create process group: " << std::strerror(errno) << Phrases::EndFlush;
584 if (!newProfilingPath.empty()) {
585 setenv(
"LLVM_PROFILE_FILE", newProfilingPath.data(),
true);
589 if (enableSearchPath) {
590 execvp(appPath,
const_cast<char *
const *
>(args));
592 execv(appPath,
const_cast<char *
const *
>(args));
594 cerr << Phrases::Error <<
"Unable to execute \"" << appPath <<
"\": " << std::strerror(errno) << Phrases::EndFlush;
599 throw std::runtime_error(
"lauching test applications is not supported on this platform");
611int TestApplication::execApp(
const char *
const *args,
string &output,
string &errors,
bool suppressLogging,
int timeout)
const
614 static unsigned int invocationCount = 0;
618 const char *
appPath = m_applicationPathArg.firstValue();
619 auto fallbackAppPath = string();
624 const char *
const testAppPath = m_parser.executable();
625 const auto testAppPathLength = strlen(testAppPath);
626 if (testAppPathLength > 6 && !strcmp(testAppPath + testAppPathLength - 6,
"_tests")) {
627 fallbackAppPath.assign(testAppPath, testAppPathLength - 6);
628 appPath = fallbackAppPath.data();
631 throw runtime_error(
"Unable to execute application to be tested: no application path specified");
636 const auto newProfilingPath = [
appPath] {
637 auto path = string();
638 const char *
const llvmProfileFile = getenv(
"LLVM_PROFILE_FILE");
639 if (!llvmProfileFile) {
643 const char *
const llvmProfileFileEnd = strstr(llvmProfileFile,
".profraw");
644 if (!llvmProfileFileEnd) {
647 const auto llvmProfileFileWithoutExtension = string(llvmProfileFile, llvmProfileFileEnd);
649 const char *appName = strrchr(
appPath,
'/');
650 appName = appName ? appName + 1 :
appPath;
652 path =
argsToString(llvmProfileFileWithoutExtension,
'_', appName, invocationCount,
".profraw");
654 if (
const char *
const profrawListFile = getenv(
"LLVM_PROFILE_LIST_FILE")) {
655 ofstream(profrawListFile, ios_base::app) << path << endl;
660 return execAppInternal(
appPath, args, output, errors, suppressLogging, timeout, newProfilingPath);
669int execHelperApp(
const char *appPath,
const char *
const *args, std::string &output, std::string &errors,
bool suppressLogging,
int timeout)
671 return execAppInternal(appPath, args, output, errors, suppressLogging, timeout,
string());
683int execHelperAppInSearchPath(
684 const char *appName,
const char *
const *args, std::string &output, std::string &errors,
bool suppressLogging,
int timeout)
686 return execAppInternal(appName, args, output, errors, suppressLogging, timeout,
string(),
true);
693string TestApplication::readTestfilePathFromEnv()
695 const char *
const testFilesPathEnv = getenv(
"TEST_FILE_PATH");
696 if (!testFilesPathEnv || !*testFilesPathEnv) {
707std::vector<std::string> TestApplication::readTestfilePathFromSrcRef()
711 auto res = std::vector<std::string>();
712 auto binaryPath = std::string();
713#if defined(CPP_UTILITIES_USE_STANDARD_FILESYSTEM) && defined(PLATFORM_UNIX)
715 binaryPath = std::filesystem::read_symlink(
"/proc/self/exe").parent_path();
716 }
catch (
const std::filesystem::filesystem_error &e) {
717 cerr << Phrases::Warning <<
"Unable to detect binary path for finding \"srcdirref\": " << e.what() << Phrases::EndFlush;
719#elif defined(CPP_UTILITIES_USE_STANDARD_FILESYSTEM) && defined(PLATFORM_WINDOWS)
720 auto binaryPathBuffer = std::vector<wchar_t>();
721 auto copied = DWORD();
723 binaryPathBuffer.resize(binaryPathBuffer.size() + MAX_PATH);
724 copied = GetModuleFileNameW(0, binaryPathBuffer.data(),
static_cast<DWORD
>(binaryPathBuffer.size()));
725 }
while (copied >= binaryPathBuffer.size());
726 binaryPath = std::filesystem::path(binaryPathBuffer.begin(), binaryPathBuffer.begin() + copied, std::filesystem::path::native_format)
730 const auto srcdirrefPath = binaryPath.empty() ?
"srcdirref" : binaryPath +
"/srcdirref";
733 const auto srcDirContent =
readFile(srcdirrefPath, 1024 * 1024);
734 if (srcDirContent.empty()) {
735 cerr << Phrases::Warning <<
"The file \"srcdirref\" is empty." << Phrases::EndFlush;
741 for (
const auto &srcPath : srcPaths) {
742 auto testfilesPath =
argsToString(srcPath,
"/testfiles/");
743 if (dirExists(testfilesPath)) {
744 res.emplace_back(std::move(testfilesPath));
746 cerr << Phrases::Warning
747 <<
"The source directory referenced by the file \"srcdirref\" does not contain a \"testfiles\" directory or does not exist."
748 << Phrases::End <<
"Referenced source directory: " << testfilesPath << endl;
753 }
catch (
const std::ios_base::failure &e) {
754 cerr << Phrases::Warning <<
"The file \"" << srcdirrefPath <<
"\" can not be opened: " << e.what() << Phrases::EndFlush;
static constexpr std::size_t varValueCount
Denotes a variable number of values.
The ParseError class is thrown by an ArgumentParser when a parsing error occurs.
The TestApplication class simplifies writing test applications that require opening test files.
std::string workingCopyPath(const std::string &relativeTestFilePath, WorkingCopyMode mode=WorkingCopyMode::CreateCopy) const
Returns the full path to a working copy of the test file with the specified relativeTestFilePath.
std::string testFilePath(const std::string &relativeTestFilePath) const
Returns the full path of the test file with the specified relativeTestFilePath.
static const char * appPath()
Returns the application path or an empty string if no application path has been set.
TestApplication()
Constructs a TestApplication instance without further arguments.
std::string workingCopyPathAs(const std::string &relativeTestFilePath, const std::string &relativeWorkingCopyPath, WorkingCopyMode mode=WorkingCopyMode::CreateCopy) const
Returns the full path to a working copy of the test file with the specified relativeTestFilePath.
std::string testDirPath(const std::string &relativeTestDirPath) const
Returns the full path of the test directory with the specified relativeTestDirPath.
~TestApplication()
Destroys the TestApplication.
Encapsulates functions for formatted terminal output using ANSI escape codes.
Contains all utilities provided by the c++utilities library.
CPP_UTILITIES_EXPORT std::string readFile(const std::string &path, std::string::size_type maxSize=std::string::npos)
Reads all contents of the specified file in a single call.
WorkingCopyMode
The WorkingCopyMode enum specifies additional options to influence behavior of TestApplication::worki...
ReturnType joinStrings(const Container &strings, Detail::StringParamForContainer< Container > delimiter=Detail::StringParamForContainer< Container >(), bool omitEmpty=false, Detail::StringParamForContainer< Container > leftClosure=Detail::StringParamForContainer< Container >(), Detail::StringParamForContainer< Container > rightClosure=Detail::StringParamForContainer< Container >())
Joins the given strings using the specified delimiter.
std::fstream NativeFileStream
Container splitStringSimple(Detail::StringParamForContainer< Container > string, Detail::StringParamForContainer< Container > delimiter, int maxParts=-1)
Splits the given string (which might also be a string view) at the specified delimiter.
StringType argsToString(Args &&...args)
Container splitString(Detail::StringParamForContainer< Container > string, Detail::StringParamForContainer< Container > delimiter, EmptyPartsTreat emptyPartsRole=EmptyPartsTreat::Keep, int maxParts=-1)
Splits the given string at the specified delimiter.