Skip to content

Comments

Refatoração do arquivo test_api.py usando Pytest#81

Open
thisiscleverson wants to merge 5 commits intookfn-brasil:mainfrom
thisiscleverson:refactor-test-api
Open

Refatoração do arquivo test_api.py usando Pytest#81
thisiscleverson wants to merge 5 commits intookfn-brasil:mainfrom
thisiscleverson:refactor-test-api

Conversation

@thisiscleverson
Copy link
Contributor

Fiz a refatoração do arquivo test_api.py para tentar solucionar a issue #67. Com isso, decidir fechar o pull request #79 que usava unittest e refiz usando o Pytest.

Fixtures

mock_gazette_interface: Essa fixture é responsável por criar o mock para GazetteAccessInterface. Para poder usar, basta usar como uma função comum:

interface = mock_gazette_interface()

Você pode customizar a interface passando parâmetros para configurá-la:

Exemplo usando mock_gazette_interface:

interface = mock_gazette_interface(
            (
                1,
                [
                    {
                        "territory_id": "123456",
                        "date": today,
                        "scraped_at": datetime_now,
                        "url": "https://queridodiario.ok.org.br/",
                        "territory_name": "My city",
                        "state_code": "My state",
                        "excerpts": [],
                        "edition": "12.3442",
                        "is_extra_edition": False,
                        "txt_url": "https://queridodiario.ok.org.br/123456/1a2345b678c9.txt",
                    }
                ],
            )
        )

Exemplo usando mock_suggestion_service_interface:

interface = mock_suggestion_service_interface(success=True, status="sent")

Essa mesma lógica se replica para mock_city_interface e mock_suggestion_service_interface.

configure_app: Essa fixture usa mocks pre-definido (default_mock) para fazer configuração automática sem a necessidade de reescrever o configure_api_app. É possível injetar uma interface personalizada usando kwargs, onde cada chave corresponde ao nome de um componente e o valor é o mock personalizado para substituir o padrão.

Exemplo de uso:

 interface = mock_city_interface(
            city_info={
                "territory_id": "2611606",
                "territory_name": "Recife",
                "state_code": "PE",
                "publication_urls": ["https://querido-diario.org.br"],
                "level": "1",
                "availability_date": today
            }
        )
        
        configure_app(cities=interface)

freeze_time: Essa fixture usa o plugin pytest-freezegun para facilitar testes que manipulam o tempo. Isso faz com que o tempo seja "congelado" em uma data e hora específica (foi definido a data de 2025-01-01 14:50:03).

@pytest.fixture(autouse=True)
def freeze_time(freezer):
    freezer.move_to("2025-01-01 14:50:03")

def test_current_date():
    assert date.today() == date(2025, 1, 1)

Como executar os testes

make test-shell
pytest -v tests/test_api.py

Plugins usados no Pytest

pytest-mock==3.14.0
pytest-freezegun==0.4.2

Antes:

def test_gazettes_endpoint_should_accept_territory_id_in_the_path(self):
        interface = self.create_mock_gazette_interface()
        configure_api_app(
            interface, MockSuggestionService(), MockCompaniesAccessInterface()
        )
        client = TestClient(app)
        response = client.get("/gazettes/4205902")
        # ...

Depois:

def test_gazettes_endpoint_should_accept_territory_id_in_the_path(self, mock_gazette_interface, configure_app, client):
        interface = mock_gazette_interface()

        configure_app(
            gazettes=interface
        )
        
        response = client.get("/gazettes", params={"territory_ids": "4205902"}) 
        # ...

@diraol diraol force-pushed the main branch 4 times, most recently from adf2084 to 8352b14 Compare January 13, 2026 19:40
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant