2

I have problems with understanding mock library in python. Here is example: A have two files test.py and another.py

test.py

#!
from mock import patch
from another import C


class A(object):
    def method(self):
        return 2


@patch('another.C')
@patch('test.A')
class TestB(object):

    def test1(self, mA, mC):
        print mA, A
        print mC, C

another.py

class C(object):

    def a(self):
        return 3

So, question is "Why A have in output:

<MagicMock name='A' id='13985040'> <MagicMock name='A' id='13985040'>
<MagicMock name='C' id='13993936'> <class 'another.C'>

Why class from another.py can't be patched? In my case I have heavy function to test, and it imports classes from other files. So I cant understand how to them right.

Thanks

1 Answer 1

2

With the Python mock library you always patch (mock) the function or class in the location that you are actually using it.

Since you are importing 'C' into 'test' and using it there you would patch it like this:

@patch('test.C')
@patch('test.A')
class TestB(object):

    def test1(self, mA, mC):
        print mA, A
        print mC, C

Which will give you output like this:

<MagicMock name='A' id='3070076204'> <MagicMock name='A' id='3070076204'>
<MagicMock name='C' id='3070084940'> <MagicMock name='C' id='3070084940'>

You can mock any class, method, or function that you want. But You need to mock the object in the location that it is actually being used.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.