xref: /webtrees/tests/TestCase.php (revision 6f4ec3cadc983f0a7294108c634bef48846b4311)
1<?php
2
3/**
4 * webtrees: online genealogy
5 * Copyright (C) 2023 webtrees development team
6 * This program is free software: you can redistribute it and/or modify
7 * it under the terms of the GNU General Public License as published by
8 * the Free Software Foundation, either version 3 of the License, or
9 * (at your option) any later version.
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
14 * You should have received a copy of the GNU General Public License
15 * along with this program. If not, see <https://www.gnu.org/licenses/>.
16 */
17
18declare(strict_types=1);
19
20namespace Fisharebest\Webtrees;
21
22use Aura\Router\Route;
23use Aura\Router\RouterContainer;
24use Fig\Http\Message\RequestMethodInterface;
25use Fig\Http\Message\StatusCodeInterface;
26use Fisharebest\Webtrees\Http\RequestHandlers\GedcomLoad;
27use Fisharebest\Webtrees\Http\Routes\WebRoutes;
28use Fisharebest\Webtrees\Module\ModuleThemeInterface;
29use Fisharebest\Webtrees\Module\WebtreesTheme;
30use Fisharebest\Webtrees\Services\GedcomImportService;
31use Fisharebest\Webtrees\Services\MigrationService;
32use Fisharebest\Webtrees\Services\ModuleService;
33use Fisharebest\Webtrees\Services\TimeoutService;
34use Fisharebest\Webtrees\Services\TreeService;
35use PHPUnit\Framework\Constraint\Callback;
36use Psr\Http\Message\ResponseInterface;
37use Psr\Http\Message\ServerRequestFactoryInterface;
38use Psr\Http\Message\ServerRequestInterface;
39use Psr\Http\Message\StreamFactoryInterface;
40use Psr\Http\Message\UploadedFileFactoryInterface;
41use Psr\Http\Message\UploadedFileInterface;
42
43use function array_shift;
44use function basename;
45use function filesize;
46use function http_build_query;
47use function implode;
48use function preg_match;
49use function str_starts_with;
50use function strcspn;
51use function strlen;
52use function strpos;
53use function substr;
54
55use const UPLOAD_ERR_OK;
56
57/**
58 * Base class for unit tests
59 */
60class TestCase extends \PHPUnit\Framework\TestCase
61{
62    public static ?object $mock_functions = null;
63
64    protected static bool $uses_database = false;
65
66    /**
67     * Things to run once, before all the tests.
68     */
69    public static function setUpBeforeClass(): void
70    {
71        parent::setUpBeforeClass();
72
73        $webtrees = new Webtrees();
74        $webtrees->bootstrap();
75
76        // This is normally set in middleware.
77        Registry::container()->set(ModuleThemeInterface::class, new WebtreesTheme());
78
79        // Need the routing table, to generate URLs.
80        $router_container = new RouterContainer('/');
81        (new WebRoutes())->load($router_container->getMap());
82        Registry::container()->set(RouterContainer::class, $router_container);
83
84        if (static::$uses_database) {
85            static::createTestDatabase();
86
87            I18N::init('en-US');
88
89            // This is normally set in middleware.
90            (new Gedcom())->registerTags(Registry::elementFactory(), true);
91
92            // Boot modules
93            (new ModuleService())->bootModules(new WebtreesTheme());
94        } else {
95            I18N::init('en-US', true);
96        }
97
98        self::createRequest();
99    }
100
101    /**
102     * Things to run once, AFTER all the tests.
103     */
104    public static function tearDownAfterClass(): void
105    {
106        if (static::$uses_database) {
107            $pdo = DB::connection()->getPdo();
108            unset($pdo);
109        }
110
111        parent::tearDownAfterClass();
112    }
113
114    /**
115     * Create an SQLite in-memory database for testing
116     */
117    protected static function createTestDatabase(): void
118    {
119        $capsule = new DB();
120        $capsule->addConnection([
121            'driver'   => 'sqlite',
122            'database' => ':memory:',
123        ]);
124        $capsule->setAsGlobal();
125
126        // Create tables
127        $migration_service = new MigrationService();
128        $migration_service->updateSchema('\Fisharebest\Webtrees\Schema', 'WT_SCHEMA_VERSION', Webtrees::SCHEMA_VERSION);
129
130        // Create config data
131        $migration_service->seedDatabase();
132    }
133
134    /**
135     * Create a request and bind it into the container.
136     *
137     * @param string                       $method
138     * @param array<string>                $query
139     * @param array<string>                $params
140     * @param array<UploadedFileInterface> $files
141     * @param array<string|Tree>           $attributes
142     *
143     * @return ServerRequestInterface
144     */
145    protected static function createRequest(
146        string $method = RequestMethodInterface::METHOD_GET,
147        array $query = [],
148        array $params = [],
149        array $files = [],
150        array $attributes = []
151    ): ServerRequestInterface {
152        $server_request_factory = Registry::container()->get(ServerRequestFactoryInterface::class);
153
154        $uri = 'https://webtrees.test/index.php?' . http_build_query($query);
155
156        $request = $server_request_factory
157            ->createServerRequest($method, $uri)
158            ->withQueryParams($query)
159            ->withParsedBody($params)
160            ->withUploadedFiles($files)
161            ->withAttribute('base_url', 'https://webtrees.test')
162            ->withAttribute('client-ip', '127.0.0.1')
163            ->withAttribute('user', new GuestUser())
164            ->withAttribute('route', new Route());
165
166        foreach ($attributes as $key => $value) {
167            $request = $request->withAttribute($key, $value);
168
169            if ($key === 'tree') {
170                Registry::container()->set(Tree::class, $value);
171            }
172        }
173
174        Registry::container()->set(ServerRequestInterface::class, $request);
175
176        return $request;
177    }
178
179    /**
180     * Things to run before every test.
181     */
182    protected function setUp(): void
183    {
184        parent::setUp();
185
186        if (static::$uses_database) {
187            DB::connection()->beginTransaction();
188        }
189    }
190
191    /**
192     * Things to run after every test
193     */
194    protected function tearDown(): void
195    {
196        if (static::$uses_database) {
197            DB::connection()->rollBack();
198        }
199
200        Site::$preferences = [];
201
202        Auth::logout();
203    }
204
205    /**
206     * Import a GEDCOM file into the test database.
207     *
208     * @param string $gedcom_file
209     *
210     * @return Tree
211     */
212    protected function importTree(string $gedcom_file): Tree
213    {
214        $gedcom_import_service = new GedcomImportService();
215        $tree_service          = new TreeService($gedcom_import_service);
216        $tree                  = $tree_service->create(basename($gedcom_file), basename($gedcom_file));
217        $stream                = Registry::container()->get(StreamFactoryInterface::class)->createStreamFromFile(__DIR__ . '/data/' . $gedcom_file);
218
219        $tree_service->importGedcomFile($tree, $stream, $gedcom_file, '');
220
221        $timeout_service = new TimeoutService();
222        $controller      = new GedcomLoad($gedcom_import_service, $timeout_service);
223        $request         = self::createRequest()->withAttribute('tree', $tree);
224
225        do {
226            $controller->handle($request);
227
228            $imported = $tree->getPreference('imported');
229        } while (!$imported);
230
231        return $tree;
232    }
233
234    /**
235     * Create an uploaded file for a request.
236     *
237     * @param string $filename
238     * @param string $mime_type
239     *
240     * @return UploadedFileInterface
241     */
242    protected function createUploadedFile(string $filename, string $mime_type): UploadedFileInterface
243    {
244        $stream_factory        = Registry::container()->get(StreamFactoryInterface::class);
245        $uploaded_file_factory = Registry::container()->get(UploadedFileFactoryInterface::class);
246
247        $stream      = $stream_factory->createStreamFromFile($filename);
248        $size        = filesize($filename);
249        $status      = UPLOAD_ERR_OK;
250        $client_name = basename($filename);
251
252        return $uploaded_file_factory->createUploadedFile($stream, $size, $status, $client_name, $mime_type);
253    }
254
255    /**
256     * Assert that a response contains valid HTML - either a full page or a fragment.
257     *
258     * @param ResponseInterface $response
259     */
260    protected function validateHtmlResponse(ResponseInterface $response): void
261    {
262        self::assertSame(StatusCodeInterface::STATUS_OK, $response->getStatusCode());
263
264        self::assertEquals('text/html; charset=UTF-8', $response->getHeaderLine('content-type'));
265
266        $html = $response->getBody()->getContents();
267
268        self::assertStringStartsWith('<DOCTYPE html>', $html);
269
270        $this->validateHtml(substr($html, strlen('<DOCTYPE html>')));
271    }
272
273    /**
274     * Assert that a response contains valid HTML - either a full page or a fragment.
275     *
276     * @param string $html
277     */
278    protected function validateHtml(string $html): void
279    {
280        $stack = [];
281
282        do {
283            $html = substr($html, strcspn($html, '<>'));
284
285            if (str_starts_with($html, '>')) {
286                static::fail('Unescaped > found in HTML');
287            }
288
289            if (str_starts_with($html, '<')) {
290                if (preg_match('~^</([a-z]+)>~', $html, $match)) {
291                    if ($match[1] !== array_pop($stack)) {
292                        static::fail('Closing tag matches nothing: ' . $match[0] . ' at ' . implode(':', $stack));
293                    }
294                    $html = substr($html, strlen($match[0]));
295                } elseif (preg_match('~^<([a-z]+)(?:\s+[a-z_\-]+="[^">]*")*\s*(/?)>~', $html, $match)) {
296                    $tag = $match[1];
297                    $self_closing = $match[2] === '/';
298
299                    $message = 'Tag ' . $tag . ' is not allowed at ' . implode(':', $stack) . '.';
300
301                    switch ($tag) {
302                        case 'html':
303                            static::assertSame([], $stack);
304                            break;
305                        case 'head':
306                        case 'body':
307                            static::assertSame(['head'], $stack);
308                            break;
309                        case 'div':
310                            static::assertNotContains('span', $stack, $message);
311                            break;
312                    }
313
314                    if (!$self_closing) {
315                        $stack[] = $tag;
316                    }
317
318                    if ($tag === 'script' && !$self_closing) {
319                        $html = substr($html, strpos($html, '</script>'));
320                    } else {
321                        $html = substr($html, strlen($match[0]));
322                    }
323                } else {
324                    static::fail('Unrecognised tag: ' . substr($html, 0, 40));
325                }
326            }
327        } while ($html !== '');
328
329        static::assertSame([], $stack);
330    }
331
332    /**
333     * Workaround for removal of withConsecutive in phpunit 10.
334     *
335     * @param array<int,mixed> $parameters
336     *
337     * @return Callback
338     */
339    protected static function withConsecutive(array $parameters): Callback
340    {
341        return self::callback(static function (mixed $parameter) use ($parameters): bool {
342            static $array = null;
343
344            $array ??= $parameters;
345
346            return $parameter === array_shift($array);
347        });
348    }
349}
350