Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does pytest parametrized test work with unittest class based tests?

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.

like image 859
graffic Avatar asked Aug 12 '13 08:08

graffic


People also ask

Can I use pytest and unittest together?

pytest supports running Python unittest -based tests out of the box. It's meant for leveraging existing unittest -based test suites to use pytest as a test runner and also allow to incrementally adapt the test suite to take full advantage of pytest's features.

Is unittest part of pytest?

Python comes packaged with unittest , which works fine in most cases; however, most developers today are using pytest .

Is PyUnit and unittest same?

PyUnit is an easy way to create unit testing programs and UnitTests with Python. (Note that docs.python.org uses the name "unittest", which is also the module name.)

Which is better pytest or unittest?

Which is better – pytest or unittest? Although both the frameworks are great for performing testing in python, pytest is easier to work with. The code in pytest is simple, compact, and efficient. For unittest, we will have to import modules, create a class and define the testing functions within that class.


2 Answers

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.

like image 105
falsetru Avatar answered Sep 18 '22 15:09

falsetru


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.8.1

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.

like image 29
Michael Mintz Avatar answered Sep 19 '22 15:09

Michael Mintz