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