xref: /webtrees/tests/TestCase.php (revision a26ec5ede3c2ecdb45b783755ede967935aaecba)
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;
359aef375dSGreg Roachuse PHPUnit\Framework\Constraint\Callback;
36d4786c66SGreg 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;
4271378461SGreg Roach
439aef375dSGreg Roachuse function array_shift;
447def76c7SGreg Roachuse function basename;
456ccdf4f0SGreg Roachuse function filesize;
466ccdf4f0SGreg Roachuse function http_build_query;
47d4786c66SGreg Roachuse function implode;
48d4786c66SGreg Roachuse function preg_match;
49d4786c66SGreg Roachuse function str_starts_with;
50d4786c66SGreg Roachuse function strcspn;
51d4786c66SGreg Roachuse function strlen;
52d4786c66SGreg Roachuse function strpos;
53d4786c66SGreg Roachuse function substr;
54d4786c66SGreg Roach
556ccdf4f0SGreg Roachuse const UPLOAD_ERR_OK;
560115bc16SGreg Roach
5784e2cf4eSGreg Roach/**
5884e2cf4eSGreg Roach * Base class for unit tests
5984e2cf4eSGreg Roach */
6071378461SGreg Roachclass TestCase extends \PHPUnit\Framework\TestCase
6184e2cf4eSGreg Roach{
62cd94ca66SGreg Roach    public static ?object $mock_functions = null;
63cd94ca66SGreg Roach
64cd94ca66SGreg Roach    protected static bool $uses_database = false;
6574d6dc0eSGreg Roach
66061b43d7SGreg Roach    /**
676ccdf4f0SGreg Roach     * Create an SQLite in-memory database for testing
686ccdf4f0SGreg Roach     */
69*a26ec5edSGreg Roach    private static function createTestDatabase(): void
706ccdf4f0SGreg Roach    {
716ccdf4f0SGreg Roach        $capsule = new DB();
726ccdf4f0SGreg Roach        $capsule->addConnection([
736ccdf4f0SGreg Roach            'driver'   => 'sqlite',
746ccdf4f0SGreg Roach            'database' => ':memory:',
756ccdf4f0SGreg Roach        ]);
766ccdf4f0SGreg Roach        $capsule->setAsGlobal();
77e16a1bfdSGreg Roach
786ccdf4f0SGreg Roach        // Create tables
793cfcc809SGreg Roach        $migration_service = new MigrationService();
806ccdf4f0SGreg Roach        $migration_service->updateSchema('\Fisharebest\Webtrees\Schema', 'WT_SCHEMA_VERSION', Webtrees::SCHEMA_VERSION);
816ccdf4f0SGreg Roach
826ccdf4f0SGreg Roach        // Create config data
836ccdf4f0SGreg Roach        $migration_service->seedDatabase();
846ccdf4f0SGreg Roach    }
856ccdf4f0SGreg Roach
866ccdf4f0SGreg Roach    /**
8757ab2231SGreg Roach     * Create a request and bind it into the container.
8857ab2231SGreg Roach     *
8957ab2231SGreg Roach     * @param string                       $method
9009482a55SGreg Roach     * @param array<string>                $query
9109482a55SGreg Roach     * @param array<string>                $params
9209482a55SGreg Roach     * @param array<UploadedFileInterface> $files
930acf1b4bSGreg Roach     * @param array<string|Tree>           $attributes
9457ab2231SGreg Roach     *
9557ab2231SGreg Roach     * @return ServerRequestInterface
9657ab2231SGreg Roach     */
971a218474SGreg Roach    protected static function createRequest(
981a218474SGreg Roach        string $method = RequestMethodInterface::METHOD_GET,
991a218474SGreg Roach        array $query = [],
1001a218474SGreg Roach        array $params = [],
101b3a775f6SGreg Roach        array $files = [],
102b3a775f6SGreg Roach        array $attributes = []
1031a218474SGreg Roach    ): ServerRequestInterface {
104d35568b4SGreg Roach        $server_request_factory = Registry::container()->get(ServerRequestFactoryInterface::class);
10500c45d23SGreg Roach
10657ab2231SGreg Roach        $uri = 'https://webtrees.test/index.php?' . http_build_query($query);
10757ab2231SGreg Roach
10800c45d23SGreg Roach        $request = $server_request_factory
10957ab2231SGreg Roach            ->createServerRequest($method, $uri)
11057ab2231SGreg Roach            ->withQueryParams($query)
11157ab2231SGreg Roach            ->withParsedBody($params)
11257ab2231SGreg Roach            ->withUploadedFiles($files)
11357ab2231SGreg Roach            ->withAttribute('base_url', 'https://webtrees.test')
11490a2f718SGreg Roach            ->withAttribute('client-ip', '127.0.0.1')
115b5f5afdbSGreg Roach            ->withAttribute('user', new GuestUser())
116de2aa325SGreg Roach            ->withAttribute('route', new Route());
117b3a775f6SGreg Roach
118b3a775f6SGreg Roach        foreach ($attributes as $key => $value) {
119b3a775f6SGreg Roach            $request = $request->withAttribute($key, $value);
120b3a775f6SGreg Roach
121b3a775f6SGreg Roach            if ($key === 'tree') {
122d35568b4SGreg Roach                Registry::container()->set(Tree::class, $value);
123b3a775f6SGreg Roach            }
124b3a775f6SGreg Roach        }
12557ab2231SGreg Roach
126d35568b4SGreg Roach        Registry::container()->set(ServerRequestInterface::class, $request);
12757ab2231SGreg Roach
12857ab2231SGreg Roach        return $request;
12957ab2231SGreg Roach    }
13057ab2231SGreg Roach
13157ab2231SGreg Roach    /**
132061b43d7SGreg Roach     * Things to run before every test.
133061b43d7SGreg Roach     */
1345c48bcd6SGreg Roach    protected function setUp(): void
1350115bc16SGreg Roach    {
1360115bc16SGreg Roach        parent::setUp();
1370115bc16SGreg Roach
138*a26ec5edSGreg Roach        $webtrees = new Webtrees();
139*a26ec5edSGreg Roach        $webtrees->bootstrap();
140*a26ec5edSGreg Roach
141*a26ec5edSGreg Roach        // This is normally set in middleware.
142*a26ec5edSGreg Roach        Registry::container()->set(ModuleThemeInterface::class, new WebtreesTheme());
143*a26ec5edSGreg Roach
144*a26ec5edSGreg Roach        // Need the routing table, to generate URLs.
145*a26ec5edSGreg Roach        $router_container = new RouterContainer('/');
146*a26ec5edSGreg Roach        (new WebRoutes())->load($router_container->getMap());
147*a26ec5edSGreg Roach        Registry::container()->set(RouterContainer::class, $router_container);
148*a26ec5edSGreg Roach
149061b43d7SGreg Roach        if (static::$uses_database) {
150*a26ec5edSGreg Roach            static::createTestDatabase();
151*a26ec5edSGreg Roach
152*a26ec5edSGreg Roach            // This is normally set in middleware.
153*a26ec5edSGreg Roach            (new Gedcom())->registerTags(Registry::elementFactory(), true);
154*a26ec5edSGreg Roach
155*a26ec5edSGreg Roach            // Boot modules
156*a26ec5edSGreg Roach            (new ModuleService())->bootModules(new WebtreesTheme());
157*a26ec5edSGreg Roach
158*a26ec5edSGreg Roach            I18N::init('en-US');
159*a26ec5edSGreg Roach        } else {
160*a26ec5edSGreg Roach            I18N::init('en-US', true);
161061b43d7SGreg Roach        }
162*a26ec5edSGreg Roach
163*a26ec5edSGreg Roach        self::createRequest();
164061b43d7SGreg Roach    }
165061b43d7SGreg Roach
166061b43d7SGreg Roach    /**
167061b43d7SGreg Roach     * Things to run after every test
168061b43d7SGreg Roach     */
1695e933c21SGreg Roach    protected function tearDown(): void
170a49feabaSGreg Roach    {
17132f20c14SGreg Roach        if (static::$uses_database) {
172*a26ec5edSGreg Roach            DB::connection()->disconnect();
173061b43d7SGreg Roach        }
17432f20c14SGreg Roach
175*a26ec5edSGreg Roach        Session::clear(); // Session data is stored in the super-global
176*a26ec5edSGreg Roach        Site::$preferences = []; // These are cached from the database
1770115bc16SGreg Roach    }
1780115bc16SGreg Roach
179061b43d7SGreg Roach    protected function importTree(string $gedcom_file): Tree
1800115bc16SGreg Roach    {
1812c685d76SGreg Roach        $gedcom_import_service = new GedcomImportService();
1822c685d76SGreg Roach        $tree_service          = new TreeService($gedcom_import_service);
1831e653452SGreg Roach        $tree                  = $tree_service->create(basename($gedcom_file), basename($gedcom_file));
184d35568b4SGreg Roach        $stream                = Registry::container()->get(StreamFactoryInterface::class)->createStreamFromFile(__DIR__ . '/data/' . $gedcom_file);
1851e653452SGreg Roach
1861c6adce8SGreg Roach        $tree_service->importGedcomFile($tree, $stream, $gedcom_file, '');
1870115bc16SGreg Roach
188c4943cffSGreg Roach        $timeout_service = new TimeoutService();
18910e06497SGreg Roach        $controller      = new GedcomLoad($gedcom_import_service, $timeout_service);
19057ab2231SGreg Roach        $request         = self::createRequest()->withAttribute('tree', $tree);
191126654d7SGreg Roach
192126654d7SGreg Roach        do {
1936fd01894SGreg Roach            $controller->handle($request);
194126654d7SGreg Roach
195126654d7SGreg Roach            $imported = $tree->getPreference('imported');
196126654d7SGreg Roach        } while (!$imported);
197061b43d7SGreg Roach
198061b43d7SGreg Roach        return $tree;
1990115bc16SGreg Roach    }
2006ccdf4f0SGreg Roach
2016ccdf4f0SGreg Roach    protected function createUploadedFile(string $filename, string $mime_type): UploadedFileInterface
2026ccdf4f0SGreg Roach    {
203d35568b4SGreg Roach        $stream_factory        = Registry::container()->get(StreamFactoryInterface::class);
204d35568b4SGreg Roach        $uploaded_file_factory = Registry::container()->get(UploadedFileFactoryInterface::class);
20500c45d23SGreg Roach
20600c45d23SGreg Roach        $stream      = $stream_factory->createStreamFromFile($filename);
2076ccdf4f0SGreg Roach        $size        = filesize($filename);
2086ccdf4f0SGreg Roach        $status      = UPLOAD_ERR_OK;
2096ccdf4f0SGreg Roach        $client_name = basename($filename);
2106ccdf4f0SGreg Roach
21100c45d23SGreg Roach        return $uploaded_file_factory->createUploadedFile($stream, $size, $status, $client_name, $mime_type);
2126ccdf4f0SGreg Roach    }
213d4786c66SGreg Roach
214d4786c66SGreg Roach    protected function validateHtmlResponse(ResponseInterface $response): void
215d4786c66SGreg Roach    {
21612b5bef1SGreg Roach        self::assertSame(StatusCodeInterface::STATUS_OK, $response->getStatusCode());
21712b5bef1SGreg Roach
21812b5bef1SGreg Roach        self::assertEquals('text/html; charset=UTF-8', $response->getHeaderLine('content-type'));
219d4786c66SGreg Roach
220d4786c66SGreg Roach        $html = $response->getBody()->getContents();
221d4786c66SGreg Roach
22212b5bef1SGreg Roach        self::assertStringStartsWith('<DOCTYPE html>', $html);
223d4786c66SGreg Roach
224d4786c66SGreg Roach        $this->validateHtml(substr($html, strlen('<DOCTYPE html>')));
225d4786c66SGreg Roach    }
226d4786c66SGreg Roach
227d4786c66SGreg Roach    protected function validateHtml(string $html): void
228d4786c66SGreg Roach    {
229d4786c66SGreg Roach        $stack = [];
230d4786c66SGreg Roach
231d4786c66SGreg Roach        do {
232b3027499SJonathan Jaubart            $html = substr($html, strcspn($html, '<>'));
233d4786c66SGreg Roach
234d4786c66SGreg Roach            if (str_starts_with($html, '>')) {
235f01ab4acSGreg Roach                static::fail('Unescaped > found in HTML');
236d4786c66SGreg Roach            }
237d4786c66SGreg Roach
238d4786c66SGreg Roach            if (str_starts_with($html, '<')) {
239d4786c66SGreg Roach                if (preg_match('~^</([a-z]+)>~', $html, $match)) {
240d4786c66SGreg Roach                    if ($match[1] !== array_pop($stack)) {
241f01ab4acSGreg Roach                        static::fail('Closing tag matches nothing: ' . $match[0] . ' at ' . implode(':', $stack));
242d4786c66SGreg Roach                    }
243d4786c66SGreg Roach                    $html = substr($html, strlen($match[0]));
244c3f581d9SGreg Roach                } elseif (preg_match('~^<([a-z]+)(?:\s+[a-z_\-]+="[^">]*")*\s*(/?)>~', $html, $match)) {
245d4786c66SGreg Roach                    $tag = $match[1];
246c3f581d9SGreg Roach                    $self_closing = $match[2] === '/';
247d4786c66SGreg Roach
248d4786c66SGreg Roach                    $message = 'Tag ' . $tag . ' is not allowed at ' . implode(':', $stack) . '.';
249d4786c66SGreg Roach
250d4786c66SGreg Roach                    switch ($tag) {
251d4786c66SGreg Roach                        case 'html':
252f01ab4acSGreg Roach                            static::assertSame([], $stack);
253d4786c66SGreg Roach                            break;
254d4786c66SGreg Roach                        case 'head':
255d4786c66SGreg Roach                        case 'body':
256f01ab4acSGreg Roach                            static::assertSame(['head'], $stack);
257d4786c66SGreg Roach                            break;
258d4786c66SGreg Roach                        case 'div':
259f01ab4acSGreg Roach                            static::assertNotContains('span', $stack, $message);
260d4786c66SGreg Roach                            break;
261d4786c66SGreg Roach                    }
262d4786c66SGreg Roach
263d4786c66SGreg Roach                    if (!$self_closing) {
264d4786c66SGreg Roach                        $stack[] = $tag;
265d4786c66SGreg Roach                    }
266d4786c66SGreg Roach
267b3027499SJonathan Jaubart                    if ($tag === 'script' && !$self_closing) {
268b3027499SJonathan Jaubart                        $html = substr($html, strpos($html, '</script>'));
269b3027499SJonathan Jaubart                    } else {
270d4786c66SGreg Roach                        $html = substr($html, strlen($match[0]));
271b3027499SJonathan Jaubart                    }
272d4786c66SGreg Roach                } else {
273f01ab4acSGreg Roach                    static::fail('Unrecognised tag: ' . substr($html, 0, 40));
274d4786c66SGreg Roach                }
275d4786c66SGreg Roach            }
276d4786c66SGreg Roach        } while ($html !== '');
277d4786c66SGreg Roach
278f01ab4acSGreg Roach        static::assertSame([], $stack);
279d4786c66SGreg Roach    }
2809aef375dSGreg Roach
2819aef375dSGreg Roach    /**
2829aef375dSGreg Roach     * Workaround for removal of withConsecutive in phpunit 10.
2839aef375dSGreg Roach     *
2849aef375dSGreg Roach     * @param array<int,mixed> $parameters
2859aef375dSGreg Roach     */
2869aef375dSGreg Roach    protected static function withConsecutive(array $parameters): Callback
2879aef375dSGreg Roach    {
2889aef375dSGreg Roach        return self::callback(static function (mixed $parameter) use ($parameters): bool {
2899aef375dSGreg Roach            static $array = null;
2909aef375dSGreg Roach
2919aef375dSGreg Roach            $array ??= $parameters;
2929aef375dSGreg Roach
2939aef375dSGreg Roach            return $parameter === array_shift($array);
2949aef375dSGreg Roach        });
2959aef375dSGreg Roach    }
29684e2cf4eSGreg Roach}
297