mardi 7 avril 2015

How to get a Mock to return a dictionary?

I have read the documents regarding this specific issue, however, I have been unable to actually get it to work in my tests.


Here is the unit-test, using py.test: (input is an instance of InputManager )



def test_invalid_menu_glitch_raises_exception(self, input):
''' Test that exception is raised if non-encounter is glitched. '''
def getitem(name):
return mydict[name]

position = 1
table = Mock()
mydict = {'step':1, 'input':None, 'enc':False}

table.getStep.return_value = mydict
table.__getitem__ = Mock(side_effect=getitem)

with pytest.raises(IndexError) as indexerr:
input.glitch(table, position)
assert 'Cannot Glitch a non-encounter.' in indexerr.value


And the code that I want to test is (specifically glitch() and implicitly setInput():



class InputManager(object):
''' Responsible for managing user input. '''
def __init__(self):
pass

def setInput(self, table, position, input):
''' Edits the input in table at table[position]. '''
table.setInput(position, 'G')

def getStep(self, table, position):
''' Returns the step at position. '''
return table.getStep(position)

def glitch(self, table, position):
step_to_glitch = self.getStep(table, position)

if not step_to_glitch['enc']:
raise IndexError('Cannot Glitch a non-encounter.')
self.setInput(table, position, input)


And the error is:



def test_validate_menu_glitch(self, input):
''' Test that menu glitch accepts a valid G input. '''
table = Mock()
position = 1
i = 'G'
> input.glitch(table(), position)

test_input_manager.py:25:
_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _

self = <input_manager.InputManager object at 0x10a0d3dd0>
table = <Mock name='mock()' id='4463606800'>, position = 1

def glitch(self, table, position):
step_to_glitch = self.getStep(table, position)
> if not step_to_glitch['enc']:
E TypeError: 'Mock' object has no attribute '__getitem__'

input_manager.py:17: TypeError

Aucun commentaire:

Enregistrer un commentaire