Add test for unknown number of episodes

This commit is contained in:
QasimK committed 2016-05-28 16:13:59 +01:00
1 parent 8ec6ed51bb
commit 3f63fa914a
8 files changed
+1239 -37

No files matched your search

+2
View File
@@ -4,6 +4,8 @@ graft src
graft ci
graft tests
resursive-include tests/mal_scraper *
include .bumpversion.cfg
include .coveragerc
include .cookiecutterrc
+3
View File
@@ -6,6 +6,9 @@ max-line-length = 100
max-complexity = 5
[pytest]
testpaths =
tests
docs
norecursedirs =
.git
.tox
+8 -6
View File
@@ -15,15 +15,17 @@ logger = logging.getLogger(__name__)
# pass
def retrieve_anime(id_ref, requester=request_passthrough):
def retrieve_anime(id_ref=1, requester=request_passthrough):
"""Return the metadata for a particular show. TODO.
id_ref: identifier that can be used in iterations
requester: funnel requests through a request maker, this allows
us to limit requests globally
Args:
id_ref (Optional(int)): Internal show identifier
requester (Optional(requests-like)): HTTP request maker
This allows us to control/limit/mock requests.
Return a dictionary.
See tests/mal_scraper/test_anime.py::test_download_first for the keys.
Return:
A dictionary.
See tests/mal_scraper/test_anime.py::test_download_first for the keys.
"""
url = get_url_from_id_ref(id_ref)
response = requester.get(url)
+43 -28
View File
@@ -9,48 +9,63 @@ import responses
class ResponsesWrapper:
"""Mock ALL requests more easily using saved files when use_live.
You can pass fake in instead which will ALWAYS use the fake response.
You can ALWAYS mock a request if there is no safe live page to use.
"""
RESPONSES_DIR = os.path.join(os.path.dirname(__file__), 'responses')
TODO_DIR = os.path.join(os.path.dirname(__file__), '0_todo_responses')
AUTO_DIR = os.path.join(os.path.dirname(__file__), 'auto_responses')
MANUAL_DIR = os.path.join(os.path.dirname(__file__), 'manual_responses')
def __init__(self, rsps, use_live):
self.rsps = rsps
self.use_live = use_live # Use live unless we are faking
def add(self, url, method='get', fake=None):
assert method == 'get', 'TODO: Implement other methods.'
filename = self._encode(method, url)
filepath = os.path.join(self.RESPONSES_DIR, filename)
def optional_mock(self, url):
"""Add an automatic mock for a URL, this can be disabled if desired."""
filename = self._encode('get', url)
filepath = os.path.join(self.AUTO_DIR, filename)
pass_method = {
'get': responses.GET
}[method]
if fake:
# Always mock the response whether it is live or not
self.rsps.add(pass_method, url, body=fake)
elif os.path.isfile(filepath): # pragma: no cover
# Only mock the response if we are not using live
# Otherwise allow a live request to be made
if os.path.isfile(filepath): # pragma: no cover
# Mock the response unless we are using live
if not self.use_live:
with open(filepath, 'rb') as fin:
body = fin.read()
self.rsps.add(pass_method, url, body=body)
else:
# To avoid an error let's make the request and add it in as mocked
# Make the request manually, avoiding requests which is mocked.
with urllib.request.urlopen(url) as nin:
self.rsps.add(pass_method, url, body=nin.read())
body = nin.read()
self.rsps.add(responses.GET, url, body=body)
else: # pragma: no cover
# Produce a file to mock this request (needs to be checked manually)
todo_filename = 'TODO_' + filename
todo_filepath = os.path.join(self.RESPONSES_DIR, todo_filename)
with urllib.request.urlopen(url) as nin,\
open(todo_filepath, 'wb') as fout:
fout.write(nin.read())
print('Response Mocked:', method, url)
print('File in responses tests directory: ', todo_filename)
print('Look at it and rename it by removing "TODO_".')
assert False, 'Look at stdout because a response was mocked for you.'
self._save_url(url, filename)
def always_mock(self, url, filename):
"""Always mock this response, never test against the live url.
Args:
url (str): The URL to mock.
filename (str): The file inside self.RESPONSES_DIR to use.
"""
filepath = os.path.join(self.MANUAL_DIR, filename)
if os.path.isfile(filepath):
with open(filepath, 'rb') as fin:
self.rsps.add(responses.GET, url, body=fin.read())
else: # pragma: no cover
# Produce a file to mock this request (needs to be checked manually)
self._save_url(url, filename)
def _save_url(self, url, filename):
os.makedirs(self.TODO_DIR, exist_ok=True)
todo_filepath = os.path.join(self.TODO_DIR, filename)
with urllib.request.urlopen(url) as nin,\
open(todo_filepath, 'wb') as fout:
fout.write(nin.read())
print('Response Mocked:', url)
print('File in TODO responses directory:', filename)
print('If you want to edit the file, move it into manual responses and use always_mock.')
print('Otherwise, move it into the auto responses folder.')
assert False, 'Look at stdout because a response was mocked for you.'
@staticmethod
def _encode(method, url):
@@ -0,0 +1 @@
bla
File diff suppressed because it is too large. Load diff
+19 -3
View File
@@ -7,7 +7,7 @@ import mal_scraper
def test_download_first(mock_requests):
"""Can we retrieve the first show ever?"""
mock_requests.add('http://myanimelist.net/anime/1')
mock_requests.optional_mock('http://myanimelist.net/anime/1')
info = mal_scraper.retrieve_anime(1)
# Fuzzy match datetime
@@ -15,7 +15,7 @@ def test_download_first(mock_requests):
assert datetime.utcnow() - retrieval < timedelta(seconds=30)
assert info == {
'scraper_retrieved_at': retrieval,
'scraper_retrieved_at': retrieval, # UTC Datetime
'id_ref': 1,
'name': 'Cowboy Bebop',
'name_english': 'Cowboy Bebop',
@@ -36,5 +36,21 @@ def test_download_first(mock_requests):
def test_download_first_fail(mock_requests):
"""Do we get None if the page was bad??"""
mock_requests.add('http://myanimelist.net/anime/1', fake='bla')
mock_requests.always_mock(
'http://myanimelist.net/anime/1',
'garbled_anime_page',
)
assert mal_scraper.retrieve_anime(1) is None
class TestParsing:
"""Test parsing of particular parts of the page"""
def test_unknown_episodes(self, mock_requests):
"""Do we return None for an unknown number of episodes?"""
mock_requests.always_mock(
'http://myanimelist.net/anime/32105',
'unknown_episodes',
)
assert mal_scraper.retrieve_anime(32105)['episodes'] is None