![]() |
Mock obj - How to call the side_effect every time during the run? - Printable Version +- Python Forum (https://python-forum.io) +-- Forum: Python Coding (https://python-forum.io/forum-7.html) +--- Forum: General Coding Help (https://python-forum.io/forum-8.html) +--- Thread: Mock obj - How to call the side_effect every time during the run? (/thread-36564.html) |
Mock obj - How to call the side_effect every time during the run? - pythonisbae - Mar-05-2022 I need to mock an object with a bunch of methods. For all except one Mock() is perfect for me. But for one of the methods, I actually need to call a function whenever the method is called during the run. Basically, I am doing some basic threading, so for my code to work, I can't give it the return values manually before the run. The function has to be called during the run. m = Mock() m.meth.side_effect = foo()When I do this, as expected, it calls
foo() at the start, and uses that value permanentlySo, I would like it such that whenever during the run -
m.meth is called -
foo() is called (and value returned)
RE: Mock obj - How to call the side_effect every time during the run? - ndc85430 - Mar-05-2022 Don't call the function, because by doing so you assign its return value to side_effect . Instead, assign the function itself (i.e. drop the parens), so that it can be called by the mock. See the docs, but generally understand that functions can be passed around and assigned. This is very useful.By the way, do you really need to use a mock? It could be a bad idea, but you've not shown the rest of the code. Another kind of test double may be more appropriate. RE: Mock obj - How to call the side_effect every time during the run? - deanhystad - Mar-05-2022 # this m.meth.side_effect = foo # not this m.meth.side_effect = foo() RE: Mock obj - How to call the side_effect every time during the run? - pythonisbae - Mar-06-2022 Thank you! (Mar-05-2022, 10:12 PM)deanhystad Wrote:# this m.meth.side_effect = foo # not this m.meth.side_effect = foo() |