import shutil import tempfile from pathlib import Path from tempfile import NamedTemporaryFile import yaml from halig.config import get_config, Config, EncryptionKeysConfig from halig.exceptions import ConfigFileDoesNotExist, ConfigFileIsInvalid from ward import fixture, test, raises @fixture() def tmpfile(): _tmpfile = NamedTemporaryFile(delete=False) with open(_tmpfile.name, "w") as file: yield file Path(_tmpfile.name).unlink() @fixture() def tmpdir(): tmpdir = Path(tempfile.mkdtemp()) yield tmpdir shutil.rmtree(tmpdir) @test("get config raises ConfigFileDoesNotExist") def _(): with raises(ConfigFileDoesNotExist): get_config(Path("/foobar")) @test("get config raises ConfigFileIsInvalid") def _(): with raises(ConfigFileIsInvalid): with NamedTemporaryFile() as f: get_config(Path(f.name)) @test("get config raises ConfigFileIsInvalid from invalid file contents") def _(tmpfile=tmpfile): tmpfile.write("foobar") with raises(ConfigFileIsInvalid): get_config(Path(tmpfile.name)) @test("get config raises ConfigFileIsInvalid from pydantic validation") def _(tmpfile=tmpfile): yaml.dump({"foo": "bar"}, tmpfile, Dumper=yaml.SafeDumper) with raises(ConfigFileIsInvalid): get_config(Path(tmpfile.name)) @test("get config returns a correct config instance") def _(tmpdir=tmpdir): notes_root_path = Path(tmpdir / "notes") notes_root_path.mkdir(exist_ok=True) age_binary_path = Path(tmpdir / "age") age_binary_path.touch(exist_ok=True) encryption_keys_root_path = Path(tmpdir / "encryption_keys") encryption_keys_root_path.mkdir(exist_ok=True) public_key_path = Path(encryption_keys_root_path / "public.key") public_key_path.touch(exist_ok=True) private_key_path = Path(encryption_keys_root_path / "private.key") private_key_path.touch(exist_ok=True) config = Config( notes_root_path=notes_root_path, age_binary_path=age_binary_path, encryption_keys=EncryptionKeysConfig( public_key_path=public_key_path, private_key_path=private_key_path ), ) assert config.notes_root_path == notes_root_path assert config.age_binary_path == age_binary_path assert config.encryption_keys.public_key_path == public_key_path assert config.encryption_keys.private_key_path == private_key_path