Search code examples
pythonpytestmonkeypatching

Replacing keyword argument in pytest


I am doing some testing and I would like to mock one argument of a function.

For example I got function like:

def foo(arg1, arg2):
    'do something'

and call of that function:

foo(1, 2)

I would like to monkeypatch it somehow to use 3 instead of 2. Is that possible?

tried something like:

monkeypatch.setattr('foo', partial(foo, arg2= 3))

But I got type error: foo() got multiple values for keyword argument 'arg2'

Any idea how to solve this?


Solution

  • You can simply alias the function:

    old_foo = monkeypatch.foo
    def foo(arg1, arg2):
        return old_foo(arg1, 3)
    
    monkeypatch.foo = foo