From 7ff1a3d60c4a7e783dd1541f7548853412540091 Mon Sep 17 00:00:00 2001 From: Anna Schumaker Date: Tue, 19 Jul 2022 15:44:33 -0400 Subject: [PATCH] emmental: Add support for an application-specific temporary directory And include a function to help extract embedded cover.jpg files. Signed-off-by: Anna Schumaker --- emmental/tmpdir.py | 21 +++++++++++++++++++++ tests/test_tmpdir.py | 33 +++++++++++++++++++++++++++++++++ 2 files changed, 54 insertions(+) create mode 100644 emmental/tmpdir.py create mode 100644 tests/test_tmpdir.py diff --git a/emmental/tmpdir.py b/emmental/tmpdir.py new file mode 100644 index 0000000..45c676f --- /dev/null +++ b/emmental/tmpdir.py @@ -0,0 +1,21 @@ +# Copyright 2022 (c) Anna Schumaker. +"""Special handling for temporary directories.""" +import tempfile +import pathlib +from . import gsetup + +TMP_DIR = pathlib.Path(tempfile.gettempdir()) / gsetup.APPLICATION_ID +TMP_DIR.mkdir(exist_ok=True) + + +def cover_jpg(data: bytes | None = None) -> pathlib.Path: + """Get the path to the temporary cover.jpg file. + + If 'data' is provided, then the file will be created with the + contents initialized to 'data'. + """ + cover = TMP_DIR / "cover.jpg" + if data is not None: + with cover.open("wb") as f: + f.write(data) + return cover diff --git a/tests/test_tmpdir.py b/tests/test_tmpdir.py new file mode 100644 index 0000000..b823b8c --- /dev/null +++ b/tests/test_tmpdir.py @@ -0,0 +1,33 @@ +# Copyright 2022 (c) Anna Schumaker. +"""Test our temporary directory handling code.""" +import tempfile +import pathlib +import unittest +import emmental.tmpdir + +TMP_DIR = pathlib.Path(tempfile.gettempdir()) + + +class TestTmpDir(unittest.TestCase): + """Our teporary directory test case.""" + + def setUp(self): + """Prepare for testing.""" + emmental.tmpdir.cover_jpg().unlink(missing_ok=True) + + def test_tmpdir(self): + """Test TMP_DIR location and existence.""" + self.assertEqual(emmental.tmpdir.TMP_DIR, + TMP_DIR / emmental.gsetup.APPLICATION_ID) + self.assertTrue(emmental.tmpdir.TMP_DIR.is_dir()) + + def test_cover_jpg(self): + """Test temporary cover.jpg handling.""" + cover = emmental.tmpdir.cover_jpg() + self.assertEqual(cover, emmental.tmpdir.TMP_DIR / "cover.jpg") + self.assertFalse(cover.is_file()) + + cover = emmental.tmpdir.cover_jpg("Test Text".encode("utf-8")) + self.assertTrue(cover.is_file()) + with cover.open("rb") as f: + self.assertEqual(f.read(), "Test Text".encode("utf-8"))