1
0
forked from ScoDoc/ScoDoc
ScoDoc-Front/tests/api/test_api_justificatifs.py
2023-02-03 10:40:51 +01:00

407 lines
11 KiB
Python

"""
Test de l'api justificatif
Ecrit par HARTMANN Matthias
"""
from random import randint
from tests.api.setup_test_api import (
GET,
POST_JSON,
APIError,
api_headers,
API_URL,
CHECK_CERTIFICATE,
)
import requests
ETUDID = 1
FAUX = 42069
JUSTIFICATIFS_FIELDS = {
"justif_id": int,
"etudid": int,
"date_debut": str,
"date_fin": str,
"etat": str,
"raison": str,
"entry_date": str,
"fichier": str,
}
CREATE_FIELD = {"justif_id": int}
BATCH_FIELD = {"errors": dict, "success": dict}
TO_REMOVE = []
def check_fields(data, fields: dict = None):
if fields is None:
fields = JUSTIFICATIFS_FIELDS
assert set(data.keys()) == set(fields.keys())
for key in data:
if key in ("raison", "fichier"):
assert isinstance(data[key], fields[key]) or data[key] is None
else:
assert isinstance(data[key], fields[key])
def check_failure_get(path, headers, err=None):
try:
GET(path=path, headers=headers)
# ^ Renvoi un 404
except APIError as api_err:
if err is not None:
assert api_err.payload["message"] == err
else:
raise APIError("Le GET n'aurait pas du fonctionner")
def check_failure_post(path, headers, data, err=None):
try:
data = POST_JSON(path=path, headers=headers, data=data)
# ^ Renvoi un 404
except APIError as api_err:
if err is not None:
assert api_err.payload["message"] == err
else:
raise APIError("Le POST n'aurait pas du fonctionner")
def create_data(etat: str, day: str, raison: str = None):
data = {
"date_debut": f"2022-01-{day}T08:00",
"date_fin": f"2022-01-{day}T10:00",
"etat": etat,
}
if raison is not None:
data["desc"] = raison
return data
def test_route_justificatif(api_headers):
# Bon fonctionnement == id connu
data = GET(path="/justificatif/1", headers=api_headers)
check_fields(data)
# Mauvais Fonctionnement == id inconnu
check_failure_get(
f"/justificatif/{FAUX}",
api_headers,
)
def test_route_justificatifs(api_headers):
# Bon fonctionnement
data = GET(path=f"/justificatifs/{ETUDID}", headers=api_headers)
assert isinstance(data, list)
for just in data:
check_fields(just, JUSTIFICATIFS_FIELDS)
data = GET(path=f"/justificatifs/{ETUDID}/query?", headers=api_headers)
assert isinstance(data, list)
for just in data:
check_fields(just, JUSTIFICATIFS_FIELDS)
# Mauvais fonctionnement
check_failure_get(f"/justificatifs/{FAUX}", api_headers)
check_failure_get(f"/justificatifs/{FAUX}/query?", api_headers)
def test_route_create(api_headers):
# -== Unique ==-
# Bon fonctionnement
data = create_data("valide", "01")
res = POST_JSON(f"/justificatif/{ETUDID}/create", [data], api_headers)
check_fields(res, BATCH_FIELD)
assert len(res["success"]) == 1
TO_REMOVE.append(res["success"]["0"]["justif_id"])
data2 = create_data("modifie", "02", "raison")
res = POST_JSON(f"/justificatif/{ETUDID}/create", [data2], api_headers)
check_fields(res, BATCH_FIELD)
assert len(res["success"]) == 1
TO_REMOVE.append(res["success"]["0"]["justif_id"])
# Mauvais fonctionnement
check_failure_post(f"/justificatif/{FAUX}/create", api_headers, [data])
res = POST_JSON(f"/justificatif/{ETUDID}/create", [data], api_headers)
check_fields(res, BATCH_FIELD)
assert len(res["errors"]) == 1
assert (
res["errors"]["0"]
== "Duplication des justificatifs (la période rentrée rentre en conflit avec un justificatif enregistré)"
)
res = POST_JSON(
f"/justificatif/{ETUDID}/create",
[create_data("absent", "03")],
api_headers,
)
check_fields(res, BATCH_FIELD)
assert len(res["errors"]) == 1
assert res["errors"]["0"] == "param 'etat': invalide"
# -== Multiple ==-
# Bon Fonctionnement
etats = ["valide", "modifie", "non_valide", "attente"]
data = [
create_data(etats[d % 4], 10 + d, "raison" if d % 2 else None)
for d in range(randint(3, 5))
]
res = POST_JSON(f"/justificatif/{ETUDID}/create", data, api_headers)
check_fields(res, BATCH_FIELD)
for dat in res["success"]:
check_fields(res["success"][dat], CREATE_FIELD)
TO_REMOVE.append(res["success"][dat]["justif_id"])
# Mauvais Fonctionnement
data2 = [
create_data("modifie", "01"),
create_data(None, "25"),
create_data("blabla", 26),
create_data("valide", 32),
]
res = POST_JSON(f"/justificatif/{ETUDID}/create", data2, api_headers)
check_fields(res, BATCH_FIELD)
assert len(res["errors"]) == 4
assert (
res["errors"]["0"]
== "Duplication des justificatifs (la période rentrée rentre en conflit avec un justificatif enregistré)"
)
assert res["errors"]["1"] == "param 'etat': manquant"
assert res["errors"]["2"] == "param 'etat': invalide"
assert (
res["errors"]["3"]
== "param 'date_debut': format invalide, param 'date_fin': format invalide"
)
def test_route_edit(api_headers):
# Bon fonctionnement
data = {"etat": "modifie", "raison": "test"}
res = POST_JSON(f"/justificatif/{TO_REMOVE[0]}/edit", data, api_headers)
assert res == {"OK": True}
data["raison"] = None
res = POST_JSON(f"/justificatif/{TO_REMOVE[1]}/edit", data, api_headers)
assert res == {"OK": True}
# TODO: Modification date deb / fin
# Mauvais fonctionnement
check_failure_post(f"/justificatif/{FAUX}/edit", api_headers, data)
data["etat"] = "blabla"
check_failure_post(
f"/justificatif/{TO_REMOVE[2]}/edit",
api_headers,
data,
err="param 'etat': invalide",
)
def test_route_delete(api_headers):
# -== Unique ==-
# Bon fonctionnement
data = TO_REMOVE[0]
res = POST_JSON("/justificatif/delete", [data], api_headers)
check_fields(res, BATCH_FIELD)
for dat in res["success"]:
assert res["success"][dat] == {"OK": True}
# Mauvais fonctionnement
res = POST_JSON("/justificatif/delete", [data], api_headers)
check_fields(res, BATCH_FIELD)
assert len(res["errors"]) == 1
# -== Multiple ==-
# Bon Fonctionnement
data = TO_REMOVE[1:]
res = POST_JSON("/justificatif/delete", data, api_headers)
check_fields(res, BATCH_FIELD)
for dat in res["success"]:
assert res["success"][dat] == {"OK": True}
# Mauvais Fonctionnement
data2 = [
FAUX,
FAUX + 1,
FAUX + 2,
]
res = POST_JSON("/justificatif/delete", data2, api_headers)
check_fields(res, BATCH_FIELD)
assert len(res["errors"]) == 3
assert all([res["errors"][i] == "Justificatif non existant" for i in res["errors"]])
# Gestion de l'archivage
def send_file(justif_id: int, filename: str, headers):
"""
Envoi un fichier vers la route d'importation
"""
with open(filename, "rb") as file:
url: str = API_URL + f"/justificatif/import/{justif_id}"
r = requests.post(
url,
files={filename: file},
headers=headers,
verify=CHECK_CERTIFICATE,
)
if r.status_code != 200:
raise APIError(f"erreur status={r.status_code} !", r.json())
else:
return r.json()
def check_failure_send(
justif_id: int,
headers,
filename: str = "tests/api/test_api_justificatif.txt",
err: str = None,
):
try:
data = send_file(justif_id, filename, headers)
# ^ Renvoi un 404
except APIError as api_err:
if err is not None:
assert api_err.payload["message"] == err
else:
raise APIError("Le POST n'aurait pas du fonctionner")
def test_import_justificatif(api_headers):
# Bon fonctionnement
filename: str = "tests/api/test_api_justificatif.txt"
resp: dict = send_file(1, filename, api_headers)
assert "response" in resp
assert resp["response"] == "imported"
filename: str = "tests/api/test_api_justificatif2.txt"
resp: dict = send_file(1, filename, api_headers)
assert "response" in resp
assert resp["response"] == "imported"
# Mauvais fonctionnement
check_failure_send(FAUX, api_headers)
def test_list_justificatifs(api_headers):
# Bon fonctionnement
res: list = GET("/justificatif/list/1", api_headers)
assert isinstance(res, list)
assert len(res) == 2
res: list = GET("/justificatif/list/2", api_headers)
assert isinstance(res, list)
assert len(res) == 0
# Mauvais fonctionnement
check_failure_get(f"/justificatif/list/{FAUX}", api_headers)
def get_export(id: int, fname: str, api_headers):
url: str = API_URL + f"/justificatif/export/{id}/{fname}"
res = requests.get(url, headers=api_headers)
return res
def test_export(api_headers):
# Bon fonctionnement
assert get_export(1, "test_api_justificatif.txt", api_headers).status_code == 200
# Mauvais fonctionnement
assert get_export(FAUX, "test_api_justificatif.txt", api_headers).status_code == 404
assert get_export(1, "blabla.txt", api_headers).status_code == 404
assert get_export(2, "blabla.txt", api_headers).status_code == 404
def test_remove_justificatif(api_headers):
# Bon fonctionnement
filename: str = "tests/api/test_api_justificatif.txt"
send_file(2, filename, api_headers)
filename: str = "tests/api/test_api_justificatif2.txt"
send_file(2, filename, api_headers)
res: dict = POST_JSON("/justificatif/remove/1", {"remove": "all"}, api_headers)
assert res == {"response": "removed"}
assert len(GET("/justificatif/list/1", api_headers)) == 0
res: dict = POST_JSON(
"/justificatif/remove/2",
{"remove": "list", "filenames": ["test_api_justificatif2.txt"]},
api_headers,
)
assert res == {"response": "removed"}
assert len(GET("/justificatif/list/2", api_headers)) == 1
res: dict = POST_JSON(
"/justificatif/remove/2",
{"remove": "list", "filenames": ["test_api_justificatif.txt"]},
api_headers,
)
assert res == {"response": "removed"}
assert len(GET("/justificatif/list/2", api_headers)) == 0
# Mauvais fonctionnement
check_failure_post("/justificatif/remove/2", api_headers, {})
check_failure_post(f"/justificatif/remove/{FAUX}", api_headers, {"remove": "all"})
check_failure_post("/justificatif/remove/1", api_headers, {"remove": "all"})
def test_justified(api_headers):
# Bon fonctionnement
res: list = GET("/justificatif/justified/1", api_headers)
assert isinstance(res, list)
# Mauvais fonctionnement
check_failure_get(f"/justificatif/justified/{FAUX}", api_headers)