summaryrefslogtreecommitdiff
path: root/tests/Unit/BasicStrategyTest.php
blob: 2c657d61977ca3bfe7380b9ce7b4f212c24a346a (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
<?php

use Lightscale\Router\BasicStrategy;
use Lightscale\Router\Enums\HttpMethod;
use Lightscale\Router\Exceptions\NotFoundException;
use Lightscale\Router\Route;
use Lightscale\Router\RouteCall;
use Lightscale\Router\Test\Utils\TestCallable;
use Lightscale\Router\Test\Utils\TestMiddleware;
use Nyholm\Psr7\Factory\Psr17Factory;

it('initialises')
    ->expect(fn () => new BasicStrategy())
    ->toBeInstanceOf(BasicStrategy::class);

it('throws on not found', function () {
    (new BasicStrategy())->notFound(
        (new Psr17Factory())->createServerRequest(
            HttpMethod::Get->value,
            '/testing/testing'
        )
    );
})->throws(NotFoundException::class);

it('calls route', function () {
    $factory = new Psr17Factory();
    $response = $factory->createResponse(200, 'OK');
    $cb = TestCallable::make(fn () => $response);
    $res = (new BasicStrategy())->runRoute($rc = new RouteCall(
        $factory->createServerRequest(
            HttpMethod::Get->value,
            '/testing/testing'
        ),
        new Route(
            HttpMethod::Get,
            $cb
        ),
        []
    ));

    $cb->assertCalled();
    $call = $cb->getLastCall();
    expect($call->args[0] ?? null)->toBe($rc);
    expect($res)->toBe($response);
});

it('runs middleware', function () {
    $factory = new Psr17Factory();
    $request = $factory->createServerRequest('get', '/test');
    $response = $factory->createResponse();

    $middleware = [
        $mw1 = new TestMiddleware(),
        $mw2 = new TestMiddleware(),
    ];

    $handler = new TestCallable(fn () => $response);
    $strategy = new BasicStrategy();
    $result = $strategy->runMiddleware($request, $middleware, $handler);

    expect($result)->toBe($response);
    $mw1->assertCalled();
    $mw2->assertCalled();
    $handler->assertCalled();
});

it('runs handler with no middleware', function () {
    $factory = new Psr17Factory();
    $request = $factory->createServerRequest('get', '/test');
    $response = $factory->createResponse();

    $middleware = [];

    $handler = new TestCallable(fn () => $response);
    $strategy = new BasicStrategy();
    $result = $strategy->runMiddleware($request, $middleware, $handler);

    expect($result)->toBe($response);
    $handler->assertCalled();
});