Merge branch 'fixes'

This commit is contained in:
Colin Goutte 2021-11-14 22:07:42 +01:00
commit 518d353a16
8 changed files with 94 additions and 27 deletions

View File

@ -0,0 +1,5 @@
Config
======
Les configs pour prendre en compte les données transmises sont préfixées par api_client
Pour les relais par relais.

View File

@ -1,7 +1,7 @@
[relais]
identitifant_sonde = 838266b2-fc3a-4430-95e8-f7f0d0fc9871
api_login_url = 'https://merlin.savediffusion.fr/api/1.1/user/login'
api_status_url = 'https://merlin.savediffusion.fr/api/1.1/status"
api_user_login = 'admin'
api_user_password = 'Watermark35'
forward_api_address = 'https:/papi.silib.re/'
api_login_url = https://merlin.savediffusion.fr/api/1.1/user/login
api_status_url = https://merlin.savediffusion.fr/api/1.1/status
api_user_login =admin
api_user_password = Watermark35
forward_api_address = https:/papi.silib.re/

View File

@ -3,23 +3,45 @@ import glob
import configparser
import logging as logger
def read_config(*, pattern="*"):
def read_config(*, kind=None, pattern="*"):
if kind is None:
kind = "api"
paths = []
for relpath in glob.glob(f"confs/{pattern}.ini"):
if "/api_client" in relpath:
paths.append(os.path.abspath(relpath))
logger.info(f"Found api client {relpath} to add")
paths.append(os.path.abspath(relpath))
res = []
for path in paths:
# TODO: use case/switch
if kind == "api":
for path in paths:
conf = configparser.ConfigParser()
conf.read(path)
probe_settings = dict(conf["probe"])
emails = probe_settings["emails"]
stripped = [x.strip() for x in emails.split()]
probe_settings["emails"] = stripped
probe_settings["debug_source_path"] = path
res.append(probe_settings)
elif kind == "relais":
assert len(paths) == 1 # for now only one path is allowed
conf = configparser.ConfigParser()
path = paths[0]
conf.read(path)
probe_settings = dict(conf["probe"])
emails = probe_settings["emails"]
stripped = [x.strip() for x in emails.split()]
probe_settings["emails"] = stripped
probe_settings["debug_source_path"] = path
res.append(probe_settings)
gg = dict(conf["relais"])
for k, v in gg.items():
gg[k] = v.strip()
if "'" in v or '"' in v:
raise ValueError(
f"{k}:{v} from {path} containts forbidden char (escaping issue)"
)
res.append(gg)
return res

View File

@ -105,15 +105,18 @@ class Notifier:
)
@staticmethod
def error_sonde(idsonde, kind="perte_contact_api"):
def error_sonde(idsonde, kind="perte contact api"):
notifications[idsonde].append(
{
"changes": ["perte contact api"],
"status": ["Le monitoring est inacessible"],
}
)
conf = PROBES[idsonde]
try:
conf = PROBES[idsonde]
except KeyError:
logger.info(f"{idsonde} not found in probe")
return
subject = "Probleme api supervision"
content = kind
from papi.mail_sendermodel import sendmail
@ -170,7 +173,9 @@ def list_notification(idsonde: str):
@app.get("/notifications/{idsonde}/text")
def last_notif_text(request: Request, idsonde: str):
def last_notif_text(request: Request, idsonde: str, db: Session = Depends(get_db)):
db_sonde = crud.get_sonde(db, identifiant=idsonde)
notifs = notifications[idsonde]
try:
content = notifs[-1]
@ -179,7 +184,10 @@ def last_notif_text(request: Request, idsonde: str):
try:
recipients = sondeid2notifsemails(idsonde)
except KeyError: # pragma: no cover
recipients = ["mail1@xxx", "mail2@xxx"]
# breakpoint()
recipients = ["mail1@xxx", "mail2@xxx", f"{idsonde}@fqdn"]
changements = content["changes"]
status = content["status"]
@ -212,7 +220,7 @@ def post_sonde_error(
if idsonde != "test":
raise LookupError(f"{idsonde} not found")
Notifier.error_sonde(idsonde, body["msg"])
Notifier.error_sonde(idsonde, body.get("msg"))
# create fake sample
try:
@ -266,7 +274,7 @@ def post_sonde_data(
)
if content:
Notifier(db, idsonde, content)
res = last_notif_text(request, idsonde)
res = last_notif_text(request, idsonde, db)
html = res.body.decode("utf-8")
from papi.mail_sendermodel import sendmail

View File

@ -23,7 +23,10 @@ def api_login(config):
post_url = config["api_login_url"]
login_r = session.post(
post_url,
json={"login": api_credentials.user, "password": api_credentials.password},
json={
"login": config["api_user_login"],
"password": config["api_user_password"],
},
)
logged.append(True)
@ -77,7 +80,7 @@ def main(
pattern="relais_*"
):
loopcount = itertools.count().__next__
config = read_config(pattern=pattern)
config = read_config(kind="relais", pattern=pattern)
assert len(config) == 1
config = config[0]
login(config)

23
tests/test_config.py Normal file
View File

@ -0,0 +1,23 @@
from unittest import TestCase
from papi import main
class ConfigurationTestCase(TestCase):
""" Check configuration parsing """
def test_get_config(self):
configs = main.read_config(pattern="api_client*test_sonde")
assert len(configs) == 1
config = configs[0]
assert config["identifiant_sonde"] == "838266b2-fc3a-4430-95e8-f7f0d0fc9871"
assert config["nom_sonde"] == "SondeTest"
assert config["emails"] == ["1@1", "2@2"]
def test_get_config1mail(self):
configs = main.read_config(pattern="*1mail")
assert len(configs) == 1
config = configs[0]
assert config["emails"] == [
"1@1",
]

View File

@ -248,7 +248,7 @@ class CodeCoverageTestCase(TestCase):
import string
id_sonde = "".join(choices(string.ascii_lowercase, k=8))
r = client.get(f"/sonde/{id_sonde}/rapport")
r = client.post(f"/sonde/{id_sonde}/", json={})
assert r.ok
with pytest.raises(LookupError):
r = client.get(f"/sonde/{id_sonde}/rapport")
with pytest.raises(LookupError):
r = client.post(f"/sonde/{id_sonde}/", json={})

6
tests/test_relais.py Normal file
View File

@ -0,0 +1,6 @@
from papi import relais
def test_main():
relais.main(maxloop=1, pattern="relais_test_sonde")