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