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