__name__ ==“__main___”下的Python补丁/模拟

fnatzsnv  于 2023-03-11  发布在  Python
关注(0)|答案(1)|浏览(94)

我有一个名为w.py的文件,在__name__ == "__main__"下,我想修补MyAPI,运行python w.py显示修补根本不起作用。patch('common.apis.MyAPI', mock_api)是否正确使用?

from common.apis import MyAPI

class Worker:
    def __init__(self):
        companies = MyAPI.all()
        raise Exception(companies)

if __name__ == "__main__":
    from mock import patch, Mock

    mock_api = Mock()
    mock_api.all.return_value = {'dummy': 'dummy'}

    with patch('common.apis.MyAPI', mock_api):
        Worker()
f2uvfpb9

f2uvfpb91#

IIUC你想给MyAPI.all打补丁,让它返回{'dummy': 'dummy'},你可以这样做:

from common.apis import MyAPI

class Worker:
    def __init__(self):
        companies = MyAPI.all()
        raise Exception(companies)

if __name__ == "__main__":
    from unittest.mock import patch, Mock

    def all_dummy():
        return {'dummy': 'dummy'}

    with patch.object(MyAPI, 'all', all_dummy):
        Worker()

相关问题