gpt4 book ai didi

python - Pytest 模拟 eval 导入函数

转载 作者:行者123 更新时间:2023-12-01 08:51:01 26 4
gpt4 key购买 nike

不确定这是否可能,但有没有办法模拟 eval 导入函数?

例如:

a.py

import b

def code():
me = 'ME'
should_be_changed = eval('b.mock' + me + '()')

return should_be_changed

b.py

def mockME():
return 'Dummy code'

测试_a.py

import a
import pytest
from unittest.mock import patch

def test_code():
#with patch('patch mockME somehow?', return_value='mocked code') as mock_mockME:
assert_me = a.code()
assert assert_me == 'mocked code'

最佳答案

使用monkeypatch固定装置:

# test_a.py

def test_code(monkeypatch):
monkeypatch.setattr('b.mockME', lambda: 'mocked code')
assert_me = a.code()
assert assert_me == 'mocked code'

关于python - Pytest 模拟 eval 导入函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53123153/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com