xref: /webtrees/tests/TestCase.php (revision 57ab22314b2599feb432b1a1ed71643cfc2f0452)
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\FilesystemInterface;
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 function microtime;
52use const UPLOAD_ERR_OK;
53
54/**
55 * Base class for unit tests
56 */
57class TestCase extends \PHPUnit\Framework\TestCase implements StatusCodeInterface
58{
59    /** @var object */
60    public static $mock_functions;
61    /** @var bool */
62    protected static $uses_database = false;
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()->instance(UserService::class, new UserService());
82        app()->instance(FilesystemInterface::class, new Filesystem(new MemoryAdapter()));
83        app()->bind(LocaleInterface::class, LocaleEnUs::class);
84        app()->bind(ModuleThemeInterface::class, WebtreesTheme::class);
85        app()->bind(UserInterface::class, GuestUser::class);
86
87        defined('WT_DATA_DIR') || define('WT_DATA_DIR', Webtrees::ROOT_DIR . 'data/');
88        defined('WT_LOCALE') || define('WT_LOCALE', I18N::init('en-US', null, true));
89
90        if (static::$uses_database) {
91            static::createTestDatabase();
92        }
93    }
94
95    /**
96     * Create an SQLite in-memory database for testing
97     */
98    protected static function createTestDatabase(): void
99    {
100        $capsule = new DB();
101        $capsule->addConnection([
102            'driver'   => 'sqlite',
103            'database' => ':memory:',
104        ]);
105        $capsule->setAsGlobal();
106
107        Builder::macro('whereContains', function ($column, string $search, string $boolean = 'and'): Builder {
108            $search = strtr($search, ['\\' => '\\\\', '%' => '\\%', '_' => '\\_', ' ' => '%']);
109
110            return $this->where($column, 'LIKE', '%' . $search . '%', $boolean);
111        });
112
113        // Migrations create logs, which requires an IP address, which requires a request
114        self::createRequest();
115
116        // Create tables
117        $migration_service = new MigrationService;
118        $migration_service->updateSchema('\Fisharebest\Webtrees\Schema', 'WT_SCHEMA_VERSION', Webtrees::SCHEMA_VERSION);
119
120        // Create config data
121        $migration_service->seedDatabase();
122    }
123
124    /**
125     * Create a request and bind it into the container.
126     *
127     * @param string                  $method
128     * @param string[]                $query
129     * @param string[]                $params
130     * @param UploadedFileInterface[] $files
131     *
132     * @return ServerRequestInterface
133     */
134    protected static function createRequest(string $method = 'GET', array $query = [], array $params = [], array $files = []): ServerRequestInterface
135    {
136        /** @var ServerRequestFactoryInterface */
137        $server_request_factory = app(ServerRequestFactoryInterface::class);
138
139        $uri = 'https://webtrees.test/index.php?' . http_build_query($query);
140
141        /** @var ServerRequestInterface $request */
142        $request = $server_request_factory
143            ->createServerRequest($method, $uri)
144            ->withQueryParams($query)
145            ->withParsedBody($params)
146            ->withUploadedFiles($files)
147            ->withAttribute('base_url', 'https://webtrees.test')
148            ->withAttribute('client_ip', '127.0.0.1');
149
150        app()->instance(ServerRequestInterface::class, $request);
151
152        return $request;
153    }
154
155    /**
156     * Things to run once, AFTER all the tests.
157     */
158    public static function tearDownAfterClass()
159    {
160        if (static::$uses_database) {
161            $pdo = DB::connection()->getPdo();
162            unset($pdo);
163        }
164
165        parent::tearDownAfterClass();
166    }
167
168    /**
169     * Things to run before every test.
170     */
171    protected function setUp(): void
172    {
173        parent::setUp();
174
175        if (static::$uses_database) {
176            DB::connection()->beginTransaction();
177        }
178    }
179
180    /**
181     * Things to run after every test
182     */
183    protected function tearDown()
184    {
185        if (static::$uses_database) {
186            DB::connection()->rollBack();
187        }
188
189        app('cache.array')->flush();
190
191        Site::$preferences                  = [];
192        Tree::$trees                        = [];
193        GedcomRecord::$gedcom_record_cache  = null;
194        GedcomRecord::$pending_record_cache = null;
195
196        Auth::logout();
197    }
198
199    /**
200     * Import a GEDCOM file into the test database.
201     *
202     * @param string $gedcom_file
203     *
204     * @return Tree
205     */
206    protected function importTree(string $gedcom_file): Tree
207    {
208        $tree = Tree::create(basename($gedcom_file), basename($gedcom_file));
209
210        $stream = app(StreamFactoryInterface::class)->createStreamFromFile(__DIR__ . '/data/' . $gedcom_file);
211        $tree->importGedcomFile($stream, $gedcom_file);
212
213        View::share('tree', $tree);
214
215        $timeout_service = new TimeoutService(microtime(true));
216        $controller      = new GedcomFileController($timeout_service);
217        $request         = self::createRequest()->withAttribute('tree', $tree);
218
219        do {
220            $controller->import($request);
221
222            $imported = $tree->getPreference('imported');
223        } while (!$imported);
224
225        return $tree;
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        $size        = filesize($filename);
246        $status      = UPLOAD_ERR_OK;
247        $client_name = basename($filename);
248
249        return $uploaded_file_factory->createUploadedFile($stream, $size, $status, $client_name, $mime_type);
250    }
251}
252