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\MigrationService; 31use Fisharebest\Webtrees\Services\ModuleService; 32use Fisharebest\Webtrees\Services\TimeoutService; 33use Fisharebest\Webtrees\Services\TreeService; 34use Illuminate\Database\Capsule\Manager as DB; 35use Nyholm\Psr7\Factory\Psr17Factory; 36use Psr\Http\Message\ResponseFactoryInterface; 37use Psr\Http\Message\ResponseInterface; 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; 44 45use function app; 46use function basename; 47use function filesize; 48use function http_build_query; 49use function implode; 50use function preg_match; 51use function str_starts_with; 52use function strcspn; 53use function strlen; 54use function strpos; 55use function substr; 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(): 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 string[] $query 145 * @param string[] $params 146 * @param UploadedFileInterface[] $files 147 * @param 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 $tree_service = new TreeService(); 223 $tree = $tree_service->create(basename($gedcom_file), basename($gedcom_file)); 224 $stream = app(StreamFactoryInterface::class)->createStreamFromFile(__DIR__ . '/data/' . $gedcom_file); 225 226 $tree_service->importGedcomFile($tree, $stream, $gedcom_file); 227 228 $timeout_service = new TimeoutService(); 229 $controller = new GedcomLoad($timeout_service, $tree_service); 230 $request = self::createRequest()->withAttribute('tree', $tree); 231 232 do { 233 $controller->handle($request); 234 235 $imported = $tree->getPreference('imported'); 236 } while (!$imported); 237 238 return $tree; 239 } 240 241 /** 242 * Create an uploaded file for a request. 243 * 244 * @param string $filename 245 * @param string $mime_type 246 * 247 * @return UploadedFileInterface 248 */ 249 protected function createUploadedFile(string $filename, string $mime_type): UploadedFileInterface 250 { 251 /** @var StreamFactoryInterface */ 252 $stream_factory = app(StreamFactoryInterface::class); 253 254 /** @var UploadedFileFactoryInterface */ 255 $uploaded_file_factory = app(UploadedFileFactoryInterface::class); 256 257 $stream = $stream_factory->createStreamFromFile($filename); 258 $size = filesize($filename); 259 $status = UPLOAD_ERR_OK; 260 $client_name = basename($filename); 261 262 return $uploaded_file_factory->createUploadedFile($stream, $size, $status, $client_name, $mime_type); 263 } 264 265 /** 266 * Assert that a response contains valid HTML - either a full page or a fragment. 267 * 268 * @param ResponseInterface $response 269 */ 270 protected function validateHtmlResponse(ResponseInterface $response): void 271 { 272 self::assertSame(StatusCodeInterface::STATUS_OK, $response->getStatusCode()); 273 274 self::assertEquals('text/html; charset=UTF-8', $response->getHeaderLine('content-type')); 275 276 $html = $response->getBody()->getContents(); 277 278 self::assertStringStartsWith('<DOCTYPE html>', $html); 279 280 $this->validateHtml(substr($html, strlen('<DOCTYPE html>'))); 281 } 282 283 /** 284 * Assert that a response contains valid HTML - either a full page or a fragment. 285 * 286 * @param string $html 287 */ 288 protected function validateHtml(string $html): void 289 { 290 $stack = []; 291 292 do { 293 $html = substr($html, strcspn($html, '<>')); 294 295 if (str_starts_with($html, '>')) { 296 $this->fail('Unescaped > found in HTML'); 297 } 298 299 if (str_starts_with($html, '<')) { 300 if (preg_match('~^</([a-z]+)>~', $html, $match)) { 301 if ($match[1] !== array_pop($stack)) { 302 $this->fail('Closing tag matches nothing: ' . $match[0] . ' at ' . implode(':', $stack)); 303 } 304 $html = substr($html, strlen($match[0])); 305 } elseif (preg_match('~^<([a-z]+)(?:\s+[a-z_\-]+="[^">]*")*\s*(/?)>~', $html, $match)) { 306 $tag = $match[1]; 307 $self_closing = $match[2] === '/'; 308 309 $message = 'Tag ' . $tag . ' is not allowed at ' . implode(':', $stack) . '.'; 310 311 switch ($tag) { 312 case 'html': 313 $this->assertSame([], $stack); 314 break; 315 case 'head': 316 case 'body': 317 $this->assertSame(['head'], $stack); 318 break; 319 case 'div': 320 $this->assertNotContains('span', $stack, $message); 321 break; 322 } 323 324 if (!$self_closing) { 325 $stack[] = $tag; 326 } 327 328 if ($tag === 'script' && !$self_closing) { 329 $html = substr($html, strpos($html, '</script>')); 330 } else { 331 $html = substr($html, strlen($match[0])); 332 } 333 } else { 334 $this->fail('Unrecognised tag: ' . substr($html, 0, 40)); 335 } 336 } 337 } while ($html !== ''); 338 339 $this->assertSame([], $stack); 340 } 341} 342