[TIP] pytest: mocking module imports

Zhi An Ng ngzhian at gmail.com
Fri Apr 17 10:47:33 PDT 2015


Hi,
I believe you can mock out ClassY as such:

@patch('liB.ClassY')
def test_unit_test(self):
    stuff


More info:
https://docs.python.org/3.3/library/unittest.mock.html#quick-guide

Best,
Zhi An

On Fri, Apr 17, 2015 at 1:35 PM, Vinicius Kwiecien Ruoso <
vinicius.ruoso at gmail.com> wrote:

> Hi!
>
> I've been using pytest and it is great. There is just one thing that
> I'm not satisfied with the way I've implemented, that is module level
> moking.
>
> My scenario is as follows: libA and libB where libA depends on libB
> (uses class definition as superclass). Let's assume this code:
>
> <libA.py>
> from libB import ClassY
>
> class ClassX(ClassY):
>    pass
>
> <libB.py>
> class ClassY(object):
>    pass
>
> Those modules live on different packages/repositories. LibB can be
> unit tested just fine, but we need to mock libB module to allow libA
> to be unit tested (libB won't be available in the moment of the test).
>
> In a conftest.py file in the tests directory of libA, I've managed to
> mock the module import by mocking sys.modules dictionary, but I did
> this at the module (global) scope. I was not able to do it with any
> hook (like pytest_configure), because the tests files are imported
> before the hook is called. So a test_libA.py file with "import libA"
> would cause the test to fail.
>
> Am I doing something wrong or is this really the way to go?
>
> Greetings,
> Vinicius
>
> _______________________________________________
> testing-in-python mailing list
> testing-in-python at lists.idyll.org
> http://lists.idyll.org/listinfo/testing-in-python
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://lists.idyll.org/pipermail/testing-in-python/attachments/20150417/d6cf352f/attachment.html>


More information about the testing-in-python mailing list