Search code examples
pythonmockingpytestmonkeypatching

Pytest mocking an eval imported function


Not sure if this is even possible but is there a way to mock an eval imported function?

For example:

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'

Solution

  • Using monkeypatch fixture:

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