Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 907
donopj2 Avatar asked Feb 25 '15 10:02

donopj2


People also ask

Can pytest take arguments?

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.

Can pytest fixtures be parameterized?

pytest. fixture() allows one to parametrize fixture functions.


1 Answers

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]
like image 119
donopj2 Avatar answered Oct 05 '22 13:10

donopj2