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