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

时间:2015-03-05 21:30:04

标签: python unit-testing mocking

我遇到了一个生产中的错误,即使它应该已经过单元测试的测试。

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)

1 个答案:

答案 0 :(得分:2)

Autospeccing是你炒的!在补丁装饰器中使用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)
相关问题