requests_mock
requests_mock是一个可以模拟requests请求的一个包,通常用于测试阶段。
它既可以支持real requests也可以不进行real requests而是通过设置好的内容进行requests。
一些比较常用的方法包括使用
Context Mangaer
import requests import requests_mock example_url = 'https://www.example.com' with requests_mock.Mocker() as m: m.get(example_url, text="response") print(requests.get(example_url).text) # response
Decorator
当然也可以用装饰器来装饰,如果函数所需要的参数与requests_mock
传递的参数产生冲突,那么可以考虑用kwargs
的方式传入,添加kw
来指定索引。
example_url = 'https://www.example.com' @requests_mock.Mocker() def test_function(m): m.post(example_url, request_headers={"username": "user", "password": "pw"}, text="sessionid1") return requests.post(example_url, headers={"username": "user", "password": "pw"}).text sessionid = test_function() print(sessionid) #sessionid1 # If the position of the mock is likely to conflict with other arguments you can pass the kw argument to the Mocker to have the mocker object passed as that keyword argument instead. @requests_mock.Mocker(kw='mock') def test_kw_function(sessionid, **kwargs): kwargs['mock'].delete(f"{example_url}/{sessionid}", text="delete success", status_code=200) return requests.delete(f"{example_url}/{sessionid}").text print(test_kw_function(sessionid)) #delete success
unittest.mock
unittest.mock
is a library for testing in Python. It allows you to replace parts of your system under test with mock objects and make assertions about how they have been used.
之前我所遇到的问题主要是关于如何模拟argparse
,因此我这里主要涉及如何利用unittest.mock
来模拟类似于argparse
的输入。我们这里主要用到的是patch
这个函数
from unittest import mock import argparse with mock.patch('argparse._sys.argv', ['python', '--user', 'username', '--password', 'pw']): parser = argparse.ArgumentParser() parser.add_argument("--user", type=str) parser.add_argument("--password", type=str) args, unknown = parser.parse_known_args() assert vars(args) == {"user": "username", "password": "pw"} print(vars(args), unknown) # {'user': 'username', 'password': 'pw'} []
这样我们就能直接模拟argparse
的输入了。