不知道要拿来做什么但觉得很有意思的个人博客
Python 一些模拟请求和输入的方法
Python 一些模拟请求和输入的方法

Python 一些模拟请求和输入的方法

requests_mock

requests_mock是一个可以模拟requests请求的一个包,通常用于测试阶段。

requests_mock documentation

它既可以支持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的输入了。

发表评论

您的电子邮箱地址不会被公开。