ghostrider
ghostrider

Reputation: 5259

Python and pytest - mocking a db object

That's my first attempt to use mock in order to mock a db and cannot understand how it works.

My main file :

 def _test( db ) :
       res = {}
       for x in db.getData() :
          res[ x['id'] ] = x['name'] 
       return res

and this is my test :

def test_small() :
   mock_db = mock.Mock()
   mock_db.getData.return_value = [{ u'name':u'Nick',u'id':1234}]
   _test( mock_db )
   assert mock_db.getData.assert_called_once()

Assert fails though. Error is :

assert None
E        +  where None = <bound method Mock.assert_called_once of <Mock name='mock.getData' id='140103447969552'>>()
E        +    where <bound method Mock.assert_called_once of <Mock name='mock.getData' id='140103447969552'>> = <Mock name='mock.getData' id='140103447969552'>.assert_called_once
E        +      where <Mock name='mock.getData' id='140103447969552'> = <Mock id='140103462485712'>.getData

Can someone explain me what am I missing? ideally I want to put some asserts later on - that result of _test is the return value of my mock.

Upvotes: 1

Views: 1401

Answers (1)

georgexsh
georgexsh

Reputation: 16624

assert_called_once method itself already done the assertion for you:

def assert_called_once(_mock_self):
    """assert that the mock was called only once.
    """
    self = _mock_self
    if not self.call_count == 1:
        msg = ("Expected '%s' to have been called once. Called %s times." %
               (self._mock_name or 'mock', self.call_count))
        raise AssertionError(msg)

you could remove the surplus assert clause:

mock_db.getData.assert_called_once()

or

assert mock_db.getData.call_count == 1

Upvotes: 1

Related Questions