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