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