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