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?
Summary. You can pass arguments to fixtures with the params keyword argument in the fixture decorator, and you can also pass arguments to tests with the @pytest. mark. parametrize decorator for individual tests.
pytest. fixture() allows one to parametrize fixture functions.
Well. I've come up with something that seems to work, but I suppose its similar to mock:
@pytest.fixture
def argtest():
class TestArgs(object):
def __call__(self, *args):
self.args = list(args)
return TestArgs()
class ProductionClass:
def method(self):
self.something(1,2,3)
def something(self, a, b, c):
pass
def test_example(monkeypatch, argtest):
monkeypatch.setattr("test_module.ProductionClass.something", argtest)
real = ProductionClass()
real.method()
assert argtest.args == [1,2,3]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With