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

I am learning how testing is done in Python using py.test . I am trying to check a specific situation, which is quite common when using other libraries, such as mock . In particular, testing that a function or method calls another called with the correct arguments. A return value is not required, just a confirmation that the tested method correctly calls.

Here is an example directly from 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 with monkeypatch or fixtures from py.test without creating an efficient spelling of my own mocking class? I was looking for this specific use case but could not find an example. Does py.test an alternative way to implement such code?

+6
source share
2 answers

You can use pytest-mock , which makes it easy to use mock as a pytest fitting.

+3
source

Well. I came up with something that seems to work, but I suppose it looks like 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] 
+1
source

Source: https://habr.com/ru/post/982981/


All Articles