Stack Exchange
How to write to a file in a googletest test case with bazel test?
I have a simple Bazel C++ project with the following directory layout:
├── BUILD
├── WORKSPACE
├── file_test.cc

WORKSPACE:
load("@bazel_tools//tools/build_defs/repo:http.bzl", "http_archive")

http_archive(
  name = "gtest",
  url = "https://github.com/google/googletest/archive/release-1.10.0.tar.gz",
  sha256 = "9dc9157a9a1551ec7a7e43daea9a694a0bb5fb8bec81235d8a1e6ef64c716dcb",
  strip_prefix = "googletest-release-1.10.0",
)

BUILD:
cc_test(
  name = "file_test",
  srcs = ["file_test.cc"],
  deps = [
    "@gtest//:gtest",
    "@gtest//:gtest_main",
  ],
)

file_test.cc:
#include <iostream>
#include <fstream>

#include "gtest/gtest.h"

using namespace std;

TEST(File, Write) {
  cout << "Running..." << endl;
  ofstream out("foo", ios_base::app);
  out << "Go\n";
}

After running bazelisk test, foo is not created in the current working directory.
$ bazelisk test :file_test --test_output=all --cache_test_results=no
$ cat foo
cat: foo: No such file or directory

However, after running the built result, foo is created with the expected content.
$ bazel-bin/file_test
$ cat foo
Go

I am using the following Bazel through Bazelisk macOS 10.15.5.
$ bazelisk version
Bazelisk version: v1.7.5
Build label: 4.1.0
Build target: bazel-out/darwin-opt/bin/src/main/java/com/google/devtools/build/lib/bazel/BazelServer_deploy.jar
Build time: Fri May 21 11:16:55 2021 (1621595815)
Build timestamp: 1621595815
Build timestamp as int: 1621595815

It seems that Bazel Sandboxing is the cause of file creation failure.
Is there a way to write the foo file with bazel test? Or if foo is created elsewhere, where can I find it?

It is not possible to do it with bazel test, because tests have to be hermetic. But you can use a test target to generate files using bazel run, see example from python rules: there is a env variable check, which dispatch different actions based on invocation type

Your file should be in the folder that is outputted by bazel info bazel-bin. There should be a folder named CC_TEST_TARGET_NAME.runfiles. This folder should reflect our workspace structure.
foo fill never be created in your current source working directory. Tests run always "hermetic" and are restricted in the access to the filesystem.
BTW: copts = ["-Iexternal/gtest/include"] is not needed

Remove copts as you suggested. But CC_TEST_TARGET_NAME.runfiles does not contain the foo file.

Add ---sandbox_debug option when running bazelisk test.
After Bazel terimnates, use bazelisk info to get output_base. Then use find ${output_base} -name foo can find the file.
