xref: /webtrees/tests/TestCase.php (revision d35568b467207589ea9059739da0bf1f7e785a0d)
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;
369aef375dSGreg Roachuse PHPUnit\Framework\Constraint\Callback;
37d4786c66SGreg Roachuse Psr\Http\Message\ResponseInterface;
3800c45d23SGreg Roachuse Psr\Http\Message\ServerRequestFactoryInterface;
396ccdf4f0SGreg Roachuse Psr\Http\Message\ServerRequestInterface;
406ccdf4f0SGreg Roachuse Psr\Http\Message\StreamFactoryInterface;
416ccdf4f0SGreg Roachuse Psr\Http\Message\UploadedFileFactoryInterface;
426ccdf4f0SGreg Roachuse Psr\Http\Message\UploadedFileInterface;
4371378461SGreg Roach
449aef375dSGreg Roachuse function array_shift;
457def76c7SGreg Roachuse function basename;
466ccdf4f0SGreg Roachuse function filesize;
476ccdf4f0SGreg Roachuse function http_build_query;
48d4786c66SGreg Roachuse function implode;
49d4786c66SGreg Roachuse function preg_match;
50d4786c66SGreg Roachuse function str_starts_with;
51d4786c66SGreg Roachuse function strcspn;
52d4786c66SGreg Roachuse function strlen;
53d4786c66SGreg Roachuse function strpos;
54d4786c66SGreg Roachuse function substr;
55d4786c66SGreg Roach
566ccdf4f0SGreg Roachuse const UPLOAD_ERR_OK;
570115bc16SGreg Roach
5884e2cf4eSGreg Roach/**
5984e2cf4eSGreg Roach * Base class for unit tests
6084e2cf4eSGreg Roach */
6171378461SGreg Roachclass TestCase extends \PHPUnit\Framework\TestCase
6284e2cf4eSGreg Roach{
63cd94ca66SGreg Roach    public static ?object $mock_functions = null;
64cd94ca66SGreg Roach
65cd94ca66SGreg Roach    protected static bool $uses_database = false;
6674d6dc0eSGreg Roach
67061b43d7SGreg Roach    /**
68061b43d7SGreg Roach     * Things to run once, before all the tests.
69061b43d7SGreg Roach     */
705e933c21SGreg Roach    public static function setUpBeforeClass(): void
71061b43d7SGreg Roach    {
72061b43d7SGreg Roach        parent::setUpBeforeClass();
73061b43d7SGreg Roach
74785274b8SGreg Roach        $webtrees = new Webtrees();
75785274b8SGreg Roach        $webtrees->bootstrap();
7600c45d23SGreg Roach
77785274b8SGreg Roach        // This is normally set in middleware.
78*d35568b4SGreg Roach        Registry::container()->set(ModuleThemeInterface::class, new WebtreesTheme());
796ccdf4f0SGreg Roach
80ee4364daSGreg Roach        // Need the routing table, to generate URLs.
812279b4f3SGreg Roach        $router_container = new RouterContainer('/');
822279b4f3SGreg Roach        (new WebRoutes())->load($router_container->getMap());
83*d35568b4SGreg Roach        Registry::container()->set(RouterContainer::class, $router_container);
84ee4364daSGreg Roach
85061b43d7SGreg Roach        if (static::$uses_database) {
86061b43d7SGreg Roach            static::createTestDatabase();
8771378461SGreg Roach
880be3fcd1SJonathan Jaubart            I18N::init('en-US');
890be3fcd1SJonathan Jaubart
9000c92694SGreg Roach            // This is normally set in middleware.
91e669bb4bSGreg Roach            (new Gedcom())->registerTags(Registry::elementFactory(), true);
9200c92694SGreg Roach
9371378461SGreg Roach            // Boot modules
9471378461SGreg Roach            (new ModuleService())->bootModules(new WebtreesTheme());
954a9a6095SGreg Roach        } else {
964a9a6095SGreg Roach            I18N::init('en-US', true);
97061b43d7SGreg Roach        }
98*d35568b4SGreg Roach
99*d35568b4SGreg Roach        self::createRequest();
100061b43d7SGreg Roach    }
101061b43d7SGreg Roach
102061b43d7SGreg Roach    /**
10371378461SGreg Roach     * Things to run once, AFTER all the tests.
10471378461SGreg Roach     */
1055e933c21SGreg Roach    public static function tearDownAfterClass(): void
10671378461SGreg Roach    {
10771378461SGreg Roach        if (static::$uses_database) {
10871378461SGreg Roach            $pdo = DB::connection()->getPdo();
10971378461SGreg Roach            unset($pdo);
11071378461SGreg Roach        }
11171378461SGreg Roach
11271378461SGreg Roach        parent::tearDownAfterClass();
11371378461SGreg Roach    }
11471378461SGreg Roach
11571378461SGreg Roach    /**
1166ccdf4f0SGreg Roach     * Create an SQLite in-memory database for testing
1176ccdf4f0SGreg Roach     */
1186ccdf4f0SGreg Roach    protected static function createTestDatabase(): void
1196ccdf4f0SGreg Roach    {
1206ccdf4f0SGreg Roach        $capsule = new DB();
1216ccdf4f0SGreg Roach        $capsule->addConnection([
1226ccdf4f0SGreg Roach            'driver'   => 'sqlite',
1236ccdf4f0SGreg Roach            'database' => ':memory:',
1246ccdf4f0SGreg Roach        ]);
1256ccdf4f0SGreg Roach        $capsule->setAsGlobal();
126e16a1bfdSGreg Roach
1276ccdf4f0SGreg Roach        // Create tables
1283cfcc809SGreg Roach        $migration_service = new MigrationService();
1296ccdf4f0SGreg Roach        $migration_service->updateSchema('\Fisharebest\Webtrees\Schema', 'WT_SCHEMA_VERSION', Webtrees::SCHEMA_VERSION);
1306ccdf4f0SGreg Roach
1316ccdf4f0SGreg Roach        // Create config data
1326ccdf4f0SGreg Roach        $migration_service->seedDatabase();
1336ccdf4f0SGreg Roach    }
1346ccdf4f0SGreg Roach
1356ccdf4f0SGreg Roach    /**
13657ab2231SGreg Roach     * Create a request and bind it into the container.
13757ab2231SGreg Roach     *
13857ab2231SGreg Roach     * @param string                       $method
13909482a55SGreg Roach     * @param array<string>                $query
14009482a55SGreg Roach     * @param array<string>                $params
14109482a55SGreg Roach     * @param array<UploadedFileInterface> $files
14209482a55SGreg Roach     * @param array<string>                $attributes
14357ab2231SGreg Roach     *
14457ab2231SGreg Roach     * @return ServerRequestInterface
14557ab2231SGreg Roach     */
1461a218474SGreg Roach    protected static function createRequest(
1471a218474SGreg Roach        string $method = RequestMethodInterface::METHOD_GET,
1481a218474SGreg Roach        array $query = [],
1491a218474SGreg Roach        array $params = [],
150b3a775f6SGreg Roach        array $files = [],
151b3a775f6SGreg Roach        array $attributes = []
1521a218474SGreg Roach    ): ServerRequestInterface {
153*d35568b4SGreg Roach        $server_request_factory = Registry::container()->get(ServerRequestFactoryInterface::class);
15400c45d23SGreg Roach
15557ab2231SGreg Roach        $uri = 'https://webtrees.test/index.php?' . http_build_query($query);
15657ab2231SGreg Roach
15700c45d23SGreg Roach        $request = $server_request_factory
15857ab2231SGreg Roach            ->createServerRequest($method, $uri)
15957ab2231SGreg Roach            ->withQueryParams($query)
16057ab2231SGreg Roach            ->withParsedBody($params)
16157ab2231SGreg Roach            ->withUploadedFiles($files)
16257ab2231SGreg Roach            ->withAttribute('base_url', 'https://webtrees.test')
16390a2f718SGreg Roach            ->withAttribute('client-ip', '127.0.0.1')
164b5f5afdbSGreg Roach            ->withAttribute('user', new GuestUser())
165de2aa325SGreg Roach            ->withAttribute('route', new Route());
166b3a775f6SGreg Roach
167b3a775f6SGreg Roach        foreach ($attributes as $key => $value) {
168b3a775f6SGreg Roach            $request = $request->withAttribute($key, $value);
169b3a775f6SGreg Roach
170b3a775f6SGreg Roach            if ($key === 'tree') {
171*d35568b4SGreg Roach                Registry::container()->set(Tree::class, $value);
172b3a775f6SGreg Roach            }
173b3a775f6SGreg Roach        }
17457ab2231SGreg Roach
175*d35568b4SGreg Roach        Registry::container()->set(ServerRequestInterface::class, $request);
17657ab2231SGreg Roach
17757ab2231SGreg Roach        return $request;
17857ab2231SGreg Roach    }
17957ab2231SGreg Roach
18057ab2231SGreg Roach    /**
181061b43d7SGreg Roach     * Things to run before every test.
182061b43d7SGreg Roach     */
1835c48bcd6SGreg Roach    protected function setUp(): void
1840115bc16SGreg Roach    {
1850115bc16SGreg Roach        parent::setUp();
1860115bc16SGreg Roach
187061b43d7SGreg Roach        if (static::$uses_database) {
188061b43d7SGreg Roach            DB::connection()->beginTransaction();
189061b43d7SGreg Roach        }
190061b43d7SGreg Roach    }
191061b43d7SGreg Roach
192061b43d7SGreg Roach    /**
193061b43d7SGreg Roach     * Things to run after every test
194061b43d7SGreg Roach     */
1955e933c21SGreg Roach    protected function tearDown(): void
196a49feabaSGreg Roach    {
19732f20c14SGreg Roach        if (static::$uses_database) {
198061b43d7SGreg Roach            DB::connection()->rollBack();
199061b43d7SGreg Roach        }
20032f20c14SGreg Roach
20132f20c14SGreg Roach        Site::$preferences = [];
20232f20c14SGreg Roach
20332f20c14SGreg Roach        Auth::logout();
2040115bc16SGreg Roach    }
2050115bc16SGreg Roach
2060115bc16SGreg Roach    /**
2070115bc16SGreg Roach     * Import a GEDCOM file into the test database.
2080115bc16SGreg Roach     *
2090115bc16SGreg Roach     * @param string $gedcom_file
210061b43d7SGreg Roach     *
211061b43d7SGreg Roach     * @return Tree
2120115bc16SGreg Roach     */
213061b43d7SGreg Roach    protected function importTree(string $gedcom_file): Tree
2140115bc16SGreg Roach    {
2152c685d76SGreg Roach        $gedcom_import_service = new GedcomImportService();
2162c685d76SGreg Roach        $tree_service          = new TreeService($gedcom_import_service);
2171e653452SGreg Roach        $tree                  = $tree_service->create(basename($gedcom_file), basename($gedcom_file));
218*d35568b4SGreg Roach        $stream                = Registry::container()->get(StreamFactoryInterface::class)->createStreamFromFile(__DIR__ . '/data/' . $gedcom_file);
2191e653452SGreg Roach
2201c6adce8SGreg Roach        $tree_service->importGedcomFile($tree, $stream, $gedcom_file, '');
2210115bc16SGreg Roach
222c4943cffSGreg Roach        $timeout_service = new TimeoutService();
22310e06497SGreg Roach        $controller      = new GedcomLoad($gedcom_import_service, $timeout_service);
22457ab2231SGreg Roach        $request         = self::createRequest()->withAttribute('tree', $tree);
225126654d7SGreg Roach
226126654d7SGreg Roach        do {
2276fd01894SGreg Roach            $controller->handle($request);
228126654d7SGreg Roach
229126654d7SGreg Roach            $imported = $tree->getPreference('imported');
230126654d7SGreg Roach        } while (!$imported);
231061b43d7SGreg Roach
232061b43d7SGreg Roach        return $tree;
2330115bc16SGreg Roach    }
2346ccdf4f0SGreg Roach
2356ccdf4f0SGreg Roach    /**
2366ccdf4f0SGreg Roach     * Create an uploaded file for a request.
2376ccdf4f0SGreg Roach     *
2386ccdf4f0SGreg Roach     * @param string $filename
2396ccdf4f0SGreg Roach     * @param string $mime_type
2406ccdf4f0SGreg Roach     *
2416ccdf4f0SGreg Roach     * @return UploadedFileInterface
2426ccdf4f0SGreg Roach     */
2436ccdf4f0SGreg Roach    protected function createUploadedFile(string $filename, string $mime_type): UploadedFileInterface
2446ccdf4f0SGreg Roach    {
245*d35568b4SGreg Roach        $stream_factory        = Registry::container()->get(StreamFactoryInterface::class);
246*d35568b4SGreg Roach        $uploaded_file_factory = Registry::container()->get(UploadedFileFactoryInterface::class);
24700c45d23SGreg Roach
24800c45d23SGreg Roach        $stream      = $stream_factory->createStreamFromFile($filename);
2496ccdf4f0SGreg Roach        $size        = filesize($filename);
2506ccdf4f0SGreg Roach        $status      = UPLOAD_ERR_OK;
2516ccdf4f0SGreg Roach        $client_name = basename($filename);
2526ccdf4f0SGreg Roach
25300c45d23SGreg Roach        return $uploaded_file_factory->createUploadedFile($stream, $size, $status, $client_name, $mime_type);
2546ccdf4f0SGreg Roach    }
255d4786c66SGreg Roach
256d4786c66SGreg Roach    /**
257d4786c66SGreg Roach     * Assert that a response contains valid HTML - either a full page or a fragment.
258d4786c66SGreg Roach     *
259d4786c66SGreg Roach     * @param ResponseInterface $response
260d4786c66SGreg Roach     */
261d4786c66SGreg Roach    protected function validateHtmlResponse(ResponseInterface $response): void
262d4786c66SGreg Roach    {
26312b5bef1SGreg Roach        self::assertSame(StatusCodeInterface::STATUS_OK, $response->getStatusCode());
26412b5bef1SGreg Roach
26512b5bef1SGreg Roach        self::assertEquals('text/html; charset=UTF-8', $response->getHeaderLine('content-type'));
266d4786c66SGreg Roach
267d4786c66SGreg Roach        $html = $response->getBody()->getContents();
268d4786c66SGreg Roach
26912b5bef1SGreg Roach        self::assertStringStartsWith('<DOCTYPE html>', $html);
270d4786c66SGreg Roach
271d4786c66SGreg Roach        $this->validateHtml(substr($html, strlen('<DOCTYPE html>')));
272d4786c66SGreg Roach    }
273d4786c66SGreg Roach
274d4786c66SGreg Roach    /**
275d4786c66SGreg Roach     * Assert that a response contains valid HTML - either a full page or a fragment.
276d4786c66SGreg Roach     *
277d4786c66SGreg Roach     * @param string $html
278d4786c66SGreg Roach     */
279d4786c66SGreg Roach    protected function validateHtml(string $html): void
280d4786c66SGreg Roach    {
281d4786c66SGreg Roach        $stack = [];
282d4786c66SGreg Roach
283d4786c66SGreg Roach        do {
284b3027499SJonathan Jaubart            $html = substr($html, strcspn($html, '<>'));
285d4786c66SGreg Roach
286d4786c66SGreg Roach            if (str_starts_with($html, '>')) {
287f01ab4acSGreg Roach                static::fail('Unescaped > found in HTML');
288d4786c66SGreg Roach            }
289d4786c66SGreg Roach
290d4786c66SGreg Roach            if (str_starts_with($html, '<')) {
291d4786c66SGreg Roach                if (preg_match('~^</([a-z]+)>~', $html, $match)) {
292d4786c66SGreg Roach                    if ($match[1] !== array_pop($stack)) {
293f01ab4acSGreg Roach                        static::fail('Closing tag matches nothing: ' . $match[0] . ' at ' . implode(':', $stack));
294d4786c66SGreg Roach                    }
295d4786c66SGreg Roach                    $html = substr($html, strlen($match[0]));
296c3f581d9SGreg Roach                } elseif (preg_match('~^<([a-z]+)(?:\s+[a-z_\-]+="[^">]*")*\s*(/?)>~', $html, $match)) {
297d4786c66SGreg Roach                    $tag = $match[1];
298c3f581d9SGreg Roach                    $self_closing = $match[2] === '/';
299d4786c66SGreg Roach
300d4786c66SGreg Roach                    $message = 'Tag ' . $tag . ' is not allowed at ' . implode(':', $stack) . '.';
301d4786c66SGreg Roach
302d4786c66SGreg Roach                    switch ($tag) {
303d4786c66SGreg Roach                        case 'html':
304f01ab4acSGreg Roach                            static::assertSame([], $stack);
305d4786c66SGreg Roach                            break;
306d4786c66SGreg Roach                        case 'head':
307d4786c66SGreg Roach                        case 'body':
308f01ab4acSGreg Roach                            static::assertSame(['head'], $stack);
309d4786c66SGreg Roach                            break;
310d4786c66SGreg Roach                        case 'div':
311f01ab4acSGreg Roach                            static::assertNotContains('span', $stack, $message);
312d4786c66SGreg Roach                            break;
313d4786c66SGreg Roach                    }
314d4786c66SGreg Roach
315d4786c66SGreg Roach                    if (!$self_closing) {
316d4786c66SGreg Roach                        $stack[] = $tag;
317d4786c66SGreg Roach                    }
318d4786c66SGreg Roach
319b3027499SJonathan Jaubart                    if ($tag === 'script' && !$self_closing) {
320b3027499SJonathan Jaubart                        $html = substr($html, strpos($html, '</script>'));
321b3027499SJonathan Jaubart                    } else {
322d4786c66SGreg Roach                        $html = substr($html, strlen($match[0]));
323b3027499SJonathan Jaubart                    }
324d4786c66SGreg Roach                } else {
325f01ab4acSGreg Roach                    static::fail('Unrecognised tag: ' . substr($html, 0, 40));
326d4786c66SGreg Roach                }
327d4786c66SGreg Roach            }
328d4786c66SGreg Roach        } while ($html !== '');
329d4786c66SGreg Roach
330f01ab4acSGreg Roach        static::assertSame([], $stack);
331d4786c66SGreg Roach    }
3329aef375dSGreg Roach
3339aef375dSGreg Roach    /**
3349aef375dSGreg Roach     * Workaround for removal of withConsecutive in phpunit 10.
3359aef375dSGreg Roach     *
3369aef375dSGreg Roach     * @param array<int,mixed> $parameters
3379aef375dSGreg Roach     *
3389aef375dSGreg Roach     * @return Callback
3399aef375dSGreg Roach     */
3409aef375dSGreg Roach    protected static function withConsecutive(array $parameters): Callback
3419aef375dSGreg Roach    {
3429aef375dSGreg Roach        return self::callback(static function (mixed $parameter) use ($parameters): bool {
3439aef375dSGreg Roach            static $array = null;
3449aef375dSGreg Roach
3459aef375dSGreg Roach            $array ??= $parameters;
3469aef375dSGreg Roach
3479aef375dSGreg Roach            return $parameter === array_shift($array);
3489aef375dSGreg Roach        });
3499aef375dSGreg Roach    }
35084e2cf4eSGreg Roach}
351