15#include <initializer_list>
19#ifdef CPP_UTILITIES_USE_STANDARD_FILESYSTEM
28#ifdef CPP_UTILITIES_BOOST_PROCESS
29#include <boost/asio/buffers_iterator.hpp>
30#include <boost/asio/io_context.hpp>
31#include <boost/asio/streambuf.hpp>
32#if BOOST_VERSION >= 108600
33#include <boost/process/v1/async.hpp>
34#include <boost/process/v1/child.hpp>
35#include <boost/process/v1/env.hpp>
36#include <boost/process/v1/environment.hpp>
37#include <boost/process/v1/group.hpp>
38#include <boost/process/v1/io.hpp>
39#include <boost/process/v1/search_path.hpp>
41#include <boost/process/async.hpp>
42#include <boost/process/child.hpp>
43#include <boost/process/env.hpp>
44#include <boost/process/environment.hpp>
45#include <boost/process/group.hpp>
46#include <boost/process/io.hpp>
47#include <boost/process/search_path.hpp>
48namespace boost::process {
49namespace v1 = boost::process;
54#ifdef PLATFORM_WINDOWS
67static bool fileSystemItemExists(
const string &path)
71 return stat(path.data(), &res) == 0;
73 const auto widePath(convertMultiByteToWide(path));
74 if (!widePath.first) {
77 const auto fileType(GetFileAttributesW(widePath.first.get()));
78 return fileType != INVALID_FILE_ATTRIBUTES;
82static bool fileExists(
const string &path)
86 return stat(path.data(), &res) == 0 && !S_ISDIR(res.st_mode);
88 const auto widePath(convertMultiByteToWide(path));
89 if (!widePath.first) {
92 const auto fileType(GetFileAttributesW(widePath.first.get()));
93 return (fileType != INVALID_FILE_ATTRIBUTES) && !(fileType & FILE_ATTRIBUTE_DIRECTORY) && !(fileType & FILE_ATTRIBUTE_DEVICE);
97static bool dirExists(
const string &path)
101 return stat(path.data(), &res) == 0 && S_ISDIR(res.st_mode);
103 const auto widePath(convertMultiByteToWide(path));
104 if (!widePath.first) {
107 const auto fileType(GetFileAttributesW(widePath.first.get()));
108 return (fileType != INVALID_FILE_ATTRIBUTES) && (fileType & FILE_ATTRIBUTE_DIRECTORY);
112static bool makeDir(
const string &path)
115 return mkdir(path.data(), S_IRWXU | S_IRWXG | S_IROTH | S_IXOTH) == 0;
117 const auto widePath(convertMultiByteToWide(path));
118 if (!widePath.first) {
121 return CreateDirectoryW(widePath.first.get(),
nullptr) || GetLastError() == ERROR_ALREADY_EXISTS;
150 : m_listArg(
"list",
'l',
"lists available test units")
151 , m_runArg(
"run",
'r',
"runs the tests")
152 , m_testFilesPathArg(
"test-files-path",
'p',
"specifies the path of the directory with test files", {
"path" })
153 , m_applicationPathArg(
"app-path",
'a',
"specifies the path of the application to be tested", {
"path" })
154 , m_workingDirArg(
"working-dir",
'w',
"specifies the directory to store working copies of test files", {
"path" })
155 , m_unitsArg(
"units",
'u',
"specifies the units to test; omit to test all units", {
"unit1",
"unit2",
"unit3" })
159 throw runtime_error(
"only one TestApplication instance allowed at a time");
168 m_runArg.setImplicit(
true);
169 m_runArg.setSubArguments({ &m_testFilesPathArg, &m_applicationPathArg, &m_workingDirArg, &m_unitsArg });
170 m_parser.setMainArguments({ &m_runArg, &m_listArg, &m_parser.noColorArg(), &m_parser.helpArg() });
182 if (m_parser.helpArg().isPresent()) {
189 if (m_testFilesPathArg.isPresent()) {
190 for (
const char *
const testFilesPath : m_testFilesPathArg.values()) {
191 if (*testFilesPath) {
192 m_testFilesPaths.emplace_back(
argsToString(testFilesPath,
'/'));
194 m_testFilesPaths.emplace_back(
"./");
199 bool hasTestFilePathFromEnv;
200 if (
auto testFilePathFromEnv = readTestfilePathFromEnv(); (hasTestFilePathFromEnv = !testFilePathFromEnv.empty())) {
201 m_testFilesPaths.emplace_back(std::move(testFilePathFromEnv));
204 if (
auto testFilePathFromSrcDirRef = readTestfilePathFromSrcRef(); !testFilePathFromSrcDirRef.empty()) {
205 m_testFilesPaths.insert(m_testFilesPaths.end(), std::make_move_iterator(testFilePathFromSrcDirRef.begin()),
206 std::make_move_iterator(testFilePathFromSrcDirRef.end()));
209 m_testFilesPaths.emplace_back(
"./testfiles/");
210 for (
const auto &testFilesPath : m_testFilesPaths) {
211 cerr << testFilesPath <<
'\n';
215 if (m_workingDirArg.isPresent()) {
216 if (*m_workingDirArg.values().front()) {
217 (m_workingDir = m_workingDirArg.values().front()) +=
'/';
221 }
else if (
const char *
const workingDirEnv = getenv(
"WORKING_DIR")) {
222 if (*workingDirEnv) {
226 if ((m_testFilesPathArg.isPresent() && !m_testFilesPathArg.values().empty()) || hasTestFilePathFromEnv) {
227 m_workingDir = m_testFilesPaths.front() +
"workingdir/";
229 m_workingDir =
"./testfiles/workingdir/";
232 cerr <<
"Directory used to store working copies:\n" << m_workingDir <<
'\n';
235 if (
const char *
const profrawListFile = getenv(
"LLVM_PROFILE_LIST_FILE")) {
236 ofstream(profrawListFile, ios_base::trunc);
247 s_instance =
nullptr;
265 for (
const auto &testFilesPath : m_testFilesPaths) {
266 if (fileExists(path = testFilesPath + relativeTestFilePath)) {
270 throw std::runtime_error(
"The test file \"" % relativeTestFilePath %
"\" can not be located. Was looking under:\n"
271 +
joinStrings(m_testFilesPaths,
"\n",
false,
" - ", relativeTestFilePath));
283 for (
const auto &testFilesPath : m_testFilesPaths) {
284 if (dirExists(path = testFilesPath + relativeTestDirPath)) {
288 throw std::runtime_error(
"The test directory \"" % relativeTestDirPath %
"\" can not be located. Was looking under:\n"
289 +
joinStrings(m_testFilesPaths,
"\n",
false,
" - ", relativeTestDirPath));
319 const std::string &relativeTestFilePath,
const std::string &relativeWorkingCopyPath,
WorkingCopyMode mode)
const
323 if (!dirExists(m_workingDir) && !makeDir(m_workingDir)) {
324 cerr <<
Phrases::Error <<
"Unable to create working copy for \"" << relativeTestFilePath <<
"\": can't create working directory \""
331 if (!parts.empty()) {
334 currentLevel.reserve(m_workingDir.size() + relativeWorkingCopyPath.size() + 1);
335 currentLevel.assign(m_workingDir);
336 for (
auto i = parts.cbegin(), end = parts.end() - 1;
i != end; ++
i) {
337 if (currentLevel.back() !=
'/') {
343 if (dirExists(currentLevel) || makeDir(currentLevel)) {
347 cerr <<
Phrases::Error <<
"Unable to create working copy for \"" << relativeWorkingCopyPath <<
"\": can't create directory \""
361 const auto error = std::strerror(errno);
370 const auto origFilePath =
testFilePath(relativeTestFilePath);
371 size_t workingCopyPathAttempt = 0;
373 origFile.open(origFilePath, ios_base::in | ios_base::binary);
374 if (origFile.fail()) {
375 cerr <<
Phrases::Error <<
"Unable to create working copy for \"" << relativeTestFilePath
376 <<
"\": an IO error occurred when opening original file \"" << origFilePath <<
"\"." <<
Phrases::EndFlush;
377 cerr <<
"error: " << std::strerror(errno) << endl;
381 workingCopy.open(
workingCopyPath, ios_base::out | ios_base::binary | ios_base::trunc);
386 workingCopy.open(
workingCopyPath, ios_base::out | ios_base::binary | ios_base::trunc);
388 if (workingCopy.fail()) {
389 cerr <<
Phrases::Error <<
"Unable to create working copy for \"" << relativeTestFilePath
391 cerr <<
"error: " << strerror(errno) << endl;
395 workingCopy << origFile.rdbuf();
397 if (!origFile.fail() && !workingCopy.fail()) {
401 cerr <<
Phrases::Error <<
"Unable to create working copy for \"" << relativeTestFilePath <<
"\": ";
402 if (origFile.fail()) {
403 cerr <<
"an IO error occurred when reading original file \"" << origFilePath <<
"\"";
407 if (workingCopy.fail()) {
408 if (origFile.fail()) {
411 cerr <<
" an IO error occurred when writing to target file \"" <<
workingCopyPath <<
"\".";
413 cerr <<
"error: " << strerror(errno) << endl;
418#ifdef CPP_UTILITIES_HAS_EXEC_APP
420#if defined(CPP_UTILITIES_BOOST_PROCESS)
421inline static std::string streambufToString(boost::asio::streambuf &buf)
423 const auto begin = boost::asio::buffers_begin(buf.data());
424 return std::string(begin, begin +
static_cast<std::ptrdiff_t
>(buf.size()));
432static int execAppInternal(
const char *appPath,
const char *
const *args, std::string &output, std::string &errors,
bool suppressLogging,
int timeout,
433 const std::string &newProfilingPath,
bool enableSearchPath =
false)
436 if (!suppressLogging) {
438 cout <<
'-' <<
' ' << appPath;
440 for (
const char *
const *
i = args + 1; *
i; ++
i) {
447#if defined(CPP_UTILITIES_BOOST_PROCESS)
448 auto path = enableSearchPath ? boost::process::v1::search_path(appPath) : boost::process::v1::filesystem::path(appPath);
449 auto ctx = boost::asio::io_context();
450 auto group = boost::process::v1::group();
452#if defined(PLATFORM_WINDOWS)
453 std::vector<std::wstring>();
455 std::vector<std::string>();
458 for (
const char *
const *arg = args + 1; *arg; ++arg) {
459#if defined(PLATFORM_WINDOWS)
460 auto ec = std::error_code();
461 argsAsVector.emplace_back(convertMultiByteToWide(ec, std::string_view(*arg)));
463 throw std::runtime_error(
argsToString(
"unable to convert arg \"", *arg,
"\" to wide string"));
466 argsAsVector.emplace_back(*arg);
470 auto outputBuffer = boost::asio::streambuf(), errorBuffer = boost::asio::streambuf();
471 auto env = boost::process::v1::environment(boost::this_process::environment());
472 if (!newProfilingPath.empty()) {
473 env[
"LLVM_PROFILE_FILE"] = newProfilingPath;
475 auto child = boost::process::v1::child(
476 ctx, group, path, argsAsVector, env, boost::process::v1::std_out > outputBuffer, boost::process::v1::std_err > errorBuffer);
478 ctx.run_for(std::chrono::milliseconds(timeout));
482 output = streambufToString(outputBuffer);
483 errors = streambufToString(errorBuffer);
486 return child.exit_code();
488#elif defined(PLATFORM_UNIX)
490 int coutPipes[2], cerrPipes[2];
491 if (pipe(coutPipes) != 0 || pipe(cerrPipes) != 0) {
492 throw std::runtime_error(
argsToString(
"Unable to create pipe: ", std::strerror(errno)));
494 const auto readCoutPipe = coutPipes[0], writeCoutPipe = coutPipes[1];
495 const auto readCerrPipe = cerrPipes[0], writeCerrPipe = cerrPipes[1];
498 if (
const auto child = fork()) {
500 close(writeCoutPipe);
501 close(writeCerrPipe);
505 throw std::runtime_error(
argsToString(
"Unable to create fork: ", std::strerror(errno)));
509 struct pollfd fileDescriptorSet[2];
510 fileDescriptorSet[0].fd = readCoutPipe;
511 fileDescriptorSet[1].fd = readCerrPipe;
512 fileDescriptorSet[0].events = fileDescriptorSet[1].events = POLLIN;
521 const auto retpoll = poll(fileDescriptorSet, 2, timeout);
523 throw std::runtime_error(
"Poll timed out");
526 throw std::runtime_error(
argsToString(
"Poll failed: ", std::strerror(errno)));
528 if (fileDescriptorSet[0].revents & POLLIN) {
529 const auto count = read(readCoutPipe, buffer,
sizeof(buffer));
531 output.append(buffer,
static_cast<size_t>(count));
533 }
else if (fileDescriptorSet[0].revents & POLLHUP) {
535 fileDescriptorSet[0].fd = -1;
537 if (fileDescriptorSet[1].revents & POLLIN) {
538 const auto count = read(readCerrPipe, buffer,
sizeof(buffer));
540 errors.append(buffer,
static_cast<size_t>(count));
542 }
else if (fileDescriptorSet[1].revents & POLLHUP) {
544 fileDescriptorSet[1].fd = -1;
546 }
while (fileDescriptorSet[0].fd >= 0 || fileDescriptorSet[1].fd >= 0);
556 waitpid(child, &childReturnCode, 0);
557 waitpid(-child,
nullptr, 0);
558 return childReturnCode;
562 if (dup2(writeCoutPipe, STDOUT_FILENO) == -1 || dup2(writeCerrPipe, STDERR_FILENO) == -1) {
563 std::cerr << Phrases::Error <<
"Unable to duplicate file descriptor: " << std::strerror(errno) << Phrases::EndFlush;
564 std::exit(EXIT_FAILURE);
567 close(writeCoutPipe);
569 close(writeCerrPipe);
573 cerr << Phrases::Error <<
"Unable create process group: " << std::strerror(errno) << Phrases::EndFlush;
578 if (!newProfilingPath.empty()) {
579 setenv(
"LLVM_PROFILE_FILE", newProfilingPath.data(),
true);
583 if (enableSearchPath) {
584 execvp(appPath,
const_cast<char *
const *
>(args));
586 execv(appPath,
const_cast<char *
const *
>(args));
588 cerr << Phrases::Error <<
"Unable to execute \"" << appPath <<
"\": " << std::strerror(errno) << Phrases::EndFlush;
593 throw std::runtime_error(
"lauching test applications is not supported on this platform");
605int TestApplication::execApp(
const char *
const *args,
string &output,
string &errors,
bool suppressLogging,
int timeout)
const
608 static unsigned int invocationCount = 0;
612 const char *
appPath = m_applicationPathArg.firstValue();
613 auto fallbackAppPath = string();
618 const char *
const testAppPath = m_parser.executable();
619 const auto testAppPathLength = strlen(testAppPath);
620 if (testAppPathLength > 6 && !strcmp(testAppPath + testAppPathLength - 6,
"_tests")) {
621 fallbackAppPath.assign(testAppPath, testAppPathLength - 6);
622 appPath = fallbackAppPath.data();
625 throw runtime_error(
"Unable to execute application to be tested: no application path specified");
630 const auto newProfilingPath = [
appPath] {
631 auto path = string();
632 const char *
const llvmProfileFile = getenv(
"LLVM_PROFILE_FILE");
633 if (!llvmProfileFile) {
637 const char *
const llvmProfileFileEnd = strstr(llvmProfileFile,
".profraw");
638 if (!llvmProfileFileEnd) {
641 const auto llvmProfileFileWithoutExtension = string(llvmProfileFile, llvmProfileFileEnd);
643 const char *appName = strrchr(
appPath,
'/');
644 appName = appName ? appName + 1 :
appPath;
646 path =
argsToString(llvmProfileFileWithoutExtension,
'_', appName, invocationCount,
".profraw");
648 if (
const char *
const profrawListFile = getenv(
"LLVM_PROFILE_LIST_FILE")) {
649 ofstream(profrawListFile, ios_base::app) << path << endl;
654 return execAppInternal(
appPath, args, output, errors, suppressLogging, timeout, newProfilingPath);
663int execHelperApp(
const char *appPath,
const char *
const *args, std::string &output, std::string &errors,
bool suppressLogging,
int timeout)
665 return execAppInternal(appPath, args, output, errors, suppressLogging, timeout,
string());
677int execHelperAppInSearchPath(
678 const char *appName,
const char *
const *args, std::string &output, std::string &errors,
bool suppressLogging,
int timeout)
680 return execAppInternal(appName, args, output, errors, suppressLogging, timeout,
string(),
true);
687string TestApplication::readTestfilePathFromEnv()
689 const char *
const testFilesPathEnv = getenv(
"TEST_FILE_PATH");
690 if (!testFilesPathEnv || !*testFilesPathEnv) {
701std::vector<std::string> TestApplication::readTestfilePathFromSrcRef()
705 auto res = std::vector<std::string>();
706 auto binaryPath = std::string();
707#if defined(CPP_UTILITIES_USE_STANDARD_FILESYSTEM) && defined(PLATFORM_UNIX)
709 binaryPath = std::filesystem::read_symlink(
"/proc/self/exe").parent_path();
711 }
catch (
const std::filesystem::filesystem_error &e) {
712 cerr << Phrases::Warning <<
"Unable to detect binary path for finding \"srcdirref\": " << e.what() << Phrases::EndFlush;
715 const auto srcdirrefPath = binaryPath +
"srcdirref";
718 const auto srcDirContent =
readFile(srcdirrefPath, 2 * 1024);
719 if (srcDirContent.empty()) {
720 cerr << Phrases::Warning <<
"The file \"srcdirref\" is empty." << Phrases::EndFlush;
726 for (
const auto &srcPath : srcPaths) {
727 auto testfilesPath =
argsToString(srcPath,
"/testfiles/");
728 if (dirExists(testfilesPath)) {
729 res.emplace_back(std::move(testfilesPath));
731 cerr << Phrases::Warning
732 <<
"The source directory referenced by the file \"srcdirref\" does not contain a \"testfiles\" directory or does not exist."
733 << Phrases::End <<
"Referenced source directory: " << testfilesPath << endl;
738 }
catch (
const std::ios_base::failure &e) {
739 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.