105 lines
4.2 KiB
Python
105 lines
4.2 KiB
Python
import math
|
|
import os
|
|
import re
|
|
from unittest.mock import Mock
|
|
|
|
import pytest
|
|
from fastapi.testclient import TestClient
|
|
|
|
import main
|
|
|
|
|
|
class Tokenizer:
|
|
is_fast = True
|
|
|
|
def __call__(self, texts, add_special_tokens=True, **_kwargs):
|
|
if isinstance(texts, list):
|
|
return {"input_ids": [self(text)["input_ids"] for text in texts]}
|
|
offsets = [match.span() for match in re.finditer(r"\S+", texts)]
|
|
return {"input_ids": [1] * (len(offsets) + 2 * add_special_tokens),
|
|
"offset_mapping": offsets}
|
|
|
|
|
|
@pytest.fixture
|
|
def model(monkeypatch):
|
|
model = Mock(max_seq_length=512, tokenizer=Tokenizer())
|
|
model.get_sentence_embedding_dimension.return_value = 384
|
|
|
|
def encode(texts, **_kwargs):
|
|
array = Mock(shape=(len(texts), 384))
|
|
array.tolist.return_value = [[1.0] + [0.0] * 383 for _ in texts]
|
|
return array
|
|
|
|
model.encode.side_effect = encode
|
|
monkeypatch.setattr(main, "load_model", lambda: model)
|
|
return model
|
|
|
|
|
|
def test_prefixes_batch_and_metadata(model):
|
|
with TestClient(main.app) as client:
|
|
assert client.get("/health").status_code == 200
|
|
assert client.get("/model").json()["dimensions"] == 384
|
|
for kind in ("query", "passage"):
|
|
result = client.post("/embed", json={"input_type": kind, "texts": ["سلام", "text"]})
|
|
assert result.status_code == 200
|
|
assert len(result.json()["embeddings"]) == 2
|
|
assert len(result.json()["embeddings"][0]) == 384
|
|
assert model.encode.call_args.args[0] == [f"{kind}: سلام", f"{kind}: text"]
|
|
assert model.encode.call_args.kwargs["normalize_embeddings"]
|
|
|
|
|
|
def test_limits_and_validation_does_not_echo_content(model):
|
|
with TestClient(main.app) as client:
|
|
for payload in (
|
|
{"input_type": "secret-invalid", "texts": ["hello"]},
|
|
{"input_type": "query", "texts": []},
|
|
{"input_type": "query", "texts": [" "]},
|
|
{"input_type": "query", "texts": [123]},
|
|
{"input_type": "query", "texts": ["x"] * 33},
|
|
{"input_type": "query", "texts": ["x " * 513]},
|
|
{"input_type": "query", "texts": ["x" * 8193]},
|
|
):
|
|
response = client.post("/embed", json=payload)
|
|
assert response.status_code == 422
|
|
assert "secret-invalid" not in response.text
|
|
model.encode.assert_not_called()
|
|
|
|
|
|
def test_token_chunks_overlap_and_fit(model):
|
|
words = [f"واژه{i}" for i in range(150)]
|
|
with TestClient(main.app) as client:
|
|
response = client.post("/chunks", json={"text": " ".join(words), "size": 64, "overlap": 12})
|
|
assert response.status_code == 200
|
|
first, second, last = [chunk.split() for chunk in response.json()["chunks"]]
|
|
assert len(first) == 64
|
|
assert first[-12:] == second[:12]
|
|
assert last[-1] == words[-1]
|
|
assert client.post("/chunks", json={"text": "سلام", "size": 64, "overlap": 64}).status_code == 422
|
|
|
|
|
|
@pytest.mark.skipif(os.getenv("RAG_REAL_MODEL_TEST") != "1", reason="requires CPU model weights")
|
|
def test_real_model_contract():
|
|
with TestClient(main.app) as client:
|
|
assert main.app.state.model.device.type == "cpu"
|
|
response = client.post("/embed", json={
|
|
"input_type": "query",
|
|
"texts": ["فشار خون چیست؟", "What is blood pressure?"],
|
|
})
|
|
assert response.status_code == 200
|
|
assert response.json()["model"] == main.MODEL_ID
|
|
embeddings = response.json()["embeddings"]
|
|
assert len(embeddings) == 2
|
|
for embedding in embeddings:
|
|
assert len(embedding) == 384
|
|
assert math.isclose(sum(value * value for value in embedding), 1, abs_tol=1e-3)
|
|
|
|
text = "این بخش درباره فشار خون است. " * 240
|
|
chunk_response = client.post("/chunks", json={"text": text, "size": 440, "overlap": 88})
|
|
assert chunk_response.status_code == 200
|
|
passages = chunk_response.json()["chunks"]
|
|
assert 1 < len(passages) <= main.MAX_BATCH
|
|
passage_response = client.post("/embed", json={"input_type": "passage", "texts": passages})
|
|
assert passage_response.status_code == 200
|
|
assert len(passage_response.json()["embeddings"]) == len(passages)
|
|
|