Field Manual Brokerage / Linux / Laravel
← Laravel

tests/Feature/BrokerageTest.php

Paste the complete file at this path. Names and paths are case-sensitive on Linux.

What it is

Complete brokerage practice file. The Assemble project page lists every file in order.

When to use it

Paste the complete file at this path. Names and paths are case-sensitive on Linux.

Syntax

mkdir -p 'tests/Feature'
# Paste the Example below into tests/Feature/BrokerageTest.php

Example

<?php

declare(strict_types=1);

namespace Tests\Feature;

use App\Models\Order;
use Illuminate\Foundation\Testing\DatabaseMigrations;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Http;
use RuntimeException;
use Tests\TestCase;

class BrokerageTest extends TestCase
{
    use DatabaseMigrations;

    protected function setUp(): void
    {
        parent::setUp();
        Http::preventStrayRequests();
        config(['services.exchange.base_url' => 'https://exchange.test', 'services.exchange.api_key' => 'test-key']);
    }

    private function payload(): array
    {
        return ['symbol' => 'AAPL', 'side' => 'buy', 'type' => 'limit', 'quantity' => 100, 'price' => 189.4];
    }

    public function test_page_and_market_feed(): void
    {
        $market = ['data' => [['symbol' => 'AAPL', 'last_price' => 189.42]]];
        Http::fake(['exchange.test/v1/market-data' => Http::response($market)]);
        $this->get('/')->assertOk()->assertSee('Brokerage Market')->assertSee('csrf-token');
        $this->getJson('/market-data')->assertOk()->assertExactJson($market);
        Http::assertSent(fn ($request): bool => $request->hasHeader('Authorization', 'Bearer test-key'));
    }

    public function test_validation_messages(): void
    {
        $this->postJson('/orders', ['symbol' => 'aapl', 'side' => 'invalid', 'type' => 'limit', 'quantity' => 0])
            ->assertUnprocessable()
            ->assertJsonPath('errors.symbol.0', 'Use 1 to 5 uppercase letters for the symbol.')
            ->assertJsonPath('errors.side.0', 'Side must be buy or sell.')
            ->assertJsonPath('errors.quantity.0', 'Quantity must be at least 1.')
            ->assertJsonPath('errors.price.0', 'Price is required for limit orders.');
        $this->assertDatabaseCount('orders', 0);
        Http::assertNothingSent();
    }

    public function test_order_acceptance_calls_http_outside_transaction(): void
    {
        Http::fake(function ($request) {
            $this->assertSame(0, DB::transactionLevel());
            $this->assertDatabaseHas('orders', ['status' => 'pending', 'client_order_id' => $request['client_order_id']]);
            return Http::response(['exchange_order_id' => 'EX-123', 'status' => 'accepted'], 201);
        });
        $this->postJson('/orders', $this->payload())->assertCreated()->assertJsonPath('exchange_order_id', 'EX-123');
        $this->assertDatabaseHas('orders', ['status' => 'accepted', 'exchange_order_id' => 'EX-123']);
        Http::assertSentCount(1);
    }

    public function test_exchange_rejection_is_persisted(): void
    {
        Http::fake(['*' => Http::response(['error' => ['message' => 'Private upstream detail']], 422)]);
        $this->postJson('/orders', $this->payload())->assertUnprocessable()
            ->assertJsonPath('message', 'The exchange rejected the order. Please check your order details.');
        $this->assertDatabaseHas('orders', ['status' => 'rejected']);
    }

    public function test_timeout_is_unknown_and_not_retried(): void
    {
        Http::fake(['*' => Http::failedConnection()]);
        $this->postJson('/orders', $this->payload())->assertStatus(503)
            ->assertJsonPath('message', 'Order status is unconfirmed. Do not submit it again; contact the broker.');
        $this->assertDatabaseCount('orders', 1);
        $this->assertDatabaseHas('orders', ['status' => 'unknown']);
        $this->assertDatabaseMissing('orders', ['status' => 'rejected']);
        Http::assertSentCount(1);
    }

    public function test_server_error_is_unknown(): void
    {
        Http::fake(['*' => Http::response([], 500)]);
        $this->postJson('/orders', $this->payload())->assertStatus(503);
        $this->assertDatabaseHas('orders', ['status' => 'unknown']);
        Http::assertSentCount(1);
    }

    public function test_market_order_excludes_price(): void
    {
        Http::fake(function ($request) {
            $this->assertArrayNotHasKey('price', $request->data());
            return Http::response(['exchange_order_id' => 'EX-MARKET', 'status' => 'accepted'], 201);
        });
        $this->postJson('/orders', [...$this->payload(), 'type' => 'market'])->assertCreated();
        $this->assertDatabaseHas('orders', ['type' => 'market', 'price' => null]);
    }

    public function test_initial_transaction_failure_leaves_no_order(): void
    {
        Order::created(function (): void {
            throw new RuntimeException('Private database detail');
        });
        try {
            $this->postJson('/orders', $this->payload())->assertStatus(500)
                ->assertJsonPath('message', 'An unexpected error occurred. Please contact the broker before submitting again.');
            $this->assertDatabaseCount('orders', 0);
            Http::assertNothingSent();
        } finally {
            Order::flushEventListeners();
        }
    }

    public function test_final_transaction_failure_leaves_order_pending(): void
    {
        Http::fake(['*' => Http::response(['exchange_order_id' => 'EX-123', 'status' => 'accepted'], 201)]);
        Order::updated(function (): void {
            throw new RuntimeException('Private database detail');
        });
        try {
            $this->postJson('/orders', $this->payload())->assertStatus(500)
                ->assertJsonPath('message', 'An unexpected error occurred. Please contact the broker before submitting again.');
            $this->assertDatabaseHas('orders', ['status' => 'pending', 'exchange_order_id' => null]);
        } finally {
            Order::flushEventListeners();
        }
    }

    public function test_market_polling_does_not_use_the_order_rate_limit(): void
    {
        config(['services.exchange.demo' => true]);
        for ($i = 0; $i < 11; $i++) {
            $this->getJson('/market-data')->assertOk();
        }
        $this->postJson('/orders', $this->payload())->assertCreated();
    }

    public function test_demo_runs_without_exchange_access(): void
    {
        config(['services.exchange.demo' => true]);
        $this->get('/')->assertOk()->assertSee('Practice mode');
        $this->getJson('/market-data')->assertOk()->assertJsonPath('data.0.symbol', 'AAPL');
        $this->postJson('/orders', $this->payload())->assertCreated();
        $this->assertDatabaseHas('orders', ['status' => 'accepted']);
        Http::assertNothingSent();
    }
}

Common mistakes

Use the setup runbook first. Adapt provisional API assumptions to the supplied contract. Merge into supplied applications; do not duplicate the orders migration.

Related topics

API contract: change these points first