Fix IsolatedConfig test (#5768)

* Fix IsolatedConfig test

The test was throwing import errors past the lifetime of the owning scoped_interpreter

* Clang format

* Clang tidy
This commit is contained in:
b-pass
2025-07-27 01:17:37 -04:00
committed by GitHub
parent 7f5eea432e
commit 33533ff3f8

View File

@@ -198,17 +198,32 @@ TEST_CASE("Custom PyConfig") {
}
TEST_CASE("scoped_interpreter with PyConfig_InitIsolatedConfig and argv") {
std::vector<std::string> path;
for (auto p : py::module::import("sys").attr("path")) {
path.emplace_back(py::str(p));
}
py::finalize_interpreter();
{
PyConfig config;
PyConfig_InitIsolatedConfig(&config);
char *argv[] = {strdup("a.out")};
py::scoped_interpreter argv_scope{&config, 1, argv};
py::scoped_interpreter argv_scope{&config, 1, argv, true};
std::free(argv[0]);
auto module = py::module::import("test_interpreter");
auto py_widget = module.attr("DerivedWidget")("The question");
const auto &cpp_widget = py_widget.cast<const Widget &>();
REQUIRE(cpp_widget.argv0() == "a.out");
// Because this config is isolated, setting the path during init will not work, we have to
// set it manually. If we don't set it, then we can't import "test_interpreter"
for (auto &&p : path) {
py::list(py::module::import("sys").attr("path")).append(p);
}
try {
auto module = py::module::import("test_interpreter");
auto py_widget = module.attr("DerivedWidget")("The question");
const auto &cpp_widget = py_widget.cast<const Widget &>();
REQUIRE(cpp_widget.argv0() == "a.out");
} catch (py::error_already_set &e) {
// catch here so that the exception doesn't escape the interpreter that owns it
FAIL(e.what());
}
}
py::initialize_interpreter();
}