From 33533ff3f8b032fbeccc2ed964207e556702e992 Mon Sep 17 00:00:00 2001 From: b-pass Date: Sun, 27 Jul 2025 01:17:37 -0400 Subject: [PATCH] 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 --- tests/test_embed/test_interpreter.cpp | 25 ++++++++++++++++++++----- 1 file changed, 20 insertions(+), 5 deletions(-) diff --git a/tests/test_embed/test_interpreter.cpp b/tests/test_embed/test_interpreter.cpp index bd50eaf1f..0e6c17a77 100644 --- a/tests/test_embed/test_interpreter.cpp +++ b/tests/test_embed/test_interpreter.cpp @@ -198,17 +198,32 @@ TEST_CASE("Custom PyConfig") { } TEST_CASE("scoped_interpreter with PyConfig_InitIsolatedConfig and argv") { + std::vector 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(); - 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(); + 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(); }