On 16.09.2017 20:06, Paul Hammant wrote:
>
>
> foo.py:
>
> import os
> def my_mocked_os_system(*args, **kwargs):
> print('a mockery')
> os.system = my_mocked_os_system
>
>
> bar.py:
>
> import os
> os.system("echo bar")
>
> import foo
> os.system("echo foo")
>
>
> Then:
>
> $ PYTHONPATH=. python bar.py
> bar
> a mockery
>
>
> I've spent the last 5 hours looking at mock decorators for Python (and
> MagicMock and stackoverflow and blogs). I can't get it working on my
> own - I'm not experienced enough with Python. Specifically, I can't
> do it _less_ lines of code and have it the correct Pythonic way. I
> need help from someone that's prepared to remote pair on it.
Why are you complicating your life with trying to implement complex
decorators? Python decorators are _hard_. Just replace the default
functions in the module in the testcase setup method and restore them in
the teardown method. Or write a simple context manager and use it in
your test case, e.g., like this:
def test_foo():
with mock_my_stuff():
# code for testing foo goes here
pass
Now all you have to do is write the mock_my_stuff() function, which
should return a context manager object that injects the mock functions
into the module in its __enter__() method an restores them in the
__exit__() method. This standard module will help make this even
simpler: https://docs.python.org/2/library/contextlib.html
-- Brane
Received on 2017-09-16 21:36:33 CEST