Skip to content

Commit

Permalink
Handle malformed input better
Browse files Browse the repository at this point in the history
  • Loading branch information
rlan committed May 29, 2024
1 parent 796ba98 commit ed03996
Show file tree
Hide file tree
Showing 2 changed files with 34 additions and 15 deletions.
29 changes: 22 additions & 7 deletions src/beancount_multitool/read_config.py
Original file line number Diff line number Diff line change
Expand Up @@ -20,11 +20,26 @@ def read_config(file_name: str) -> dict:
Returns
-------
dict
TOML file content
TOML file content. Returns an empty dict if file not found
or error decoding TOML data.
"""
with open(file_name, "rb") as f:
config = tomllib.load(f)
# Exception will be thrown if file not found.
# print(config) # debug
# print(type(config)) # debug
return config
try:
with open(file_name, "rb") as f:
try:
config = tomllib.load(f)
except tomllib.TOMLDecodeError as e:
print(f"Has invalid TOML data: {file_name}")
print(e)
config = {}
else:
if len(config) == 0: # Empty file
print(f"Has no TOML data: {file_name}")

except FileNotFoundError as e:
print(f"File not found: {file_name}")
print(e)
config = {}

# print(config) # debug
# print(type(config)) # debug
return config
20 changes: 12 additions & 8 deletions src/beancount_multitool/tests/test_read_config.py
Original file line number Diff line number Diff line change
@@ -1,11 +1,15 @@
#import pytest
from beancount_multitool.read_config import read_config


def test_read_config():
try:
read_config("no_file_error.toml")
except Exception as e:
print(e)
assert True
else:
assert AssertionError
def test_read_config_no_such_file(tmp_path):
file = tmp_path / "no_such_file.toml"
config = read_config(file)
assert config == {}


def test_read_config_empty_file(tmp_path):
file = tmp_path / "empty.toml"
file.write_text("")
config = read_config(file)
assert config == {}

0 comments on commit ed03996

Please sign in to comment.