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