模拟类时如何区分静态方法和实例方法?

2024-09-30 02:37:00 发布

您现在位置:Python中文网/ 问答频道 /正文

我在生产中遇到了一个bug,尽管它应该通过单元测试来测试

class Stage2TaskView(MethodView):
    def post(self):
        json_data = json.loads(request.data)
        news_url_string = json_data['news_url_string']
        OpenCalais().generate_tags_for_news(news_url_string) // ?
        return "", 201

以前是静态的:

OpenCalais.generate_tags_for_news(news_url_string)

但后来我改变了方法,删除了静态装饰程序。 但我忘了把那行改成

OpenCalais().generate_tags_for_news(news_url_string)

不过,测试没有看到。我以后如何测试这个

@mock.patch('news.opencalais.opencalais.OpenCalais.generate_tags_for_news')
def test_url_stage2_points_to_correct_class(self, mo):
    rv = self.client.post('/worker/stage-2', data=json.dumps({'news_url_string': 'x'}))
    self.assertEqual(rv.status_code, 201)

Tags: selfjsonurlfordatastringdeftags
1条回答
网友
1楼 · 发布于 2024-09-30 02:37:00

Autospeccing是你的油炸!在patch decorator中使用autospec=True将检查完整的签名:

class A():
    def no_static_method(self):
        pass

with patch(__name__+'.A.no_static_method', autospec=True):
    A.no_static_method()

将引发异常:

Traceback (most recent call last):
  File "/home/damico/PycharmProjects/mock_import/autospec.py", line 9, in <module>
    A.no_static_method()
TypeError: unbound method no_static_method() must be called with A instance as first argument (got nothing instead)

相关问题 更多 >

    热门问题