Python Mock - How to get MagicMock return as if it were a regular method

For example:

import mock

class MyClass(object):
    def foo(self, x, y, z):
        return (x, y, z)


class TestMyClass(TestCase)
    @mock.patch('MyClass')
    def TestMyClass(self, MyClassMock):
        foo_mock = MyClassMock.foo()

        self.assertEquals((x, y, z), foo_mock)

So, the real question is: how to get the return of this test to get this, <MagicMock name='MyClass.foo()' id='191728464'>or how to handle this MagicMock object to get the return of this test, which should be a tuple containing 3 elements and nothing more or less?

Any suggestion, any idea, any arguments would be welcome. Thanks in advance!

+4
source share
1 answer

If you are trying to check if it works MyClass.foo()correctly, you should not scoff at it.

Mocking - ; foo , some_module.bar(), some_module.bar() :

import some_module

class MyClass(object):
    def foo(self, x, y, z):
        result = some_module.bar(x, y, z)
        return result[0] + 2, result[1] * 2, result[2] - 2

class TestMyClass(TestCase):
    @mock.patch('some_module.bar')
    def test_myclass(self, mocked_bar):
        mocked_bar.return_value = (10, 20, 30)

        mc = MyClass()

        # calling MyClass.foo returns a result based on bar()
        self.assertEquals(mc.foo('spam', 'ham', 'eggs'),
            (12, 40, 28))
        # some_class.bar() was called with the original arguments
        mocked_bar.assert_called_with('spam', 'ham', 'eggs')

mocked_bar.return_value , , mocked some_module.bar(). -- bar(), .

return_value, MagicMock(), , , mocked_bar, ..

+4

Source: https://habr.com/ru/post/1525671/


All Articles