我使用python mocks來聲明一個特定的對象是用正確的參數創建的。這是我的代碼的外觀:斷言__init__被調用了正確的參數
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()
現在,我想斷言,installer
與正確的參數創建。這是我到目前爲止的代碼:
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)
這是錯誤我得到:
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'
這裏是固定的代碼(稱之爲test.py
)。謝謝,所有!
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)
'Installer'應該如何作爲上下文管理器工作? – jonrsharpe
對不起,我急於做一個簡明的例子,我忽略了'Installer'的上下文管理器位。現在填寫 – Srikanth
這不完全相同,但你看看例如http://stackoverflow.com/a/6112456/3001761?請注意,就模擬而言,初始化只是對「mock_installer」本身的調用。 – jonrsharpe