xref: /webtrees/tests/TestCase.php (revision eef4add847fc196987084a36c42787ff20f8ca19)
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        $webtrees = new Webtrees();
85        $webtrees->bootstrap();
86
87        // PSR7 messages and PSR17 message-factories
88        Webtrees::set(ResponseFactoryInterface::class, Psr17Factory::class);
89        Webtrees::set(ServerRequestFactoryInterface::class, Psr17Factory::class);
90        Webtrees::set(StreamFactoryInterface::class, Psr17Factory::class);
91        Webtrees::set(UploadedFileFactoryInterface::class, Psr17Factory::class);
92        Webtrees::set(UriFactoryInterface::class, Psr17Factory::class);
93
94        // This is normally set in middleware.
95        Webtrees::set(ModuleThemeInterface::class, WebtreesTheme::class);
96
97        // Need the routing table, to generate URLs.
98        $router_container = new RouterContainer('/');
99        (new WebRoutes())->load($router_container->getMap());
100        Webtrees::set(RouterContainer::class, $router_container);
101
102        I18N::init('en-US', true);
103
104        if (static::$uses_database) {
105            static::createTestDatabase();
106
107            // Boot modules
108            (new ModuleService())->bootModules(new WebtreesTheme());
109        }
110    }
111
112    /**
113     * Things to run once, AFTER all the tests.
114     */
115    public static function tearDownAfterClass(): void
116    {
117        if (static::$uses_database) {
118            $pdo = DB::connection()->getPdo();
119            unset($pdo);
120        }
121
122        parent::tearDownAfterClass();
123    }
124
125    /**
126     * Create an SQLite in-memory database for testing
127     */
128    protected static function createTestDatabase(): void
129    {
130        $capsule = new DB();
131        $capsule->addConnection([
132            'driver'   => 'sqlite',
133            'database' => ':memory:',
134        ]);
135        $capsule->setAsGlobal();
136
137        // Migrations create logs, which requires an IP address, which requires a request
138        self::createRequest();
139
140        // Create tables
141        $migration_service = new MigrationService();
142        $migration_service->updateSchema('\Fisharebest\Webtrees\Schema', 'WT_SCHEMA_VERSION', Webtrees::SCHEMA_VERSION);
143
144        // Create config data
145        $migration_service->seedDatabase();
146    }
147
148    /**
149     * Create a request and bind it into the container.
150     *
151     * @param string                  $method
152     * @param string[]                $query
153     * @param string[]                $params
154     * @param UploadedFileInterface[] $files
155     * @param string[]                $attributes
156     *
157     * @return ServerRequestInterface
158     */
159    protected static function createRequest(
160        string $method = RequestMethodInterface::METHOD_GET,
161        array $query = [],
162        array $params = [],
163        array $files = [],
164        array $attributes = []
165    ): ServerRequestInterface {
166        /** @var ServerRequestFactoryInterface */
167        $server_request_factory = app(ServerRequestFactoryInterface::class);
168
169        $uri = 'https://webtrees.test/index.php?' . http_build_query($query);
170
171        /** @var ServerRequestInterface $request */
172        $request = $server_request_factory
173            ->createServerRequest($method, $uri)
174            ->withQueryParams($query)
175            ->withParsedBody($params)
176            ->withUploadedFiles($files)
177            ->withAttribute('base_url', 'https://webtrees.test')
178            ->withAttribute('client-ip', '127.0.0.1')
179            ->withAttribute('user', new GuestUser())
180            ->withAttribute('route', new Route());
181
182        foreach ($attributes as $key => $value) {
183            $request = $request->withAttribute($key, $value);
184
185            if ($key === 'tree') {
186                app()->instance(Tree::class, $value);
187            }
188        }
189
190        app()->instance(ServerRequestInterface::class, $request);
191
192        return $request;
193    }
194
195    /**
196     * Things to run before every test.
197     */
198    protected function setUp(): void
199    {
200        parent::setUp();
201
202        if (static::$uses_database) {
203            DB::connection()->beginTransaction();
204        }
205    }
206
207    /**
208     * Things to run after every test
209     */
210    protected function tearDown(): void
211    {
212        if (static::$uses_database) {
213            DB::connection()->rollBack();
214        }
215
216        Site::$preferences = [];
217
218        Auth::logout();
219    }
220
221    /**
222     * Import a GEDCOM file into the test database.
223     *
224     * @param string $gedcom_file
225     *
226     * @return Tree
227     */
228    protected function importTree(string $gedcom_file): Tree
229    {
230        $tree_service = new TreeService();
231        $tree         = $tree_service->create(basename($gedcom_file), basename($gedcom_file));
232        $stream       = app(StreamFactoryInterface::class)->createStreamFromFile(__DIR__ . '/data/' . $gedcom_file);
233
234        $tree_service->importGedcomFile($tree, $stream, $gedcom_file);
235
236        $timeout_service = new TimeoutService(microtime(true));
237        $controller      = new GedcomLoad($timeout_service, $tree_service);
238        $request         = self::createRequest()->withAttribute('tree', $tree);
239
240        do {
241            $controller->handle($request);
242
243            $imported = $tree->getPreference('imported');
244        } while (!$imported);
245
246        return $tree;
247    }
248
249    /**
250     * Create an uploaded file for a request.
251     *
252     * @param string $filename
253     * @param string $mime_type
254     *
255     * @return UploadedFileInterface
256     */
257    protected function createUploadedFile(string $filename, string $mime_type): UploadedFileInterface
258    {
259        /** @var StreamFactoryInterface */
260        $stream_factory = app(StreamFactoryInterface::class);
261
262        /** @var UploadedFileFactoryInterface */
263        $uploaded_file_factory = app(UploadedFileFactoryInterface::class);
264
265        $stream      = $stream_factory->createStreamFromFile($filename);
266        $size        = filesize($filename);
267        $status      = UPLOAD_ERR_OK;
268        $client_name = basename($filename);
269
270        return $uploaded_file_factory->createUploadedFile($stream, $size, $status, $client_name, $mime_type);
271    }
272}
273