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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
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
# Testing Guide

> **Last Updated**: 2025-12-06

This guide covers testing strategy, patterns, and best practices for DeepBoner.

## Quick Reference

```bash
# Run all tests
make test

# Run with coverage
make test-cov

# Run specific file
uv run pytest tests/unit/utils/test_config.py -v

# Run specific test
uv run pytest tests/unit/utils/test_config.py::TestSettings::test_default -v

# Run by marker
uv run pytest -m unit          # Unit tests only
uv run pytest -m integration   # Integration tests only
uv run pytest -m "not slow"    # Skip slow tests
```

## Test Organization

```
tests/
β”œβ”€β”€ conftest.py                 # Shared fixtures
β”œβ”€β”€ unit/                       # Unit tests (mocked, fast)
β”‚   β”œβ”€β”€ orchestrators/
β”‚   β”œβ”€β”€ agents/
β”‚   β”œβ”€β”€ clients/
β”‚   β”œβ”€β”€ tools/
β”‚   β”œβ”€β”€ services/
β”‚   β”œβ”€β”€ utils/
β”‚   β”œβ”€β”€ prompts/
β”‚   β”œβ”€β”€ agent_factory/
β”‚   β”œβ”€β”€ config/
β”‚   β”œβ”€β”€ graph/
β”‚   └── mcp/
β”œβ”€β”€ integration/                # Integration tests (real APIs)
└── e2e/                        # End-to-end tests
```

### Directory Mapping

Tests mirror the `src/` structure:
- `src/tools/pubmed.py` β†’ `tests/unit/tools/test_pubmed.py`
- `src/utils/config.py` β†’ `tests/unit/utils/test_config.py`

## Test Markers

### Available Markers

| Marker | Purpose | Example |
|--------|---------|---------|
| `@pytest.mark.unit` | Unit tests (mocked) | Most tests |
| `@pytest.mark.integration` | Real API calls | API testing |
| `@pytest.mark.slow` | Long-running tests | Full pipeline |
| `@pytest.mark.e2e` | End-to-end tests | Complete flows |

### Using Markers

```python
import pytest

@pytest.mark.unit
def test_search_returns_results():
    """Unit test with mocked API."""
    pass

@pytest.mark.integration
def test_pubmed_real_api():
    """Integration test with real PubMed API."""
    pass
```

### Running by Marker

```bash
uv run pytest -m unit              # Only unit tests
uv run pytest -m "not integration" # Skip integration tests
uv run pytest -m "unit or slow"    # Unit OR slow tests
```

## Test Fixtures

### Core Fixtures (conftest.py)

#### `mock_httpx_client`

Mocks httpx for HTTP testing:

```python
def test_pubmed_search(mock_httpx_client):
    mock_httpx_client.get("https://eutils.ncbi.nlm.nih.gov/...").respond(
        200,
        json={"esearchresult": {"idlist": ["12345"]}}
    )

    tool = PubMedTool()
    result = tool.search("test query")
    assert len(result.evidence) > 0
```

#### `mock_llm_response`

Mocks LLM completions:

```python
def test_judge_evaluates(mock_llm_response):
    mock_llm_response("The evidence is sufficient.")

    judge = JudgeAgent()
    assessment = judge.assess(evidence)
    assert assessment.sufficient
```

#### `sample_evidence`

Provides test evidence data:

```python
def test_synthesis(sample_evidence):
    report = synthesizer.create_report(sample_evidence)
    assert report.title
```

### Creating Fixtures

```python
# tests/conftest.py

@pytest.fixture
def mock_search_handler(mocker):
    """Mock SearchHandler for unit tests."""
    handler = mocker.Mock(spec=SearchHandler)
    handler.search_all.return_value = SearchResult(
        query="test",
        evidence=[],
        sources_searched=["pubmed"],
        total_found=0
    )
    return handler
```

## Mocking Patterns

### HTTP Mocking with respx

```python
import respx
from httpx import Response

@pytest.mark.unit
def test_api_call():
    with respx.mock:
        respx.get("https://api.example.com/data").mock(
            return_value=Response(200, json={"result": "ok"})
        )

        result = make_api_call()
        assert result == "ok"
```

### General Mocking with pytest-mock

```python
def test_with_mock(mocker):
    # Mock a function
    mock_func = mocker.patch("src.tools.pubmed.fetch_results")
    mock_func.return_value = {"results": []}

    # Mock a class method
    mocker.patch.object(PubMedTool, "search", return_value=[])

    # Mock a property
    mocker.patch.object(Settings, "has_openai_key", True)
```

