The statement that __init__ was called with the correct arguments

I use python mocks to claim that a specific object was created with the correct arguments. This is what my code looks like:

class Installer:
    def __init__(foo, bar, version):
        # Init stuff
        pass
    def __enter__(self):
        return self

    def __exit__(self, type, value, tb):
        # cleanup
        pass

    def install(self):
        # Install stuff
        pass

class Deployer:
    def deploy(self):
        with Installer('foo', 'bar', 1) as installer:
            installer.install()

Now I want to claim that it installerwas created with the right arguments. This is the code that I still have:

class DeployerTest(unittest.TestCase):
    @patch('Installer', autospec=True)
    def testInstaller(self, mock_installer):
        deployer = Deployer()
        deployer.deploy()

        # Can't do this :-(
        mock_installer.__init__.assert_called_once_with('foo', 'bar', 1)

This is the error I get:

  File "test_deployment.py", line .., in testInstaller
    mock_installer.__init__.assert_called_once_with('foo', 'bar', 1)
AttributeError: 'function' object has no attribute 'assert_called_once_with'

Here is a fixed code (call it test.py). Thank you all!

import unittest
from mock import patch

class Installer:
    def __init__(self, foo, bar, version):
        # Init stuff
        pass

    def __enter__(self):
        return self

    def __exit__(self, type, value, tb):
        # cleanup
        pass

    def install(self):
        # Install stuff
        pass

class Deployer:
    def deploy(self):
        with Installer('foo', 'bar', 1) as installer:
            installer.install()

class DeployerTest(unittest.TestCase):
    @patch('tests.test.Installer', autospec=True)
    def testInstaller(self, mock_installer):
        deployer = Deployer()
        deployer.deploy()

        # Can't do this :-(
        # mock_installer.__init__.assert_called_once_with('foo', 'bar', 1)

        # Try this instead
        mock_installer.assert_called_once_with('foo', 'bar', 1)
+4
source share
2 answers

, , , , . , , , , Installer Mock.

, Installer() , , Mock().

, , , mock_installer, mock_installer.__init__.:

mock_installer.assert_called_once_with('foo', 'bar', 1)

:

class DeployerTest(unittest.TestCase):

    @patch('Installer', autospec=True)
    def testInstaller(self, mock_installer):
        deployer = Deployer()
        deployer.deploy()

        mock_installer.assert_called_once_with('foo', 'bar', 1)

, , , , , __enter__, :

mock_obj :

mock_obj = mock_installer.return_value

, , __enter__(). , , .

, , :

mock_obj.__enter__().install.assert_called_once_with()
+3

, Installer(...) Installer.__init__ ; , Installer - type, type.__call__ , Installer(),

type.__call__(Installer, ...)

Installer.__new__(Installer, ...), x Installer.__init__ .

, , , Installer, type, . Installer(...) - , :

mock_installer.assert_called_once_with('foo', 'bar', 1)
+2

All Articles