DEV Community

Cover image for How to use fixture and parameterize in Python?
Possawat Sanorkam
Possawat Sanorkam

Posted on • Edited on

How to use fixture and parameterize in Python?

In Python, fixtures are used to provide data for test functions. The parameterize function from the pytest-parameterize package can be used to run the same test function with different sets of data. Here is an example of how to use fixtures with parameterize:

import pytest
from pytest_parameterize import parameterize

@pytest.fixture
def data():
  return [1, 2, 3]

@parameterize('num', data())
def test_numbers(num):
  assert isinstance(num, int)
Enter fullscreen mode Exit fullscreen mode

In this example, the data fixture provides a list of numbers to the parameterize function. The parameterize function then runs the test_numbers test function with each of the numbers in the data list as the num parameter. The test function uses the assert statement to check that each num value is an integer.

import pytest
from pytest_parameterize import parameterize

@pytest.fixture
def data1():
  return [1, 2, 3]

@pytest.fixture
def data2():
  return ['a', 'b', 'c']

@parameterize('num', 'letter', data1(), data2())
def test_numbers_letters(num, letter):
  assert isinstance(num, int)
  assert isinstance(letter, str)
Enter fullscreen mode Exit fullscreen mode

In this example, the data1 and data2 fixtures provide lists of numbers and letters, respectively. The parameterize function is called with two arguments: num and letter. The parameterize function then runs the test_numbers_letters test function with each combination of num and letter values from the data1 and data2 lists. The test function uses the assert statement to check that each num value is an integer and each letter value is a string.

Overall, using parameterize with multiple data parameters is similar to using it with a single parameter. You simply need to provide multiple fixtures to supply the data and specify multiple arguments in the parameterize function call.

Surprise, this article was generated by ChatGPT!

Top comments (0)