T
T
tytar2016-03-28 17:22:30
Python
tytar, 2016-03-28 17:22:30

How to patch a class that is called in __init__ of another class?

Actually a question.
How to patch a class that is called in __init__ of another class?
Since now, in a very similar code, the substitution does not occur. Perhaps I misunderstand how @patch works

class B(object):

    def some1(self):
        print 'some 1'


class C(object):

    def some2(self):
        print 'some 2'


class A(object):

    def __init__(self):
        self.b = B()
        self.c = C()

    def just_do_it(self):
        print 'Hello'


class BMock(object):
    pass


class CMock(object):
    pass


class ATestCase(TestCase):

    @patch('B', BMock)  # lambda *args, **kwargs: BMock()
    @patch('C', CMock)  # lambda *args, **kwargs: CMock()
    def test_success_just_do_it(self):
        a = A()
        a.just_do_it()

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Andy_U, 2016-03-28
@tytar

If you wanted to test such code, then the solution (for Python 2.7.11) is below.

import unittest
import mock


class B(object):
    def some1(self):
        print 'some 1'


class C(object):
    def some2(self):
        print 'some 2'


class A(object):
    def __init__(self):
        self.b = B()
        self.c = C()

    def just_do_it(self):
        print 'Hello'
        self.b.some1()
        self.c.some2()


class BMock(object):
    def some1(self):
        print 'mock.some 1'


class CMock(object):
    def some2(self):
        print 'mock.some 2'


class ATestCase(unittest.TestCase):

    @mock.patch('main.B')
    @mock.patch('main.C')
    def test_success_just_do_it(self, c, b):
        b.side_effect = BMock
        c.side_effect = CMock
        a = A()
        a.just_do_it()

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question