xref: /webtrees/tests/TestCase.php (revision 449b311ecf65f677a2595e1e29f712d11ef22f34)
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
57class TestCase extends \PHPUnit\Framework\TestCase
58{
59    public static ?object $mock_functions = null;
60
61    protected static bool $uses_database = false;
62
63    /**
64     * Create an SQLite in-memory database for testing
65     */
66    private static function createTestDatabase(): void
67    {
68        $capsule = new DB();
69        $capsule->addConnection([
70            'driver'   => 'sqlite',
71            'database' => ':memory:',
72        ]);
73        $capsule->setAsGlobal();
74
75        // Create tables
76        $migration_service = new MigrationService();
77        $migration_service->updateSchema('\Fisharebest\Webtrees\Schema', 'WT_SCHEMA_VERSION', Webtrees::SCHEMA_VERSION);
78
79        // Create config data
80        $migration_service->seedDatabase();
81    }
82
83    /**
84     * Create a request and bind it into the container.
85     *
86     * @param array<string>                $query
87     * @param array<string>                $params
88     * @param array<UploadedFileInterface> $files
89     * @param array<string|Tree>           $attributes
90     */
91    protected static function createRequest(
92        string $method = RequestMethodInterface::METHOD_GET,
93        array $query = [],
94        array $params = [],
95        array $files = [],
96        array $attributes = []
97    ): ServerRequestInterface {
98        $server_request_factory = Registry::container()->get(ServerRequestFactoryInterface::class);
99
100        $uri = 'https://webtrees.test/index.php?' . http_build_query($query);
101
102        $request = $server_request_factory
103            ->createServerRequest($method, $uri)
104            ->withQueryParams($query)
105            ->withParsedBody($params)
106            ->withUploadedFiles($files)
107            ->withAttribute('base_url', 'https://webtrees.test')
108            ->withAttribute('client-ip', '127.0.0.1')
109            ->withAttribute('user', new GuestUser())
110            ->withAttribute('route', new Route());
111
112        foreach ($attributes as $key => $value) {
113            $request = $request->withAttribute($key, $value);
114
115            if ($key === 'tree') {
116                Registry::container()->set(Tree::class, $value);
117            }
118        }
119
120        Registry::container()->set(ServerRequestInterface::class, $request);
121
122        return $request;
123    }
124
125    /**
126     * Things to run before every test.
127     */
128    protected function setUp(): void
129    {
130        parent::setUp();
131
132        $webtrees = new Webtrees();
133        $webtrees->bootstrap();
134
135        // This is normally set in middleware.
136        Registry::container()->set(ModuleThemeInterface::class, new WebtreesTheme());
137
138        // Need the routing table, to generate URLs.
139        $router_container = new RouterContainer('/');
140        (new WebRoutes())->load($router_container->getMap());
141        Registry::container()->set(RouterContainer::class, $router_container);
142
143        if (static::$uses_database) {
144            self::createTestDatabase();
145
146            // This is normally set in middleware.
147            (new Gedcom())->registerTags(Registry::elementFactory(), true);
148
149            // Boot modules
150            (new ModuleService())->bootModules(new WebtreesTheme());
151
152            I18N::init('en-US');
153        } else {
154            I18N::init('en-US', true);
155        }
156
157        self::createRequest();
158    }
159
160    /**
161     * Things to run after every test
162     */
163    protected function tearDown(): void
164    {
165        if (static::$uses_database) {
166            DB::connection()->disconnect();
167        }
168
169        Session::clear(); // Session data is stored in the super-global
170        Site::$preferences = []; // These are cached from the database
171    }
172
173    protected function importTree(string $gedcom_file): Tree
174    {
175        $gedcom_import_service = new GedcomImportService();
176        $tree_service          = new TreeService($gedcom_import_service);
177        $tree                  = $tree_service->create(basename($gedcom_file), basename($gedcom_file));
178        $stream                = Registry::container()->get(StreamFactoryInterface::class)->createStreamFromFile(__DIR__ . '/data/' . $gedcom_file);
179
180        $tree_service->importGedcomFile($tree, $stream, $gedcom_file, '');
181
182        $timeout_service = new TimeoutService();
183        $controller      = new GedcomLoad($gedcom_import_service, $timeout_service);
184        $request         = self::createRequest()->withAttribute('tree', $tree);
185
186        do {
187            $controller->handle($request);
188
189            $imported = $tree->getPreference('imported');
190        } while (!$imported);
191
192        return $tree;
193    }
194
195    protected function createUploadedFile(string $filename, string $mime_type): UploadedFileInterface
196    {
197        $stream_factory        = Registry::container()->get(StreamFactoryInterface::class);
198        $uploaded_file_factory = Registry::container()->get(UploadedFileFactoryInterface::class);
199
200        $stream      = $stream_factory->createStreamFromFile($filename);
201        $size        = filesize($filename);
202        $status      = UPLOAD_ERR_OK;
203        $client_name = basename($filename);
204
205        return $uploaded_file_factory->createUploadedFile($stream, $size, $status, $client_name, $mime_type);
206    }
207
208    protected function validateHtmlResponse(ResponseInterface $response): void
209    {
210        self::assertSame(StatusCodeInterface::STATUS_OK, $response->getStatusCode());
211
212        self::assertEquals('text/html; charset=UTF-8', $response->getHeaderLine('content-type'));
213
214        $html = $response->getBody()->getContents();
215
216        self::assertStringStartsWith('<DOCTYPE html>', $html);
217
218        $this->validateHtml(substr($html, strlen('<DOCTYPE html>')));
219    }
220
221    protected function validateHtml(string $html): void
222    {
223        $stack = [];
224
225        do {
226            $html = substr($html, strcspn($html, '<>'));
227
228            if (str_starts_with($html, '>')) {
229                static::fail('Unescaped > found in HTML');
230            }
231
232            if (str_starts_with($html, '<')) {
233                if (preg_match('~^</([a-z]+)>~', $html, $match)) {
234                    if ($match[1] !== array_pop($stack)) {
235                        static::fail('Closing tag matches nothing: ' . $match[0] . ' at ' . implode(':', $stack));
236                    }
237                    $html = substr($html, strlen($match[0]));
238                } elseif (preg_match('~^<([a-z]+)(?:\s+[a-z_\-]+="[^">]*")*\s*(/?)>~', $html, $match)) {
239                    $tag = $match[1];
240                    $self_closing = $match[2] === '/';
241
242                    $message = 'Tag ' . $tag . ' is not allowed at ' . implode(':', $stack) . '.';
243
244                    switch ($tag) {
245                        case 'html':
246                            static::assertSame([], $stack);
247                            break;
248                        case 'head':
249                        case 'body':
250                            static::assertSame(['head'], $stack);
251                            break;
252                        case 'div':
253                            static::assertNotContains('span', $stack, $message);
254                            break;
255                    }
256
257                    if (!$self_closing) {
258                        $stack[] = $tag;
259                    }
260
261                    if ($tag === 'script' && !$self_closing) {
262                        $html = substr($html, strpos($html, '</script>'));
263                    } else {
264                        $html = substr($html, strlen($match[0]));
265                    }
266                } else {
267                    static::fail('Unrecognised tag: ' . substr($html, 0, 40));
268                }
269            }
270        } while ($html !== '');
271
272        static::assertSame([], $stack);
273    }
274
275    /**
276     * Workaround for removal of withConsecutive in phpunit 10.
277     *
278     * @param array<int,mixed> $parameters
279     */
280    protected static function withConsecutive(array $parameters): Callback
281    {
282        return self::callback(static function (mixed $parameter) use ($parameters): bool {
283            static $array = null;
284
285            $array ??= $parameters;
286
287            return $parameter === array_shift($array);
288        });
289    }
290}
291