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