122 lines
4.8 KiB
Python
122 lines
4.8 KiB
Python
"""Cover the bundle HTTP contract with an app client and two temporary registries.
|
|
|
|
Fails if export loses ZIP metadata, import misreports registry versions or malformed uploads succeed.
|
|
"""
|
|
|
|
import hashlib
|
|
import json
|
|
import zipfile
|
|
from dataclasses import replace
|
|
from io import BytesIO
|
|
|
|
import mlflow
|
|
import numpy as np
|
|
import pytest
|
|
from flask import Flask
|
|
from models.io.registry import PRODUCTION_ALIAS
|
|
from models.tea.eeg import bundle, train
|
|
from models.tea.eeg.analyze import ReferenceStudy, pipeline
|
|
from models.tea.eeg.settings import settings
|
|
|
|
from webapi.blueprints.governance import governance_bp
|
|
from webapi.tea import baselines
|
|
|
|
BASELINES = "/governance/tea/baselines"
|
|
SCENARIO = "eeg-posterior-rhythm"
|
|
|
|
|
|
@pytest.fixture
|
|
def client():
|
|
"""Mount the governance routes so changes to route registration or error handling surface in HTTP."""
|
|
app = Flask(__name__)
|
|
app.config.update(TESTING=True)
|
|
app.register_blueprint(governance_bp, url_prefix="/governance")
|
|
return app.test_client()
|
|
|
|
|
|
@pytest.fixture
|
|
def trained_registries(tmp_path, monkeypatch):
|
|
"""Train one synthetic baseline in SQLite and provide an empty destination to expose failed transfers."""
|
|
config = settings()
|
|
metric = next(metric for metric in config.metrics if metric.scenario == SCENARIO)
|
|
config = replace(config, metrics=(metric,))
|
|
monkeypatch.setattr(baselines, "settings", lambda: config)
|
|
monkeypatch.chdir(tmp_path)
|
|
previous_uri = mlflow.get_tracking_uri()
|
|
|
|
def use_store(name):
|
|
uri = f"sqlite:///{tmp_path / f'{name}.db'}"
|
|
monkeypatch.setenv("MLFLOW_TRACKING_URI", uri)
|
|
mlflow.set_tracking_uri(uri)
|
|
|
|
try:
|
|
use_store("source")
|
|
biomarker, phase = config.scenarios[SCENARIO]
|
|
features = pipeline(config).module(biomarker).features
|
|
rng = np.random.default_rng(0)
|
|
ages = np.linspace(16, 36, 100)
|
|
found = train.Listing.of("source", [(f"/synthetic/{k}.edf", float(age)) for k, age in enumerate(ages)])
|
|
studies = [
|
|
ReferenceStudy(key, age, 1, {
|
|
(biomarker, phase): {feature: float(1 + 0.02 * age + rng.normal(0, 0.1)) for feature in features},
|
|
})
|
|
for key, _, age in found.studies
|
|
]
|
|
train.train_all(config, "PROD", found=found, studies=studies)
|
|
yield use_store
|
|
finally:
|
|
mlflow.set_tracking_uri(previous_uri)
|
|
|
|
|
|
def test_export_and_import_baselines(client, trained_registries, monkeypatch):
|
|
"""Pin ZIP headers, cleanup and registry transfer. Fail if repeats register another version."""
|
|
real_export = bundle.export
|
|
export_paths = []
|
|
|
|
def capture_export(config, path, **kwargs):
|
|
export_paths.append(path)
|
|
return real_export(config, path, **kwargs)
|
|
|
|
monkeypatch.setattr(bundle, "export", capture_export)
|
|
with client.get(f"{BASELINES}/export?environment=prod&production=0") as response:
|
|
assert response.status_code == 200
|
|
assert response.mimetype == "application/zip"
|
|
assert response.headers["Content-Disposition"] == "attachment; filename=baselines.zip"
|
|
assert response.headers["X-Baselines-Versions"] == "1"
|
|
assert export_paths[0].is_file()
|
|
archive = response.data
|
|
sha256 = hashlib.sha256(archive).hexdigest()
|
|
assert response.headers["X-Baselines-Sha256"] == sha256
|
|
assert not export_paths[0].exists()
|
|
with zipfile.ZipFile(BytesIO(archive)) as exported:
|
|
manifest = json.loads(exported.read(bundle.MANIFEST))
|
|
assert list(manifest["escenarios"]) == [SCENARIO]
|
|
|
|
model = train.latest(SCENARIO, "PROD")
|
|
mlflow.MlflowClient().set_registered_model_alias(model.name, PRODUCTION_ALIAS, model.version)
|
|
with client.get(f"{BASELINES}/export?environment=dev&production=1") as response:
|
|
assert response.status_code == 200
|
|
assert response.data == archive
|
|
assert not export_paths[1].exists()
|
|
|
|
trained_registries("destination")
|
|
response = client.post(f"{BASELINES}/import", data={"file": (BytesIO(archive), "baselines.zip")})
|
|
|
|
assert response.status_code == 200
|
|
assert response.json == {"sha256": sha256, "imported": [{"scenario": SCENARIO, "version": 1}]}
|
|
assert train.latest(SCENARIO, "PROD").tags[bundle.BUNDLE_TAG] == sha256
|
|
|
|
duplicate = client.post(f"{BASELINES}/import", data={"file": (BytesIO(archive), "baselines.zip")})
|
|
assert duplicate.status_code == 409
|
|
assert duplicate.json["error"]
|
|
versions = mlflow.MlflowClient().search_model_versions(f"name = '{model.name}'")
|
|
assert [int(version.version) for version in versions] == [1]
|
|
|
|
|
|
def test_import_rejects_garbage(client):
|
|
"""Pin a JSON 400 for non-ZIP bytes. Fail if the ZIP exception becomes a server error."""
|
|
response = client.post(f"{BASELINES}/import", data={"file": (BytesIO(b"garbage"), "baselines.zip")})
|
|
|
|
assert response.status_code == 400
|
|
assert response.json["error"]
|