我有一个简单的功能。
def graphite_json(target):
url = 'http://server/render/?format=json&target={}&from=-10days'.format(target)
r = requests.get(url)
return r.json()它与(Graphite)服务器联系,使用请求库获取JSON字符串并将其转换为本机列表。很简单。
然后我想测试它,把它弄得一团糟。我的想法是:我很快就需要更多的Graphite功能,所以最好是创建一个类,并将请求库作为外部依赖,这样我就可以更好地进行测试。我最后得到的结果是:
import json
import requests
class Graphite(object):
def __init__(self, server_url = 'http://server', requests_module=requests):
self.requests = requests_module
self.server_url = server_url
def get(self, metric):
url = '{}/render/?format=json&target={}'.format(
self.server_url, metric)
response = self.requests.get(url)
return response.json()import json
import os
import pytest
from api.graphite import Graphite
@pytest.fixture(scope="session")
def sample_response():
dirpath = os.path.dirname(os.path.realpath(__file__))
with open('{}/data/graphite_response.json'.format(dirpath), 'r') as content_file:
content = content_file.read()
return content
@pytest.fixture(scope="session")
def mock_graphite_requests(sample_response):
class Requests(object):
def get(self, url):
if 'target' not in url:
raise NotImplementedError('need a target for graphite stats')
class Response(object):
def __init__(self, data):
self.data = data
def json(self):
return json.loads(self.data)
return Response(sample_response)
return Requests()
@pytest.fixture(scope="session")
def graphite(mock_graphite_requests):
return Graphite(requests_module=mock_graphite_requests)
def test_graphite_metric(graphite, sample_response):
data = graphite.get('summarize(stats.gauges.items,"12hour","avg")')
assert data == json.loads(sample_response)我认为这是软弱的,因为:
我怎么才能解决这个烂摊子?
发布于 2015-02-05 16:16:38
您不希望测试网络、requests或json库,您希望检查您的方法是否使用了某个参数调用requests (以检查您的字符串插值是否有效并使用了正确的参数),以及是否返回响应的JSON方法的返回值(以检查您是否实际使用并通过对象传递)。
至少这些东西是值得测试的。如果您喜欢的话,可以用模拟来简化代码,否则我会说移动类定义,以便您有正确的MockRequests和MockResponse类,可能是带有响应构造函数参数的请求。
类应该尽可能简单,没有必要检查"target",只需检查传入的URL是否具有正确的(预置)值。响应不应该调用任何东西,它应该只返回(再次预置) JSON对象。
https://codereview.stackexchange.com/questions/79683
复制相似问题