Question:
How to mock a constant value in Python?

Solution:

To mock a constant value in python you need to set the CONST attribute of the module object mod1.mod2 to a different object. It does not affect any existing names referencing the original mod1.mod2.CONST object.


When utils.py does:

from mod1.mod2 import CONST


it creates a name CONST in the namespace of the mod1.mod2.utils module, referencing the object -1 currently referenced by the mod1.mod2.CONST name.


And when test_mod_function then does:

mock = mocker.patch("mod1.mod2.CONST")


it modifies mod1.mod2 such that its CONST attribute now references a Mock object, while the CONST name in mod1.mod2.utils continues to reference the object -1, which is why setting mock.return_value does not affect the outcome of mod_function.


To properly test mod_function with a mock CONST you can either patch CONST in the namespace where mod_function is defined:

mock = mocker.patch("mod1.mod2.utils.CONST")


or you can defer the import of mod1.mod2.utils until mod1.mod2.CONST has been patched:

def test_mod_function(mocker):

    mock = mocker.patch("mod1.mod2.CONST")

    mock.return_value = 1000

    from mod1.mod2.utils import mod_function

    mod_function()


Answered by: >blhsing

Credit:> StackOverflow


Suggested blogs:

>How to access the state using Redux RTK in the React Native app?

>How to Build a Python GUI Application With WX Python

>How to Build a RESTful API Using Node Express and MongoDB- Part 1

>How to build an Electron application from scratch?

>How to build interactive_graphviz in Python

>How to change the project in GCP using CLI command

>How to create a line animation in Python?


Submit
0 Answers