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