Skip to content

Commit

Permalink
fix: PAN-2008 handle errors on not allowed paths (#38)
Browse files Browse the repository at this point in the history
* fix: PAN-2008 handle errors on not allowed paths
  • Loading branch information
jpantos authored Jun 28, 2024
1 parent 37ef618 commit 68a9008
Show file tree
Hide file tree
Showing 2 changed files with 28 additions and 11 deletions.
32 changes: 24 additions & 8 deletions pantos/common/configuration.py
Original file line number Diff line number Diff line change
Expand Up @@ -157,10 +157,15 @@ def __find_file(self, file_path: str | None) -> pathlib.Path:
# Find the configuration file at common locations
for path in _CONFIGURATION_PATHS:
config_path = path
if config_path.is_dir():
config_path = config_path / self.default_file_name
if config_path.is_file():
return config_path
try:
if config_path.is_dir():
config_path = config_path / self.default_file_name
if config_path.is_file():
return config_path
except OSError:
# Perhaps the path is not readable
_logger.warning(f'error while reading: {config_path}',
exc_info=True)
# Package resource
if importlib.resources.is_resource('pantos', self.default_file_name):
with importlib.resources.path('pantos',
Expand All @@ -179,15 +184,26 @@ def __parse_file(self, path: pathlib.Path) -> dict[str, typing.Any]:
_logger.info('loading env variables from environment defined file '
'PANTOS_ENV_FILE')
env_files.insert(0, pathlib.Path(os.environ['PANTOS_ENV_FILE']))

# Extend env_files with .env paths from _CONFIGURATION_PATHS
env_files.extend(
pathlib.Path(str(p)).with_name(
str(p.name) + self.default_file_name + '.env')
for p in _CONFIGURATION_PATHS)
# Iterate over the potential .env file paths
for env_file in env_files:
if env_file.is_file():
try:
try:
if env_file.is_file():
dotenv.load_dotenv(env_file)
_logger.info(f'loaded .env from file {env_file}')
break
except Exception:
raise ConfigError(f'unable to load .env file {env_file}')
except OSError:
# Perhaps the path is not readable
_logger.warning(f'error while reading: {env_file}',
exc_info=True)
except Exception:
_logger.error(f'unable to load .env file {env_file}',
exc_info=True)
# Parse the YAML code in the configuration file
try:
return pyaml_env.parse_config(path.as_posix(), default_value='')
Expand Down
7 changes: 4 additions & 3 deletions tests/test_configuration.py
Original file line number Diff line number Diff line change
Expand Up @@ -117,6 +117,7 @@ def test_parse_file_error(mock_open, mock_parse_config, mock_load_dotenv,
mock_parse_config.return_value = {'key': 'value'}

config = Config('config.yaml')
with pytest.raises(ConfigError):
config._Config__parse_file(
pathlib.Path('config.yaml')) # Accessing private function
result = config._Config__parse_file(
pathlib.Path('config.yaml')) # Accessing private function

assert result == {'key': 'value'}

0 comments on commit 68a9008

Please sign in to comment.