16#include <initializer_list>
21#ifdef CPP_UTILITIES_USE_STANDARD_FILESYSTEM
30#ifdef CPP_UTILITIES_BOOST_PROCESS
31#include <boost/asio/buffers_iterator.hpp>
32#include <boost/asio/io_context.hpp>
33#include <boost/asio/streambuf.hpp>
34#include <boost/process/async.hpp>
35#include <boost/process/child.hpp>
36#include <boost/process/env.hpp>
37#include <boost/process/environment.hpp>
38#include <boost/process/group.hpp>
39#include <boost/process/io.hpp>
40#include <boost/process/search_path.hpp>
43#ifdef PLATFORM_WINDOWS
56static bool fileSystemItemExists(
const string &path)
60 return stat(path.data(), &res) == 0;
62 const auto widePath(convertMultiByteToWide(path));
63 if (!widePath.first) {
66 const auto fileType(GetFileAttributesW(widePath.first.get()));
67 return fileType != INVALID_FILE_ATTRIBUTES;
71static bool fileExists(
const string &path)
75 return stat(path.data(), &res) == 0 && !S_ISDIR(res.st_mode);
77 const auto widePath(convertMultiByteToWide(path));
78 if (!widePath.first) {
81 const auto fileType(GetFileAttributesW(widePath.first.get()));
82 return (fileType != INVALID_FILE_ATTRIBUTES) && !(fileType & FILE_ATTRIBUTE_DIRECTORY) && !(fileType & FILE_ATTRIBUTE_DEVICE);
86static bool dirExists(
const string &path)
90 return stat(path.data(), &res) == 0 && S_ISDIR(res.st_mode);
92 const auto widePath(convertMultiByteToWide(path));
93 if (!widePath.first) {
96 const auto fileType(GetFileAttributesW(widePath.first.get()));
97 return (fileType != INVALID_FILE_ATTRIBUTES) && (fileType & FILE_ATTRIBUTE_DIRECTORY);
101static bool makeDir(
const string &path)
104 return mkdir(path.data(), S_IRWXU | S_IRWXG | S_IROTH | S_IXOTH) == 0;
106 const auto widePath(convertMultiByteToWide(path));
107 if (!widePath.first) {
110 return CreateDirectoryW(widePath.first.get(),
nullptr) || GetLastError() == ERROR_ALREADY_EXISTS;
139 : m_listArg(
"list",
'l',
"lists available test units")
140 , m_runArg(
"run",
'r',
"runs the tests")
141 , m_testFilesPathArg(
"test-files-path",
'p',
"specifies the path of the directory with test files", {
"path" })
142 , m_applicationPathArg(
"app-path",
'a',
"specifies the path of the application to be tested", {
"path" })
143 , m_workingDirArg(
"working-dir",
'w',
"specifies the directory to store working copies of test files", {
"path" })
144 , m_unitsArg(
"units",
'u',
"specifies the units to test; omit to test all units", {
"unit1",
"unit2",
"unit3" })
148 throw runtime_error(
"only one TestApplication instance allowed at a time");
157 m_runArg.setImplicit(
true);
158 m_runArg.setSubArguments({ &m_testFilesPathArg, &m_applicationPathArg, &m_workingDirArg, &m_unitsArg });
159 m_parser.setMainArguments({ &m_runArg, &m_listArg, &m_parser.noColorArg(), &m_parser.helpArg() });
171 if (m_parser.helpArg().isPresent()) {
178 if (m_testFilesPathArg.isPresent()) {
179 for (
const char *
const testFilesPath : m_testFilesPathArg.values()) {
180 if (*testFilesPath) {
181 m_testFilesPaths.emplace_back(
argsToString(testFilesPath,
'/'));
183 m_testFilesPaths.emplace_back(
"./");
188 bool hasTestFilePathFromEnv;
189 if (
auto testFilePathFromEnv = readTestfilePathFromEnv(); (hasTestFilePathFromEnv = !testFilePathFromEnv.empty())) {
190 m_testFilesPaths.emplace_back(std::move(testFilePathFromEnv));
193 if (
auto testFilePathFromSrcDirRef = readTestfilePathFromSrcRef(); !testFilePathFromSrcDirRef.empty()) {
194 m_testFilesPaths.insert(m_testFilesPaths.end(), std::make_move_iterator(testFilePathFromSrcDirRef.begin()),
195 std::make_move_iterator(testFilePathFromSrcDirRef.end()));
198 m_testFilesPaths.emplace_back(
"./testfiles/");
199 for (
const auto &testFilesPath : m_testFilesPaths) {
200 cerr << testFilesPath <<
'\n';
204 if (m_workingDirArg.isPresent()) {
205 if (*m_workingDirArg.values().front()) {
206 (m_workingDir = m_workingDirArg.values().front()) +=
'/';
210 }
else if (
const char *
const workingDirEnv = getenv(
"WORKING_DIR")) {
211 if (*workingDirEnv) {
215 if ((m_testFilesPathArg.isPresent() && !m_testFilesPathArg.values().empty()) || hasTestFilePathFromEnv) {
216 m_workingDir = m_testFilesPaths.front() +
"workingdir/";
218 m_workingDir =
"./testfiles/workingdir/";
221 cerr <<
"Directory used to store working copies:\n" << m_workingDir <<
'\n';
224 if (
const char *
const profrawListFile = getenv(
"LLVM_PROFILE_LIST_FILE")) {
225 ofstream(profrawListFile, ios_base::trunc);
236 s_instance =
nullptr;
254 for (
const auto &testFilesPath : m_testFilesPaths) {
255 if (fileExists(path = testFilesPath + relativeTestFilePath)) {
259 throw std::runtime_error(
"The test file \"" % relativeTestFilePath %
"\" can not be located. Was looking under:\n"
260 +
joinStrings(m_testFilesPaths,
"\n",
false,
" - ", relativeTestFilePath));
272 for (
const auto &testFilesPath : m_testFilesPaths) {
273 if (dirExists(path = testFilesPath + relativeTestDirPath)) {
277 throw std::runtime_error(
"The test directory \"" % relativeTestDirPath %
"\" can not be located. Was looking under:\n"
278 +
joinStrings(m_testFilesPaths,
"\n",
false,
" - ", relativeTestDirPath));
308 const std::string &relativeTestFilePath,
const std::string &relativeWorkingCopyPath,
WorkingCopyMode mode)
const
312 if (!dirExists(m_workingDir) && !makeDir(m_workingDir)) {
313 cerr << Phrases::Error <<
"Unable to create working copy for \"" << relativeTestFilePath <<
"\": can't create working directory \""
314 << m_workingDir <<
"\"." << Phrases::EndFlush;
320 if (!parts.empty()) {
323 currentLevel.reserve(m_workingDir.size() + relativeWorkingCopyPath.size() + 1);
324 currentLevel.assign(m_workingDir);
325 for (
auto i = parts.cbegin(), end = parts.end() - 1;
i != end; ++
i) {
326 if (currentLevel.back() !=
'/') {
332 if (dirExists(currentLevel) || makeDir(currentLevel)) {
336 cerr << Phrases::Error <<
"Unable to create working copy for \"" << relativeWorkingCopyPath <<
"\": can't create directory \""
337 << currentLevel <<
"\" (inside working directory)." << Phrases::EndFlush;
350 const auto error = std::strerror(errno);
351 cerr << Phrases::Error <<
"Unable to delete \"" <<
workingCopyPath <<
"\": " << error << Phrases::EndFlush;
359 const auto origFilePath =
testFilePath(relativeTestFilePath);
360 size_t workingCopyPathAttempt = 0;
362 origFile.open(origFilePath, ios_base::in | ios_base::binary);
363 if (origFile.fail()) {
364 cerr << Phrases::Error <<
"Unable to create working copy for \"" << relativeTestFilePath
365 <<
"\": an IO error occurred when opening original file \"" << origFilePath <<
"\"." << Phrases::EndFlush;
366 cerr <<
"error: " << std::strerror(errno) << endl;
370 workingCopy.open(
workingCopyPath, ios_base::out | ios_base::binary | ios_base::trunc);
375 workingCopy.open(
workingCopyPath, ios_base::out | ios_base::binary | ios_base::trunc);
377 if (workingCopy.fail()) {
378 cerr << Phrases::Error <<
"Unable to create working copy for \"" << relativeTestFilePath
379 <<
"\": an IO error occurred when opening target file \"" <<
workingCopyPath <<
"\"." << Phrases::EndFlush;
380 cerr <<
"error: " << strerror(errno) << endl;
384 workingCopy << origFile.rdbuf();
386 if (!origFile.fail() && !workingCopy.fail()) {
390 cerr << Phrases::Error <<
"Unable to create working copy for \"" << relativeTestFilePath <<
"\": ";
391 if (origFile.fail()) {
392 cerr <<
"an IO error occurred when reading original file \"" << origFilePath <<
"\"";
396 if (workingCopy.fail()) {
397 if (origFile.fail()) {
400 cerr <<
" an IO error occurred when writing to target file \"" <<
workingCopyPath <<
"\".";
402 cerr <<
"error: " << strerror(errno) << endl;
407#ifdef CPP_UTILITIES_HAS_EXEC_APP
409#if defined(CPP_UTILITIES_BOOST_PROCESS)
410inline static std::string streambufToString(boost::asio::streambuf &buf)
412 const auto begin = boost::asio::buffers_begin(buf.data());
413 return std::string(begin, begin +
static_cast<std::ptrdiff_t
>(buf.size()));
421static int execAppInternal(
const char *appPath,
const char *
const *args, std::string &output, std::string &errors,
bool suppressLogging,
int timeout,
422 const std::string &newProfilingPath,
bool enableSearchPath =
false)
425 if (!suppressLogging) {
427 cout <<
'-' <<
' ' << appPath;
429 for (
const char *
const *
i = args + 1; *
i; ++
i) {
436#if defined(CPP_UTILITIES_BOOST_PROCESS)
437 auto path = enableSearchPath ? boost::process::search_path(appPath) : boost::process::filesystem::path(appPath);
438 auto ctx = boost::asio::io_context();
439 auto group = boost::process::group();
441#if defined(PLATFORM_WINDOWS)
442 std::vector<std::wstring>();
444 std::vector<std::string>();
447 for (
const char *
const *arg = args + 1; *arg; ++arg) {
448#if defined(PLATFORM_WINDOWS)
449 auto ec = std::error_code();
450 argsAsVector.emplace_back(convertMultiByteToWide(ec, std::string_view(*arg)));
452 throw std::runtime_error(
argsToString(
"unable to convert arg \"", *arg,
"\" to wide string"));
455 argsAsVector.emplace_back(*arg);
459 auto outputBuffer = boost::asio::streambuf(), errorBuffer = boost::asio::streambuf();
460 auto env = boost::process::environment(boost::this_process::environment());
461 if (!newProfilingPath.empty()) {
462 env[
"LLVM_PROFILE_FILE"] = newProfilingPath;
465 = boost::process::child(ctx, group, path, argsAsVector, env, boost::process::std_out > outputBuffer, boost::process::std_err > errorBuffer);
467 ctx.run_for(std::chrono::milliseconds(timeout));
471 output = streambufToString(outputBuffer);
472 errors = streambufToString(errorBuffer);
475 return child.exit_code();
477#elif defined(PLATFORM_UNIX)
479 int coutPipes[2], cerrPipes[2];
482 const auto readCoutPipe = coutPipes[0], writeCoutPipe = coutPipes[1];
483 const auto readCerrPipe = cerrPipes[0], writeCerrPipe = cerrPipes[1];
486 if (
const auto child = fork()) {
488 close(writeCoutPipe);
489 close(writeCerrPipe);
493 throw runtime_error(
"Unable to create fork");
497 struct pollfd fileDescriptorSet[2];
498 fileDescriptorSet[0].fd = readCoutPipe;
499 fileDescriptorSet[1].fd = readCerrPipe;
500 fileDescriptorSet[0].events = fileDescriptorSet[1].events = POLLIN;
509 const auto retpoll = poll(fileDescriptorSet, 2, timeout);
511 throw runtime_error(
"Poll time-out");
514 throw runtime_error(
"Poll failed");
516 if (fileDescriptorSet[0].revents & POLLIN) {
517 const auto count = read(readCoutPipe, buffer,
sizeof(buffer));
519 output.append(buffer,
static_cast<size_t>(count));
521 }
else if (fileDescriptorSet[0].revents & POLLHUP) {
523 fileDescriptorSet[0].fd = -1;
525 if (fileDescriptorSet[1].revents & POLLIN) {
526 const auto count = read(readCerrPipe, buffer,
sizeof(buffer));
528 errors.append(buffer,
static_cast<size_t>(count));
530 }
else if (fileDescriptorSet[1].revents & POLLHUP) {
532 fileDescriptorSet[1].fd = -1;
534 }
while (fileDescriptorSet[0].fd >= 0 || fileDescriptorSet[1].fd >= 0);
544 waitpid(child, &childReturnCode, 0);
545 waitpid(-child,
nullptr, 0);
546 return childReturnCode;
550 dup2(writeCoutPipe, STDOUT_FILENO);
551 dup2(writeCerrPipe, STDERR_FILENO);
553 close(writeCoutPipe);
555 close(writeCerrPipe);
559 cerr << Phrases::Error <<
"Unable create process group: " << std::strerror(errno) << Phrases::EndFlush;
564 if (!newProfilingPath.empty()) {
565 setenv(
"LLVM_PROFILE_FILE", newProfilingPath.data(),
true);
569 if (enableSearchPath) {
570 execvp(appPath,
const_cast<char *
const *
>(args));
572 execv(appPath,
const_cast<char *
const *
>(args));
574 cerr << Phrases::Error <<
"Unable to execute \"" << appPath <<
"\": " << std::strerror(errno) << Phrases::EndFlush;
579 throw std::runtime_error(
"lauching test applications is not supported on this platform");
591int TestApplication::execApp(
const char *
const *args,
string &output,
string &errors,
bool suppressLogging,
int timeout)
const
594 static unsigned int invocationCount = 0;
599 auto fallbackAppPath = string();
604 const char *
const testAppPath = m_parser.
executable();
605 const auto testAppPathLength = strlen(testAppPath);
606 if (testAppPathLength > 6 && !strcmp(testAppPath + testAppPathLength - 6,
"_tests")) {
607 fallbackAppPath.assign(testAppPath, testAppPathLength - 6);
608 appPath = fallbackAppPath.data();
611 throw runtime_error(
"Unable to execute application to be tested: no application path specified");
616 const auto newProfilingPath = [
appPath] {
617 auto path = string();
618 const char *
const llvmProfileFile = getenv(
"LLVM_PROFILE_FILE");
619 if (!llvmProfileFile) {
623 const char *
const llvmProfileFileEnd = strstr(llvmProfileFile,
".profraw");
624 if (!llvmProfileFileEnd) {
627 const auto llvmProfileFileWithoutExtension = string(llvmProfileFile, llvmProfileFileEnd);
629 const char *appName = strrchr(
appPath,
'/');
630 appName = appName ? appName + 1 :
appPath;
632 path =
argsToString(llvmProfileFileWithoutExtension,
'_', appName, invocationCount,
".profraw");
634 if (
const char *
const profrawListFile = getenv(
"LLVM_PROFILE_LIST_FILE")) {
635 ofstream(profrawListFile, ios_base::app) << path << endl;
640 return execAppInternal(
appPath, args, output, errors, suppressLogging, timeout, newProfilingPath);
649int execHelperApp(
const char *appPath,
const char *
const *args, std::string &output, std::string &errors,
bool suppressLogging,
int timeout)
651 return execAppInternal(appPath, args, output, errors, suppressLogging, timeout,
string());
663int execHelperAppInSearchPath(
664 const char *appName,
const char *
const *args, std::string &output, std::string &errors,
bool suppressLogging,
int timeout)
666 return execAppInternal(appName, args, output, errors, suppressLogging, timeout,
string(),
true);
673string TestApplication::readTestfilePathFromEnv()
675 const char *
const testFilesPathEnv = getenv(
"TEST_FILE_PATH");
676 if (!testFilesPathEnv || !*testFilesPathEnv) {
687std::vector<std::string> TestApplication::readTestfilePathFromSrcRef()
691 auto res = std::vector<std::string>();
692 auto binaryPath = std::string();
693#if defined(CPP_UTILITIES_USE_STANDARD_FILESYSTEM) && defined(PLATFORM_UNIX)
695 binaryPath = std::filesystem::read_symlink(
"/proc/self/exe").parent_path();
697 }
catch (
const std::filesystem::filesystem_error &e) {
698 cerr << Phrases::Warning <<
"Unable to detect binary path for finding \"srcdirref\": " << e.what() << Phrases::EndFlush;
701 const auto srcdirrefPath = binaryPath +
"srcdirref";
704 const auto srcDirContent =
readFile(srcdirrefPath, 2 * 1024);
705 if (srcDirContent.empty()) {
706 cerr << Phrases::Warning <<
"The file \"srcdirref\" is empty." << Phrases::EndFlush;
712 for (
const auto &srcPath : srcPaths) {
713 auto testfilesPath =
argsToString(srcPath,
"/testfiles/");
714 if (dirExists(testfilesPath)) {
715 res.emplace_back(std::move(testfilesPath));
717 cerr << Phrases::Warning
718 <<
"The source directory referenced by the file \"srcdirref\" does not contain a \"testfiles\" directory or does not exist."
719 << Phrases::End <<
"Referenced source directory: " << testfilesPath << endl;
724 }
catch (
const std::ios_base::failure &e) {
725 cerr << Phrases::Warning <<
"The file \"" << srcdirrefPath <<
"\" can not be opened: " << e.what() << Phrases::EndFlush;
const char * executable() const
Returns the name of the current executable.
static constexpr std::size_t varValueCount
Denotes a variable number of values.
const char * firstValue() const
Returns the first parameter value of the first occurrence of the argument.
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 provides 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.