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

How to make a distinction between static methods and instance methods when mocking a class?

我在生产中遇到了一个错误,尽管它应该已经通过单元测试进行了测试。

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)

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)