[英]combine httpretty with pytest tmpdir
The following pytest-test uses httpretty, to mock a request. 以下pytest-test使用httpretty来模拟请求。 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. 我现在想做的就是利用pytest tmpdir功能。 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: 它失败,因为httpretty装饰器似乎对附加参数有问题:
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. 似乎此装饰器无法与pytest的funcargs配合使用。
The only solution I see is to manually call httprertty.enable()
and httpretty.disable()
methods. 我看到的唯一解决方案是手动调用
httprertty.enable()
和httpretty.disable()
方法。
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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.