Download tests/test_core.py from PYTHAI/drAIML: direct link, hf CLI and curl.
- Browser
- Download file 7.7 kB
-
https://huggingface.co/spaces/PYTHAI/drAIML/resolve/main/tests/test_core.py
- Command line
-
hf download hf://spaces/PYTHAI/drAIML/tests/test_core.py
-
curl -L -o test_core.py https://huggingface.co/spaces/PYTHAI/drAIML/resolve/main/tests/test_core.py
7.7 kB
| import asyncio | |
| import json | |
| from pathlib import Path | |
| import pytest | |
| from draiml import catalogue, consult, engines, licences, net, rag, safety | |
| ROOT = Path(__file__).resolve().parents[1] | |
| # ── licence gate ── | |
| def test_gate(lic, kind, ok): | |
| assert licences.is_open(lic, kind) is ok | |
| def test_licence_of_tags_and_lists(): | |
| assert licences.licence_of({"tags": ["license:MIT"]}) == "mit" | |
| assert licences.licence_of({"cardData": {"license": ["apache-2.0"]}}) == "apache-2.0" | |
| assert not licences.is_open(licences.licence_of({"cardData": {"license": ["mit", "other"]}}), "model") | |
| def test_curated_catalogue_is_all_open(): | |
| cat = json.loads((ROOT / "app/data/catalogue.json").read_text()) | |
| ids = {m["id"] for m in cat["models"]} | |
| assert "google/medgemma-4b-it" not in ids and "aaditya/Llama3-OpenBioLLM-8B" not in ids | |
| assert "FreedomIntelligence/HuatuoGPT-o1-8B" not in ids # apache card over a Llama-3.1 base | |
| for m in cat["models"]: | |
| assert licences.is_open(m["licence"], "model"), m["id"] | |
| for d in cat["datasets"]: | |
| assert licences.is_open(d["licence"], "dataset"), d["id"] | |
| for mid in cat["router_open"]: | |
| assert mid not in cat["router_closed"] | |
| def test_unsuited_filter(): | |
| assert catalogue.UNSUITED.search("Qwen/Qwen3-Coder-480B-A35B-Instruct") | |
| assert catalogue.UNSUITED.search("dphn/Dolphin-Mistral-24B-Venice-Edition") | |
| assert not catalogue.UNSUITED.search("openai/gpt-oss-120b") | |
| # ── triage ── | |
| def test_triage_positive(text, cat): | |
| t = safety.triage(text) | |
| assert t.emergency and cat in t.categories | |
| def test_triage_negative(text): | |
| assert not safety.triage(text).emergency | |
| def test_validation_runs_without_disk(tmp_path, monkeypatch): | |
| monkeypatch.chdir(tmp_path) | |
| r = safety.validate("Likely a tension headache. Rest, fluids; see a doctor if it worsens.", "headache") | |
| assert "overall_score" in r and r["risk"]["level"] == "low" | |
| assert not any(tmp_path.iterdir()) # v1 wrote ./memory/logs; 2.0 must not | |
| # ── retrieval ── | |
| PASSAGES = {"sources": [{"repo": "x/a", "licence": "mit", "count": 3}], | |
| "passages": [["Nitrofurantoin is a safe antibiotic for cystitis in pregnancy.", 0, "a:1", ""], | |
| ["Metformin is first-line therapy for type 2 diabetes.", 0, "a:2", ""], | |
| ["Aspirin and nitroglycerin for suspected myocardial infarction.", 0, "a:3", ""]]} | |
| def test_bm25_ranks_and_cites(): | |
| idx = rag.EvidenceIndex(PASSAGES) | |
| hits, method = asyncio.run(rag.search(idx, "antibiotic for bladder cystitis in pregnancy", 2)) | |
| assert method == "bm25" and hits[0].ref == "a:1" and hits[0].licence == "mit" | |
| def test_bm25_arrays_roundtrip(tmp_path): | |
| a = rag.bm25_arrays(PASSAGES["passages"]) | |
| rag.save_bm25(tmp_path / "b.npz", a) | |
| idx = rag.EvidenceIndex(PASSAGES, bm25=rag.read_bm25(tmp_path / "b.npz")) | |
| assert idx.bm25("metformin diabetes")[0][0] == 1 | |
| def test_rrf(): | |
| assert rag.rrf([[(1, 9), (2, 8)], [(2, 1), (3, 0.5)]])[0][0] == 2 | |
| def test_prepare_includes_evidence_and_triage(): | |
| idx = rag.EvidenceIndex(PASSAGES) | |
| p = asyncio.run(consult.prepare("crushing chest pain, should I take aspirin?", [], idx, k=2)) | |
| assert p.triage.emergency and "TRIAGE ALERT" in p.messages[0]["content"] | |
| assert "EVIDENCE" in p.messages[-1]["content"] and "[1]" in p.messages[-1]["content"] | |
| # ── engines (mocked SSE) ── | |
| def test_stream_chat_parses_reasoning_and_content(monkeypatch): | |
| events = [json.dumps({"choices": [{"delta": {"reasoning_content": "think "}}]}), | |
| json.dumps({"choices": [{"delta": {"content": "Hello"}}]}), | |
| json.dumps({"choices": [{"delta": {"content": " world"}}]}), "[DONE]"] | |
| async def fake_sse(url, payload, headers=None): | |
| assert url.endswith("/chat/completions") and payload["stream"] is True | |
| assert headers == {"Authorization": "Bearer k"} | |
| for e in events: | |
| yield e | |
| monkeypatch.setattr(net, "post_sse", fake_sse) | |
| r, a = asyncio.run(engines.complete(engines.ENDPOINTS["hf"], "openai/gpt-oss-120b", [], key="k")) | |
| assert (r, a) == ("think", "Hello world") | |
| def test_split_think(): | |
| assert engines.split_think("<think>hmm</think>Answer") == ("hmm", "Answer") | |
| assert engines.split_think("plain") == ("", "plain") | |
| def test_http_error_message(): | |
| e = net.HTTPError(402, '{"error":"Purchase pre-paid credits"}', "u") | |
| assert "pre-paid credits" in e.message() | |
| def test_modes_change_prompt(mode, needle): | |
| idx = rag.EvidenceIndex(PASSAGES) | |
| p = asyncio.run(consult.prepare("my lower back hurts", [], idx, k=1, mode=mode)) | |
| assert needle in p.messages[0]["content"] | |
| g = asyncio.run(consult.prepare("my lower back hurts", [], idx, k=1)) | |
| assert needle not in g.messages[0]["content"] | |
| # ── Bonsai in the browser (browseML) ── | |
| def test_compact_prepare_is_short(): | |
| idx = rag.EvidenceIndex(PASSAGES) | |
| hist = [{"role": "user", "content": f"q{i}"} for i in range(10)] | |
| full = asyncio.run(consult.prepare("antibiotic for cystitis", hist, idx, k=6)) | |
| small = asyncio.run(consult.prepare("antibiotic for cystitis", hist, idx, k=6, compact=True)) | |
| assert len(small.hits) <= 2 and len(small.messages) == 1 + 2 + 1 | |
| assert small.messages[0]["content"].startswith("You are drAIML, a friendly") and "[1]" in small.messages[0]["content"] | |
| assert small.messages[-1]["content"] == "antibiotic for cystitis" | |
| assert len(small.messages[0]["content"]) < len(full.messages[0]["content"]) | |
| def test_bonsai_engine_uses_the_page_bridge(monkeypatch): | |
| from draiml import bonsai | |
| seen = {} | |
| async def fake_stream(msgs, max_tokens, temperature): | |
| seen.update(last=msgs[-1]["content"], max_tokens=max_tokens) | |
| for kind, d in [("content", "<think>\n\n</think>"), ("content", "Rest"), ("content", " and fluids."), | |
| ("receipt", "✓ bankML receipt")]: | |
| yield kind, d | |
| monkeypatch.setattr(bonsai, "stream", fake_stream) | |
| ep = engines.ENDPOINTS["bonsai"] | |
| assert not ep.needs_key | |
| r, a = asyncio.run(engines.complete(ep, bonsai.MODEL_ID, [{"role": "user", "content": "cold?"}], max_tokens=4096)) | |
| assert a == "Rest and fluids." and seen["last"].endswith("/no_think") and seen["max_tokens"] == 600 | |
| def test_bonsai_unavailable_outside_browser(): | |
| from draiml import bonsai | |
| assert not bonsai.available() | |
| assert asyncio.run(bonsai.status()) == {} | |
| with pytest.raises(bonsai.BonsaiError): | |
| asyncio.run(bonsai.ensure()) | |