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