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