xref: /webtrees/tests/TestCase.php (revision 92ae7c02c6f923ea48675d51b7775e5eb9ad559e)
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\Factories\CacheFactory;
26use Fisharebest\Webtrees\Factories\FamilyFactory;
27use Fisharebest\Webtrees\Factories\FilesystemFactory;
28use Fisharebest\Webtrees\Factories\ElementFactory;
29use Fisharebest\Webtrees\Factories\GedcomRecordFactory;
30use Fisharebest\Webtrees\Factories\HeaderFactory;
31use Fisharebest\Webtrees\Factories\IndividualFactory;
32use Fisharebest\Webtrees\Factories\LocationFactory;
33use Fisharebest\Webtrees\Factories\MediaFactory;
34use Fisharebest\Webtrees\Factories\NoteFactory;
35use Fisharebest\Webtrees\Factories\RepositoryFactory;
36use Fisharebest\Webtrees\Factories\SlugFactory;
37use Fisharebest\Webtrees\Factories\SourceFactory;
38use Fisharebest\Webtrees\Factories\SubmissionFactory;
39use Fisharebest\Webtrees\Factories\SubmitterFactory;
40use Fisharebest\Webtrees\Factories\XrefFactory;
41use Fisharebest\Webtrees\Http\RequestHandlers\GedcomLoad;
42use Fisharebest\Webtrees\Http\Routes\WebRoutes;
43use Fisharebest\Webtrees\Module\ModuleThemeInterface;
44use Fisharebest\Webtrees\Module\WebtreesTheme;
45use Fisharebest\Webtrees\Services\MigrationService;
46use Fisharebest\Webtrees\Services\ModuleService;
47use Fisharebest\Webtrees\Services\TimeoutService;
48use Fisharebest\Webtrees\Services\TreeService;
49use Illuminate\Database\Capsule\Manager as DB;
50use Nyholm\Psr7\Factory\Psr17Factory;
51use Psr\Http\Message\ResponseFactoryInterface;
52use Psr\Http\Message\ServerRequestFactoryInterface;
53use Psr\Http\Message\ServerRequestInterface;
54use Psr\Http\Message\StreamFactoryInterface;
55use Psr\Http\Message\UploadedFileFactoryInterface;
56use Psr\Http\Message\UploadedFileInterface;
57use Psr\Http\Message\UriFactoryInterface;
58
59use function app;
60use function basename;
61use function filesize;
62use function http_build_query;
63use function microtime;
64
65use const UPLOAD_ERR_OK;
66
67/**
68 * Base class for unit tests
69 */
70class TestCase extends \PHPUnit\Framework\TestCase
71{
72    /** @var object */
73    public static $mock_functions;
74    /** @var bool */
75    protected static $uses_database = false;
76
77    /**
78     * Things to run once, before all the tests.
79     */
80    public static function setUpBeforeClass(): void
81    {
82        parent::setUpBeforeClass();
83
84        // Use nyholm as our PSR7 factory
85        app()->bind(ResponseFactoryInterface::class, Psr17Factory::class);
86        app()->bind(ServerRequestFactoryInterface::class, Psr17Factory::class);
87        app()->bind(StreamFactoryInterface::class, Psr17Factory::class);
88        app()->bind(UploadedFileFactoryInterface::class, Psr17Factory::class);
89        app()->bind(UriFactoryInterface::class, Psr17Factory::class);
90
91        // Register the factories
92        Registry::cache(new CacheFactory());
93        Registry::familyFactory(new FamilyFactory());
94        Registry::filesystem(new FilesystemFactory());
95        Registry::elementFactory(new ElementFactory());
96        Registry::gedcomRecordFactory(new GedcomRecordFactory());
97        Registry::headerFactory(new HeaderFactory());
98        Registry::individualFactory(new IndividualFactory());
99        Registry::locationFactory(new LocationFactory());
100        Registry::mediaFactory(new MediaFactory());
101        Registry::noteFactory(new NoteFactory());
102        Registry::repositoryFactory(new RepositoryFactory());
103        Registry::slugFactory(new SlugFactory());
104        Registry::sourceFactory(new SourceFactory());
105        Registry::submissionFactory(new SubmissionFactory());
106        Registry::submitterFactory(new SubmitterFactory());
107        Registry::xrefFactory(new XrefFactory());
108
109        app()->bind(ModuleThemeInterface::class, WebtreesTheme::class);
110
111        // Need the routing table, to generate URLs.
112        $router_container = new RouterContainer('/');
113        (new WebRoutes())->load($router_container->getMap());
114        app()->instance(RouterContainer::class, $router_container);
115
116        I18N::init('en-US', true);
117
118        if (static::$uses_database) {
119            static::createTestDatabase();
120
121            // Boot modules
122            (new ModuleService())->bootModules(new WebtreesTheme());
123        }
124    }
125
126    /**
127     * Things to run once, AFTER all the tests.
128     */
129    public static function tearDownAfterClass(): void
130    {
131        if (static::$uses_database) {
132            $pdo = DB::connection()->getPdo();
133            unset($pdo);
134        }
135
136        parent::tearDownAfterClass();
137    }
138
139    /**
140     * Create an SQLite in-memory database for testing
141     */
142    protected static function createTestDatabase(): void
143    {
144        $capsule = new DB();
145        $capsule->addConnection([
146            'driver'   => 'sqlite',
147            'database' => ':memory:',
148        ]);
149        $capsule->setAsGlobal();
150
151        // Migrations create logs, which requires an IP address, which requires a request
152        self::createRequest();
153
154        // Create tables
155        $migration_service = new MigrationService();
156        $migration_service->updateSchema('\Fisharebest\Webtrees\Schema', 'WT_SCHEMA_VERSION', Webtrees::SCHEMA_VERSION);
157
158        // Create config data
159        $migration_service->seedDatabase();
160    }
161
162    /**
163     * Create a request and bind it into the container.
164     *
165     * @param string                  $method
166     * @param string[]                $query
167     * @param string[]                $params
168     * @param UploadedFileInterface[] $files
169     * @param string[]                $attributes
170     *
171     * @return ServerRequestInterface
172     */
173    protected static function createRequest(
174        string $method = RequestMethodInterface::METHOD_GET,
175        array $query = [],
176        array $params = [],
177        array $files = [],
178        array $attributes = []
179    ): ServerRequestInterface {
180        /** @var ServerRequestFactoryInterface */
181        $server_request_factory = app(ServerRequestFactoryInterface::class);
182
183        $uri = 'https://webtrees.test/index.php?' . http_build_query($query);
184
185        /** @var ServerRequestInterface $request */
186        $request = $server_request_factory
187            ->createServerRequest($method, $uri)
188            ->withQueryParams($query)
189            ->withParsedBody($params)
190            ->withUploadedFiles($files)
191            ->withAttribute('base_url', 'https://webtrees.test')
192            ->withAttribute('client-ip', '127.0.0.1')
193            ->withAttribute('user', new GuestUser())
194            ->withAttribute('route', new Route());
195
196        foreach ($attributes as $key => $value) {
197            $request = $request->withAttribute($key, $value);
198
199            if ($key === 'tree') {
200                app()->instance(Tree::class, $value);
201            }
202        }
203
204        app()->instance(ServerRequestInterface::class, $request);
205
206        return $request;
207    }
208
209    /**
210     * Things to run before every test.
211     */
212    protected function setUp(): void
213    {
214        parent::setUp();
215
216        if (static::$uses_database) {
217            DB::connection()->beginTransaction();
218        }
219    }
220
221    /**
222     * Things to run after every test
223     */
224    protected function tearDown(): void
225    {
226        if (static::$uses_database) {
227            DB::connection()->rollBack();
228        }
229
230        Site::$preferences = [];
231
232        Auth::logout();
233    }
234
235    /**
236     * Import a GEDCOM file into the test database.
237     *
238     * @param string $gedcom_file
239     *
240     * @return Tree
241     */
242    protected function importTree(string $gedcom_file): Tree
243    {
244        $tree_service = new TreeService();
245        $tree         = $tree_service->create(basename($gedcom_file), basename($gedcom_file));
246        $stream       = app(StreamFactoryInterface::class)->createStreamFromFile(__DIR__ . '/data/' . $gedcom_file);
247
248        $tree_service->importGedcomFile($tree, $stream, $gedcom_file);
249
250        $timeout_service = new TimeoutService(microtime(true));
251        $controller      = new GedcomLoad($timeout_service, $tree_service);
252        $request         = self::createRequest()->withAttribute('tree', $tree);
253
254        do {
255            $controller->handle($request);
256
257            $imported = $tree->getPreference('imported');
258        } while (!$imported);
259
260        return $tree;
261    }
262
263    /**
264     * Create an uploaded file for a request.
265     *
266     * @param string $filename
267     * @param string $mime_type
268     *
269     * @return UploadedFileInterface
270     */
271    protected function createUploadedFile(string $filename, string $mime_type): UploadedFileInterface
272    {
273        /** @var StreamFactoryInterface */
274        $stream_factory = app(StreamFactoryInterface::class);
275
276        /** @var UploadedFileFactoryInterface */
277        $uploaded_file_factory = app(UploadedFileFactoryInterface::class);
278
279        $stream      = $stream_factory->createStreamFromFile($filename);
280        $size        = filesize($filename);
281        $status      = UPLOAD_ERR_OK;
282        $client_name = basename($filename);
283
284        return $uploaded_file_factory->createUploadedFile($stream, $size, $status, $client_name, $mime_type);
285    }
286}
287