Skip to content
Open
Show file tree
Hide file tree
Changes from all 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
9 changes: 5 additions & 4 deletions hey/configs/utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,12 +14,12 @@ def read_configs() -> dict:

if os.path.exists(CONFIG_FILE_PATH):
try:
with open(CONFIG_FILE_PATH) as file:
return json.loads(file.read())
with open(CONFIG_FILE_PATH, encoding="utf-8") as file:
return json.load(file)
except json.JSONDecodeError as e:
error_message = (
f"Your config file is [red bold]broken[/red bold]. "
f"Try `hey config edit` or `hey config init`. {e}"
f"Try `hey config edit` or `hey config create`. {e}"
)
console.print(error_message)
console.print("Using the [green bold]default settings[/green bold].")
Expand All @@ -28,7 +28,8 @@ def read_configs() -> dict:


def init_config():
with open(CONFIG_FILE_PATH, "w+") as conf_file:
os.makedirs(APP_CONFIG_DIR, exist_ok=True)
with open(CONFIG_FILE_PATH, "w+", encoding="utf-8") as conf_file:
conf_file.write(json.dumps(BASE_CONFIG, indent=4))


Expand Down
46 changes: 46 additions & 0 deletions tests/test_configs_utils.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,46 @@
import json

from hey.configs import utils
from hey.consts import BASE_CONFIG


def test_init_config_creates_directory_and_file(tmp_path, monkeypatch):
config_dir = tmp_path / "hey"
config_file = config_dir / "config.json"

monkeypatch.setattr(utils, "APP_CONFIG_DIR", config_dir)
monkeypatch.setattr(utils, "CONFIG_FILE_PATH", config_file)

utils.init_config()

assert config_file.exists()
loaded = json.loads(config_file.read_text(encoding="utf-8"))
assert loaded == BASE_CONFIG


def test_read_configs_returns_user_config_when_valid_json(tmp_path, monkeypatch):
config_file = tmp_path / "config.json"
expected = {"model": "gpt-4o-mini"}
config_file.write_text(json.dumps(expected), encoding="utf-8")

monkeypatch.setattr(utils, "CONFIG_FILE_PATH", config_file)

assert utils.read_configs() == expected


def test_read_configs_falls_back_and_shows_create_hint_for_invalid_json(
tmp_path, monkeypatch
):
config_file = tmp_path / "config.json"
config_file.write_text("{broken", encoding="utf-8")

printed = []

def fake_print(message):
printed.append(str(message))

monkeypatch.setattr(utils, "CONFIG_FILE_PATH", config_file)
monkeypatch.setattr(utils.console, "print", fake_print)

assert utils.read_configs() == BASE_CONFIG
assert any("hey config create" in msg for msg in printed)