58

I've been trying to add parametrized @pytest.mark.parametrize tests to a class based unittest.

class SomethingTests(unittest.TestCase):
    @pytest.mark.parametrize(('one', 'two'), [
        (1, 2), (2, 3)])
    def test_default_values(self, one, two):
        assert one == (two + 1)

But the parametrized stuff didn't kick in:

TypeError: test_default_values() takes exactly 3 arguments (1 given)

I've switched to simple class based tests (without unittest). But I'd like to know if anyone tried it and it worked.

0

2 Answers 2

57

According to pytest documentation:

unittest.TestCase methods cannot directly receive fixture function arguments as implementing that is likely to inflict on the ability to run general unittest.TestCase test suites.

Sign up to request clarification or add additional context in comments.

Comments

17

There's a simple workaround to parameterize unittest-based Python tests by using "parameterized": https://pypi.org/project/parameterized/

Here's a simple example. First install "parameterized": pip install parameterized==0.9.0

import unittest
from parameterized import parameterized

class MyTestClass(unittest.TestCase):

    @parameterized.expand([
        ["One", "Two"],
        ["Three", "Four"],
        ["Five", "Six"],
    ])
    def test_parameterized(self, arg1, arg2):
        print(arg1, arg2)

Now you can easily run your code with pytest

I've successfully used this technique to parameterize selenium browser tests that use the SeleniumBase framework on GitHub in this example.

4 Comments

Note that, to use mocks, you should decorate behind the @parametrized and should "collect" the mock at the end of the args list (arg3 maybe). I just tried it.
this doesn't solve the need to indirect parameterization, though :/
I am getting error "TypeError: 'list' object is not callable"
I'm using 0.8.1 and it needs a LIST of the function arguments for each test, provided in a TUPLE format. E.g. my function takes one input so I'm doing: @parameterized.expand([(20.0,), (0.0,)])

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.