xref: /webtrees/tests/TestCase.php (revision 6b4dc746d4f08ae2d31f5db469ac67a13688bef6)
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\Route;
23use Aura\Router\RouterContainer;
24use Fig\Http\Message\RequestMethodInterface;
25use Fisharebest\Webtrees\Http\Controllers\GedcomFileController;
26use Fisharebest\Webtrees\Http\Routes\WebRoutes;
27use Fisharebest\Webtrees\Module\ModuleThemeInterface;
28use Fisharebest\Webtrees\Module\WebtreesTheme;
29use Fisharebest\Webtrees\Services\MigrationService;
30use Fisharebest\Webtrees\Services\ModuleService;
31use Fisharebest\Webtrees\Services\TimeoutService;
32use Fisharebest\Webtrees\Services\TreeService;
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 Symfony\Component\Cache\Adapter\NullAdapter;
46
47use function app;
48use function basename;
49use function filesize;
50use function http_build_query;
51use function microtime;
52
53use const UPLOAD_ERR_OK;
54
55/**
56 * Base class for unit tests
57 */
58class TestCase extends \PHPUnit\Framework\TestCase
59{
60    /** @var object */
61    public static $mock_functions;
62    /** @var bool */
63    protected static $uses_database = false;
64
65    /**
66     * Things to run once, before all the tests.
67     */
68    public static function setUpBeforeClass()
69    {
70        parent::setUpBeforeClass();
71
72        // Use nyholm as our PSR7 factory
73        app()->bind(ResponseFactoryInterface::class, Psr17Factory::class);
74        app()->bind(ServerRequestFactoryInterface::class, Psr17Factory::class);
75        app()->bind(StreamFactoryInterface::class, Psr17Factory::class);
76        app()->bind(UploadedFileFactoryInterface::class, Psr17Factory::class);
77        app()->bind(UriFactoryInterface::class, Psr17Factory::class);
78
79        // Disable the cache.
80        app()->instance('cache.array', new Cache(new NullAdapter()));
81
82        app()->bind(ModuleThemeInterface::class, WebtreesTheme::class);
83
84        // Need the routing table, to generate URLs.
85        $router_container = new RouterContainer('/');
86        (new WebRoutes())->load($router_container->getMap());
87        app()->instance(RouterContainer::class, $router_container);
88
89        I18N::init('en-US', true);
90
91        if (static::$uses_database) {
92            static::createTestDatabase();
93
94            // Boot modules
95            (new ModuleService())->bootModules(new WebtreesTheme());
96        }
97    }
98
99    /**
100     * Things to run once, AFTER all the tests.
101     */
102    public static function tearDownAfterClass()
103    {
104        if (static::$uses_database) {
105            $pdo = DB::connection()->getPdo();
106            unset($pdo);
107        }
108
109        parent::tearDownAfterClass();
110    }
111
112    /**
113     * Create an SQLite in-memory database for testing
114     */
115    protected static function createTestDatabase(): void
116    {
117        $capsule = new DB();
118        $capsule->addConnection([
119            'driver'   => 'sqlite',
120            'database' => ':memory:',
121        ]);
122        $capsule->setAsGlobal();
123
124        Builder::macro('whereContains', function ($column, string $search, string $boolean = 'and'): Builder {
125            $search = strtr($search, ['\\' => '\\\\', '%' => '\\%', '_' => '\\_', ' ' => '%']);
126
127            return $this->where($column, 'LIKE', '%' . $search . '%', $boolean);
128        });
129
130        // Migrations create logs, which requires an IP address, which requires a request
131        self::createRequest();
132
133        // Create tables
134        $migration_service = new MigrationService();
135        $migration_service->updateSchema('\Fisharebest\Webtrees\Schema', 'WT_SCHEMA_VERSION', Webtrees::SCHEMA_VERSION);
136
137        // Create config data
138        $migration_service->seedDatabase();
139    }
140
141    /**
142     * Create a request and bind it into the container.
143     *
144     * @param string                  $method
145     * @param string[]                $query
146     * @param string[]                $params
147     * @param UploadedFileInterface[] $files
148     * @param string[]                $attributes
149     *
150     * @return ServerRequestInterface
151     */
152    protected static function createRequest(
153        string $method = RequestMethodInterface::METHOD_GET,
154        array $query = [],
155        array $params = [],
156        array $files = [],
157        array $attributes = []
158    ): ServerRequestInterface {
159        /** @var ServerRequestFactoryInterface */
160        $server_request_factory = app(ServerRequestFactoryInterface::class);
161
162        $uri = 'https://webtrees.test/index.php?' . http_build_query($query);
163
164        /** @var ServerRequestInterface $request */
165        $request = $server_request_factory
166            ->createServerRequest($method, $uri)
167            ->withQueryParams($query)
168            ->withParsedBody($params)
169            ->withUploadedFiles($files)
170            ->withAttribute('base_url', 'https://webtrees.test')
171            ->withAttribute('client-ip', '127.0.0.1')
172            ->withAttribute('user', new GuestUser())
173            ->withAttribute('filesystem.data', new Filesystem(new MemoryAdapter()))
174            ->withAttribute('filesystem.data.name', 'data/')
175            ->withAttribute('route', new Route());
176
177        foreach ($attributes as $key => $value) {
178            $request = $request->withAttribute($key, $value);
179
180            if ($key === 'tree') {
181                app()->instance(Tree::class, $value);
182            }
183        }
184
185        app()->instance(ServerRequestInterface::class, $request);
186
187        return $request;
188    }
189
190    /**
191     * Things to run before every test.
192     */
193    protected function setUp(): void
194    {
195        parent::setUp();
196
197        if (static::$uses_database) {
198            DB::connection()->beginTransaction();
199        }
200    }
201
202    /**
203     * Things to run after every test
204     */
205    protected function tearDown()
206    {
207        if (static::$uses_database) {
208            DB::connection()->rollBack();
209        }
210
211        Site::$preferences                  = [];
212        GedcomRecord::$gedcom_record_cache  = null;
213        GedcomRecord::$pending_record_cache = null;
214
215        Auth::logout();
216    }
217
218    /**
219     * Import a GEDCOM file into the test database.
220     *
221     * @param string $gedcom_file
222     *
223     * @return Tree
224     */
225    protected function importTree(string $gedcom_file): Tree
226    {
227        $tree_service = new TreeService();
228        $tree         = $tree_service->create(basename($gedcom_file), basename($gedcom_file));
229        $stream       = app(StreamFactoryInterface::class)->createStreamFromFile(__DIR__ . '/data/' . $gedcom_file);
230
231        $tree->importGedcomFile($stream, $gedcom_file);
232
233        $timeout_service = new TimeoutService(microtime(true));
234        $controller      = new GedcomFileController($timeout_service);
235        $request         = self::createRequest()->withAttribute('tree', $tree);
236
237        do {
238            $controller->import($request);
239
240            $imported = $tree->getPreference('imported');
241        } while (!$imported);
242
243        return $tree;
244    }
245
246    /**
247     * Create an uploaded file for a request.
248     *
249     * @param string $filename
250     * @param string $mime_type
251     *
252     * @return UploadedFileInterface
253     */
254    protected function createUploadedFile(string $filename, string $mime_type): UploadedFileInterface
255    {
256        /** @var StreamFactoryInterface */
257        $stream_factory = app(StreamFactoryInterface::class);
258
259        /** @var UploadedFileFactoryInterface */
260        $uploaded_file_factory = app(UploadedFileFactoryInterface::class);
261
262        $stream      = $stream_factory->createStreamFromFile($filename);
263        $size        = filesize($filename);
264        $status      = UPLOAD_ERR_OK;
265        $client_name = basename($filename);
266
267        return $uploaded_file_factory->createUploadedFile($stream, $size, $status, $client_name, $mime_type);
268    }
269}
270