File size: 8,132 Bytes
d4cede8 115794d d4cede8 115794d d4cede8 1a2c92d d4cede8 1a2c92d d4cede8 1a2c92d d4cede8 1a2c92d d4cede8 1a2c92d d4cede8 1a2c92d d4cede8 e7633a1 5b48ad6 8eb0662 5b48ad6 d4cede8 1a2c92d d4cede8 8eb0662 e7633a1 d4cede8 1a2c92d d4cede8 8eb0662 e7633a1 d4cede8 1a2c92d d4cede8 8eb0662 e7633a1 d4cede8 1a2c92d d4cede8 8eb0662 e7633a1 d4cede8 1a2c92d d4cede8 8eb0662 e7633a1 d4cede8 115794d d4cede8 1a2c92d d4cede8 115794d d4cede8 5b48ad6 d4cede8 5b48ad6 d4cede8 115794d | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 | import asyncio
import time
import pytest
from agents.acquisition_agent import AcquisitionAgent
from models.state import State
def make_pdf_bytes(long: bool = True) -> bytes:
import fitz
doc = fitz.open()
if long:
body = "This is a test. " * 100
for _ in range(3):
page = doc.new_page()
page.insert_textbox(fitz.Rect(72, 72, 500, 700), body)
else:
page = doc.new_page()
page.insert_textbox(fitz.Rect(72, 72, 500, 700), "Tiny")
return doc.write()
class MockContent:
def __init__(
self, data: bytes, delay_per_chunk: float = 0.0, chunk_size: int = 1024
):
self._data = data
self._delay = delay_per_chunk
self._chunk_size = chunk_size
async def aiter_content(self, chunk_size=1024):
for i in range(0, len(self._data), chunk_size):
if self._delay > 0:
await asyncio.sleep(self._delay)
yield self._data[i : i + chunk_size]
class MockResponse:
def __init__(self, status: int, data: bytes = b"", delay_per_chunk: float = 0.0):
self.status_code = status
self.content = MockContent(data, delay_per_chunk=delay_per_chunk)
async def __aenter__(self):
return self
async def __aexit__(self, exc_type, exc, tb):
return False
def aiter_content(self, chunk_size=1024):
return self.content.aiter_content(chunk_size)
class MockSession:
def __init__(self, mapping):
# mapping: url -> (status, bytes, delay_per_chunk)
self._map = mapping
async def __aenter__(self):
return self
async def __aexit__(self, exc_type, exc, tb):
return False
async def get(self, url, *args, **kwargs):
entry = self._map.get(url)
if entry is None:
raise RuntimeError("No mapping for URL")
status, data, delay = entry
return MockResponse(status, data, delay_per_chunk=delay)
@pytest.mark.unit
@pytest.mark.asyncio
async def test_acquisition_enriches_state_success(monkeypatch):
data = make_pdf_bytes(long=True)
url = "https://example.com/p1.pdf"
mapping = {url: (200, data, 0.0)}
async def session_factory(*args, **kwargs):
return MockSession(mapping)
monkeypatch.setattr(
"agents.acquisition_agent.AsyncSession", lambda *a, **k: MockSession(mapping)
)
state = State(
query="q",
finalists=[{"paperId": "abc123", "title": "T", "openAccessPdf": {"url": url}}],
)
agent = AcquisitionAgent()
agent.PER_PDF_TIMEOUT = 5.0
new_state = await agent.process(state)
assert new_state.passages is not None
assert len(new_state.passages) == 1
pdf_passages = [
p for p in new_state.passages if p.metadata.get("text_source") == "pdf"
]
assert len(pdf_passages) == 1
p = pdf_passages[0]
assert p.paper_id == "abc123"
assert p.metadata["text_source"] == "pdf"
assert len(p.text) > 500
@pytest.mark.unit
@pytest.mark.asyncio
async def test_acquisition_timeout_skips(monkeypatch):
# slow chunks cause timeout
data = make_pdf_bytes(long=True)
url = "https://example.com/slow.pdf"
mapping = {url: (200, data, 0.2)}
monkeypatch.setattr(
"agents.acquisition_agent.AsyncSession", lambda *a, **k: MockSession(mapping)
)
state = State(
query="q",
finalists=[{"paperId": "slow1", "title": "T", "openAccessPdf": {"url": url}}],
)
agent = AcquisitionAgent()
agent.PER_PDF_TIMEOUT = 0.05
new_state = await agent.process(state)
assert new_state.passages is not None
assert len(new_state.passages) == 0
@pytest.mark.unit
@pytest.mark.asyncio
async def test_acquisition_http_404_skips(monkeypatch):
url = "https://example.com/notfound.pdf"
mapping = {url: (404, b"", 0.0)}
monkeypatch.setattr(
"agents.acquisition_agent.AsyncSession", lambda *a, **k: MockSession(mapping)
)
state = State(
query="q",
finalists=[{"paperId": "nf", "title": "T", "openAccessPdf": {"url": url}}],
)
agent = AcquisitionAgent()
agent.PER_PDF_TIMEOUT = 1.0
new_state = await agent.process(state)
assert new_state.passages is not None
assert len(new_state.passages) == 0
@pytest.mark.unit
@pytest.mark.asyncio
async def test_acquisition_malformed_pdf_skips(monkeypatch):
# malformed PDF bytes should cause extraction to fail and be skipped
url = "https://example.com/bad.pdf"
mapping = {url: (200, b"not-a-pdf", 0.0)}
monkeypatch.setattr(
"curl_cffi.requests.AsyncSession", lambda *a, **k: MockSession(mapping)
)
state = State(
query="q",
finalists=[{"paperId": "bad1", "title": "T", "openAccessPdf": {"url": url}}],
)
agent = AcquisitionAgent()
agent.PER_PDF_TIMEOUT = 1.0
new_state = await agent.process(state)
# should be skipped
assert new_state.passages is not None
assert len(new_state.passages) == 0
@pytest.mark.unit
@pytest.mark.asyncio
async def test_acquisition_zero_successes_appends_error(monkeypatch):
# all 404 -> no successes -> state.errors contains critical message
urls = [f"https://example.com/n{i}.pdf" for i in range(3)]
mapping = {u: (404, b"", 0.0) for u in urls}
monkeypatch.setattr(
"agents.acquisition_agent.AsyncSession", lambda *a, **k: MockSession(mapping)
)
finalists = [
{"paperId": f"n{i}", "title": "T", "openAccessPdf": {"url": urls[i]}}
for i in range(3)
]
state = State(query="q", finalists=finalists)
agent = AcquisitionAgent()
agent.PER_PDF_TIMEOUT = 1.0
new_state = await agent.process(state)
assert new_state.passages is not None
assert len(new_state.passages) == 0
# Error since no PDFs acquired
assert new_state.errors
@pytest.mark.unit
@pytest.mark.asyncio
async def test_acquisition_get_raises_timeout(monkeypatch):
# simulate session.get raising a TimeoutError
class RaisingSession:
async def __aenter__(self):
return self
async def __aexit__(self, exc_type, exc, tb):
return False
def get(self, url, *args, **kwargs):
raise asyncio.TimeoutError()
monkeypatch.setattr(
"agents.acquisition_agent.AsyncSession", lambda *a, **k: RaisingSession()
)
state = State(
query="q",
finalists=[
{
"paperId": "tmo",
"title": "T",
"openAccessPdf": {"url": "https://example.com/x.pdf"},
}
],
)
agent = AcquisitionAgent()
agent.PER_PDF_TIMEOUT = 0.5
new_state = await agent.process(state)
assert new_state.passages is not None
assert len(new_state.passages) == 0
@pytest.mark.unit
@pytest.mark.asyncio
async def test_acquisition_parallel_10_with_2_failures(monkeypatch):
# 10 finalists: 8 fast, 2 slow (timeout)
urls = [f"https://example.com/p{i}.pdf" for i in range(10)]
mapping = {}
fast_bytes = make_pdf_bytes(long=True)
for i, u in enumerate(urls):
if i < 8:
mapping[u] = (200, fast_bytes, 0.0)
else:
mapping[u] = (200, fast_bytes, 2.0)
monkeypatch.setattr(
"agents.acquisition_agent.AsyncSession", lambda *a, **k: MockSession(mapping)
)
finalists = [
{"paperId": f"p{i}", "title": "T", "openAccessPdf": {"url": urls[i]}}
for i in range(10)
]
state = State(query="q", finalists=finalists)
agent = AcquisitionAgent()
# make timeouts small so test doesn't actually wait long
agent.PER_PDF_TIMEOUT = 1.0
start = time.monotonic()
new_state = await agent.process(state)
elapsed = time.monotonic() - start
# successful should be 5 PDFs (target limit)
passages = new_state.passages or []
assert len(passages) == 5
pdf_passages = [p for p in passages if p.metadata.get("text_source") == "pdf"]
assert len(pdf_passages) == 5
# requirement: return in under 4 seconds in real world; here ensure it's fast
assert elapsed < 4.0
assert elapsed < 4.0
|