xref: /webtrees/tests/TestCase.php (revision 12b5bef18374d0f646b8a7dd78cab23b03bc953e)
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;
25*12b5bef1SGreg 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;
308c3e1068SGreg Roachuse Fisharebest\Webtrees\Services\MigrationService;
3171378461SGreg Roachuse Fisharebest\Webtrees\Services\ModuleService;
32126654d7SGreg Roachuse Fisharebest\Webtrees\Services\TimeoutService;
331e653452SGreg Roachuse Fisharebest\Webtrees\Services\TreeService;
340115bc16SGreg Roachuse Illuminate\Database\Capsule\Manager as DB;
3500c45d23SGreg Roachuse Nyholm\Psr7\Factory\Psr17Factory;
3600c45d23SGreg Roachuse Psr\Http\Message\ResponseFactoryInterface;
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;
4300c45d23SGreg Roachuse Psr\Http\Message\UriFactoryInterface;
4471378461SGreg Roach
456ccdf4f0SGreg Roachuse function app;
467def76c7SGreg Roachuse function basename;
476ccdf4f0SGreg Roachuse function filesize;
486ccdf4f0SGreg Roachuse function http_build_query;
49d4786c66SGreg Roachuse function implode;
50d4786c66SGreg Roachuse function preg_match;
51d4786c66SGreg Roachuse function str_starts_with;
52d4786c66SGreg Roachuse function strcspn;
53d4786c66SGreg Roachuse function strlen;
54d4786c66SGreg Roachuse function strpos;
55d4786c66SGreg Roachuse function substr;
56d4786c66SGreg Roach
576ccdf4f0SGreg Roachuse const UPLOAD_ERR_OK;
580115bc16SGreg Roach
5984e2cf4eSGreg Roach/**
6084e2cf4eSGreg Roach * Base class for unit tests
6184e2cf4eSGreg Roach */
6271378461SGreg Roachclass TestCase extends \PHPUnit\Framework\TestCase
6384e2cf4eSGreg Roach{
6474d6dc0eSGreg Roach    /** @var object */
6574d6dc0eSGreg Roach    public static $mock_functions;
6657ab2231SGreg Roach    /** @var bool */
6757ab2231SGreg Roach    protected static $uses_database = false;
6874d6dc0eSGreg Roach
69061b43d7SGreg Roach    /**
70061b43d7SGreg Roach     * Things to run once, before all the tests.
71061b43d7SGreg Roach     */
725e933c21SGreg Roach    public static function setUpBeforeClass(): void
73061b43d7SGreg Roach    {
74061b43d7SGreg Roach        parent::setUpBeforeClass();
75061b43d7SGreg Roach
76785274b8SGreg Roach        $webtrees = new Webtrees();
77785274b8SGreg Roach        $webtrees->bootstrap();
7800c45d23SGreg Roach
79785274b8SGreg Roach        // PSR7 messages and PSR17 message-factories
80785274b8SGreg Roach        Webtrees::set(ResponseFactoryInterface::class, Psr17Factory::class);
81785274b8SGreg Roach        Webtrees::set(ServerRequestFactoryInterface::class, Psr17Factory::class);
82785274b8SGreg Roach        Webtrees::set(StreamFactoryInterface::class, Psr17Factory::class);
83785274b8SGreg Roach        Webtrees::set(UploadedFileFactoryInterface::class, Psr17Factory::class);
84785274b8SGreg Roach        Webtrees::set(UriFactoryInterface::class, Psr17Factory::class);
856ccdf4f0SGreg Roach
86785274b8SGreg Roach        // This is normally set in middleware.
87785274b8SGreg Roach        Webtrees::set(ModuleThemeInterface::class, WebtreesTheme::class);
886ccdf4f0SGreg Roach
89ee4364daSGreg Roach        // Need the routing table, to generate URLs.
902279b4f3SGreg Roach        $router_container = new RouterContainer('/');
912279b4f3SGreg Roach        (new WebRoutes())->load($router_container->getMap());
92785274b8SGreg Roach        Webtrees::set(RouterContainer::class, $router_container);
93ee4364daSGreg Roach
94150f35adSGreg Roach        I18N::init('en-US', true);
956ccdf4f0SGreg Roach
96061b43d7SGreg Roach        if (static::$uses_database) {
97061b43d7SGreg Roach            static::createTestDatabase();
9871378461SGreg Roach
9971378461SGreg Roach            // Boot modules
10071378461SGreg Roach            (new ModuleService())->bootModules(new WebtreesTheme());
101061b43d7SGreg Roach        }
102061b43d7SGreg Roach    }
103061b43d7SGreg Roach
104061b43d7SGreg Roach    /**
10571378461SGreg Roach     * Things to run once, AFTER all the tests.
10671378461SGreg Roach     */
1075e933c21SGreg Roach    public static function tearDownAfterClass(): void
10871378461SGreg Roach    {
10971378461SGreg Roach        if (static::$uses_database) {
11071378461SGreg Roach            $pdo = DB::connection()->getPdo();
11171378461SGreg Roach            unset($pdo);
11271378461SGreg Roach        }
11371378461SGreg Roach
11471378461SGreg Roach        parent::tearDownAfterClass();
11571378461SGreg Roach    }
11671378461SGreg Roach
11771378461SGreg Roach    /**
1186ccdf4f0SGreg Roach     * Create an SQLite in-memory database for testing
1196ccdf4f0SGreg Roach     */
1206ccdf4f0SGreg Roach    protected static function createTestDatabase(): void
1216ccdf4f0SGreg Roach    {
1226ccdf4f0SGreg Roach        $capsule = new DB();
1236ccdf4f0SGreg Roach        $capsule->addConnection([
1246ccdf4f0SGreg Roach            'driver'   => 'sqlite',
1256ccdf4f0SGreg Roach            'database' => ':memory:',
1266ccdf4f0SGreg Roach        ]);
1276ccdf4f0SGreg Roach        $capsule->setAsGlobal();
128e16a1bfdSGreg Roach
1296ccdf4f0SGreg Roach        // Migrations create logs, which requires an IP address, which requires a request
1306ccdf4f0SGreg Roach        self::createRequest();
1316ccdf4f0SGreg Roach
1326ccdf4f0SGreg Roach        // Create tables
1333cfcc809SGreg Roach        $migration_service = new MigrationService();
1346ccdf4f0SGreg Roach        $migration_service->updateSchema('\Fisharebest\Webtrees\Schema', 'WT_SCHEMA_VERSION', Webtrees::SCHEMA_VERSION);
1356ccdf4f0SGreg Roach
1366ccdf4f0SGreg Roach        // Create config data
1376ccdf4f0SGreg Roach        $migration_service->seedDatabase();
1386ccdf4f0SGreg Roach    }
1396ccdf4f0SGreg Roach
1406ccdf4f0SGreg Roach    /**
14157ab2231SGreg Roach     * Create a request and bind it into the container.
14257ab2231SGreg Roach     *
14357ab2231SGreg Roach     * @param string                  $method
14457ab2231SGreg Roach     * @param string[]                $query
14557ab2231SGreg Roach     * @param string[]                $params
14657ab2231SGreg Roach     * @param UploadedFileInterface[] $files
147b3a775f6SGreg Roach     * @param string[]                $attributes
14857ab2231SGreg Roach     *
14957ab2231SGreg Roach     * @return ServerRequestInterface
15057ab2231SGreg Roach     */
1511a218474SGreg Roach    protected static function createRequest(
1521a218474SGreg Roach        string $method = RequestMethodInterface::METHOD_GET,
1531a218474SGreg Roach        array $query = [],
1541a218474SGreg Roach        array $params = [],
155b3a775f6SGreg Roach        array $files = [],
156b3a775f6SGreg Roach        array $attributes = []
1571a218474SGreg Roach    ): ServerRequestInterface {
15800c45d23SGreg Roach        /** @var ServerRequestFactoryInterface */
15900c45d23SGreg Roach        $server_request_factory = app(ServerRequestFactoryInterface::class);
16000c45d23SGreg Roach
16157ab2231SGreg Roach        $uri = 'https://webtrees.test/index.php?' . http_build_query($query);
16257ab2231SGreg Roach
16300c45d23SGreg Roach        /** @var ServerRequestInterface $request */
16400c45d23SGreg Roach        $request = $server_request_factory
16557ab2231SGreg Roach            ->createServerRequest($method, $uri)
16657ab2231SGreg Roach            ->withQueryParams($query)
16757ab2231SGreg Roach            ->withParsedBody($params)
16857ab2231SGreg Roach            ->withUploadedFiles($files)
16957ab2231SGreg Roach            ->withAttribute('base_url', 'https://webtrees.test')
17090a2f718SGreg Roach            ->withAttribute('client-ip', '127.0.0.1')
171b5f5afdbSGreg Roach            ->withAttribute('user', new GuestUser())
172de2aa325SGreg Roach            ->withAttribute('route', new Route());
173b3a775f6SGreg Roach
174b3a775f6SGreg Roach        foreach ($attributes as $key => $value) {
175b3a775f6SGreg Roach            $request = $request->withAttribute($key, $value);
176b3a775f6SGreg Roach
177b3a775f6SGreg Roach            if ($key === 'tree') {
178b3a775f6SGreg Roach                app()->instance(Tree::class, $value);
179b3a775f6SGreg Roach            }
180b3a775f6SGreg Roach        }
18157ab2231SGreg Roach
18257ab2231SGreg Roach        app()->instance(ServerRequestInterface::class, $request);
18357ab2231SGreg Roach
18457ab2231SGreg Roach        return $request;
18557ab2231SGreg Roach    }
18657ab2231SGreg Roach
18757ab2231SGreg Roach    /**
188061b43d7SGreg Roach     * Things to run before every test.
189061b43d7SGreg Roach     */
1905c48bcd6SGreg Roach    protected function setUp(): void
1910115bc16SGreg Roach    {
1920115bc16SGreg Roach        parent::setUp();
1930115bc16SGreg Roach
194061b43d7SGreg Roach        if (static::$uses_database) {
195061b43d7SGreg Roach            DB::connection()->beginTransaction();
196061b43d7SGreg Roach        }
197061b43d7SGreg Roach    }
198061b43d7SGreg Roach
199061b43d7SGreg Roach    /**
200061b43d7SGreg Roach     * Things to run after every test
201061b43d7SGreg Roach     */
2025e933c21SGreg Roach    protected function tearDown(): void
203a49feabaSGreg Roach    {
20432f20c14SGreg Roach        if (static::$uses_database) {
205061b43d7SGreg Roach            DB::connection()->rollBack();
206061b43d7SGreg Roach        }
20732f20c14SGreg Roach
20832f20c14SGreg Roach        Site::$preferences = [];
20932f20c14SGreg Roach
21032f20c14SGreg Roach        Auth::logout();
2110115bc16SGreg Roach    }
2120115bc16SGreg Roach
2130115bc16SGreg Roach    /**
2140115bc16SGreg Roach     * Import a GEDCOM file into the test database.
2150115bc16SGreg Roach     *
2160115bc16SGreg Roach     * @param string $gedcom_file
217061b43d7SGreg Roach     *
218061b43d7SGreg Roach     * @return Tree
2190115bc16SGreg Roach     */
220061b43d7SGreg Roach    protected function importTree(string $gedcom_file): Tree
2210115bc16SGreg Roach    {
2221e653452SGreg Roach        $tree_service = new TreeService();
2231e653452SGreg Roach        $tree         = $tree_service->create(basename($gedcom_file), basename($gedcom_file));
22400c45d23SGreg Roach        $stream       = app(StreamFactoryInterface::class)->createStreamFromFile(__DIR__ . '/data/' . $gedcom_file);
2251e653452SGreg Roach
2265cd281f4SGreg Roach        $tree_service->importGedcomFile($tree, $stream, $gedcom_file);
2270115bc16SGreg Roach
228c4943cffSGreg Roach        $timeout_service = new TimeoutService();
2295cd281f4SGreg Roach        $controller      = new GedcomLoad($timeout_service, $tree_service);
23057ab2231SGreg Roach        $request         = self::createRequest()->withAttribute('tree', $tree);
231126654d7SGreg Roach
232126654d7SGreg Roach        do {
2336fd01894SGreg Roach            $controller->handle($request);
234126654d7SGreg Roach
235126654d7SGreg Roach            $imported = $tree->getPreference('imported');
236126654d7SGreg Roach        } while (!$imported);
237061b43d7SGreg Roach
238061b43d7SGreg Roach        return $tree;
2390115bc16SGreg Roach    }
2406ccdf4f0SGreg Roach
2416ccdf4f0SGreg Roach    /**
2426ccdf4f0SGreg Roach     * Create an uploaded file for a request.
2436ccdf4f0SGreg Roach     *
2446ccdf4f0SGreg Roach     * @param string $filename
2456ccdf4f0SGreg Roach     * @param string $mime_type
2466ccdf4f0SGreg Roach     *
2476ccdf4f0SGreg Roach     * @return UploadedFileInterface
2486ccdf4f0SGreg Roach     */
2496ccdf4f0SGreg Roach    protected function createUploadedFile(string $filename, string $mime_type): UploadedFileInterface
2506ccdf4f0SGreg Roach    {
25100c45d23SGreg Roach        /** @var StreamFactoryInterface */
25200c45d23SGreg Roach        $stream_factory = app(StreamFactoryInterface::class);
25300c45d23SGreg Roach
25400c45d23SGreg Roach        /** @var UploadedFileFactoryInterface */
25500c45d23SGreg Roach        $uploaded_file_factory = app(UploadedFileFactoryInterface::class);
25600c45d23SGreg Roach
25700c45d23SGreg Roach        $stream      = $stream_factory->createStreamFromFile($filename);
2586ccdf4f0SGreg Roach        $size        = filesize($filename);
2596ccdf4f0SGreg Roach        $status      = UPLOAD_ERR_OK;
2606ccdf4f0SGreg Roach        $client_name = basename($filename);
2616ccdf4f0SGreg Roach
26200c45d23SGreg Roach        return $uploaded_file_factory->createUploadedFile($stream, $size, $status, $client_name, $mime_type);
2636ccdf4f0SGreg Roach    }
264d4786c66SGreg Roach
265d4786c66SGreg Roach    /**
266d4786c66SGreg Roach     * Assert that a response contains valid HTML - either a full page or a fragment.
267d4786c66SGreg Roach     *
268d4786c66SGreg Roach     * @param ResponseInterface $response
269d4786c66SGreg Roach     */
270d4786c66SGreg Roach    protected function validateHtmlResponse(ResponseInterface $response): void
271d4786c66SGreg Roach    {
272*12b5bef1SGreg Roach        self::assertSame(StatusCodeInterface::STATUS_OK, $response->getStatusCode());
273*12b5bef1SGreg Roach
274*12b5bef1SGreg Roach        self::assertEquals('text/html; charset=UTF-8', $response->getHeaderLine('content-type'));
275d4786c66SGreg Roach
276d4786c66SGreg Roach        $html = $response->getBody()->getContents();
277d4786c66SGreg Roach
278*12b5bef1SGreg Roach        self::assertStringStartsWith('<DOCTYPE html>', $html);
279d4786c66SGreg Roach
280d4786c66SGreg Roach        $this->validateHtml(substr($html, strlen('<DOCTYPE html>')));
281d4786c66SGreg Roach    }
282d4786c66SGreg Roach
283d4786c66SGreg Roach    /**
284d4786c66SGreg Roach     * Assert that a response contains valid HTML - either a full page or a fragment.
285d4786c66SGreg Roach     *
286d4786c66SGreg Roach     * @param string $html
287d4786c66SGreg Roach     */
288d4786c66SGreg Roach    protected function validateHtml(string $html): void
289d4786c66SGreg Roach    {
290d4786c66SGreg Roach        $stack = [];
291d4786c66SGreg Roach
292d4786c66SGreg Roach        do {
293b3027499SJonathan Jaubart            $html = substr($html, strcspn($html, '<>'));
294d4786c66SGreg Roach
295d4786c66SGreg Roach            if (str_starts_with($html, '>')) {
296d4786c66SGreg Roach                $this->fail('Unescaped > found in HTML');
297d4786c66SGreg Roach            }
298d4786c66SGreg Roach
299d4786c66SGreg Roach            if (str_starts_with($html, '<')) {
300d4786c66SGreg Roach                if (preg_match('~^</([a-z]+)>~', $html, $match)) {
301d4786c66SGreg Roach                    if ($match[1] !== array_pop($stack)) {
302d4786c66SGreg Roach                        $this->fail('Closing tag matches nothing: ' . $match[0] . ' at ' . implode(':', $stack));
303d4786c66SGreg Roach                    }
304d4786c66SGreg Roach                    $html = substr($html, strlen($match[0]));
305c3f581d9SGreg Roach                } elseif (preg_match('~^<([a-z]+)(?:\s+[a-z_\-]+="[^">]*")*\s*(/?)>~', $html, $match)) {
306d4786c66SGreg Roach                    $tag = $match[1];
307c3f581d9SGreg Roach                    $self_closing = $match[2] === '/';
308d4786c66SGreg Roach
309d4786c66SGreg Roach                    $message = 'Tag ' . $tag . ' is not allowed at ' . implode(':', $stack) . '.';
310d4786c66SGreg Roach
311d4786c66SGreg Roach                    switch ($tag) {
312d4786c66SGreg Roach                        case 'html':
313d4786c66SGreg Roach                            $this->assertSame([], $stack);
314d4786c66SGreg Roach                            break;
315d4786c66SGreg Roach                        case 'head':
316d4786c66SGreg Roach                        case 'body':
317d4786c66SGreg Roach                            $this->assertSame(['head'], $stack);
318d4786c66SGreg Roach                            break;
319d4786c66SGreg Roach                        case 'div':
320d4786c66SGreg Roach                            $this->assertNotContains('span', $stack, $message);
321d4786c66SGreg Roach                            break;
322d4786c66SGreg Roach                    }
323d4786c66SGreg Roach
324d4786c66SGreg Roach                    if (!$self_closing) {
325d4786c66SGreg Roach                        $stack[] = $tag;
326d4786c66SGreg Roach                    }
327d4786c66SGreg Roach
328b3027499SJonathan Jaubart                    if ($tag === 'script' && !$self_closing) {
329b3027499SJonathan Jaubart                        $html = substr($html, strpos($html, '</script>'));
330b3027499SJonathan Jaubart                    } else {
331d4786c66SGreg Roach                        $html = substr($html, strlen($match[0]));
332b3027499SJonathan Jaubart                    }
333d4786c66SGreg Roach                } else {
334d4786c66SGreg Roach                    $this->fail('Unrecognised tag: ' . substr($html, 0, 40));
335d4786c66SGreg Roach                }
336d4786c66SGreg Roach            }
337d4786c66SGreg Roach        } while ($html !== '');
338d4786c66SGreg Roach
339d4786c66SGreg Roach        $this->assertSame([], $stack);
340d4786c66SGreg Roach    }
34184e2cf4eSGreg Roach}
342