Skip to content

Instantly share code, notes, and snippets.

@zobayer1
Last active August 26, 2022 04:13
Show Gist options
  • Save zobayer1/31f07011f1eaca7e0e5714bf647c2886 to your computer and use it in GitHub Desktop.
Save zobayer1/31f07011f1eaca7e0e5714bf647c2886 to your computer and use it in GitHub Desktop.
Using pytest parametrize with indirect for multiple test functions

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]

Reference

Documentation on indirect parameter

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment