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