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