1<?php 2 3/** 4 * webtrees: online genealogy 5 * Copyright (C) 2022 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 <https://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 Fig\Http\Message\StatusCodeInterface; 26use Fisharebest\Webtrees\Http\RequestHandlers\GedcomLoad; 27use Fisharebest\Webtrees\Http\Routes\WebRoutes; 28use Fisharebest\Webtrees\Module\ModuleThemeInterface; 29use Fisharebest\Webtrees\Module\WebtreesTheme; 30use Fisharebest\Webtrees\Services\GedcomImportService; 31use Fisharebest\Webtrees\Services\MigrationService; 32use Fisharebest\Webtrees\Services\ModuleService; 33use Fisharebest\Webtrees\Services\TimeoutService; 34use Fisharebest\Webtrees\Services\TreeService; 35use Illuminate\Database\Capsule\Manager as DB; 36use Nyholm\Psr7\Factory\Psr17Factory; 37use Psr\Http\Message\ResponseFactoryInterface; 38use Psr\Http\Message\ResponseInterface; 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; 45 46use function app; 47use function basename; 48use function filesize; 49use function http_build_query; 50use function implode; 51use function preg_match; 52use function str_starts_with; 53use function strcspn; 54use function strlen; 55use function strpos; 56use function substr; 57 58use const UPLOAD_ERR_OK; 59 60/** 61 * Base class for unit tests 62 */ 63class TestCase extends \PHPUnit\Framework\TestCase 64{ 65 public static ?object $mock_functions = null; 66 67 protected static bool $uses_database = false; 68 69 /** 70 * Things to run once, before all the tests. 71 */ 72 public static function setUpBeforeClass(): void 73 { 74 parent::setUpBeforeClass(); 75 76 $webtrees = new Webtrees(); 77 $webtrees->bootstrap(); 78 79 // PSR7 messages and PSR17 message-factories 80 Webtrees::set(ResponseFactoryInterface::class, Psr17Factory::class); 81 Webtrees::set(ServerRequestFactoryInterface::class, Psr17Factory::class); 82 Webtrees::set(StreamFactoryInterface::class, Psr17Factory::class); 83 Webtrees::set(UploadedFileFactoryInterface::class, Psr17Factory::class); 84 Webtrees::set(UriFactoryInterface::class, Psr17Factory::class); 85 86 // This is normally set in middleware. 87 Webtrees::set(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 Webtrees::set(RouterContainer::class, $router_container); 93 94 I18N::init('en-US', true); 95 96 if (static::$uses_database) { 97 static::createTestDatabase(); 98 99 // This is normally set in middleware. 100 (new Gedcom())->registerTags(Registry::elementFactory(), true); 101 102 // Boot modules 103 (new ModuleService())->bootModules(new WebtreesTheme()); 104 } 105 } 106 107 /** 108 * Things to run once, AFTER all the tests. 109 */ 110 public static function tearDownAfterClass(): void 111 { 112 if (static::$uses_database) { 113 $pdo = DB::connection()->getPdo(); 114 unset($pdo); 115 } 116 117 parent::tearDownAfterClass(); 118 } 119 120 /** 121 * Create an SQLite in-memory database for testing 122 */ 123 protected static function createTestDatabase(): void 124 { 125 $capsule = new DB(); 126 $capsule->addConnection([ 127 'driver' => 'sqlite', 128 'database' => ':memory:', 129 ]); 130 $capsule->setAsGlobal(); 131 132 // Migrations create logs, which requires an IP address, which requires a request 133 self::createRequest(); 134 135 // Create tables 136 $migration_service = new MigrationService(); 137 $migration_service->updateSchema('\Fisharebest\Webtrees\Schema', 'WT_SCHEMA_VERSION', Webtrees::SCHEMA_VERSION); 138 139 // Create config data 140 $migration_service->seedDatabase(); 141 } 142 143 /** 144 * Create a request and bind it into the container. 145 * 146 * @param string $method 147 * @param array<string> $query 148 * @param array<string> $params 149 * @param array<UploadedFileInterface> $files 150 * @param array<string> $attributes 151 * 152 * @return ServerRequestInterface 153 */ 154 protected static function createRequest( 155 string $method = RequestMethodInterface::METHOD_GET, 156 array $query = [], 157 array $params = [], 158 array $files = [], 159 array $attributes = [] 160 ): ServerRequestInterface { 161 /** @var ServerRequestFactoryInterface */ 162 $server_request_factory = app(ServerRequestFactoryInterface::class); 163 164 $uri = 'https://webtrees.test/index.php?' . http_build_query($query); 165 166 $request = $server_request_factory 167 ->createServerRequest($method, $uri) 168 ->withQueryParams($query) 169 ->withParsedBody($params) 170 ->withUploadedFiles($files) 171 ->withAttribute('base_url', 'https://webtrees.test') 172 ->withAttribute('client-ip', '127.0.0.1') 173 ->withAttribute('user', new GuestUser()) 174 ->withAttribute('route', new Route()); 175 176 foreach ($attributes as $key => $value) { 177 $request = $request->withAttribute($key, $value); 178 179 if ($key === 'tree') { 180 app()->instance(Tree::class, $value); 181 } 182 } 183 184 app()->instance(ServerRequestInterface::class, $request); 185 186 return $request; 187 } 188 189 /** 190 * Things to run before every test. 191 */ 192 protected function setUp(): void 193 { 194 parent::setUp(); 195 196 if (static::$uses_database) { 197 DB::connection()->beginTransaction(); 198 } 199 } 200 201 /** 202 * Things to run after every test 203 */ 204 protected function tearDown(): void 205 { 206 if (static::$uses_database) { 207 DB::connection()->rollBack(); 208 } 209 210 Site::$preferences = []; 211 212 Auth::logout(); 213 } 214 215 /** 216 * Import a GEDCOM file into the test database. 217 * 218 * @param string $gedcom_file 219 * 220 * @return Tree 221 */ 222 protected function importTree(string $gedcom_file): Tree 223 { 224 $gedcom_import_service = new GedcomImportService(); 225 $tree_service = new TreeService($gedcom_import_service); 226 $tree = $tree_service->create(basename($gedcom_file), basename($gedcom_file)); 227 $stream = app(StreamFactoryInterface::class)->createStreamFromFile(__DIR__ . '/data/' . $gedcom_file); 228 229 $tree_service->importGedcomFile($tree, $stream, $gedcom_file, ''); 230 231 $timeout_service = new TimeoutService(); 232 $controller = new GedcomLoad($gedcom_import_service, $timeout_service); 233 $request = self::createRequest()->withAttribute('tree', $tree); 234 235 do { 236 $controller->handle($request); 237 238 $imported = $tree->getPreference('imported'); 239 } while (!$imported); 240 241 return $tree; 242 } 243 244 /** 245 * Create an uploaded file for a request. 246 * 247 * @param string $filename 248 * @param string $mime_type 249 * 250 * @return UploadedFileInterface 251 */ 252 protected function createUploadedFile(string $filename, string $mime_type): UploadedFileInterface 253 { 254 /** @var StreamFactoryInterface */ 255 $stream_factory = app(StreamFactoryInterface::class); 256 257 /** @var UploadedFileFactoryInterface */ 258 $uploaded_file_factory = app(UploadedFileFactoryInterface::class); 259 260 $stream = $stream_factory->createStreamFromFile($filename); 261 $size = filesize($filename); 262 $status = UPLOAD_ERR_OK; 263 $client_name = basename($filename); 264 265 return $uploaded_file_factory->createUploadedFile($stream, $size, $status, $client_name, $mime_type); 266 } 267 268 /** 269 * Assert that a response contains valid HTML - either a full page or a fragment. 270 * 271 * @param ResponseInterface $response 272 */ 273 protected function validateHtmlResponse(ResponseInterface $response): void 274 { 275 self::assertSame(StatusCodeInterface::STATUS_OK, $response->getStatusCode()); 276 277 self::assertEquals('text/html; charset=UTF-8', $response->getHeaderLine('content-type')); 278 279 $html = $response->getBody()->getContents(); 280 281 self::assertStringStartsWith('<DOCTYPE html>', $html); 282 283 $this->validateHtml(substr($html, strlen('<DOCTYPE html>'))); 284 } 285 286 /** 287 * Assert that a response contains valid HTML - either a full page or a fragment. 288 * 289 * @param string $html 290 */ 291 protected function validateHtml(string $html): void 292 { 293 $stack = []; 294 295 do { 296 $html = substr($html, strcspn($html, '<>')); 297 298 if (str_starts_with($html, '>')) { 299 static::fail('Unescaped > found in HTML'); 300 } 301 302 if (str_starts_with($html, '<')) { 303 if (preg_match('~^</([a-z]+)>~', $html, $match)) { 304 if ($match[1] !== array_pop($stack)) { 305 static::fail('Closing tag matches nothing: ' . $match[0] . ' at ' . implode(':', $stack)); 306 } 307 $html = substr($html, strlen($match[0])); 308 } elseif (preg_match('~^<([a-z]+)(?:\s+[a-z_\-]+="[^">]*")*\s*(/?)>~', $html, $match)) { 309 $tag = $match[1]; 310 $self_closing = $match[2] === '/'; 311 312 $message = 'Tag ' . $tag . ' is not allowed at ' . implode(':', $stack) . '.'; 313 314 switch ($tag) { 315 case 'html': 316 static::assertSame([], $stack); 317 break; 318 case 'head': 319 case 'body': 320 static::assertSame(['head'], $stack); 321 break; 322 case 'div': 323 static::assertNotContains('span', $stack, $message); 324 break; 325 } 326 327 if (!$self_closing) { 328 $stack[] = $tag; 329 } 330 331 if ($tag === 'script' && !$self_closing) { 332 $html = substr($html, strpos($html, '</script>')); 333 } else { 334 $html = substr($html, strlen($match[0])); 335 } 336 } else { 337 static::fail('Unrecognised tag: ' . substr($html, 0, 40)); 338 } 339 } 340 } while ($html !== ''); 341 342 static::assertSame([], $stack); 343 } 344} 345