Don't create empty file when attempting a YAML export to a non-existing folder (#1600)

* Call `export_journal` before opening file handle
* Use correct exporter class
* Fix unit test
This commit is contained in:
outa 2022-10-08 22:48:29 +02:00 committed by GitHub
parent a925c81ba8
commit d7242d81a4
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
2 changed files with 29 additions and 10 deletions

View file

@ -31,18 +31,19 @@ class TextExporter:
@classmethod @classmethod
def write_file(cls, journal, path): def write_file(cls, journal, path):
"""Exports a journal into a single file.""" """Exports a journal into a single file."""
export_str = cls.export_journal(journal)
with open(path, "w", encoding="utf-8") as f: with open(path, "w", encoding="utf-8") as f:
f.write(cls.export_journal(journal)) f.write(export_str)
print_msg( print_msg(
Message( Message(
MsgText.JournalExportedTo, MsgText.JournalExportedTo,
MsgStyle.NORMAL, MsgStyle.NORMAL,
{ {
"path": path, "path": path,
}, },
)
) )
return "" )
return ""
@classmethod @classmethod
def make_filename(cls, entry): def make_filename(cls, entry):

View file

@ -1,10 +1,16 @@
# Copyright © 2012-2022 jrnl contributors # Copyright © 2012-2022 jrnl contributors
# License: https://www.gnu.org/licenses/gpl-3.0.html # License: https://www.gnu.org/licenses/gpl-3.0.html
from unittest import mock
import pytest import pytest
from jrnl.exception import JrnlException from jrnl.exception import JrnlException
from jrnl.messages import Message
from jrnl.messages import MsgStyle
from jrnl.messages import MsgText
from jrnl.plugins.fancy_exporter import check_provided_linewrap_viability from jrnl.plugins.fancy_exporter import check_provided_linewrap_viability
from jrnl.plugins.yaml_exporter import YAMLExporter
@pytest.fixture() @pytest.fixture()
@ -28,3 +34,15 @@ class TestFancy:
with pytest.raises(JrnlException): with pytest.raises(JrnlException):
check_provided_linewrap_viability(total_linewrap, [content], journal) check_provided_linewrap_viability(total_linewrap, [content], journal)
class TestYaml:
@mock.patch("jrnl.plugins.yaml_exporter.YAMLExporter.export_journal")
@mock.patch("builtins.open")
def test_export_to_nonexisting_folder(self, mock_open, mock_export_journal):
mock_export_journal.side_effect = JrnlException(
Message(MsgText.YamlMustBeDirectory, MsgStyle.ERROR)
)
with pytest.raises(JrnlException):
YAMLExporter.write_file("journal", "non-existing-path")
mock_open.assert_not_called()