如何在另一个使用pytest调用的方法中模拟函数

我的项目结构如下

myapp
|
 -contrib
   |
   - helpers.py
 - views
   |
   - app_view.py

helpers.py中,我有以下方法

def method(**kwargs) -> int:
    # Some code here
    requests.post(
            url=f"{REMOTE_SERVER}/sc",json=kwargs,timeout=5
        )

app_view.py中,我有以下实现。我正在线程内调用该方法,我需要使用pytest对其进行模拟,以检查它是否被调用一次并使用一定数量的参数调用。


import myapp.contrib.helpers import method


class Score(MethodView):


    @prepare_req
    def post(self,**kwargs):
        """
        Post Score
        """
        response_data = dict()
        # Some logic here
        self.filter_score(kwargs)

        return jsonify(response_data)

    def filter_score(self,**kwargs)
        thread = threading.Thread(target=method,kwargs=event_data)
        thread.start()

我正在使用pytest来模拟method(),如下所示。

def test_score(client,mocker): 
    url = "sc/1.1/score"
    patched_method = mocker.patch(
        "myapp.contrib.helpers.method"
    )

    client.post(url,json=issue_voucher_post_data)
    patched_method.assert_called_once() # <- this is getting false and not mocking the method

也尝试了以下内容,但无法正确修补

patched_method = mocker.patch(
        "myapp.views.app_view.method"
    )

但是它将调用相应的视图

如何使用pytest在视图中模拟在线程内使用的函数,该函数在另一个模块中可用 ?

zhangyeah19887 回答:如何在另一个使用pytest调用的方法中模拟函数

暂时没有好的解决方案,如果你有好的解决方案,请发邮件至:iooj@foxmail.com
本文链接:https://www.f2er.com/3142050.html

大家都在问