Allow string path arguments in directory fetcher

This commit is contained in:
Joakim Soderlund 2019-03-13 11:51:35 +01:00
parent 9386f8de30
commit e5b321136b
3 changed files with 48 additions and 6 deletions

View file

@ -25,11 +25,12 @@ Directory fetcher.
import json
from itertools import chain
from pathlib import Path
from typing import Any, Dict, Iterable, Iterator, Optional, Set
from typing import Any, Dict, Iterable, Iterator, Optional, Set, Union
from fimfarchive.exceptions import InvalidStoryError, StorySourceError
from fimfarchive.flavors import Flavor
from fimfarchive.stories import Story
from fimfarchive.utils import get_path
from .base import Fetcher
@ -48,8 +49,8 @@ class DirectoryFetcher(Fetcher):
def __init__(
self,
meta_path: Path = None,
data_path: Path = None,
meta_path: Union[Path, str] = None,
data_path: Union[Path, str] = None,
flavors: Iterable[Flavor] = tuple(),
) -> None:
"""
@ -60,8 +61,8 @@ class DirectoryFetcher(Fetcher):
data: The directory for story data.
flavors: The flavors to add to stories.
"""
self.meta_path = meta_path
self.data_path = data_path
self.meta_path = get_path(meta_path)
self.data_path = get_path(data_path)
self.length: Optional[int] = None
self.flavors = frozenset(flavors)

View file

@ -28,6 +28,7 @@ import shutil
from functools import partial
from importlib import import_module
from importlib_resources import read_binary, read_text
from pathlib import Path
from typing import (
cast, Any, Callable, Dict, Iterator,
Optional, Tuple, Type, TypeVar, Union,
@ -42,8 +43,10 @@ from fimfarchive.stories import Story
__all__ = (
'Empty',
'PersistedDict',
'ResourceLoader',
'find_compressor',
'find_flavor',
'get_path',
'tqdm',
)
@ -203,6 +206,22 @@ def find_flavor(story: Story, flavor: Type[F]) -> Optional[F]:
return None
def get_path(source: Union[None, Path, str]) -> Optional[Path]:
"""
Creates a path from an object, if one is supplied.
Args:
source: Object to create a path from.
Returns:
A resolved path instance, or None.
"""
if source is None:
return None
return Path(source).resolve()
class ResourceLoader:
"""
Loads resources from a package.

View file

@ -24,12 +24,16 @@ Utility tests.
import json
import os
from pathlib import Path
from unittest.mock import call, patch
import pytest
from fimfarchive.flavors import DataFormat, MetaFormat, MetaPurity
from fimfarchive.utils import find_flavor, Empty, JayWalker, PersistedDict
from fimfarchive.utils import (
find_flavor, get_path,
Empty, JayWalker, PersistedDict
)
class TestEmpty:
@ -291,3 +295,21 @@ class TestFindFlavor:
"""
found = find_flavor(story, DataFormat)
assert found is None
class TestGetPath:
"""
get_path tests.
"""
@pytest.mark.parametrize('source,target', (
(None, None),
('', Path().resolve()),
('alpaca', Path('alpaca').resolve()),
(Path('alpaca'), Path('alpaca').resolve()),
))
def test_return_values(self, source, target):
"""
Tests function returns the correct value.
"""
assert target == get_path(source)