Skip to content

Latest commit

 

History

History
627 lines (486 loc) · 35.6 KB

TESTING.md

File metadata and controls

627 lines (486 loc) · 35.6 KB

Testing Coverage Documentation

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.

Current Coverage Status

Last Updated: December 23, 2025

Coverage Metrics (Overall)

  • 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.

Coverage Breakdown

Fully Covered Classes (100%):

  • App\Application\DTO\TransferRequest
  • App\Application\MessageHandler\TransferReceiptHandler
  • App\Application\MessageHandler\BatchTransferHandler
  • App\Application\MessageHandler\WebhookDeliveryHandler
  • App\Application\Message\BatchTransferMessage
  • App\Application\UseCase\ProcessBatchTransferUseCase
  • App\Domain\Event\FundsTransferredEvent
  • App\Domain\Exception\AccountNotFoundException
  • App\Domain\Exception\InsufficientFundsException
  • App\Domain\Exception\TransactionLimitExceededException
  • App\Domain\Model\Account
  • App\Domain\Model\AuditLog
  • App\Domain\Model\BatchTransfer
  • App\Domain\Model\WebhookEvent
  • App\Domain\Model\WebhookSubscription
  • App\Domain\Service\FundTransferService
  • App\Domain\ValueObject\AccountId
  • App\Domain\ValueObject\AuditCategory
  • App\Domain\ValueObject\BatchId
  • App\Domain\ValueObject\BatchStatus
  • App\Domain\ValueObject\ComplianceLevel
  • App\Domain\ValueObject\Currency
  • App\Domain\ValueObject\Money
  • App\Domain\ValueObject\RegulatoryRequirement
  • App\Domain\ValueObject\RiskLevel
  • App\Domain\ValueObject\TransactionStatus
  • App\Domain\ValueObject\WebhookId
  • App\Domain\ValueObject\WebhookSecret
  • App\Infrastructure\Service\AuditLogService
  • App\Infrastructure\Service\RiskBasedRateLimiter
  • App\Infrastructure\Service\RedisTransactionLimitService
  • App\Infrastructure\Service\WebhookDeliveryService
  • App\Infrastructure\EventSubscriber\SecurityHeadersSubscriber
  • App\Infrastructure\EventSubscriber\RateLimitHeadersSubscriber
  • App\Infrastructure\EventSubscriber\RequestLoggingSubscriber
  • App\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:

  1. Comprehensive Unit Test Coverage: All Domain value objects, models, exceptions, and Application handlers now have dedicated unit tests
  2. Infrastructure Layer Testing: Event subscribers, services, and security components are now fully tested
  3. Test Quality: All tests use static assertions and follow PHPStan compliance standards

1. Unit Tests (Domain Logic)

Location: tests/Unit/ Goal: Verify pure PHP domain logic in isolation without any infrastructure (DB, API, Framework) dependencies.

