Thanks to visit codestin.com
Credit goes to github.com

Skip to content

Commit 1f40564

Browse files
authored
TestPythonEngineProperties.SetPythonPath avoids corrupting the module search path for later tests (#1336)
SetPythonPath uses System.IO.Path.PathSeparator and imports a module under the new path
1 parent a0d1a3d commit 1f40564

File tree

1 file changed

+25
-1
lines changed

1 file changed

+25
-1
lines changed

src/embed_tests/TestPythonEngineProperties.cs

Lines changed: 25 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -181,13 +181,37 @@ public void SetProgramName()
181181
public void SetPythonPath()
182182
{
183183
PythonEngine.Initialize();
184-
string path = PythonEngine.PythonPath;
184+
185+
const string moduleName = "pytest";
186+
bool importShouldSucceed;
187+
try
188+
{
189+
Py.Import(moduleName);
190+
importShouldSucceed = true;
191+
}
192+
catch
193+
{
194+
importShouldSucceed = false;
195+
}
196+
197+
string[] paths = Py.Import("sys").GetAttr("path").As<string[]>();
198+
string path = string.Join(System.IO.Path.PathSeparator.ToString(), paths);
199+
200+
// path should not be set to PythonEngine.PythonPath here.
201+
// PythonEngine.PythonPath gets the default module search path, not the full search path.
202+
// The list sys.path is initialized with this value on interpreter startup;
203+
// it can be (and usually is) modified later to change the search path for loading modules.
204+
// See https://docs.python.org/3/c-api/init.html#c.Py_GetPath
205+
// After PythonPath is set, then PythonEngine.PythonPath will correctly return the full search path.
206+
185207
PythonEngine.Shutdown();
186208

187209
PythonEngine.PythonPath = path;
188210
PythonEngine.Initialize();
189211

190212
Assert.AreEqual(path, PythonEngine.PythonPath);
213+
if (importShouldSucceed) Py.Import(moduleName);
214+
191215
PythonEngine.Shutdown();
192216
}
193217
}

0 commit comments

Comments
 (0)