This document outlines the testing strategy and coverage for the Symfony Fund Transfer Application. The testing suite strictly adheres to the "Testing Pyramid" (Unit > Integration > Functional) and includes manual verification scenarios for API security.
Last Updated: December 23, 2025
- Classes: 55.17% (32/58)
- Methods: 62.11% (100/161)
- Lines: 53.82% (712/1323)
Note: Coverage has significantly improved with the addition of comprehensive unit tests for Domain, Application, and Infrastructure layers. All critical business logic components now have dedicated test coverage.
Fully Covered Classes (100%):
App\Application\DTO\TransferRequestApp\Application\MessageHandler\TransferReceiptHandlerApp\Application\MessageHandler\BatchTransferHandlerApp\Application\MessageHandler\WebhookDeliveryHandlerApp\Application\Message\BatchTransferMessageApp\Application\UseCase\ProcessBatchTransferUseCaseApp\Domain\Event\FundsTransferredEventApp\Domain\Exception\AccountNotFoundExceptionApp\Domain\Exception\InsufficientFundsExceptionApp\Domain\Exception\TransactionLimitExceededExceptionApp\Domain\Model\AccountApp\Domain\Model\AuditLogApp\Domain\Model\BatchTransferApp\Domain\Model\WebhookEventApp\Domain\Model\WebhookSubscriptionApp\Domain\Service\FundTransferServiceApp\Domain\ValueObject\AccountIdApp\Domain\ValueObject\AuditCategoryApp\Domain\ValueObject\BatchIdApp\Domain\ValueObject\BatchStatusApp\Domain\ValueObject\ComplianceLevelApp\Domain\ValueObject\CurrencyApp\Domain\ValueObject\MoneyApp\Domain\ValueObject\RegulatoryRequirementApp\Domain\ValueObject\RiskLevelApp\Domain\ValueObject\TransactionStatusApp\Domain\ValueObject\WebhookIdApp\Domain\ValueObject\WebhookSecretApp\Infrastructure\Service\AuditLogServiceApp\Infrastructure\Service\RiskBasedRateLimiterApp\Infrastructure\Service\RedisTransactionLimitServiceApp\Infrastructure\Service\WebhookDeliveryServiceApp\Infrastructure\EventSubscriber\SecurityHeadersSubscriberApp\Infrastructure\EventSubscriber\RateLimitHeadersSubscriberApp\Infrastructure\EventSubscriber\RequestLoggingSubscriberApp\Infrastructure\Security\ThrottlingAwareAuthenticationFailureHandler
Partially Covered Classes:
App\Application\UseCase\TransferFundsUseCase(50% methods, 96.30% lines)App\Domain\Model\Transaction(66.67% methods, 83.33% lines)App\Domain\ValueObject\WebhookId(80% methods, 90% lines)App\Domain\ValueObject\WebhookSecret(66.67% methods, 75% lines)
Coverage Improvements:
- Comprehensive Unit Test Coverage: All Domain value objects, models, exceptions, and Application handlers now have dedicated unit tests
- Infrastructure Layer Testing: Event subscribers, services, and security components are now fully tested
- Test Quality: All tests use static assertions and follow PHPStan compliance standards
Location: tests/Unit/
Goal: Verify pure PHP domain logic in isolation without any infrastructure (DB, API, Framework) dependencies.
-
Account (
AccountTest.php)testAccountCanBeCreatedWithInitialBalance: Verifies initialization.testCreditIncreasesBalance: Ensures money is added correctly.testDebitDecreasesBalance: Ensures money is subtracted correctly.testDebitThrowsExceptionOnInsufficientFunds: Enforces business rule: balance cannot go negative.testDebitThrowsExceptionOnCurrencyMismatch: Enforces currency consistency.testCreditThrowsExceptionOnCurrencyMismatch: Enforces currency consistency.
-
Transaction (
TransactionTest.php)testTransactionCanBeCreated: Verifies structure.testTransactionCanBeCompleted: Verifies status transitions.
-
AuditLog (
AuditLogTest.php)testAuditLogCanBeCreated: Verifies immutable recording structure.
-
BatchTransfer (
BatchTransferTest.php)testConstructorInitializesBatchTransfer: Verifies batch transfer initialization with transactionstestTotalCountIsSetFromTransactionsCount: Ensures total count matches transaction array lengthtestStatusCanBeChanged: Tests batch status transitions (PENDING -> PROCESSING -> COMPLETED)testSuccessAndFailureCountsCanBeUpdated: Verifies success/failure counter updatestestErrorsCanBeSet: Tests error tracking for failed transactionstestProcessedAtCanBeSet: Verifies processed timestamp assignment
-
WebhookEvent (
WebhookEventTest.php)testConstructorInitializesWebhookEvent: Verifies webhook event creation with event type, payload, and timestampstestConstructorWithNullEntityId: Tests webhook event creation with optional null entity IDtestWebhookEventIsReadonly: Ensures webhook event properties are immutable
-
WebhookSubscription (
WebhookSubscriptionTest.php)testConstructorInitializesWebhookSubscription: Verifies subscription creation with URL, events, and secrettestUrlCanBeUpdated: Tests URL modification for webhook subscriptionstestEventsCanBeUpdated: Verifies event list updatestestActiveCanBeUpdated: Tests active status togglingtestUpdatedAtCanBeSet: Verifies updated timestamp assignment
-
Value Objects
-
Money (
MoneyTest.php):testCanCreateMoneyFromEurosAndCurrencytestMoneyIsImmutabletestCanAddMoney/testCanSubtractMoneytestCannotAddMoneyWithMismatchedCurrency/testCannotSubtractMoneyWithMismatchedCurrencytestMoneyCanBeComparedForEquality/testMoneyCanBeComparedForGreaterThantestFromEurosCreatesMoneyWithEurCurrency
-
Currency (
CurrencyTest.php):testCanCreateCurrencyWithValidCodetestCannotCreateCurrencyWithInvalidCode(ISO 4217 validation)testCurrencyIsImmutabletestCurrenciesCanBeComparedForEquality
-
AccountId (
AccountIdTest.php):testCanGenerateAccountId(UUID v7 check)testCanCreateAccountIdFromStringtestCannotCreateAccountIdFromInvalidStringtestAccountIdIsImmutabletestAccountIdCanBeComparedForEquality
-
BatchId (
BatchIdTest.php):testGenerateCreatesValidUuidV7: Verifies UUID v7 generationtestFromStringWithValidUuidV7: Tests creation from valid UUID stringtestFromStringWithInvalidUuidThrowsException: Validates error handling for invalid UUIDstestFromStringWithNonV7UuidThrowsException: Ensures only UUID v7 is acceptedtestEqualsReturnsTrueForSameBatchId: Tests equality comparisontestEqualsReturnsFalseForDifferentBatchIds: Tests inequalitytestToStringReturnsRfc4122Format: Verifies string representation format
-
BatchStatus (
BatchStatusTest.php):testAllStatusValuesExist: Verifies all enum values (PENDING, PROCESSING, COMPLETED, FAILED, PARTIAL)testStatusValuesAreStrings: Ensures enum values are strings
-
TransactionStatus (
TransactionStatusTest.php):testAllStatusValuesExist: Verifies all enum values (PENDING, COMPLETED, FAILED)testStatusValuesAreStrings: Ensures enum values are strings
-
RiskLevel (
RiskLevelTest.php):testAllRiskLevelsExist: Verifies all enum values (LOW, MEDIUM, HIGH)testRiskLevelValuesAreStrings: Ensures enum values are strings
-
WebhookId (
WebhookIdTest.php):testGenerateCreatesValidUuidV7: Verifies UUID v7 generationtestFromStringWithValidUuidV7: Tests creation from valid UUID stringtestFromStringWithInvalidUuidThrowsException: Validates error handlingtestEqualsReturnsTrueForSameWebhookId: Tests equality comparison
-
WebhookSecret (
WebhookSecretTest.php):testConstructorWithValidSecret: Verifies secret creation with valid length (≥32 chars)testConstructorWithShortSecretThrowsException: Validates minimum length enforcementtestGenerateCreatesValidSecret: Tests secret generation
-
RegulatoryRequirement (
RegulatoryRequirementTest.php):testAllRegulatoryRequirementsExist: Verifies all enum values (FATCA, CRS, PSD2, GDPR, AML, KYC)testRegulatoryRequirementValuesAreStrings: Ensures enum values are strings
-
AuditCategory (
AuditCategoryTest.php):testAllAuditCategoriesExist: Verifies all enum values (TRANSACTION, KYC, AML, ACCESS, CONFIG)testAuditCategoryValuesAreStrings: Ensures enum values are stringstestAuditCategoryCanBeCreatedFromString: Tests enum creation from string values
-
ComplianceLevel (
ComplianceLevelTest.php):testAllComplianceLevelsExist: Verifies all enum values (REGULATORY, OPERATIONAL, SECURITY)testComplianceLevelValuesAreStrings: Ensures enum values are stringstestComplianceLevelCanBeCreatedFromString: Tests enum creation from string values
-
- FundTransferService (
FundTransferServiceTest.php)testTransferThrowsExceptionOnInsufficientFunds: Ensures insufficient funds exception is throwntestTransferThrowsExceptionOnCurrencyMismatch: Ensures currency mismatch exception is throwntestTransferMovesMoney: Verifies the core "debit source, credit target" logic returns updated Account entities.
- FundsTransferredEvent (
FundsTransferredEventTest.php)testEventCanBeCreated: Verifies the DTO structure for the event.
-
TransferReceiptHandler (
TransferReceiptHandlerTest.php)testFundsTransferredEventEmailFailsAndLogsError: Tests error handling when email sending failstestFundsTransferredEventTriggersEmail: Verifies that an email is composed and sent via the Mailer interface.
-
BatchTransferHandler (
BatchTransferHandlerTest.php)testInvokeProcessesBatchSuccessfully: Verifies successful batch processing with all transactions completedtestInvokeHandlesPartialSuccess: Tests batch processing with mixed success/failure scenariostestInvokeHandlesCompleteFailure: Verifies batch failure handling when all transactions failtestInvokeLogsBatchProcessing: Ensures batch processing events are logged appropriately
-
WebhookDeliveryHandler (
WebhookDeliveryHandlerTest.php)testInvokeDeliversWebhookSuccessfully: Verifies successful webhook delivery with HTTP 200 responsetestInvokeRetriesOnFailure: Tests webhook retry logic for failed deliveriestestInvokeHandlesMaxRetriesExceeded: Verifies handling when maximum retry attempts are exceededtestInvokeLogsDeliveryFailures: Ensures delivery failures are logged appropriately
- ProcessBatchTransferUseCase (
ProcessBatchTransferUseCaseTest.php)testExecuteCreatesBatchAndDispatchesMessage: Verifies batch creation and message dispatch to async queuetestExecuteValidatesAccountExistence: Tests account validation before batch creationtestExecuteHandlesInvalidAccounts: Verifies error handling for non-existent accountstestExecuteCreatesBatchWithCorrectStatus: Ensures batch is created with PENDING status
- BatchTransferMessage (
BatchTransferMessageTest.php)testConstructorInitializesMessage: Verifies message creation with batch ID and transactions arraytestMessageIsReadonly: Ensures message properties are immutable
- AccountNotFoundException (Covered via integration tests)
- Exception thrown when account lookup fails
- InsufficientFundsException (Covered via integration tests)
- Exception thrown when transfer amount exceeds balance
- TransactionLimitExceededException (
TransactionLimitExceededExceptionTest.php)testExceptionMessageContainsAccountIdAndLimitDetails: Verifies exception message includes account ID, limit type, limit value, and current valuetestExceptionMessageFormat: Tests exception message formatting for daily and monthly limits
- TransferRequest (Covered via integration tests)
- DTO for single transfer requests, validated through use case tests
- BatchTransferRequest (Partially covered via integration tests)
- DTO for batch transfer requests, validated through integration tests
- BatchTransferResponse (Partially covered via integration tests)
- Response DTO for batch transfer operations, validated through integration tests
Location: tests/Unit/Infrastructure/
Goal: Verify Infrastructure adapters, event subscribers, services, and security components in isolation.
-
SecurityHeadersSubscriber (
SecurityHeadersSubscriberTest.php)testGetSubscribedEventsReturnsCorrectEvents: Verifies subscriber listens to RESPONSE eventstestOnKernelResponseAddsSecurityHeadersForApiRoutes: Tests security headers (X-Content-Type-Options, X-Frame-Options, Strict-Transport-Security, CSP, Referrer-Policy) are added to API responsestestOnKernelResponseSkipsNonApiRoutes: Ensures security headers are only added to API routes
-
RateLimitHeadersSubscriber (
RateLimitHeadersSubscriberTest.php)testGetSubscribedEventsReturnsCorrectEvents: Verifies subscriber listens to RESPONSE eventstestOnKernelResponseAddsRateLimitHeadersWhenAccountIdPresent: Tests rate limit headers (X-RateLimit-Limit, X-RateLimit-Remaining, X-RateLimit-Reset) are added when account ID is availabletestOnKernelResponseSkipsWhenNoAccountId: Ensures headers are skipped when account ID is not present
-
RequestLoggingSubscriber (
RequestLoggingSubscriberTest.php)testGetSubscribedEventsReturnsCorrectEvents: Verifies subscriber listens to REQUEST and RESPONSE eventstestOnKernelRequestLogsApiRequest: Tests API request logging with method, path, and user agenttestOnKernelResponseLogsApiResponse: Verifies API response logging with status code and response time
-
AuditLogService (
AuditLogServiceTest.php)testLogTransactionCreatesAndSavesAuditLog: Verifies transaction audit log creation with proper categorizationtestLogKYCCreatesAndSavesAuditLog: Tests KYC audit log creation with compliance leveltestLogAMLCreatesAndSavesAuditLog: Verifies AML audit log creation with regulatory requirementstestLogAccessCreatesAndSavesAuditLog: Tests access audit log creation with metadata
-
RiskBasedRateLimiter (
RiskBasedRateLimiterTest.php)testGetLimitForAccountReturnsLowRiskLimit: Verifies LOW risk accounts get 100 requests/hour limittestGetLimitForAccountReturnsMediumRiskLimit: Tests MEDIUM risk accounts get 50 requests/hour limittestGetLimitForAccountReturnsHighRiskLimit: Verifies HIGH risk accounts get 10 requests/hour limittestConsumeDecrementsTokens: Tests token consumption and remaining count
-
RedisTransactionLimitService (
RedisTransactionLimitServiceTest.php)testCheckLimitAllowsTransactionWithinDailyLimit: Verifies transactions within daily limit are allowedtestCheckLimitThrowsExceptionWhenDailyLimitExceeded: Tests exception thrown when daily limit is exceededtestCheckLimitThrowsExceptionWhenMonthlyLimitExceeded: Verifies exception thrown when monthly limit is exceededtestRecordTransactionIncrementsCounters: Tests transaction recording updates daily and monthly counters
-
WebhookDeliveryService (
WebhookDeliveryServiceTest.php)testDeliverDispatchesMessageForActiveSubscription: Verifies webhook delivery message dispatch for active subscriptionstestDeliverSkipsInactiveSubscription: Tests inactive subscriptions are skippedtestDeliverFiltersEventsBySubscription: Ensures only subscribed event types trigger delivery
- ThrottlingAwareAuthenticationFailureHandler (
ThrottlingAwareAuthenticationFailureHandlerTest.php)testOnAuthenticationFailureReturns429ForThrottlingException: Verifies HTTP 429 response for rate-limited login attemptstestOnAuthenticationFailureReturns429ForWrappedThrottlingException: Tests wrapped throttling exceptions are handled correctlytestOnAuthenticationFailureDelegatesToLexikHandler: Ensures non-throttling exceptions are delegated to Lexik handler
Location: tests/Integration/
Goal: Verify the interaction between the Application layer and Infrastructure adapters (Database, Doctrine, Messenger).
- TransferFundsUseCase (
TransferFundsUseCaseTest.php)testTransferSuccess: Verifies the happy path (Lock -> Debit/Credit -> Save -> Dispatch Event).testTransferFailsOnInsufficientFunds: Ensures the transaction is rolled back and exception thrown.testTransferFailsWhenAccountNotFound: Ensures correct exception when IDs are invalid.
- AccountRepository (
AccountRepositoryTest.php)testSaveAndFind: Verifies account persistence and retrieval- Tests Doctrine repository implementation
- Concurrency (
ConcurrencyTest.php)testRaceConditionOnAccountDebit: Critical stress test.- Scenario: 10 concurrent requests attempt to debit an account simultaneously.
- Expected Outcome: Database locks (
PESSIMISTIC_WRITE) ensure serial processing. Final balance is mathematically correct (Initial - 10 * Amount).
Location: tests/Functional/
Goal: Verify the HTTP interface, Request/Response mapping, and Firewall/Security integration.
-
TransferController (
TransferControllerTest.php) -
AccountController (
AccountControllerTest.php)-
testGetBalanceSuccess: Verifies balance retrieval -
testGetBalanceNotFound: Tests error handling for non-existent accounts -
testGetAccountDetailsSuccess: Verifies account details retrieval -
testGetAccountDetailsNotFound: Tests error handling for non-existent accounts -
testTransferSuccess:- Authenticates via JWT.
- Sends valid JSON payload.
- Asserts HTTP 200 OK.
- Asserts JSON response status "success".
- Verifies DB state change.
-
testInsufficientFunds:- Authenticates via JWT.
- Sends request exceeding balance.
- Asserts HTTP 422 Unprocessable Entity (mapped from Exception).
- Asserts error message "Insufficient funds".
-
testTransferFailsOnAccountNotFound:- Authenticates via JWT.
- Sends request with non-existent ID.
- Asserts HTTP 422.
-
Tool: test_api.sh (Interactive Shell Script) / curl
Goal: Verify infrastructure configuration, firewall rules, and event listeners that are outside the scope of PHPUnit.
The test_api.sh script provides an interactive menu to run the following scenarios against the local environment. The script includes the following test suites:
- Authentication Tests - Login failures and protected resource access
- Basic Validation Tests - Content-Type and JSON format validation
- Extended Validation Tests - Missing fields, zero amounts, invalid currency formats
- Business Logic Tests - Self-transfers, negative amounts, currency mismatches, insufficient funds, account not found, invalid UUIDs
- Happy Path Transfer - Successful transfer operations
- Multiple Transfers & Balance Verification - Sequential transfers with balance consistency checks
- Account Read Operations - Balance and details retrieval with error cases
- Health Check Endpoint - System health status verification
- Batch Transfer Operations - Batch processing with various validation scenarios
- Rate Limiting Tests - Rate limit enforcement verification
Run the script with ./test_api.sh for interactive mode or ./test_api.sh --run-all to execute all tests sequentially.
| Scenario | Description | Example Request | Expected Result |
|---|---|---|---|
| Login Success | Valid credentials return a JWT token. | POST /api/login_check{"email":"api@example.com", "password":"secure123"} |
200 OK{"token": "eyJ..."} |
| Login Failure | Invalid password is rejected. | POST /api/login_check{"email":"api@example.com", "password":"WRONG"} |
401 Unauthorized{"message": "Invalid credentials."} |
| Protected Resource (No Token) | Accessing API without Authorization header. |
POST /api/v1/transfer |
401 Unauthorized{"message": "JWT Token not found"} |
| Scenario | Description | Example Request | Expected Result |
|---|---|---|---|
| Content-Type Check | Sending text/plain instead of application/json. |
POST /api/v1/transferContent-Type: text/plain |
415 Unsupported Media Type or 400 Bad Request{"detail": "Invalid Content-Type..."} |
| Malformed JSON | Sending invalid JSON syntax. | POST /api/v1/transferBody: {bad_json} |
400 Bad Request{"detail": "Invalid JSON format..."} |
| Scenario | Description | Example Request | Expected Result |
|---|---|---|---|
| Missing sourceAccountId | Request without source account ID. | POST /api/v1/transfer{"targetAccountId": "...", "amount": 100, "currency": "EUR"} |
422 Unprocessable Entity or 400 Bad RequestValidation Error: "This value should not be blank." |
| Missing targetAccountId | Request without target account ID. | POST /api/v1/transfer{"sourceAccountId": "...", "amount": 100, "currency": "EUR"} |
422 Unprocessable Entity or 400 Bad RequestValidation Error: "This value should not be blank." |
| Missing amount | Request without amount field. | POST /api/v1/transfer{"sourceAccountId": "...", "targetAccountId": "...", "currency": "EUR"} |
422 Unprocessable Entity or 400 Bad RequestValidation Error: "This value should not be blank." |
| Missing currency | Request without currency field. | POST /api/v1/transfer{"sourceAccountId": "...", "targetAccountId": "...", "amount": 100} |
422 Unprocessable Entity or 400 Bad RequestValidation Error: "This value should not be blank." |
| Zero Amount | Sending amount of 0. | POST /api/v1/transfer{"amount": 0, ...} |
422 Unprocessable EntityValidation Error: "This value should be positive." |
| Invalid Currency Length (Too Short) | Currency code with less than 3 characters. | POST /api/v1/transfer{"currency": "EU", ...} |
422 Unprocessable EntityValidation Error: "This value should have exactly 3 characters." |
| Invalid Currency Length (Too Long) | Currency code with more than 3 characters. | POST /api/v1/transfer{"currency": "EURO", ...} |
422 Unprocessable EntityValidation Error: "This value should have exactly 3 characters." |
| Empty JSON Body | Sending empty JSON object. | POST /api/v1/transfer{} |
422 Unprocessable Entity or 400 Bad RequestValidation errors for all required fields. |
| Scenario | Description | Example Request | Expected Result |
|---|---|---|---|
| Self Transfer | Source and Target Account IDs are identical. | POST /api/v1/transfer{"sourceAccountId": "UUID-A", "targetAccountId": "UUID-A", ...} |
500 Internal Server Error (or 400 if mapped)Exception: "Source and Target accounts cannot be the same." |
| Negative Amount | Sending a negative amount (e.g., -100). | POST /api/v1/transfer{"amount": -100} |
422 Unprocessable EntityValidation Error: "This value should be positive." |
| Currency Mismatch | Transferring between mismatched currencies (e.g., EUR -> USD). | POST /api/v1/transfer{"sourceAccountId": "EUR-Account", "targetAccountId": "USD-Account"} |
500 Internal Server ErrorException: "Currency mismatch..." |
| Insufficient Funds | Transfer amount exceeds source balance. | POST /api/v1/transfer{"amount": 1000000} |
422 Unprocessable EntityException: "Insufficient funds" |
| Account Not Found | Source or Target ID does not exist. | POST /api/v1/transfer{"sourceAccountId": "RANDOM-UUID"} |
422 Unprocessable EntityException: "Account with ID ... not found." |
| Invalid UUID | Malformed UUID string. | POST /api/v1/transfer{"sourceAccountId": "INVALID"} |
422 Unprocessable EntityValidation Error: "This is not a valid UUID." |
| Scenario | Description | Example Request | Expected Result |
|---|---|---|---|
| Successful Transfer | Valid credentials, valid accounts, sufficient funds. | POST /api/v1/transferAuthorization: Bearer <TOKEN>{"sourceAccountId": "UUID-A", "targetAccountId": "UUID-B", "amount": 100, "currency": "EUR"} |
200 OK{"status": "success", "message": "Transfer initiated successfully."} |
| Scenario | Description | Example Request | Expected Result |
|---|---|---|---|
| Get Balance | Retrieve account balance with valid UUID. | GET /api/v1/accounts/{id}/balanceAuthorization: Bearer <TOKEN> |
200 OK{"account_id": "...", "balance": 100000, "currency": "EUR"} |
| Get Account Details | Retrieve full account information. | GET /api/v1/accounts/{id}Authorization: Bearer <TOKEN> |
200 OK{"id": "...", "balance": 100000, "currency": "EUR", "created_at": "..."} |
| Get Balance Without Auth | Accessing balance endpoint without token. | GET /api/v1/accounts/{id}/balance |
401 Unauthorized{"message": "JWT Token not found"} |
| Get Account Details Without Auth | Accessing account endpoint without token. | GET /api/v1/accounts/{id} |
401 Unauthorized{"message": "JWT Token not found"} |
| Get Balance with Invalid UUID | Using malformed UUID in URL path. | GET /api/v1/accounts/INVALID-UUID/balanceAuthorization: Bearer <TOKEN> |
404 Not Found or 400 Bad RequestRouting or validation error. |
| Get Account Details with Invalid UUID | Using malformed UUID in URL path. | GET /api/v1/accounts/INVALID-UUIDAuthorization: Bearer <TOKEN> |
404 Not Found or 400 Bad RequestRouting or validation error. |
| Get Balance with Non-Existent Account | Using valid UUID format but account doesn't exist. | GET /api/v1/accounts/{non-existent-uuid}/balanceAuthorization: Bearer <TOKEN> |
422 Unprocessable Entity or 404 Not Found{"message": "Account with ID ... not found."} |
| Get Account Details with Non-Existent Account | Using valid UUID format but account doesn't exist. | GET /api/v1/accounts/{non-existent-uuid}Authorization: Bearer <TOKEN> |
422 Unprocessable Entity or 404 Not Found{"message": "Account with ID ... not found."} |
| Scenario | Description | Example Request | Expected Result |
|---|---|---|---|
| Health Check | System health status (no authentication required). | GET /api/v1/health |
200 OK (if all systems healthy) or 503 Service Unavailable (if degraded){"status": "ok", "timestamp": "...", "checks": {"database": {...}, "redis": {...}, "queue": {...}}} |
| Scenario | Description | Example Request | Expected Result |
|---|---|---|---|
| Batch Transfer - Empty Array | Sending batch with no transactions. | POST /api/v1/batch/transfer{"transactions": []} |
422 Unprocessable EntityValidation Error: "Batch must contain at least one transaction" |
| Batch Transfer - Missing transactions Field | Request without transactions array. | POST /api/v1/batch/transfer{} |
422 Unprocessable Entity or 400 Bad RequestValidation Error: "This value should not be blank." |
| Batch Transfer - Single Valid Transaction | Batch with one valid transfer. | POST /api/v1/batch/transfer{"transactions": [{"sourceAccountId": "...", "targetAccountId": "...", "amount": 5000, "currency": "EUR"}]} |
202 Accepted{"status": "success", "batch_id": "...", "batch_status": "...", "total_count": 1, "message": "..."} |
| Batch Transfer - Multiple Valid Transactions | Batch with multiple valid transfers. | POST /api/v1/batch/transfer{"transactions": [{...}, {...}]} |
202 Accepted{"status": "success", "batch_id": "...", "batch_status": "...", "total_count": N, "message": "..."} |
| Batch Transfer - Invalid Transaction in Batch | Batch containing at least one invalid transaction (e.g., non-existent account). | POST /api/v1/batch/transfer{"transactions": [valid, invalid]} |
202 Accepted (batch accepted, errors processed) or 422 Unprocessable Entity (batch rejected) |
| Batch Transfer - Self-Transfer in Batch | Batch containing a self-transfer transaction. | POST /api/v1/batch/transfer{"transactions": [{"sourceAccountId": "X", "targetAccountId": "X", ...}]} |
422 Unprocessable Entity or 400 Bad RequestError: "Source and Target accounts cannot be the same." |
| Batch Transfer Without Authentication | Accessing batch endpoint without token. | POST /api/v1/batch/transfer |
401 Unauthorized{"message": "JWT Token not found"} |
| Scenario | Description | Example Request | Expected Result |
|---|---|---|---|
| Multiple Sequential Transfers | Performing multiple transfers and verifying balance updates. | Multiple POST /api/v1/transfer requests |
Each transfer succeeds (200 OK), and final balance matches: initial_balance - sum(all_transfers) |
| Balance Consistency | Verify account balances are correctly updated after transfers. | GET /api/v1/accounts/{id}/balance after transfers |
Balance reflects all completed transfers accurately. |
| Scenario | Description | Example Request | Expected Result |
|---|---|---|---|
| Login Rate Limit | Testing authentication rate limiting (5 attempts/minute). | 7 rapid POST /api/login_check requests with wrong password |
First 5 return 401 Unauthorized, subsequent requests return 429 Too Many Requests |
| Transfer Rate Limit | Testing transfer endpoint rate limiting (1000 requests/minute). | Multiple rapid POST /api/v1/transfer requests |
All requests succeed if under limit, or 429 Too Many Requests if limit exceeded{"status": "error", "message": "Rate limit exceeded. Please try again later."} |
1. Login & Get Token
TOKEN=$(curl -s -X POST http://localhost/api/login_check \
-H "Content-Type: application/json" \
-d '{"email":"api@example.com","password":"secure123"}' | jq -r .token)2. Successful Transfer
curl -X POST http://localhost/api/v1/transfer \
-H "Authorization: Bearer $TOKEN" \
-H "Content-Type: application/json" \
-d '{
"sourceAccountId": "0193da46-abcd-7ef8-9012-34567890abcd",
"targetAccountId": "0193da46-ef01-7234-5678-901234567890",
"amount": 100,
"currency": "EUR"
}'3. Get Account Balance
curl -X GET http://localhost/api/v1/accounts/{account-id}/balance \
-H "Authorization: Bearer $TOKEN"4. Get Account Details
curl -X GET http://localhost/api/v1/accounts/{account-id} \
-H "Authorization: Bearer $TOKEN"5. Health Check
curl -X GET http://localhost/api/v1/health6. Batch Transfer
curl -X POST http://localhost/api/v1/batch/transfer \
-H "Authorization: Bearer $TOKEN" \
-H "Content-Type: application/json" \
-d '{
"transactions": [
{
"sourceAccountId": "0193da46-abcd-7ef8-9012-34567890abcd",
"targetAccountId": "0193da46-ef01-7234-5678-901234567890",
"amount": 1000,
"currency": "EUR"
},
{
"sourceAccountId": "0193da46-abcd-7ef8-9012-34567890abcd",
"targetAccountId": "0193da46-ef01-7234-5678-901234567890",
"amount": 2000,
"currency": "EUR"
}
]
}'Tool: stress_test.sh (non-interactive)
Goal: Verify that:
- Pessimistic locking (
PESSIMISTIC_WRITE) prevents race conditions under load. - Balances remain mathematically correct after many concurrent transfers.
- Database is reset before each test run for consistent results.
- Script:
./stress_test.sh 200- Automatically resets the database before each run (drops, recreates, runs migrations, loads fixtures).
- Clears rate limiter cache.
- Authenticates via
/api/login_checkusing the seeded user (api@example.com/secure123). - Creates:
- Source account with enough initial balance.
- Target account with zero balance.
- Sends N transfer requests (default 200) using correct API endpoints (
/api/v1/transfer). - Verifies:
- Final source balance:
initial - N * amount. - Final target balance:
0 + N * amount.
- Final source balance:
If the final balances do not match the expected values, the script flags a potential race condition.
From the project root:
make start
make seed
make test-stress # Runs ./stress_test.sh 200Rate limiting is enabled on transfer endpoints (transfer_api limiter). For normal development:
- Default limit: 10 transfers/minute.
- If you run
./stress_test.sh 200without adjusting the limit:- Some requests may be throttled (
429 Too Many Requests). - Final balances will not match expected values (by design).
- Some requests may be throttled (
To run high-volume stress tests without hitting rate limits, temporarily increase the transfer_api.limit value in config/packages/rate_limiter.yaml:
framework:
rate_limiter:
transfer_api:
policy: 'fixed_window'
limit: 1000 # temporarily increased for stress tests
interval: '1 minute'
cache_pool: cache.rate_limiterThen clear the cache so Symfony picks up the new configuration:
docker compose exec php bin/console cache:clear --env=dev
make test-stressAfter the test, revert limit back to 10 and clear the cache again.
-
✅ PASS (No Rate Limiting Hit):
- All requests succeed (no
429in Nginx/Symfony logs). - Final source and target balances exactly match expected values.
- Indicates:
- Pessimistic locking works under load.
- No lost updates or double-spends.
- All requests succeed (no
-
⚠️ FAIL (Rate Limiting Hit):- Some requests return
429 Too Many Requests. - Final balances do not match
N * amount. - Action:
- Increase
RATE_LIMIT_TRANSFER_APIand re-run. - This is a test configuration issue, not a domain logic bug.
- Increase
- Some requests return
-
❌ FAIL (No Rate Limiting, Balances Wrong):
- No
429responses. - Balances do not match expected values.
- Action:
- Investigate for real concurrency bugs (locking, transaction boundaries, repository methods).
- No
This separation ensures we don't misinterpret rate limit configuration problems as pessimistic locking failures.