73 lines
2.4 KiB
Python
73 lines
2.4 KiB
Python
import requests
|
|
import unittest
|
|
from unittest import mock
|
|
# from blenderpack import Repositories, fetch_repo
|
|
from datetime import datetime
|
|
import json
|
|
|
|
# based on https://stackoverflow.com/a/28507806/2730823
|
|
|
|
# This method will be used by the mock to replace requests.get
|
|
def mocked_requests_get(*args, **kwargs):
|
|
cidict = requests.structures.CaseInsensitiveDict
|
|
req_headers = cidict(kwargs.get('headers'))
|
|
t_fmt = '%a, %m %b %Y %X %Z'
|
|
|
|
class MockResponse:
|
|
def __init__(self, headers: cidict, status_code: int):
|
|
self.headers = headers
|
|
self.status_code = status_code
|
|
|
|
def json(self):
|
|
return json.dumps({'url': 'http://someurl.tld/repo.json'})
|
|
|
|
if args[0] == 'http://someurl.tld/repo.json':
|
|
resp_headers = cidict({
|
|
"ETag": '"2a0094b-b74-55326ced274f3"',
|
|
"Last-Modified": 'Sun, 13 Mar 2011 13:38:53 GMT',
|
|
})
|
|
|
|
if req_headers == {}:
|
|
resp_code = 200
|
|
else:
|
|
req_headers = cidict(req_headers)
|
|
resp_code = 304 if req_headers.get('if-none-match', '') == resp_headers['etag']\
|
|
or datetime.strptime(req_headers.get('if-modified-since', ''), t_fmt) < \
|
|
datetime.strptime(resp_headers['last-modified'], t_fmt) \
|
|
else 200
|
|
return MockResponse(resp_headers, resp_code)
|
|
|
|
return MockResponse(None, 404)
|
|
|
|
class MockRepositories:
|
|
storage = {}
|
|
|
|
def load(self, *args, **kwargs):
|
|
if args[0] not in self.storage:
|
|
self.storage[args[0]] = {'url': args[0]}
|
|
|
|
return self.storage[args[0]]
|
|
|
|
def write(self, *args, **kwargs):
|
|
self.storage[args[0]['url']] = args[0]
|
|
|
|
|
|
class fetch_url_twice(unittest.TestCase):
|
|
|
|
@mock.patch('requests.get', side_effect=mocked_requests_get)
|
|
def test_fetch(self, mock_get):
|
|
self.fail('unfinished test')
|
|
repos = MockRepositories()
|
|
fetch_repo('http://someurl.tld/repo.json', repos)
|
|
mock_get.assert_called_with('http://someurl.tld/repo.json', headers={})
|
|
|
|
fetch_repo('http://someurl.tld/repo.json', repos)
|
|
mock_get.assert_called_with('http://someurl.tld/repo.json', headers={
|
|
'If-None-Match': '"2a0094b-b74-55326ced274f3"',
|
|
'If-Modified-Since': 'Sun, 13 Mar 2011 13:38:53 GMT'
|
|
})
|
|
|
|
|
|
if __name__ == '__main__':
|
|
unittest.main()
|