### Mocking Async Functions

```python
import pytest
from unittest.mock import AsyncMock

@pytest.mark.asyncio
async def test_async_search(mocker):
    mock_search = AsyncMock(return_value=[])
    mocker.patch.object(SearchHandler, "search_all", mock_search)

    result = await handler.search_all("query")
    assert result == []
```

## Writing Tests

### Test Structure (AAA Pattern)

```python
def test_search_handler_aggregates_results():
    """Verify search handler combines results from multiple sources."""
    # Arrange
    handler = SearchHandler()
    query = "testosterone therapy"

    # Act
    result = handler.search_all(query)

    # Assert
    assert len(result.evidence) > 0
    assert "pubmed" in result.sources_searched
```

### Test Naming

```python
# Good: Describes behavior
def test_judge_returns_continue_when_evidence_insufficient():
    pass

def test_search_raises_rate_limit_error_on_429():
    pass

# Bad: Vague
def test_judge():
    pass

def test_search_error():
    pass
```

### Testing Exceptions

```python
import pytest
from src.utils.exceptions import SearchError

def test_search_raises_on_api_failure():
    """Verify SearchError is raised when API returns error."""
    with pytest.raises(SearchError) as exc_info:
        search_with_failing_api()

    assert "API returned 500" in str(exc_info.value)
```

### Async Tests

```python
import pytest

@pytest.mark.asyncio
async def test_async_search():
    """Test async search operation."""
    result = await search_handler.search_all("query")
    assert result is not None
```

## Test Data

### Using Factories

```python
# tests/factories.py

def make_evidence(
    content: str = "Test content",
    source: str = "pubmed",
    relevance: float = 0.8
) -> Evidence:
    return Evidence(
        content=content,
        citation=Citation(
            source=source,
            title="Test Paper",
            url="https://test.com",
            date="2024-01-01",
            authors=["Test Author"]
        ),
        relevance=relevance,
        metadata={}
    )
```

### Parameterized Tests

```python
import pytest

@pytest.mark.parametrize("query,expected_count", [
    ("testosterone", 10),
    ("estrogen therapy", 5),
    ("very specific rare condition", 0),
])
def test_search_returns_expected_results(query, expected_count, mock_api):
    result = search(query)
    assert len(result.evidence) == expected_count
```

## Coverage

### Running with Coverage

```bash
# Terminal report
make test-cov

# HTML report
uv run pytest --cov=src --cov-report=html
open htmlcov/index.html
```

### Coverage Configuration

From `pyproject.toml`:

```toml
[tool.coverage.run]
source = ["src"]
omit = ["*/__init__.py"]

[tool.coverage.report]
exclude_lines = [
    "pragma: no cover",
    "if TYPE_CHECKING:",
    "raise NotImplementedError",
]
```

### Coverage Targets

| Module | Target | Notes |
|--------|--------|-------|
| `utils/` | 90%+ | Core utilities |
| `tools/` | 80%+ | API wrappers |
| `orchestrators/` | 70%+ | Complex logic |
| `agents/` | 70%+ | LLM-dependent |

## CI Integration

Tests run in GitHub Actions:

```yaml
# .github/workflows/ci.yml
- name: Run Tests
  run: uv run pytest --cov=src --cov-report=xml

- name: Upload Coverage
  uses: codecov/codecov-action@v4
```

## Best Practices

### Do

- Write tests before implementation (TDD)
- Use descriptive test names
- Test edge cases and error conditions
- Keep tests fast (mock external dependencies)
- Use fixtures for shared setup
- Test one behavior per test

### Don't

- Test implementation details
- Make tests dependent on order
- Use real API keys in tests
- Skip error handling tests
- Leave flaky tests unfixed

## Troubleshooting

### Tests pass locally but fail in CI

1. Check for hardcoded paths
2. Verify timezone handling
3. Look for async timing issues
4. Check environment variables

### Async test hangs

```python
# Add timeout
@pytest.mark.asyncio
@pytest.mark.timeout(10)
async def test_with_timeout():
    pass
```

### Mock not working

```python
# Ensure correct import path
mocker.patch("src.tools.pubmed.PubMedTool")  # Correct
mocker.patch("tools.pubmed.PubMedTool")       # Wrong
```

---

## Related Documentation

- [Code Style Guide](code-style.md)
- [Contributing Guide](../../CONTRIBUTING.md)
- [Component Inventory](../architecture/component-inventory.md)