lundi 29 février 2016

python unittest mock can't handle partially qualified name

If I have two files with the following contents:

test_helper.py:

class Installer:
    def __init__(self, foo, bar, version):
        # Init stuff
        raise Exception('If we're here, mock didn't work')

    def __enter__(self):
        return self

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

    def install(self):
        # Install stuff
        raise Exception('If we're here, mock didn't work')

And test.py:

import unittest
from mock import patch
from test_helper import Installer

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

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

The code above doesn't test correctly. The mock is not applied properly:

  File "/Library/Python/2.7/site-packages/http://ift.tt/1LRgPTF", line 947, in assert_called_once_with
    raise AssertionError(msg)
AssertionError: Expected 'Installer' to be called once. Called 0 times.

If I make the following changes in test.py:

  1. Change from test_helper import Installer to import test_helper, and
  2. Change with Installer('foo', 'bar', 1) as installer: to with test_helper.Installer('foo', 'bar', 1) as installer:

The code then works. Why does the mock only apply when I use the fully qualified name? Is it supposed to work in the partially-qualified case?

Aucun commentaire:

Enregistrer un commentaire