Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python @patch not working

I am trying to test a method that within it creates an instance of another class, I am attempting to mock the creation of the inner class... That is not working for me. I tried replicating the problem to a simplified case - and still no go. Here is the simplified case:

I have a directory named pymock with a __init__.py in it. Other than that there are these 3 files:

foo.py

#!/usr/bin/python
class Foo(object):
    def foo1(self):
        return 1

goo.py

#!/usr/bin/python
from foo import Foo


class Goo(object):
    def goo1(self):
        f = Foo()
        return f.foo1()

goo_test.py

#!/usr/bin/python
from mock import patch, Mock
from nose.tools import assert_equal

from goo import Goo


class TestGoo(object):
    def setup(self):
        self.goo = Goo()

    @patch('pymock.foo.Foo', autospec=True)
    def test_goo1(self, foo1_mock):
        foo_instance = Mock()
        foo1_mock.return_value = foo_instance
        foo_instance.foo1.return_value = 11
        assert_equal(11, self.goo.goo1())

Thanks in advance!

like image 872
Uri Shalit Avatar asked Sep 08 '15 15:09

Uri Shalit


People also ask

Why patch is not working?

A common reason for this error is because the back-end data source is a table but there is no primary key or is read-only. Ensure that the input to the Patch function is a collection. Ensure that the back-end data source table is writable and has a primary key.

What is @patch in Python?

This, along with its subclasses, will meet most Python mocking needs that you will face in your tests. The library also provides a function, called patch() , which replaces the real objects in your code with Mock instances.

What is the difference between mock and MagicMock?

So what is the difference between them? MagicMock is a subclass of Mock . It contains all magic methods pre-created and ready to use (e.g. __str__ , __len__ , etc.). Therefore, you should use MagicMock when you need magic methods, and Mock if you don't need them.

What is Side_effect in mock Python?

side_effect: A function to be called whenever the Mock is called. See the side_effect attribute. Useful for raising exceptions or dynamically changing return values. The function is called with the same arguments as the mock, and unless it returns DEFAULT , the return value of this function is used as the return value.


1 Answers

You need to patch the name that goo is using.

@patch('pymock.goo.Foo', autospec=True)
like image 143
chepner Avatar answered Oct 25 '22 19:10

chepner