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 Fisharebest\Webtrees\Http\RequestHandlers\GedcomLoad; 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\Database\Capsule\Manager as DB; 34use Nyholm\Psr7\Factory\Psr17Factory; 35use Psr\Http\Message\ResponseFactoryInterface; 36use Psr\Http\Message\ResponseInterface; 37use Psr\Http\Message\ServerRequestFactoryInterface; 38use Psr\Http\Message\ServerRequestInterface; 39use Psr\Http\Message\StreamFactoryInterface; 40use Psr\Http\Message\UploadedFileFactoryInterface; 41use Psr\Http\Message\UploadedFileInterface; 42use Psr\Http\Message\UriFactoryInterface; 43 44use function app; 45use function basename; 46use function filesize; 47use function http_build_query; 48use function implode; 49use function preg_match; 50use function str_contains; 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 $this->assertEquals('text/html; charsert=utf8', $response->getHeaderLine('content-type')); 273 274 $html = $response->getBody()->getContents(); 275 276 $this->assertStringStartsWith('<DOCTYPE html>', $html); 277 278 $this->validateHtml(substr($html, strlen('<DOCTYPE html>'))); 279 } 280 281 /** 282 * Assert that a response contains valid HTML - either a full page or a fragment. 283 * 284 * @param string $html 285 */ 286 protected function validateHtml(string $html): void 287 { 288 $stack = []; 289 290 do { 291 $html = substr($html, strcspn($html, '<>')); 292 293 if (str_starts_with($html, '>')) { 294 $this->fail('Unescaped > found in HTML'); 295 } 296 297 if (str_starts_with($html, '<')) { 298 if (preg_match('~^</([a-z]+)>~', $html, $match)) { 299 if ($match[1] !== array_pop($stack)) { 300 $this->fail('Closing tag matches nothing: ' . $match[0] . ' at ' . implode(':', $stack)); 301 } 302 $html = substr($html, strlen($match[0])); 303 } elseif (preg_match('~^<([a-z]+)(?:\s+[a-z_\-]+="[^">]*")*\s*(/?)>~', $html, $match)) { 304 $tag = $match[1]; 305 $self_closing = $match[2] === '/'; 306 307 $message = 'Tag ' . $tag . ' is not allowed at ' . implode(':', $stack) . '.'; 308 309 switch ($tag) { 310 case 'html': 311 $this->assertSame([], $stack); 312 break; 313 case 'head': 314 case 'body': 315 $this->assertSame(['head'], $stack); 316 break; 317 case 'div': 318 $this->assertNotContains('span', $stack, $message); 319 break; 320 } 321 322 if (!$self_closing) { 323 $stack[] = $tag; 324 } 325 326 if ($tag === 'script' && !$self_closing) { 327 $html = substr($html, strpos($html, '</script>')); 328 } else { 329 $html = substr($html, strlen($match[0])); 330 } 331 } else { 332 $this->fail('Unrecognised tag: ' . substr($html, 0, 40)); 333 } 334 } 335 } while ($html !== ''); 336 337 $this->assertSame([], $stack); 338 } 339} 340