对于在一个视图中多次使用的函数,我可以向monkeypatch.setattr中的函数传递参数吗



我的web应用程序对Spotify进行API调用。在我的一个Flask视图中,我对不同的端点使用相同的方法。具体而言:

sh = SpotifyHelper()
...
@bp.route('/profile', methods=['GET', 'POST'])
@login_required
def profile():
...
profile = sh.get_data(header, 'profile_endpoint')
...
playlist = sh.get_data(header, 'playlist_endpoint')
...
# There are 3 more like this to different endpoints -- history, top_artists, top_tracks
...
return render_template(
'profile.html',
playlists=playlists['items'],
history=history['items'],
...
)

我不想在测试期间调用API,所以我编写了一个mock.json来替换API的json响应。当该方法每次视图只使用一次时,我已经成功地做到了这一点:

class MockResponse:
@staticmethod
def profile_response():
with open(path + '/music_app/static/JSON/mock.json') as f:
response = json.load(f)
return response
@pytest.fixture
def mock_profile(monkeypatch):
def mock_json(*args, **kwargs):
return MockResponse.profile_response()
monkeypatch.setattr(sh, "get_data", mock_json)

我的问题是,我需要将get_data调用到具有不同响应的不同端点。我的mock.json是这样写的:

{'playlists': {'items': [# List of playlist data]},
'history': {'items': [# List of playlist data]},
...

因此,对于每个API端点,我都需要类似的东西

playlists = mock_json['playlists']
history = mock_json['history']

我可以写mock_playlists()mock_history()等,但如何为每个写一个猴痘?有没有办法将端点参数传递给monkeypatch.setattr(sh, "get_data", mock_???)

from unittest.mock import MagicMock

#other code...
mocked_response = MagicMock(side_effect=[
# write it in the order of calls you need
profile_responce_1, profile_response_2 ... profile_response_n
])
monkeypatch.setattr(sh, "get_data", mocked_response)

相关内容

最新更新