xref: /webtrees/tests/TestCase.php (revision 557edc6474b92c23923f1472519b2caf1e5c5d91)
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\Filesystem;
37use League\Flysystem\Memory\MemoryAdapter;
38use League\Flysystem\Memory\NullAdapter;
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()->bind(ModuleThemeInterface::class, WebtreesTheme::class);
86
87        // Need the routing table, to generate URLs.
88        $router_container = new RouterContainer('/');
89        (new WebRoutes())->load($router_container->getMap());
90        app()->instance(RouterContainer::class, $router_container);
91
92        defined('WT_DATA_DIR') || define('WT_DATA_DIR', Webtrees::ROOT_DIR . 'data/');
93        I18N::init('en-US', 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     * @param string[]                $attributes
153     *
154     * @return ServerRequestInterface
155     */
156    protected static function createRequest(
157        string $method = RequestMethodInterface::METHOD_GET,
158        array $query = [],
159        array $params = [],
160        array $files = [],
161        array $attributes = []
162    ): ServerRequestInterface {
163        /** @var ServerRequestFactoryInterface */
164        $server_request_factory = app(ServerRequestFactoryInterface::class);
165
166        $uri = 'https://webtrees.test/index.php?' . http_build_query($query);
167
168        /** @var ServerRequestInterface $request */
169        $request = $server_request_factory
170            ->createServerRequest($method, $uri)
171            ->withQueryParams($query)
172            ->withParsedBody($params)
173            ->withUploadedFiles($files)
174            ->withAttribute('base_url', 'https://webtrees.test')
175            ->withAttribute('client-ip', '127.0.0.1')
176            ->withAttribute('user', new GuestUser())
177            ->withAttribute('filesystem.data', new Filesystem(new MemoryAdapter()))
178            ->withAttribute('filesystem.data.name', 'data/');
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