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