Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Handle empty config files #41

Merged
merged 3 commits into from
Oct 16, 2024
Merged
Show file tree
Hide file tree
Changes from 2 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
39 changes: 33 additions & 6 deletions joft/utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,22 @@ def load_and_parse_yaml_file(path: str) -> typing.Dict[str, typing.Any]:
return yaml_obj


def read_and_validate_config(
path: str | pathlib.Path,
) -> typing.Dict[str, typing.Any] | None:
"""Read and return config file is it's valid. Return None otherwise."""
with open(path, "rb") as fp:
config = tomllib.load(fp)

try:
config["jira"]["server"]["hostname"]
config["jira"]["server"]["pat_token"]
except KeyError:
return None
else:
return config


def load_toml_app_config() -> typing.Any:
possible_paths = []

Expand All @@ -26,7 +42,23 @@ def load_toml_app_config() -> typing.Any:
for path in possible_paths:
config_file_path = pathlib.Path(path) / "joft.config.toml"
if config_file_path.is_file():
break
if config := read_and_validate_config(config_file_path):
return config
else:
err_msg = textwrap.dedent(f"""\
[ERROR] Configuration file {config_file_path} is invalid.

Configuration file should have the following content:

[jira.server]
hostname = "<your jira server url>"
pat_token = "<your jira pat token>"

and should be stored in one of the following directories:
{', '.join(possible_paths)}\
""")
print(err_msg)
sys.exit(1)
else:
err_msg = textwrap.dedent(f"""\
[ERROR] Cannot find configuration file 'joft.config.toml'.
Expand All @@ -43,8 +75,3 @@ def load_toml_app_config() -> typing.Any:

print(err_msg)
sys.exit(1)

with open(config_file_path, "rb") as fp:
config = tomllib.load(fp)

return config
49 changes: 49 additions & 0 deletions tests/test_utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -81,3 +81,52 @@ def test_load_toml_app_config_no_config_found(mock_platformdirs, mock_cwd) -> No

assert "Cannot find configuration file" in mock_stdout.getvalue()
assert sys_exit.value.args[0] == 1


@unittest.mock.patch("joft.utils.pathlib.Path.cwd")
def test_load_toml_app_config_invalid_config_found(mock_cwd) -> None:
"""
Test that we will end with a non-zero error code when there is an invalid
config present and printing a message on the stdout.
"""

invalid_config_file_contents = """[jira.server]
pat_token = "__pat_token__"
"""

with tempfile.TemporaryDirectory() as tmpdir:
mock_cwd.return_value = tmpdir

config_file_path = os.path.join(tmpdir, "joft.config.toml")
with open(config_file_path, "w") as fp:
fp.write(invalid_config_file_contents)

with unittest.mock.patch("sys.stdout", new=io.StringIO()) as mock_stdout:
with pytest.raises(SystemExit) as sys_exit:
joft.utils.load_toml_app_config()

assert f"Configuration file {config_file_path} is invalid" in mock_stdout.getvalue()
assert sys_exit.value.args[0] == 1


@pytest.mark.parametrize(
"config_file_content, valid",
[
("[jira.server]\nhostname = 'foo'\npat_token = 'bar'", True),
("", False),
("[jira.server]\nhostname = 'foo'", False),
("[jira.server]\npat_token = 'bar'", False),
("hostname = 'foo'\npat_token = 'bar'", False),
],
)
def test_read_and_validate_config(config_file_content, valid, tmp_path) -> None:
config_file_path = tmp_path / "joft.config.toml"
config_file_path.write_text(config_file_content)

config = joft.utils.read_and_validate_config(config_file_path)

if valid:
assert config["jira"]["server"]["hostname"] == "foo"
assert config["jira"]["server"]["pat_token"] == "bar"
else:
assert config is None
Loading