Skip to content
New issue

Have a question about this project? # for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “#”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? # to your account

Refactor tests for Plano de Trabalho and Participante to use pytest classes #118

Merged
merged 27 commits into from
Aug 16, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
27 commits
Select commit Hold shift + click to select a range
b77a46c
Make clearer reference to PE in docstring arguments
augusto-herrmann Aug 8, 2024
46a1996
Add response class to return type hinting
augusto-herrmann Aug 8, 2024
12ba797
Create base test class for Plano de Entrega
augusto-herrmann Aug 8, 2024
e607036
Refactor some test functions into methods of class TestCreatePlanoEnt…
augusto-herrmann Aug 8, 2024
6f60785
Refactor some more test functions into a class
augusto-herrmann Aug 13, 2024
9019475
Refactor the get test functions into a class
augusto-herrmann Aug 13, 2024
e8a1312
Refactor test_create_invalid_cod_unidade into a class
augusto-herrmann Aug 13, 2024
5f8ef61
Refactor test_create_entrega_invalid_percent into a class
augusto-herrmann Aug 13, 2024
adbb5bc
Refactor test_create_entrega_invalid_tipo_meta into a class method
augusto-herrmann Aug 13, 2024
9aaf56f
Refactor test_create_pe_invalid_avaliacao into a class method
augusto-herrmann Aug 13, 2024
5f44226
Refactor test_create_pe_status_avaliado into a class method
augusto-herrmann Aug 13, 2024
6b13180
Use copies of input data instead of the original
augusto-herrmann Aug 13, 2024
2a7d2e8
Rename methods to improve code readability
augusto-herrmann Aug 13, 2024
5edef5b
Refactor into a class functions that test duplicate data
augusto-herrmann Aug 13, 2024
614530b
Add spacing after docstring
augusto-herrmann Aug 13, 2024
cd88de4
Improve upon docstrings and comments
augusto-herrmann Aug 13, 2024
84eeef7
Improve upon docstrings
augusto-herrmann Aug 13, 2024
2ba0b05
Remove unused import
augusto-herrmann Aug 13, 2024
44f59a4
Refactor basic dates tests into a new class
augusto-herrmann Aug 13, 2024
8703949
Refactor into classes date tests for P.E.
augusto-herrmann Aug 13, 2024
5bb0946
Remove unused import
augusto-herrmann Aug 13, 2024
803aa32
Refactor into classes permissions tests for P.E.
augusto-herrmann Aug 13, 2024
4978433
Fix method name
augusto-herrmann Aug 13, 2024
52b7739
Rename class to reflect what it actually does
augusto-herrmann Aug 13, 2024
d0140a4
Add test for reading a P.E. from a different unit as admin
augusto-herrmann Aug 13, 2024
b2594b7
Refactor tests for Participante to use test classes
augusto-herrmann Aug 16, 2024
ea2ce99
Rename methods and improve docstrings
augusto-herrmann Aug 16, 2024
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1,064 changes: 528 additions & 536 deletions tests/participantes_test.py

Large diffs are not rendered by default.

1,233 changes: 625 additions & 608 deletions tests/plano_entregas/core_test.py

Large diffs are not rendered by default.

454 changes: 211 additions & 243 deletions tests/plano_entregas/date_validation_test.py

Large diffs are not rendered by default.

