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