Skip to content

TestPythonEngineProperties.SetPythonPath avoids corrupting the module search path for later tests #1336

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 3 commits into from
Dec 22, 2020
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
26 changes: 25 additions & 1 deletion src/embed_tests/TestPythonEngineProperties.cs
Original file line number Diff line number Diff line change
Expand Up @@ -181,13 +181,37 @@ public void SetProgramName()
public void SetPythonPath()
{
PythonEngine.Initialize();
string path = PythonEngine.PythonPath;

const string moduleName = "pytest";
bool importShouldSucceed;
try
{
Py.Import(moduleName);
importShouldSucceed = true;
}
catch
{
importShouldSucceed = false;
}

string[] paths = Py.Import("sys").GetAttr("path").As<string[]>();
string path = string.Join(System.IO.Path.PathSeparator.ToString(), paths);

// path should not be set to PythonEngine.PythonPath here.
// PythonEngine.PythonPath gets the default module search path, not the full search path.
// The list sys.path is initialized with this value on interpreter startup;
// it can be (and usually is) modified later to change the search path for loading modules.
// See https://docs.python.org/3/c-api/init.html#c.Py_GetPath
// After PythonPath is set, then PythonEngine.PythonPath will correctly return the full search path.

PythonEngine.Shutdown();

PythonEngine.PythonPath = path;
PythonEngine.Initialize();

Assert.AreEqual(path, PythonEngine.PythonPath);
if (importShouldSucceed) Py.Import(moduleName);

PythonEngine.Shutdown();
}
}
Expand Down