Skip to content

Commit

Permalink
Fix empty self-referential variable issue (theskumar#135)
Browse files Browse the repository at this point in the history
* Show empty self-referential variable issue

theskumar#132

* Correct test names to use interpolation

* Only use previously defined variables when handling interpolation

* Recover original os.environ after tweaking it in a test
  • Loading branch information
altendky authored and theskumar committed Sep 25, 2018
1 parent c5f5a8f commit 40ed1b1
Show file tree
Hide file tree
Showing 2 changed files with 34 additions and 3 deletions.
8 changes: 5 additions & 3 deletions dotenv/main.py
Original file line number Diff line number Diff line change
Expand Up @@ -187,7 +187,7 @@ def _replacement(name):
first search in environ, if not found,
then look into the dotenv variables
"""
ret = os.getenv(name, values.get(name, ""))
ret = os.getenv(name, new_values.get(name, ""))
return ret

def _re_sub_callback(match_object):
Expand All @@ -197,10 +197,12 @@ def _re_sub_callback(match_object):
"""
return _replacement(match_object.group()[2:-1])

new_values = {}

for k, v in values.items():
values[k] = __posix_variable.sub(_re_sub_callback, v)
new_values[k] = __posix_variable.sub(_re_sub_callback, v)

return values
return new_values


def _walk_to_root(path):
Expand Down
29 changes: 29 additions & 0 deletions tests/test_core.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
# -*- coding: utf-8 -*-
from __future__ import unicode_literals

import contextlib
import os
import pytest
import tempfile
Expand All @@ -13,6 +14,16 @@
from IPython.terminal.embed import InteractiveShellEmbed


@contextlib.contextmanager
def restore_os_environ():
environ = dict(os.environ)

try:
yield
finally:
os.environ.update(environ)


@pytest.mark.parametrize("test_input,expected", [
("a=b", ("a", "b")),
(" a = b ", ("a", "b")),
Expand Down Expand Up @@ -161,3 +172,21 @@ def test_dotenv_values_export():
load_dotenv(stream=stream)
assert 'foo' in os.environ
assert os.environ['foo'] == 'bar'


def test_dotenv_empty_selfreferential_interpolation():
stream = StringIO(u'some_path="${some_path}:a/b/c"\n')
stream.seek(0)
assert u'some_path' not in os.environ
parsed_dict = dotenv_values(stream=stream)
assert {u'some_path': u':a/b/c'} == parsed_dict


def test_dotenv_nonempty_selfreferential_interpolation():
stream = StringIO(u'some_path="${some_path}:a/b/c"\n')
stream.seek(0)
assert u'some_path' not in os.environ
with restore_os_environ():
os.environ[u'some_path'] = u'x/y/z'
parsed_dict = dotenv_values(stream=stream)
assert {u'some_path': u'x/y/z:a/b/c'} == parsed_dict

0 comments on commit 40ed1b1

Please sign in to comment.