xref: /webtrees/tests/TestCase.php (revision d4786c66945cca20d5ce34ac3cf08cf5a5110ae2)
184e2cf4eSGreg Roach<?php
23cfcc809SGreg Roach
384e2cf4eSGreg Roach/**
484e2cf4eSGreg Roach * webtrees: online genealogy
589f7189bSGreg Roach * Copyright (C) 2021 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;
256fd01894SGreg Roachuse Fisharebest\Webtrees\Http\RequestHandlers\GedcomLoad;
262279b4f3SGreg Roachuse Fisharebest\Webtrees\Http\Routes\WebRoutes;
278136679eSGreg Roachuse Fisharebest\Webtrees\Module\ModuleThemeInterface;
288136679eSGreg Roachuse Fisharebest\Webtrees\Module\WebtreesTheme;
298c3e1068SGreg Roachuse Fisharebest\Webtrees\Services\MigrationService;
3071378461SGreg Roachuse Fisharebest\Webtrees\Services\ModuleService;
31126654d7SGreg Roachuse Fisharebest\Webtrees\Services\TimeoutService;
321e653452SGreg Roachuse Fisharebest\Webtrees\Services\TreeService;
330115bc16SGreg Roachuse Illuminate\Database\Capsule\Manager as DB;
3400c45d23SGreg Roachuse Nyholm\Psr7\Factory\Psr17Factory;
3500c45d23SGreg Roachuse Psr\Http\Message\ResponseFactoryInterface;
36*d4786c66SGreg Roachuse Psr\Http\Message\ResponseInterface;
3700c45d23SGreg Roachuse Psr\Http\Message\ServerRequestFactoryInterface;
386ccdf4f0SGreg Roachuse Psr\Http\Message\ServerRequestInterface;
396ccdf4f0SGreg Roachuse Psr\Http\Message\StreamFactoryInterface;
406ccdf4f0SGreg Roachuse Psr\Http\Message\UploadedFileFactoryInterface;
416ccdf4f0SGreg Roachuse Psr\Http\Message\UploadedFileInterface;
4200c45d23SGreg Roachuse Psr\Http\Message\UriFactoryInterface;
4371378461SGreg Roach
446ccdf4f0SGreg Roachuse function app;
457def76c7SGreg Roachuse function basename;
466ccdf4f0SGreg Roachuse function filesize;
476ccdf4f0SGreg Roachuse function http_build_query;
48*d4786c66SGreg Roachuse function implode;
49*d4786c66SGreg Roachuse function preg_match;
50*d4786c66SGreg Roachuse function str_contains;
51*d4786c66SGreg Roachuse function str_starts_with;
52*d4786c66SGreg Roachuse function strcspn;
53*d4786c66SGreg Roachuse function strlen;
54*d4786c66SGreg Roachuse function strpos;
55*d4786c66SGreg Roachuse function substr;
56*d4786c66SGreg Roach
57*d4786c66SGreg Roachuse function var_dump;
5871378461SGreg Roach
596ccdf4f0SGreg Roachuse const UPLOAD_ERR_OK;
600115bc16SGreg Roach
6184e2cf4eSGreg Roach/**
6284e2cf4eSGreg Roach * Base class for unit tests
6384e2cf4eSGreg Roach */
6471378461SGreg Roachclass TestCase extends \PHPUnit\Framework\TestCase
6584e2cf4eSGreg Roach{
6674d6dc0eSGreg Roach    /** @var object */
6774d6dc0eSGreg Roach    public static $mock_functions;
6857ab2231SGreg Roach    /** @var bool */
6957ab2231SGreg Roach    protected static $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
96150f35adSGreg Roach        I18N::init('en-US', true);
976ccdf4f0SGreg Roach
98061b43d7SGreg Roach        if (static::$uses_database) {
99061b43d7SGreg Roach            static::createTestDatabase();
10071378461SGreg Roach
10171378461SGreg Roach            // Boot modules
10271378461SGreg Roach            (new ModuleService())->bootModules(new WebtreesTheme());
103061b43d7SGreg Roach        }
104061b43d7SGreg Roach    }
105061b43d7SGreg Roach
106061b43d7SGreg Roach    /**
10771378461SGreg Roach     * Things to run once, AFTER all the tests.
10871378461SGreg Roach     */
1095e933c21SGreg Roach    public static function tearDownAfterClass(): void
11071378461SGreg Roach    {
11171378461SGreg Roach        if (static::$uses_database) {
11271378461SGreg Roach            $pdo = DB::connection()->getPdo();
11371378461SGreg Roach            unset($pdo);
11471378461SGreg Roach        }
11571378461SGreg Roach
11671378461SGreg Roach        parent::tearDownAfterClass();
11771378461SGreg Roach    }
11871378461SGreg Roach
11971378461SGreg Roach    /**
1206ccdf4f0SGreg Roach     * Create an SQLite in-memory database for testing
1216ccdf4f0SGreg Roach     */
1226ccdf4f0SGreg Roach    protected static function createTestDatabase(): void
1236ccdf4f0SGreg Roach    {
1246ccdf4f0SGreg Roach        $capsule = new DB();
1256ccdf4f0SGreg Roach        $capsule->addConnection([
1266ccdf4f0SGreg Roach            'driver'   => 'sqlite',
1276ccdf4f0SGreg Roach            'database' => ':memory:',
1286ccdf4f0SGreg Roach        ]);
1296ccdf4f0SGreg Roach        $capsule->setAsGlobal();
130e16a1bfdSGreg Roach
1316ccdf4f0SGreg Roach        // Migrations create logs, which requires an IP address, which requires a request
1326ccdf4f0SGreg Roach        self::createRequest();
1336ccdf4f0SGreg Roach
1346ccdf4f0SGreg Roach        // Create tables
1353cfcc809SGreg Roach        $migration_service = new MigrationService();
1366ccdf4f0SGreg Roach        $migration_service->updateSchema('\Fisharebest\Webtrees\Schema', 'WT_SCHEMA_VERSION', Webtrees::SCHEMA_VERSION);
1376ccdf4f0SGreg Roach
1386ccdf4f0SGreg Roach        // Create config data
1396ccdf4f0SGreg Roach        $migration_service->seedDatabase();
1406ccdf4f0SGreg Roach    }
1416ccdf4f0SGreg Roach
1426ccdf4f0SGreg Roach    /**
14357ab2231SGreg Roach     * Create a request and bind it into the container.
14457ab2231SGreg Roach     *
14557ab2231SGreg Roach     * @param string                  $method
14657ab2231SGreg Roach     * @param string[]                $query
14757ab2231SGreg Roach     * @param string[]                $params
14857ab2231SGreg Roach     * @param UploadedFileInterface[] $files
149b3a775f6SGreg Roach     * @param string[]                $attributes
15057ab2231SGreg Roach     *
15157ab2231SGreg Roach     * @return ServerRequestInterface
15257ab2231SGreg Roach     */
1531a218474SGreg Roach    protected static function createRequest(
1541a218474SGreg Roach        string $method = RequestMethodInterface::METHOD_GET,
1551a218474SGreg Roach        array $query = [],
1561a218474SGreg Roach        array $params = [],
157b3a775f6SGreg Roach        array $files = [],
158b3a775f6SGreg Roach        array $attributes = []
1591a218474SGreg Roach    ): ServerRequestInterface {
16000c45d23SGreg Roach        /** @var ServerRequestFactoryInterface */
16100c45d23SGreg Roach        $server_request_factory = app(ServerRequestFactoryInterface::class);
16200c45d23SGreg Roach
16357ab2231SGreg Roach        $uri = 'https://webtrees.test/index.php?' . http_build_query($query);
16457ab2231SGreg Roach
16500c45d23SGreg Roach        /** @var ServerRequestInterface $request */
16600c45d23SGreg Roach        $request = $server_request_factory
16757ab2231SGreg Roach            ->createServerRequest($method, $uri)
16857ab2231SGreg Roach            ->withQueryParams($query)
16957ab2231SGreg Roach            ->withParsedBody($params)
17057ab2231SGreg Roach            ->withUploadedFiles($files)
17157ab2231SGreg Roach            ->withAttribute('base_url', 'https://webtrees.test')
17290a2f718SGreg Roach            ->withAttribute('client-ip', '127.0.0.1')
173b5f5afdbSGreg Roach            ->withAttribute('user', new GuestUser())
174de2aa325SGreg Roach            ->withAttribute('route', new Route());
175b3a775f6SGreg Roach
176b3a775f6SGreg Roach        foreach ($attributes as $key => $value) {
177b3a775f6SGreg Roach            $request = $request->withAttribute($key, $value);
178b3a775f6SGreg Roach
179b3a775f6SGreg Roach            if ($key === 'tree') {
180b3a775f6SGreg Roach                app()->instance(Tree::class, $value);
181b3a775f6SGreg Roach            }
182b3a775f6SGreg Roach        }
18357ab2231SGreg Roach
18457ab2231SGreg Roach        app()->instance(ServerRequestInterface::class, $request);
18557ab2231SGreg Roach
18657ab2231SGreg Roach        return $request;
18757ab2231SGreg Roach    }
18857ab2231SGreg Roach
18957ab2231SGreg Roach    /**
190061b43d7SGreg Roach     * Things to run before every test.
191061b43d7SGreg Roach     */
1925c48bcd6SGreg Roach    protected function setUp(): void
1930115bc16SGreg Roach    {
1940115bc16SGreg Roach        parent::setUp();
1950115bc16SGreg Roach
196061b43d7SGreg Roach        if (static::$uses_database) {
197061b43d7SGreg Roach            DB::connection()->beginTransaction();
198061b43d7SGreg Roach        }
199061b43d7SGreg Roach    }
200061b43d7SGreg Roach
201061b43d7SGreg Roach    /**
202061b43d7SGreg Roach     * Things to run after every test
203061b43d7SGreg Roach     */
2045e933c21SGreg Roach    protected function tearDown(): void
205a49feabaSGreg Roach    {
20632f20c14SGreg Roach        if (static::$uses_database) {
207061b43d7SGreg Roach            DB::connection()->rollBack();
208061b43d7SGreg Roach        }
20932f20c14SGreg Roach
21032f20c14SGreg Roach        Site::$preferences = [];
21132f20c14SGreg Roach
21232f20c14SGreg Roach        Auth::logout();
2130115bc16SGreg Roach    }
2140115bc16SGreg Roach
2150115bc16SGreg Roach    /**
2160115bc16SGreg Roach     * Import a GEDCOM file into the test database.
2170115bc16SGreg Roach     *
2180115bc16SGreg Roach     * @param string $gedcom_file
219061b43d7SGreg Roach     *
220061b43d7SGreg Roach     * @return Tree
2210115bc16SGreg Roach     */
222061b43d7SGreg Roach    protected function importTree(string $gedcom_file): Tree
2230115bc16SGreg Roach    {
2241e653452SGreg Roach        $tree_service = new TreeService();
2251e653452SGreg Roach        $tree         = $tree_service->create(basename($gedcom_file), basename($gedcom_file));
22600c45d23SGreg Roach        $stream       = app(StreamFactoryInterface::class)->createStreamFromFile(__DIR__ . '/data/' . $gedcom_file);
2271e653452SGreg Roach
2285cd281f4SGreg Roach        $tree_service->importGedcomFile($tree, $stream, $gedcom_file);
2290115bc16SGreg Roach
230c4943cffSGreg Roach        $timeout_service = new TimeoutService();
2315cd281f4SGreg Roach        $controller      = new GedcomLoad($timeout_service, $tree_service);
23257ab2231SGreg Roach        $request         = self::createRequest()->withAttribute('tree', $tree);
233126654d7SGreg Roach
234126654d7SGreg Roach        do {
2356fd01894SGreg Roach            $controller->handle($request);
236126654d7SGreg Roach
237126654d7SGreg Roach            $imported = $tree->getPreference('imported');
238126654d7SGreg Roach        } while (!$imported);
239061b43d7SGreg Roach
240061b43d7SGreg Roach        return $tree;
2410115bc16SGreg Roach    }
2426ccdf4f0SGreg Roach
2436ccdf4f0SGreg Roach    /**
2446ccdf4f0SGreg Roach     * Create an uploaded file for a request.
2456ccdf4f0SGreg Roach     *
2466ccdf4f0SGreg Roach     * @param string $filename
2476ccdf4f0SGreg Roach     * @param string $mime_type
2486ccdf4f0SGreg Roach     *
2496ccdf4f0SGreg Roach     * @return UploadedFileInterface
2506ccdf4f0SGreg Roach     */
2516ccdf4f0SGreg Roach    protected function createUploadedFile(string $filename, string $mime_type): UploadedFileInterface
2526ccdf4f0SGreg Roach    {
25300c45d23SGreg Roach        /** @var StreamFactoryInterface */
25400c45d23SGreg Roach        $stream_factory = app(StreamFactoryInterface::class);
25500c45d23SGreg Roach
25600c45d23SGreg Roach        /** @var UploadedFileFactoryInterface */
25700c45d23SGreg Roach        $uploaded_file_factory = app(UploadedFileFactoryInterface::class);
25800c45d23SGreg Roach
25900c45d23SGreg Roach        $stream      = $stream_factory->createStreamFromFile($filename);
2606ccdf4f0SGreg Roach        $size        = filesize($filename);
2616ccdf4f0SGreg Roach        $status      = UPLOAD_ERR_OK;
2626ccdf4f0SGreg Roach        $client_name = basename($filename);
2636ccdf4f0SGreg Roach
26400c45d23SGreg Roach        return $uploaded_file_factory->createUploadedFile($stream, $size, $status, $client_name, $mime_type);
2656ccdf4f0SGreg Roach    }
266*d4786c66SGreg Roach
267*d4786c66SGreg Roach    /**
268*d4786c66SGreg Roach     * Assert that a response contains valid HTML - either a full page or a fragment.
269*d4786c66SGreg Roach     *
270*d4786c66SGreg Roach     * @param ResponseInterface $response
271*d4786c66SGreg Roach     */
272*d4786c66SGreg Roach    protected function validateHtmlResponse(ResponseInterface $response): void
273*d4786c66SGreg Roach    {
274*d4786c66SGreg Roach        $this->assertEquals('text/html; charsert=utf8', $response->getHeaderLine('content-type'));
275*d4786c66SGreg Roach
276*d4786c66SGreg Roach        $html = $response->getBody()->getContents();
277*d4786c66SGreg Roach
278*d4786c66SGreg Roach        $this->assertStringStartsWith('<DOCTYPE html>', $html);
279*d4786c66SGreg Roach
280*d4786c66SGreg Roach        $this->validateHtml(substr($html, strlen('<DOCTYPE html>')));
281*d4786c66SGreg Roach
282*d4786c66SGreg Roach    }
283*d4786c66SGreg Roach
284*d4786c66SGreg Roach    /**
285*d4786c66SGreg Roach     * Assert that a response contains valid HTML - either a full page or a fragment.
286*d4786c66SGreg Roach     *
287*d4786c66SGreg Roach     * @param string $html
288*d4786c66SGreg Roach     */
289*d4786c66SGreg Roach    protected function validateHtml(string $html): void
290*d4786c66SGreg Roach    {
291*d4786c66SGreg Roach        $stack = [];
292*d4786c66SGreg Roach
293*d4786c66SGreg Roach        do {
294*d4786c66SGreg Roach            $html = substr($html, 0, strcspn($html, '<>'));
295*d4786c66SGreg Roach
296*d4786c66SGreg Roach            if (str_starts_with($html, '>')) {
297*d4786c66SGreg Roach                $this->fail('Unescaped > found in HTML');
298*d4786c66SGreg Roach            }
299*d4786c66SGreg Roach
300*d4786c66SGreg Roach            if (str_starts_with($html, '<')) {
301*d4786c66SGreg Roach                if (preg_match('~^</([a-z]+)>~', $html, $match)) {
302*d4786c66SGreg Roach                    if ($match[1] !== array_pop($stack)) {
303*d4786c66SGreg Roach                        $this->fail('Closing tag matches nothing: ' . $match[0] . ' at ' . implode(':', $stack));
304*d4786c66SGreg Roach                    }
305*d4786c66SGreg Roach                    $html = substr($html, strlen($match[0]));
306*d4786c66SGreg Roach                } elseif (preg_match('~^<([a-z]+)(?:\s*="[^">]*")*\s*(/)?>~', $html, $match)) {
307*d4786c66SGreg Roach                    $tag = $match[1];
308*d4786c66SGreg Roach                    $self_closing = $match[2] === '/';
309*d4786c66SGreg Roach
310*d4786c66SGreg Roach                    $message = 'Tag ' . $tag . ' is not allowed at ' . implode(':', $stack) . '.';
311*d4786c66SGreg Roach
312*d4786c66SGreg Roach                    switch ($tag) {
313*d4786c66SGreg Roach                        case 'html':
314*d4786c66SGreg Roach                            $this->assertSame([], $stack);
315*d4786c66SGreg Roach                            break;
316*d4786c66SGreg Roach                        case 'head':
317*d4786c66SGreg Roach                        case 'body':
318*d4786c66SGreg Roach                            $this->assertSame(['head'], $stack);
319*d4786c66SGreg Roach                            break;
320*d4786c66SGreg Roach                        case 'div':
321*d4786c66SGreg Roach                            $this->assertNotContains('span', $stack, $message);
322*d4786c66SGreg Roach                            break;
323*d4786c66SGreg Roach                    }
324*d4786c66SGreg Roach
325*d4786c66SGreg Roach                    if (!$self_closing) {
326*d4786c66SGreg Roach                        $stack[] = $tag;
327*d4786c66SGreg Roach                    }
328*d4786c66SGreg Roach
329*d4786c66SGreg Roach                    $html = substr($html, strlen($match[0]));
330*d4786c66SGreg Roach                } else {
331*d4786c66SGreg Roach                    $this->fail('Unrecognised tag: ' . substr($html, 0, 40));
332*d4786c66SGreg Roach                }
333*d4786c66SGreg Roach            }
334*d4786c66SGreg Roach        } while ($html !== '');
335*d4786c66SGreg Roach
336*d4786c66SGreg Roach        $this->assertSame([], $stack);
337*d4786c66SGreg Roach
338*d4786c66SGreg Roach    }
33984e2cf4eSGreg Roach}
340