Skip to content

Commit

Permalink
add more tests and allow user to modify path during with statement
Browse files Browse the repository at this point in the history
  • Loading branch information
joezuntz committed Jun 29, 2020
1 parent 3799e7a commit 8ea0c54
Show file tree
Hide file tree
Showing 2 changed files with 41 additions and 7 deletions.
21 changes: 17 additions & 4 deletions ceci/utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,23 +3,36 @@

@contextmanager
def extra_paths(paths, start=True):
# allow passing a single path or
# a list of them
if isinstance(paths, str):
paths = paths.split()

# On enter, add paths to sys.path,
# either the start or the end depending
# on the start argument
for path in paths:
if start:
sys.path.insert(0, path)
else:
sys.path.append(path)

# Return control to caller
try:
yield
# On exit, remove the paths
finally:
for path in paths:
if start:
sys.path.remove(path)
else:
remove_last(sys.path, path)
try:
if start:
sys.path.remove(path)
else:
remove_last(sys.path, path)
# If e.g. user has already done this
# manually for some reason then just
# skip
except ValueError:
pass

def remove_last(lst, item):
"""
Expand Down
27 changes: 24 additions & 3 deletions tests/test_python_paths.py
Original file line number Diff line number Diff line change
Expand Up @@ -67,7 +67,8 @@ def test_extra_paths():
assert sys.path[0] == p[1]
assert sys.path[1] == p[0]

assert p not in sys.path
for p1 in p:
assert p1 not in sys.path
assert sys.path == orig_path

try:
Expand All @@ -78,7 +79,8 @@ def test_extra_paths():
except MyError:
pass

assert p not in sys.path
for p1 in p:
assert p1 not in sys.path
assert sys.path == orig_path


Expand All @@ -89,7 +91,8 @@ def test_extra_paths():
assert sys.path[-1] == p[1]
assert sys.path[-2] == p[0]

assert p not in sys.path
for p1 in p:
assert p1 not in sys.path
assert sys.path == orig_path

try:
Expand All @@ -103,4 +106,22 @@ def test_extra_paths():
assert p not in sys.path
assert sys.path == orig_path

# check that if the user removes the path
# themselves then it is okay
p = ['xxx111yyy222', 'aaa222333']
with extra_paths(p, start=True):
sys.path.remove('xxx111yyy222')

assert sys.path == orig_path

# check only one copy is removed
sys.path.append("aaa")
tmp_paths = sys.path[:]
p = "aaa"
with extra_paths(p, start=True):
pass

assert sys.path == tmp_paths

with extra_paths(p, start=False):
pass

0 comments on commit 8ea0c54

Please sign in to comment.