不确定这是否可行,但是是否可以模拟导入的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'
test_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'
答案 0 :(得分:1)
使用monkeypatch
固定装置:
# test_a.py
def test_code(monkeypatch):
monkeypatch.setattr('b.mockME', lambda: 'mocked code')
assert_me = a.code()
assert assert_me == 'mocked code'