70 lines
2.0 KiB
Python
70 lines
2.0 KiB
Python
# -*- coding: utf-8 -*-
|
|
|
|
"""Test API
|
|
|
|
Utilisation :
|
|
créer les variables d'environnement: (indiquer les valeurs
|
|
pour le serveur ScoDoc que vous voulez interroger)
|
|
|
|
export SCODOC_URL="https://scodoc.xxx.net/"
|
|
export API_USER="xxx"
|
|
export SCODOC_PASSWD="xxx"
|
|
export CHECK_CERTIFICATE=0 # ou 1 si serveur de production avec certif SSL valide
|
|
|
|
(on peut aussi placer ces valeurs dans un fichier .env du répertoire tests/api).
|
|
"""
|
|
import os
|
|
import requests
|
|
from dotenv import load_dotenv
|
|
import pytest
|
|
|
|
BASEDIR = "/opt/scodoc/tests/api"
|
|
load_dotenv(os.path.join(BASEDIR, ".env"))
|
|
CHECK_CERTIFICATE = bool(os.environ.get("CHECK_CERTIFICATE", False))
|
|
SCODOC_URL = os.environ["SCODOC_URL"]
|
|
API_URL = SCODOC_URL + "/ScoDoc/api"
|
|
API_USER = os.environ.get("API_USER", "test")
|
|
API_PASSWORD = os.environ.get("API_PASSWD", "test")
|
|
DEPT_ACRONYM = "TAPI"
|
|
print(f"SCODOC_URL={SCODOC_URL}")
|
|
print(f"API URL={API_URL}")
|
|
|
|
|
|
@pytest.fixture
|
|
def api_headers() -> dict:
|
|
"""
|
|
Demande un jeton et renvoie un dict à utiliser dans les en-têtes de requêtes http
|
|
"""
|
|
r0 = requests.post(API_URL + "/tokens", auth=(API_USER, API_PASSWORD))
|
|
token = r0.json()["token"]
|
|
return {"Authorization": f"Bearer {token}"}
|
|
|
|
|
|
class APIError(Exception):
|
|
pass
|
|
|
|
|
|
def GET(path: str, headers={}, errmsg=None, dept=None):
|
|
"""Get and returns as JSON"""
|
|
if dept:
|
|
url = SCODOC_URL + f"/ScoDoc/{dept}/api" + path
|
|
else:
|
|
url = API_URL + path
|
|
r = requests.get(url, headers=headers, verify=CHECK_CERTIFICATE)
|
|
if r.status_code != 200:
|
|
raise APIError(errmsg or f"""erreur status={r.status_code} !\n{r.text}""")
|
|
return r.json() # decode la reponse JSON
|
|
|
|
|
|
def POST_JSON(path: str, data: dict = {}, headers={}, errmsg=None):
|
|
"""Post"""
|
|
r = requests.post(
|
|
API_URL + path,
|
|
json=data,
|
|
headers=headers,
|
|
verify=CHECK_CERTIFICATE,
|
|
)
|
|
if r.status_code != 200:
|
|
raise APIError(errmsg or f"erreur status={r.status_code} !\n{r.text}")
|
|
return r.json() # decode la reponse JSON
|