Domain Models & Value Objects

  • 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 transactions
    • testTotalCountIsSetFromTransactionsCount: Ensures total count matches transaction array length
    • testStatusCanBeChanged: Tests batch status transitions (PENDING -> PROCESSING -> COMPLETED)
    • testSuccessAndFailureCountsCanBeUpdated: Verifies success/failure counter updates
    • testErrorsCanBeSet: Tests error tracking for failed transactions
    • testProcessedAtCanBeSet: Verifies processed timestamp assignment
  • WebhookEvent (WebhookEventTest.php)

    • testConstructorInitializesWebhookEvent: Verifies webhook event creation with event type, payload, and timestamps
    • testConstructorWithNullEntityId: Tests webhook event creation with optional null entity ID
    • testWebhookEventIsReadonly: Ensures webhook event properties are immutable
  • WebhookSubscription (WebhookSubscriptionTest.php)

    • testConstructorInitializesWebhookSubscription: Verifies subscription creation with URL, events, and secret
    • testUrlCanBeUpdated: Tests URL modification for webhook subscriptions
    • testEventsCanBeUpdated: Verifies event list updates
    • testActiveCanBeUpdated: Tests active status toggling
    • testUpdatedAtCanBeSet: Verifies updated timestamp assignment
  • Value Objects

    • Money (MoneyTest.php):

      • testCanCreateMoneyFromEurosAndCurrency
      • testMoneyIsImmutable
      • testCanAddMoney / testCanSubtractMoney
      • testCannotAddMoneyWithMismatchedCurrency / testCannotSubtractMoneyWithMismatchedCurrency
      • testMoneyCanBeComparedForEquality / testMoneyCanBeComparedForGreaterThan
      • testFromEurosCreatesMoneyWithEurCurrency
    • Currency (CurrencyTest.php):

      • testCanCreateCurrencyWithValidCode
      • testCannotCreateCurrencyWithInvalidCode (ISO 4217 validation)
      • testCurrencyIsImmutable
      • testCurrenciesCanBeComparedForEquality
    • AccountId (AccountIdTest.php):

      • testCanGenerateAccountId (UUID v7 check)
      • testCanCreateAccountIdFromString
      • testCannotCreateAccountIdFromInvalidString
      • testAccountIdIsImmutable
      • testAccountIdCanBeComparedForEquality
    • BatchId (BatchIdTest.php):

      • testGenerateCreatesValidUuidV7: Verifies UUID v7 generation
      • testFromStringWithValidUuidV7: Tests creation from valid UUID string
      • testFromStringWithInvalidUuidThrowsException: Validates error handling for invalid UUIDs
      • testFromStringWithNonV7UuidThrowsException: Ensures only UUID v7 is accepted
      • testEqualsReturnsTrueForSameBatchId: Tests equality comparison
      • testEqualsReturnsFalseForDifferentBatchIds: Tests inequality
      • testToStringReturnsRfc4122Format: 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 generation
      • testFromStringWithValidUuidV7: Tests creation from valid UUID string
      • testFromStringWithInvalidUuidThrowsException: Validates error handling
      • testEqualsReturnsTrueForSameWebhookId: Tests equality comparison
    • WebhookSecret (WebhookSecretTest.php):

      • testConstructorWithValidSecret: Verifies secret creation with valid length (≥32 chars)
      • testConstructorWithShortSecretThrowsException: Validates minimum length enforcement
      • testGenerateCreatesValidSecret: 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 strings
      • testAuditCategoryCanBeCreatedFromString: Tests enum creation from string values
    • ComplianceLevel (ComplianceLevelTest.php):

      • testAllComplianceLevelsExist: Verifies all enum values (REGULATORY, OPERATIONAL, SECURITY)
      • testComplianceLevelValuesAreStrings: Ensures enum values are strings
      • testComplianceLevelCanBeCreatedFromString: Tests enum creation from string values

Domain Services

  • FundTransferService (FundTransferServiceTest.php)
    • testTransferThrowsExceptionOnInsufficientFunds: Ensures insufficient funds exception is thrown
    • testTransferThrowsExceptionOnCurrencyMismatch: Ensures currency mismatch exception is thrown
    • testTransferMovesMoney: Verifies the core "debit source, credit target" logic returns updated Account entities.

Domain Events

  • FundsTransferredEvent (FundsTransferredEventTest.php)
    • testEventCanBeCreated: Verifies the DTO structure for the event.

