| 1 | # Phase 0: Foundation Setup |
| 2 | |
| 3 | **Estimated Time**: 2-3 hours |
| 4 | **Priority**: CRITICAL - Must complete before other tasks |
| 5 | |
| 6 | --- |
| 7 | |
| 8 | ## Task 0.1: Add Testing Dependencies |
| 9 | |
| 10 | **File**: `/home/user/exabgp/pyproject.toml` |
| 11 | |
| 12 | **What to do**: |
| 13 | 1. Open `pyproject.toml` |
| 14 | 2. Locate the `[tool.uv]` section with `dev-dependencies` |
| 15 | 3. Add these new dependencies: |
| 16 | |
| 17 | ```toml |
| 18 | [tool.uv] |
| 19 | dev-dependencies = [ |
| 20 | "ruff", |
| 21 | "pytest", |
| 22 | "pytest-cov", |
| 23 | "coveralls", |
| 24 | "psutil", |
| 25 | "hypothesis>=6.0", # NEW: Property-based testing/fuzzing |
| 26 | "pytest-benchmark>=4.0", # NEW: Performance benchmarking |
| 27 | "pytest-xdist>=3.0", # NEW: Parallel test execution |
| 28 | "pytest-timeout>=2.0", # NEW: Timeout protection for tests |
| 29 | ] |
| 30 | ``` |
| 31 | |
| 32 | **Acceptance Criteria**: |
| 33 | - [ ] All 4 new dependencies added |
| 34 | - [ ] Version constraints specified (>=) |
| 35 | - [ ] File saved |
| 36 | |
| 37 | **Verification**: |
| 38 | ```bash |
| 39 | cd /home/user/exabgp |
| 40 | uv pip install -e ".[dev]" |
| 41 | python -c "import hypothesis; import pytest_benchmark; print('Success!')" |
| 42 | ``` |
| 43 | |
| 44 | --- |
| 45 | |
| 46 | ## Task 0.2: Update Coverage Configuration |
| 47 | |
| 48 | **File**: `/home/user/exabgp/.coveragerc` |
| 49 | |
| 50 | **What to do**: |
| 51 | 1. Open `.coveragerc` |
| 52 | 2. Find the `[run]` section |
| 53 | 3. Add branch coverage tracking: |
| 54 | |
| 55 | ```ini |
| 56 | [run] |
| 57 | branch = True # Track branch coverage, not just line coverage |
| 58 | omit = |
| 59 | */python?.?/* |
| 60 | dist-packages/* |
| 61 | usr/* |
| 62 | /qa/* |
| 63 | /dev/* |
| 64 | /debian/* |
| 65 | /systemd/* |
| 66 | */__init__.py |
| 67 | ``` |
| 68 | |
| 69 | 4. Find the `[report]` section |
| 70 | 5. Add coverage thresholds: |
| 71 | |
| 72 | ```ini |
| 73 | [report] |
| 74 | fail_under = 70 # Fail if coverage below 70% |
| 75 | show_missing = True |
| 76 | skip_covered = False |
| 77 | exclude_lines = |
| 78 | pragma: no cover |
| 79 | ^\s*pass\s*$ |
| 80 | ^\s*\.\.\.\s*$ |
| 81 | def __repr__ |
| 82 | if __name__ == .__main__.: |
| 83 | if TYPE_CHECKING: |
| 84 | @(abc\.)?abstractmethod |
| 85 | ``` |
| 86 | |
| 87 | **Acceptance Criteria**: |
| 88 | - [ ] `branch = True` added to `[run]` |
| 89 | - [ ] `fail_under = 70` added to `[report]` |
| 90 | - [ ] `show_missing = True` added |
| 91 | - [ ] File saved |
| 92 | |
| 93 | **Verification**: |
| 94 | ```bash |
| 95 | env PYTHONPATH=src pytest --cov --cov-report=term ./tests/cache_test.py |
| 96 | # Should show branch coverage in output |
| 97 | ``` |
| 98 | |
| 99 | --- |
| 100 | |
| 101 | ## Task 0.3: Create Test Directory Structure |
| 102 | |
| 103 | **What to do**: |
| 104 | ```bash |
| 105 | cd /home/user/exabgp/tests |
| 106 | mkdir -p fuzz |
| 107 | mkdir -p integration |
| 108 | mkdir -p performance |
| 109 | mkdir -p security |
| 110 | mkdir -p regression |
| 111 | ``` |
| 112 | |
| 113 | **Create `.gitkeep` files**: |
| 114 | ```bash |
| 115 | touch tests/fuzz/.gitkeep |
| 116 | touch tests/integration/.gitkeep |
| 117 | touch tests/performance/.gitkeep |
| 118 | touch tests/security/.gitkeep |
| 119 | touch tests/regression/.gitkeep |
| 120 | ``` |
| 121 | |
| 122 | **Acceptance Criteria**: |
| 123 | - [ ] 5 new directories created under `tests/` |
| 124 | - [ ] Each has a `.gitkeep` file |
| 125 | - [ ] Directory structure matches plan |
| 126 | |
| 127 | **Verification**: |
| 128 | ```bash |
| 129 | ls -la tests/fuzz tests/integration tests/performance tests/security tests/regression |
| 130 | ``` |
| 131 | |
| 132 | --- |
| 133 | |
| 134 | ## Task 0.4: Create Fuzzing Conftest |
| 135 | |
| 136 | **File**: `/home/user/exabgp/tests/fuzz/conftest.py` |
| 137 | |
| 138 | **What to do**: |
| 139 | Create a pytest configuration file for fuzzing tests: |
| 140 | |
| 141 | ```python |
| 142 | """Pytest configuration for fuzzing tests.""" |
| 143 | import pytest |
| 144 | from hypothesis import settings, HealthCheck |
| 145 | |
| 146 | # Configure Hypothesis for fuzzing |
| 147 | settings.register_profile( |
| 148 | "ci", |
| 149 | max_examples=100, |
| 150 | deadline=1000, |
| 151 | suppress_health_check=[HealthCheck.too_slow], |
| 152 | ) |
| 153 | |
| 154 | settings.register_profile( |
| 155 | "dev", |
| 156 | max_examples=50, |
| 157 | deadline=500, |
| 158 | ) |
| 159 | |
| 160 | settings.register_profile( |
| 161 | "extensive", |
| 162 | max_examples=10000, |
| 163 | deadline=None, |
| 164 | suppress_health_check=[HealthCheck.too_slow], |
| 165 | ) |
| 166 | |
| 167 | # Use dev profile by default |
| 168 | settings.load_profile("dev") |
| 169 | |
| 170 | |
| 171 | @pytest.fixture |
| 172 | def negotiated(): |
| 173 | """Fixture providing a mock negotiated capabilities object.""" |
| 174 | from exabgp.bgp.message.open.capability.negotiated import Negotiated |
| 175 | return Negotiated(None) |
| 176 | |
| 177 | |
| 178 | @pytest.fixture |
| 179 | def direction(): |
| 180 | """Fixture providing message direction.""" |
| 181 | from exabgp.bgp.message.direction import Direction |
| 182 | return Direction.IN |
| 183 | ``` |
| 184 | |
| 185 | **Acceptance Criteria**: |
| 186 | - [ ] File created at correct path |
| 187 | - [ ] Three Hypothesis profiles configured |
| 188 | - [ ] Fixtures for `negotiated` and `direction` added |
| 189 | - [ ] File saved |
| 190 | |
| 191 | **Verification**: |
| 192 | ```bash |
| 193 | python -c "import sys; sys.path.insert(0, 'tests/fuzz'); import conftest; print('Success!')" |
| 194 | ``` |
| 195 | |
| 196 | --- |
| 197 | |
| 198 | ## Task 0.5: Create Test Utilities Module |
| 199 | |
| 200 | **File**: `/home/user/exabgp/tests/unit/helpers.py` |
| 201 | |
| 202 | **What to do**: |
| 203 | Create a shared utilities module: |
| 204 | |
| 205 | ```python |
| 206 | """Shared test utilities and helpers.""" |
| 207 | |
| 208 | def create_bgp_header(length, msg_type): |
| 209 | """Create a BGP message header. |
| 210 | |
| 211 | Args: |
| 212 | length: Message length (19-4096) |
| 213 | msg_type: Message type (1-5) |
| 214 | |
| 215 | Returns: |
| 216 | bytes: BGP header (19 bytes) |
| 217 | """ |
| 218 | marker = b'\xFF' * 16 |
| 219 | length_bytes = length.to_bytes(2, 'big') |
| 220 | type_byte = bytes([msg_type]) |
| 221 | return marker + length_bytes + type_byte |
| 222 | |
| 223 | |
| 224 | def create_update_message(withdrawn_routes=b'', attributes=b'', announced_routes=b''): |
| 225 | """Create a BGP UPDATE message. |
| 226 | |
| 227 | Args: |
| 228 | withdrawn_routes: Withdrawn routes (prefixed with 2-byte length) |
| 229 | attributes: Path attributes (prefixed with 2-byte length) |
| 230 | announced_routes: Announced routes |
| 231 | |
| 232 | Returns: |
| 233 | bytes: Complete UPDATE message with header |
| 234 | """ |
| 235 | withdrawn_len = len(withdrawn_routes).to_bytes(2, 'big') |
| 236 | attr_len = len(attributes).to_bytes(2, 'big') |
| 237 | |
| 238 | body = withdrawn_len + withdrawn_routes + attr_len + attributes + announced_routes |
| 239 | header = create_bgp_header(19 + len(body), 2) # Type 2 = UPDATE |
| 240 | |
| 241 | return header + body |
| 242 | |
| 243 | |
| 244 | def create_open_message(asn=65000, holdtime=180, router_id='192.0.2.1', capabilities=b''): |
| 245 | """Create a BGP OPEN message. |
| 246 | |
| 247 | Args: |
| 248 | asn: AS number |
| 249 | holdtime: Hold time in seconds |
| 250 | router_id: Router ID as string |
| 251 | capabilities: Optional capabilities |
| 252 | |
| 253 | Returns: |
| 254 | bytes: Complete OPEN message with header |
| 255 | """ |
| 256 | import struct |
| 257 | |
| 258 | version = b'\x04' # BGP-4 |
| 259 | asn_bytes = asn.to_bytes(2, 'big') |
| 260 | holdtime_bytes = holdtime.to_bytes(2, 'big') |
| 261 | router_id_bytes = bytes(map(int, router_id.split('.'))) |
| 262 | |
| 263 | opt_param_len = len(capabilities) |
| 264 | if opt_param_len > 0: |
| 265 | opt_param_len += 2 # Include type and length bytes |
| 266 | |
| 267 | body = version + asn_bytes + holdtime_bytes + router_id_bytes |
| 268 | body += bytes([opt_param_len]) |
| 269 | |
| 270 | if capabilities: |
| 271 | body += b'\x02' # Parameter type: Capabilities |
| 272 | body += bytes([len(capabilities)]) |
| 273 | body += capabilities |
| 274 | |
| 275 | header = create_bgp_header(19 + len(body), 1) # Type 1 = OPEN |
| 276 | return header + body |
| 277 | |
| 278 | |
| 279 | class ExpectedException(Exception): |
| 280 | """Base class for expected exceptions in tests.""" |
| 281 | pass |
| 282 | |
| 283 | |
| 284 | def assert_clean_error(func, *args, **kwargs): |
| 285 | """Assert that a function raises only expected exceptions. |
| 286 | |
| 287 | Args: |
| 288 | func: Function to call |
| 289 | *args: Positional arguments |
| 290 | **kwargs: Keyword arguments |
| 291 | |
| 292 | Raises: |
| 293 | AssertionError: If unexpected exception raised |
| 294 | """ |
| 295 | from exabgp.bgp.message import Notify |
| 296 | |
| 297 | expected_exceptions = ( |
| 298 | Notify, |
| 299 | ValueError, |
| 300 | KeyError, |
| 301 | IndexError, |
| 302 | TypeError, |
| 303 | struct.error, |
| 304 | ) |
| 305 | |
| 306 | try: |
| 307 | func(*args, **kwargs) |
| 308 | except expected_exceptions: |
| 309 | # This is fine - these are expected error conditions |
| 310 | pass |
| 311 | except Exception as e: |
| 312 | # Unexpected exception type |
| 313 | raise AssertionError( |
| 314 | f"Unexpected exception: {type(e).__name__}: {e}\n" |
| 315 | f"Expected one of: {[e.__name__ for e in expected_exceptions]}" |
| 316 | ) |
| 317 | ``` |
| 318 | |
| 319 | **Acceptance Criteria**: |
| 320 | - [ ] File created with all helper functions |
| 321 | - [ ] Functions documented with docstrings |
| 322 | - [ ] `assert_clean_error` utility added |
| 323 | - [ ] File saved |
| 324 | |
| 325 | **Verification**: |
| 326 | ```bash |
| 327 | python -c "import sys; sys.path.insert(0, 'tests'); from helpers import create_bgp_header; print(create_bgp_header(19, 1).hex())" |
| 328 | ``` |
| 329 | |
| 330 | --- |
| 331 | |
| 332 | ## Task 0.6: Update pytest.ini Configuration |
| 333 | |
| 334 | **File**: `/home/user/exabgp/pytest.ini` (create if doesn't exist) |
| 335 | |
| 336 | **What to do**: |
| 337 | Create or update pytest configuration: |
| 338 | |
| 339 | ```ini |
| 340 | [pytest] |
| 341 | testpaths = tests |
| 342 | python_files = *_test.py test_*.py fuzz_*.py |
| 343 | python_classes = Test* |
| 344 | python_functions = test_* |
| 345 | addopts = |
| 346 | -v |
| 347 | --strict-markers |
| 348 | --tb=short |
| 349 | --hypothesis-show-statistics |
| 350 | |
| 351 | markers = |
| 352 | fuzz: Fuzzing tests using Hypothesis |
| 353 | integration: Integration tests requiring multiple components |
| 354 | performance: Performance and benchmark tests |
| 355 | security: Security-focused tests |
| 356 | slow: Tests that take significant time |
| 357 | |
| 358 | # Timeout for tests (prevent infinite loops) |
| 359 | timeout = 30 |
| 360 | timeout_method = thread |
| 361 | |
| 362 | # Coverage settings |
| 363 | [coverage:run] |
| 364 | source = src/exabgp |
| 365 | branch = True |
| 366 | |
| 367 | [coverage:report] |
| 368 | precision = 2 |
| 369 | show_missing = True |
| 370 | skip_covered = False |
| 371 | ``` |
| 372 | |
| 373 | **Acceptance Criteria**: |
| 374 | - [ ] File created or updated |
| 375 | - [ ] Test markers defined |
| 376 | - [ ] Timeout configured |
| 377 | - [ ] Coverage paths set |
| 378 | - [ ] File saved |
| 379 | |
| 380 | **Verification**: |
| 381 | ```bash |
| 382 | pytest --markers | grep -E "(fuzz|integration|performance|security)" |
| 383 | ``` |
| 384 | |
| 385 | --- |
| 386 | |
| 387 | ## Task 0.7: Create README for Test Directory |
| 388 | |
| 389 | **File**: `/home/user/exabgp/tests/README.md` |
| 390 | |
| 391 | **What to do**: |
| 392 | Create documentation for test organization: |
| 393 | |
| 394 | ```markdown |
| 395 | # ExaBGP Test Suite |
| 396 | |
| 397 | ## Directory Structure |
| 398 | |
| 399 | ``` |
| 400 | tests/ |
| 401 | ├── *_test.py # Unit tests (existing) |
| 402 | ├── fuzz/ # Fuzzing tests (Hypothesis) |
| 403 | ├── integration/ # Integration tests |
| 404 | ├── performance/ # Performance benchmarks |
| 405 | ├── security/ # Security-focused tests |
| 406 | ├── regression/ # Regression tests for bug fixes |
| 407 | └── helpers.py # Shared test utilities |
| 408 | ``` |
| 409 | |
| 410 | ## Running Tests |
| 411 | |
| 412 | ### All Tests |
| 413 | ```bash |
| 414 | env PYTHONPATH=src pytest |
| 415 | ``` |
| 416 | |
| 417 | ### Specific Category |
| 418 | ```bash |
| 419 | # Unit tests only |
| 420 | env PYTHONPATH=src pytest tests/unit/*_test.py |
| 421 | |
| 422 | # Fuzzing tests |
| 423 | env PYTHONPATH=src pytest tests/fuzz/ -m fuzz |
| 424 | |
| 425 | # Integration tests |
| 426 | env PYTHONPATH=src pytest tests/unit/ -m integration |
| 427 | |
| 428 | # Performance benchmarks |
| 429 | env PYTHONPATH=src pytest tests/unit/ --benchmark-only |
| 430 | ``` |
| 431 | |
| 432 | ### With Coverage |
| 433 | ```bash |
| 434 | env PYTHONPATH=src pytest --cov --cov-report=html |
| 435 | # Open htmlcov/index.html to view coverage report |
| 436 | ``` |
| 437 | |
| 438 | ### Parallel Execution |
| 439 | ```bash |
| 440 | env PYTHONPATH=src pytest -n auto |
| 441 | ``` |
| 442 | |
| 443 | ## Fuzzing Profiles |
| 444 | |
| 445 | Configure fuzzing intensity with environment variable: |
| 446 | |
| 447 | ```bash |
| 448 | # Fast (50 examples) |
| 449 | env HYPOTHESIS_PROFILE=dev pytest tests/fuzz/ |
| 450 | |
| 451 | # CI (100 examples) |
| 452 | env HYPOTHESIS_PROFILE=ci pytest tests/fuzz/ |
| 453 | |
| 454 | # Extensive (10,000 examples) |
| 455 | env HYPOTHESIS_PROFILE=extensive pytest tests/fuzz/ |
| 456 | ``` |
| 457 | |
| 458 | ## Writing Tests |
| 459 | |
| 460 | ### Unit Test Example |
| 461 | ```python |
| 462 | import unittest |
| 463 | from exabgp.bgp.message import Message |
| 464 | |
| 465 | class TestMyFeature(unittest.TestCase): |
| 466 | def test_basic_case(self): |
| 467 | result = Message.do_something() |
| 468 | self.assertEqual(result, expected) |
| 469 | ``` |
| 470 | |
| 471 | ### Fuzzing Test Example |
| 472 | ```python |
| 473 | import pytest |
| 474 | from hypothesis import given, strategies as st |
| 475 | |
| 476 | @pytest.mark.fuzz |
| 477 | @given(data=st.binary(min_size=0, max_size=4096)) |
| 478 | def test_parser_never_crashes(data): |
| 479 | try: |
| 480 | parse_message(data) |
| 481 | except (ValueError, KeyError): |
| 482 | pass # Expected errors |
| 483 | ``` |
| 484 | |
| 485 | ## Test Markers |
| 486 | |
| 487 | Use pytest markers to categorize tests: |
| 488 | |
| 489 | - `@pytest.mark.fuzz` - Fuzzing tests |
| 490 | - `@pytest.mark.integration` - Integration tests |
| 491 | - `@pytest.mark.performance` - Performance tests |
| 492 | - `@pytest.mark.security` - Security tests |
| 493 | - `@pytest.mark.slow` - Slow tests (skip in quick runs) |
| 494 | |
| 495 | Run specific markers: |
| 496 | ```bash |
| 497 | pytest -m fuzz # Only fuzzing tests |
| 498 | pytest -m "not slow" # Skip slow tests |
| 499 | ``` |
| 500 | ``` |
| 501 | |
| 502 | **Acceptance Criteria**: |
| 503 | - [ ] File created with comprehensive documentation |
| 504 | - [ ] Examples for each test type included |
| 505 | - [ ] Running instructions clear |
| 506 | - [ ] File saved |
| 507 | |
| 508 | **Verification**: |
| 509 | ```bash |
| 510 | cat tests/README.md | grep -E "(Directory Structure|Running Tests)" |
| 511 | ``` |
| 512 | |
| 513 | --- |
| 514 | |
| 515 | ## Task 0.8: Commit Foundation Changes |
| 516 | |
| 517 | **What to do**: |
| 518 | ```bash |
| 519 | cd /home/user/exabgp |
| 520 | git add pyproject.toml .coveragerc pytest.ini |
| 521 | git add tests/fuzz tests/integration tests/performance tests/security tests/regression |
| 522 | git add tests/unit/helpers.py tests/README.md |
| 523 | git add tests/fuzz/conftest.py |
| 524 | |
| 525 | git commit -m "Set up testing foundation infrastructure |
| 526 | |
| 527 | - Add Hypothesis, pytest-benchmark, pytest-xdist, pytest-timeout |
| 528 | - Configure coverage for branch tracking and 70% threshold |
| 529 | - Create test directory structure (fuzz, integration, performance, security, regression) |
| 530 | - Add fuzzing conftest with Hypothesis profiles |
| 531 | - Create shared test helpers and utilities |
| 532 | - Configure pytest with markers and settings |
| 533 | - Document test organization and usage" |
| 534 | ``` |
| 535 | |
| 536 | **Acceptance Criteria**: |
| 537 | - [ ] All new files staged |
| 538 | - [ ] Descriptive commit message |
| 539 | - [ ] Committed successfully |
| 540 | |
| 541 | **Verification**: |
| 542 | ```bash |
| 543 | git log -1 --stat |
| 544 | git status |
| 545 | ``` |
| 546 | |
| 547 | --- |
| 548 | |
| 549 | ## Completion Checklist |
| 550 | |
| 551 | - [ ] Task 0.1: Dependencies added to pyproject.toml |
| 552 | - [ ] Task 0.2: Coverage configuration updated |
| 553 | - [ ] Task 0.3: Test directories created |
| 554 | - [ ] Task 0.4: Fuzzing conftest created |
| 555 | - [ ] Task 0.5: Test helpers module created |
| 556 | - [ ] Task 0.6: pytest.ini configured |
| 557 | - [ ] Task 0.7: Test README documented |
| 558 | - [ ] Task 0.8: Changes committed |
| 559 | |
| 560 | **Estimated Total Time**: 2-3 hours |
| 561 | **Next File**: `01-FUZZ-MESSAGE-HEADER.md` |