from pathlib import Path from subprocess import CalledProcessError import pytest from halig.config import Config, EncryptionKeysConfig from halig.edit_note import edit_note from halig.exceptions import CouldNotEditTempfile from halig.new_note import new_note from tests.file_fixtures import tmpfile, tempfile # noqa: F401 from sh import age, ssh_keygen, yes @pytest.fixture() def notes_path(tmpdir): # noqa: F811 notes_path = Path(tmpdir.dirname) / "notes" notes_path.mkdir(exist_ok=True) yield notes_path @pytest.fixture() def config(notes_path): # noqa: F811 keys_path = Path(notes_path.parent / ".ssh") keys_path.mkdir(exist_ok=True) private_key_path = keys_path / "key" public_key_path = keys_path / "key.pub" ssh_keygen(yes(_piped=True), t="ed25519", f=str(private_key_path)) config = Config( notes_root_path=notes_path, encryption_keys=EncryptionKeysConfig( public_key_path=public_key_path, private_key_path=private_key_path, ), ) note_path = notes_path / "note" note_path.touch(exist_ok=True) with open(note_path, "w") as f: f.write("this is a test") age( "-R", str(config.encryption_keys.public_key_path), str(note_path), _out=f"{note_path}.age", ) yield config def mock_subprocess(args: list): with open(args[1], "a") as f: f.write(" mocked") def test_new_note_default_template_data(config: Config, mocker): # noqa: F811 mocker.patch("subprocess.call", side_effect=mock_subprocess) new_note(config.notes_root_path / "new_default_note.age", config) note_contents = age( "-d", "-i", config.encryption_keys.private_key_path, config.notes_root_path / "new_default_note.age", ) assert note_contents == f"{config._default_template_data} mocked" def test_new_note_custom_template_data(config: Config, mocker): # noqa: F811 mocker.patch("subprocess.call", side_effect=mock_subprocess) template_path = config.notes_root_path / "template.halig" template_path.touch(exist_ok=True) with open(template_path, "w") as f: f.write("template string") new_note(config.notes_root_path / "new_note.age", config) template_path.unlink() note_contents = age( "-d", "-i", config.encryption_keys.private_key_path, config.notes_root_path / "new_note.age", ) assert note_contents == "template string mocked" def test_new_not_raises_could_not_edit_tempfile(config: Config, mocker): # noqa: F811 mocker.patch( "subprocess.call", side_effect=CalledProcessError(returncode=1, cmd="foo", output="mocked error"), ) with pytest.raises(CouldNotEditTempfile): edit_note(config.notes_root_path / "note.age", config)