Skip to content

Instantly share code, notes, and snippets.

@tgecho
Created April 5, 2012 16:27
Show Gist options
  • Save tgecho/2312331 to your computer and use it in GitHub Desktop.
Save tgecho/2312331 to your computer and use it in GitHub Desktop.
Brainstormed mock for testing salt states and modules
class Mock(object):
def __init__(self):
history = []
unmet_expectations = []
def __call__(self, func, *args, **kwargs):
"""
Here we can grab a copy of the actual function/state and insert
the Mock object as __salt__ so the usual calls to
__salt__['mod.func']() get intercepted and handled by the mock.
"""
def __getitem__(self, cmd_name):
def mock_function(*args, **kwargs):
cmd = {
'cmd': cmd_name,
'args': args,
'kwargs': kwargs
}
# Find instances of the given cmd in expectations
candidates = [e for e in self.unmet_expectations if e == cmd]
# Save some history for future examination
self.history.append(cmd)
# This will raise an error if an unexpected command is received
index = self.unmet_expectations.index(candidates[0])
expectation = self.unmet_expectations.pop(index)
# Return the specified reply
return expectation['reply']
return mock_function
def expect(self, cmd, args, kwargs, reply):
self.unmet_expectations.append({
'cmd': cmd,
'args': args,
'kwargs': kwargs,
'reply': reply,
})
class GitTestCase(TestCase):
def test_clone(self):
mock = Mock()
mock.expect('cmd.run',
args=('/path/to/repo',),
reply='Cloning into.... blah blah...'
)
mock('git.clone', '/path/to/repo')
self.assertFalse(mock.unmet_expectations)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment