-
Notifications
You must be signed in to change notification settings - Fork 825
/
Copy pathSapphireTest.php
2692 lines (2412 loc) · 86 KB
/
SapphireTest.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
<?php
namespace SilverStripe\Dev;
use Exception;
use InvalidArgumentException;
use LogicException;
use PHPUnit_Framework_Constraint_Not;
use PHPUnit_Extensions_GroupTestSuite;
use PHPUnit_Framework_Error;
use PHPUnit_Framework_Error_Warning;
use PHPUnit_Framework_Error_Notice;
use PHPUnit_Framework_Error_Deprecation;
use PHPUnit_Framework_TestCase;
use PHPUnit_Util_InvalidArgumentHelper;
use PHPUnit\Framework\Constraint\LogicalNot;
use PHPUnit\Framework\Constraint\IsEqualCanonicalizing;
use PHPUnit\Framework\TestCase;
use PHPUnit\Framework\Exception as PHPUnitFrameworkException;
use PHPUnit\Util\Test as TestUtil;
use SilverStripe\CMS\Controllers\RootURLController;
use SilverStripe\Control\CLIRequestBuilder;
use SilverStripe\Control\Controller;
use SilverStripe\Control\Cookie;
use SilverStripe\Control\Director;
use SilverStripe\Control\Email\Email;
use SilverStripe\Control\Email\Mailer;
use SilverStripe\Control\HTTPApplication;
use SilverStripe\Control\HTTPRequest;
use SilverStripe\Core\Config\Config;
use SilverStripe\Core\Injector\Injector;
use SilverStripe\Core\Injector\InjectorLoader;
use SilverStripe\Core\Manifest\ClassLoader;
use SilverStripe\Core\Manifest\Module;
use SilverStripe\Core\Manifest\ModuleResourceLoader;
use SilverStripe\Dev\Constraint\SSListContains;
use SilverStripe\Dev\Constraint\SSListContainsOnly;
use SilverStripe\Dev\Constraint\SSListContainsOnlyMatchingItems;
use SilverStripe\Dev\State\FixtureTestState;
use SilverStripe\Dev\State\SapphireTestState;
use SilverStripe\i18n\i18n;
use SilverStripe\ORM\Connect\TempDatabase;
use SilverStripe\ORM\DataObject;
use SilverStripe\ORM\FieldType\DBDatetime;
use SilverStripe\ORM\FieldType\DBField;
use SilverStripe\ORM\SS_List;
use SilverStripe\Security\Group;
use SilverStripe\Security\IdentityStore;
use SilverStripe\Security\Member;
use SilverStripe\Security\Permission;
use SilverStripe\Security\Security;
use SilverStripe\View\SSViewer;
use SilverStripe\Dev\Deprecation;
/* -------------------------------------------------
*
* This version of SapphireTest is for phpunit 9
* The PHPUnit 5 version is lower down in this file
* PHPUnit 6, 7 and 8 are not supported
*
* Why there are two versions of SapphireTest:
* - PHPUnit 5 is not compatible with PHP 8
* - a minimum version of PHP 7.3 is required for PHPUnit 9
*
* The PHPUnit-5 compatibility layer will be preserved until support for PHP7 is dropped in early 2023.
*
* The used on `if(class_exists()` and indentation ensure the the phpunit 5 version function
* signature is used by the php interprester. This is required because the phpunit5
* signature for `setUp()` has no return type while the phpunit 9 version has `setUp(): void`
* Return type covariance allows more specific return types to be defined, while contravariance
* of return types of more abstract return types is not supported
*
* IsEqualCanonicalizing::class is a new class added in PHPUnit 9, testing that this class exists
*
* -------------------------------------------------
*/
if (class_exists(IsEqualCanonicalizing::class)) {
/**
* Test case class for the Sapphire framework.
* Sapphire unit testing is based on PHPUnit, but provides a number of hooks into our data model that make it easier
* to work with.
*
* This class should not be used anywhere outside of unit tests, as phpunit may not be installed
* in production sites.
*/
// Ignore multiple classes in same file
// @codingStandardsIgnoreStart
class SapphireTest extends TestCase implements TestOnly
{
// @codingStandardsIgnoreEnd
/**
* Path to fixture data for this test run.
* If passed as an array, multiple fixture files will be loaded.
* Please note that you won't be able to refer with "=>" notation
* between the fixtures, they act independent of each other.
*
* @var string|array
*/
protected static $fixture_file = null;
/**
* @deprecated 4.0.1 Use FixtureTestState instead
* @var FixtureFactory
*/
protected $fixtureFactory;
/**
* @var Boolean If set to TRUE, this will force a test database to be generated
* in {@link setUp()}. Note that this flag is overruled by the presence of a
* {@link $fixture_file}, which always forces a database build.
*
* @var bool
*/
protected $usesDatabase = null;
/**
* This test will cleanup its state via transactions.
* If set to false a full schema is forced between tests, but at a performance cost.
*
* @var bool
*/
protected $usesTransactions = true;
/**
* @var bool
*/
protected static $is_running_test = false;
/**
* By default, setUp() does not require default records. Pass
* class names in here, and the require/augment default records
* function will be called on them.
*
* @var array
*/
protected $requireDefaultRecordsFrom = [];
/**
* A list of extensions that can't be applied during the execution of this run. If they are
* applied, they will be temporarily removed and a database migration called.
*
* The keys of the are the classes that the extensions can't be applied the extensions to, and
* the values are an array of illegal extensions on that class.
*
* Set a class to `*` to remove all extensions (unadvised)
*
* @var array
*/
protected static $illegal_extensions = [];
/**
* A list of extensions that must be applied during the execution of this run. If they are
* not applied, they will be temporarily added and a database migration called.
*
* The keys of the are the classes to apply the extensions to, and the values are an array
* of required extensions on that class.
*
* Example:
* <code>
* array("MyTreeDataObject" => array("Versioned", "Hierarchy"))
* </code>
*
* @var array
*/
protected static $required_extensions = [];
/**
* By default, the test database won't contain any DataObjects that have the interface TestOnly.
* This variable lets you define additional TestOnly DataObjects to set up for this test.
* Set it to an array of DataObject subclass names.
*
* @var array
*/
protected static $extra_dataobjects = [];
/**
* List of class names of {@see Controller} objects to register routes for
* Controllers must implement Link() method
*
* @var array
*/
protected static $extra_controllers = [];
/**
* We need to disabling backing up of globals to avoid overriding
* the few globals SilverStripe relies on, like $lang for the i18n subsystem.
*
* @see http://sebastian-bergmann.de/archives/797-Global-Variables-and-PHPUnit.html
*/
protected $backupGlobals = false;
/**
* State management container for SapphireTest
*
* @var SapphireTestState
*/
protected static $state = null;
/**
* Temp database helper
*
* @var TempDatabase
*/
protected static $tempDB = null;
/**
* @return TempDatabase
*/
public static function tempDB()
{
if (!class_exists(TempDatabase::class)) {
return null;
}
if (!static::$tempDB) {
static::$tempDB = TempDatabase::create();
}
return static::$tempDB;
}
/**
* Gets illegal extensions for this class
*
* @return array
*/
public static function getIllegalExtensions()
{
return static::$illegal_extensions;
}
/**
* Gets required extensions for this class
*
* @return array
*/
public static function getRequiredExtensions()
{
return static::$required_extensions;
}
/**
* Check if test bootstrapping has been performed. Must not be relied on
* outside of unit tests.
*
* @return bool
*/
protected static function is_running_test()
{
return self::$is_running_test;
}
/**
* Set test running state
*
* @param bool $bool
*/
protected static function set_is_running_test($bool)
{
self::$is_running_test = $bool;
}
/**
* @return String
*/
public static function get_fixture_file()
{
return static::$fixture_file;
}
/**
* @return bool
*/
public function getUsesDatabase()
{
return $this->usesDatabase;
}
/**
* @return bool
*/
public function getUsesTransactions()
{
return $this->usesTransactions;
}
/**
* @return array
*/
public function getRequireDefaultRecordsFrom()
{
return $this->requireDefaultRecordsFrom;
}
/**
* Setup the test.
* Always sets up in order:
* - Reset php state
* - Nest
* - Custom state helpers
*
* User code should call parent::setUp() before custom setup code
*/
protected function setUp(): void
{
if (!defined('FRAMEWORK_PATH')) {
trigger_error(
'Missing constants, did you remember to include the test bootstrap in your phpunit.xml file?',
E_USER_WARNING
);
}
// Call state helpers
static::$state->setUp($this);
// We cannot run the tests on this abstract class.
if (static::class == __CLASS__) {
$this->markTestSkipped(sprintf('Skipping %s ', static::class));
}
// i18n needs to be set to the defaults or tests fail
if (class_exists(i18n::class)) {
i18n::set_locale(i18n::config()->uninherited('default_locale'));
}
// Set default timezone consistently to avoid NZ-specific dependencies
date_default_timezone_set('UTC');
if (class_exists(Member::class)) {
Member::set_password_validator(null);
}
if (class_exists(Cookie::class)) {
Cookie::config()->set('report_errors', false);
}
if (class_exists(RootURLController::class)) {
RootURLController::reset();
}
if (class_exists(Security::class)) {
Security::clear_database_is_ready();
}
// Set up test routes
$this->setUpRoutes();
$fixtureFiles = $this->getFixturePaths();
if ($this->shouldSetupDatabaseForCurrentTest($fixtureFiles)) {
// Assign fixture factory to deprecated prop in case old tests use it over the getter
$this->logInWithPermission('ADMIN');
}
// turn off template debugging
if (class_exists(SSViewer::class)) {
SSViewer::config()->set('source_file_comments', false);
}
// Set up the test mailer
if (class_exists(TestMailer::class)) {
Injector::inst()->registerService(new TestMailer(), Mailer::class);
}
if (class_exists(Email::class)) {
Email::config()->remove('send_all_emails_to');
Email::config()->remove('send_all_emails_from');
Email::config()->remove('cc_all_emails_to');
Email::config()->remove('bcc_all_emails_to');
}
}
/**
* Helper method to determine if the current test should enable a test database
*
* @param $fixtureFiles
* @return bool
*/
protected function shouldSetupDatabaseForCurrentTest($fixtureFiles)
{
$databaseEnabledByDefault = $fixtureFiles || $this->usesDatabase;
return ($databaseEnabledByDefault && !$this->currentTestDisablesDatabase())
|| $this->currentTestEnablesDatabase();
}
/**
* Helper method to check, if the current test uses the database.
* This can be switched on with the annotation "@useDatabase"
*
* @return bool
*/
protected function currentTestEnablesDatabase()
{
$annotations = $this->getAnnotations();
return array_key_exists('useDatabase', $annotations['method'] ?? [])
&& $annotations['method']['useDatabase'][0] !== 'false';
}
/**
* Helper method to check, if the current test uses the database.
* This can be switched on with the annotation "@useDatabase false"
*
* @return bool
*/
protected function currentTestDisablesDatabase()
{
$annotations = $this->getAnnotations();
return array_key_exists('useDatabase', $annotations['method'] ?? [])
&& $annotations['method']['useDatabase'][0] === 'false';
}
/**
* Called once per test case ({@link SapphireTest} subclass).
* This is different to {@link setUp()}, which gets called once
* per method. Useful to initialize expensive operations which
* don't change state for any called method inside the test,
* e.g. dynamically adding an extension. See {@link teardownAfterClass()}
* for tearing down the state again.
*
* Always sets up in order:
* - Reset php state
* - Nest
* - Custom state helpers
*
* User code should call parent::setUpBeforeClass() before custom setup code
*
* @throws Exception
*/
public static function setUpBeforeClass(): void
{
// Start tests
static::start();
if (!static::$state) {
throw new Exception('SapphireTest failed to bootstrap!');
}
// Call state helpers
static::$state->setUpOnce(static::class);
// Build DB if we have objects
if (class_exists(DataObject::class) && static::getExtraDataObjects()) {
DataObject::reset();
static::resetDBSchema(true, true);
}
}
/**
* tearDown method that's called once per test class rather once per test method.
*
* Always sets up in order:
* - Custom state helpers
* - Unnest
* - Reset php state
*
* User code should call parent::tearDownAfterClass() after custom tear down code
*/
public static function tearDownAfterClass(): void
{
// Call state helpers
static::$state->tearDownOnce(static::class);
// Reset DB schema
static::resetDBSchema();
}
/**
* @return FixtureFactory|false
* @deprecated 4.0.1 Use FixtureTestState instead
*/
public function getFixtureFactory()
{
Deprecation::notice('4.0.1', 'Use FixtureTestState instead');
/** @var FixtureTestState $state */
$state = static::$state->getStateByName('fixtures');
return $state->getFixtureFactory(static::class);
}
/**
* Sets a new fixture factory
* @param FixtureFactory $factory
* @return $this
* @deprecated 4.0.1 Use FixtureTestState instead
*/
public function setFixtureFactory(FixtureFactory $factory)
{
Deprecation::notice('4.0.1', 'Use FixtureTestState instead');
/** @var FixtureTestState $state */
$state = static::$state->getStateByName('fixtures');
$state->setFixtureFactory($factory, static::class);
$this->fixtureFactory = $factory;
return $this;
}
/**
* Get the ID of an object from the fixture.
*
* @param string $className The data class or table name, as specified in your fixture file. Parent classes won't work
* @param string $identifier The identifier string, as provided in your fixture file
* @return int
*/
protected function idFromFixture($className, $identifier)
{
/** @var FixtureTestState $state */
$state = static::$state->getStateByName('fixtures');
$id = $state->getFixtureFactory(static::class)->getId($className, $identifier);
if (!$id) {
throw new InvalidArgumentException(sprintf(
"Couldn't find object '%s' (class: %s)",
$identifier,
$className
));
}
return $id;
}
/**
* Return all of the IDs in the fixture of a particular class name.
* Will collate all IDs form all fixtures if multiple fixtures are provided.
*
* @param string $className The data class or table name, as specified in your fixture file
* @return array A map of fixture-identifier => object-id
*/
protected function allFixtureIDs($className)
{
/** @var FixtureTestState $state */
$state = static::$state->getStateByName('fixtures');
return $state->getFixtureFactory(static::class)->getIds($className);
}
/**
* Get an object from the fixture.
*
* @param string $className The data class or table name, as specified in your fixture file. Parent classes won't work
* @param string $identifier The identifier string, as provided in your fixture file
*
* @return DataObject
*/
protected function objFromFixture($className, $identifier)
{
/** @var FixtureTestState $state */
$state = static::$state->getStateByName('fixtures');
$obj = $state->getFixtureFactory(static::class)->get($className, $identifier);
if (!$obj) {
throw new InvalidArgumentException(sprintf(
"Couldn't find object '%s' (class: %s)",
$identifier,
$className
));
}
return $obj;
}
/**
* Load a YAML fixture file into the database.
* Once loaded, you can use idFromFixture() and objFromFixture() to get items from the fixture.
* Doesn't clear existing fixtures.
* @param string $fixtureFile The location of the .yml fixture file, relative to the site base dir
* @deprecated 4.0.1 Use FixtureTestState instead
*/
public function loadFixture($fixtureFile)
{
Deprecation::notice('4.0.1', 'Use FixtureTestState instead');
$fixture = Injector::inst()->create(YamlFixture::class, $fixtureFile);
Deprecation::withNoReplacement(function () use ($fixture) {
$fixture->writeInto($this->getFixtureFactory());
});
}
/**
* Clear all fixtures which were previously loaded through
* {@link loadFixture()}
*/
public function clearFixtures()
{
/** @var FixtureTestState $state */
$state = static::$state->getStateByName('fixtures');
$state->getFixtureFactory(static::class)->clear();
}
/**
* Useful for writing unit tests without hardcoding folder structures.
*
* @return string Absolute path to current class.
*/
protected function getCurrentAbsolutePath()
{
$filename = ClassLoader::inst()->getItemPath(static::class);
if (!$filename) {
throw new LogicException('getItemPath returned null for ' . static::class
. '. Try adding flush=1 to the test run.');
}
return dirname($filename ?? '');
}
/**
* @return string File path relative to webroot
*/
protected function getCurrentRelativePath()
{
$base = Director::baseFolder();
$path = $this->getCurrentAbsolutePath();
if (substr($path ?? '', 0, strlen($base ?? '')) == $base) {
$path = preg_replace('/^\/*/', '', substr($path ?? '', strlen($base ?? '')));
}
return $path;
}
/**
* Setup the test.
* Always sets up in order:
* - Custom state helpers
* - Unnest
* - Reset php state
*
* User code should call parent::tearDown() after custom tear down code
*/
protected function tearDown(): void
{
// Reset mocked datetime
if (class_exists(DBDatetime::class)) {
DBDatetime::clear_mock_now();
}
// Stop the redirection that might have been requested in the test.
// Note: Ideally a clean Controller should be created for each test.
// Now all tests executed in a batch share the same controller.
if (class_exists(Controller::class)) {
$controller = Controller::has_curr() ? Controller::curr() : null;
if ($controller && ($response = $controller->getResponse()) && $response->getHeader('Location')) {
$response->setStatusCode(200);
$response->removeHeader('Location');
}
}
// Call state helpers
static::$state->tearDown($this);
}
/**
* Clear the log of emails sent
*
* @return bool True if emails cleared
*/
public function clearEmails()
{
/** @var Mailer $mailer */
$mailer = Injector::inst()->get(Mailer::class);
if ($mailer instanceof TestMailer) {
$mailer->clearEmails();
return true;
}
return false;
}
/**
* Search for an email that was sent.
* All of the parameters can either be a string, or, if they start with "/", a PREG-compatible regular expression.
* @param string $to
* @param string $from
* @param string $subject
* @param string $content
* @return array|null Contains keys: 'Type', 'To', 'From', 'Subject', 'Content', 'PlainContent', 'AttachedFiles',
* 'HtmlContent'
*/
public static function findEmail($to, $from = null, $subject = null, $content = null)
{
/** @var Mailer $mailer */
$mailer = Injector::inst()->get(Mailer::class);
if ($mailer instanceof TestMailer) {
return $mailer->findEmail($to, $from, $subject, $content);
}
return null;
}
/**
* Assert that the matching email was sent since the last call to clearEmails()
* All of the parameters can either be a string, or, if they start with "/", a PREG-compatible regular expression.
*
* @param string $to
* @param string $from
* @param string $subject
* @param string $content
*/
public static function assertEmailSent($to, $from = null, $subject = null, $content = null)
{
$found = (bool)static::findEmail($to, $from, $subject, $content);
$infoParts = '';
$withParts = [];
if ($to) {
$infoParts .= " to '$to'";
}
if ($from) {
$infoParts .= " from '$from'";
}
if ($subject) {
$withParts[] = "subject '$subject'";
}
if ($content) {
$withParts[] = "content '$content'";
}
if ($withParts) {
$infoParts .= ' with ' . implode(' and ', $withParts);
}
static::assertTrue(
$found,
"Failed asserting that an email was sent$infoParts."
);
}
/**
* Assert that the given {@link SS_List} includes DataObjects matching the given key-value
* pairs. Each match must correspond to 1 distinct record.
*
* @param SS_List|array $matches The patterns to match. Each pattern is a map of key-value pairs. You can
* either pass a single pattern or an array of patterns.
* @param SS_List $list The {@link SS_List} to test.
* @param string $message
*
* Examples
* --------
* Check that $members includes an entry with Email = sam@example.com:
* $this->assertListContains(['Email' => '...@example.com'], $members);
*
* Check that $members includes entries with Email = sam@example.com and with
* Email = ingo@example.com:
* $this->assertListContains([
* ['Email' => '...@example.com'],
* ['Email' => 'i...@example.com'],
* ], $members);
*/
public static function assertListContains($matches, SS_List $list, $message = '')
{
if (!is_array($matches)) {
throw self::createInvalidArgumentException(
1,
'array'
);
}
static::assertThat(
$list,
new SSListContains(
$matches
),
$message
);
}
/**
* @param $matches
* @param $dataObjectSet
* @deprecated 4.0.1 Use assertListContains() instead
*
*/
public function assertDOSContains($matches, $dataObjectSet)
{
Deprecation::notice('4.0.1', 'Use assertListContains() instead');
static::assertListContains($matches, $dataObjectSet);
}
/**
* Asserts that no items in a given list appear in the given dataobject list
*
* @param SS_List|array $matches The patterns to match. Each pattern is a map of key-value pairs. You can
* either pass a single pattern or an array of patterns.
* @param SS_List $list The {@link SS_List} to test.
* @param string $message
*
* Examples
* --------
* Check that $members doesn't have an entry with Email = sam@example.com:
* $this->assertListNotContains(['Email' => '...@example.com'], $members);
*
* Check that $members doesn't have entries with Email = sam@example.com and with
* Email = ingo@example.com:
* $this->assertListNotContains([
* ['Email' => '...@example.com'],
* ['Email' => 'i...@example.com'],
* ], $members);
*/
public static function assertListNotContains($matches, SS_List $list, $message = '')
{
if (!is_array($matches)) {
throw self::createInvalidArgumentException(
1,
'array'
);
}
$constraint = new LogicalNot(
new SSListContains(
$matches
)
);
static::assertThat(
$list,
$constraint,
$message
);
}
/**
* @param $matches
* @param $dataObjectSet
* @deprecated 4.0.1 Use assertListNotContains() instead
*
*/
public static function assertNotDOSContains($matches, $dataObjectSet)
{
Deprecation::notice('4.0.1', 'Use assertListNotContains() instead');
static::assertListNotContains($matches, $dataObjectSet);
}
/**
* Assert that the given {@link SS_List} includes only DataObjects matching the given
* key-value pairs. Each match must correspond to 1 distinct record.
*
* Example
* --------
* Check that *only* the entries Sam Minnee and Ingo Schommer exist in $members. Order doesn't
* matter:
* $this->assertListEquals([
* ['FirstName' =>'Sam', 'Surname' => 'Minnee'],
* ['FirstName' => 'Ingo', 'Surname' => 'Schommer'],
* ], $members);
*
* @param mixed $matches The patterns to match. Each pattern is a map of key-value pairs. You can
* either pass a single pattern or an array of patterns.
* @param mixed $list The {@link SS_List} to test.
* @param string $message
*/
public static function assertListEquals($matches, SS_List $list, $message = '')
{
if (!is_array($matches)) {
throw self::createInvalidArgumentException(
1,
'array'
);
}
static::assertThat(
$list,
new SSListContainsOnly(
$matches
),
$message
);
}
/**
* @param $matches
* @param SS_List $dataObjectSet
* @deprecated 4.0.1 Use assertListEquals() instead
*
*/
public function assertDOSEquals($matches, $dataObjectSet)
{
Deprecation::notice('4.0.1', 'Use assertListEquals() instead');
static::assertListEquals($matches, $dataObjectSet);
}
/**
* Assert that the every record in the given {@link SS_List} matches the given key-value
* pairs.
*
* Example
* --------
* Check that every entry in $members has a Status of 'Active':
* $this->assertListAllMatch(['Status' => 'Active'], $members);
*
* @param mixed $match The pattern to match. The pattern is a map of key-value pairs.
* @param mixed $list The {@link SS_List} to test.
* @param string $message
*/
public static function assertListAllMatch($match, SS_List $list, $message = '')
{
if (!is_array($match)) {
throw self::createInvalidArgumentException(
1,
'array'
);
}
static::assertThat(
$list,
new SSListContainsOnlyMatchingItems(
$match
),
$message
);
}
/**
* @param $match
* @param SS_List $dataObjectSet
* @deprecated 4.0.1 Use assertListAllMatch() instead
*
*/
public function assertDOSAllMatch($match, SS_List $dataObjectSet)
{
Deprecation::notice('4.0.1', 'Use assertListAllMatch() instead');
static::assertListAllMatch($match, $dataObjectSet);
}
/**
* Removes sequences of repeated whitespace characters from SQL queries
* making them suitable for string comparison
*
* @param string $sql
* @return string The cleaned and normalised SQL string
*/
protected static function normaliseSQL($sql)
{
return trim(preg_replace('/\s+/m', ' ', $sql ?? '') ?? '');
}
/**
* Asserts that two SQL queries are equivalent
*
* @param string $expectedSQL
* @param string $actualSQL
* @param string $message
*/
public static function assertSQLEquals(
$expectedSQL,
$actualSQL,
$message = ''
) {
// Normalise SQL queries to remove patterns of repeating whitespace
$expectedSQL = static::normaliseSQL($expectedSQL);
$actualSQL = static::normaliseSQL($actualSQL);
static::assertEquals($expectedSQL, $actualSQL, $message);
}
/**
* Asserts that a SQL query contains a SQL fragment
*
* @param string $needleSQL
* @param string $haystackSQL
* @param string $message
*/
public static function assertSQLContains(
$needleSQL,
$haystackSQL,
$message = ''
) {
$needleSQL = static::normaliseSQL($needleSQL);
$haystackSQL = static::normaliseSQL($haystackSQL);
if (is_iterable($haystackSQL)) {
/** @var iterable $iterableHaystackSQL */
$iterableHaystackSQL = $haystackSQL;
static::assertContains($needleSQL, $iterableHaystackSQL, $message);
} else {
static::assertStringContainsString($needleSQL, $haystackSQL, $message);
}
}
/**
* Asserts that a SQL query contains a SQL fragment
*
* @param string $needleSQL
* @param string $haystackSQL
* @param string $message
*/
public static function assertSQLNotContains(
$needleSQL,
$haystackSQL,
$message = ''
) {
$needleSQL = static::normaliseSQL($needleSQL);
$haystackSQL = static::normaliseSQL($haystackSQL);
if (is_iterable($haystackSQL)) {
/** @var iterable $iterableHaystackSQL */
$iterableHaystackSQL = $haystackSQL;
static::assertNotContains($needleSQL, $iterableHaystackSQL, $message);
} else {
static::assertStringNotContainsString($needleSQL, $haystackSQL, $message);
}
}
/**
* Start test environment
*/
public static function start()
{
if (static::is_running_test()) {