diff --git a/docs/reports/lab5-additions.md b/docs/reports/lab5-additions.md new file mode 100644 index 0000000..caa4b80 --- /dev/null +++ b/docs/reports/lab5-additions.md @@ -0,0 +1,31 @@ +# تغییرات آزمایش ۵ و اجرای تست‌ها + +در این محیط ویندوز، برای اتصال مستقیم به PostgreSQL از `127.0.0.1` استفاده کنید؛ `localhost` ممکن است در اتصال معطل بماند. برای پرهیز از استفاده از دیتابیس تست قدیمی با migrationهای ناسازگار، در PowerShell قبل از اجرای pytest مقدارهای زیر را تنظیم کنید: + +```powershell +$env:POSTGRES_HOST = '127.0.0.1' +$env:POSTGRES_DB = 'lab5_verify_20261108' +``` + +pytest یک دیتابیس آزمایشی به نام `test_lab5_verify_20261108` می‌سازد؛ استفاده از `--create-db` دیتابیس آزمایشی هم‌نام را بازسازی می‌کند. تست‌های همسایه فقط با گزینهٔ `--run-neighbor-contract` اجرا می‌شوند. نتیجهٔ Prism بر اساس پیش‌نویس، تأیید سرویس واقعی S2 نیست. + +آزمون‌های تطابق پاسخ APIهای قوانین و health با `openapi/s4_rsk.yaml` در گروه `openapi` قرار دارند. برای اجرای تمام تست‌های بک‌اند از ریشه در PowerShell، با PostgreSQL آزمایشی آماده: + +```powershell +cd s4_rsk +..\.venv\Scripts\python.exe -m pytest --create-db +``` + +بعد از اعمال migration جدید، `--create-db` دیتابیس **تست** را بازسازی می‌کند. در دفعات بعد می‌توانید این گزینه را حذف کنید. برای اجرای تست‌های قرارداد سرویس خودمان از همین پوشه `..\.venv\Scripts\python.exe -m pytest -m openapi` را اجرا کنید. + +در فرانت‌اند `cd frontend`، سپس `npm ci` و `npm test` را اجرا کنید. تست‌ها از Vitest و React Testing Library استفاده می‌کنند و درخواست واقعی به بک‌اند نمی‌فرستند. + +## دفترکل S2 + +`openapi/neighbors/s2_ldg.yaml` فقط **پیش‌نویس فرضی** است و قرارداد تأییدشدهٔ تیم S2 نیست. کلاینت دفترکل و تست‌های MockTransport آماده بررسی‌اند، اما به ارزیابی واقعی تراکنش وصل نشده‌اند. برای اتصال واقعی باید قرارداد و نحوهٔ احراز هویت با تیم S2 توافق و بعد پیاده‌سازی و تست شود. + +تست‌های `contract` به‌طور پیش‌فرض اجرا نمی‌شوند. پس از آماده‌کردن Prism یا سرویس آزمایشی و جایگزینی قرارداد تأییدشده، آدرس مورد اعتماد را در `NEIGHBOR_BASE_URL` تنظیم کنید و از `s4_rsk` با `..\.venv\Scripts\python.exe -m pytest -m contract --run-neighbor-contract` اجرا کنید. این دستور به سرویس مشخص‌شده درخواست واقعی می‌فرستد. برای حساب‌های آزمایشی از `NEIGHBOR_ACCOUNT_ID_OK` و `NEIGHBOR_ACCOUNT_ID_MISSING` استفاده کنید. + +برای تمرین با همین پیش‌نویس، از ریشه `prism mock openapi/neighbors/s2_ldg.yaml -p 4010` را اجرا کنید. در ترمینال دوم و پوشهٔ `s4_rsk` مقدار `$env:NEIGHBOR_BASE_URL='http://127.0.0.1:4010'` را تنظیم کنید و دستور تست بالا را اجرا کنید. پاسخ ۴۰۴ در این آزمون با هدر مخصوص Prism شبیه‌سازی می‌شود؛ موفقیت در Prism به معنی تأیید سرویس واقعی نیست. + +اسکریپت نمونهٔ ساخت کاربر و seed خودکار بسته ادغام نشده است: نسخهٔ پیشنهادی می‌تواند حساب موجود را فعال کند، رمز آن را تغییر دهد یا fixture را مجدداً بارگذاری کند. برای ساخت کاربر به [راهنمای JWT](jwt-authentication.md) مراجعه کنید. diff --git a/docs/test-matrices/README.md b/docs/test-matrices/README.md index 7be8999..4b4e4c2 100644 --- a/docs/test-matrices/README.md +++ b/docs/test-matrices/README.md @@ -12,3 +12,5 @@ - [US-02 مدیریت قوانین](us-02.md) - [US-08 توضیح‌پذیری تصمیم، پیش‌نویس](us-08-draft.md) +- [تست‌های فرانت‌اند](frontend.md) +- [پیش‌نویس تست مصرف‌کننده دفترکل](ledger-consumer.md) diff --git a/docs/test-matrices/frontend.md b/docs/test-matrices/frontend.md new file mode 100644 index 0000000..ce12249 --- /dev/null +++ b/docs/test-matrices/frontend.md @@ -0,0 +1,15 @@ +# ماتریس تست فرانت‌اند (Component Test با Vitest و React Testing Library) + +| شناسه | سناریو | ورودی (fetch ساختگی) | نتیجهٔ مورد انتظار | Edge | تست | +|---|---|---|---|---|---| +| F-01 | سلامت موفق | 200 با `{status: UP}` | پیام «بک‌اند در دسترس است» و JSON سرویس | خیر | `با پاسخ ۲۰۰ بک‌اند، پیام موفقیت را نشان می‌دهد` | +| F-02 | خطای شبکه | `fetch` رد می‌شود | «خطا: Failed to fetch» | بله | `اگر بک‌اند خطا بدهد، پیام خطا را نشان می‌دهد` | +| F-03 | مسیر ناشناخته | آدرس `/abc` | صفحهٔ ۴۰۴ | بله | `آدرس ناشناخته صفحه‌ی ۴۰۴ را نشان می‌دهد` | +| F-04 | Problem Details | 503 با `application/problem+json` | عنوان، کد، توضیح و `correlation_id` نمایش داده می‌شود | بله | `خطای Problem Details را با کد و شناسهٔ ردیابی نشان می‌دهد` | +| F-05 | خطای HTTP بدون Problem Details | 500 با متن ساده | پیام کلی «HTTP 500» بدون جزئیات ساختگی | بله | `خطای HTTP عادی را بدون جزئیات Problem نشان می‌دهد` | +| F-06 | تلاش دوباره | کلیک روی «بررسی دوباره» | `fetch` دوباره صدا زده می‌شود | خیر | `کلیک روی بررسی دوباره درخواست تازه می‌فرستد` | + +## پوشش‌نیافته‌ها + +- فرم و فهرست قوانین (US-02C): هنوز پیاده‌سازی نشده‌اند؛ تست‌های کامپوننتشان همراه همان استوری در اسپرینت ۴ می‌آید. +- تست E2E با Playwright: در جلسهٔ ۵ لازم نیست؛ فقط ابزار نصب شده است. diff --git a/docs/test-matrices/ledger-consumer.md b/docs/test-matrices/ledger-consumer.md new file mode 100644 index 0000000..9acbfc9 --- /dev/null +++ b/docs/test-matrices/ledger-consumer.md @@ -0,0 +1,23 @@ +# ماتریس تست مصرف‌کننده: کلاینت دفترکل S2-LDG + +وضعیت: کلاینت `s4_rsk/integrations/ledger_client.py` آزمون شده است ولی هنوز در `assessments.services` فراخوانی نمی‌شود (US-01B). پاسخ‌های Stub از مثال‌های `openapi/neighbors/s2_ldg.yaml` گرفته شده‌اند. اگر فایل واقعی S2 جایگزین شد، تست‌ها دوباره اجرا شوند. + +| شناسه | سناریو | پاسخ Stub / ورودی | نتیجهٔ مورد انتظار | Edge | تست خودکار | +|---|---|---|---|---|---| +| L-01 | پاسخ موفق | 200 با دو بدهکاری | دو ورودی تجزیه‌شده، وضعیت OK، بدون تصمیم اجباری؛ درخواست شامل `direction=DEBIT`، `from` و `X-Correlation-ID` | خیر | `test_success_returns_parsed_debits_and_sends_the_draft_request` | +| L-02 | صفحه‌بندی | صفحهٔ اول با `next_cursor` | درخواست دوم با همان cursor و ادغام نتایج | بله | `test_pagination_follows_next_cursor_until_exhausted` | +| L-03 | حساب ناموجود | 404 Problem Details | `ACCOUNT_NOT_FOUND` و تصمیم اجباری REVIEW | بله | `test_unknown_account_forces_review_with_explicit_reason` | +| L-04 | Timeout | استثنای `ConnectTimeout` | `LEDGER_UNAVAILABLE` و REVIEW بدون پرتاب خطا | بله | `test_timeout_forces_review_instead_of_raising` | +| L-05 | خطای سرور | 503 Problem Details | `LEDGER_UNAVAILABLE` و REVIEW | بله | `test_server_error_forces_review` | +| L-06 | بدنهٔ ناقص | 200 بدون فیلد `amount` | خطا، نه اعتماد به داده؛ REVIEW | بله | `test_malformed_success_body_is_not_trusted` | +| L-07 | آدرس همسایه | `NEIGHBOR_BASE_URL` | درخواست به همان میزبان و پورت می‌رود | خیر | `test_neighbor_base_url_environment_variable_selects_the_host` | +| L-08 | آدرس تنظیم‌نشده | بدون متغیر محیطی | خطای روشن، نه آدرس حدسی | بله | `test_missing_neighbor_base_url_is_a_clear_error` | +| L-09 | خطای غیرمنتظرهٔ ۴xx | 403 | خطا، نه تاریخچهٔ خالی؛ تصمیم اجباری REVIEW | بله | `test_unexpected_client_error_is_not_treated_as_empty_history` | +| L-10 | زنجیرهٔ بی‌پایان cursor | هر صفحه `next_cursor` دارد | قطع پس از سقف صفحه‌ها با خطا | بله | `test_endless_cursor_chain_is_cut_off` | +| L-11 | توکن سرویس | کلاینت با `token` | هدر `Authorization: Bearer` ارسال می‌شود | خیر | `test_bearer_token_is_sent_when_configured` | +| L-12 | Contract Test روی Prism یا همسایهٔ واقعی | `NEIGHBOR_BASE_URL` | موفق و خطا با قرارداد همسایه می‌خوانند | خیر | `test_ledger_contract.py` (نشانگر `contract`) | + +## پوشش‌نیافته‌ها + +- احراز هویت سرویس‌به‌سرویس به S2: روش آن هنوز با تیم S2 توافق نشده؛ فقط ارسال هدر آزموده شده (L-11)، نه پذیرفته‌شدن توسط S2. +- retry با backoff: عمداً پیاده‌سازی نشده است؛ هر خطا یک سیگنال REVIEW است (طبق نمودار توالی جلسهٔ ۴). diff --git a/frontend/package.json b/frontend/package.json index 133d7bb..a0ad6fc 100644 --- a/frontend/package.json +++ b/frontend/package.json @@ -19,9 +19,9 @@ }, "devDependencies": { "@playwright/test": "^1.64.1", + "@testing-library/dom": "^10.4.2", "@testing-library/jest-dom": "^7.0.1", "@testing-library/react": "^16.3.3", - "@testing-library/dom": "^10.4.2", "@types/node": "^24.19.2", "@types/react": "^19.3.0", "@types/react-dom": "^19.3.0", diff --git a/frontend/src/App.extra.test.tsx b/frontend/src/App.extra.test.tsx new file mode 100644 index 0000000..a6fd5cc --- /dev/null +++ b/frontend/src/App.extra.test.tsx @@ -0,0 +1,110 @@ +import { cleanup, fireEvent, render, screen } from '@testing-library/react' +import { afterEach, describe, expect, it, vi } from 'vitest' +import App from './App' + +afterEach(() => { + cleanup() + vi.unstubAllGlobals() + window.history.replaceState(null, '', '/') +}) + +describe('صفحه‌ی /health', () => { + it('با پاسخ ۲۰۰ بک‌اند، پیام موفقیت را نشان می‌دهد', async () => { + window.history.replaceState(null, '', '/health') + vi.stubGlobal( + 'fetch', + vi.fn().mockResolvedValue({ + ok: true, + status: 200, + json: async () => ({ status: 'UP', service: 's4-rsk' }), + }), + ) + + render() + + expect(await screen.findByText(/بک‌اند در دسترس است/)).toBeInTheDocument() + expect(screen.getByText(/"service": "s4-rsk"/)).toBeInTheDocument() + }) + + it('اگر بک‌اند خطا بدهد، پیام خطا را نشان می‌دهد', async () => { + window.history.replaceState(null, '', '/health') + vi.stubGlobal('fetch', vi.fn().mockRejectedValue(new Error('Failed to fetch'))) + + render() + + expect(await screen.findByText(/خطا: Failed to fetch/)).toBeInTheDocument() + }) + + it('آدرس ناشناخته صفحه‌ی ۴۰۴ را نشان می‌دهد', () => { + window.history.replaceState(null, '', '/abc') + + render() + + expect(screen.getByText('۴۰۴')).toBeInTheDocument() + }) + + it('خطای Problem Details را با کد و شناسهٔ ردیابی نشان می‌دهد', async () => { + window.history.replaceState(null, '', '/health') + vi.stubGlobal( + 'fetch', + vi.fn().mockResolvedValue({ + ok: false, + status: 503, + headers: new Headers({ 'content-type': 'application/problem+json' }), + json: async () => ({ + type: 'https://errors.labbank.example/service-unavailable', + title: 'Dependency unavailable', + status: 503, + code: 'SERVICE_UNAVAILABLE', + detail: 'The database is unavailable.', + correlation_id: 'cid-503', + }), + }), + ) + + render() + + expect(await screen.findByRole('alert')).toHaveTextContent('Dependency unavailable') + const details = screen.getByRole('alert') + expect(details).toHaveTextContent('SERVICE_UNAVAILABLE') + expect(details).toHaveTextContent('The database is unavailable.') + expect(details).toHaveTextContent('cid-503') + }) + + it('خطای HTTP عادی را بدون جزئیات Problem نشان می‌دهد', async () => { + window.history.replaceState(null, '', '/health') + vi.stubGlobal( + 'fetch', + vi.fn().mockResolvedValue({ + ok: false, + status: 500, + headers: new Headers({ 'content-type': 'text/html' }), + json: async () => { + throw new Error('not json') + }, + }), + ) + + render() + + expect(await screen.findByText(/خطا: HTTP 500/)).toBeInTheDocument() + expect(screen.queryByRole('alert')).not.toBeInTheDocument() + }) + + it('کلیک روی بررسی دوباره درخواست تازه می‌فرستد', async () => { + window.history.replaceState(null, '', '/health') + const fetchMock = vi.fn().mockResolvedValue({ + ok: true, + status: 200, + json: async () => ({ status: 'UP', service: 's4-rsk' }), + }) + vi.stubGlobal('fetch', fetchMock) + + render() + await screen.findByText(/بک‌اند در دسترس است/) + fireEvent.click(screen.getByRole('button', { name: 'بررسی دوباره' })) + + await screen.findByText(/بک‌اند در دسترس است/) + expect(fetchMock).toHaveBeenCalledTimes(2) + }) +}) diff --git a/frontend/src/api/schema.d.ts b/frontend/src/api/schema.d.ts index 20fd0bb..d38d82d 100644 --- a/frontend/src/api/schema.d.ts +++ b/frontend/src/api/schema.d.ts @@ -760,6 +760,15 @@ export interface components { "application/problem+json": components["schemas"]["Problem"]; }; }; + /** @description The access token is missing, invalid or expired. */ + Unauthorized: { + headers: { + [name: string]: unknown; + }; + content: { + "application/problem+json": components["schemas"]["Problem"]; + }; + }; /** @description The authenticated caller lacks the required role (`FORBIDDEN`). */ Forbidden: { headers: { @@ -1074,6 +1083,7 @@ export interface operations { "application/json": components["schemas"]["RiskRulePage"]; }; }; + 401: components["responses"]["Unauthorized"]; 403: components["responses"]["Forbidden"]; 404: components["responses"]["NotFound"]; }; @@ -1104,6 +1114,7 @@ export interface operations { }; }; 400: components["responses"]["BadRequest"]; + 401: components["responses"]["Unauthorized"]; 403: components["responses"]["Forbidden"]; 409: components["responses"]["Conflict"]; }; @@ -1133,6 +1144,7 @@ export interface operations { }; }; 400: components["responses"]["BadRequest"]; + 401: components["responses"]["Unauthorized"]; 403: components["responses"]["Forbidden"]; 404: components["responses"]["NotFound"]; 409: components["responses"]["Conflict"]; @@ -1163,6 +1175,7 @@ export interface operations { "application/json": components["schemas"]["RuleRevisionPage"]; }; }; + 401: components["responses"]["Unauthorized"]; 403: components["responses"]["Forbidden"]; 404: components["responses"]["NotFound"]; }; diff --git a/openapi/neighbors/s2_ldg.yaml b/openapi/neighbors/s2_ldg.yaml new file mode 100644 index 0000000..f8067c5 --- /dev/null +++ b/openapi/neighbors/s2_ldg.yaml @@ -0,0 +1,117 @@ +# DRAFT of the S2-LDG endpoint that S4-RSK consumes. +# +# The field names below were derived from our own contract (openapi/s4_rsk.yaml, +# "source_account_id") and the session-4 sequence diagram. They are an ASSUMPTION. +# Replace this file with the real contract copied from the S2-LDG team's repository +# (same path), then re-run the stub and contract tests; fix LedgerEntry and the +# test data only where the real names differ. +openapi: 3.1.0 +info: + title: S2-LDG ledger (consumer-side copy, draft) + version: 0.1.0-draft +servers: + - url: http://localhost:8082 +paths: + /api/v1/accounts/{account_id}/entries: + get: + operationId: listAccountEntries + summary: Ledger entries of one account, newest first + parameters: + - name: account_id + in: path + required: true + schema: { type: string, format: uuid } + - name: direction + in: query + required: false + schema: { type: string, enum: [DEBIT, CREDIT] } + - name: from + in: query + required: false + schema: { type: string, format: date-time } + - name: limit + in: query + required: false + schema: { type: integer, minimum: 1, maximum: 200 } + - name: cursor + in: query + required: false + schema: { type: string } + responses: + '200': + description: A page of entries. + content: + application/json: + schema: + $ref: '#/components/schemas/EntryPage' + example: + items: + - id: 0192f5a0-1111-7000-8000-000000000001 + account_id: 0192f5a0-5555-7aaa-8bbb-0123456789ab + direction: DEBIT + amount: 1500000 + currency: IRR + occurred_at: '2026-10-24T08:00:00Z' + - id: 0192f5a0-1111-7000-8000-000000000002 + account_id: 0192f5a0-5555-7aaa-8bbb-0123456789ab + direction: DEBIT + amount: 700000 + currency: IRR + occurred_at: '2026-10-24T08:10:00Z' + next_cursor: null + '404': + description: The account does not exist (`NOT_FOUND`). + content: + application/problem+json: + schema: + $ref: '#/components/schemas/Problem' + example: + type: https://errors.labbank.example/not-found + title: Resource not found + status: 404 + code: NOT_FOUND + detail: Account was not found. + correlation_id: 7f3c1e52-5a0b-4a4f-9c1e-0d2b6a9f1c33 + '503': + description: The ledger is temporarily unavailable. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/Problem' + example: + type: https://errors.labbank.example/service-unavailable + title: Dependency unavailable + status: 503 + code: SERVICE_UNAVAILABLE + detail: The ledger database is unavailable. + correlation_id: 7f3c1e52-5a0b-4a4f-9c1e-0d2b6a9f1c33 +components: + schemas: + Entry: + type: object + required: [id, account_id, direction, amount, occurred_at] + properties: + id: { type: string, format: uuid } + account_id: { type: string, format: uuid } + direction: { type: string, enum: [DEBIT, CREDIT] } + amount: { type: integer, minimum: 1 } + currency: { type: string, enum: [IRR] } + occurred_at: { type: string, format: date-time } + EntryPage: + type: object + required: [items, next_cursor] + properties: + items: + type: array + items: { $ref: '#/components/schemas/Entry' } + next_cursor: { type: [string, 'null'] } + Problem: + type: object + required: [type, title, status, code, detail, correlation_id] + properties: + type: { type: string } + title: { type: string } + status: { type: integer } + code: { type: string } + detail: { type: string } + correlation_id: { type: string } diff --git a/openapi/s4_rsk.yaml b/openapi/s4_rsk.yaml index 68ad022..ddb7ff7 100644 --- a/openapi/s4_rsk.yaml +++ b/openapi/s4_rsk.yaml @@ -289,6 +289,8 @@ paths: created_at: '2026-10-01T00:00:00Z' updated_at: '2026-10-01T00:00:00Z' next_cursor: null + '401': + $ref: '#/components/responses/Unauthorized' '403': $ref: '#/components/responses/Forbidden' '404': @@ -317,6 +319,8 @@ paths: $ref: '#/components/schemas/RiskRule' '400': $ref: '#/components/responses/BadRequest' + '401': + $ref: '#/components/responses/Unauthorized' '403': $ref: '#/components/responses/Forbidden' '409': @@ -351,6 +355,8 @@ paths: $ref: '#/components/schemas/RiskRule' '400': $ref: '#/components/responses/BadRequest' + '401': + $ref: '#/components/responses/Unauthorized' '403': $ref: '#/components/responses/Forbidden' '404': @@ -378,6 +384,8 @@ paths: application/json: schema: $ref: '#/components/schemas/RuleRevisionPage' + '401': + $ref: '#/components/responses/Unauthorized' '403': $ref: '#/components/responses/Forbidden' '404': @@ -751,6 +759,12 @@ components: code: VALIDATION_ERROR detail: start must not be later than end. correlation_id: 7f3c1e52-5a0b-4a4f-9c1e-0d2b6a9f1c33 + Unauthorized: + description: The access token is missing, invalid or expired. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/Problem' Forbidden: description: The authenticated caller lacks the required role (`FORBIDDEN`). content: @@ -965,6 +979,7 @@ components: type: [string, 'null'] RiskRuleInput: type: object + additionalProperties: false description: For AMOUNT_LIMIT, parameters.max_amount is a positive integer amount in IRR (maximum 9223372036854775807). required: [name, type, parameters] properties: @@ -986,6 +1001,7 @@ components: format: date-time RiskRulePatch: type: object + additionalProperties: false description: For AMOUNT_LIMIT, parameters.max_amount is a positive integer amount in IRR (maximum 9223372036854775807). required: [expected_revision] properties: diff --git a/s4_rsk/common/openapi_contract.py b/s4_rsk/common/openapi_contract.py new file mode 100644 index 0000000..5286a92 --- /dev/null +++ b/s4_rsk/common/openapi_contract.py @@ -0,0 +1,124 @@ +"""Check real HTTP responses against an OpenAPI 3.1 contract file. + +The service is contract-first (ADR-002): ``openapi/s4_rsk.yaml`` is the agreement, +and the code must conform to it. ``assert_response_matches`` verifies that + +1. the status code is documented for the operation (exact code or ``4XX``/``5XX``), +2. the ``Content-Type`` is one the contract lists for that status, +3. the JSON body satisfies the documented schema, and +4. every response header the contract declares is present. + +It works with Django/DRF test responses and with ``httpx`` responses, so the same +helper validates our own API (provider tests) and a neighbour's API (consumer +contract tests). +""" + +from __future__ import annotations + +from functools import lru_cache +from pathlib import Path + +import yaml +from jsonschema import Draft202012Validator, FormatChecker + +REPO_ROOT = Path(__file__).resolve().parents[2] +PROVIDER_SPEC = REPO_ROOT / "openapi" / "s4_rsk.yaml" +NEIGHBOR_SPEC = REPO_ROOT / "openapi" / "neighbors" / "s2_ldg.yaml" + + +class ContractViolation(AssertionError): + """The observed response is not allowed by the contract.""" + + +@lru_cache(maxsize=None) +def load_spec(path: str | Path) -> dict: + return yaml.safe_load(Path(path).read_text(encoding="utf-8")) + + +def _resolve(spec: dict, node: dict) -> dict: + """Follow a local ``$ref`` such as ``#/components/responses/Forbidden``.""" + seen = 0 + while isinstance(node, dict) and "$ref" in node: + pointer = node["$ref"] + if not pointer.startswith("#/"): + raise ContractViolation(f"Only local $ref values are supported: {pointer}") + target = spec + for part in pointer[2:].split("/"): + target = target[part.replace("~1", "/").replace("~0", "~")] + node = target + seen += 1 + if seen > 20: + raise ContractViolation(f"$ref loop at {pointer}") + return node + + +def operation(spec: dict, path_template: str, method: str) -> dict: + try: + return spec["paths"][path_template][method.lower()] + except KeyError as exc: + raise ContractViolation(f"{method.upper()} {path_template} is not in the contract") from exc + + +def documented_statuses(spec: dict, path_template: str, method: str) -> list[str]: + return sorted(operation(spec, path_template, method)["responses"]) + + +def contract_example(spec: dict, path_template: str, method: str, status: str = "200") -> dict | list | None: + """Return the ``example`` the contract gives for a response (used to build stubs).""" + response = _resolve(spec, operation(spec, path_template, method)["responses"][status]) + media = next(iter(response.get("content", {}).values()), {}) + return media.get("example") + + +def _schema_validator(spec: dict, schema: dict) -> Draft202012Validator: + # The whole document is embedded so that "#/components/..." references resolve. + root = {"components": spec.get("components", {}), **schema} + return Draft202012Validator(root, format_checker=FormatChecker()) + + +def _header(response, name: str): + headers = getattr(response, "headers", None) + return headers.get(name) if headers is not None else None + + +def assert_response_matches(response, *, path_template: str, method: str, spec_path=PROVIDER_SPEC) -> None: + spec = load_spec(spec_path) + responses = operation(spec, path_template, method)["responses"] + status = str(response.status_code) + key = status if status in responses else f"{status[0]}XX" if f"{status[0]}XX" in responses else None + if key is None: + raise ContractViolation( + f"{method.upper()} {path_template} returned {status}, but the contract documents only {sorted(responses)}" + ) + declared = _resolve(spec, responses[key]) + + content = declared.get("content") or {} + if content: + content_type = (_header(response, "Content-Type") or "").split(";")[0].strip().lower() + media = content.get(content_type) + if media is None: + raise ContractViolation( + f"{method.upper()} {path_template} {status}: Content-Type {content_type!r} " + f"is not among {sorted(content)}" + ) + if "schema" in media: + errors = sorted( + _schema_validator(spec, media["schema"]).iter_errors(response.json()), + key=lambda error: tuple(str(part) for part in error.path), + ) + if errors: + lines = "; ".join(f"{'/'.join(map(str, e.path)) or ''}: {e.message}" for e in errors[:5]) + raise ContractViolation(f"{method.upper()} {path_template} {status} body violates the schema: {lines}") + + for header_name in declared.get("headers", {}): + if _header(response, header_name) is None: + raise ContractViolation(f"{method.upper()} {path_template} {status}: header {header_name} is missing") + + +def assert_payload_matches(schema_name: str, payload, *, spec_path=PROVIDER_SPEC) -> None: + """Check a request payload against ``components.schemas.``.""" + spec = load_spec(spec_path) + validator = _schema_validator(spec, {"$ref": f"#/components/schemas/{schema_name}"}) + errors = sorted(validator.iter_errors(payload), key=lambda error: list(error.path)) + if errors: + raise ContractViolation(f"Payload violates {schema_name}: {errors[0].message}") diff --git a/s4_rsk/common/test_health_contract.py b/s4_rsk/common/test_health_contract.py new file mode 100644 index 0000000..26c39fd --- /dev/null +++ b/s4_rsk/common/test_health_contract.py @@ -0,0 +1,33 @@ +"""Provider API tests for the probes against openapi/s4_rsk.yaml (no authentication needed).""" + +from unittest.mock import patch + +import pytest +from django.db import OperationalError +from rest_framework.test import APIClient + +from .openapi_contract import assert_response_matches + +pytestmark = pytest.mark.openapi + + +def test_health_matches_contract(): + response = APIClient().get("/health") + assert_response_matches(response, path_template="/health", method="get") + assert response.status_code == 200 + + +@pytest.mark.django_db +def test_ready_matches_contract_on_real_postgresql(): + response = APIClient().get("/ready") + assert_response_matches(response, path_template="/ready", method="get") + assert response.status_code == 200 + + +def test_ready_failure_is_documented_problem_details(): + with patch("common.views.connections") as connections: + connections.__getitem__.return_value.cursor.side_effect = OperationalError("down") + response = APIClient().get("/ready") + assert_response_matches(response, path_template="/ready", method="get") + assert response.status_code == 503 + assert response["Content-Type"] == "application/problem+json" diff --git a/s4_rsk/conftest.py b/s4_rsk/conftest.py new file mode 100644 index 0000000..3459e0f --- /dev/null +++ b/s4_rsk/conftest.py @@ -0,0 +1,17 @@ +import pytest + + +def pytest_addoption(parser): + parser.addoption( + "--run-neighbor-contract", action="store_true", default=False, + help="Run contract tests against the explicitly configured neighbour or stub.", + ) + + +def pytest_collection_modifyitems(config, items): + if config.getoption("--run-neighbor-contract"): + return + skip = pytest.mark.skip(reason="Pass --run-neighbor-contract to contact a running neighbour or stub") + for item in items: + if item.get_closest_marker("contract"): + item.add_marker(skip) diff --git a/s4_rsk/integrations/__init__.py b/s4_rsk/integrations/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/s4_rsk/integrations/ledger_client.py b/s4_rsk/integrations/ledger_client.py new file mode 100644 index 0000000..919e317 --- /dev/null +++ b/s4_rsk/integrations/ledger_client.py @@ -0,0 +1,168 @@ +"""Consumer client for the S2-LDG ledger service (our neighbour / provider). + +While assessing a transfer, S4-RSK reads the recent DEBIT entries of the source +account to spot unusual withdrawal patterns. Failures of the neighbour must never +break our own endpoint: they are translated into a safe REVIEW signal. + +The neighbour's address is read from ``NEIGHBOR_BASE_URL`` (see ``resolve_base_url``); +``S2_LDG_BASE_URL`` from .env is the fallback. + +Status of the integration: this module is the tested client. It is not yet called by +``assessments.services`` (that wiring belongs to US-01B). +""" + +from __future__ import annotations + +import os +from dataclasses import dataclass +from datetime import datetime +from urllib.parse import quote +from uuid import UUID + +import httpx + +DEFAULT_TIMEOUT_SECONDS = 2.0 +MAX_PAGES = 10 +ENTRIES_PATH = "/api/v1/accounts/{account_id}/entries" + +STATUS_OK = "OK" +STATUS_ACCOUNT_NOT_FOUND = "ACCOUNT_NOT_FOUND" +STATUS_LEDGER_UNAVAILABLE = "LEDGER_UNAVAILABLE" + + +class LedgerError(Exception): + """The ledger answer cannot be used.""" + + +class LedgerAccountNotFound(LedgerError): + """S2-LDG answered 404 for the account.""" + + +class LedgerUnavailable(LedgerError): + """Timeout, connection failure or 5xx from S2-LDG.""" + + +@dataclass(frozen=True) +class LedgerEntry: + id: str + account_id: str + direction: str + amount: int + occurred_at: datetime + + +@dataclass(frozen=True) +class LedgerHistory: + """What the rule engine receives; ``forced_decision`` is set when history is unusable.""" + + status: str + entries: tuple[LedgerEntry, ...] = () + forced_decision: str | None = None + + @property + def reason_code(self) -> str | None: + return None if self.status == STATUS_OK else self.status + + +def resolve_base_url(explicit: str | None = None) -> str: + """NEIGHBOR_BASE_URL is the single place where the neighbour address is read.""" + url = explicit or os.environ.get("NEIGHBOR_BASE_URL") or os.environ.get("S2_LDG_BASE_URL") + if not url: + raise LedgerError("NEIGHBOR_BASE_URL is not configured.") + return url.rstrip("/") + + +def _parse_entry(raw: dict) -> LedgerEntry: + try: + if not isinstance(raw, dict): + raise ValueError("entry must be an object") + amount = raw["amount"] + if isinstance(amount, bool) or not isinstance(amount, int) or amount < 1: + raise ValueError("amount must be a positive integer") + if raw["direction"] != "DEBIT": + raise ValueError("entry must be a debit") + UUID(str(raw["id"])) + UUID(str(raw["account_id"])) + occurred_at = datetime.fromisoformat(raw["occurred_at"]) + if occurred_at.utcoffset() is None: + raise ValueError("occurred_at must include a timezone") + return LedgerEntry( + id=str(raw["id"]), + account_id=str(raw["account_id"]), + direction=str(raw["direction"]), + amount=amount, + occurred_at=occurred_at, + ) + except (KeyError, TypeError, ValueError) as exc: + raise LedgerError(f"Malformed ledger entry: {exc}") from exc + + +class LedgerClient: + def __init__( + self, + base_url: str | None = None, + *, + timeout: float = DEFAULT_TIMEOUT_SECONDS, + transport: httpx.BaseTransport | None = None, + token: str | None = None, + ): + self._base_url = resolve_base_url(base_url) + self._timeout = timeout + self._transport = transport + self._token = token + + def recent_debits(self, account_id, since: datetime, *, correlation_id: str | None = None) -> list[LedgerEntry]: + headers = {"Accept": "application/json"} + if correlation_id: + headers["X-Correlation-ID"] = correlation_id + if self._token: + headers["Authorization"] = f"Bearer {self._token}" + url = ENTRIES_PATH.format(account_id=quote(str(account_id), safe="")) + entries: list[LedgerEntry] = [] + cursor: str | None = None + + with httpx.Client(base_url=self._base_url, timeout=self._timeout, transport=self._transport) as http: + for _ in range(MAX_PAGES): + params = {"direction": "DEBIT", "from": since.isoformat(), "limit": 200} + if cursor: + params["cursor"] = cursor + try: + response = http.get(url, params=params, headers=headers) + except httpx.HTTPError as exc: # timeout, connection refused, protocol error + raise LedgerUnavailable(f"Ledger request failed: {type(exc).__name__}") from exc + + if response.status_code == 404: + raise LedgerAccountNotFound(str(account_id)) + if response.status_code >= 500: + raise LedgerUnavailable(f"Ledger answered {response.status_code}") + if response.status_code != 200: + raise LedgerError(f"Unexpected ledger status {response.status_code}") + try: + body = response.json() + items = body["items"] + cursor = body.get("next_cursor") + if not isinstance(items, list) or (cursor is not None and not isinstance(cursor, str)): + raise ValueError("invalid page") + except (ValueError, KeyError, TypeError) as exc: + raise LedgerError("Ledger answered 200 with an unreadable body") from exc + for item in items: + entry = _parse_entry(item) + if entry.account_id != str(account_id): + raise LedgerError("Ledger returned an entry for a different account") + entries.append(entry) + if not cursor: + return entries + raise LedgerError("Ledger returned too many pages") + + +def assess_ledger_history( + client: LedgerClient, account_id, since: datetime, *, correlation_id: str | None = None +) -> LedgerHistory: + """Never raises: turns every neighbour failure into an explicit REVIEW signal.""" + try: + entries = client.recent_debits(account_id, since, correlation_id=correlation_id) + except LedgerAccountNotFound: + return LedgerHistory(STATUS_ACCOUNT_NOT_FOUND, forced_decision="REVIEW") + except LedgerError: + return LedgerHistory(STATUS_LEDGER_UNAVAILABLE, forced_decision="REVIEW") + return LedgerHistory(STATUS_OK, tuple(entries)) diff --git a/s4_rsk/integrations/test_ledger_client_stub.py b/s4_rsk/integrations/test_ledger_client_stub.py new file mode 100644 index 0000000..19a4cf0 --- /dev/null +++ b/s4_rsk/integrations/test_ledger_client_stub.py @@ -0,0 +1,184 @@ +"""Consumer tests: S4-RSK's ledger client against a Stub of S2-LDG (no neighbour needed). + +The stub answers are taken from the examples of the neighbour's OpenAPI file +(openapi/neighbors/s2_ldg.yaml), so the tests stay tied to the draft contract. +The asserts check the behaviour of OUR code (decision signal), not only that the stub was called. +""" + +import uuid +from datetime import UTC, datetime + +import httpx +import pytest + +from common.openapi_contract import NEIGHBOR_SPEC, contract_example, load_spec + +from .ledger_client import ( + STATUS_ACCOUNT_NOT_FOUND, + STATUS_LEDGER_UNAVAILABLE, + STATUS_OK, + LedgerClient, + LedgerError, + assess_ledger_history, + resolve_base_url, +) + +PATH = "/api/v1/accounts/{account_id}/entries" +SPEC = load_spec(NEIGHBOR_SPEC) +OK_BODY = contract_example(SPEC, PATH, "get", "200") +NOT_FOUND_BODY = contract_example(SPEC, PATH, "get", "404") +UNAVAILABLE_BODY = contract_example(SPEC, PATH, "get", "503") + +ACCOUNT_ID = uuid.UUID("0192f5a0-5555-7aaa-8bbb-0123456789ab") +SINCE = datetime(2026, 10, 24, 0, 0, tzinfo=UTC) + + +def _client(handler, base_url="http://s2-ldg.test"): + return LedgerClient(base_url, transport=httpx.MockTransport(handler)) + + +def test_success_returns_parsed_debits_and_sends_the_draft_request(): + seen = {} + + def handler(request: httpx.Request) -> httpx.Response: + seen["path"] = request.url.path + seen["params"] = dict(request.url.params) + seen["correlation"] = request.headers.get("X-Correlation-ID") + return httpx.Response(200, json=OK_BODY) + + history = assess_ledger_history(_client(handler), ACCOUNT_ID, SINCE, correlation_id="stub-cid-1") + + assert seen["path"] == f"/api/v1/accounts/{ACCOUNT_ID}/entries" + assert seen["params"]["direction"] == "DEBIT" + assert seen["params"]["from"] == "2026-10-24T00:00:00+00:00" + assert seen["correlation"] == "stub-cid-1" + assert history.status == STATUS_OK + assert history.forced_decision is None + assert [entry.amount for entry in history.entries] == [1_500_000, 700_000] + assert all(entry.occurred_at.tzinfo is not None for entry in history.entries) + + +def test_pagination_follows_next_cursor_until_exhausted(): + calls = [] + + def handler(request: httpx.Request) -> httpx.Response: + calls.append(request.url.params.get("cursor")) + if request.url.params.get("cursor") is None: + return httpx.Response(200, json={"items": OK_BODY["items"][:1], "next_cursor": "page-2"}) + return httpx.Response(200, json={"items": OK_BODY["items"][1:], "next_cursor": None}) + + entries = _client(handler).recent_debits(ACCOUNT_ID, SINCE) + + assert calls == [None, "page-2"] + assert len(entries) == 2 + + +def test_unknown_account_forces_review_with_explicit_reason(): + def handler(request): + return httpx.Response(404, json=NOT_FOUND_BODY, headers={"Content-Type": "application/problem+json"}) + + history = assess_ledger_history(_client(handler), ACCOUNT_ID, SINCE) + + assert history.reason_code == STATUS_ACCOUNT_NOT_FOUND + assert history.forced_decision == "REVIEW" + assert history.entries == () + + +def test_timeout_forces_review_instead_of_raising(): + def handler(request): + raise httpx.ConnectTimeout("simulated timeout", request=request) + + history = assess_ledger_history(_client(handler), ACCOUNT_ID, SINCE) + + assert history.reason_code == STATUS_LEDGER_UNAVAILABLE + assert history.forced_decision == "REVIEW" + + +def test_server_error_forces_review(): + def handler(request): + return httpx.Response(503, json=UNAVAILABLE_BODY, headers={"Content-Type": "application/problem+json"}) + + history = assess_ledger_history(_client(handler), ACCOUNT_ID, SINCE) + + assert history.reason_code == STATUS_LEDGER_UNAVAILABLE + assert history.forced_decision == "REVIEW" + + +def test_malformed_success_body_is_not_trusted(): + bad_entry = {"id": "x", "account_id": "y", "direction": "DEBIT", "occurred_at": "2026-10-24T08:00:00Z"} + + def handler(request): + return httpx.Response(200, json={"items": [bad_entry], "next_cursor": None}) + + with pytest.raises(LedgerError): + _client(handler).recent_debits(ACCOUNT_ID, SINCE) + assert assess_ledger_history(_client(handler), ACCOUNT_ID, SINCE).forced_decision == "REVIEW" + + +@pytest.mark.parametrize("body", [{"items": None}, {"items": [] , "next_cursor": 1}, {"items": [None]}]) +def test_malformed_page_is_reported_as_unavailable(body): + def handler(request): + return httpx.Response(200, json=body) + + history = assess_ledger_history(_client(handler), ACCOUNT_ID, SINCE) + assert history.reason_code == STATUS_LEDGER_UNAVAILABLE + assert history.forced_decision == "REVIEW" + + +def test_entry_for_another_account_is_rejected(): + entry = {**OK_BODY["items"][0], "account_id": "0192f5a0-9999-7aaa-8bbb-000000000000"} + + def handler(request): + return httpx.Response(200, json={"items": [entry], "next_cursor": None}) + + assert assess_ledger_history(_client(handler), ACCOUNT_ID, SINCE).reason_code == STATUS_LEDGER_UNAVAILABLE + + +def test_neighbor_base_url_environment_variable_selects_the_host(monkeypatch): + monkeypatch.setenv("NEIGHBOR_BASE_URL", "http://neighbour.invalid:9999/") + hosts = [] + + def handler(request): + hosts.append((request.url.host, request.url.port)) + return httpx.Response(200, json=OK_BODY) + + LedgerClient(transport=httpx.MockTransport(handler)).recent_debits(ACCOUNT_ID, SINCE) + + assert hosts == [("neighbour.invalid", 9999)] + + +def test_missing_neighbor_base_url_is_a_clear_error(monkeypatch): + monkeypatch.delenv("NEIGHBOR_BASE_URL", raising=False) + monkeypatch.delenv("S2_LDG_BASE_URL", raising=False) + with pytest.raises(LedgerError, match="NEIGHBOR_BASE_URL"): + resolve_base_url() + + +def test_unexpected_client_error_is_not_treated_as_empty_history(): + def handler(request): + return httpx.Response(403, json={"code": "FORBIDDEN"}) + + with pytest.raises(LedgerError, match="403"): + _client(handler).recent_debits(ACCOUNT_ID, SINCE) + assert assess_ledger_history(_client(handler), ACCOUNT_ID, SINCE).forced_decision == "REVIEW" + + +def test_endless_cursor_chain_is_cut_off(): + def handler(request): + return httpx.Response(200, json={"items": [], "next_cursor": "again"}) + + with pytest.raises(LedgerError, match="too many pages"): + _client(handler).recent_debits(ACCOUNT_ID, SINCE) + + +def test_bearer_token_is_sent_when_configured(): + seen = {} + + def handler(request): + seen["authorization"] = request.headers.get("Authorization") + return httpx.Response(200, json=OK_BODY) + + client = LedgerClient("http://s2-ldg.test", transport=httpx.MockTransport(handler), token="stub-token") + client.recent_debits(ACCOUNT_ID, SINCE) + + assert seen["authorization"] == "Bearer stub-token" diff --git a/s4_rsk/integrations/test_ledger_contract.py b/s4_rsk/integrations/test_ledger_contract.py new file mode 100644 index 0000000..4ce14a1 --- /dev/null +++ b/s4_rsk/integrations/test_ledger_contract.py @@ -0,0 +1,66 @@ +"""Consumer contract tests: our expectations against a RUNNING provider. + +Target: NEIGHBOR_BASE_URL - either a Prism mock built from the neighbour's contract +(http://127.0.0.1:4010) or the neighbour's real service (bonus, section 12). + + prism mock openapi/neighbors/s2_ldg.yaml -p 4010 + $env:NEIGHBOR_BASE_URL="http://127.0.0.1:4010" + pytest -m contract --run-neighbor-contract -v -s + +Optional: NEIGHBOR_ACCOUNT_ID_OK / NEIGHBOR_ACCOUNT_ID_MISSING select the seeded account ids. +""" + +import os +from datetime import UTC, datetime + +import httpx +import pytest + +from common.openapi_contract import NEIGHBOR_SPEC, assert_response_matches + +from .ledger_client import STATUS_ACCOUNT_NOT_FOUND, STATUS_OK, LedgerClient, assess_ledger_history + +BASE_URL = os.environ.get("NEIGHBOR_BASE_URL", "").rstrip("/") +ACCOUNT_OK = os.environ.get("NEIGHBOR_ACCOUNT_ID_OK", "0192f5a0-5555-7aaa-8bbb-0123456789ab") +ACCOUNT_MISSING = os.environ.get("NEIGHBOR_ACCOUNT_ID_MISSING", "0192f5a0-9999-7aaa-8bbb-000000000000") +SINCE = datetime(2026, 10, 24, tzinfo=UTC) +PATH = "/api/v1/accounts/{account_id}/entries" + +pytestmark = [ + pytest.mark.contract, + pytest.mark.skipif(not BASE_URL, reason="NEIGHBOR_BASE_URL is not set"), +] + + +def stamp(message: str) -> None: + print(f"[{datetime.now(UTC).isoformat(timespec='milliseconds')}] {message}") + + +def _get(account_id: str, **extra_headers) -> httpx.Response: + url = f"{BASE_URL}/api/v1/accounts/{account_id}/entries" + stamp(f"GET {url}") + response = httpx.get(url, params={"direction": "DEBIT"}, headers=extra_headers, timeout=5.0) + stamp(f"-> {response.status_code} {response.headers.get('content-type')}") + return response + + +def test_success_response_matches_neighbor_contract(): + response = _get(ACCOUNT_OK) + assert response.status_code == 200 + assert_response_matches(response, path_template=PATH, method="get", spec_path=NEIGHBOR_SPEC) + + +def test_unknown_account_response_matches_neighbor_contract(): + # "Prefer: code=404" makes a Prism mock return its 404 example; a real provider ignores it. + response = _get(ACCOUNT_MISSING, Prefer="code=404") + assert response.status_code == 404 + assert response.headers["content-type"].startswith("application/problem+json") + assert_response_matches(response, path_template=PATH, method="get", spec_path=NEIGHBOR_SPEC) + + +def test_our_client_understands_the_real_success_response(): + stamp("LedgerClient.recent_debits against the running neighbour") + history = assess_ledger_history(LedgerClient(BASE_URL), ACCOUNT_OK, SINCE) + stamp(f"-> status={history.status} entries={len(history.entries)}") + assert history.status == STATUS_OK + assert history.status != STATUS_ACCOUNT_NOT_FOUND diff --git a/s4_rsk/pytest.ini b/s4_rsk/pytest.ini index 4167098..8e4a310 100644 --- a/s4_rsk/pytest.ini +++ b/s4_rsk/pytest.ini @@ -3,3 +3,6 @@ DJANGO_SETTINGS_MODULE = config.settings pythonpath = . python_files = tests.py test_*.py *_tests.py addopts = --reuse-db -v +markers = + openapi: provider response conforms to its OpenAPI contract + contract: optional tests against a running neighbour or Prism stub diff --git a/s4_rsk/rules/test_rule_contract.py b/s4_rsk/rules/test_rule_contract.py new file mode 100644 index 0000000..b150ad2 --- /dev/null +++ b/s4_rsk/rules/test_rule_contract.py @@ -0,0 +1,132 @@ +"""Provider API tests: every response of the rule endpoints must match openapi/s4_rsk.yaml. + +Run only these tests with: pytest -m openapi -v +""" + +import pytest +from django.contrib.auth.models import Group +from rest_framework.test import APIClient +from rest_framework_simplejwt.tokens import AccessToken + +from common.openapi_contract import assert_payload_matches, assert_response_matches + +from .models import RiskRule + +URL = "/api/v1/risk-rules" +pytestmark = [pytest.mark.django_db, pytest.mark.openapi] + + +def _client_for(user): + client = APIClient() + client.credentials(HTTP_AUTHORIZATION=f"Bearer {AccessToken.for_user(user)}") + return client + + +@pytest.fixture +def manager(django_user_model): + user = django_user_model.objects.create_user("contract-manager") + user.groups.add(Group.objects.get_or_create(name="manager")[0]) + return user + + +@pytest.fixture +def client(manager): + return _client_for(manager) + + +@pytest.fixture +def payload(): + return {"name": "contract limit", "type": "AMOUNT_LIMIT", "parameters": {"max_amount": 5_000_000}} + + +def _create(client, payload): + response = client.post(URL, payload, format="json") + assert response.status_code == 201 + return response.json() + + +def test_list_matches_contract(client, payload): + _create(client, payload) + response = client.get(URL) + assert_response_matches(response, path_template="/risk-rules", method="get") + assert response.status_code == 200 + + +def test_create_matches_contract(client, payload): + assert_payload_matches("RiskRuleInput", payload) + response = client.post(URL, payload, format="json") + assert_response_matches(response, path_template="/risk-rules", method="post") + assert response.status_code == 201 + assert response.json()["revision"] == 1 + + +def test_invalid_amount_is_documented_problem_details(client, payload): + payload["parameters"] = {"max_amount": 0} + response = client.post(URL, payload, format="json") + assert_response_matches(response, path_template="/risk-rules", method="post") + assert response.status_code == 400 + assert response["Content-Type"] == "application/problem+json" + assert response.json()["code"] == "VALIDATION_ERROR" + + +def test_stale_revision_is_documented_conflict(client, payload): + rule = _create(client, payload) + response = client.patch(f"{URL}/{rule['id']}", {"expected_revision": 99, "name": "x"}, format="json") + assert_response_matches(response, path_template="/risk-rules/{rule_id}", method="patch") + assert response.status_code == 409 + assert response.json()["code"] == "CONFLICT" + + +def test_patch_success_matches_contract(client, payload): + rule = _create(client, payload) + body = {"expected_revision": 1, "parameters": {"max_amount": 9_000_000}} + assert_payload_matches("RiskRulePatch", body) + response = client.patch(f"{URL}/{rule['id']}", body, format="json") + assert_response_matches(response, path_template="/risk-rules/{rule_id}", method="patch") + assert response.json()["revision"] == 2 + + +def test_audit_matches_contract(client, payload): + rule = _create(client, payload) + response = client.get(f"{URL}/{rule['id']}/audit") + assert_response_matches(response, path_template="/risk-rules/{rule_id}/audit", method="get") + assert response.status_code == 200 + + +def test_unknown_rule_is_documented_not_found(client): + response = client.patch( + f"{URL}/019a0100-0000-7000-8000-00000000ffff", {"expected_revision": 1, "name": "x"}, format="json" + ) + assert_response_matches(response, path_template="/risk-rules/{rule_id}", method="patch") + assert response.status_code == 404 + + +def test_missing_token_is_a_documented_401(): + response = APIClient().get(URL) + assert response.status_code == 401 + assert_response_matches(response, path_template="/risk-rules", method="get") + + +def test_non_manager_is_a_documented_403(django_user_model): + user = django_user_model.objects.create_user("contract-no-role") + response = _client_for(user).get(URL) + assert response.status_code == 403 + assert_response_matches(response, path_template="/risk-rules", method="get") + + +def test_idempotency_key_reuse_uses_the_code_named_in_the_contract(client, payload): + key = "019a0100-0000-7000-8000-0000000000aa" + assert client.post(URL, payload, format="json", HTTP_IDEMPOTENCY_KEY=key).status_code == 201 + response = client.post(URL, {**payload, "name": "other"}, format="json", HTTP_IDEMPOTENCY_KEY=key) + assert_response_matches(response, path_template="/risk-rules", method="post") + assert response.status_code == 409 + assert response.json()["code"] == "IDEMPOTENCY_KEY_REUSED" + assert RiskRule.objects.count() == 1 + + +def test_invalid_idempotency_key_is_a_validation_problem(client, payload): + response = client.post(URL, payload, format="json", HTTP_IDEMPOTENCY_KEY="not-a-uuid") + assert_response_matches(response, path_template="/risk-rules", method="post") + assert response.status_code == 400 + assert response.json()["code"] == "VALIDATION_ERROR" + assert RiskRule.objects.count() == 0