Application Handlers

  • TransferReceiptHandler (TransferReceiptHandlerTest.php)

    • testFundsTransferredEventEmailFailsAndLogsError: Tests error handling when email sending fails
    • testFundsTransferredEventTriggersEmail: Verifies that an email is composed and sent via the Mailer interface.
  • BatchTransferHandler (BatchTransferHandlerTest.php)

    • testInvokeProcessesBatchSuccessfully: Verifies successful batch processing with all transactions completed
    • testInvokeHandlesPartialSuccess: Tests batch processing with mixed success/failure scenarios
    • testInvokeHandlesCompleteFailure: Verifies batch failure handling when all transactions fail
    • testInvokeLogsBatchProcessing: Ensures batch processing events are logged appropriately
  • WebhookDeliveryHandler (WebhookDeliveryHandlerTest.php)

    • testInvokeDeliversWebhookSuccessfully: Verifies successful webhook delivery with HTTP 200 response
    • testInvokeRetriesOnFailure: Tests webhook retry logic for failed deliveries
    • testInvokeHandlesMaxRetriesExceeded: Verifies handling when maximum retry attempts are exceeded
    • testInvokeLogsDeliveryFailures: Ensures delivery failures are logged appropriately

Application Use Cases

  • ProcessBatchTransferUseCase (ProcessBatchTransferUseCaseTest.php)
    • testExecuteCreatesBatchAndDispatchesMessage: Verifies batch creation and message dispatch to async queue
    • testExecuteValidatesAccountExistence: Tests account validation before batch creation
    • testExecuteHandlesInvalidAccounts: Verifies error handling for non-existent accounts
    • testExecuteCreatesBatchWithCorrectStatus: Ensures batch is created with PENDING status

Application Messages

  • BatchTransferMessage (BatchTransferMessageTest.php)
    • testConstructorInitializesMessage: Verifies message creation with batch ID and transactions array
    • testMessageIsReadonly: Ensures message properties are immutable

Domain Exceptions

  • 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 value
    • testExceptionMessageFormat: Tests exception message formatting for daily and monthly limits

Application DTOs

  • 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

Infrastructure Layer Unit Tests

Location: tests/Unit/Infrastructure/ Goal: Verify Infrastructure adapters, event subscribers, services, and security components in isolation.

Event Subscribers

  • SecurityHeadersSubscriber (SecurityHeadersSubscriberTest.php)

    • testGetSubscribedEventsReturnsCorrectEvents: Verifies subscriber listens to RESPONSE events
    • testOnKernelResponseAddsSecurityHeadersForApiRoutes: Tests security headers (X-Content-Type-Options, X-Frame-Options, Strict-Transport-Security, CSP, Referrer-Policy) are added to API responses
    • testOnKernelResponseSkipsNonApiRoutes: Ensures security headers are only added to API routes
  • RateLimitHeadersSubscriber (RateLimitHeadersSubscriberTest.php)

    • testGetSubscribedEventsReturnsCorrectEvents: Verifies subscriber listens to RESPONSE events
    • testOnKernelResponseAddsRateLimitHeadersWhenAccountIdPresent: Tests rate limit headers (X-RateLimit-Limit, X-RateLimit-Remaining, X-RateLimit-Reset) are added when account ID is available
    • testOnKernelResponseSkipsWhenNoAccountId: Ensures headers are skipped when account ID is not present
  • RequestLoggingSubscriber (RequestLoggingSubscriberTest.php)

    • testGetSubscribedEventsReturnsCorrectEvents: Verifies subscriber listens to REQUEST and RESPONSE events
    • testOnKernelRequestLogsApiRequest: Tests API request logging with method, path, and user agent
    • testOnKernelResponseLogsApiResponse: Verifies API response logging with status code and response time

