3

I am trying to parametrize unit tests in Python using parameterize library and unittest framework. I need to patch certain functions and I use the following which works

@parameterized.expand([
    [a1, b1],
    [a2, b2]
])
@patch("package.module.f2")
@patch("package.module.f1")
def test_my_func(self, a, b, f1, f2):
    f1.return_value = "Hello"
    f2.return_value = "World"

However, the order of arguments in this working case is a bit weird. Generally while patching the arguments are passed from bottom to top. But when I use parameterize, along with patch, I had expected something like

@parameterized.expand([
    [a1, b1],
    [a2, b2]
])
@patch("package.module.f2")
@patch("package.module.f1")
def test_my_func(self, f1, f2, a, b):
    f1.return_value = "Hello"
    f2.return_value = "World"

but it doesn't work. Can somebody please explain?

Thanks

1 Answer 1

4

According to the documentation

Using with @mock.patch

parameterized can be used with mock.patch, but the argument ordering can be confusing. The @mock.patch(...) decorator must come below the @parameterized(...), and the mocked parameters must come last:

@mock.patch("os.getpid")
class TestOS(object):
   @parameterized(...)
   @mock.patch("os.fdopen")
   @mock.patch("os.umask")
   def test_method(self, param1, param2, ..., mock_umask, mock_fdopen, mock_getpid):
       ...

Note: the same holds true when using @parameterized.expand.

considering the documentation, your method parameters are out of order:

@parameterized.expand([
    [a1, b1],
    [a2, b2]
])
@patch("package.module.f2")
@patch("package.module.f1")
def test_my_func(self, a, b, f1, f2):
    f1.return_value = "Hello"
    f2.return_value = "World"
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.