使用pytest运行测试时,unittest.mock不起作用

时间:2017-04-16 13:34:00

标签: python mocking flask-sqlalchemy pytest python-unittest.mock

我有以下项目结构:

$('#linkAbhaeghar').mouseover(function(e) {
    $('#abhaegharMap').mouseover();
}).mouseout(function(e) {
    $('#abhaegharMap').mouseout();
}).click(function(e) {
    e.preventDefault(); 
});

tests/ └── messenger/ └── messaging_test.py app/ ├── __init__.py ├── models.py └── messenger/ ├── __init__.py └── messaging.py 模块中,有一个函数messaging.py,其中包含以下几行:

send_schedule

我试图修补talks = models.Talk.query.all() raise ValueError(str(talks)) # the debug output 电话。在models.Talk.query.all()内,有以下测试:

messaging_test.py

当我使用@patch('app.models.Talk.query.all') def test_send_schedule(self, all_query_mock): all_query_mock.return_value = [] for talk_id in range(1, 6): talk_mock = MagicMock(id=talk_id, title=str(talk_id), speaker_facebook_id=1) all_query_mock.return_value.append(talk_mock) with vcr.use_cassette('vcr_cassettes/send_schedule.yaml'): response = messaging.send_schedule(self.access_token, self.user_id) self.assertTrue('recipient_id' in response) self.assertTrue('message_id' in response) self.assertEqual(response['recipient_id'], self.user_id) 命令运行测试时,python3 -m pytest tests/messenger/messaging_test.py会输出一个空列表,表示该呼叫未被修补。你能建议解决这个问题吗?

我该怎么做才能解决这个问题:

  • 阅读"Where to patch"段文档。这让我怀疑ValueError以一种奇怪的方式运行我的测试。
  • 尝试使用pytest但未能弄清楚如何将其与pytest-mock一起使用。

1 个答案:

答案 0 :(得分:0)

好的,我显然对此做了一个糟糕的研究。 pytest模块没有问题。为了解决问题,我需要修补app.models.Talk,而不是奇怪的app.models.Talk.query.all。在修补了课程后,我只是添加了我需要的属性:

    @patch('app.models.Talk')
def test_send_schedule(self, talk_class_mock):
    talk_mocks = []
    for talk_id in range(1, 6):
        talk_mock = MagicMock(id=talk_id, title=str(talk_id), speaker_facebook_id=1)
        talk_mocks.append(talk_mock)
    query_mock = MagicMock(all=MagicMock(return_value=talk_mocks))
    talk_class_mock.query = query_mock
    with vcr.use_cassette('vcr_cassettes/send_schedule.yaml'):
        response = messaging.send_schedule(self.access_token, self.user_id)

    self.assertTrue('recipient_id' in response)
    self.assertTrue('message_id' in response)
    self.assertEqual(response['recipient_id'], self.user_id)