Services

  • AuditLogService (AuditLogServiceTest.php)

    • testLogTransactionCreatesAndSavesAuditLog: Verifies transaction audit log creation with proper categorization
    • testLogKYCCreatesAndSavesAuditLog: Tests KYC audit log creation with compliance level
    • testLogAMLCreatesAndSavesAuditLog: Verifies AML audit log creation with regulatory requirements
    • testLogAccessCreatesAndSavesAuditLog: Tests access audit log creation with metadata
  • RiskBasedRateLimiter (RiskBasedRateLimiterTest.php)

    • testGetLimitForAccountReturnsLowRiskLimit: Verifies LOW risk accounts get 100 requests/hour limit
    • testGetLimitForAccountReturnsMediumRiskLimit: Tests MEDIUM risk accounts get 50 requests/hour limit
    • testGetLimitForAccountReturnsHighRiskLimit: Verifies HIGH risk accounts get 10 requests/hour limit
    • testConsumeDecrementsTokens: Tests token consumption and remaining count
  • RedisTransactionLimitService (RedisTransactionLimitServiceTest.php)

    • testCheckLimitAllowsTransactionWithinDailyLimit: Verifies transactions within daily limit are allowed
    • testCheckLimitThrowsExceptionWhenDailyLimitExceeded: Tests exception thrown when daily limit is exceeded
    • testCheckLimitThrowsExceptionWhenMonthlyLimitExceeded: Verifies exception thrown when monthly limit is exceeded
    • testRecordTransactionIncrementsCounters: Tests transaction recording updates daily and monthly counters
  • WebhookDeliveryService (WebhookDeliveryServiceTest.php)

    • testDeliverDispatchesMessageForActiveSubscription: Verifies webhook delivery message dispatch for active subscriptions
    • testDeliverSkipsInactiveSubscription: Tests inactive subscriptions are skipped
    • testDeliverFiltersEventsBySubscription: Ensures only subscribed event types trigger delivery

Security

  • ThrottlingAwareAuthenticationFailureHandler (ThrottlingAwareAuthenticationFailureHandlerTest.php)
    • testOnAuthenticationFailureReturns429ForThrottlingException: Verifies HTTP 429 response for rate-limited login attempts
    • testOnAuthenticationFailureReturns429ForWrappedThrottlingException: Tests wrapped throttling exceptions are handled correctly
    • testOnAuthenticationFailureDelegatesToLexikHandler: Ensures non-throttling exceptions are delegated to Lexik handler

2. Integration Tests (Use Cases & Infrastructure)

Location: tests/Integration/ Goal: Verify the interaction between the Application layer and Infrastructure adapters (Database, Doctrine, Messenger).

Use Cases

  • 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.

Repository Tests

  • AccountRepository (AccountRepositoryTest.php)
    • testSaveAndFind: Verifies account persistence and retrieval
    • Tests Doctrine repository implementation

Concurrency & Locking

  • 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).

3. Functional Tests (API Endpoints)

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.

4. Manual Verification & Security Scenarios

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:

  1. Authentication Tests - Login failures and protected resource access
  2. Basic Validation Tests - Content-Type and JSON format validation
  3. Extended Validation Tests - Missing fields, zero amounts, invalid currency formats
  4. Business Logic Tests - Self-transfers, negative amounts, currency mismatches, insufficient funds, account not found, invalid UUIDs
  5. Happy Path Transfer - Successful transfer operations
  6. Multiple Transfers & Balance Verification - Sequential transfers with balance consistency checks
  7. Account Read Operations - Balance and details retrieval with error cases
  8. Health Check Endpoint - System health status verification
  9. Batch Transfer Operations - Batch processing with various validation scenarios
  10. 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.

A. Authentication & Authorization

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"}

B. Validation & Middleware

Scenario Description Example Request Expected Result
Content-Type Check Sending text/plain instead of application/json. POST /api/v1/transfer
Content-Type: text/plain
415 Unsupported Media Type or 400 Bad Request
{"detail": "Invalid Content-Type..."}
Malformed JSON Sending invalid JSON syntax. POST /api/v1/transfer
Body: {bad_json}
400 Bad Request
{"detail": "Invalid JSON format..."}

B.1 Extended Validation Tests

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 Request
Validation 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 Request
Validation 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 Request
Validation 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 Request
Validation Error: "This value should not be blank."
Zero Amount Sending amount of 0. POST /api/v1/transfer
{"amount": 0, ...}
422 Unprocessable Entity
Validation 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 Entity
Validation 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 Entity
Validation 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 Request
Validation errors for all required fields.

