Skip to content
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

Support PYTHONSAFEPATH #1700

Open
wants to merge 19 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from 3 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
5 changes: 4 additions & 1 deletion coverage/execfile.py
Original file line number Diff line number Diff line change
Expand Up @@ -90,7 +90,10 @@ def prepare(self) -> None:
This needs to happen before any importing, and without importing anything.
"""
path0: Optional[str]
if self.as_module:
if os.environ.get('PYTHONSAFEPATH', ''):
flying-sheep marked this conversation as resolved.
Show resolved Hide resolved
# See https://docs.python.org/3/using/cmdline.html#cmdoption-P
path0 = None
elif self.as_module:
path0 = os.getcwd()
elif os.path.isdir(self.arg0):
# Running a directory means running the __main__.py file in that
Expand Down
12 changes: 11 additions & 1 deletion tests/test_execfile.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@
import py_compile
import re
import sys

from unittest import mock
flying-sheep marked this conversation as resolved.
Show resolved Hide resolved
from typing import Any, Iterator

import pytest
Expand All @@ -23,6 +23,7 @@
from coverage.files import python_reported_file

from tests.coveragetest import CoverageTest, TESTS_DIR, UsingModulesMixin
from tests.helpers import change_dir

TRY_EXECFILE = os.path.join(TESTS_DIR, "modules/process_test/try_execfile.py")

Expand Down Expand Up @@ -306,6 +307,15 @@ def test_pkg1_init(self) -> None:
assert out == "pkg1.__init__: pkg1\npkg1.__init__: __main__\n"
assert err == ""

def test_pythonpath(self, tmp_path) -> None:
flying-sheep marked this conversation as resolved.
Show resolved Hide resolved
env = {"PYTHONSAFEPATH": "1"}
with mock.patch.dict(os.environ, env), change_dir(tmp_path):
flying-sheep marked this conversation as resolved.
Show resolved Hide resolved
run_python_module(["process_test.try_execfile"])
out, err = self.stdouterr()
mod_globs = json.loads(out)
assert tmp_path not in mod_globs["path"]
assert err == ""

def test_no_such_module(self) -> None:
with pytest.raises(NoSource, match="No module named '?i_dont_exist'?"):
run_python_module(["i_dont_exist"])
Expand Down
Loading