[Pytest-commit] Issue #603: monkeypatch does not work on already-imported function (hpk42/pytest)

Anatoly Bubenkov bubenkoff at gmail.com
Tue Sep 30 17:18:22 CEST 2014


monkeypatch receives the object, not the dotted name of the object to mock
so:

```
#!python

from project import bar

def test_foo(monkeypatch):
    monkeypatch.setattr(bar, 'zoo', lambda x: 0)
    assert foo() == 0

```

On 30 September 2014 17:16, Marco Chomut <issues-reply at bitbucket.org> wrote:

> New issue 603: monkeypatch does not work on already-imported function
>
> https://bitbucket.org/hpk42/pytest/issue/603/monkeypatch-does-not-work-on-already
>
> Marco Chomut:
>
> Given the following tests file:
>
> ```
> #!python
>
> from project.main import foo
>
> def test_foo(monkeypatch):
>     monkeypatch.setattr('project.bar.zoo', lambda x: 0)
>     assert foo() == 0
>
> ```
>
> And this system under test:
>
> ```
> #!python
>
> # project/main.py
>
> from project.bar import zoo
>
> def foo():
>     return zoo('lion')
>
> ```
>
> ```
> #!python
>
> # project/bar.py
>
> def zoo(animal):
>     if animal == 'lion':
>         return 7
>
> ```
>
> Then the ``zoo`` that's already been imported in ``main.py`` remains
> unpatched. Moving the imports around to be local to the test function would
> fix the problem, unless ``main.py`` is imported by other files at any point
> during the test suite running. Alternatively, if ``main.py`` instead does
> ``import project.bar`` and calls its dependency with
> ``project.bar.zoo('lion')``, then the test passes again. But this is
> cumbersome and difficult to enforce across an entire project.
>
>
> _______________________________________________
> pytest-commit mailing list
> pytest-commit at python.org
> https://mail.python.org/mailman/listinfo/pytest-commit
>



-- 
Anatoly Bubenkov
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/pytest-commit/attachments/20140930/c9cdca73/attachment.html>


More information about the pytest-commit mailing list