134 changes: 85 additions & 49 deletions tests/plano_entregas/permissions_test.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,63 +2,99 @@
Entregas.
"""

from httpx import Client
from fastapi import status as http_status

from .core_test import assert_equal_plano_entregas
from .core_test import BasePETest


def test_get_plano_entregas_different_unit(
truncate_pe, # pylint: disable=unused-argument
example_pe_unidade_3, # pylint: disable=unused-argument
header_usr_2: dict,
input_pe,
client: Client,
):
"""Tenta buscar um plano de entregas existente em uma unidade diferente,
à qual o usuário não tem acesso."""
class TestPermissionsPE(BasePETest):
"""Testes relacionados a permissões e acesso ao Plano de Entregas de diferentes unidades."""

response = client.get(
f"/organizacao/SIAPE/3" # Sem autorização nesta unidade
f"/plano_entregas/{input_pe['id_plano_entregas']}",
headers=header_usr_2,
)
assert response.status_code == http_status.HTTP_403_FORBIDDEN
def test_get_plano_entregas_different_unit(
self,
truncate_pe, # pylint: disable=unused-argument
example_pe_unidade_3, # pylint: disable=unused-argument
header_usr_2: dict,
):
"""Tenta buscar um plano de entregas existente em uma unidade diferente,
à qual o usuário não tem acesso.
"""
input_pe = self.input_pe.copy()
response = self.get_plano_entregas(
input_pe["id_plano_entregas"],
3, # Sem autorização nesta unidade
header_usr=header_usr_2,
)
assert response.status_code == http_status.HTTP_403_FORBIDDEN

def test_get_plano_entregas_different_unit_admin(
self,
truncate_pe, # pylint: disable=unused-argument
example_pe_unidade_3, # pylint: disable=unused-argument
header_admin: dict,
admin_credentials: dict,
):
"""Tenta, como administrador, buscar um Plano de Entregas
em uma organização diferente da sua própria organização.
"""
input_pe = self.input_pe.copy()
input_pe["cod_unidade_autorizadora"] = 3

def test_get_plano_entregas_different_unit_admin(
truncate_pe, # pylint: disable=unused-argument
input_pe: dict,
header_admin: dict,
admin_credentials: dict,
client: Client,
):
"""Tenta, como administrador, criar um novo Plano de Entregas em uma
organização diferente da sua própria organização.
"""
input_pe["cod_unidade_autorizadora"] = 3 # unidade diferente
response = self.client.get(
f"/user/{admin_credentials['username']}",
headers=header_admin,
)

response = client.get(
f"/user/{admin_credentials['username']}",
headers=header_admin,
)
# Verifica se o usuário é admin e se está em outra unidade
assert response.status_code == http_status.HTTP_200_OK
admin_data = response.json()
assert (
admin_data.get("cod_unidade_autorizadora", None)
!= input_pe["cod_unidade_autorizadora"]
)
assert admin_data.get("is_admin", None) is True

# Verifica se o usuário é admin e se está em outra unidade
assert response.status_code == http_status.HTTP_200_OK
admin_data = response.json()
assert (
admin_data.get("cod_unidade_autorizadora", None)
!= input_pe["cod_unidade_autorizadora"]
)
assert admin_data.get("is_admin", None) is True
response = self.get_plano_entregas(
input_pe["id_plano_entregas"],
input_pe["cod_unidade_autorizadora"],
header_usr=header_admin,
)

response = client.put(
f"/organizacao/SIAPE/{input_pe['cod_unidade_autorizadora']}"
f"/plano_entregas/{input_pe['id_plano_entregas']}",
json=input_pe,
headers=header_admin,
)
assert response.status_code == http_status.HTTP_200_OK

assert response.status_code == http_status.HTTP_201_CREATED
assert response.json().get("detail", None) is None
assert_equal_plano_entregas(response.json(), input_pe)
def test_put_plano_entregas_different_unit_admin(
self,
truncate_pe, # pylint: disable=unused-argument
header_admin: dict,
admin_credentials: dict,
):
"""Tenta, como administrador, criar um novo Plano de Entregas
em uma organização diferente da sua própria organização.
"""
input_pe = self.input_pe.copy()
input_pe["cod_unidade_autorizadora"] = 3 # Unidade diferente

response = self.client.get(
f"/user/{admin_credentials['username']}",
headers=header_admin,
)

# Verifica se o usuário é admin e se está em outra unidade
assert response.status_code == http_status.HTTP_200_OK
admin_data = response.json()
assert (
admin_data.get("cod_unidade_autorizadora", None)
!= input_pe["cod_unidade_autorizadora"]
)
assert admin_data.get("is_admin", None) is True

response = self.put_plano_entregas(
input_pe,
cod_unidade_autorizadora=input_pe["cod_unidade_autorizadora"],
id_plano_entregas=input_pe["id_plano_entregas"],
header_usr=header_admin,
)

assert response.status_code == http_status.HTTP_201_CREATED
assert response.json().get("detail", None) is None
self.assert_equal_plano_entregas(response.json(), input_pe)
6 changes: 3 additions & 3 deletions tests/plano_trabalho/avaliacao_registros_execucao_test.py
Original file line number Diff line number Diff line change
Expand Up @@ -36,7 +36,7 @@ def test_create_pt_missing_mandatory_fields_avaliacao_registros_execucao(
input_pt["avaliacoes_registros_execucao"][0][field] = None

input_pt["id_plano_trabalho"] = "111222333"
response = self.create_pt(input_pt)
response = self.put_plano_trabalho(input_pt)
assert response.status_code == status.HTTP_422_UNPROCESSABLE_ENTITY


Expand Down Expand Up @@ -70,7 +70,7 @@ def test_create_pt_invalid_avaliacao_registros_execucao(
"avaliacao_registros_execucao"
] = avaliacao_registros_execucao

response = self.create_pt(input_pt)
response = self.put_plano_trabalho(input_pt)

if avaliacao_registros_execucao in range(1, 6):
assert response.status_code == status.HTTP_201_CREATED
Expand Down Expand Up @@ -208,7 +208,7 @@ def test_create_pt_invalid_avaliacao_registros_execucao_date(
"data_avaliacao_registros_execucao"
] = data_avaliacao_registros_execucao

response = self.create_pt(input_pt)
response = self.put_plano_trabalho(input_pt)

if date.fromisoformat(data_avaliacao_registros_execucao) > date.fromisoformat(
data_inicio_periodo_avaliativo
Expand Down
14 changes: 7 additions & 7 deletions tests/plano_trabalho/contribuicoes_test.py
Original file line number Diff line number Diff line change
Expand Up @@ -45,7 +45,7 @@ def test_create_pt_missing_mandatory_fields_contribuicoes(
"percentual_contribuicao"
] = percentual_contribuicao

response = self.create_pt(input_pt)
response = self.put_plano_trabalho(input_pt)
assert response.status_code == status.HTTP_422_UNPROCESSABLE_ENTITY


Expand All @@ -70,7 +70,7 @@ def test_create_pt_invalid_tipo_contribuicao(
input_pt = self.input_pt.copy()
input_pt["contribuicoes"][0]["tipo_contribuicao"] = tipo_contribuicao

response = self.create_pt(input_pt)
response = self.put_plano_trabalho(input_pt)

if tipo_contribuicao in [1, 2, 3]:
assert response.status_code == status.HTTP_201_CREATED
Expand Down Expand Up @@ -105,7 +105,7 @@ def test_create_plano_trabalho_percentual_contribuicao(
"percentual_contribuicao"
] = percentual_contribuicao

response = self.create_pt(input_pt, header_usr=self.header_usr_1)
response = self.put_plano_trabalho(input_pt, header_usr=self.header_usr_1)

if 0 <= percentual_contribuicao <= 100:
assert response.status_code == status.HTTP_201_CREATED
Expand Down Expand Up @@ -142,7 +142,7 @@ def test_create_plano_trabalho_contribuicao_omit_optional_fields(
del contribuicao[field]

partial_input_pt["id_plano_trabalho"] = str(557 + offset)
response = self.create_pt(partial_input_pt)
response = self.put_plano_trabalho(partial_input_pt)
assert response.status_code == status.HTTP_201_CREATED


Expand Down Expand Up @@ -173,7 +173,7 @@ def test_create_plano_trabalho_contribuicao_null_optional_fields(
contribuicao[field] = None

partial_input_pt["id_plano_trabalho"] = str(557 + offset)
response = self.create_pt(partial_input_pt)
response = self.put_plano_trabalho(partial_input_pt)
assert response.status_code == status.HTTP_201_CREATED


Expand Down Expand Up @@ -223,7 +223,7 @@ def test_tipo_contribuicao(
contribuicao["tipo_contribuicao"] = tipo_contribuicao
contribuicao["id_plano_entregas"] = id_plano_entregas
contribuicao["id_entrega"] = id_entrega
response = self.create_pt(input_pt, header_usr=self.header_usr_1)
response = self.put_plano_trabalho(input_pt, header_usr=self.header_usr_1)

error_messages = []
if tipo_contribuicao == 1:
Expand Down Expand Up @@ -263,7 +263,7 @@ def test_referencia_entrega_inexistente(
contribuicao["id_plano_entregas"] = id_plano_entregas
contribuicao["id_entrega"] = id_entrega

response = self.create_pt(input_pt, header_usr=self.header_usr_1)
response = self.put_plano_trabalho(input_pt, header_usr=self.header_usr_1)

if id_plano_entregas == input_pe["id_plano_entregas"] and \
id_entrega in [entrega["id_entrega"] for entrega in input_pe["entregas"]]:
Expand Down
40 changes: 21 additions & 19 deletions tests/plano_trabalho/core_test.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@

from typing import Optional

from httpx import Client
from httpx import Client, Response
from fastapi import status

import pytest
Expand Down Expand Up @@ -82,8 +82,10 @@ def setup(
"""Configurar o ambiente de teste.

