1

我正在使用requests-mock并试图弄清楚如何断言put请求已被正确调用:


def funtion_to_be_tested():
    requests.put(
        headers={'X-API-Key': 'api_key'},
        url=url,
        params={'param1': 'foo'},
        data='This is the data'
    )


def test_upload(requests_mock):
    url = 'http://example.com/upload'
    requests_mock.put(url, text='ok')
    funtion_to_be_tested()
    # how to check that `data` was `This is the data` and that `headers` contained the `X-API-Key`?

编辑:我将要测试的代码重构为一个名为funtion_to_be_tested

4

2 回答 2

0

执行此操作的标准方法是运行您的函数,然后对request_history进行断言:

更改示例,因为我总是需要一段时间才能使 pytest 正常工作,但它的工作方式基本相同:

import requests
import requests_mock

def funtion_to_be_tested():
    requests.put(
        headers={'X-API-Key': 'api_key'},
        url=url,
        params={'param1': 'foo'},
        data='This is the data'
    )

with requests_mock.mock() as m:
    url = 'http://example.com/upload'
    m.put(url, text='ok')
    funtion_to_be_tested()

    assert m.last_request.headers['X-API-Key'] == 'api_key'
    assert m.last_request.text == 'This is the data'
于 2020-12-15T03:52:09.617 回答
0

如果您只想检查正在使用的方法,可以通过验证发送的请求来检查。

def test_upload(requests_mock: Any):
    url = 'http://example.com/upload'
    requests_mock.put(url, text='ok')
    r = requests.put(
        headers={'X-API-Key': 'api_key'},
        url=url,
        params={'param1': 'foo'},
        data='This is the data'
    )
    print(r.request.method)  # Prints PUT/POST 
    print(r.request.headers) # Prints your headers sent
    print(r.request.body)    # Prints your data sent

如果您还想检查其他参数,我已经在上面的代码中包含了请求标头/正文。

于 2020-02-13T07:59:08.680 回答