Search code examples
pythonpytestfixtures

Passing arguments to fixture in TestCase with pytest


How to pass custom arguments to fixture inside test method of unittest.TestCase derived class using pytest?


Solution

  • After searching for definitely too long time I managed to invent solution with usage of doc and threads about wrapping fixtures. I hope somebody will find it useful.

    conftest.py

    import pytest
    
    @pytest.fixture()
    def add(request):
        def wrapped(a=10, b=5):
            return a + b
        request.cls.add = wrapped
    

    add_test.py

    import pytest
    from unittest import TestCase
    
    @pytest.mark.usefixtures('add')
    class AddTestCase(TestCase):
        def test_add(self):
            # parameters can be passed inside test method
            result = self.add(2, 2) 
            assert result == 4