flask - 对于在一个 View 中多次使用的函数,我可以将参数传递给monkeypatch.setattr 中的函数吗?

标签 flask pytest monkeypatching

我的 Web 应用程序对 Spotify 进行 API 调用。在我的一个 Flask View 中,我对不同的端点使用相同的方法。具体来说:

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 响应。当每个 View 仅使用该方法一次时,我已成功完成此操作:
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, "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)

关于flask - 对于在一个 View 中多次使用的函数,我可以将参数传递给monkeypatch.setattr 中的函数吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58922935/

相关文章:

当 pytest 测试失败时,Jenkins 作业失败

python - 无法在 Windows 上使用 Python 模拟操作系统名称

ruby - ruby 会发生冲突吗?

ruby-on-rails - 从 Impressionist Gem in Rails 4 重新打开 Impression 类

Python - 替换套接字库中由另一个库调用的函数,该函数由另一个库调用

python - Flask 应用程序处理请求线程错误?

python - 将安全过滤器应用于连接的 html 字符串

python - pytest中params中fixture的输出

python-3.x - Docker 中的 Flask 无法检测到 FLASK_ENV

python - Flask 比较字符串