Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
31 changes: 31 additions & 0 deletions docs/reports/lab5-additions.md
Original file line number Diff line number Diff line change
@@ -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) مراجعه کنید.
2 changes: 2 additions & 0 deletions docs/test-matrices/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -12,3 +12,5 @@

- [US-02 مدیریت قوانین](us-02.md)
- [US-08 توضیح‌پذیری تصمیم، پیش‌نویس](us-08-draft.md)
- [تست‌های فرانت‌اند](frontend.md)
- [پیش‌نویس تست مصرف‌کننده دفترکل](ledger-consumer.md)
15 changes: 15 additions & 0 deletions docs/test-matrices/frontend.md
Original file line number Diff line number Diff line change
@@ -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: در جلسهٔ ۵ لازم نیست؛ فقط ابزار نصب شده است.
23 changes: 23 additions & 0 deletions docs/test-matrices/ledger-consumer.md
Original file line number Diff line number Diff line change
@@ -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 است (طبق نمودار توالی جلسهٔ ۴).
2 changes: 1 addition & 1 deletion frontend/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -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",
Expand Down
110 changes: 110 additions & 0 deletions frontend/src/App.extra.test.tsx
Original file line number Diff line number Diff line change
@@ -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(<App />)

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(<App />)

expect(await screen.findByText(/خطا: Failed to fetch/)).toBeInTheDocument()
})

it('آدرس ناشناخته صفحه‌ی ۴۰۴ را نشان می‌دهد', () => {
window.history.replaceState(null, '', '/abc')

render(<App />)

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(<App />)

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(<App />)

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(<App />)
await screen.findByText(/بک‌اند در دسترس است/)
fireEvent.click(screen.getByRole('button', { name: 'بررسی دوباره' }))

await screen.findByText(/بک‌اند در دسترس است/)
expect(fetchMock).toHaveBeenCalledTimes(2)
})
})
13 changes: 13 additions & 0 deletions frontend/src/api/schema.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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: {
Expand Down Expand Up @@ -1074,6 +1083,7 @@ export interface operations {
"application/json": components["schemas"]["RiskRulePage"];
};
};
401: components["responses"]["Unauthorized"];
403: components["responses"]["Forbidden"];
404: components["responses"]["NotFound"];
};
Expand Down Expand Up @@ -1104,6 +1114,7 @@ export interface operations {
};
};
400: components["responses"]["BadRequest"];
401: components["responses"]["Unauthorized"];
403: components["responses"]["Forbidden"];
409: components["responses"]["Conflict"];
};
Expand Down Expand Up @@ -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"];
Expand Down Expand Up @@ -1163,6 +1175,7 @@ export interface operations {
"application/json": components["schemas"]["RuleRevisionPage"];
};
};
401: components["responses"]["Unauthorized"];
403: components["responses"]["Forbidden"];
404: components["responses"]["NotFound"];
};
Expand Down
117 changes: 117 additions & 0 deletions openapi/neighbors/s2_ldg.yaml
Original file line number Diff line number Diff line change
@@ -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 }
Loading
Loading