xref: /webtrees/tests/TestCase.php (revision e252129f69fbec0af9c81ab88481e006f8a0c031)
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(string $method = RequestMethodInterface::METHOD_GET, array $query = [], array $params = [], array $files = []): ServerRequestInterface
161    {
162        /** @var ServerRequestFactoryInterface */
163        $server_request_factory = app(ServerRequestFactoryInterface::class);
164
165        $uri = 'https://webtrees.test/index.php?' . http_build_query($query);
166
167        /** @var ServerRequestInterface $request */
168        $request = $server_request_factory
169            ->createServerRequest($method, $uri)
170            ->withQueryParams($query)
171            ->withParsedBody($params)
172            ->withUploadedFiles($files)
173            ->withAttribute('base_url', 'https://webtrees.test')
174            ->withAttribute('client-ip', '127.0.0.1');
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        app('cache.array')->flush();
204
205        Site::$preferences                  = [];
206        Tree::$trees                        = [];
207        GedcomRecord::$gedcom_record_cache  = null;
208        GedcomRecord::$pending_record_cache = null;
209
210        Auth::logout();
211    }
212
213    /**
214     * Import a GEDCOM file into the test database.
215     *
216     * @param string $gedcom_file
217     *
218     * @return Tree
219     */
220    protected function importTree(string $gedcom_file): Tree
221    {
222        $tree = Tree::create(basename($gedcom_file), basename($gedcom_file));
223
224        $stream = app(StreamFactoryInterface::class)->createStreamFromFile(__DIR__ . '/data/' . $gedcom_file);
225        $tree->importGedcomFile($stream, $gedcom_file);
226
227        View::share('tree', $tree);
228
229        $timeout_service = new TimeoutService(microtime(true));
230        $controller      = new GedcomFileController($timeout_service);
231        $request         = self::createRequest()->withAttribute('tree', $tree);
232
233        do {
234            $controller->import($request);
235
236            $imported = $tree->getPreference('imported');
237        } while (!$imported);
238
239        return $tree;
240    }
241
242    /**
243     * Create an uploaded file for a request.
244     *
245     * @param string $filename
246     * @param string $mime_type
247     *
248     * @return UploadedFileInterface
249     */
250    protected function createUploadedFile(string $filename, string $mime_type): UploadedFileInterface
251    {
252        /** @var StreamFactoryInterface */
253        $stream_factory = app(StreamFactoryInterface::class);
254
255        /** @var UploadedFileFactoryInterface */
256        $uploaded_file_factory = app(UploadedFileFactoryInterface::class);
257
258        $stream      = $stream_factory->createStreamFromFile($filename);
259        $size        = filesize($filename);
260        $status      = UPLOAD_ERR_OK;
261        $client_name = basename($filename);
262
263        return $uploaded_file_factory->createUploadedFile($stream, $size, $status, $client_name, $mime_type);
264    }
265}
266