| Total Complexity | 127 | 
| Total Lines | 1264 | 
| Duplicated Lines | 0 % | 
| Changes | 2 | ||
| Bugs | 0 | Features | 0 | 
Complex classes like SapphireTest often do a lot of different things. To break such a class down, we need to identify a cohesive component within that class. A common approach to find such a component is to look for fields/methods that share the same prefixes, or suffixes.
Once you have determined the fields that belong together, you can apply the Extract Class refactoring. If the component makes sense as a sub-class, Extract Subclass is also a candidate, and is often faster.
While breaking up the class, it is a good idea to analyze how other classes use SapphireTest, and based on these observations, apply Extract Interface, too.
| 1 | <?php | ||
| 54 | * The phpunit 5 version is lower down in this file | ||
| 55 | * phpunit 6, 7 and 8 are not supported | ||
| 56 | * | ||
| 57 | * Why there are two versions of SapphireTest: | ||
| 58 | * - phpunit 5 is not compatible with php 8 | ||
| 59 | * - a mimimum versin of php 7.3 is required for phpunit 9 | ||
| 60 | * - framework still supports php 7.1 + 7.2 so we need to support both versions for a while | ||
| 61 | * | ||
| 62 | * Once php 7.3 is the minimum version required by framework, the phpunit5 versions of SapphireTest | ||
| 63 | * and FunctionalTest could be removed, along with the if(class_exists()) checks in this file | ||
| 64 | * However, we still may choose to keep both until php 8 is the minimum to give projects more | ||
| 65 | * time to upgrade their unit tests to be phpunit 9 compatible | ||
| 66 | * | ||
| 67 | * The used on `if(class_exists()` and indentation ensure the the phpunit 5 version function | ||
| 68 | * signature is used by the php interprester. This is required because the phpunit5 | ||
| 69 | * signature for `setUp()` has no return type while the phpunit 9 version has `setUp(): void` | ||
| 70 | * Return type covariance allows more specific return types to be defined, while contravariance | ||
| 71 | * of return types of more abstract return types is not supported | ||
| 72 | * | ||
| 73 | * IsEqualCanonicalizing::class is a new class added in phpunit 9, testing that this class exists | ||
| 74 | * to ensure that we're not using a a prior, incompatible version of php | ||
| 75 | * | ||
| 76 | * ------------------------------------------------- | ||
| 77 | */ | ||
| 78 | if (class_exists(IsEqualCanonicalizing::class)) { | ||
| 79 | |||
| 80 | /** | ||
| 81 | * Test case class for the Sapphire framework. | ||
| 82 | * Sapphire unit testing is based on PHPUnit, but provides a number of hooks into our data model that make it easier | ||
| 83 | * to work with. | ||
| 84 | * | ||
| 85 | * This class should not be used anywhere outside of unit tests, as phpunit may not be installed | ||
| 86 | * in production sites. | ||
| 87 | */ | ||
| 88 | // Ignore multiple classes in same file | ||
| 89 | // @codingStandardsIgnoreStart | ||
| 90 | class SapphireTest extends TestCase implements TestOnly | ||
| 91 |     { | ||
| 92 | // @codingStandardsIgnoreEnd | ||
| 93 | /** | ||
| 94 | * Path to fixture data for this test run. | ||
| 95 | * If passed as an array, multiple fixture files will be loaded. | ||
| 96 | * Please note that you won't be able to refer with "=>" notation | ||
| 97 | * between the fixtures, they act independent of each other. | ||
| 98 | * | ||
| 99 | * @var string|array | ||
| 100 | */ | ||
| 101 | protected static $fixture_file = null; | ||
| 102 | |||
| 103 | /** | ||
| 104 | * @deprecated 4.0..5.0 Use FixtureTestState instead | ||
| 105 | * @var FixtureFactory | ||
| 106 | */ | ||
| 107 | protected $fixtureFactory; | ||
| 108 | |||
| 109 | /** | ||
| 110 | * @var Boolean If set to TRUE, this will force a test database to be generated | ||
| 111 |          * in {@link setUp()}. Note that this flag is overruled by the presence of a | ||
| 112 |          * {@link $fixture_file}, which always forces a database build. | ||
| 113 | * | ||
| 114 | * @var bool | ||
| 115 | */ | ||
| 116 | protected $usesDatabase = null; | ||
| 117 | |||
| 118 | /** | ||
| 119 | * This test will cleanup its state via transactions. | ||
| 120 | * If set to false a full schema is forced between tests, but at a performance cost. | ||
| 121 | * | ||
| 122 | * @var bool | ||
| 123 | */ | ||
| 124 | protected $usesTransactions = true; | ||
| 125 | |||
| 126 | /** | ||
| 127 | * @var bool | ||
| 128 | */ | ||
| 129 | protected static $is_running_test = false; | ||
| 130 | |||
| 131 | /** | ||
| 132 | * By default, setUp() does not require default records. Pass | ||
| 133 | * class names in here, and the require/augment default records | ||
| 134 | * function will be called on them. | ||
| 135 | * | ||
| 136 | * @var array | ||
| 137 | */ | ||
| 138 | protected $requireDefaultRecordsFrom = []; | ||
| 139 | |||
| 140 | /** | ||
| 141 | * A list of extensions that can't be applied during the execution of this run. If they are | ||
| 142 | * applied, they will be temporarily removed and a database migration called. | ||
| 143 | * | ||
| 144 | * The keys of the are the classes that the extensions can't be applied the extensions to, and | ||
| 145 | * the values are an array of illegal extensions on that class. | ||
| 146 | * | ||
| 147 | * Set a class to `*` to remove all extensions (unadvised) | ||
| 148 | * | ||
| 149 | * @var array | ||
| 150 | */ | ||
| 151 | protected static $illegal_extensions = []; | ||
| 152 | |||
| 153 | /** | ||
| 154 | * A list of extensions that must be applied during the execution of this run. If they are | ||
| 155 | * not applied, they will be temporarily added and a database migration called. | ||
| 156 | * | ||
| 157 | * The keys of the are the classes to apply the extensions to, and the values are an array | ||
| 158 | * of required extensions on that class. | ||
| 159 | * | ||
| 160 | * Example: | ||
| 161 | * <code> | ||
| 162 |          * array("MyTreeDataObject" => array("Versioned", "Hierarchy")) | ||
| 163 | * </code> | ||
| 164 | * | ||
| 165 | * @var array | ||
| 166 | */ | ||
| 167 | protected static $required_extensions = []; | ||
| 168 | |||
| 169 | /** | ||
| 170 | * By default, the test database won't contain any DataObjects that have the interface TestOnly. | ||
| 171 | * This variable lets you define additional TestOnly DataObjects to set up for this test. | ||
| 172 | * Set it to an array of DataObject subclass names. | ||
| 173 | * | ||
| 174 | * @var array | ||
| 175 | */ | ||
| 176 | protected static $extra_dataobjects = []; | ||
| 177 | |||
| 178 | /** | ||
| 179 |          * List of class names of {@see Controller} objects to register routes for | ||
| 180 | * Controllers must implement Link() method | ||
| 181 | * | ||
| 182 | * @var array | ||
| 183 | */ | ||
| 184 | protected static $extra_controllers = []; | ||
| 185 | |||
| 186 | /** | ||
| 187 | * We need to disabling backing up of globals to avoid overriding | ||
| 188 | * the few globals SilverStripe relies on, like $lang for the i18n subsystem. | ||
| 189 | * | ||
| 190 | * @see http://sebastian-bergmann.de/archives/797-Global-Variables-and-PHPUnit.html | ||
| 191 | */ | ||
| 192 | protected $backupGlobals = false; | ||
| 193 | |||
| 194 | /** | ||
| 195 | * State management container for SapphireTest | ||
| 196 | * | ||
| 197 | * @var SapphireTestState | ||
| 198 | */ | ||
| 199 | protected static $state = null; | ||
| 200 | |||
| 201 | /** | ||
| 202 | * Temp database helper | ||
| 203 | * | ||
| 204 | * @var TempDatabase | ||
| 205 | */ | ||
| 206 | protected static $tempDB = null; | ||
| 207 | |||
| 208 | /** | ||
| 209 | * @return TempDatabase | ||
| 210 | */ | ||
| 211 | public static function tempDB() | ||
| 212 |         { | ||
| 213 |             if (!class_exists(TempDatabase::class)) { | ||
| 214 | return null; | ||
| 215 | } | ||
| 216 | |||
| 217 |             if (!static::$tempDB) { | ||
| 218 | static::$tempDB = TempDatabase::create(); | ||
| 219 | } | ||
| 220 | return static::$tempDB; | ||
| 221 | } | ||
| 222 | |||
| 223 | /** | ||
| 224 | * Gets illegal extensions for this class | ||
| 225 | * | ||
| 226 | * @return array | ||
| 227 | */ | ||
| 228 | public static function getIllegalExtensions() | ||
| 229 |         { | ||
| 230 | return static::$illegal_extensions; | ||
| 231 | } | ||
| 232 | |||
| 233 | /** | ||
| 234 | * Gets required extensions for this class | ||
| 235 | * | ||
| 236 | * @return array | ||
| 237 | */ | ||
| 238 | public static function getRequiredExtensions() | ||
| 239 |         { | ||
| 240 | return static::$required_extensions; | ||
| 241 | } | ||
| 242 | |||
| 243 | /** | ||
| 244 | * Check if test bootstrapping has been performed. Must not be relied on | ||
| 245 | * outside of unit tests. | ||
| 246 | * | ||
| 247 | * @return bool | ||
| 248 | */ | ||
| 249 | protected static function is_running_test() | ||
| 250 |         { | ||
| 251 | return self::$is_running_test; | ||
| 252 | } | ||
| 253 | |||
| 254 | /** | ||
| 255 | * Set test running state | ||
| 256 | * | ||
| 257 | * @param bool $bool | ||
| 258 | */ | ||
| 259 | protected static function set_is_running_test($bool) | ||
| 260 |         { | ||
| 261 | self::$is_running_test = $bool; | ||
| 262 | } | ||
| 263 | |||
| 264 | /** | ||
| 265 | * @return String | ||
| 266 | */ | ||
| 267 | public static function get_fixture_file() | ||
| 268 |         { | ||
| 269 | return static::$fixture_file; | ||
| 270 | } | ||
| 271 | |||
| 272 | /** | ||
| 273 | * @return bool | ||
| 274 | */ | ||
| 275 | public function getUsesDatabase() | ||
| 276 |         { | ||
| 277 | return $this->usesDatabase; | ||
| 278 | } | ||
| 279 | |||
| 280 | /** | ||
| 281 | * @return bool | ||
| 282 | */ | ||
| 283 | public function getUsesTransactions() | ||
| 284 |         { | ||
| 285 | return $this->usesTransactions; | ||
| 286 | } | ||
| 287 | |||
| 288 | /** | ||
| 289 | * @return array | ||
| 290 | */ | ||
| 291 | public function getRequireDefaultRecordsFrom() | ||
| 292 |         { | ||
| 293 | return $this->requireDefaultRecordsFrom; | ||
| 294 | } | ||
| 295 | |||
| 296 | /** | ||
| 297 | * Setup the test. | ||
| 298 | * Always sets up in order: | ||
| 299 | * - Reset php state | ||
| 300 | * - Nest | ||
| 301 | * - Custom state helpers | ||
| 302 | * | ||
| 303 | * User code should call parent::setUp() before custom setup code | ||
| 304 | */ | ||
| 305 | protected function setUp(): void | ||
| 306 |         { | ||
| 307 |             if (!defined('FRAMEWORK_PATH')) { | ||
| 308 | trigger_error( | ||
| 309 | 'Missing constants, did you remember to include the test bootstrap in your phpunit.xml file?', | ||
| 310 | E_USER_WARNING | ||
| 311 | ); | ||
| 312 | } | ||
| 313 | |||
| 314 | // Call state helpers | ||
| 315 | static::$state->setUp($this); | ||
| 316 | |||
| 317 | // We cannot run the tests on this abstract class. | ||
| 318 |             if (static::class == __CLASS__) { | ||
| 319 |                 $this->markTestSkipped(sprintf('Skipping %s ', static::class)); | ||
| 320 | } | ||
| 321 | |||
| 322 | // i18n needs to be set to the defaults or tests fail | ||
| 323 |             if (class_exists(i18n::class)) { | ||
| 324 |                 i18n::set_locale(i18n::config()->uninherited('default_locale')); | ||
| 325 | } | ||
| 326 | |||
| 327 | // Set default timezone consistently to avoid NZ-specific dependencies | ||
| 328 |             date_default_timezone_set('UTC'); | ||
| 329 | |||
| 330 |             if (class_exists(Member::class)) { | ||
| 331 | Member::set_password_validator(null); | ||
| 332 | } | ||
| 333 | |||
| 334 |             if (class_exists(Cookie::class)) { | ||
| 335 |                 Cookie::config()->update('report_errors', false); | ||
| 336 | } | ||
| 337 | |||
| 338 |             if (class_exists(RootURLController::class)) { | ||
| 339 | RootURLController::reset(); | ||
| 340 | } | ||
| 341 | |||
| 342 |             if (class_exists(Security::class)) { | ||
| 343 | Security::clear_database_is_ready(); | ||
| 344 | } | ||
| 345 | |||
| 346 | // Set up test routes | ||
| 347 | $this->setUpRoutes(); | ||
| 348 | |||
| 349 | $fixtureFiles = $this->getFixturePaths(); | ||
| 350 | |||
| 351 |             if ($this->shouldSetupDatabaseForCurrentTest($fixtureFiles)) { | ||
| 352 | // Assign fixture factory to deprecated prop in case old tests use it over the getter | ||
| 353 | /** @var FixtureTestState $fixtureState */ | ||
| 354 |                 $fixtureState = static::$state->getStateByName('fixtures'); | ||
| 355 | $this->fixtureFactory = $fixtureState->getFixtureFactory(static::class); | ||
| 356 | |||
| 357 |                 $this->logInWithPermission('ADMIN'); | ||
| 358 | } | ||
| 359 | |||
| 360 | // turn off template debugging | ||
| 361 |             if (class_exists(SSViewer::class)) { | ||
| 362 |                 SSViewer::config()->update('source_file_comments', false); | ||
| 363 | } | ||
| 364 | |||
| 365 | // Set up the test mailer | ||
| 366 |             if (class_exists(TestMailer::class)) { | ||
| 367 | Injector::inst()->registerService(new TestMailer(), Mailer::class); | ||
| 368 | } | ||
| 369 | |||
| 370 |             if (class_exists(Email::class)) { | ||
| 371 |                 Email::config()->remove('send_all_emails_to'); | ||
| 372 |                 Email::config()->remove('send_all_emails_from'); | ||
| 373 |                 Email::config()->remove('cc_all_emails_to'); | ||
| 374 |                 Email::config()->remove('bcc_all_emails_to'); | ||
| 375 | } | ||
| 376 | } | ||
| 377 | |||
| 378 | |||
| 379 | /** | ||
| 380 | * Helper method to determine if the current test should enable a test database | ||
| 381 | * | ||
| 382 | * @param $fixtureFiles | ||
| 383 | * @return bool | ||
| 384 | */ | ||
| 385 | protected function shouldSetupDatabaseForCurrentTest($fixtureFiles) | ||
| 386 |         { | ||
| 387 | $databaseEnabledByDefault = $fixtureFiles || $this->usesDatabase; | ||
| 388 | |||
| 389 | return ($databaseEnabledByDefault && !$this->currentTestDisablesDatabase()) | ||
| 390 | || $this->currentTestEnablesDatabase(); | ||
| 391 | } | ||
| 392 | |||
| 393 | /** | ||
| 394 | * Helper method to check, if the current test uses the database. | ||
| 395 | * This can be switched on with the annotation "@useDatabase" | ||
| 396 | * | ||
| 397 | * @return bool | ||
| 398 | */ | ||
| 399 | protected function currentTestEnablesDatabase() | ||
| 400 |         { | ||
| 401 | $annotations = $this->getAnnotations(); | ||
| 402 | |||
| 403 |             return array_key_exists('useDatabase', $annotations['method']) | ||
| 404 | && $annotations['method']['useDatabase'][0] !== 'false'; | ||
| 405 | } | ||
| 406 | |||
| 407 | /** | ||
| 408 | * Helper method to check, if the current test uses the database. | ||
| 409 | * This can be switched on with the annotation "@useDatabase false" | ||
| 410 | * | ||
| 411 | * @return bool | ||
| 412 | */ | ||
| 413 | protected function currentTestDisablesDatabase() | ||
| 414 |         { | ||
| 415 | $annotations = $this->getAnnotations(); | ||
| 416 | |||
| 417 |             return array_key_exists('useDatabase', $annotations['method']) | ||
| 418 | && $annotations['method']['useDatabase'][0] === 'false'; | ||
| 419 | } | ||
| 420 | |||
| 421 | /** | ||
| 422 |          * Called once per test case ({@link SapphireTest} subclass). | ||
| 423 |          * This is different to {@link setUp()}, which gets called once | ||
| 424 | * per method. Useful to initialize expensive operations which | ||
| 425 | * don't change state for any called method inside the test, | ||
| 426 |          * e.g. dynamically adding an extension. See {@link teardownAfterClass()} | ||
| 427 | * for tearing down the state again. | ||
| 428 | * | ||
| 429 | * Always sets up in order: | ||
| 430 | * - Reset php state | ||
| 431 | * - Nest | ||
| 432 | * - Custom state helpers | ||
| 433 | * | ||
| 434 | * User code should call parent::setUpBeforeClass() before custom setup code | ||
| 435 | * | ||
| 436 | * @throws Exception | ||
| 437 | */ | ||
| 438 | public static function setUpBeforeClass(): void | ||
| 439 |         { | ||
| 440 | // Start tests | ||
| 441 | static::start(); | ||
| 442 | |||
| 443 |             if (!static::$state) { | ||
| 444 |                 throw new Exception('SapphireTest failed to bootstrap!'); | ||
| 445 | } | ||
| 446 | |||
| 447 | // Call state helpers | ||
| 448 | static::$state->setUpOnce(static::class); | ||
| 449 | |||
| 450 | // Build DB if we have objects | ||
| 451 |             if (class_exists(DataObject::class) && static::getExtraDataObjects()) { | ||
| 452 | DataObject::reset(); | ||
| 453 | static::resetDBSchema(true, true); | ||
| 454 | } | ||
| 455 | } | ||
| 456 | |||
| 457 | /** | ||
| 458 | * tearDown method that's called once per test class rather once per test method. | ||
| 459 | * | ||
| 460 | * Always sets up in order: | ||
| 461 | * - Custom state helpers | ||
| 462 | * - Unnest | ||
| 463 | * - Reset php state | ||
| 464 | * | ||
| 465 | * User code should call parent::tearDownAfterClass() after custom tear down code | ||
| 466 | */ | ||
| 467 | public static function tearDownAfterClass(): void | ||
| 468 |         { | ||
| 469 | // Call state helpers | ||
| 470 | static::$state->tearDownOnce(static::class); | ||
| 471 | |||
| 472 | // Reset DB schema | ||
| 473 | static::resetDBSchema(); | ||
| 474 | } | ||
| 475 | |||
| 476 | /** | ||
| 477 | * @return FixtureFactory|false | ||
| 478 | * @deprecated 4.0.0:5.0.0 | ||
| 479 | */ | ||
| 480 | public function getFixtureFactory() | ||
| 481 |         { | ||
| 482 |             Deprecation::notice('5.0', __FUNCTION__ . ' is deprecated, use ' . FixtureTestState::class . ' instead'); | ||
| 483 | /** @var FixtureTestState $state */ | ||
| 484 |             $state = static::$state->getStateByName('fixtures'); | ||
| 485 | return $state->getFixtureFactory(static::class); | ||
| 486 | } | ||
| 487 | |||
| 488 | /** | ||
| 489 | * Sets a new fixture factory | ||
| 490 | * @param FixtureFactory $factory | ||
| 491 | * @return $this | ||
| 492 | * @deprecated 4.0.0:5.0.0 | ||
| 493 | */ | ||
| 494 | public function setFixtureFactory(FixtureFactory $factory) | ||
| 495 |         { | ||
| 496 |             Deprecation::notice('5.0', __FUNCTION__ . ' is deprecated, use ' . FixtureTestState::class . ' instead'); | ||
| 497 | /** @var FixtureTestState $state */ | ||
| 498 |             $state = static::$state->getStateByName('fixtures'); | ||
| 499 | $state->setFixtureFactory($factory, static::class); | ||
| 500 | $this->fixtureFactory = $factory; | ||
| 501 | return $this; | ||
| 502 | } | ||
| 503 | |||
| 504 | /** | ||
| 505 | * Get the ID of an object from the fixture. | ||
| 506 | * | ||
| 507 | * @param string $className The data class or table name, as specified in your fixture file. Parent classes won't work | ||
| 508 | * @param string $identifier The identifier string, as provided in your fixture file | ||
| 509 | * @return int | ||
| 510 | */ | ||
| 511 | protected function idFromFixture($className, $identifier) | ||
| 512 |         { | ||
| 513 | /** @var FixtureTestState $state */ | ||
| 514 |             $state = static::$state->getStateByName('fixtures'); | ||
| 515 | $id = $state->getFixtureFactory(static::class)->getId($className, $identifier); | ||
| 516 | |||
| 517 |             if (!$id) { | ||
| 518 | throw new InvalidArgumentException(sprintf( | ||
| 519 | "Couldn't find object '%s' (class: %s)", | ||
| 520 | $identifier, | ||
| 521 | $className | ||
| 522 | )); | ||
| 523 | } | ||
| 524 | |||
| 525 | return $id; | ||
| 526 | } | ||
| 527 | |||
| 528 | /** | ||
| 529 | * Return all of the IDs in the fixture of a particular class name. | ||
| 530 | * Will collate all IDs form all fixtures if multiple fixtures are provided. | ||
| 531 | * | ||
| 532 | * @param string $className The data class or table name, as specified in your fixture file | ||
| 533 | * @return array A map of fixture-identifier => object-id | ||
| 534 | */ | ||
| 535 | protected function allFixtureIDs($className) | ||
| 536 |         { | ||
| 537 | /** @var FixtureTestState $state */ | ||
| 538 |             $state = static::$state->getStateByName('fixtures'); | ||
| 539 | return $state->getFixtureFactory(static::class)->getIds($className); | ||
| 540 | } | ||
| 541 | |||
| 542 | /** | ||
| 543 | * Get an object from the fixture. | ||
| 544 | * | ||
| 545 | * @param string $className The data class or table name, as specified in your fixture file. Parent classes won't work | ||
| 546 | * @param string $identifier The identifier string, as provided in your fixture file | ||
| 547 | * | ||
| 548 | * @return DataObject | ||
| 549 | */ | ||
| 550 | protected function objFromFixture($className, $identifier) | ||
| 551 |         { | ||
| 552 | /** @var FixtureTestState $state */ | ||
| 553 |             $state = static::$state->getStateByName('fixtures'); | ||
| 554 | $obj = $state->getFixtureFactory(static::class)->get($className, $identifier); | ||
| 555 | |||
| 556 |             if (!$obj) { | ||
| 557 | throw new InvalidArgumentException(sprintf( | ||
| 558 | "Couldn't find object '%s' (class: %s)", | ||
| 559 | $identifier, | ||
| 560 | $className | ||
| 561 | )); | ||
| 562 | } | ||
| 563 | |||
| 564 | return $obj; | ||
| 565 | } | ||
| 566 | |||
| 567 | /** | ||
| 568 | * Load a YAML fixture file into the database. | ||
| 569 | * Once loaded, you can use idFromFixture() and objFromFixture() to get items from the fixture. | ||
| 570 | * Doesn't clear existing fixtures. | ||
| 571 | * @param string $fixtureFile The location of the .yml fixture file, relative to the site base dir | ||
| 572 | * @deprecated 4.0.0:5.0.0 | ||
| 573 | * | ||
| 574 | */ | ||
| 575 | public function loadFixture($fixtureFile) | ||
| 576 |         { | ||
| 577 |             Deprecation::notice('5.0', __FUNCTION__ . ' is deprecated, use ' . FixtureTestState::class . ' instead'); | ||
| 578 | $fixture = Injector::inst()->create(YamlFixture::class, $fixtureFile); | ||
| 579 | $fixture->writeInto($this->getFixtureFactory()); | ||
| 580 | } | ||
| 581 | |||
| 582 | /** | ||
| 583 | * Clear all fixtures which were previously loaded through | ||
| 584 |          * {@link loadFixture()} | ||
| 585 | */ | ||
| 586 | public function clearFixtures() | ||
| 587 |         { | ||
| 588 | /** @var FixtureTestState $state */ | ||
| 589 |             $state = static::$state->getStateByName('fixtures'); | ||
| 590 | $state->getFixtureFactory(static::class)->clear(); | ||
| 591 | } | ||
| 592 | |||
| 593 | /** | ||
| 594 | * Useful for writing unit tests without hardcoding folder structures. | ||
| 595 | * | ||
| 596 | * @return string Absolute path to current class. | ||
| 597 | */ | ||
| 598 | protected function getCurrentAbsolutePath() | ||
| 599 |         { | ||
| 600 | $filename = ClassLoader::inst()->getItemPath(static::class); | ||
| 601 |             if (!$filename) { | ||
| 602 |                 throw new LogicException('getItemPath returned null for ' . static::class | ||
| 603 | . '. Try adding flush=1 to the test run.'); | ||
| 604 | } | ||
| 605 | return dirname($filename); | ||
| 606 | } | ||
| 607 | |||
| 608 | /** | ||
| 609 | * @return string File path relative to webroot | ||
| 610 | */ | ||
| 611 | protected function getCurrentRelativePath() | ||
| 612 |         { | ||
| 613 | $base = Director::baseFolder(); | ||
| 614 | $path = $this->getCurrentAbsolutePath(); | ||
| 615 |             if (substr($path, 0, strlen($base)) == $base) { | ||
| 616 |                 $path = preg_replace('/^\/*/', '', substr($path, strlen($base))); | ||
| 617 | } | ||
| 618 | return $path; | ||
| 619 | } | ||
| 620 | |||
| 621 | /** | ||
| 622 | * Setup the test. | ||
| 623 | * Always sets up in order: | ||
| 624 | * - Custom state helpers | ||
| 625 | * - Unnest | ||
| 626 | * - Reset php state | ||
| 627 | * | ||
| 628 | * User code should call parent::tearDown() after custom tear down code | ||
| 629 | */ | ||
| 630 | protected function tearDown(): void | ||
| 631 |         { | ||
| 632 | // Reset mocked datetime | ||
| 633 |             if (class_exists(DBDatetime::class)) { | ||
| 634 | DBDatetime::clear_mock_now(); | ||
| 635 | } | ||
| 636 | |||
| 637 | // Stop the redirection that might have been requested in the test. | ||
| 638 | // Note: Ideally a clean Controller should be created for each test. | ||
| 639 | // Now all tests executed in a batch share the same controller. | ||
| 640 |             if (class_exists(Controller::class)) { | ||
| 641 | $controller = Controller::has_curr() ? Controller::curr() : null; | ||
| 642 |                 if ($controller && ($response = $controller->getResponse()) && $response->getHeader('Location')) { | ||
| 643 | $response->setStatusCode(200); | ||
| 644 |                     $response->removeHeader('Location'); | ||
| 645 | } | ||
| 646 | } | ||
| 647 | |||
| 648 | // Call state helpers | ||
| 649 | static::$state->tearDown($this); | ||
| 650 | } | ||
| 651 | |||
| 652 | // public static function assertContains( | ||
| 653 | // $needle, | ||
| 654 | // $haystack, | ||
| 655 | // $message = '', | ||
| 656 | // $ignoreCase = false, | ||
| 657 | // $checkForObjectIdentity = true, | ||
| 658 | // $checkForNonObjectIdentity = false | ||
| 659 |         // ): void { | ||
| 660 |         //     if ($haystack instanceof DBField) { | ||
| 661 | // $haystack = (string)$haystack; | ||
| 662 | // } | ||
| 663 |         //     if (is_iterable($haystack)) { | ||
| 664 | // $strict = is_object($needle) ? $checkForObjectIdentity : $checkForNonObjectIdentity; | ||
| 665 |         //         if ($strict) { | ||
| 666 | // parent::assertContains($needle, $haystack, $message); | ||
| 667 |         //         } else { | ||
| 668 | // parent::assertContainsEquals($needle, $haystack, $message); | ||
| 669 | // } | ||
| 670 |         //     } else { | ||
| 671 | // static::assertContainsNonIterable($needle, $haystack, $message, $ignoreCase); | ||
| 672 | // } | ||
| 673 | // } | ||
| 674 | |||
| 675 | // public static function assertContainsNonIterable( | ||
| 676 | // $needle, | ||
| 677 | // $haystack, | ||
| 678 | // $message = '', | ||
| 679 | // $ignoreCase = false | ||
| 680 |         // ): void { | ||
| 681 |         //     if ($haystack instanceof DBField) { | ||
| 682 | // $haystack = (string)$haystack; | ||
| 683 | // } | ||
| 684 |         //     if ($ignoreCase) { | ||
| 685 | // parent::assertStringContainsStringIgnoringCase($needle, $haystack, $message); | ||
| 686 |         //     } else { | ||
| 687 | // parent::assertStringContainsString($needle, $haystack, $message); | ||
| 688 | // } | ||
| 689 | // } | ||
| 690 | |||
| 691 | // public static function assertNotContains( | ||
| 692 | // $needle, | ||
| 693 | // $haystack, | ||
| 694 | // $message = '', | ||
| 695 | // $ignoreCase = false, | ||
| 696 | // $checkForObjectIdentity = true, | ||
| 697 | // $checkForNonObjectIdentity = false | ||
| 698 |         // ): void { | ||
| 699 |         //     if ($haystack instanceof DBField) { | ||
| 700 | // $haystack = (string)$haystack; | ||
| 701 | // } | ||
| 702 |         //     if (is_iterable($haystack)) { | ||
| 703 | // $strict = is_object($needle) ? $checkForObjectIdentity : $checkForNonObjectIdentity; | ||
| 704 |         //         if ($strict) { | ||
| 705 | // parent::assertNotContains($needle, $haystack, $message); | ||
| 706 |         //         } else { | ||
| 707 | // parent::assertNotContainsEquals($needle, $haystack, $message); | ||
| 708 | // } | ||
| 709 |         //     } else { | ||
| 710 | // static::assertNotContainsNonIterable($needle, $haystack, $message, $ignoreCase); | ||
| 711 | // } | ||
| 712 | // } | ||
| 713 | |||
| 714 | // protected static function assertNotContainsNonIterable( | ||
| 715 | // $needle, | ||
| 716 | // $haystack, | ||
| 717 | // $message = '', | ||
| 718 | // $ignoreCase = false | ||
| 719 |         // ): void { | ||
| 720 |         //     if ($haystack instanceof DBField) { | ||
| 721 | // $haystack = (string)$haystack; | ||
| 722 | // } | ||
| 723 |         //     if ($ignoreCase) { | ||
| 724 | // parent::assertStringNotContainsStringIgnoringCase($needle, $haystack, $message); | ||
| 725 |         //     } else { | ||
| 726 | // parent::assertStringNotContainsString($needle, $haystack, $message); | ||
| 727 | // } | ||
| 728 | // } | ||
| 729 | |||
| 730 | // /** | ||
| 731 | // * Backwards compatibility for core tests | ||
| 732 | // */ | ||
| 733 | // public static function assertInternalType($expected, $actual, $message = '') | ||
| 734 |         // { | ||
| 735 |         //     switch ($expected) { | ||
| 736 | // case 'numeric': | ||
| 737 | // static::assertIsNumeric($actual, $message); | ||
| 738 | // return; | ||
| 739 | // case 'integer': | ||
| 740 | // case 'int': | ||
| 741 | // static::assertIsInt($actual, $message); | ||
| 742 | // return; | ||
| 743 | // case 'double': | ||
| 744 | // case 'float': | ||
| 745 | // case 'real': | ||
| 746 | // static::assertIsFloat($actual, $message); | ||
| 747 | // return; | ||
| 748 | // case 'string': | ||
| 749 | // static::assertIsString($actual, $message); | ||
| 750 | // return; | ||
| 751 | // case 'boolean': | ||
| 752 | // case 'bool': | ||
| 753 | // static::assertIsBool($actual, $message); | ||
| 754 | // return; | ||
| 755 | // case 'null': | ||
| 756 | // static::assertTrue(is_null($actual), $message); | ||
| 757 | // return; | ||
| 758 | // case 'array': | ||
| 759 | // static::assertIsArray($actual, $message); | ||
| 760 | // return; | ||
| 761 | // case 'object': | ||
| 762 | // static::assertIsObject($actual, $message); | ||
| 763 | // return; | ||
| 764 | // case 'resource': | ||
| 765 | // static::assertIsResource($actual, $message); | ||
| 766 | // return; | ||
| 767 | // case 'resource (closed)': | ||
| 768 | // static::assertIsClosedResource($actual, $message); | ||
| 769 | // return; | ||
| 770 | // case 'scalar': | ||
| 771 | // static::assertIsScalar($actual, $message); | ||
| 772 | // return; | ||
| 773 | // case 'callable': | ||
| 774 | // static::assertIsCallable($actual, $message); | ||
| 775 | // return; | ||
| 776 | // case 'iterable': | ||
| 777 | // static::assertIsIterable($actual, $message); | ||
| 778 | // return; | ||
| 779 | // default: | ||
| 780 | // return false; | ||
| 781 | // } | ||
| 782 | // } | ||
| 783 | |||
| 784 | /** | ||
| 785 | * Clear the log of emails sent | ||
| 786 | * | ||
| 787 | * @return bool True if emails cleared | ||
| 788 | */ | ||
| 789 | public function clearEmails() | ||
| 790 |         { | ||
| 791 | /** @var Mailer $mailer */ | ||
| 792 | $mailer = Injector::inst()->get(Mailer::class); | ||
| 793 |             if ($mailer instanceof TestMailer) { | ||
| 794 | $mailer->clearEmails(); | ||
| 795 | return true; | ||
| 796 | } | ||
| 797 | return false; | ||
| 798 | } | ||
| 799 | |||
| 800 | /** | ||
| 801 | * Search for an email that was sent. | ||
| 802 | * All of the parameters can either be a string, or, if they start with "/", a PREG-compatible regular expression. | ||
| 803 | * @param string $to | ||
| 804 | * @param string $from | ||
| 805 | * @param string $subject | ||
| 806 | * @param string $content | ||
| 807 | * @return array|null Contains keys: 'Type', 'To', 'From', 'Subject', 'Content', 'PlainContent', 'AttachedFiles', | ||
| 808 | * 'HtmlContent' | ||
| 809 | */ | ||
| 810 | public static function findEmail($to, $from = null, $subject = null, $content = null) | ||
| 811 |         { | ||
| 812 | /** @var Mailer $mailer */ | ||
| 813 | $mailer = Injector::inst()->get(Mailer::class); | ||
| 814 |             if ($mailer instanceof TestMailer) { | ||
| 815 | return $mailer->findEmail($to, $from, $subject, $content); | ||
| 816 | } | ||
| 817 | return null; | ||
| 818 | } | ||
| 819 | |||
| 820 | /** | ||
| 821 | * Assert that the matching email was sent since the last call to clearEmails() | ||
| 822 | * All of the parameters can either be a string, or, if they start with "/", a PREG-compatible regular expression. | ||
| 823 | * | ||
| 824 | * @param string $to | ||
| 825 | * @param string $from | ||
| 826 | * @param string $subject | ||
| 827 | * @param string $content | ||
| 828 | */ | ||
| 829 | public static function assertEmailSent($to, $from = null, $subject = null, $content = null) | ||
| 830 |         { | ||
| 831 | $found = (bool)static::findEmail($to, $from, $subject, $content); | ||
| 832 | |||
| 833 | $infoParts = ''; | ||
| 834 | $withParts = []; | ||
| 835 |             if ($to) { | ||
| 836 | $infoParts .= " to '$to'"; | ||
| 837 | } | ||
| 838 |             if ($from) { | ||
| 839 | $infoParts .= " from '$from'"; | ||
| 840 | } | ||
| 841 |             if ($subject) { | ||
| 842 | $withParts[] = "subject '$subject'"; | ||
| 843 | } | ||
| 844 |             if ($content) { | ||
| 845 | $withParts[] = "content '$content'"; | ||
| 846 | } | ||
| 847 |             if ($withParts) { | ||
| 848 |                 $infoParts .= ' with ' . implode(' and ', $withParts); | ||
| 849 | } | ||
| 850 | |||
| 851 | static::assertTrue( | ||
| 852 | $found, | ||
| 853 | "Failed asserting that an email was sent$infoParts." | ||
| 854 | ); | ||
| 855 | } | ||
| 856 | |||
| 857 | |||
| 858 | /** | ||
| 859 |          * Assert that the given {@link SS_List} includes DataObjects matching the given key-value | ||
| 860 | * pairs. Each match must correspond to 1 distinct record. | ||
| 861 | * | ||
| 862 | * @param SS_List|array $matches The patterns to match. Each pattern is a map of key-value pairs. You can | ||
| 863 | * either pass a single pattern or an array of patterns. | ||
| 864 |          * @param SS_List $list The {@link SS_List} to test. | ||
| 865 | * @param string $message | ||
| 866 | * | ||
| 867 | * Examples | ||
| 868 | * -------- | ||
| 869 | * Check that $members includes an entry with Email = [email protected]: | ||
| 870 | * $this->assertListContains(['Email' => '[email protected]'], $members); | ||
| 871 | * | ||
| 872 | * Check that $members includes entries with Email = [email protected] and with | ||
| 873 | * Email = [email protected]: | ||
| 874 | * $this->assertListContains([ | ||
| 875 | * ['Email' => '[email protected]'], | ||
| 876 | * ['Email' => '[email protected]'], | ||
| 877 | * ], $members); | ||
| 878 | */ | ||
| 879 | public static function assertListContains($matches, SS_List $list, $message = '') | ||
| 880 |         { | ||
| 881 |             if (!is_array($matches)) { | ||
| 882 | throw self::createInvalidArgumentException( | ||
| 883 | 1, | ||
| 884 | 'array' | ||
| 885 | ); | ||
| 886 | } | ||
| 887 | |||
| 888 | static::assertThat( | ||
| 889 | $list, | ||
| 890 | new SSListContains( | ||
| 891 | $matches | ||
| 892 | ), | ||
| 893 | $message | ||
| 894 | ); | ||
| 895 | } | ||
| 896 | |||
| 897 | /** | ||
| 898 | * @param $matches | ||
| 899 | * @param $dataObjectSet | ||
| 900 | * @deprecated 4.0.0:5.0.0 Use assertListContains() instead | ||
| 901 | * | ||
| 902 | */ | ||
| 903 | public function assertDOSContains($matches, $dataObjectSet) | ||
| 904 |         { | ||
| 905 |             Deprecation::notice('5.0', 'Use assertListContains() instead'); | ||
| 906 | static::assertListContains($matches, $dataObjectSet); | ||
| 907 | } | ||
| 908 | |||
| 909 | /** | ||
| 910 | * Asserts that no items in a given list appear in the given dataobject list | ||
| 911 | * | ||
| 912 | * @param SS_List|array $matches The patterns to match. Each pattern is a map of key-value pairs. You can | ||
| 913 | * either pass a single pattern or an array of patterns. | ||
| 914 |          * @param SS_List $list The {@link SS_List} to test. | ||
| 915 | * @param string $message | ||
| 916 | * | ||
| 917 | * Examples | ||
| 918 | * -------- | ||
| 919 | * Check that $members doesn't have an entry with Email = [email protected]: | ||
| 920 | * $this->assertListNotContains(['Email' => '[email protected]'], $members); | ||
| 921 | * | ||
| 922 | * Check that $members doesn't have entries with Email = [email protected] and with | ||
| 923 | * Email = [email protected]: | ||
| 924 | * $this->assertListNotContains([ | ||
| 925 | * ['Email' => '[email protected]'], | ||
| 926 | * ['Email' => '[email protected]'], | ||
| 927 | * ], $members); | ||
| 928 | */ | ||
| 929 | public static function assertListNotContains($matches, SS_List $list, $message = '') | ||
| 930 |         { | ||
| 931 |             if (!is_array($matches)) { | ||
| 932 | throw self::createInvalidArgumentException( | ||
| 933 | 1, | ||
| 934 | 'array' | ||
| 935 | ); | ||
| 936 | } | ||
| 937 | |||
| 938 | $constraint = new LogicalNot( | ||
| 939 | new SSListContains( | ||
| 940 | $matches | ||
| 941 | ) | ||
| 942 | ); | ||
| 943 | |||
| 944 | static::assertThat( | ||
| 945 | $list, | ||
| 946 | $constraint, | ||
| 947 | $message | ||
| 948 | ); | ||
| 949 | } | ||
| 950 | |||
| 951 | /** | ||
| 952 | * @param $matches | ||
| 953 | * @param $dataObjectSet | ||
| 954 | * @deprecated 4.0.0:5.0.0 Use assertListNotContains() instead | ||
| 955 | * | ||
| 956 | */ | ||
| 957 | public static function assertNotDOSContains($matches, $dataObjectSet) | ||
| 958 |         { | ||
| 959 |             Deprecation::notice('5.0', 'Use assertListNotContains() instead'); | ||
| 960 | static::assertListNotContains($matches, $dataObjectSet); | ||
| 961 | } | ||
| 962 | |||
| 963 | /** | ||
| 964 |          * Assert that the given {@link SS_List} includes only DataObjects matching the given | ||
| 965 | * key-value pairs. Each match must correspond to 1 distinct record. | ||
| 966 | * | ||
| 967 | * Example | ||
| 968 | * -------- | ||
| 969 | * Check that *only* the entries Sam Minnee and Ingo Schommer exist in $members. Order doesn't | ||
| 970 | * matter: | ||
| 971 | * $this->assertListEquals([ | ||
| 972 | * ['FirstName' =>'Sam', 'Surname' => 'Minnee'], | ||
| 973 | * ['FirstName' => 'Ingo', 'Surname' => 'Schommer'], | ||
| 974 | * ], $members); | ||
| 975 | * | ||
| 976 | * @param mixed $matches The patterns to match. Each pattern is a map of key-value pairs. You can | ||
| 977 | * either pass a single pattern or an array of patterns. | ||
| 978 |          * @param mixed $list The {@link SS_List} to test. | ||
| 979 | * @param string $message | ||
| 980 | */ | ||
| 981 | public static function assertListEquals($matches, SS_List $list, $message = '') | ||
| 982 |         { | ||
| 983 |             if (!is_array($matches)) { | ||
| 984 | throw self::createInvalidArgumentException( | ||
| 985 | 1, | ||
| 986 | 'array' | ||
| 987 | ); | ||
| 988 | } | ||
| 989 | |||
| 990 | static::assertThat( | ||
| 991 | $list, | ||
| 992 | new SSListContainsOnly( | ||
| 993 | $matches | ||
| 994 | ), | ||
| 995 | $message | ||
| 996 | ); | ||
| 997 | } | ||
| 998 | |||
| 999 | /** | ||
| 1000 | * @param $matches | ||
| 1001 | * @param SS_List $dataObjectSet | ||
| 1002 | * @deprecated 4.0.0:5.0.0 Use assertListEquals() instead | ||
| 1003 | * | ||
| 1004 | */ | ||
| 1005 | public function assertDOSEquals($matches, $dataObjectSet) | ||
| 1006 |         { | ||
| 1007 |             Deprecation::notice('5.0', 'Use assertListEquals() instead'); | ||
| 1008 | static::assertListEquals($matches, $dataObjectSet); | ||
| 1009 | } | ||
| 1010 | |||
| 1011 | |||
| 1012 | /** | ||
| 1013 |          * Assert that the every record in the given {@link SS_List} matches the given key-value | ||
| 1014 | * pairs. | ||
| 1015 | * | ||
| 1016 | * Example | ||
| 1017 | * -------- | ||
| 1018 | * Check that every entry in $members has a Status of 'Active': | ||
| 1019 | * $this->assertListAllMatch(['Status' => 'Active'], $members); | ||
| 1020 | * | ||
| 1021 | * @param mixed $match The pattern to match. The pattern is a map of key-value pairs. | ||
| 1022 |          * @param mixed $list The {@link SS_List} to test. | ||
| 1023 | * @param string $message | ||
| 1024 | */ | ||
| 1025 | public static function assertListAllMatch($match, SS_List $list, $message = '') | ||
| 1026 |         { | ||
| 1027 |             if (!is_array($match)) { | ||
| 1028 | throw self::createInvalidArgumentException( | ||
| 1029 | 1, | ||
| 1030 | 'array' | ||
| 1031 | ); | ||
| 1032 | } | ||
| 1033 | |||
| 1034 | static::assertThat( | ||
| 1035 | $list, | ||
| 1036 | new SSListContainsOnlyMatchingItems( | ||
| 1037 | $match | ||
| 1038 | ), | ||
| 1039 | $message | ||
| 1040 | ); | ||
| 1041 | } | ||
| 1042 | |||
| 1043 | /** | ||
| 1044 | * @param $match | ||
| 1045 | * @param SS_List $dataObjectSet | ||
| 1046 | * @deprecated 4.0.0:5.0.0 Use assertListAllMatch() instead | ||
| 1047 | * | ||
| 1048 | */ | ||
| 1049 | public function assertDOSAllMatch($match, SS_List $dataObjectSet) | ||
| 1050 |         { | ||
| 1051 |             Deprecation::notice('5.0', 'Use assertListAllMatch() instead'); | ||
| 1052 | static::assertListAllMatch($match, $dataObjectSet); | ||
| 1053 | } | ||
| 1054 | |||
| 1055 | /** | ||
| 1056 | * Removes sequences of repeated whitespace characters from SQL queries | ||
| 1057 | * making them suitable for string comparison | ||
| 1058 | * | ||
| 1059 | * @param string $sql | ||
| 1060 | * @return string The cleaned and normalised SQL string | ||
| 1061 | */ | ||
| 1062 | protected static function normaliseSQL($sql) | ||
| 1063 |         { | ||
| 1064 |             return trim(preg_replace('/\s+/m', ' ', $sql)); | ||
| 1065 | } | ||
| 1066 | |||
| 1067 | /** | ||
| 1068 | * Asserts that two SQL queries are equivalent | ||
| 1069 | * | ||
| 1070 | * @param string $expectedSQL | ||
| 1071 | * @param string $actualSQL | ||
| 1072 | * @param string $message | ||
| 1073 | * @param float|int $delta | ||
| 1074 | * @param integer $maxDepth | ||
| 1075 | * @param boolean $canonicalize | ||
| 1076 | * @param boolean $ignoreCase | ||
| 1077 | */ | ||
| 1078 | public static function assertSQLEquals( | ||
| 1079 | $expectedSQL, | ||
| 1080 | $actualSQL, | ||
| 1081 | $message = '' | ||
| 1082 |         ) { | ||
| 1083 | // Normalise SQL queries to remove patterns of repeating whitespace | ||
| 1084 | $expectedSQL = static::normaliseSQL($expectedSQL); | ||
| 1085 | $actualSQL = static::normaliseSQL($actualSQL); | ||
| 1086 | |||
| 1087 | static::assertEquals($expectedSQL, $actualSQL, $message); | ||
| 1088 | } | ||
| 1089 | |||
| 1090 | /** | ||
| 1091 | * Asserts that a SQL query contains a SQL fragment | ||
| 1092 | * | ||
| 1093 | * @param string $needleSQL | ||
| 1094 | * @param string $haystackSQL | ||
| 1095 | * @param string $message | ||
| 1096 | * @param boolean $ignoreCase | ||
| 1097 | * @param boolean $checkForObjectIdentity | ||
| 1098 | */ | ||
| 1099 | public static function assertSQLContains( | ||
| 1100 | $needleSQL, | ||
| 1101 | $haystackSQL, | ||
| 1102 | $message = '', | ||
| 1103 | $ignoreCase = false, | ||
| 1104 | $checkForObjectIdentity = true | ||
| 1105 |         ) { | ||
| 1106 | $needleSQL = static::normaliseSQL($needleSQL); | ||
| 1107 | $haystackSQL = static::normaliseSQL($haystackSQL); | ||
| 1108 |             if (is_iterable($haystackSQL)) { | ||
| 1109 | /** @var iterable $iterableHaystackSQL */ | ||
| 1110 | $iterableHaystackSQL = $haystackSQL; | ||
| 1111 | static::assertContains($needleSQL, $iterableHaystackSQL, $message, $ignoreCase, $checkForObjectIdentity); | ||
| 1112 |             } else { | ||
| 1113 | static::assertContainsNonIterable($needleSQL, $haystackSQL, $message, $ignoreCase); | ||
| 1114 | } | ||
| 1115 | } | ||
| 1116 | |||
| 1117 | /** | ||
| 1118 | * Asserts that a SQL query contains a SQL fragment | ||
| 1119 | * | ||
| 1120 | * @param string $needleSQL | ||
| 1121 | * @param string $haystackSQL | ||
| 1122 | * @param string $message | ||
| 1123 | * @param boolean $ignoreCase | ||
| 1124 | * @param boolean $checkForObjectIdentity | ||
| 1125 | */ | ||
| 1126 | public static function assertSQLNotContains( | ||
| 1127 | $needleSQL, | ||
| 1128 | $haystackSQL, | ||
| 1129 | $message = '', | ||
| 1130 | $ignoreCase = false, | ||
| 1131 | $checkForObjectIdentity = true | ||
| 1132 |         ) { | ||
| 1133 | $needleSQL = static::normaliseSQL($needleSQL); | ||
| 1134 | $haystackSQL = static::normaliseSQL($haystackSQL); | ||
| 1135 |             if (is_iterable($haystackSQL)) { | ||
| 1136 | /** @var iterable $iterableHaystackSQL */ | ||
| 1137 | $iterableHaystackSQL = $haystackSQL; | ||
| 1138 | static::assertNotContains($needleSQL, $iterableHaystackSQL, $message, $ignoreCase, $checkForObjectIdentity); | ||
| 1139 |             } else { | ||
| 1140 | static::assertNotContainsNonIterable($needleSQL, $haystackSQL, $message, $ignoreCase); | ||
| 1141 | } | ||
| 1142 | } | ||
| 1143 | |||
| 1144 | /** | ||
| 1145 | * Start test environment | ||
| 1146 | */ | ||
| 1147 | public static function start() | ||
| 1148 |         { | ||
| 1149 |             if (static::is_running_test()) { | ||
| 1150 | return; | ||
| 1151 | } | ||
| 1152 | |||
| 1153 | // Health check | ||
| 1154 |             if (InjectorLoader::inst()->countManifests()) { | ||
| 1155 |                 throw new LogicException('SapphireTest::start() cannot be called within another application'); | ||
| 1156 | } | ||
| 1157 | static::set_is_running_test(true); | ||
| 1158 | |||
| 1159 | // Test application | ||
| 1160 | $kernel = new TestKernel(BASE_PATH); | ||
| 1161 | |||
| 1162 |             if (class_exists(HTTPApplication::class)) { | ||
| 1163 | // Mock request | ||
| 1164 | $_SERVER['argv'] = ['vendor/bin/phpunit', '/']; | ||
| 1165 | $request = CLIRequestBuilder::createFromEnvironment(); | ||
| 1166 | |||
| 1167 | $app = new HTTPApplication($kernel); | ||
| 1168 |                 $flush = array_key_exists('flush', $request->getVars()); | ||
| 1169 | |||
| 1170 | // Custom application | ||
| 1171 |                 $res = $app->execute($request, function (HTTPRequest $request) { | ||
| 1172 | // Start session and execute | ||
| 1173 | $request->getSession()->init($request); | ||
| 1174 | |||
| 1175 | // Invalidate classname spec since the test manifest will now pull out new subclasses for each internal class | ||
| 1176 | // (e.g. Member will now have various subclasses of DataObjects that implement TestOnly) | ||
| 1177 | DataObject::reset(); | ||
| 1178 | |||
| 1179 | // Set dummy controller; | ||
| 1180 | $controller = Controller::create(); | ||
| 1181 | $controller->setRequest($request); | ||
| 1182 | $controller->pushCurrent(); | ||
| 1183 | $controller->doInit(); | ||
| 1184 | }, $flush); | ||
| 1185 | |||
| 1186 |                 if ($res && $res->isError()) { | ||
| 1187 | throw new LogicException($res->getBody()); | ||
| 1188 | } | ||
| 1189 |             } else { | ||
| 1190 | // Allow flush from the command line in the absence of HTTPApplication's special sauce | ||
| 1191 | $flush = false; | ||
| 1192 |                 foreach ($_SERVER['argv'] as $arg) { | ||
| 1193 |                     if (preg_match('/^(--)?flush(=1)?$/', $arg)) { | ||
| 1194 | $flush = true; | ||
| 1195 | } | ||
| 1196 | } | ||
| 1197 | $kernel->boot($flush); | ||
| 1198 | } | ||
| 1199 | |||
| 1200 | // Register state | ||
| 1201 | static::$state = SapphireTestState::singleton(); | ||
| 1202 | // Register temp DB holder | ||
| 1203 | static::tempDB(); | ||
| 1204 | } | ||
| 1205 | |||
| 1206 | /** | ||
| 1207 | * Reset the testing database's schema, but only if it is active | ||
| 1208 | * @param bool $includeExtraDataObjects If true, the extraDataObjects tables will also be included | ||
| 1209 | * @param bool $forceCreate Force DB to be created if it doesn't exist | ||
| 1210 | */ | ||
| 1211 | public static function resetDBSchema($includeExtraDataObjects = false, $forceCreate = false) | ||
| 1212 |         { | ||
| 1213 |             if (!static::$tempDB) { | ||
| 1214 | return; | ||
| 1215 | } | ||
| 1216 | |||
| 1217 | // Check if DB is active before reset | ||
| 1218 |             if (!static::$tempDB->isUsed()) { | ||
| 1219 |                 if (!$forceCreate) { | ||
| 1220 | return; | ||
| 1221 | } | ||
| 1222 | static::$tempDB->build(); | ||
| 1223 | } | ||
| 1224 | $extraDataObjects = $includeExtraDataObjects ? static::getExtraDataObjects() : []; | ||
| 1225 | static::$tempDB->resetDBSchema((array)$extraDataObjects); | ||
| 1226 | } | ||
| 1227 | |||
| 1228 | /** | ||
| 1229 | * A wrapper for automatically performing callbacks as a user with a specific permission | ||
| 1230 | * | ||
| 1231 | * @param string|array $permCode | ||
| 1232 | * @param callable $callback | ||
| 1233 | * @return mixed | ||
| 1234 | */ | ||
| 1235 | public function actWithPermission($permCode, $callback) | ||
| 1236 |         { | ||
| 1237 | return Member::actAs($this->createMemberWithPermission($permCode), $callback); | ||
| 1238 | } | ||
| 1239 | |||
| 1240 | /** | ||
| 1241 | * Create Member and Group objects on demand with specific permission code | ||
| 1242 | * | ||
| 1243 | * @param string|array $permCode | ||
| 1244 | * @return Member | ||
| 1245 | */ | ||
| 1246 | protected function createMemberWithPermission($permCode) | ||
| 1247 |         { | ||
| 1248 |             if (is_array($permCode)) { | ||
| 1249 | $permArray = $permCode; | ||
| 1250 |                 $permCode = implode('.', $permCode); | ||
| 1251 |             } else { | ||
| 1252 | $permArray = [$permCode]; | ||
| 1253 | } | ||
| 1254 | |||
| 1255 | // Check cached member | ||
| 1256 |             if (isset($this->cache_generatedMembers[$permCode])) { | ||
| 1257 | $member = $this->cache_generatedMembers[$permCode]; | ||
| 1258 |             } else { | ||
| 1259 | // Generate group with these permissions | ||
| 1260 | $group = Group::create(); | ||
| 1261 | $group->Title = "$permCode group"; | ||
| 1262 | $group->write(); | ||
| 1263 | |||
| 1264 | // Create each individual permission | ||
| 1265 |                 foreach ($permArray as $permArrayItem) { | ||
| 1266 | $permission = Permission::create(); | ||
| 1267 | $permission->Code = $permArrayItem; | ||
| 1268 | $permission->write(); | ||
| 1269 | $group->Permissions()->add($permission); | ||
| 1270 | } | ||
| 1271 | |||
| 1272 | $member = Member::get()->filter([ | ||
| 1273 | 'Email' => "[email protected]", | ||
| 1274 | ])->first(); | ||
| 1275 |                 if (!$member) { | ||
| 1276 | $member = Member::create(); | ||
| 1277 | } | ||
| 1278 | |||
| 1279 | $member->FirstName = $permCode; | ||
| 1280 | $member->Surname = 'User'; | ||
| 1281 | $member->Email = "[email protected]"; | ||
| 1282 | $member->write(); | ||
| 1283 | $group->Members()->add($member); | ||
| 1284 | |||
| 1285 | $this->cache_generatedMembers[$permCode] = $member; | ||
| 1286 | } | ||
| 1287 | return $member; | ||
| 1288 | } | ||
| 1289 | |||
| 1290 | /** | ||
| 1291 | * Create a member and group with the given permission code, and log in with it. | ||
| 1292 | * Returns the member ID. | ||
| 1293 | * | ||
| 1294 | * @param string|array $permCode Either a permission, or list of permissions | ||
| 1295 | * @return int Member ID | ||
| 1296 | */ | ||
| 1297 | public function logInWithPermission($permCode = 'ADMIN') | ||
| 1298 |         { | ||
| 1299 | $member = $this->createMemberWithPermission($permCode); | ||
| 1300 | $this->logInAs($member); | ||
| 1301 | return $member->ID; | ||
| 1302 | } | ||
| 1303 | |||
| 1304 | /** | ||
| 1305 | * Log in as the given member | ||
| 1306 | * | ||
| 1307 | * @param Member|int|string $member The ID, fixture codename, or Member object of the member that you want to log in | ||
| 1308 | */ | ||
| 1309 | public function logInAs($member) | ||
| 1310 |         { | ||
| 1311 |             if (is_numeric($member)) { | ||
| 1312 | $member = DataObject::get_by_id(Member::class, $member); | ||
| 1313 |             } elseif (!is_object($member)) { | ||
| 1314 | $member = $this->objFromFixture(Member::class, $member); | ||
| 1315 | } | ||
| 1316 | Injector::inst()->get(IdentityStore::class)->logIn($member); | ||
| 1317 | } | ||
| 1318 | |||
| 2878 |