fimfarchive/tests/tasks/conftest.py

119 lines
2.8 KiB
Python
Raw Normal View History

2020-03-21 19:48:34 +01:00
"""
Common task fixtures.
"""
#
# Fimfarchive, preserves stories from Fimfiction.
# Copyright (C) 2020 Joakim Soderlund
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#
2020-03-29 17:52:26 +02:00
from copy import deepcopy
2020-03-21 19:48:34 +01:00
from typing import Dict
from fimfarchive.exceptions import InvalidStoryError
2020-03-29 17:52:26 +02:00
from fimfarchive.converters import Converter
2020-03-21 19:48:34 +01:00
from fimfarchive.fetchers import Fetcher
from fimfarchive.stories import Story
2020-03-29 17:52:26 +02:00
from fimfarchive.utils import Empty
class DummyConverer(Converter):
"""
Converter that increments a counter.
"""
def __call__(self, story: Story) -> Story:
meta = deepcopy(story.meta)
meta['conversions'] += 1
return story.merge(meta=meta)
2020-03-21 19:48:34 +01:00
class DummyFetcher(Fetcher):
"""
Fetcher with local instance storage.
"""
def __init__(self):
"""
Constructor.
"""
self.stories: Dict[int, Story] = dict()
2020-03-29 17:52:26 +02:00
def add(self, key, date, flavors=(), data=Empty):
2020-03-21 19:48:34 +01:00
"""
Adds a story to the fetcher.
"""
2020-03-29 17:52:26 +02:00
meta = {
'id': key,
'title': f't{key}',
'date_modified': date,
'conversions': 0,
'author': {
'id': key,
'name': f'n{key}'
},
'chapters': [
{'id': key},
],
}
if data is Empty:
text = f'd{key}'
data = text.encode()
2020-03-21 19:48:34 +01:00
story = Story(
key=key,
2020-03-29 17:52:26 +02:00
fetcher=self,
meta=meta,
data=data,
2020-03-21 19:48:34 +01:00
flavors=flavors,
)
self.stories[key] = story
return story
2020-03-29 17:52:26 +02:00
def fetch(self, key, prefetch_meta=None, prefetch_data=None):
2020-03-21 19:48:34 +01:00
"""
Returns a previously stored story.
"""
try:
return self.stories[key]
except KeyError:
raise InvalidStoryError()
2020-03-29 17:52:26 +02:00
def fetch_data(self, key):
"""
Raises exception for missing data.
"""
raise InvalidStoryError()
def fetch_meta(self, key):
"""
Raises exception for missing meta.
"""
raise InvalidStoryError()
def __iter__(self):
"""
Yields all previously stored stories.
"""
for key in sorted(self.stories.keys()):
yield self.stories[key]