xref: /webtrees/tests/TestCase.php (revision 9aef375d1d8983f11b518f41ee6f490c9351cbb7)
184e2cf4eSGreg Roach<?php
23cfcc809SGreg Roach
384e2cf4eSGreg Roach/**
484e2cf4eSGreg Roach * webtrees: online genealogy
5d11be702SGreg Roach * Copyright (C) 2023 webtrees development team
684e2cf4eSGreg Roach * This program is free software: you can redistribute it and/or modify
784e2cf4eSGreg Roach * it under the terms of the GNU General Public License as published by
884e2cf4eSGreg Roach * the Free Software Foundation, either version 3 of the License, or
984e2cf4eSGreg Roach * (at your option) any later version.
1084e2cf4eSGreg Roach * This program is distributed in the hope that it will be useful,
1184e2cf4eSGreg Roach * but WITHOUT ANY WARRANTY; without even the implied warranty of
1284e2cf4eSGreg Roach * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
1384e2cf4eSGreg Roach * GNU General Public License for more details.
1484e2cf4eSGreg Roach * You should have received a copy of the GNU General Public License
1589f7189bSGreg Roach * along with this program. If not, see <https://www.gnu.org/licenses/>.
1684e2cf4eSGreg Roach */
173cfcc809SGreg Roach
18e7f56f2aSGreg Roachdeclare(strict_types=1);
19e7f56f2aSGreg Roach
2084e2cf4eSGreg Roachnamespace Fisharebest\Webtrees;
2184e2cf4eSGreg Roach
22de2aa325SGreg Roachuse Aura\Router\Route;
23ee4364daSGreg Roachuse Aura\Router\RouterContainer;
24d403609dSGreg Roachuse Fig\Http\Message\RequestMethodInterface;
2512b5bef1SGreg Roachuse Fig\Http\Message\StatusCodeInterface;
266fd01894SGreg Roachuse Fisharebest\Webtrees\Http\RequestHandlers\GedcomLoad;
272279b4f3SGreg Roachuse Fisharebest\Webtrees\Http\Routes\WebRoutes;
288136679eSGreg Roachuse Fisharebest\Webtrees\Module\ModuleThemeInterface;
298136679eSGreg Roachuse Fisharebest\Webtrees\Module\WebtreesTheme;
302c685d76SGreg Roachuse Fisharebest\Webtrees\Services\GedcomImportService;
318c3e1068SGreg Roachuse Fisharebest\Webtrees\Services\MigrationService;
3271378461SGreg Roachuse Fisharebest\Webtrees\Services\ModuleService;
33126654d7SGreg Roachuse Fisharebest\Webtrees\Services\TimeoutService;
341e653452SGreg Roachuse Fisharebest\Webtrees\Services\TreeService;
350115bc16SGreg Roachuse Illuminate\Database\Capsule\Manager as DB;
3600c45d23SGreg Roachuse Nyholm\Psr7\Factory\Psr17Factory;
37*9aef375dSGreg Roachuse PHPUnit\Framework\Constraint\Callback;
3800c45d23SGreg Roachuse Psr\Http\Message\ResponseFactoryInterface;
39d4786c66SGreg Roachuse Psr\Http\Message\ResponseInterface;
4000c45d23SGreg Roachuse Psr\Http\Message\ServerRequestFactoryInterface;
416ccdf4f0SGreg Roachuse Psr\Http\Message\ServerRequestInterface;
426ccdf4f0SGreg Roachuse Psr\Http\Message\StreamFactoryInterface;
436ccdf4f0SGreg Roachuse Psr\Http\Message\UploadedFileFactoryInterface;
446ccdf4f0SGreg Roachuse Psr\Http\Message\UploadedFileInterface;
4500c45d23SGreg Roachuse Psr\Http\Message\UriFactoryInterface;
4671378461SGreg Roach
476ccdf4f0SGreg Roachuse function app;
48*9aef375dSGreg Roachuse function array_shift;
497def76c7SGreg Roachuse function basename;
506ccdf4f0SGreg Roachuse function filesize;
516ccdf4f0SGreg Roachuse function http_build_query;
52d4786c66SGreg Roachuse function implode;
53d4786c66SGreg Roachuse function preg_match;
54d4786c66SGreg Roachuse function str_starts_with;
55d4786c66SGreg Roachuse function strcspn;
56d4786c66SGreg Roachuse function strlen;
57d4786c66SGreg Roachuse function strpos;
58d4786c66SGreg Roachuse function substr;
59d4786c66SGreg Roach
606ccdf4f0SGreg Roachuse const UPLOAD_ERR_OK;
610115bc16SGreg Roach
6284e2cf4eSGreg Roach/**
6384e2cf4eSGreg Roach * Base class for unit tests
6484e2cf4eSGreg Roach */
6571378461SGreg Roachclass TestCase extends \PHPUnit\Framework\TestCase
6684e2cf4eSGreg Roach{
67cd94ca66SGreg Roach    public static ?object $mock_functions = null;
68cd94ca66SGreg Roach
69cd94ca66SGreg Roach    protected static bool $uses_database = false;
7074d6dc0eSGreg Roach
71061b43d7SGreg Roach    /**
72061b43d7SGreg Roach     * Things to run once, before all the tests.
73061b43d7SGreg Roach     */
745e933c21SGreg Roach    public static function setUpBeforeClass(): void
75061b43d7SGreg Roach    {
76061b43d7SGreg Roach        parent::setUpBeforeClass();
77061b43d7SGreg Roach
78785274b8SGreg Roach        $webtrees = new Webtrees();
79785274b8SGreg Roach        $webtrees->bootstrap();
8000c45d23SGreg Roach
81785274b8SGreg Roach        // PSR7 messages and PSR17 message-factories
82785274b8SGreg Roach        Webtrees::set(ResponseFactoryInterface::class, Psr17Factory::class);
83785274b8SGreg Roach        Webtrees::set(ServerRequestFactoryInterface::class, Psr17Factory::class);
84785274b8SGreg Roach        Webtrees::set(StreamFactoryInterface::class, Psr17Factory::class);
85785274b8SGreg Roach        Webtrees::set(UploadedFileFactoryInterface::class, Psr17Factory::class);
86785274b8SGreg Roach        Webtrees::set(UriFactoryInterface::class, Psr17Factory::class);
876ccdf4f0SGreg Roach
88785274b8SGreg Roach        // This is normally set in middleware.
89785274b8SGreg Roach        Webtrees::set(ModuleThemeInterface::class, WebtreesTheme::class);
906ccdf4f0SGreg Roach
91ee4364daSGreg Roach        // Need the routing table, to generate URLs.
922279b4f3SGreg Roach        $router_container = new RouterContainer('/');
932279b4f3SGreg Roach        (new WebRoutes())->load($router_container->getMap());
94785274b8SGreg Roach        Webtrees::set(RouterContainer::class, $router_container);
95ee4364daSGreg Roach
96061b43d7SGreg Roach        if (static::$uses_database) {
97061b43d7SGreg Roach            static::createTestDatabase();
9871378461SGreg Roach
990be3fcd1SJonathan Jaubart            I18N::init('en-US');
1000be3fcd1SJonathan Jaubart
10100c92694SGreg Roach            // This is normally set in middleware.
102e669bb4bSGreg Roach            (new Gedcom())->registerTags(Registry::elementFactory(), true);
10300c92694SGreg Roach
10471378461SGreg Roach            // Boot modules
10571378461SGreg Roach            (new ModuleService())->bootModules(new WebtreesTheme());
1064a9a6095SGreg Roach        } else {
1074a9a6095SGreg Roach            I18N::init('en-US', true);
108061b43d7SGreg Roach        }
109061b43d7SGreg Roach    }
110061b43d7SGreg Roach
111061b43d7SGreg Roach    /**
11271378461SGreg Roach     * Things to run once, AFTER all the tests.
11371378461SGreg Roach     */
1145e933c21SGreg Roach    public static function tearDownAfterClass(): void
11571378461SGreg Roach    {
11671378461SGreg Roach        if (static::$uses_database) {
11771378461SGreg Roach            $pdo = DB::connection()->getPdo();
11871378461SGreg Roach            unset($pdo);
11971378461SGreg Roach        }
12071378461SGreg Roach
12171378461SGreg Roach        parent::tearDownAfterClass();
12271378461SGreg Roach    }
12371378461SGreg Roach
12471378461SGreg Roach    /**
1256ccdf4f0SGreg Roach     * Create an SQLite in-memory database for testing
1266ccdf4f0SGreg Roach     */
1276ccdf4f0SGreg Roach    protected static function createTestDatabase(): void
1286ccdf4f0SGreg Roach    {
1296ccdf4f0SGreg Roach        $capsule = new DB();
1306ccdf4f0SGreg Roach        $capsule->addConnection([
1316ccdf4f0SGreg Roach            'driver'   => 'sqlite',
1326ccdf4f0SGreg Roach            'database' => ':memory:',
1336ccdf4f0SGreg Roach        ]);
1346ccdf4f0SGreg Roach        $capsule->setAsGlobal();
135e16a1bfdSGreg Roach
1366ccdf4f0SGreg Roach        // Migrations create logs, which requires an IP address, which requires a request
1376ccdf4f0SGreg Roach        self::createRequest();
1386ccdf4f0SGreg Roach
1396ccdf4f0SGreg Roach        // Create tables
1403cfcc809SGreg Roach        $migration_service = new MigrationService();
1416ccdf4f0SGreg Roach        $migration_service->updateSchema('\Fisharebest\Webtrees\Schema', 'WT_SCHEMA_VERSION', Webtrees::SCHEMA_VERSION);
1426ccdf4f0SGreg Roach
1436ccdf4f0SGreg Roach        // Create config data
1446ccdf4f0SGreg Roach        $migration_service->seedDatabase();
1456ccdf4f0SGreg Roach    }
1466ccdf4f0SGreg Roach
1476ccdf4f0SGreg Roach    /**
14857ab2231SGreg Roach     * Create a request and bind it into the container.
14957ab2231SGreg Roach     *
15057ab2231SGreg Roach     * @param string                       $method
15109482a55SGreg Roach     * @param array<string>                $query
15209482a55SGreg Roach     * @param array<string>                $params
15309482a55SGreg Roach     * @param array<UploadedFileInterface> $files
15409482a55SGreg Roach     * @param array<string>                $attributes
15557ab2231SGreg Roach     *
15657ab2231SGreg Roach     * @return ServerRequestInterface
15757ab2231SGreg Roach     */
1581a218474SGreg Roach    protected static function createRequest(
1591a218474SGreg Roach        string $method = RequestMethodInterface::METHOD_GET,
1601a218474SGreg Roach        array $query = [],
1611a218474SGreg Roach        array $params = [],
162b3a775f6SGreg Roach        array $files = [],
163b3a775f6SGreg Roach        array $attributes = []
1641a218474SGreg Roach    ): ServerRequestInterface {
16500c45d23SGreg Roach        /** @var ServerRequestFactoryInterface */
16600c45d23SGreg Roach        $server_request_factory = app(ServerRequestFactoryInterface::class);
16700c45d23SGreg Roach
16857ab2231SGreg Roach        $uri = 'https://webtrees.test/index.php?' . http_build_query($query);
16957ab2231SGreg Roach
17000c45d23SGreg Roach        $request = $server_request_factory
17157ab2231SGreg Roach            ->createServerRequest($method, $uri)
17257ab2231SGreg Roach            ->withQueryParams($query)
17357ab2231SGreg Roach            ->withParsedBody($params)
17457ab2231SGreg Roach            ->withUploadedFiles($files)
17557ab2231SGreg Roach            ->withAttribute('base_url', 'https://webtrees.test')
17690a2f718SGreg Roach            ->withAttribute('client-ip', '127.0.0.1')
177b5f5afdbSGreg Roach            ->withAttribute('user', new GuestUser())
178de2aa325SGreg Roach            ->withAttribute('route', new Route());
179b3a775f6SGreg Roach
180b3a775f6SGreg Roach        foreach ($attributes as $key => $value) {
181b3a775f6SGreg Roach            $request = $request->withAttribute($key, $value);
182b3a775f6SGreg Roach
183b3a775f6SGreg Roach            if ($key === 'tree') {
184b3a775f6SGreg Roach                app()->instance(Tree::class, $value);
185b3a775f6SGreg Roach            }
186b3a775f6SGreg Roach        }
18757ab2231SGreg Roach
18857ab2231SGreg Roach        app()->instance(ServerRequestInterface::class, $request);
18957ab2231SGreg Roach
19057ab2231SGreg Roach        return $request;
19157ab2231SGreg Roach    }
19257ab2231SGreg Roach
19357ab2231SGreg Roach    /**
194061b43d7SGreg Roach     * Things to run before every test.
195061b43d7SGreg Roach     */
1965c48bcd6SGreg Roach    protected function setUp(): void
1970115bc16SGreg Roach    {
1980115bc16SGreg Roach        parent::setUp();
1990115bc16SGreg Roach
200061b43d7SGreg Roach        if (static::$uses_database) {
201061b43d7SGreg Roach            DB::connection()->beginTransaction();
202061b43d7SGreg Roach        }
203061b43d7SGreg Roach    }
204061b43d7SGreg Roach
205061b43d7SGreg Roach    /**
206061b43d7SGreg Roach     * Things to run after every test
207061b43d7SGreg Roach     */
2085e933c21SGreg Roach    protected function tearDown(): void
209a49feabaSGreg Roach    {
21032f20c14SGreg Roach        if (static::$uses_database) {
211061b43d7SGreg Roach            DB::connection()->rollBack();
212061b43d7SGreg Roach        }
21332f20c14SGreg Roach
21432f20c14SGreg Roach        Site::$preferences = [];
21532f20c14SGreg Roach
21632f20c14SGreg Roach        Auth::logout();
2170115bc16SGreg Roach    }
2180115bc16SGreg Roach
2190115bc16SGreg Roach    /**
2200115bc16SGreg Roach     * Import a GEDCOM file into the test database.
2210115bc16SGreg Roach     *
2220115bc16SGreg Roach     * @param string $gedcom_file
223061b43d7SGreg Roach     *
224061b43d7SGreg Roach     * @return Tree
2250115bc16SGreg Roach     */
226061b43d7SGreg Roach    protected function importTree(string $gedcom_file): Tree
2270115bc16SGreg Roach    {
2282c685d76SGreg Roach        $gedcom_import_service = new GedcomImportService();
2292c685d76SGreg Roach        $tree_service          = new TreeService($gedcom_import_service);
2301e653452SGreg Roach        $tree                  = $tree_service->create(basename($gedcom_file), basename($gedcom_file));
23100c45d23SGreg Roach        $stream                = app(StreamFactoryInterface::class)->createStreamFromFile(__DIR__ . '/data/' . $gedcom_file);
2321e653452SGreg Roach
2331c6adce8SGreg Roach        $tree_service->importGedcomFile($tree, $stream, $gedcom_file, '');
2340115bc16SGreg Roach
235c4943cffSGreg Roach        $timeout_service = new TimeoutService();
23610e06497SGreg Roach        $controller      = new GedcomLoad($gedcom_import_service, $timeout_service);
23757ab2231SGreg Roach        $request         = self::createRequest()->withAttribute('tree', $tree);
238126654d7SGreg Roach
239126654d7SGreg Roach        do {
2406fd01894SGreg Roach            $controller->handle($request);
241126654d7SGreg Roach
242126654d7SGreg Roach            $imported = $tree->getPreference('imported');
243126654d7SGreg Roach        } while (!$imported);
244061b43d7SGreg Roach
245061b43d7SGreg Roach        return $tree;
2460115bc16SGreg Roach    }
2476ccdf4f0SGreg Roach
2486ccdf4f0SGreg Roach    /**
2496ccdf4f0SGreg Roach     * Create an uploaded file for a request.
2506ccdf4f0SGreg Roach     *
2516ccdf4f0SGreg Roach     * @param string $filename
2526ccdf4f0SGreg Roach     * @param string $mime_type
2536ccdf4f0SGreg Roach     *
2546ccdf4f0SGreg Roach     * @return UploadedFileInterface
2556ccdf4f0SGreg Roach     */
2566ccdf4f0SGreg Roach    protected function createUploadedFile(string $filename, string $mime_type): UploadedFileInterface
2576ccdf4f0SGreg Roach    {
25800c45d23SGreg Roach        /** @var StreamFactoryInterface */
25900c45d23SGreg Roach        $stream_factory = app(StreamFactoryInterface::class);
26000c45d23SGreg Roach
26100c45d23SGreg Roach        /** @var UploadedFileFactoryInterface */
26200c45d23SGreg Roach        $uploaded_file_factory = app(UploadedFileFactoryInterface::class);
26300c45d23SGreg Roach
26400c45d23SGreg Roach        $stream      = $stream_factory->createStreamFromFile($filename);
2656ccdf4f0SGreg Roach        $size        = filesize($filename);
2666ccdf4f0SGreg Roach        $status      = UPLOAD_ERR_OK;
2676ccdf4f0SGreg Roach        $client_name = basename($filename);
2686ccdf4f0SGreg Roach
26900c45d23SGreg Roach        return $uploaded_file_factory->createUploadedFile($stream, $size, $status, $client_name, $mime_type);
2706ccdf4f0SGreg Roach    }
271d4786c66SGreg Roach
272d4786c66SGreg Roach    /**
273d4786c66SGreg Roach     * Assert that a response contains valid HTML - either a full page or a fragment.
274d4786c66SGreg Roach     *
275d4786c66SGreg Roach     * @param ResponseInterface $response
276d4786c66SGreg Roach     */
277d4786c66SGreg Roach    protected function validateHtmlResponse(ResponseInterface $response): void
278d4786c66SGreg Roach    {
27912b5bef1SGreg Roach        self::assertSame(StatusCodeInterface::STATUS_OK, $response->getStatusCode());
28012b5bef1SGreg Roach
28112b5bef1SGreg Roach        self::assertEquals('text/html; charset=UTF-8', $response->getHeaderLine('content-type'));
282d4786c66SGreg Roach
283d4786c66SGreg Roach        $html = $response->getBody()->getContents();
284d4786c66SGreg Roach
28512b5bef1SGreg Roach        self::assertStringStartsWith('<DOCTYPE html>', $html);
286d4786c66SGreg Roach
287d4786c66SGreg Roach        $this->validateHtml(substr($html, strlen('<DOCTYPE html>')));
288d4786c66SGreg Roach    }
289d4786c66SGreg Roach
290d4786c66SGreg Roach    /**
291d4786c66SGreg Roach     * Assert that a response contains valid HTML - either a full page or a fragment.
292d4786c66SGreg Roach     *
293d4786c66SGreg Roach     * @param string $html
294d4786c66SGreg Roach     */
295d4786c66SGreg Roach    protected function validateHtml(string $html): void
296d4786c66SGreg Roach    {
297d4786c66SGreg Roach        $stack = [];
298d4786c66SGreg Roach
299d4786c66SGreg Roach        do {
300b3027499SJonathan Jaubart            $html = substr($html, strcspn($html, '<>'));
301d4786c66SGreg Roach
302d4786c66SGreg Roach            if (str_starts_with($html, '>')) {
303f01ab4acSGreg Roach                static::fail('Unescaped > found in HTML');
304d4786c66SGreg Roach            }
305d4786c66SGreg Roach
306d4786c66SGreg Roach            if (str_starts_with($html, '<')) {
307d4786c66SGreg Roach                if (preg_match('~^</([a-z]+)>~', $html, $match)) {
308d4786c66SGreg Roach                    if ($match[1] !== array_pop($stack)) {
309f01ab4acSGreg Roach                        static::fail('Closing tag matches nothing: ' . $match[0] . ' at ' . implode(':', $stack));
310d4786c66SGreg Roach                    }
311d4786c66SGreg Roach                    $html = substr($html, strlen($match[0]));
312c3f581d9SGreg Roach                } elseif (preg_match('~^<([a-z]+)(?:\s+[a-z_\-]+="[^">]*")*\s*(/?)>~', $html, $match)) {
313d4786c66SGreg Roach                    $tag = $match[1];
314c3f581d9SGreg Roach                    $self_closing = $match[2] === '/';
315d4786c66SGreg Roach
316d4786c66SGreg Roach                    $message = 'Tag ' . $tag . ' is not allowed at ' . implode(':', $stack) . '.';
317d4786c66SGreg Roach
318d4786c66SGreg Roach                    switch ($tag) {
319d4786c66SGreg Roach                        case 'html':
320f01ab4acSGreg Roach                            static::assertSame([], $stack);
321d4786c66SGreg Roach                            break;
322d4786c66SGreg Roach                        case 'head':
323d4786c66SGreg Roach                        case 'body':
324f01ab4acSGreg Roach                            static::assertSame(['head'], $stack);
325d4786c66SGreg Roach                            break;
326d4786c66SGreg Roach                        case 'div':
327f01ab4acSGreg Roach                            static::assertNotContains('span', $stack, $message);
328d4786c66SGreg Roach                            break;
329d4786c66SGreg Roach                    }
330d4786c66SGreg Roach
331d4786c66SGreg Roach                    if (!$self_closing) {
332d4786c66SGreg Roach                        $stack[] = $tag;
333d4786c66SGreg Roach                    }
334d4786c66SGreg Roach
335b3027499SJonathan Jaubart                    if ($tag === 'script' && !$self_closing) {
336b3027499SJonathan Jaubart                        $html = substr($html, strpos($html, '</script>'));
337b3027499SJonathan Jaubart                    } else {
338d4786c66SGreg Roach                        $html = substr($html, strlen($match[0]));
339b3027499SJonathan Jaubart                    }
340d4786c66SGreg Roach                } else {
341f01ab4acSGreg Roach                    static::fail('Unrecognised tag: ' . substr($html, 0, 40));
342d4786c66SGreg Roach                }
343d4786c66SGreg Roach            }
344d4786c66SGreg Roach        } while ($html !== '');
345d4786c66SGreg Roach
346f01ab4acSGreg Roach        static::assertSame([], $stack);
347d4786c66SGreg Roach    }
348*9aef375dSGreg Roach
349*9aef375dSGreg Roach    /**
350*9aef375dSGreg Roach     * Workaround for removal of withConsecutive in phpunit 10.
351*9aef375dSGreg Roach     *
352*9aef375dSGreg Roach     * @param array<int,mixed> $parameters
353*9aef375dSGreg Roach     *
354*9aef375dSGreg Roach     * @return Callback
355*9aef375dSGreg Roach     */
356*9aef375dSGreg Roach    protected static function withConsecutive(array $parameters): Callback
357*9aef375dSGreg Roach    {
358*9aef375dSGreg Roach        return self::callback(static function (mixed $parameter) use ($parameters): bool {
359*9aef375dSGreg Roach            static $array = null;
360*9aef375dSGreg Roach
361*9aef375dSGreg Roach            $array ??= $parameters;
362*9aef375dSGreg Roach
363*9aef375dSGreg Roach            return $parameter === array_shift($array);
364*9aef375dSGreg Roach        });
365*9aef375dSGreg Roach    }
36684e2cf4eSGreg Roach}
367