Pytest - Conftest.py

Podemos definir as funções de fixação neste arquivo para torná-las acessíveis em vários arquivos de teste.

Crie um novo arquivo conftest.py e adicione o código abaixo nele -

import pytest

@pytest.fixture
def input_value():
   input = 39
   return input

Edite o test_div_by_3_6.py para remover a função de fixação -

import pytest

def test_divisible_by_3(input_value):
   assert input_value % 3 == 0

def test_divisible_by_6(input_value):
   assert input_value % 6 == 0

Crie um novo arquivo test_div_by_13.py -

import pytest

def test_divisible_by_13(input_value):
   assert input_value % 13 == 0

Agora, temos os arquivos test_div_by_3_6.py e test_div_by_13.py fazendo uso do acessório definido em conftest.py.

Execute os testes executando o seguinte comando -

pytest -k divisible -v

O comando acima irá gerar o seguinte resultado -

test_div_by_13.py::test_divisible_by_13 PASSED
test_div_by_3_6.py::test_divisible_by_3 PASSED
test_div_by_3_6.py::test_divisible_by_6 FAILED
============================================== FAILURES
==============================================
________________________________________ test_divisible_by_6
_________________________________________
input_value = 39
   def test_divisible_by_6(input_value):
>  assert input_value % 6 == 0
E  assert (39 % 6) == 0
test_div_by_3_6.py:7: AssertionError
========================== 1 failed, 2 passed, 6 deselected in 0.09 seconds
==========================

Os testes procurarão fixture no mesmo arquivo. Como o fixture não foi encontrado no arquivo, ele irá verificar o fixture no arquivo conftest.py. Ao encontrá-lo, o método fixture é invocado e o resultado é retornado para o argumento de entrada do teste.