Skip to content

TestPythonEngineProperties.SetPythonPath spoils later tests that load modules #1335

Description

@tminka

Environment

  • Pythonnet version: Latest master
  • Python version: 3.7.8
  • Operating System: Windows 10
  • .NET Runtime: Core 3.1

Details

  • Describe what you were trying to get done.

Add an embedded test that imports pytest.

Add the following test to TestTypeManager.cs (so that it runs last):

        [Test]
        public void PathTest()
        {
            Py.Import("pytest");
        }

Then run dotnet test --runtime any-x64 src/embed_tests

  • If there was a crash, please include the traceback here.
  Failed PathTest [20 ms]
  Error Message:
   Python.Runtime.PythonException : ImportError : No module named pytest

The reason for the failure is that an earlier test named TestPythonEngineProperties.SetPythonPath corrupts the Python import mechanism. Removing that test causes PathTest to pass. You can see the causal effect most clearly by adding Py.Import("pytest"); to the end of the SetPythonPath test, where it will fail.

As explained in the documentation for Py_SetPath, setting the Python path has the side effect of changing sys.executable, sys.prefix, and sys.exec_prefix. The import mechanism uses those variables to locate modules. You can confirm that these variables are being altered by making the following change to SetPythonPath:

        public void SetPythonPath()
        {
            PythonEngine.Initialize();

            dynamic sys = Py.Import("sys");
            Console.WriteLine(sys.executable);
            Console.WriteLine(sys.prefix);
            Console.WriteLine(sys.exec_prefix);

            string path = PythonEngine.PythonPath;
            PythonEngine.Shutdown();

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

            sys = Py.Import("sys");
            Console.WriteLine(sys.executable);
            Console.WriteLine(sys.prefix);
            Console.WriteLine(sys.exec_prefix);

            Assert.AreEqual(path, PythonEngine.PythonPath);
            PythonEngine.Shutdown();
        }

The SetPythonPath test should restore the original values of those variables.

Activity

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions