Search code examples
pythontestingpytest

Can I define functions other than fixtures in conftest.py


Can I define functions other than fixtures in conftest.py.

If I have a function add(), defined in conftest.py.

Can I using the function inside test_add.py file just calling add()?


Solution

  • Two possible ways

    1. You could just import function add from conftest.py, or move it to something more appropriate. (for example utils.py)

    2. You could create fixture that returns function and use it in your tests. Something like this.

    conftest.py

    import pytest
    
    
    @pytest.fixture
    def add():
        def inner_add(x, y):
            return x + y
        return inner_add
    

    test_all.py

    def test_all(add):
        assert add(1, 2) == 3
    

    I can not imagine situation when it will be a good solution. But I am sure it exists.