pytest模拟一个eval导入函数

时间:2018-11-02 17:17:48

标签: python mocking pytest monkeypatching

不确定这是否可行,但是是否可以模拟导入的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'

1 个答案:

答案 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'