Flask 对于在一个视图中多次使用的函数,是否可以将参数传递给monkeypatch.setattr中的函数?
我的web应用程序对Spotify进行API调用。在我的一个烧瓶视图中,我对不同的端点使用相同的方法。具体而言:Flask 对于在一个视图中多次使用的函数,是否可以将参数传递给monkeypatch.setattr中的函数?,flask,pytest,monkeypatching,Flask,Pytest,Monkeypatching,我的web应用程序对Spotify进行API调用。在我的一个烧瓶视图中,我对不同的端点使用相同的方法。具体而言: sh = SpotifyHelper() ... @bp.route('/profile', methods=['GET', 'POST']) @login_required def profile(): ... profile = sh.get_data(header, 'profile_endpoint') ... playlist = sh.get_da
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呢?是否有某种方法将端点参数传递给monkeypatch.setattr(sh,“获取数据”,mock_u???
?感谢您发布此答案。虽然这段代码可能会回答这个问题,但您是否可以在您的帖子中添加一个解释,说明它为什么/如何工作?这可以帮助未来的读者学习和应用你的答案。当你加入一个解释时,你也更有可能得到积极的反馈(向上投票)。真的没有什么需要解释的:副作用是可接受的,并且在调用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)