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

Repair hermetic_environment_as for C-level environment variable access. #5898

Merged
merged 4 commits into from
Jun 1, 2018
Merged
Show file tree
Hide file tree
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
20 changes: 18 additions & 2 deletions src/python/pants/util/contextutil.py
Original file line number Diff line number Diff line change
Expand Up @@ -76,15 +76,31 @@ def setenv(key, val):
setenv(key, val)


def _purge_env():
# N.B. Without the use of `del` here (which calls `os.unsetenv` under the hood), subprocess32
# invokes or other things that may access the environment at the C level may not see the
# correct env vars (i.e. we can't just replace os.environ with an empty dict).
# See https://docs.python.org/2/library/os.html#os.unsetenv for more info.
for k in os.environ.keys():
del os.environ[k]


def _restore_env(env):
for k, v in env.items():
os.environ[k] = v


@contextmanager
def hermetic_environment_as(**kwargs):
"""Set the environment to the supplied values from an empty state."""
old_environment, os.environ = os.environ, {}
old_environment = os.environ.copy()
_purge_env()
try:
with environment_as(**kwargs):
yield
finally:
os.environ = old_environment
_purge_env()
_restore_env(old_environment)


@contextmanager
Expand Down
10 changes: 10 additions & 0 deletions tests/python/pants_test/util/test_contextutil.py
Original file line number Diff line number Diff line change
Expand Up @@ -64,6 +64,16 @@ def test_hermetic_environment(self):
with hermetic_environment_as(**{}):
self.assertNotIn('USER', os.environ)

def test_hermetic_environment_subprocesses(self):
self.assertIn('USER', os.environ)
with hermetic_environment_as(**dict(AAA='333')):
output = subprocess.check_output('env', shell=True)
self.assertNotIn('USER=', output)
self.assertIn('AAA', os.environ)
self.assertEquals(os.environ['AAA'], '333')
self.assertIn('USER', os.environ)
self.assertNotIn('AAA', os.environ)

def test_simple_pushd(self):
pre_cwd = os.getcwd()
with temporary_dir() as tempdir:
Expand Down