Args:
truncate_pe (callable): Fixture para truncar a tabela PE.
truncate_pt (callable): Fixture para truncar a tabela PT.
truncate_pe (callable): Fixture para truncar a tabela de
Planos de Entrega.
truncate_pt (callable): Fixture para truncar a tabela de
Planos de Trabalho.
example_pe (callable): Fixture que cria exemplo de PE.
input_pt (dict): Dados usados para ciar um PT
user1_credentials (dict): Credenciais do usuário 1.
Expand Down Expand Up @@ -148,15 +150,15 @@ def assert_equal_plano_trabalho(plano_trabalho_1: dict, plano_trabalho_2: dict):
)
assert avaliacao_registros_execucao_1 == avaliacao_registros_execucao_2

def create_pt(
def put_plano_trabalho(
self,
input_pt: dict,
id_plano_trabalho: Optional[str] = None,
origem_unidade: Optional[str] = None,
cod_unidade_autorizadora: Optional[int] = None,
header_usr: Optional[dict] = None,
):
"""Criar um Plano de Trabalho.
) -> Response:
"""Cria ou atualiza um Plano de Trabalho pela API, usando o verbo PUT.

Args:
input_pt (dict): O dicionário de entrada do Plano de Trabalho.
Expand Down Expand Up @@ -188,14 +190,14 @@ def create_pt(
)
return response

def get_pt(
def get_plano_trabalho(
self,
id_plano_trabalho: str,
cod_unidade_autorizadora: int,
origem_unidade: Optional[str] = "SIAPE",
header_usr: Optional[dict] = None,
):
"""Obter um Plano de Trabalho.
) -> Response:
"""Obtém um Plano de Trabalho pela API, usando o verbo GET.

Args:
id_plano_trabalho (str): O ID do Plano de Trabalho.
Expand Down Expand Up @@ -225,13 +227,13 @@ def test_completo(self):
"""Cria um novo Plano de Trabalho do Participante, em uma unidade
na qual ele está autorizado, contendo todos os dados necessários.
"""
response = self.create_pt(self.input_pt)
response = self.put_plano_trabalho(self.input_pt)

assert response.status_code == status.HTTP_201_CREATED
self.assert_equal_plano_trabalho(response.json(), self.input_pt)

# Consulta API para conferir se a criação foi persistida
response = self.get_pt(
response = self.get_plano_trabalho(
self.input_pt["id_plano_trabalho"],
self.input_pt["cod_unidade_autorizadora"],
)
Expand Down Expand Up @@ -268,7 +270,7 @@ def test_create_plano_trabalho_missing_mandatory_fields(self, missing_fields):
input_pt["id_plano_trabalho"] = f"{1800 + offset}" # precisa ser um novo plano

# Act
response = self.create_pt(input_pt, **placeholder_fields)
response = self.put_plano_trabalho(input_pt, **placeholder_fields)

# Assert
assert response.status_code == status.HTTP_422_UNPROCESSABLE_ENTITY
Expand All @@ -282,7 +284,7 @@ def test_create_pt_cod_plano_inconsistent(self):
input_pt["id_plano_trabalho"] = "110"

# Act
response = self.create_pt(
response = self.put_plano_trabalho(
input_pt, id_plano_trabalho="111", header_usr=self.header_usr_1
)

Expand All @@ -308,7 +310,7 @@ def test_create_pt_invalid_carga_horaria_disponivel(self, carga_horaria_disponiv
input_pt["carga_horaria_disponivel"] = carga_horaria_disponivel

# Act
response = self.create_pt(input_pt)
response = self.put_plano_trabalho(input_pt)

# Assert
assert response.status_code == status.HTTP_422_UNPROCESSABLE_ENTITY
Expand Down Expand Up @@ -354,7 +356,7 @@ def test_put_plano_trabalho_invalid_cpf(self, cpf_participante):
input_pt["cpf_participante"] = cpf_participante

# Act
response = self.create_pt(input_pt)
response = self.put_plano_trabalho(input_pt)

# Assert
assert response.status_code == status.HTTP_422_UNPROCESSABLE_ENTITY
Expand Down Expand Up @@ -406,12 +408,12 @@ def test_update_plano_trabalho(self):
input_pt = self.input_pt.copy()
input_pt["status"] = 4 # Valor era 3
input_pt["data_termino"] = "2023-01-31" # Valor era "2023-01-15"
response = self.create_pt(input_pt)
response = self.put_plano_trabalho(input_pt)
assert response.status_code == status.HTTP_200_OK
self.assert_equal_plano_trabalho(response.json(), input_pt)

# Consulta API para conferir se a alteração foi persistida
response = self.get_pt(
response = self.get_plano_trabalho(
input_pt["id_plano_trabalho"],
self.user1_credentials["cod_unidade_autorizadora"],
)
Expand All @@ -431,7 +433,7 @@ def test_get_plano_trabalho(self, example_pt): # pylint: disable=unused-argumen
input_pt["contribuicoes"][1]["id_entrega"] = None
input_pt["contribuicoes"][1]["descricao_contribuicao"] = None

response = self.get_pt(
response = self.get_plano_trabalho(
input_pt["id_plano_trabalho"], input_pt["cod_unidade_autorizadora"]
)

Expand All @@ -442,7 +444,7 @@ def test_get_pt_inexistente(self):
"""Tenta acessar um plano de trabalho inexistente."""
non_existent_id = "888888888"

response = self.get_pt(
response = self.get_plano_trabalho(
non_existent_id, self.user1_credentials["cod_unidade_autorizadora"]
)

Expand Down
Loading