[英]unittest.mock doesn't work when tests are run with pytest
我有以下項目結構:
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
命令運行測試時, ValueError
輸出一個空列表,表示該呼叫未打補丁。 您能提出解決辦法嗎?
我做了什么來解決這個問題:
pytest
以一種奇怪的方式運行我的測試。 pytest-mock
但未能弄清楚如何與unittest.TestCase
一起使用。 好的,我顯然對此做了不好的研究。 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)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.