Make the file_test binary work without custom environment variables. (#5442)

Instead of crashing when run outside of `bazel`, make the toolchain's
`file_test` binary work properly when no test-specific environment
variables are set. This makes it a lot easier to run `file_test` under a
debugger.

There are two main changes here:

- Don't crash if `$TEST_TMPDIR` is unset. Instead, fall back to LLVM's
temporary directory (typically `$TMPDIR`). We already did this in some
places in tests. We now do it in more places.
- Don't fall back to a target label of `<target>` in the reproduction
commands if `$TEST_TARGET` is unset, because this causes all the tests
to fail because their output doesn't match the expected output due to a
differing bazel run command. Instead explicitly specify the target from
the `FileTestBase`-derived class.

Infrastructure for this has been added generally, but only rolled out to
the toolchain `file_test` binary for now.

---------

Co-authored-by: Jon Ross-Perkins <jperkins@google.com>
This commit is contained in:
Richard Smith
2025-05-07 22:28:13 +00:00
committed by GitHub
co-authored by Jon Ross-Perkins
parent f2a16d8742
commit 66caff2c26
9 changed files with 61 additions and 40 deletions
+9 -7
View File
@@ -14,6 +14,14 @@
namespace Carbon::Testing {
auto GetTempDirectory() -> std::filesystem::path {
if (char* tmpdir_env = getenv("TEST_TMPDIR"); tmpdir_env != nullptr) {
return tmpdir_env;
} else {
return std::filesystem::temp_directory_path();
}
}
auto ReadFile(std::filesystem::path path) -> ErrorOr<std::string> {
std::ifstream file_stream(path);
if (file_stream.fail()) {
@@ -29,13 +37,7 @@ auto ReadFile(std::filesystem::path path) -> ErrorOr<std::string> {
auto WriteTestFile(llvm::StringRef name, llvm::StringRef contents)
-> ErrorOr<std::filesystem::path> {
std::filesystem::path test_tmpdir;
if (char* tmpdir_env = getenv("TEST_TMPDIR"); tmpdir_env != nullptr) {
test_tmpdir = std::string(tmpdir_env);
} else {
test_tmpdir = std::filesystem::temp_directory_path();
}
std::filesystem::path test_tmpdir = GetTempDirectory();
const auto* unit_test = ::testing::UnitTest::GetInstance();
const auto* test_info = unit_test->current_test_info();
std::filesystem::path test_file =