【发布时间】:2017-10-04 14:58:09
【问题描述】:
我正在使用 unittest.mock 模拟一个 API。我的界面是一个在幕后使用requests 的类。所以我正在做这样的事情:
@pytest.fixture
def mocked_api_and_requests():
with mock.patch('my.thing.requests') as mock_requests:
mock_requests.post.return_value = good_credentials
api = MyApi(some='values', that='are defaults')
yield api, mock_requests
def test_my_thing_one(mocked_api_and_requests):
api, mocked_requests = mocked_api_and_requests
... # some assertion or another
def test_my_thing_two(mocked_api_and_requests):
api, mocked_requests = mocked_api_and_requests
... # some other assertions that are different
正如您可能看到的那样,我在这两个测试中的第一行都是相同的,闻起来对我来说还不够干。
我希望能够做类似的事情:
def test_my_thing_one(mock_requests, logged_in_api):
mock_requests.get.return_value = ...
不必解压这些值,但我不确定是否有办法使用 pytest 可靠地做到这一点。如果它在documentation for fixtures 中,我完全错过了它。但确实感觉应该有一种正确的方法来做我想做的事情。
有什么想法吗?如果我需要走那条路,我愿意使用class TestGivenLoggedInApiAndMockRequests: ...。我只是不太确定这里的合适模式是什么。
【问题讨论】:
-
这里,
logged_in_api代表在夹具mocked_api_and_requests中定义的api? -
@ChandaKorat 是的 - 基本上将参数作为单独的参数而不是一个并将它们解包。