Pytest 模拟 eval 导入函数

Pytest mocking an eval imported function

不确定这是否可能,但有没有办法模拟 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'

使用monkeypatch夹具:

# test_a.py

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