[TIP] Problem with mock
Ken Hagler
khagler at orange-road.com
Wed Dec 19 12:45:02 PST 2012
I've run into a problem using the mock library. It's probably something obvious, but I just can't see it. I'm testing this:
def __init__(self, buildNum, configFile = "configfile.txt"):
super(DevBuild, self).__init__(buildNum, configFile)
if configFile == "configfile.txt":
self.config.MakeDevBuild()
The superclass's (called Build) __init__ assigns an instance of another class (Config) to the self.config attribute. I don't want to run the real Build.__init__, so I'm attempting to create a mock object which has a config attribute which is another mock, which in turn has a MakeDevBuild attribute which is yet another mock.
Here's the best I could come up with:
class TestInit(TestCase):
def test_init(self):
old_super = __builtin__.super
mock_Config = MagicMock()
mock_Config.MakeDevBuild = MagicMock()
mock_Build = MagicMock()
mock_Build.config = mock_Config
__builtin__.super = mock_Build
# Test with manual configuration
self.testBuild = DevBuild("42", "devconfigfile.txt")
self.assertFalse(mock_Config.MakeDevBuild.called)
# Test with automated configuration
self.testBuild = DevBuild("42")
mock_Config.MakeDevBuild.assert_called_once_with()
__builtin__.super = old_super
However, this produces an error:
Error
Traceback (most recent call last):
File "/Users/khagler/Projects/BuildClass/BuildClass/test_devBuild.py", line 22, in test_init
self.testBuild = DevBuild("42")
File "/Users/khagler/Projects/BuildClass/BuildClass/DevBuild.py", line 39, in __init__
self.config.MakeDevBuild()
AttributeError: 'DevBuild' object has no attribute 'config'
So I've got as far as getting a mock DevBuild object, but the config attribute is missing. Can anyone see what I'm missing?
--
Ken Hagler
| http://www.orange-road.com/ |
| And tho' we are not now that strength which in old days |
| Moved earth and heaven, that which we are, we are --Tennyson |
More information about the testing-in-python
mailing list