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