Skip to content

Commit

Permalink
FilesystemBackend will now automatically create the directory given a…
Browse files Browse the repository at this point in the history
…s its

argument if the new create_if_missing argument is explicitely turned to
True (False by default).
  • Loading branch information
lumip committed Aug 30, 2018
1 parent e817eb7 commit 42944ba
Show file tree
Hide file tree
Showing 2 changed files with 22 additions and 3 deletions.
8 changes: 6 additions & 2 deletions qctoolkit/serialization.py
Original file line number Diff line number Diff line change
Expand Up @@ -106,18 +106,22 @@ class FilesystemBackend(StorageBackend):
Data will be stored in plain text files in a directory. The directory is given in the
constructor of this FilesystemBackend. For each data item, a separate file is created an named
after the corresponding identifier.
after the corresponding identifier. If the directory does not exist, it is not created unless the create_if_missing
argument is explicitly set to True.
"""

def __init__(self, root: str='.') -> None:
def __init__(self, root: str='.', create_if_missing: bool=False) -> None:
"""Create a new FilesystemBackend.
Args:
root: The path of the directory in which all data files are located. (default: ".",
i.e. the current directory)
create_if_missing: If False, do not create the specified directory if it does not exist. (default: False)
Raises:
NotADirectoryError: if root is not a valid directory path.
"""
if not os.path.exists(root) and create_if_missing:
os.makedirs(root)
if not os.path.isdir(root):
raise NotADirectoryError()
self._root = os.path.abspath(root)
Expand Down
17 changes: 16 additions & 1 deletion tests/serialization_tests.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@
from unittest import mock
from abc import ABCMeta, abstractmethod

from tempfile import TemporaryDirectory
from tempfile import TemporaryDirectory, TemporaryFile
from typing import Optional, Any, Dict, Tuple

from qctoolkit.serialization import FilesystemBackend, CachingBackend, Serializable, JSONSerializableEncoder,\
Expand Down Expand Up @@ -265,6 +265,21 @@ def setUp(self) -> None:
def tearDown(self) -> None:
self.tmp_dir.cleanup()

def test_init_create_dir(self) -> None:
path = self.tmp_dir.name + "/inner_dir"
self.assertFalse(os.path.isdir(path))
with self.assertRaises(NotADirectoryError):
FilesystemBackend(path)
FilesystemBackend(path, create_if_missing=False)
self.assertFalse(os.path.isdir(path))
FilesystemBackend(path, create_if_missing=True)
self.assertTrue(os.path.isdir(path))

def test_init_file_path(self) -> None:
with TemporaryFile() as tmp_file:
with self.assertRaises(NotADirectoryError):
FilesystemBackend(tmp_file.name)

def test_put_and_get_normal(self) -> None:
# first put the data
self.backend.put(self.identifier, self.test_data)
Expand Down

0 comments on commit 42944ba

Please sign in to comment.