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