diff --git a/decouple.py b/decouple.py index 31d6877..f499862 100644 --- a/decouple.py +++ b/decouple.py @@ -11,10 +11,10 @@ if PYVERSION >= (3, 0, 0): - from configparser import ConfigParser + from configparser import ConfigParser, NoOptionError text_type = str else: - from ConfigParser import SafeConfigParser as ConfigParser + from ConfigParser import SafeConfigParser as ConfigParser, NoOptionError text_type = unicode if PYVERSION >= (3, 2, 0): @@ -134,7 +134,10 @@ def __contains__(self, key): self.parser.has_option(self.SECTION, key)) def __getitem__(self, key): - return self.parser.get(self.SECTION, key) + try: + return self.parser.get(self.SECTION, key) + except NoOptionError: + raise KeyError(key) class RepositoryEnv(RepositoryEmpty): diff --git a/tests/test_env.py b/tests/test_env.py index a259af3..a91c95c 100644 --- a/tests/test_env.py +++ b/tests/test_env.py @@ -136,3 +136,7 @@ def test_env_with_quote(config): assert '"Y"' == config('KeyHasTwoDoubleQuote') assert '''"Y\'''' == config('KeyHasMixedQuotesAsData1') assert '''\'Y"''' == config('KeyHasMixedQuotesAsData2') + +def test_env_repo_keyerror(config): + with pytest.raises(KeyError): + config.repository['UndefinedKey'] diff --git a/tests/test_ini.py b/tests/test_ini.py index 6ff0523..f610078 100644 --- a/tests/test_ini.py +++ b/tests/test_ini.py @@ -121,3 +121,8 @@ def test_ini_undefined_but_present_in_os_environ(config): def test_ini_empty_string_means_false(config): assert False is config('KeyEmpty', cast=bool) + + +def test_ini_repo_keyerror(config): + with pytest.raises(KeyError): + config.repository['UndefinedKey'] diff --git a/tests/test_secrets.py b/tests/test_secrets.py index 481fdeb..7d6185b 100644 --- a/tests/test_secrets.py +++ b/tests/test_secrets.py @@ -1,5 +1,6 @@ # coding: utf-8 import os +import pytest from decouple import Config, RepositorySecret @@ -28,3 +29,10 @@ def test_secret_overriden_by_environ(): os.environ['db_user'] = 'hi' assert 'hi' == config('db_user') del os.environ['db_user'] + +def test_secret_repo_keyerror(): + path = os.path.join(os.path.dirname(__file__), 'secrets') + repo = RepositorySecret(path) + + with pytest.raises(KeyError): + repo['UndefinedKey']