Skip to content

Commit

Permalink
Raise KeyError when key is not found in ini repositories
Browse files Browse the repository at this point in the history
Enables RepositoryIni to be used in a collections.ChainMap
to allow cascading multiple repositories.

See #142
  • Loading branch information
b0o committed Feb 16, 2023
1 parent 9cc2f7e commit d596515
Show file tree
Hide file tree
Showing 4 changed files with 23 additions and 3 deletions.
9 changes: 6 additions & 3 deletions decouple.py
Original file line number Diff line number Diff line change
Expand Up @@ -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):
Expand Down Expand Up @@ -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):
Expand Down
4 changes: 4 additions & 0 deletions tests/test_env.py
Original file line number Diff line number Diff line change
Expand Up @@ -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']
5 changes: 5 additions & 0 deletions tests/test_ini.py
Original file line number Diff line number Diff line change
Expand Up @@ -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']
8 changes: 8 additions & 0 deletions tests/test_secrets.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
# coding: utf-8
import os
import pytest

from decouple import Config, RepositorySecret

Expand Down Expand Up @@ -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']

0 comments on commit d596515

Please sign in to comment.