xref: /webtrees/tests/TestCase.php (revision 3df1e584fbd868b51c2f8559129ab0652c3acaa3)
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        GedcomRecord::$gedcom_record_cache  = null;
207        GedcomRecord::$pending_record_cache = null;
208
209        Auth::logout();
210    }
211
212    /**
213     * Import a GEDCOM file into the test database.
214     *
215     * @param string $gedcom_file
216     *
217     * @return Tree
218     */
219    protected function importTree(string $gedcom_file): Tree
220    {
221        $tree = Tree::create(basename($gedcom_file), basename($gedcom_file));
222
223        $stream = app(StreamFactoryInterface::class)->createStreamFromFile(__DIR__ . '/data/' . $gedcom_file);
224        $tree->importGedcomFile($stream, $gedcom_file);
225
226        View::share('tree', $tree);
227
228        $timeout_service = new TimeoutService(microtime(true));
229        $controller      = new GedcomFileController($timeout_service);
230        $request         = self::createRequest()->withAttribute('tree', $tree);
231
232        do {
233            $controller->import($request);
234
235            $imported = $tree->getPreference('imported');
236        } while (!$imported);
237
238        return $tree;
239    }
240
241    /**
242     * Create an uploaded file for a request.
243     *
244     * @param string $filename
245     * @param string $mime_type
246     *
247     * @return UploadedFileInterface
248     */
249    protected function createUploadedFile(string $filename, string $mime_type): UploadedFileInterface
250    {
251        /** @var StreamFactoryInterface */
252        $stream_factory = app(StreamFactoryInterface::class);
253
254        /** @var UploadedFileFactoryInterface */
255        $uploaded_file_factory = app(UploadedFileFactoryInterface::class);
256
257        $stream      = $stream_factory->createStreamFromFile($filename);
258        $size        = filesize($filename);
259        $status      = UPLOAD_ERR_OK;
260        $client_name = basename($filename);
261
262        return $uploaded_file_factory->createUploadedFile($stream, $size, $status, $client_name, $mime_type);
263    }
264}
265