The following pytest-test uses httpretty, to mock a request. It writes the fetched data to a file:
import requests
import httpretty
import json
from os import listdir
from os.path import join
@httpretty.activate
def test_write_file_from_datasource():
tmpdir = './mytestdir'
# mock the connection
concert_url = 'http://apis.is/concerts'
httpretty.register_uri(httpretty.GET, concert_url,
body = json.dumps({'results': []}),
content_type='application/json')
# fetch data
concerts = requests.get(concert_url).json()
# write data
with open(join(tmpdir, 'concerts.json'), 'w') as json_data:
json.dump(concerts, json_data, indent=2)
assert len(listdir(tmpdir)) == 1
What I would like to do now, is making use of the pytest tmpdir feature. To reach this, I wrote a test like this (imports same as above):
@httpretty.activate
def test_write_file_from_datasource_failing(tmpdir):
tmpdir = str(tmpdir)
# mock the connection
concert_url = 'http://apis.is/concerts'
httpretty.register_uri(httpretty.GET, concert_url,
body = json.dumps({'results': []}),
content_type='application/json')
# fetch data
concerts = requests.get(concert_url).json()
# write data
with open(join(tmpdir, 'concerts.json'), 'w') as json_data:
json.dump(concerts, json_data, indent=2)
assert len(listdir(tmpdir)) == 1
It fails, because the httpretty decorator seems to have problems with the additional parameter:
TypeError: test_write_file_from_datasource_failing() takes exactly 1 argument (0 given)
Any ideas, how to fix this?
It seems that this decorator does not work well with pytest's funcargs.
The only solution I see is to manually call httprertty.enable()
and httpretty.disable()
methods.
Or create a fixture:
@pytest.yield_fixture
def http_pretty_mock():
httpretty.enable()
yield
httpretty.disable()
def test_write_file_from_datasource_failing(http_pretty_mock, tmpdir):
tmpdir = str(tmpdir)
# mock the connection