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