xref: /webtrees/tests/TestCase.php (revision 953f11988d09a6cba4eb7cf9a517539ee72ed23c)
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\NullStore;
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        // Disable the cache.
85        app()->instance('cache.array', new Repository(new NullStore()));
86
87        app()->instance(FilesystemInterface::class, new Filesystem(new MemoryAdapter()));
88        app()->bind(LocaleInterface::class, LocaleEnUs::class);
89        app()->bind(ModuleThemeInterface::class, WebtreesTheme::class);
90
91        // Need the routing table, to generate URLs.
92        app()->instance(RouterContainer::class, new RouterContainer());
93        require __DIR__ . '/../routes/web.php';
94
95        defined('WT_DATA_DIR') || define('WT_DATA_DIR', Webtrees::ROOT_DIR . 'data/');
96        defined('WT_LOCALE') || define('WT_LOCALE', I18N::init('en-US', null, true));
97
98        if (static::$uses_database) {
99            static::createTestDatabase();
100
101            // Boot modules
102            (new ModuleService())->bootModules(new WebtreesTheme());
103        }
104    }
105
106    /**
107     * Things to run once, AFTER all the tests.
108     */
109    public static function tearDownAfterClass()
110    {
111        if (static::$uses_database) {
112            $pdo = DB::connection()->getPdo();
113            unset($pdo);
114        }
115
116        parent::tearDownAfterClass();
117    }
118
119    /**
120     * Create an SQLite in-memory database for testing
121     */
122    protected static function createTestDatabase(): void
123    {
124        $capsule = new DB();
125        $capsule->addConnection([
126            'driver'   => 'sqlite',
127            'database' => ':memory:',
128        ]);
129        $capsule->setAsGlobal();
130
131        Builder::macro('whereContains', function ($column, string $search, string $boolean = 'and'): Builder {
132            $search = strtr($search, ['\\' => '\\\\', '%' => '\\%', '_' => '\\_', ' ' => '%']);
133
134            return $this->where($column, 'LIKE', '%' . $search . '%', $boolean);
135        });
136
137        // Migrations create logs, which requires an IP address, which requires a request
138        self::createRequest();
139
140        // Create tables
141        $migration_service = new MigrationService();
142        $migration_service->updateSchema('\Fisharebest\Webtrees\Schema', 'WT_SCHEMA_VERSION', Webtrees::SCHEMA_VERSION);
143
144        // Create config data
145        $migration_service->seedDatabase();
146    }
147
148    /**
149     * Create a request and bind it into the container.
150     *
151     * @param string                  $method
152     * @param string[]                $query
153     * @param string[]                $params
154     * @param UploadedFileInterface[] $files
155     *
156     * @return ServerRequestInterface
157     */
158    protected static function createRequest(
159        string $method = RequestMethodInterface::METHOD_GET,
160        array $query = [],
161        array $params = [],
162        array $files = []
163    ): ServerRequestInterface {
164        /** @var ServerRequestFactoryInterface */
165        $server_request_factory = app(ServerRequestFactoryInterface::class);
166
167        $uri = 'https://webtrees.test/index.php?' . http_build_query($query);
168
169        /** @var ServerRequestInterface $request */
170        $request = $server_request_factory
171            ->createServerRequest($method, $uri)
172            ->withQueryParams($query)
173            ->withParsedBody($params)
174            ->withUploadedFiles($files)
175            ->withAttribute('base_url', 'https://webtrees.test')
176            ->withAttribute('client-ip', '127.0.0.1');
177
178        app()->instance(ServerRequestInterface::class, $request);
179        View::share('request', $request);
180
181        return $request;
182    }
183
184    /**
185     * Things to run before every test.
186     */
187    protected function setUp(): void
188    {
189        parent::setUp();
190
191        if (static::$uses_database) {
192            DB::connection()->beginTransaction();
193        }
194    }
195
196    /**
197     * Things to run after every test
198     */
199    protected function tearDown()
200    {
201        if (static::$uses_database) {
202            DB::connection()->rollBack();
203        }
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