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