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