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