C. Business Logic (Edge Cases)

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 Entity
Validation 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 Error
Exception: "Currency mismatch..."
Insufficient Funds Transfer amount exceeds source balance. POST /api/v1/transfer
{"amount": 1000000}
422 Unprocessable Entity
Exception: "Insufficient funds"
Account Not Found Source or Target ID does not exist. POST /api/v1/transfer
{"sourceAccountId": "RANDOM-UUID"}
422 Unprocessable Entity
Exception: "Account with ID ... not found."
Invalid UUID Malformed UUID string. POST /api/v1/transfer
{"sourceAccountId": "INVALID"}
422 Unprocessable Entity
Validation Error: "This is not a valid UUID."

D. Happy Path (Success)

Scenario Description Example Request Expected Result
Successful Transfer Valid credentials, valid accounts, sufficient funds. POST /api/v1/transfer
Authorization: Bearer <TOKEN>
{"sourceAccountId": "UUID-A", "targetAccountId": "UUID-B", "amount": 100, "currency": "EUR"}
200 OK
{"status": "success", "message": "Transfer initiated successfully."}

E. Account Read Operations

Scenario Description Example Request Expected Result
Get Balance Retrieve account balance with valid UUID. GET /api/v1/accounts/{id}/balance
Authorization: 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/balance
Authorization: Bearer <TOKEN>
404 Not Found or 400 Bad Request
Routing or validation error.
Get Account Details with Invalid UUID Using malformed UUID in URL path. GET /api/v1/accounts/INVALID-UUID
Authorization: Bearer <TOKEN>
404 Not Found or 400 Bad Request
Routing 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}/balance
Authorization: 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."}

F. Health Check Endpoint

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": {...}}}

G. Batch Transfer Operations

Scenario Description Example Request Expected Result
Batch Transfer - Empty Array Sending batch with no transactions. POST /api/v1/batch/transfer
{"transactions": []}
422 Unprocessable Entity
Validation 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 Request
Validation 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 Request
Error: "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"}

H. Multiple Transfers & Balance Verification

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.

I. Rate Limiting

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."}

Example CURL Commands

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/health

6. 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"
      }
    ]
  }'

5. Stress Testing & Rate Limiting

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.

5.1 How the Stress Test Works

  • 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_check using 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.

If the final balances do not match the expected values, the script flags a potential race condition.

5.2 Running the Stress Test

From the project root:

make start
make seed
make test-stress   # Runs ./stress_test.sh 200

5.3 Interaction with Rate Limiting

Rate limiting is enabled on transfer endpoints (transfer_api limiter). For normal development:

  • Default limit: 10 transfers/minute.
  • If you run ./stress_test.sh 200 without adjusting the limit:
    • Some requests may be throttled (429 Too Many Requests).
    • Final balances will not match expected values (by design).

5.4 Adjusting Rate Limits for Stress Tests

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_limiter

Then clear the cache so Symfony picks up the new configuration:

docker compose exec php bin/console cache:clear --env=dev
make test-stress

After the test, revert limit back to 10 and clear the cache again.

5.5 Interpreting Stress Test Results

  • ✅ PASS (No Rate Limiting Hit):

    • All requests succeed (no 429 in Nginx/Symfony logs).
    • Final source and target balances exactly match expected values.
    • Indicates:
      • Pessimistic locking works under load.
      • No lost updates or double-spends.
  • ⚠️ FAIL (Rate Limiting Hit):

    • Some requests return 429 Too Many Requests.
    • Final balances do not match N * amount.
    • Action:
      • Increase RATE_LIMIT_TRANSFER_API and re-run.
      • This is a test configuration issue, not a domain logic bug.
  • ❌ FAIL (No Rate Limiting, Balances Wrong):

    • No 429 responses.
    • Balances do not match expected values.
    • Action:
      • Investigate for real concurrency bugs (locking, transaction boundaries, repository methods).

This separation ensures we don't misinterpret rate limit configuration problems as pessimistic locking failures.