我已经将我的代码拆分为单独的函数以进行单元测试。我正在尝试使用Pytest测试框架,目前只了解基础知识。
实际上我并不想向互联网发送请求——这将是一个无用的测试,因为我只会测试urllib
库。然而,我确实想测试响应的处理方式。
我有这个函数来发出请求。
def request_url(url):
return request.urlopen(url)
然后我正在检查内容类型:
def get_document_type(req):
""" checks if document is html or plain text """
doc_type = req.info().get_content_type()
if doc_type == "text/html":
return "html"
elif doc_type == "text/plain":
return "txt"
else:
return error_message["unsupported_document_type"]
接下来我需要进行测试,并需要模拟每个结果。如果这是Node.js,我可以使用类似于rewire或sinon stub的东西。
def get_content(req):
doc_type_response = get_document_type(req)
if doc_type_response == "html":
# handle html content
elif get_type_response == "txt":
# handle plain text
else:
return doc_type_response
这个单元测试可以工作,但我不想进行真正的调用。
def test_request_url():
url = request_url(url_to_try).info().get_content_type()
assert url == "text/plain"
有人知道最好的方法吗?这个问题与IT技术相关。