如何模拟在类中使用request.get的方法? [英] How do I mock a method that uses requests.get in my class?

查看:94
本文介绍了如何模拟在类中使用request.get的方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试为我的班级创建一些单元测试.我想模拟这些,以免耗尽运行这些测试的API配额.我有多个测试用例将调用fetch方法,并且根据传递的URL,我将获得不同的结果.

I'm attempting to create a few unit tests for my class. I want to mock these, so that I don't burn through my API quota running some of these tests. I have multiple test cases that will call the fetch method, and depending on the passed URL I'll get different results back.

我的 example 类如下:

import requests
class ExampleAPI(object):
    def fetch(self, url, params=None, key=None, token=None, **kwargs):
        return requests.get(url).json() # Returns a JSON string

教程看着显示我可以做这样的事情:

The tutorial I'm looking at shows that I can do something like this:

import unittest
from mock import patch

def fake_fetch_test_one(url):
    ...

class TestExampleAPI(unittest.TestCase):
    @patch('mymodule.ExampleAPI.fetch', fake_fetch_test_one)
    def test_fetch(self):
        e = ExampleAPI()
        self.assertEqual(e.fetch('http://my.api.url.example.com'), """{'result': 'True'}""")

但是,执行此操作时,出现错误消息:

When I do this, though, I get an error that says:

TypeError: fake_fetch_test_one() takes exactly 1 argument (3 given)

模拟类中的方法中的requests.get调用的正确方法是什么?我需要能够更改每个测试的模拟响应,因为不同的URL可以提供不同的响应类型.

What is the proper way to mock a requests.get call that is in a method in my class? I'll need the ability to change the mock'd response per test, because different URLs can provide different response types.

推荐答案

您的虚假获取需要接受与原始伪造相同的参数:

Your fake fetch needs to accept the same arguments as the original:

def fake_fetch(self, url, params=None, key=None, token=None, **kwargs):

请注意,最好只模拟外部接口,这意味着让fetch调用requests.get(或者至少认为它是requests.get):

Note that it's better to mock just the external interface, which means letting fetch call requests.get (or at least, what it thinks is requests.get):

@patch('mymodule.requests.get')
def test_fetch(self, fake_get):
    # It would probably be better to just construct
    # a valid fake response object whose `json` method
    # would return the right thing, but this is a easier
    # for demonstration purposes. I'm assuming nothing else
    # is done with the response.
    expected = {"result": "True"}
    fake_get.return_value.json.return_value = expected
    e = ExampleAPI()
    self.assertEqual(e.fetch('http://my.api.url.example.com'), expected)

这篇关于如何模拟在类中使用request.get的方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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