xref: /webtrees/tests/TestCase.php (revision 6ccdf4f0fd1b65a5d54259c969912382ce49629d)
1<?php
2/**
3 * webtrees: online genealogy
4 * Copyright (C) 2019 webtrees development team
5 * This program is free software: you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License as published by
7 * the Free Software Foundation, either version 3 of the License, or
8 * (at your option) any later version.
9 * This program is distributed in the hope that it will be useful,
10 * but WITHOUT ANY WARRANTY; without even the implied warranty of
11 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 * GNU General Public License for more details.
13 * You should have received a copy of the GNU General Public License
14 * along with this program. If not, see <http://www.gnu.org/licenses/>.
15 */
16declare(strict_types=1);
17
18namespace Fisharebest\Webtrees;
19
20use Fig\Http\Message\StatusCodeInterface;
21use Fisharebest\Localization\Locale\LocaleEnUs;
22use Fisharebest\Localization\Locale\LocaleInterface;
23use Fisharebest\Webtrees\Contracts\UserInterface;
24use Fisharebest\Webtrees\Http\Controllers\GedcomFileController;
25use Fisharebest\Webtrees\Http\Request;
26use Fisharebest\Webtrees\Module\ModuleThemeInterface;
27use Fisharebest\Webtrees\Module\WebtreesTheme;
28use Fisharebest\Webtrees\Services\MigrationService;
29use Fisharebest\Webtrees\Services\TimeoutService;
30use Fisharebest\Webtrees\Services\UserService;
31use Illuminate\Cache\ArrayStore;
32use Illuminate\Cache\Repository;
33use Illuminate\Database\Capsule\Manager as DB;
34use League\Flysystem\Filesystem;
35use League\Flysystem\Memory\MemoryAdapter;
36use Nyholm\Psr7\Factory\Psr17Factory;
37use Psr\Http\Message\ResponseFactoryInterface;
38use Psr\Http\Message\ServerRequestFactoryInterface;
39use Psr\Http\Message\ServerRequestInterface;
40use Psr\Http\Message\StreamFactoryInterface;
41use Psr\Http\Message\UploadedFileFactoryInterface;
42use Psr\Http\Message\UploadedFileInterface;
43use Psr\Http\Message\UriFactoryInterface;
44use function app;
45use function basename;
46use function define;
47use function defined;
48use function dirname;
49use function filesize;
50use function http_build_query;
51use function rawurlencode;
52use const UPLOAD_ERR_OK;
53
54/**
55 * Base class for unit tests
56 */
57class TestCase extends \PHPUnit\Framework\TestCase implements StatusCodeInterface
58{
59    protected static $uses_database = false;
60
61    /**
62     * Things to run once, before all the tests.
63     */
64    public static function setUpBeforeClass()
65    {
66        parent::setUpBeforeClass();
67
68        // Use nyholm as our PSR7 factory
69        app()->bind(ResponseFactoryInterface::class, Psr17Factory::class);
70        app()->bind(ServerRequestFactoryInterface::class, Psr17Factory::class);
71        app()->bind(StreamFactoryInterface::class, Psr17Factory::class);
72        app()->bind(UploadedFileFactoryInterface::class, Psr17Factory::class);
73        app()->bind(UriFactoryInterface::class, Psr17Factory::class);
74
75        // Use an array cache for database calls, etc.
76        app()->instance('cache.array', new Repository(new ArrayStore()));
77
78        app()->bind(Tree::class, static function () {
79            return null;
80        });
81
82        app()->instance(UserService::class, new UserService());
83        app()->instance(UserInterface::class, new GuestUser());
84
85        app()->instance(ServerRequestInterface::class, Request::create('http://localhost/index.php'));
86        app()->instance(Filesystem::class, new Filesystem(new MemoryAdapter()));
87
88        app()->bind(ModuleThemeInterface::class, WebtreesTheme::class);
89        app()->bind(LocaleInterface::class, LocaleEnUs::class);
90
91        defined('WT_ROOT') || define('WT_ROOT', dirname(__DIR__) . '/');
92        defined('WT_BASE_URL') || define('WT_BASE_URL', 'http://localhost/');
93        defined('WT_DATA_DIR') || define('WT_DATA_DIR', WT_ROOT . 'data/');
94        defined('WT_LOCALE') || define('WT_LOCALE', I18N::init('en-US', null, true));
95
96        if (static::$uses_database) {
97            defined('WT_ROOT') || define('WT_ROOT', dirname(__DIR__) . '/');
98
99            static::createTestDatabase();
100        }
101    }
102
103    /**
104     * Create an SQLite in-memory database for testing
105     */
106    protected static function createTestDatabase(): void
107    {
108        $capsule = new DB();
109        $capsule->addConnection([
110            'driver'   => 'sqlite',
111            'database' => ':memory:',
112        ]);
113        $capsule->setAsGlobal();
114        Database::registerMacros();
115
116        // Migrations create logs, which requires an IP address, which requires a request
117        self::createRequest();
118
119        // Create tables
120        $migration_service = new MigrationService;
121        $migration_service->updateSchema('\Fisharebest\Webtrees\Schema', 'WT_SCHEMA_VERSION', Webtrees::SCHEMA_VERSION);
122
123        // Create config data
124        $migration_service->seedDatabase();
125    }
126
127    /**
128     * Things to run once, AFTER all the tests.
129     */
130    public static function tearDownAfterClass()
131    {
132        if (static::$uses_database) {
133            $pdo = DB::connection()->getPdo();
134            unset($pdo);
135        }
136
137        parent::tearDownAfterClass();
138    }
139
140    /**
141     * Things to run before every test.
142     */
143    protected function setUp()
144    {
145        parent::setUp();
146
147        if (static::$uses_database) {
148            DB::connection()->beginTransaction();
149        }
150    }
151
152    /**
153     * Things to run after every test
154     */
155    protected function tearDown()
156    {
157        if (static::$uses_database) {
158            DB::connection()->rollBack();
159        }
160
161        app('cache.array')->flush();
162
163        Site::$preferences                  = [];
164        Tree::$trees                        = [];
165        GedcomRecord::$gedcom_record_cache  = null;
166        GedcomRecord::$pending_record_cache = null;
167
168        Auth::logout();
169    }
170
171    /**
172     * Import a GEDCOM file into the test database.
173     *
174     * @param string $gedcom_file
175     *
176     * @return Tree
177     */
178    protected function importTree(string $gedcom_file): Tree
179    {
180        $tree = Tree::create(basename($gedcom_file), basename($gedcom_file));
181
182        $stream = app(StreamFactoryInterface::class)->createStreamFromFile(__DIR__ . '/data/' . $gedcom_file);
183        $tree->importGedcomFile($stream, $gedcom_file);
184
185        View::share('tree', $tree);
186        $gedcom_file_controller = new GedcomFileController();
187
188        do {
189            $gedcom_file_controller->import(new TimeoutService(microtime(true)), $tree);
190
191            $imported = $tree->getPreference('imported');
192        } while (!$imported);
193
194        return $tree;
195    }
196
197    /**
198     * Create a request and bind it into the container.
199     *
200     * @param string                  $method
201     * @param string[]                $query
202     * @param string[]                $params
203     * @param UploadedFileInterface[] $files
204     *
205     * @return ServerRequestInterface
206     */
207    protected static function createRequest(string $method = 'GET', array $query = [], array $params = [], array $files = []): ServerRequestInterface
208    {
209        /** @var ServerRequestFactoryInterface */
210        $server_request_factory = app(ServerRequestFactoryInterface::class);
211
212        $uri = 'http://localhost/index.php?' . http_build_query($query);
213
214        /** @var ServerRequestInterface $request */
215        $request =  $server_request_factory
216            ->createServerRequest($method, $uri)
217            ->withQueryParams($query)
218            ->withParsedBody($params)
219            ->withUploadedFiles($files);
220
221        app()->instance(ServerRequestInterface::class, $request);
222
223        return $request;
224    }
225
226    /**
227     * Create an uploaded file for a request.
228     *
229     * @param string $filename
230     * @param string $mime_type
231     *
232     * @return UploadedFileInterface
233     */
234    protected function createUploadedFile(string $filename, string $mime_type): UploadedFileInterface
235    {
236        /** @var StreamFactoryInterface */
237        $stream_factory = app(StreamFactoryInterface::class);
238
239        /** @var UploadedFileFactoryInterface */
240        $uploaded_file_factory = app(UploadedFileFactoryInterface::class);
241
242        $stream = $stream_factory->createStreamFromFile($filename);
243
244        $size = filesize($filename);
245
246        $status = UPLOAD_ERR_OK;
247
248        $client_name = basename($filename);
249
250        return $uploaded_file_factory->createUploadedFile($stream, $size, $status, $client_name, $mime_type);
251    }
252}
253