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

feature/enabling environment variables unset action #4224

Merged
merged 8 commits into from
Jan 10, 2019
11 changes: 10 additions & 1 deletion conans/client/tools/env.py
Original file line number Diff line number Diff line change
Expand Up @@ -32,11 +32,18 @@ def run_environment(conanfile):
@contextmanager
def environment_append(env_vars):
"""
:param env_vars: List of simple environment vars. {name: value, name2: value2} => e.g.: MYVAR=1
:param env_vars: List (dict) of simple environment vars. {name: value, name2: value2} => e.g.: MYVAR=1
The values can also be lists of appendable environment vars. {name: [value, value2]}
=> e.g. PATH=/path/1:/path/2
If the value is set to None, then that environment variable is unset.
:return: None
"""
unset_vars = []
for key in env_vars.keys():
if env_vars[key] is None:
unset_vars.append(key)
for var in unset_vars:
env_vars.pop(var, None)
for name, value in env_vars.items():
if isinstance(value, list):
env_vars[name] = os.pathsep.join(value)
Expand All @@ -46,6 +53,8 @@ def environment_append(env_vars):
if env_vars:
old_env = dict(os.environ)
os.environ.update(env_vars)
for var in unset_vars:
alacasta marked this conversation as resolved.
Show resolved Hide resolved
os.environ.pop(var)
try:
yield
finally:
Expand Down
33 changes: 33 additions & 0 deletions conans/test/unittests/client/tools/test_env.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
# coding=utf-8

import os
import unittest
import mock

from conans.client.tools import env


class ToolsEnvTest(unittest.TestCase):
def test_environment_append_variables(self):
with mock.patch.dict('os.environ', {}),\
env.environment_append({'env_var1': 'value',
'env_var2': 'value2'}):
self.assertEqual(os.environ['env_var1'], 'value')
self.assertEqual(os.environ['env_var2'], 'value2')

def test_environment_append_overwriting(self):
with mock.patch.dict('os.environ', {'env_var1': 'value'}),\
env.environment_append({'env_var1': 'new_value'}):
self.assertEqual(os.environ['env_var1'], 'new_value')

def test_environment_append_list(self):
with mock.patch.dict('os.environ', {}),\
env.environment_append({'env_var1': ['value1', 'value2']}):
self.assertEqual(os.environ['env_var1'], 'value1' +
os.pathsep + 'value2')

def test_environment_unset_variable(self):
with mock.patch.dict('os.environ', {'env_var1': 'value'}),\
env.environment_append({'env_var1': None, 'env_var2': 'value2'}):
self.assertNotIn('env_var1', os.environ)
self.assertEqual(os.environ['env_var2'], 'value2')