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