Files
carbon-lang/testing/base/file_helpers.h
T
Richard SmithandJon Ross-Perkins 66caff2c26 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>
2025-05-07 22:28:13 +00:00

42 lines
1.5 KiB
C++

// Part of the Carbon Language project, under the Apache License v2.0 with LLVM
// Exceptions. See /LICENSE for license information.
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
#ifndef CARBON_TESTING_BASE_FILE_HELPERS_H_
#define CARBON_TESTING_BASE_FILE_HELPERS_H_
#include <filesystem>
#include <string>
#include "common/error.h"
namespace Carbon::Testing {
// Returns a directory that should be used to hold temporary files created by
// test execution.
auto GetTempDirectory() -> std::filesystem::path;
// Reads a file to string.
auto ReadFile(std::filesystem::path path) -> ErrorOr<std::string>;
// Writes a test file to disk and returns an error or the full path to the file.
//
// Note that this expects to be run from within a GoogleTest test, and relies on
// global state of GoogleTest.
//
// This locates a suitable temporary directory for the test, creates a file with
// the requested name in that directory, and writes the provided content to that
// file. The full path to the written file is returned.
//
// Where possible, this will use a Bazel-provided test temporary directory.
// However, if unavailable, it falls back to a system temporary directory. This
// helps tests be runnable outside of Bazel, for example under a debugger. It
// also works to create test file names that are unlikely to conflict with other
// tests when run.
auto WriteTestFile(llvm::StringRef name, llvm::StringRef contents)
-> ErrorOr<std::filesystem::path>;
} // namespace Carbon::Testing
#endif // CARBON_TESTING_BASE_FILE_HELPERS_H_