mercredi 25 février 2015

How to test function is called with correct arguments with pytest?

I'm learning how testing is done in Python using py.test. I am trying to test a specific situation that is quite common when using other libraries like mock. Specifically, testing that a function or method invokes another callable with the correct arguments. No return value is needed, just a confirmation that the method under test makes the call properly.


Here's an example straight from the docs:



>>> class ProductionClass:
... def method(self):
... self.something(1, 2, 3)
... def something(self, a, b, c):
... pass
...
>>> real = ProductionClass()
>>> real.something = MagicMock()
>>> real.method()
>>> real.something.assert_called_once_with(1, 2, 3)


Is it possible to do this using monkeypatch or fixtures from py.test, without effectively writing my own mocked class? I have searched for this specific use case, but couldn't find an example. Does py.test encourage an alternative way of exercising code like this?


Aucun commentaire:

Enregistrer un commentaire