xref: /webtrees/tests/TestCase.php (revision 6dee9a8c9b87a4759535afc29fe1e81073a98265)
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 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
88        app()->instance(ServerRequestInterface::class, Request::create('http://localhost/index.php'));
89        app()->instance(Filesystem::class, new Filesystem(new MemoryAdapter()));
90
91        app()->bind(ModuleThemeInterface::class, WebtreesTheme::class);
92        app()->bind(LocaleInterface::class, LocaleEnUs::class);
93
94        defined('WT_BASE_URL') || define('WT_BASE_URL', 'http://localhost/');
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    }
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
115        Builder::macro('whereContains', function ($column, string $search, string $boolean = 'and'): Builder {
116            $search = strtr($search, ['\\' => '\\\\', '%' => '\\%', '_' => '\\_', ' ' => '%']);
117
118            return $this->where($column, 'LIKE', '%' . $search . '%', $boolean);
119        });
120
121        // Migrations create logs, which requires an IP address, which requires a request
122        self::createRequest();
123
124        // Create tables
125        $migration_service = new MigrationService;
126        $migration_service->updateSchema('\Fisharebest\Webtrees\Schema', 'WT_SCHEMA_VERSION', Webtrees::SCHEMA_VERSION);
127
128        // Create config data
129        $migration_service->seedDatabase();
130    }
131
132    /**
133     * Things to run once, AFTER all the tests.
134     */
135    public static function tearDownAfterClass()
136    {
137        if (static::$uses_database) {
138            $pdo = DB::connection()->getPdo();
139            unset($pdo);
140        }
141
142        parent::tearDownAfterClass();
143    }
144
145    /**
146     * Things to run before every test.
147     */
148    protected function setUp(): void
149    {
150        parent::setUp();
151
152        if (static::$uses_database) {
153            DB::connection()->beginTransaction();
154        }
155    }
156
157    /**
158     * Things to run after every test
159     */
160    protected function tearDown()
161    {
162        if (static::$uses_database) {
163            DB::connection()->rollBack();
164        }
165
166        app('cache.array')->flush();
167
168        Site::$preferences                  = [];
169        Tree::$trees                        = [];
170        GedcomRecord::$gedcom_record_cache  = null;
171        GedcomRecord::$pending_record_cache = null;
172
173        Auth::logout();
174    }
175
176    /**
177     * Import a GEDCOM file into the test database.
178     *
179     * @param string $gedcom_file
180     *
181     * @return Tree
182     */
183    protected function importTree(string $gedcom_file): Tree
184    {
185        $tree = Tree::create(basename($gedcom_file), basename($gedcom_file));
186
187        $stream = app(StreamFactoryInterface::class)->createStreamFromFile(__DIR__ . '/data/' . $gedcom_file);
188        $tree->importGedcomFile($stream, $gedcom_file);
189
190        View::share('tree', $tree);
191        $gedcom_file_controller = new GedcomFileController();
192
193        do {
194            $gedcom_file_controller->import(new TimeoutService(microtime(true)), $tree);
195
196            $imported = $tree->getPreference('imported');
197        } while (!$imported);
198
199        return $tree;
200    }
201
202    /**
203     * Create a request and bind it into the container.
204     *
205     * @param string                  $method
206     * @param string[]                $query
207     * @param string[]                $params
208     * @param UploadedFileInterface[] $files
209     *
210     * @return ServerRequestInterface
211     */
212    protected static function createRequest(string $method = 'GET', array $query = [], array $params = [], array $files = []): ServerRequestInterface
213    {
214        /** @var ServerRequestFactoryInterface */
215        $server_request_factory = app(ServerRequestFactoryInterface::class);
216
217        $uri = 'http://localhost/index.php?' . http_build_query($query);
218
219        /** @var ServerRequestInterface $request */
220        $request =  $server_request_factory
221            ->createServerRequest($method, $uri)
222            ->withQueryParams($query)
223            ->withParsedBody($params)
224            ->withUploadedFiles($files);
225
226        app()->instance(ServerRequestInterface::class, $request);
227
228        return $request;
229    }
230
231    /**
232     * Create an uploaded file for a request.
233     *
234     * @param string $filename
235     * @param string $mime_type
236     *
237     * @return UploadedFileInterface
238     */
239    protected function createUploadedFile(string $filename, string $mime_type): UploadedFileInterface
240    {
241        /** @var StreamFactoryInterface */
242        $stream_factory = app(StreamFactoryInterface::class);
243
244        /** @var UploadedFileFactoryInterface */
245        $uploaded_file_factory = app(UploadedFileFactoryInterface::class);
246
247        $stream = $stream_factory->createStreamFromFile($filename);
248
249        $size = filesize($filename);
250
251        $status = UPLOAD_ERR_OK;
252
253        $client_name = basename($filename);
254
255        return $uploaded_file_factory->createUploadedFile($stream, $size, $status, $client_name, $mime_type);
256    }
257}
258