Search code examples
python-3.xpytestmonkeypatching

What does "use setattr [...] with target being a dotted import string " mean?


I'm starting to learn mocking, I tried to build the example below (Python 3.8) but I get an error I don't understand:

TypeError : use setattr(target, name, value) or setattr(target, value) with target being a dotted import string
import random
 
def division():
    nb = random.randrange(0, 2)
    return 100 / nb    # this is on purpose ;-)
 
def function_to_be_tested():
    result = division()
    return f"This is the result :{result}"
 
def test_function_to_be_tested_returns_str(monkeypatch):
    def mockreturn():
        return 50.0
    monkeypatch.setattr(division, mockreturn)    
    assert isinstance(function_to_be_tested(), str)

How should I write it?


Solution

  • You can access the current module for example via the sys.modules dict. The module name is set in __name__, so you can write:

    import sys
    
    def test_function_to_be_tested_returns_str(monkeypatch):
        def mockreturn():
            return 50.0
    
        monkeypatch.setattr(sys.modules[__name__], 'division', mockreturn)
        assert function_to_be_tested() == "This is the result :50.0"
    

    EDIT: This is actually the answer to the follow up question in the comments -- how do access the current module. The actual question has been answered by @jonrsharpe by linking to the documentation.