Created
April 30, 2025 03:23
-
-
Save Tusenka/6f77566a42bf76c041c41544da1c01f6 to your computer and use it in GitHub Desktop.
Fixture indirrect params
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
https://gist.github.com/zobayer1/31f07011f1eaca7e0e5714bf647c2886 | |
Using pytest.mark.parametrize with other fixtures | |
Introduction | |
When you want to run tests against multiple test parameters, but you have to use other pytest.fixture objects, you can use pytest.mark.parametrize with indirect parameter to target a fixture for extracting request.param from parametrize list. | |
Example | |
# -*- coding: utf-8 -*- | |
import os | |
import pytest | |
import requests | |
@pytest.fixture(scope='function') | |
def parameter(request): | |
""" | |
A common fixture to handle pytest.mark.parametrize decorator. | |
Attribute `param` from `request` fixture is used for indirect. | |
It is important to keep the scope limited to `function`. | |
""" | |
return request.param | |
@pytest.mark.parametrize('parameter', [ | |
'jack fruit', 'mango', 'banana', 'coconut', | |
], indirect=['parameter']) | |
def test_method_1(monkeypatch, parameter): | |
""" | |
Example test method 1 | |
Fixure `parameter` is given to indirect parameter. | |
Each item in the list is a string. | |
""" | |
monkeypatch.setenv('FRUIT', parameter) | |
assert os.getenv('FRUIT') == parameter | |
@pytest.mark.parametrize('parameter', [ | |
('sky', 'blue'), ('rose', 'red'), ('snow', 'white'), | |
], indirect=['parameter']) | |
def test_method_2(monkeypatch, parameter): | |
""" | |
Example test method 2 | |
Fixure `parameter` is given to indirect parameter. | |
Each item in the list is a tuple. | |
""" | |
def mock_get(*args, **kwargs): | |
return {parameter[0]: parameter[1]} | |
monkeypatch.setattr(requests, 'get', mock_get) | |
result = requests.get('http://testurl.com') | |
assert result.get(parameter[0]) == parameter[1] |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment