python - Pytest 如何模拟 requests库中的Response对象?

查看:319
本文介绍了python - Pytest 如何模拟 requests库中的Response对象?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

问 题

请问如何在 Pytest 框架中模拟requests库中的Response对象?

涉及到的主体代码如下:

def get_address(phone):
    url = 'http://www.ip138.com:8080/search.asp?action=mobile&mobile=%s' % (phone)
    r = requests.get(url)
    r.encoding = 'GBK'
    soup = BeautifulSoup(r.text, 'html.parser')
    try:
        data = soup.find_all('td')[6].text.split('\xa0')
    except IndexError:
        data = False
    print(data)
    return data

测试代码如下:

correct_response = requests.get('http://www.ip138.com:8080/search.asp?action=mobile&mobile=13012345678')
wrong_response = requests.get('http://www.ip138.com:8080/search.asp?action=mobile&mobile=110')

def test_get_address(monkeypatch):
    def test1(phone):
        return correct_response

    def test2(phone):
        return wrong_response

    monkeypatch.setattr('requests.get', test1)
    assert cli.get_address('13012345678') == ['重庆', '']
    monkeypatch.setattr('requests.get', test2)
    assert cli.get_address('110') == False

我希望可以构造一个Response对象,并在test函数中直接返回,但是Response对象中的text函数是无法修改的。

解决方案

requests.models

很简单, 初始化一个实例, 设置 Response.content 属性就好了. text, json, file 等属性都是由 content 通过处理得到的, 也就是说 content 才是响应的正文部分.

看看源代码就啥都知道了

这篇关于python - Pytest 如何模拟 requests库中的Response对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