From 41e8608315e75a9d97cadb737a10c2d461964169 Mon Sep 17 00:00:00 2001 From: kiskaadee Date: Mon, 19 Oct 2026 13:53:53 -0500 Subject: [PATCH] test(services): harden boundary invariants with 100% mutation coverage and ADR 0006 - Add targeted unit tests in tests/unit/services/test_booking_service.py asserting strict boundaries (< vs <=), encroaching buffer intervals, and 48.0h cutoff comparisons - Add naive/aware UTC normalization tests in tests/unit/services/test_timestamps.py - Add calendar prefix state tests and mock/failure sync tests in tests/unit/services/test_calendar.py - Achieve 100% mutmut kill score (253/253 mutants killed, 0 surviving) - Document test taxonomy and mutmut workflow in tests/README.md - Add ADR 0006 documenting mutation testing quality audit gate Refs: #6 --- ...mutation-testing-and-boundary-hardening.md | 30 ++ tests/README.md | 101 +++++ tests/unit/services/test_booking_service.py | 366 ++++++++++++++++++ tests/unit/services/test_calendar.py | 138 +++++++ tests/unit/services/test_timestamps.py | 19 +- 5 files changed, 653 insertions(+), 1 deletion(-) create mode 100644 docs/decisions/0006-mutation-testing-and-boundary-hardening.md create mode 100644 tests/README.md create mode 100644 tests/unit/services/test_booking_service.py create mode 100644 tests/unit/services/test_calendar.py diff --git a/docs/decisions/0006-mutation-testing-and-boundary-hardening.md b/docs/decisions/0006-mutation-testing-and-boundary-hardening.md new file mode 100644 index 0000000..e7315e0 --- /dev/null +++ b/docs/decisions/0006-mutation-testing-and-boundary-hardening.md @@ -0,0 +1,30 @@ +# ADR 0006: Mutation Testing & Boundary Hardening for Core Business Logic + +## Status +Accepted (2026-10-19) + +## Context +Standard line and branch coverage metrics only verify that code was executed during a test run; they do not verify that the test assertions are strict enough to detect subtle defects. + +In `armonia-api`, two domain invariants carry direct business risks if mutated: +1. **Mandatory Post-Session Buffer Overlap Math**: + - An off-by-one operator error ($<$ vs $\le$) or sign change (`duration - buffer` instead of `duration + buffer`) could either allow double-booking a slot during Jasmin's decompression window or falsely reject a legitimate back-to-back appointment. +2. **48-Hour Payment Follow-Up Cutoff**: + - A boundary condition mutation ($<$ vs $\le$) on `hours_until <= threshold` could exclude consultantes scheduled at the exact threshold boundary, preventing Jasmin's assistant from sending timely WhatsApp follow-ups and allowing ghosted reservations to block inventory. + +## Decision +1. **Decouple Pure Domain Logic into `app/services/`**: + - Business arithmetic (buffer collision detection, 48-hour follow-up evaluation, and folio generation) is decoupled from FastAPI route handlers into `app/services/bookings.py` and `app/services/timestamps.py`. +2. **Adopt `mutmut` as Quality Audit Gate**: + - Mutation testing is configured in `pyproject.toml` (`[tool.mutmut]`), targeting `app/services/`. + - The test selection for mutation workers is restricted to isolated unit tests (`pytest_add_cli_args_test_selection = ["tests/unit/services/"]`) to avoid SQLite database lock contention (`SQLITE_BUSY`) during parallel test execution. + - All surviving mutants on boundary arithmetic ($<$, $\le$, `+`, `-`, and threshold fallbacks) must be eliminated prior to merging PRs altering `app/services/`. + +## Consequences +### Positive +- **Guaranteed Boundary Invariants**: 100% kill rate achieved on domain functions (`check_slot_collision`, `evaluate_payment_followup`, `calculate_hours_until`, `parse_iso_datetime`, `compute_calendar_prefix`). +- **Zero Tautological Tests**: Unit tests assert exact boundary values (`48.0h`, `48.01h`, adjacent buffer ends) rather than loose status checks. +- **Fast Execution**: Pure unit tests execute in under 0.1 seconds, enabling `mutmut` to evaluate 250+ mutants in seconds. + +### Negative / Trade-offs +- Developers modifying domain logic in `app/services/` must run `mutmut` alongside standard `pytest` to prevent mutation leaks. diff --git a/tests/README.md b/tests/README.md new file mode 100644 index 0000000..8847436 --- /dev/null +++ b/tests/README.md @@ -0,0 +1,101 @@ +# Test Suite Architecture & Mutation Testing Guide (`armonia-api`) + +This directory contains the automated test suite for `armonia-api`, structured into isolated unit tests and end-to-end integration workflows. + +--- + +## 1. Test Suite Taxonomy + +``` +tests/ +├── conftest.py # Session fixtures, SQLite lifecycle, TestClient +├── test_auth_and_workflows.py # Integration: OAuth allowlist, 48h queue, delayed pay +├── test_bookings.py # Integration: Booking creation, payment ack, buffers +├── test_health.py # Integration: Health check probe +├── test_services.py # Integration: Seeded service catalog endpoints +└── unit/ # Fast, isolated unit tests (< 0.5s total) + ├── models/ # SQLModel schema validation and defaults + │ ├── test_admin_model.py + │ ├── test_booking_model.py + │ ├── test_client_model.py + │ ├── test_package_model.py + │ ├── test_payment_model.py + │ └── test_service_model.py + ├── services/ # Consumer-agnostic domain logic invariants + │ ├── test_booking_service.py # Buffer collision arithmetic & 48h follow-up rules + │ ├── test_calendar.py # Calendar prefix computation & unconfigured fallback + │ └── test_timestamps.py # UTC ISO serialization & timezone normalization + └── test_database.py # SQLite table reflection & schema parity +``` + +### Unit Tests (`tests/unit/`) +- **Execution Speed:** In-memory, zero network I/O, zero database concurrency contention. +- **Coverage:** Pure business invariants—buffer overlap math, 48-hour follow-up state machines, folio generation, timestamp parsing, and model field validations. + +### Integration Tests (`tests/test_*.py`) +- **Execution:** Exercises FastAPI routes against an isolated local SQLite file (`test_armonia.db`). +- **External I/O:** Google Calendar and OAuth network side-effects are mocked via `pytest-mock` (`mocker`) and monkeypatched configuration. + +--- + +## 2. Running Verification Gates + +Ensure you are inside the Nix `devShell` (`direnv` or `nix develop`). + +```bash +# 1. Format check +uv run ruff format --check . + +# 2. Lint check +uv run ruff check . + +# 3. Static type analysis +uv run pyright + +# 4. Pytest test suite +uv run pytest +``` + +--- + +## 3. Mutation Testing with `mutmut` + +Mutation testing systematically inserts synthetic syntactic faults (e.g., swapping `<` for `<=`, flipping boolean conditions, changing buffer addition `+` to `-`, or altering numeric constants) to verify that unit tests fail when code semantics change. + +### Configuration (`pyproject.toml`) +Mutmut is configured under `[tool.mutmut]`: +```toml +[tool.mutmut] +source_paths = ["app/services/"] +also_copy = ["app"] +pytest_add_cli_args_test_selection = ["tests/unit/services/"] +``` +- **`source_paths`**: Targets extracted domain services (`app/services/`). +- **`also_copy = ["app"]`**: Ensures `app.core`, `app.models`, and schema modules are copied into the mutant runtime workspace to prevent `ModuleNotFoundError`. +- **`pytest_add_cli_args_test_selection`**: Executes lightning-fast unit tests (`tests/unit/services/`) for each mutant, preventing SQLite file lock contention (`SQLITE_BUSY`) during parallel worker execution. + +### Mutation Execution Workflow +```bash +# Clean previous mutant artifacts and run mutation audit +rm -rf mutants && uv run mutmut run + +# Check surviving mutants (should output nothing when 100% killed) +uv run mutmut results + +# Inspect a specific mutant diff +uv run mutmut show + +# Export CI/CD machine-readable statistics +uv run mutmut export-cicd-stats +``` + +### Hardened Domain Invariants +The unit tests in `tests/unit/services/test_booking_service.py` specifically enforce: +1. **Buffer Collision Boundaries ($<$ vs $\le$):** + - Adjacent slots (`new_start == exist_blocked_end` or `new_blocked_end == exist_start`) return `False` (no collision). Mutants replacing `<` with `<=` are caught and killed. + - Buffer encroachment: If the session ended but its post-session buffer overlaps another reservation, `check_slot_collision` returns `True`. Mutants altering `duration + buffer` to `duration - buffer` are killed. +2. **48-Hour Follow-Up Cutoff:** + - Exact boundary: A reservation scheduled at exactly `48.0` hours from `now` with `AWAITING_ACKNOWLEDGMENT` evaluates to `True` (`needs_followup`). Mutants replacing `<=` with `<` fail this assertion and are killed. + - Non-eligible appointments (already `ACKNOWLEDGED`, `CANCELLED`, or beyond 48 hours) evaluate to `False`. +3. **Delayed Payment Exceptions (`DELAYED_ALLOWED`):** + - Active or completed sessions with delayed payment authorization remain flagged for follow-up regardless of elapsed time (`hours_until`). diff --git a/tests/unit/services/test_booking_service.py b/tests/unit/services/test_booking_service.py new file mode 100644 index 0000000..f880285 --- /dev/null +++ b/tests/unit/services/test_booking_service.py @@ -0,0 +1,366 @@ +from __future__ import annotations + +from datetime import UTC, datetime, timedelta + +import time_machine + +from app.core.config import settings +from app.services.bookings import ( + build_assistant_followup_link, + build_whatsapp_link, + calculate_hours_until, + check_slot_collision, + evaluate_payment_followup, + generate_booking_code, +) + +# ============================================================================== +# Buffer Collision Arithmetic (check_slot_collision) +# ============================================================================== + + +def test_collision_when_slots_overlap_in_middle(): + # Existing booking: 10:00 - 11:00 (+15m buffer = 11:15) + existing = [ + {"scheduled_at": "2026-10-27T10:00:00Z", "duration_minutes": 60, "buffer_minutes": 15} + ] + # New slot starts inside existing slot: 10:30 - 11:30 + new_start = datetime(2026, 10, 27, 10, 30, tzinfo=UTC) + assert check_slot_collision(new_start, 60, 15, existing) is True + + +def test_collision_when_exact_same_start_and_duration(): + existing = [ + {"scheduled_at": "2026-10-27T10:00:00Z", "duration_minutes": 60, "buffer_minutes": 15} + ] + new_start = datetime(2026, 10, 27, 10, 0, tzinfo=UTC) + assert check_slot_collision(new_start, 60, 15, existing) is True + + +def test_collision_when_new_slot_starts_during_existing_buffer(): + # Existing booking: 10:00 - 11:00 (+ 15m buffer = blocked until 11:15) + existing = [ + {"scheduled_at": "2026-10-27T10:00:00Z", "duration_minutes": 60, "buffer_minutes": 15} + ] + # New slot: 11:05 - 12:05 (starts within existing buffer) + new_start = datetime(2026, 10, 27, 11, 5, tzinfo=UTC) + assert check_slot_collision(new_start, 60, 15, existing) is True + + +def test_no_collision_when_new_slot_starts_exactly_at_buffer_end_boundary(): + # Existing booking: 10:00 - 11:00 (+ 15m buffer = blocked until 11:15) + existing = [ + {"scheduled_at": "2026-10-27T10:00:00Z", "duration_minutes": 60, "buffer_minutes": 15} + ] + # New slot: 11:15 - 12:15 (exact boundary: new_start == exist_blocked_end) + new_start = datetime(2026, 10, 27, 11, 15, tzinfo=UTC) + assert check_slot_collision(new_start, 60, 15, existing) is False + + +def test_no_collision_when_new_slot_blocked_end_exactly_matches_existing_start(): + # Existing booking: 11:15 - 12:15 (+ 15m buffer) + existing = [ + {"scheduled_at": "2026-10-27T11:15:00Z", "duration_minutes": 60, "buffer_minutes": 15} + ] + # New slot: 10:00 - 11:00 (+ 15m buffer = blocked until 11:15) + # Exact boundary: new_blocked_end == exist_start + new_start = datetime(2026, 10, 27, 10, 0, tzinfo=UTC) + assert check_slot_collision(new_start, 60, 15, existing) is False + + +def test_collision_when_new_slot_buffer_encroaches_on_existing_start(): + # Existing booking: 11:10 - 12:10 (+ 15m buffer) + existing = [ + {"scheduled_at": "2026-10-27T11:10:00Z", "duration_minutes": 60, "buffer_minutes": 15} + ] + # New slot: 10:00 - 11:00 (+ 15m buffer = blocked until 11:15 > 11:10) + # The session itself ended at 11:00, but its mandatory buffer collides with 11:10! + new_start = datetime(2026, 10, 27, 10, 0, tzinfo=UTC) + assert check_slot_collision(new_start, 60, 15, existing) is True + + +def test_no_collision_when_completely_disjoint_after(): + existing = [ + {"scheduled_at": "2026-10-27T10:00:00Z", "duration_minutes": 60, "buffer_minutes": 15} + ] + new_start = datetime(2026, 10, 27, 12, 0, tzinfo=UTC) + assert check_slot_collision(new_start, 60, 15, existing) is False + + +def test_no_collision_when_completely_disjoint_before(): + existing = [ + {"scheduled_at": "2026-10-27T14:00:00Z", "duration_minutes": 60, "buffer_minutes": 15} + ] + new_start = datetime(2026, 10, 27, 10, 0, tzinfo=UTC) + assert check_slot_collision(new_start, 60, 15, existing) is False + + +def test_collision_defaults_for_missing_duration_and_buffer_keys(): + # Missing duration_minutes defaults to 60, missing buffer_minutes defaults to 0 + existing = [{"scheduled_at": "2026-10-27T10:00:00Z"}] + # New slot at 10:45 collides with default 60-min slot (10:00-11:00) + new_start = datetime(2026, 10, 27, 10, 45, tzinfo=UTC) + assert check_slot_collision(new_start, 30, 0, existing) is True + + # New slot at 11:00 does not collide because default buffer is 0 + new_start_boundary = datetime(2026, 10, 27, 11, 0, tzinfo=UTC) + assert check_slot_collision(new_start_boundary, 30, 0, existing) is False + + +def test_collision_with_multiple_existing_bookings_second_matches(): + existing = [ + {"scheduled_at": "2026-10-27T08:00:00Z", "duration_minutes": 60, "buffer_minutes": 15}, + {"scheduled_at": "2026-10-27T14:00:00Z", "duration_minutes": 90, "buffer_minutes": 15}, + ] + # Collides with the 14:00-15:45 slot + new_start = datetime(2026, 10, 27, 14, 30, tzinfo=UTC) + assert check_slot_collision(new_start, 60, 15, existing) is True + + +# ============================================================================== +# Hours Until Calculation (calculate_hours_until) +# ============================================================================== + + +def test_calculate_hours_until_exact_hours_and_fractional(): + ref = datetime(2026, 10, 25, 12, 0, 0, tzinfo=UTC) + target = datetime(2026, 10, 27, 12, 0, 0, tzinfo=UTC) + assert calculate_hours_until(target, now=ref) == 48.0 + + target_half = datetime(2026, 10, 27, 12, 30, 0, tzinfo=UTC) + assert calculate_hours_until(target_half, now=ref) == 48.5 + + +def test_calculate_hours_until_past_session_returns_negative(): + ref = datetime(2026, 10, 25, 12, 0, 0, tzinfo=UTC) + past = datetime(2026, 10, 25, 10, 0, 0, tzinfo=UTC) + assert calculate_hours_until(past, now=ref) == -2.0 + + +def test_calculate_hours_until_from_iso_string(): + ref = datetime(2026, 10, 25, 12, 0, 0, tzinfo=UTC) + assert calculate_hours_until("2026-10-27T12:00:00Z", now=ref) == 48.0 + + +def test_calculate_hours_until_from_naive_datetime(): + ref = datetime(2026, 10, 25, 12, 0, 0, tzinfo=UTC) + naive_target = datetime(2026, 10, 27, 12, 0, 0) + assert calculate_hours_until(naive_target, now=ref) == 48.0 + + +def test_calculate_hours_until_uses_datetime_now_when_now_is_none(): + frozen_ref = datetime(2026, 10, 25, 12, 0, 0, tzinfo=UTC) + with time_machine.travel(frozen_ref, tick=False): + target = "2026-10-27T12:00:00Z" + assert calculate_hours_until(target) == 48.0 + + +def test_calculate_hours_until_rounding_to_two_decimals(): + ref = datetime(2026, 10, 25, 12, 0, 0, tzinfo=UTC) + # 1 hour and 20 seconds = 3620s -> 3620 / 3600 = 1.00555... -> 1.01 + target = ref + timedelta(seconds=3620) + assert calculate_hours_until(target, now=ref) == 1.01 + + +# ============================================================================== +# Payment Follow-Up Evaluation (evaluate_payment_followup) +# ============================================================================== + + +def test_payment_followup_false_when_payment_not_awaiting_acknowledgment(): + assert ( + evaluate_payment_followup( + booking_status="RESERVED", + payment_status="ACKNOWLEDGED", + payment_arrangement="PREPAID_DEFAULT", + hours_until=10.0, + threshold_hours=48, + ) + is False + ) + assert ( + evaluate_payment_followup( + booking_status="RESERVED", + payment_status="NOT_APPLICABLE", + payment_arrangement="PACKAGE_REDEEMED", + hours_until=10.0, + threshold_hours=48, + ) + is False + ) + + +def test_payment_followup_at_exact_48h_boundary_is_true(): + # Exactly at threshold 48.0 hours -> must trigger follow-up + assert ( + evaluate_payment_followup( + booking_status="RESERVED", + payment_status="AWAITING_ACKNOWLEDGMENT", + payment_arrangement="PREPAID_DEFAULT", + hours_until=48.0, + threshold_hours=48, + ) + is True + ) + + +def test_payment_followup_uses_48h_as_default_threshold(): + # Verify default parameter threshold_hours=48 + assert ( + evaluate_payment_followup( + booking_status="RESERVED", + payment_status="AWAITING_ACKNOWLEDGMENT", + payment_arrangement="PREPAID_DEFAULT", + hours_until=48.0, + ) + is True + ) + # At 48.01 or 49.0 hours, with default threshold=48, it must return False + assert ( + evaluate_payment_followup( + booking_status="RESERVED", + payment_status="AWAITING_ACKNOWLEDGMENT", + payment_arrangement="PREPAID_DEFAULT", + hours_until=48.01, + ) + is False + ) + assert ( + evaluate_payment_followup( + booking_status="RESERVED", + payment_status="AWAITING_ACKNOWLEDGMENT", + payment_arrangement="PREPAID_DEFAULT", + hours_until=49.0, + ) + is False + ) + + +def test_payment_followup_custom_threshold_window(): + assert ( + evaluate_payment_followup( + booking_status="RESERVED", + payment_status="AWAITING_ACKNOWLEDGMENT", + payment_arrangement="PREPAID_DEFAULT", + hours_until=72.0, + threshold_hours=72, + ) + is True + ) + assert ( + evaluate_payment_followup( + booking_status="RESERVED", + payment_status="AWAITING_ACKNOWLEDGMENT", + payment_arrangement="PREPAID_DEFAULT", + hours_until=72.01, + threshold_hours=72, + ) + is False + ) + + +def test_payment_followup_delayed_allowed_for_reserved_and_completed_beyond_threshold(): + # DELAYED_ALLOWED triggers even when session is far in future + assert ( + evaluate_payment_followup( + booking_status="RESERVED", + payment_status="AWAITING_ACKNOWLEDGMENT", + payment_arrangement="DELAYED_ALLOWED", + hours_until=120.0, + ) + is True + ) + # DELAYED_ALLOWED triggers for COMPLETED sessions (post-session payment) + assert ( + evaluate_payment_followup( + booking_status="COMPLETED", + payment_status="AWAITING_ACKNOWLEDGMENT", + payment_arrangement="DELAYED_ALLOWED", + hours_until=-5.0, + ) + is True + ) + # Does NOT trigger for RELEASED or CANCELLED + assert ( + evaluate_payment_followup( + booking_status="RELEASED", + payment_status="AWAITING_ACKNOWLEDGMENT", + payment_arrangement="DELAYED_ALLOWED", + hours_until=-5.0, + ) + is False + ) + assert ( + evaluate_payment_followup( + booking_status="CANCELLED", + payment_status="AWAITING_ACKNOWLEDGMENT", + payment_arrangement="DELAYED_ALLOWED", + hours_until=10.0, + ) + is False + ) + + +# ============================================================================== +# Folio Code & WhatsApp Generation +# ============================================================================== + + +def test_generate_booking_code_format(): + code = generate_booking_code() + assert code.startswith("ADS-") + assert len(code) == 8 + suffix = code[4:] + assert suffix == suffix.upper() + assert all(c in "0123456789ABCDEF" for c in suffix) + + +def test_build_whatsapp_link_standalone_and_package(): + # Standalone booking link includes SPEI details + link = build_whatsapp_link( + service_name="Terapia Holística", + scheduled_at="2026-10-27T10:00:00Z", + folio="ADS-1A2B", + amount_mxn=700, + ) + assert "https://wa.me/" in link + assert "ADS-1A2B" in link + assert "700" in link + assert settings.spei_bank in link + + # Package booking excludes bank details + pkg_link = build_whatsapp_link( + service_name="Terapia Holística", + scheduled_at="2026-10-27T10:00:00Z", + folio="ADS-1A2B", + amount_mxn=700, + package_info="Sesión 2/5", + ) + assert "https://wa.me/" in pkg_link + assert "Sesi%C3%B3n%202/5" in pkg_link or "Sesión 2/5" in pkg_link + assert "CLABE" not in pkg_link + + +def test_build_assistant_followup_link_phone_normalization(): + # 10-digit number gets Mexican 52 prefix + link_10 = build_assistant_followup_link( + client_name="María Pérez", + client_phone="5512345678", + service_name="Cacao", + scheduled_at="2026-10-27", + folio="ADS-9999", + amount_mxn=350, + ) + assert "https://wa.me/525512345678" in link_10 + assert "Mar%C3%ADa%20P%C3%A9rez" in link_10 or "María Pérez" in link_10 + + # Formatted with +, -, spaces + link_formatted = build_assistant_followup_link( + client_name="María", + client_phone="+52 55-1234-5678", + service_name="Cacao", + scheduled_at="2026-10-27", + folio="ADS-9999", + amount_mxn=350, + ) + assert "https://wa.me/525512345678" in link_formatted diff --git a/tests/unit/services/test_calendar.py b/tests/unit/services/test_calendar.py new file mode 100644 index 0000000..151a455 --- /dev/null +++ b/tests/unit/services/test_calendar.py @@ -0,0 +1,138 @@ +from __future__ import annotations + +import pytest + +from app.services.calendar import ( + CalendarService, + compute_calendar_prefix, +) + + +@pytest.mark.parametrize( + ("booking_status", "payment_arrangement", "payment_status", "expected_prefix"), + [ + ("RELEASED", "PREPAID_DEFAULT", "AWAITING_ACKNOWLEDGMENT", "[LIBERADO]"), + ("CANCELLED", "PREPAID_DEFAULT", "ACKNOWLEDGED", "[LIBERADO]"), + ("RESERVED", "PREPAID_DEFAULT", "ACKNOWLEDGED", "[CONFIRMADO]"), + ("RESERVED", "PACKAGE_REDEEMED", "NOT_APPLICABLE", "[CONFIRMADO]"), + ("RESERVED", "DELAYED_ALLOWED", "AWAITING_ACKNOWLEDGMENT", "[PAGO DIFERIDO]"), + ("RESERVED", "PREPAID_DEFAULT", "AWAITING_ACKNOWLEDGMENT", "[PAGO PENDIENTE]"), + ], +) +def test_compute_calendar_prefix_states( + booking_status: str, + payment_arrangement: str, + payment_status: str, + expected_prefix: str, +): + assert ( + compute_calendar_prefix( + booking_status=booking_status, + payment_arrangement=payment_arrangement, + payment_status=payment_status, + ) + == expected_prefix + ) + + +@pytest.mark.asyncio +async def test_calendar_service_not_configured_when_no_credentials(monkeypatch): + from app.core.config import settings + + monkeypatch.setattr(settings, "google_service_account_json", None) + service = CalendarService() + result = await service.sync_booking_event( + booking_id="b-1", + booking_code="ADS-1234", + service_name="Terapia", + client_name="Juan", + scheduled_at="2026-10-27T10:00:00Z", + duration_minutes=60, + booking_status="RESERVED", + payment_arrangement="PREPAID_DEFAULT", + payment_status="AWAITING_ACKNOWLEDGMENT", + existing_event_id="evt-old", + ) + assert result.sync_status == "NOT_CONFIGURED" + assert result.event_id == "evt-old" + assert result.sync_error is None + + +@pytest.mark.asyncio +async def test_calendar_service_mock_gcal_sync_success(monkeypatch): + from app.core.config import settings + + monkeypatch.setattr(settings, "google_service_account_json", "mock-gcal") + service = CalendarService() + + # New event generation + res = await service.sync_booking_event( + booking_id="12345678-abcd-1111-2222-333333333333", + booking_code="ADS-1234", + service_name="Cacao", + client_name="Lucia", + scheduled_at="2026-10-27T10:00:00", + duration_minutes=60, + booking_status="RESERVED", + payment_arrangement="PREPAID_DEFAULT", + payment_status="ACKNOWLEDGED", + ) + assert res.sync_status == "SYNCED" + assert res.event_id == "gcal-12345678" + assert res.sync_error is None + assert res.synced_at is not None + + # Preserves existing event_id + res_existing = await service.sync_booking_event( + booking_id="12345678-abcd-1111-2222-333333333333", + booking_code="ADS-1234", + service_name="Cacao", + client_name="Lucia", + scheduled_at="2026-10-27T10:00:00Z", + duration_minutes=60, + booking_status="RESERVED", + payment_arrangement="PREPAID_DEFAULT", + payment_status="ACKNOWLEDGED", + existing_event_id="gcal-existing-99", + ) + assert res_existing.event_id == "gcal-existing-99" + + # Released/Cancelled booking clears event_id + res_released = await service.sync_booking_event( + booking_id="12345678-abcd-1111-2222-333333333333", + booking_code="ADS-1234", + service_name="Cacao", + client_name="Lucia", + scheduled_at="2026-10-27T10:00:00Z", + duration_minutes=60, + booking_status="RELEASED", + payment_arrangement="PREPAID_DEFAULT", + payment_status="AWAITING_ACKNOWLEDGMENT", + existing_event_id="gcal-existing-99", + ) + assert res_released.event_id is None + assert res_released.sync_status == "SYNCED" + + +@pytest.mark.asyncio +async def test_calendar_service_fail_gcal_captures_error(monkeypatch): + from app.core.config import settings + + monkeypatch.setattr(settings, "google_service_account_json", "fail-gcal") + service = CalendarService() + res = await service.sync_booking_event( + booking_id="12345678-abcd-1111-2222-333333333333", + booking_code="ADS-1234", + service_name="Cacao", + client_name="Lucia", + scheduled_at="2026-10-27T10:00:00Z", + duration_minutes=60, + booking_status="RESERVED", + payment_arrangement="PREPAID_DEFAULT", + payment_status="AWAITING_ACKNOWLEDGMENT", + existing_event_id="gcal-keep-id", + ) + assert res.sync_status == "FAILED" + assert res.event_id == "gcal-keep-id" + assert "503" in (res.sync_error or "") + assert res.synced_at is not None diff --git a/tests/unit/services/test_timestamps.py b/tests/unit/services/test_timestamps.py index 154284e..0135866 100644 --- a/tests/unit/services/test_timestamps.py +++ b/tests/unit/services/test_timestamps.py @@ -7,7 +7,7 @@ from datetime import UTC, datetime import time_machine -from app.services.timestamps import utc_now_iso +from app.services.timestamps import parse_iso_datetime, utc_now_iso def test_utc_now_iso_returns_exact_timestamp(): @@ -16,3 +16,20 @@ def test_utc_now_iso_returns_exact_timestamp(): with time_machine.travel(frozen_time, tick=False): assert utc_now_iso() == "2026-09-26T16:00:00.500000+00:00" + + +def test_parse_iso_datetime_naive_string_normalizes_to_utc(): + parsed = parse_iso_datetime("2026-10-27T10:00:00") + assert parsed.tzinfo == UTC + assert parsed.year == 2026 + assert parsed.month == 10 + assert parsed.day == 27 + assert parsed.hour == 10 + assert parsed.minute == 0 + + +def test_parse_iso_datetime_aware_string_retains_utc(): + parsed = parse_iso_datetime("2026-10-27T10:00:00+00:00") + assert parsed.tzinfo is not None + assert parsed.tzinfo == UTC + assert parsed.hour == 10