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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
|
<?php
require_once __DIR__ . '/build-visual-html-tree.php';
require_once __DIR__ . '/factory.php';
require_once __DIR__ . '/trac.php';
/**
* Defines a basic fixture to run multiple tests.
*
* Resets the state of the WordPress installation before and after every test.
*
* Includes utility functions and assertions useful for testing WordPress.
*
* All WordPress unit tests should inherit from this class.
*/
abstract class WP_UnitTestCase_Base extends PHPUnit_Adapter_TestCase {
protected static $forced_tickets = array();
protected $expected_deprecated = array();
protected $caught_deprecated = array();
protected $expected_doing_it_wrong = array();
protected $caught_doing_it_wrong = array();
protected static $hooks_saved = array();
protected static $ignore_files;
/**
* Fixture factory.
*
* @deprecated 6.1.0 Use the WP_UnitTestCase_Base::factory() method instead.
*
* @var WP_UnitTest_Factory
*/
protected $factory;
/**
* Fetches the factory object for generating WordPress fixtures.
*
* @return WP_UnitTest_Factory The fixture factory.
*/
protected static function factory() {
static $factory = null;
if ( ! $factory ) {
$factory = new WP_UnitTest_Factory();
}
return $factory;
}
/**
* Retrieves the name of the class the static method is called in.
*
* @deprecated 5.3.0 Use the PHP native get_called_class() function instead.
*
* @return string The class name.
*/
public static function get_called_class() {
return get_called_class();
}
/**
* Runs the routine before setting up all tests.
*/
public static function set_up_before_class() {
global $wpdb;
parent::set_up_before_class();
$wpdb->suppress_errors = false;
$wpdb->show_errors = true;
$wpdb->db_connect();
ini_set( 'display_errors', 1 );
$class = get_called_class();
if ( method_exists( $class, 'wpSetUpBeforeClass' ) ) {
call_user_func( array( $class, 'wpSetUpBeforeClass' ), static::factory() );
}
self::commit_transaction();
}
/**
* Runs the routine after all tests have been run.
*/
public static function tear_down_after_class() {
$class = get_called_class();
if ( method_exists( $class, 'wpTearDownAfterClass' ) ) {
call_user_func( array( $class, 'wpTearDownAfterClass' ) );
}
_delete_all_data();
self::flush_cache();
self::commit_transaction();
parent::tear_down_after_class();
}
/**
* Runs the routine before each test is executed.
*/
public function set_up() {
set_time_limit( 0 );
$this->factory = static::factory();
if ( ! self::$ignore_files ) {
self::$ignore_files = $this->scan_user_uploads();
}
if ( ! self::$hooks_saved ) {
$this->_backup_hooks();
}
global $wp_rewrite;
$this->clean_up_global_scope();
/*
* When running core tests, ensure that post types and taxonomies
* are reset for each test. We skip this step for non-core tests,
* given the large number of plugins that register post types and
* taxonomies at 'init'.
*/
if ( defined( 'WP_RUN_CORE_TESTS' ) && WP_RUN_CORE_TESTS ) {
$this->reset_post_types();
$this->reset_taxonomies();
$this->reset_post_statuses();
$this->reset__SERVER();
if ( $wp_rewrite->permalink_structure ) {
$this->set_permalink_structure( '' );
}
}
$this->start_transaction();
$this->expectDeprecated();
add_filter( 'wp_die_handler', array( $this, 'get_wp_die_handler' ) );
add_filter( 'wp_hash_password_options', array( $this, 'wp_hash_password_options' ), 1, 2 );
}
/**
* Sets the bcrypt cost option for password hashing during tests.
*
* @param array $options The options for password hashing.
* @param string|int $algorithm The algorithm to use for hashing. This is a string in PHP 7.4+ and an integer in PHP 7.3 and earlier.
*/
public function wp_hash_password_options( array $options, $algorithm ): array {
if ( PASSWORD_BCRYPT === $algorithm ) {
$options['cost'] = 5;
}
return $options;
}
/**
* After a test method runs, resets any state in WordPress the test method might have changed.
*/
public function tear_down() {
global $wpdb, $wp_the_query, $wp_query, $wp;
$wpdb->query( 'ROLLBACK' );
if ( is_multisite() ) {
while ( ms_is_switched() ) {
restore_current_blog();
}
}
// Reset query, main query, and WP globals similar to wp-settings.php.
$wp_the_query = new WP_Query();
$wp_query = $wp_the_query;
$wp = new WP();
// Reset globals related to the post loop and `setup_postdata()`.
$post_globals = array( 'post', 'id', 'authordata', 'currentday', 'currentmonth', 'page', 'pages', 'multipage', 'more', 'numpages' );
foreach ( $post_globals as $global ) {
$GLOBALS[ $global ] = null;
}
/*
* Reset globals related to current screen to provide a consistent global starting state
* for tests that interact with admin screens. Replaces the need for individual tests
* to invoke `set_current_screen( 'front' )` (or an alternative implementation) as a reset.
*
* The globals are from `WP_Screen::set_current_screen()`.
*
* Why not invoke `set_current_screen( 'front' )`?
* Performance (faster test runs with less memory usage). How so? For each test,
* it saves creating an instance of WP_Screen, making two method calls,
* and firing of the `current_screen` action.
*/
$current_screen_globals = array( 'current_screen', 'taxnow', 'typenow' );
foreach ( $current_screen_globals as $global ) {
$GLOBALS[ $global ] = null;
}
// Reset comment globals.
$comment_globals = array( 'comment_alt', 'comment_depth', 'comment_thread_alt' );
foreach ( $comment_globals as $global ) {
$GLOBALS[ $global ] = null;
}
/*
* Reset $wp_sitemap global so that sitemap-related dynamic $wp->public_query_vars
* are added when the next test runs.
*/
$GLOBALS['wp_sitemaps'] = null;
// Reset template globals.
$GLOBALS['wp_stylesheet_path'] = null;
$GLOBALS['wp_template_path'] = null;
$this->unregister_all_meta_keys();
remove_theme_support( 'html5' );
remove_filter( 'query', array( $this, '_create_temporary_tables' ) );
remove_filter( 'query', array( $this, '_drop_temporary_tables' ) );
remove_filter( 'wp_die_handler', array( $this, 'get_wp_die_handler' ) );
$this->_restore_hooks();
wp_set_current_user( 0 );
$this->reset_lazyload_queue();
}
/**
* Cleans the global scope (e.g `$_GET` and `$_POST`).
*/
public function clean_up_global_scope() {
$_GET = array();
$_POST = array();
$_REQUEST = array();
self::flush_cache();
}
/**
* Allows tests to be skipped on some automated runs.
*
* For test runs on GitHub Actions for something other than trunk,
* we want to skip tests that only need to run for trunk.
*/
public function skipOnAutomatedBranches() {
// https://docs.github.com/en/actions/learn-github-actions/environment-variables#default-environment-variables
$github_event_name = getenv( 'GITHUB_EVENT_NAME' );
$github_ref = getenv( 'GITHUB_REF' );
if ( $github_event_name ) {
// We're on GitHub Actions.
$skipped = array( 'pull_request', 'pull_request_target' );
if ( in_array( $github_event_name, $skipped, true ) || 'refs/heads/trunk' !== $github_ref ) {
$this->markTestSkipped( 'For automated test runs, this test is only run on trunk' );
}
}
}
/**
* Allows tests to be skipped when Multisite is not in use.
*
* Use in conjunction with the ms-required group.
*/
public function skipWithoutMultisite() {
if ( ! is_multisite() ) {
$this->markTestSkipped( 'Test only runs on Multisite' );
}
}
/**
* Allows tests to be skipped when Multisite is in use.
*
* Use in conjunction with the ms-excluded group.
*/
public function skipWithMultisite() {
if ( is_multisite() ) {
$this->markTestSkipped( 'Test does not run on Multisite' );
}
}
/**
* Allows tests to be skipped if the HTTP request times out.
*
* @param array|WP_Error $response HTTP response.
*/
public function skipTestOnTimeout( $response ) {
if ( ! is_wp_error( $response ) ) {
return;
}
if ( 'connect() timed out!' === $response->get_error_message() ) {
$this->markTestSkipped( 'HTTP timeout' );
}
if ( false !== strpos( $response->get_error_message(), 'timed out after' ) ) {
$this->markTestSkipped( 'HTTP timeout' );
}
if ( 0 === strpos( $response->get_error_message(), 'stream_socket_client(): unable to connect to tcp://s.w.org:80' ) ) {
$this->markTestSkipped( 'HTTP timeout' );
}
}
/**
* Reset the lazy load meta queue.
*/
protected function reset_lazyload_queue() {
$lazyloader = wp_metadata_lazyloader();
$lazyloader->reset_queue( 'term' );
$lazyloader->reset_queue( 'comment' );
$lazyloader->reset_queue( 'blog' );
}
/**
* Unregisters existing post types and register defaults.
*
* Run before each test in order to clean up the global scope, in case
* a test forgets to unregister a post type on its own, or fails before
* it has a chance to do so.
*/
protected function reset_post_types() {
foreach ( get_post_types( array(), 'objects' ) as $pt ) {
if ( empty( $pt->tests_no_auto_unregister ) ) {
_unregister_post_type( $pt->name );
}
}
create_initial_post_types();
}
/**
* Unregisters existing taxonomies and register defaults.
*
* Run before each test in order to clean up the global scope, in case
* a test forgets to unregister a taxonomy on its own, or fails before
* it has a chance to do so.
*/
protected function reset_taxonomies() {
foreach ( get_taxonomies() as $tax ) {
_unregister_taxonomy( $tax );
}
create_initial_taxonomies();
}
/**
* Unregisters non-built-in post statuses.
*/
protected function reset_post_statuses() {
foreach ( get_post_stati( array( '_builtin' => false ) ) as $post_status ) {
_unregister_post_status( $post_status );
}
}
/**
* Resets `$_SERVER` variables
*/
protected function reset__SERVER() {
tests_reset__SERVER();
}
/**
* Saves the hook-related globals so they can be restored later.
*
* Stores $wp_filter, $wp_actions, $wp_filters, and $wp_current_filter
* on a class variable so they can be restored on tear_down() using _restore_hooks().
*
* @global array $wp_filter
* @global array $wp_actions
* @global array $wp_filters
* @global array $wp_current_filter
*/
protected function _backup_hooks() {
self::$hooks_saved['wp_filter'] = array();
foreach ( $GLOBALS['wp_filter'] as $hook_name => $hook_object ) {
self::$hooks_saved['wp_filter'][ $hook_name ] = clone $hook_object;
}
$globals = array( 'wp_actions', 'wp_filters', 'wp_current_filter' );
foreach ( $globals as $key ) {
self::$hooks_saved[ $key ] = $GLOBALS[ $key ];
}
}
/**
* Restores the hook-related globals to their state at set_up()
* so that future tests aren't affected by hooks set during this last test.
*
* @global array $wp_filter
* @global array $wp_actions
* @global array $wp_filters
* @global array $wp_current_filter
*/
protected function _restore_hooks() {
if ( isset( self::$hooks_saved['wp_filter'] ) ) {
$GLOBALS['wp_filter'] = array();
foreach ( self::$hooks_saved['wp_filter'] as $hook_name => $hook_object ) {
$GLOBALS['wp_filter'][ $hook_name ] = clone $hook_object;
}
}
$globals = array( 'wp_actions', 'wp_filters', 'wp_current_filter' );
foreach ( $globals as $key ) {
if ( isset( self::$hooks_saved[ $key ] ) ) {
$GLOBALS[ $key ] = self::$hooks_saved[ $key ];
}
}
}
/**
* Flushes the WordPress object cache.
*/
public static function flush_cache() {
global $wp_object_cache;
wp_cache_flush_runtime();
if ( is_object( $wp_object_cache ) && method_exists( $wp_object_cache, '__remoteset' ) ) {
$wp_object_cache->__remoteset();
}
wp_cache_flush();
wp_cache_add_global_groups(
array(
'blog-details',
'blog-id-cache',
'blog-lookup',
'blog_meta',
'global-posts',
'networks',
'network-queries',
'sites',
'site-details',
'site-options',
'site-queries',
'site-transient',
'theme_files',
'rss',
'users',
'user-queries',
'user_meta',
'useremail',
'userlogins',
'userslugs',
)
);
wp_cache_add_non_persistent_groups( array( 'counts', 'plugins', 'theme_json' ) );
}
/**
* Cleans up any registered meta keys.
*
* @since 5.1.0
*
* @global array $wp_meta_keys
*/
public function unregister_all_meta_keys() {
global $wp_meta_keys;
if ( ! is_array( $wp_meta_keys ) ) {
return;
}
foreach ( $wp_meta_keys as $object_type => $type_keys ) {
foreach ( $type_keys as $object_subtype => $subtype_keys ) {
foreach ( $subtype_keys as $key => $value ) {
unregister_meta_key( $object_type, $key, $object_subtype );
}
}
}
}
/**
* Starts a database transaction.
*/
public function start_transaction() {
global $wpdb;
$wpdb->query( 'SET autocommit = 0;' );
$wpdb->query( 'START TRANSACTION;' );
add_filter( 'query', array( $this, '_create_temporary_tables' ) );
add_filter( 'query', array( $this, '_drop_temporary_tables' ) );
}
/**
* Commits the queries in a transaction.
*
* @since 4.1.0
*/
public static function commit_transaction() {
global $wpdb;
$wpdb->query( 'COMMIT;' );
}
/**
* Replaces the `CREATE TABLE` statement with a `CREATE TEMPORARY TABLE` statement.
*
* @param string $query The query to replace the statement for.
* @return string The altered query.
*/
public function _create_temporary_tables( $query ) {
if ( 0 === strpos( trim( $query ), 'CREATE TABLE' ) ) {
return substr_replace( trim( $query ), 'CREATE TEMPORARY TABLE', 0, 12 );
}
return $query;
}
/**
* Replaces the `DROP TABLE` statement with a `DROP TEMPORARY TABLE` statement.
*
* @param string $query The query to replace the statement for.
* @return string The altered query.
*/
public function _drop_temporary_tables( $query ) {
if ( 0 === strpos( trim( $query ), 'DROP TABLE' ) ) {
return substr_replace( trim( $query ), 'DROP TEMPORARY TABLE', 0, 10 );
}
return $query;
}
/**
* Retrieves the `wp_die()` handler.
*
* @param callable $handler The current die handler.
* @return callable The test die handler.
*/
public function get_wp_die_handler( $handler ) {
return array( $this, 'wp_die_handler' );
}
/**
* Throws an exception when called.
*
* @since UT (3.7.0)
* @since 5.9.0 Added the `$title` and `$args` parameters.
*
* @throws WPDieException Exception containing the message and the response code.
*
* @param string|WP_Error $message The `wp_die()` message or WP_Error object.
* @param string $title The `wp_die()` title.
* @param string|array $args The `wp_die()` arguments.
*/
public function wp_die_handler( $message, $title, $args ) {
if ( is_wp_error( $message ) ) {
$message = $message->get_error_message();
}
if ( ! is_scalar( $message ) ) {
$message = '0';
}
$code = 0;
if ( isset( $args['response'] ) ) {
$code = $args['response'];
}
throw new WPDieException( $message, $code );
}
/**
* Sets up the expectations for testing a deprecated call.
*
* @since 3.7.0
*/
public function expectDeprecated() {
if ( method_exists( $this, 'getAnnotations' ) ) {
// PHPUnit < 9.5.0.
$annotations = $this->getAnnotations();
} else {
// PHPUnit >= 9.5.0.
$annotations = \PHPUnit\Util\Test::parseTestMethodAnnotations(
static::class,
$this->getName( false )
);
}
foreach ( array( 'class', 'method' ) as $depth ) {
if ( ! empty( $annotations[ $depth ]['expectedDeprecated'] ) ) {
$this->expected_deprecated = array_merge(
$this->expected_deprecated,
$annotations[ $depth ]['expectedDeprecated']
);
}
if ( ! empty( $annotations[ $depth ]['expectedIncorrectUsage'] ) ) {
$this->expected_doing_it_wrong = array_merge(
$this->expected_doing_it_wrong,
$annotations[ $depth ]['expectedIncorrectUsage']
);
}
}
add_action( 'deprecated_function_run', array( $this, 'deprecated_function_run' ), 10, 3 );
add_action( 'deprecated_argument_run', array( $this, 'deprecated_function_run' ), 10, 3 );
add_action( 'deprecated_class_run', array( $this, 'deprecated_function_run' ), 10, 3 );
add_action( 'deprecated_file_included', array( $this, 'deprecated_function_run' ), 10, 4 );
add_action( 'deprecated_hook_run', array( $this, 'deprecated_function_run' ), 10, 4 );
add_action( 'doing_it_wrong_run', array( $this, 'doing_it_wrong_run' ), 10, 3 );
add_action( 'deprecated_function_trigger_error', '__return_false' );
add_action( 'deprecated_argument_trigger_error', '__return_false' );
add_action( 'deprecated_class_trigger_error', '__return_false' );
add_action( 'deprecated_file_trigger_error', '__return_false' );
add_action( 'deprecated_hook_trigger_error', '__return_false' );
add_action( 'doing_it_wrong_trigger_error', '__return_false' );
}
/**
* Handles a deprecated expectation.
*
* The DocBlock should contain `@expectedDeprecated` to trigger this.
*
* @since 3.7.0
* @since 6.1.0 Includes the actual unexpected `_doing_it_wrong()` message
* or deprecation notice in the output if one is encountered.
*/
public function expectedDeprecated() {
$errors = array();
$not_caught_deprecated = array_diff(
$this->expected_deprecated,
array_keys( $this->caught_deprecated )
);
foreach ( $not_caught_deprecated as $not_caught ) {
$errors[] = "Failed to assert that $not_caught triggered a deprecation notice.";
}
$unexpected_deprecated = array_diff(
array_keys( $this->caught_deprecated ),
$this->expected_deprecated
);
foreach ( $unexpected_deprecated as $unexpected ) {
$errors[] = "Unexpected deprecation notice for $unexpected.";
$errors[] = $this->caught_deprecated[ $unexpected ];
}
$not_caught_doing_it_wrong = array_diff(
$this->expected_doing_it_wrong,
array_keys( $this->caught_doing_it_wrong )
);
foreach ( $not_caught_doing_it_wrong as $not_caught ) {
$errors[] = "Failed to assert that $not_caught triggered an incorrect usage notice.";
}
$unexpected_doing_it_wrong = array_diff(
array_keys( $this->caught_doing_it_wrong ),
$this->expected_doing_it_wrong
);
foreach ( $unexpected_doing_it_wrong as $unexpected ) {
$errors[] = "Unexpected incorrect usage notice for $unexpected.";
$errors[] = $this->caught_doing_it_wrong[ $unexpected ];
}
// Perform an assertion, but only if there are expected or unexpected deprecated calls or wrongdoings.
if ( ! empty( $this->expected_deprecated ) ||
! empty( $this->expected_doing_it_wrong ) ||
! empty( $this->caught_deprecated ) ||
! empty( $this->caught_doing_it_wrong ) ) {
$this->assertEmpty( $errors, implode( "\n", $errors ) );
}
}
/**
* Detects post-test failure conditions.
*
* We use this method to detect expectedDeprecated and expectedIncorrectUsage annotations.
*
* @since 4.2.0
*/
protected function assert_post_conditions() {
$this->expectedDeprecated();
}
/**
* Declares an expected `_deprecated_function()` or `_deprecated_argument()` call from within a test.
*
* @since 4.2.0
*
* @param string $deprecated Name of the function, method, class, or argument that is deprecated.
* Must match the first parameter of the `_deprecated_function()`
* or `_deprecated_argument()` call.
*/
public function setExpectedDeprecated( $deprecated ) {
$this->expected_deprecated[] = $deprecated;
}
/**
* Declares an expected `_doing_it_wrong()` call from within a test.
*
* @since 4.2.0
*
* @param string $doing_it_wrong Name of the function, method, or class that appears in
* the first argument of the source `_doing_it_wrong()` call.
*/
public function setExpectedIncorrectUsage( $doing_it_wrong ) {
$this->expected_doing_it_wrong[] = $doing_it_wrong;
}
/**
* Redundant PHPUnit 6+ compatibility shim. DO NOT USE!
*
* This method is only left in place for backward compatibility reasons.
*
* @since 4.8.0
* @deprecated 5.9.0 Use the PHPUnit native expectException*() methods directly.
*
* @param mixed $exception
* @param string $message
* @param int|string $code
*/
public function setExpectedException( $exception, $message = '', $code = null ) {
$this->expectException( $exception );
if ( '' !== $message ) {
$this->expectExceptionMessage( $message );
}
if ( null !== $code ) {
$this->expectExceptionCode( $code );
}
}
/**
* Adds a deprecated function to the list of caught deprecated calls.
*
* @since 3.7.0
* @since 6.1.0 Added the `$replacement`, `$version`, and `$message` parameters.
*
* @param string $function_name The deprecated function.
* @param string $replacement The function that should have been called.
* @param string $version The version of WordPress that deprecated the function.
* @param string $message Optional. A message regarding the change.
*/
public function deprecated_function_run( $function_name, $replacement, $version, $message = '' ) {
if ( ! isset( $this->caught_deprecated[ $function_name ] ) ) {
switch ( current_action() ) {
case 'deprecated_function_run':
if ( $replacement ) {
$message = sprintf(
'Function %1$s is deprecated since version %2$s! Use %3$s instead.',
$function_name,
$version,
$replacement
);
} else {
$message = sprintf(
'Function %1$s is deprecated since version %2$s with no alternative available.',
$function_name,
$version
);
}
break;
case 'deprecated_argument_run':
if ( $replacement ) {
$message = sprintf(
'Function %1$s was called with an argument that is deprecated since version %2$s! %3$s',
$function_name,
$version,
$replacement
);
} else {
$message = sprintf(
'Function %1$s was called with an argument that is deprecated since version %2$s with no alternative available.',
$function_name,
$version
);
}
break;
case 'deprecated_class_run':
if ( $replacement ) {
$message = sprintf(
'Class %1$s is deprecated since version %2$s! Use %3$s instead.',
$function_name,
$version,
$replacement
);
} else {
$message = sprintf(
'Class %1$s is deprecated since version %2$s with no alternative available.',
$function_name,
$version
);
}
break;
case 'deprecated_file_included':
if ( $replacement ) {
$message = sprintf(
'File %1$s is deprecated since version %2$s! Use %3$s instead.',
$function_name,
$version,
$replacement
) . ' ' . $message;
} else {
$message = sprintf(
'File %1$s is deprecated since version %2$s with no alternative available.',
$function_name,
$version
) . ' ' . $message;
}
break;
case 'deprecated_hook_run':
if ( $replacement ) {
$message = sprintf(
'Hook %1$s is deprecated since version %2$s! Use %3$s instead.',
$function_name,
$version,
$replacement
) . ' ' . $message;
} else {
$message = sprintf(
'Hook %1$s is deprecated since version %2$s with no alternative available.',
$function_name,
$version
) . ' ' . $message;
}
break;
}
$this->caught_deprecated[ $function_name ] = $message;
}
}
/**
* Adds a function called in a wrong way to the list of `_doing_it_wrong()` calls.
*
* @since 3.7.0
* @since 6.1.0 Added the `$message` and `$version` parameters.
*
* @param string $function_name The function to add.
* @param string $message A message explaining what has been done incorrectly.
* @param string $version The version of WordPress where the message was added.
*/
public function doing_it_wrong_run( $function_name, $message, $version ) {
if ( ! isset( $this->caught_doing_it_wrong[ $function_name ] ) ) {
if ( $version ) {
$message .= ' ' . sprintf( '(This message was added in version %s.)', $version );
}
$this->caught_doing_it_wrong[ $function_name ] = $message;
}
}
/**
* Asserts that the given value is an instance of WP_Error.
*
* @param mixed $actual The value to check.
* @param string $message Optional. Message to display when the assertion fails.
*/
public function assertWPError( $actual, $message = '' ) {
$this->assertInstanceOf( 'WP_Error', $actual, $message );
}
/**
* Asserts that the given value is not an instance of WP_Error.
*
* @param mixed $actual The value to check.
* @param string $message Optional. Message to display when the assertion fails.
*/
public function assertNotWPError( $actual, $message = '' ) {
if ( is_wp_error( $actual ) ) {
$message .= ' ' . $actual->get_error_message();
}
$this->assertNotInstanceOf( 'WP_Error', $actual, $message );
}
/**
* Asserts that the given value is an instance of IXR_Error.
*
* @param mixed $actual The value to check.
* @param string $message Optional. Message to display when the assertion fails.
*/
public function assertIXRError( $actual, $message = '' ) {
$this->assertInstanceOf( 'IXR_Error', $actual, $message );
}
/**
* Asserts that the given value is not an instance of IXR_Error.
*
* @param mixed $actual The value to check.
* @param string $message Optional. Message to display when the assertion fails.
*/
public function assertNotIXRError( $actual, $message = '' ) {
if ( $actual instanceof IXR_Error ) {
$message .= ' ' . $actual->message;
}
$this->assertNotInstanceOf( 'IXR_Error', $actual, $message );
}
/**
* Asserts that the given fields are present in the given object.
*
* @since UT (3.7.0)
* @since 5.9.0 Added the `$message` parameter.
*
* @param object $actual The object to check.
* @param array $fields The fields to check.
* @param string $message Optional. Message to display when the assertion fails.
*/
public function assertEqualFields( $actual, $fields, $message = '' ) {
$this->assertIsObject( $actual, $message . ' Passed $actual is not an object.' );
$this->assertIsArray( $fields, $message . ' Passed $fields is not an array.' );
$this->assertNotEmpty( $fields, $message . ' Fields array is empty.' );
foreach ( $fields as $field_name => $field_value ) {
$this->assertObjectHasProperty( $field_name, $actual, $message . " Property $field_name does not exist on the object." );
$this->assertSame( $field_value, $actual->$field_name, $message . " Value of property $field_name is not $field_value." );
}
}
/**
* Asserts that two values are equal, with whitespace differences discarded.
*
* @since UT (3.7.0)
* @since 5.9.0 Added the `$message` parameter.
*
* @param mixed $expected The expected value.
* @param mixed $actual The actual value.
* @param string $message Optional. Message to display when the assertion fails.
*/
public function assertDiscardWhitespace( $expected, $actual, $message = '' ) {
if ( is_string( $expected ) ) {
$expected = preg_replace( '/\s*/', '', $expected );
}
if ( is_string( $actual ) ) {
$actual = preg_replace( '/\s*/', '', $actual );
}
$this->assertEquals( $expected, $actual, $message );
}
/**
* Asserts that two values have the same type and value, with EOL differences discarded.
*
* @since 5.6.0
* @since 5.8.0 Added support for nested arrays.
* @since 5.9.0 Added the `$message` parameter.
*
* @param mixed $expected The expected value.
* @param mixed $actual The actual value.
* @param string $message Optional. Message to display when the assertion fails.
*/
public function assertSameIgnoreEOL( $expected, $actual, $message = '' ) {
if ( null !== $expected ) {
$expected = map_deep(
$expected,
static function ( $value ) {
if ( is_string( $value ) ) {
return str_replace( "\r\n", "\n", $value );
}
return $value;
}
);
}
if ( null !== $actual ) {
$actual = map_deep(
$actual,
static function ( $value ) {
if ( is_string( $value ) ) {
return str_replace( "\r\n", "\n", $value );
}
return $value;
}
);
}
$this->assertSame( $expected, $actual, $message );
}
/**
* Asserts that two values are equal, with EOL differences discarded.
*
* @since 5.4.0
* @since 5.6.0 Turned into an alias for `::assertSameIgnoreEOL()`.
* @since 5.9.0 Added the `$message` parameter.
*
* @param mixed $expected The expected value.
* @param mixed $actual The actual value.
* @param string $message Optional. Message to display when the assertion fails.
*/
public function assertEqualsIgnoreEOL( $expected, $actual, $message = '' ) {
$this->assertSameIgnoreEOL( $expected, $actual, $message );
}
/**
* Asserts that the contents of two un-keyed, single arrays are the same, without accounting for the order of elements.
*
* @since 5.6.0
* @since 5.9.0 Added the `$message` parameter.
*
* @param array $expected Expected array.
* @param array $actual Array to check.
* @param string $message Optional. Message to display when the assertion fails.
*/
public function assertSameSets( $expected, $actual, $message = '' ) {
$this->assertIsArray( $expected, $message . ' Expected value must be an array.' );
$this->assertIsArray( $actual, $message . ' Value under test is not an array.' );
sort( $expected );
sort( $actual );
$this->assertSame( $expected, $actual, $message );
}
/**
* Asserts that the contents of two un-keyed, single arrays are equal, without accounting for the order of elements.
*
* @since 3.5.0
* @since 5.9.0 Added the `$message` parameter.
*
* @param array $expected Expected array.
* @param array $actual Array to check.
* @param string $message Optional. Message to display when the assertion fails.
*/
public function assertEqualSets( $expected, $actual, $message = '' ) {
$this->assertIsArray( $expected, $message . ' Expected value must be an array.' );
$this->assertIsArray( $actual, $message . ' Value under test is not an array.' );
sort( $expected );
sort( $actual );
$this->assertEquals( $expected, $actual, $message );
}
/**
* Asserts that the contents of two keyed, single arrays are the same, without accounting for the order of elements.
*
* @since 5.6.0
* @since 5.9.0 Added the `$message` parameter.
*
* @param array $expected Expected array.
* @param array $actual Array to check.
* @param string $message Optional. Message to display when the assertion fails.
*/
public function assertSameSetsWithIndex( $expected, $actual, $message = '' ) {
$this->assertIsArray( $expected, $message . ' Expected value must be an array.' );
$this->assertIsArray( $actual, $message . ' Value under test is not an array.' );
ksort( $expected );
ksort( $actual );
$this->assertSame( $expected, $actual, $message );
}
/**
* Asserts that the contents of two keyed, single arrays are equal, without accounting for the order of elements.
*
* @since 4.1.0
* @since 5.9.0 Added the `$message` parameter.
*
* @param array $expected Expected array.
* @param array $actual Array to check.
* @param string $message Optional. Message to display when the assertion fails.
*/
public function assertEqualSetsWithIndex( $expected, $actual, $message = '' ) {
$this->assertIsArray( $expected, $message . ' Expected value must be an array.' );
$this->assertIsArray( $actual, $message . ' Value under test is not an array.' );
ksort( $expected );
ksort( $actual );
$this->assertEquals( $expected, $actual, $message );
}
/**
* Asserts that the given variable is a multidimensional array, and that all arrays are non-empty.
*
* @since 4.8.0
* @since 5.9.0 Added the `$message` parameter.
*
* @param array $actual Array to check.
* @param string $message Optional. Message to display when the assertion fails.
*/
public function assertNonEmptyMultidimensionalArray( $actual, $message = '' ) {
$this->assertIsArray( $actual, $message . ' Value under test is not an array.' );
$this->assertNotEmpty( $actual, $message . ' Array is empty.' );
foreach ( $actual as $sub_array ) {
$this->assertIsArray( $sub_array, $message . ' Subitem of the array is not an array.' );
$this->assertNotEmpty( $sub_array, $message . ' Subitem of the array is empty.' );
}
}
/**
* Assert that two text strings representing file paths are the same, while ignoring
* OS-specific differences in the directory separators.
*
* This allows for tests to be compatible for running on both *nix based as well as Windows OS.
*
* @since 6.7.0
*
* @param string $path_a File or directory path.
* @param string $path_b File or directory path.
*/
public function assertSamePathIgnoringDirectorySeparators( $path_a, $path_b ) {
$path_a = $this->normalizeDirectorySeparatorsInPath( $path_a );
$path_b = $this->normalizeDirectorySeparatorsInPath( $path_b );
$this->assertSame( $path_a, $path_b );
}
/**
* Normalize directory separators in a file path to be a forward slash.
*
* @since 6.7.0
*
* @param string $path File or directory path.
* @return string The normalized file or directory path.
*/
public function normalizeDirectorySeparatorsInPath( $path ) {
if ( ! is_string( $path ) || PHP_OS_FAMILY !== 'Windows' ) {
return $path;
}
return strtr( $path, '\\', '/' );
}
/**
* Checks each of the WP_Query is_* functions/properties against expected boolean value.
*
* Any properties that are listed by name as parameters will be expected to be true; all others are
* expected to be false. For example, assertQueryTrue( 'is_single', 'is_feed' ) means is_single()
* and is_feed() must be true and everything else must be false to pass.
*
* @since 2.5.0
* @since 3.8.0 Moved from `Tests_Query_Conditionals` to `WP_UnitTestCase`.
* @since 5.3.0 Formalized the existing `...$prop` parameter by adding it
* to the function signature.
*
* @param string ...$prop Any number of WP_Query properties that are expected to be true for the current request.
*/
public function assertQueryTrue( ...$prop ) {
global $wp_query;
$all = array(
'is_404',
'is_admin',
'is_archive',
'is_attachment',
'is_author',
'is_category',
'is_comment_feed',
'is_date',
'is_day',
'is_embed',
'is_feed',
'is_front_page',
'is_home',
'is_privacy_policy',
'is_month',
'is_page',
'is_paged',
'is_post_type_archive',
'is_posts_page',
'is_preview',
'is_robots',
'is_favicon',
'is_search',
'is_single',
'is_singular',
'is_tag',
'is_tax',
'is_time',
'is_trackback',
'is_year',
);
foreach ( $prop as $true_thing ) {
$this->assertContains( $true_thing, $all, "Unknown conditional: {$true_thing}." );
}
$passed = true;
$message = '';
foreach ( $all as $query_thing ) {
$result = is_callable( $query_thing ) ? call_user_func( $query_thing ) : $wp_query->$query_thing;
if ( in_array( $query_thing, $prop, true ) ) {
if ( ! $result ) {
$message .= $query_thing . ' is false but is expected to be true. ' . PHP_EOL;
$passed = false;
}
} elseif ( $result ) {
$message .= $query_thing . ' is true but is expected to be false. ' . PHP_EOL;
$passed = false;
}
}
if ( ! $passed ) {
$this->fail( $message );
}
}
/**
* Check HTML markup (including blocks) for semantic equivalence.
*
* Given two markup strings, assert that they translate to the same semantic HTML tree,
* normalizing tag names, attribute names, and attribute order. Furthermore, attributes
* and class names are sorted and deduplicated, and whitespace in style attributes
* is normalized. Finally, block delimiter comments are recognized and normalized,
* applying the same principles.
*
* @since 6.9.0
*
* @param string $expected The expected HTML.
* @param string $actual The actual HTML.
* @param string|null $fragment_context Optional. The fragment context, for example "<td>" expected HTML
* must occur within "<table><tr>" fragment context. Default "<body>".
* Only "<body>" or `null` are supported at this time.
* Set to `null` to parse a full HTML document.
* @param string|null $message Optional. The assertion error message.
*/
public function assertEqualHTML( string $expected, string $actual, ?string $fragment_context = '<body>', $message = 'HTML markup was not equivalent.' ): void {
try {
$tree_expected = build_visual_html_tree( $expected, $fragment_context );
$tree_actual = build_visual_html_tree( $actual, $fragment_context );
} catch ( Exception $e ) {
// For PHP 8.4+, we can retry, using the built-in DOM\HTMLDocument parser.
if ( class_exists( 'DOM\HtmlDocument' ) ) {
$dom_expected = DOM\HtmlDocument::createFromString( $expected, LIBXML_NOERROR );
$tree_expected = build_visual_html_tree( $dom_expected->saveHtml(), $fragment_context );
$dom_actual = DOM\HtmlDocument::createFromString( $actual, LIBXML_NOERROR );
$tree_actual = build_visual_html_tree( $dom_actual->saveHtml(), $fragment_context );
} else {
throw $e;
}
}
$this->assertSame( $tree_expected, $tree_actual, $message );
}
/**
* Helper function to convert a single-level array containing text strings to a named data provider.
*
* The value of the data set will also be used as the name of the data set.
*
* Typical usage of this method:
*
* public function data_provider_for_test_name() {
* $array = array(
* 'value1',
* 'value2',
* );
*
* return $this->text_array_to_dataprovider( $array );
* }
*
* The returned result will look like:
*
* array(
* 'value1' => array( 'value1' ),
* 'value2' => array( 'value2' ),
* )
*
* @since 6.1.0
*
* @param array $input Input array.
* @return array Array which is usable as a test data provider with named data sets.
*/
public static function text_array_to_dataprovider( $input ) {
$data = array();
foreach ( $input as $value ) {
if ( ! is_string( $value ) ) {
throw new Exception(
'All values in the input array should be text strings. Fix the input data.'
);
}
if ( isset( $data[ $value ] ) ) {
throw new Exception(
"Attempting to add a duplicate data set for value $value to the data provider. Fix the input data."
);
}
$data[ $value ] = array( $value );
}
return $data;
}
/**
* Sets the global state to as if a given URL has been requested.
*
* This sets:
* - The super globals.
* - The globals.
* - The query variables.
* - The main query.
*
* @since 3.5.0
*
* @param string $url The URL for the request.
*/
public function go_to( $url ) {
/*
* Note: the WP and WP_Query classes like to silently fetch parameters
* from all over the place (globals, GET, etc), which makes it tricky
* to run them more than once without very carefully clearing everything.
*/
$_GET = array();
$_POST = array();
foreach ( array( 'query_string', 'id', 'postdata', 'authordata', 'day', 'currentmonth', 'page', 'pages', 'multipage', 'more', 'numpages', 'pagenow', 'current_screen' ) as $v ) {
if ( isset( $GLOBALS[ $v ] ) ) {
unset( $GLOBALS[ $v ] );
}
}
$parts = parse_url( $url );
if ( isset( $parts['scheme'] ) ) {
$req = isset( $parts['path'] ) ? $parts['path'] : '';
if ( isset( $parts['query'] ) ) {
$req .= '?' . $parts['query'];
// Parse the URL query vars into $_GET.
parse_str( $parts['query'], $_GET );
}
} else {
$req = $url;
}
if ( ! isset( $parts['query'] ) ) {
$parts['query'] = '';
}
$_SERVER['REQUEST_URI'] = $req;
unset( $_SERVER['PATH_INFO'] );
self::flush_cache();
unset( $GLOBALS['wp_query'], $GLOBALS['wp_the_query'] );
$GLOBALS['wp_the_query'] = new WP_Query();
$GLOBALS['wp_query'] = $GLOBALS['wp_the_query'];
$public_query_vars = $GLOBALS['wp']->public_query_vars;
$private_query_vars = $GLOBALS['wp']->private_query_vars;
$GLOBALS['wp'] = new WP();
$GLOBALS['wp']->public_query_vars = $public_query_vars;
$GLOBALS['wp']->private_query_vars = $private_query_vars;
_cleanup_query_vars();
$GLOBALS['wp']->main( $parts['query'] );
}
/**
* Allows tests to be skipped on single or multisite installs by using @group annotations.
*
* This is a custom extension of the PHPUnit requirements handling.
*
* @since 3.5.0
* @deprecated 5.9.0 This method has not been functional since PHPUnit 7.0.
*/
protected function checkRequirements() {
// For PHPUnit 5/6, as we're overloading a public PHPUnit native method in those versions.
if ( is_callable( 'PHPUnit\Framework\TestCase', 'checkRequirements' ) ) {
parent::checkRequirements();
}
}
/**
* Skips the current test if there is an open Trac ticket associated with it.
*
* @since 3.5.0
*
* @param int $ticket_id Ticket number.
*/
public function knownWPBug( $ticket_id ) {
if ( WP_TESTS_FORCE_KNOWN_BUGS || in_array( $ticket_id, self::$forced_tickets, true ) ) {
return;
}
if ( ! TracTickets::isTracTicketClosed( 'https://core.trac.wordpress.org', $ticket_id ) ) {
$this->markTestSkipped( sprintf( 'WordPress Ticket #%d is not fixed', $ticket_id ) );
}
}
/**
* Skips the current test if there is an open Unit Test Trac ticket associated with it.
*
* @since 3.5.0
* @deprecated No longer used since the Unit Test Trac was merged into the Core Trac.
*
* @param int $ticket_id Ticket number.
*/
public function knownUTBug( $ticket_id ) {
return;
}
/**
* Skips the current test if there is an open Plugin Trac ticket associated with it.
*
* @since 3.5.0
*
* @param int $ticket_id Ticket number.
*/
public function knownPluginBug( $ticket_id ) {
if ( WP_TESTS_FORCE_KNOWN_BUGS || in_array( 'Plugin' . $ticket_id, self::$forced_tickets, true ) ) {
return;
}
if ( ! TracTickets::isTracTicketClosed( 'https://plugins.trac.wordpress.org', $ticket_id ) ) {
$this->markTestSkipped( sprintf( 'WordPress Plugin Ticket #%d is not fixed', $ticket_id ) );
}
}
/**
* Adds a Trac ticket number to the `$forced_tickets` property.
*
* @since 3.5.0
*
* @param int $ticket Ticket number.
*/
public static function forceTicket( $ticket ) {
self::$forced_tickets[] = $ticket;
}
/**
* Custom preparations for the PHPUnit process isolation template.
*
* When restoring global state between tests, PHPUnit defines all the constants that were already defined, and then
* includes included files. This does not work with WordPress, as the included files define the constants.
*
* This method defines the constants after including files.
*
* @param Text_Template $template The template to prepare.
*/
public function prepareTemplate( Text_Template $template ) {
$template->setVar( array( 'constants' => '' ) );
$template->setVar( array( 'wp_constants' => PHPUnit_Util_GlobalState::getConstantsAsString() ) );
parent::prepareTemplate( $template );
}
/**
* Creates a unique temporary file name.
*
* The directory in which the file is created depends on the environment configuration.
*
* @since 3.5.0
*
* @return string|bool Path on success, else false.
*/
public function temp_filename() {
$tmp_dir = '';
$dirs = array( 'TMP', 'TMPDIR', 'TEMP' );
foreach ( $dirs as $dir ) {
if ( isset( $_ENV[ $dir ] ) && ! empty( $_ENV[ $dir ] ) ) {
$tmp_dir = $dir;
break;
}
}
if ( empty( $tmp_dir ) ) {
$tmp_dir = get_temp_dir();
}
$tmp_dir = realpath( $tmp_dir );
return tempnam( $tmp_dir, 'wpunit' );
}
/**
* Selectively deletes a file.
*
* Does not delete a file if its path is set in the `$ignore_files` property.
*
* @param string $file File path.
*/
public function unlink( $file ) {
$exists = is_file( $file );
if ( $exists && ! in_array( $file, self::$ignore_files, true ) ) {
//error_log( $file );
unlink( $file );
} elseif ( ! $exists ) {
$this->fail( "Trying to delete a file that doesn't exist: $file" );
}
}
/**
* Selectively deletes files from a directory.
*
* Does not delete files if their paths are set in the `$ignore_files` property.
*
* @since 4.0.0
*
* @param string $path Directory path.
*/
public function rmdir( $path ) {
$files = $this->files_in_dir( $path );
foreach ( $files as $file ) {
if ( ! in_array( $file, self::$ignore_files, true ) ) {
$this->unlink( $file );
}
}
}
/**
* Deletes files added to the `uploads` directory during tests.
*
* This method works in tandem with the `set_up()` and `rmdir()` methods:
* - `set_up()` scans the `uploads` directory before every test, and stores
* its contents inside of the `$ignore_files` property.
* - `rmdir()` and its helper methods only delete files that are not listed
* in the `$ignore_files` property. If called during `tear_down()` in tests,
* this will only delete files added during the previously run test.
*/
public function remove_added_uploads() {
$uploads = wp_upload_dir();
$this->rmdir( $uploads['basedir'] );
}
/**
* Returns a list of all files contained inside a directory.
*
* @since 4.0.0
*
* @param string $dir Path to the directory to scan.
* @return string[] List of file paths.
*/
public function files_in_dir( $dir ) {
$files = array();
$iterator = new RecursiveDirectoryIterator( $dir );
$objects = new RecursiveIteratorIterator( $iterator );
foreach ( $objects as $name => $object ) {
if ( is_file( $name ) ) {
$files[] = $name;
}
}
return $files;
}
/**
* Returns a list of all files contained inside the `uploads` directory.
*
* @since 4.0.0
*
* @return string[] List of file paths.
*/
public function scan_user_uploads() {
static $files = array();
if ( ! empty( $files ) ) {
return $files;
}
$uploads = wp_upload_dir();
$files = $this->files_in_dir( $uploads['basedir'] );
return $files;
}
/**
* Deletes all directories contained inside a directory.
*
* @since 4.1.0
*
* @param string $path Path to the directory to scan.
*/
public function delete_folders( $path ) {
if ( ! is_dir( $path ) ) {
return;
}
$matched_dirs = $this->scandir( $path );
foreach ( array_reverse( $matched_dirs ) as $dir ) {
rmdir( $dir );
}
rmdir( $path );
}
/**
* Retrieves all directories contained inside a directory.
* Hidden directories are ignored.
*
* This is a helper for the `delete_folders()` method.
*
* @since 4.1.0
* @since 6.1.0 No longer sets a (dynamic) property to keep track of the directories,
* but returns an array of the directories instead.
*
* @param string $dir Path to the directory to scan.
* @return string[] List of directories.
*/
public function scandir( $dir ) {
$matched_dirs = array();
foreach ( scandir( $dir ) as $path ) {
if ( 0 !== strpos( $path, '.' ) && is_dir( $dir . '/' . $path ) ) {
$matched_dirs[] = array( $dir . '/' . $path );
$matched_dirs[] = $this->scandir( $dir . '/' . $path );
}
}
/*
* Compatibility check for PHP < 7.4, where array_merge() expects at least one array.
* See: https://3v4l.org/BIQMA
*/
if ( array() === $matched_dirs ) {
return array();
}
return array_merge( ...$matched_dirs );
}
/**
* Converts a microtime string into a float.
*
* @since 4.1.0
*
* @param string $microtime Time string generated by `microtime()`.
* @return float `microtime()` output as a float.
*/
protected function _microtime_to_float( $microtime ) {
$time_array = explode( ' ', $microtime );
return array_sum( $time_array );
}
/**
* Deletes a user from the database in a Multisite-agnostic way.
*
* @since 4.3.0
*
* @param int $user_id User ID.
* @return bool True if the user was deleted.
*/
public static function delete_user( $user_id ) {
if ( is_multisite() ) {
return wpmu_delete_user( $user_id );
}
return wp_delete_user( $user_id );
}
/**
* Resets permalinks and flushes rewrites.
*
* @since 4.4.0
*
* @global WP_Rewrite $wp_rewrite
*
* @param string $structure Optional. Permalink structure to set. Default empty.
*/
public function set_permalink_structure( $structure = '' ) {
global $wp_rewrite;
$wp_rewrite->init();
$wp_rewrite->set_permalink_structure( $structure );
$wp_rewrite->flush_rules();
}
/**
* Creates an attachment post from an uploaded file.
*
* @since 4.4.0
* @since 6.2.0 Returns a WP_Error object on failure.
*
* @param array $upload Array of information about the uploaded file, provided by wp_upload_bits().
* @param int $parent_post_id Optional. Parent post ID.
* @return int|WP_Error The attachment ID on success, WP_Error object on failure.
*/
public function _make_attachment( $upload, $parent_post_id = 0 ) {
$type = '';
if ( ! empty( $upload['type'] ) ) {
$type = $upload['type'];
} else {
$mime = wp_check_filetype( $upload['file'] );
if ( $mime ) {
$type = $mime['type'];
}
}
$attachment = array(
'post_title' => wp_basename( $upload['file'] ),
'post_content' => '',
'post_type' => 'attachment',
'post_parent' => $parent_post_id,
'post_mime_type' => $type,
'guid' => $upload['url'],
);
$attachment_id = wp_insert_attachment( $attachment, $upload['file'], $parent_post_id, true );
if ( is_wp_error( $attachment_id ) ) {
return $attachment_id;
}
wp_update_attachment_metadata(
$attachment_id,
wp_generate_attachment_metadata( $attachment_id, $upload['file'] )
);
return $attachment_id;
}
/**
* Updates the modified and modified GMT date of a post in the database.
*
* @since 4.8.0
*
* @global wpdb $wpdb WordPress database abstraction object.
*
* @param int $post_id Post ID.
* @param string $date Post date, in the format YYYY-MM-DD HH:MM:SS.
* @return int|false 1 on success, or false on error.
*/
protected function update_post_modified( $post_id, $date ) {
global $wpdb;
return $wpdb->update(
$wpdb->posts,
array(
'post_modified' => $date,
'post_modified_gmt' => $date,
),
array(
'ID' => $post_id,
),
array(
'%s',
'%s',
),
array(
'%d',
)
);
}
/**
* Touches the given file and its directory if it doesn't already exist.
*
* This can be used to ensure a file that is implicitly relied on in a test exists
* without it having to be built.
*
* @param string $file The file name.
*/
public static function touch( $file ) {
if ( file_exists( $file ) ) {
return;
}
$dir = dirname( $file );
if ( ! file_exists( $dir ) ) {
mkdir( $dir, 0777, true );
}
touch( $file );
}
/**
* Wrapper for `wp_safe_remote_request()` that retries on error and skips the test on timeout.
*
* @param string $url URL to retrieve.
* @param array $args Optional. Request arguments. Default empty array.
* @return array|WP_Error The response or WP_Error on failure.
*/
protected function wp_safe_remote_request( $url, $args = array() ) {
return self::retry_on_error( 'wp_safe_remote_request', $url, $args );
}
/**
* Wrapper for `wp_safe_remote_get()` that retries on error and skips the test on timeout.
*
* @param string $url URL to retrieve.
* @param array $args Optional. Request arguments. Default empty array.
* @return array|WP_Error The response or WP_Error on failure.
*/
protected function wp_safe_remote_get( $url, $args = array() ) {
return self::retry_on_error( 'wp_safe_remote_get', $url, $args );
}
/**
* Wrapper for `wp_safe_remote_post()` that retries on error and skips the test on timeout.
*
* @param string $url URL to retrieve.
* @param array $args Optional. Request arguments. Default empty array.
* @return array|WP_Error The response or WP_Error on failure.
*/
protected function wp_safe_remote_post( $url, $args = array() ) {
return self::retry_on_error( 'wp_safe_remote_post', $url, $args );
}
/**
* Wrapper for `wp_safe_remote_head()` that retries on error and skips the test on timeout.
*
* @param string $url URL to retrieve.
* @param array $args Optional. Request arguments. Default empty array.
* @return array|WP_Error The response or WP_Error on failure.
*/
protected function wp_safe_remote_head( $url, $args = array() ) {
return self::retry_on_error( 'wp_safe_remote_head', $url, $args );
}
/**
* Wrapper for `wp_remote_request()` that retries on error and skips the test on timeout.
*
* @param string $url URL to retrieve.
* @param array $args Optional. Request arguments. Default empty array.
* @return array|WP_Error The response or WP_Error on failure.
*/
protected function wp_remote_request( $url, $args = array() ) {
return self::retry_on_error( 'wp_remote_request', $url, $args );
}
/**
* Wrapper for `wp_remote_get()` that retries on error and skips the test on timeout.
*
* @param string $url URL to retrieve.
* @param array $args Optional. Request arguments. Default empty array.
* @return array|WP_Error The response or WP_Error on failure.
*/
protected function wp_remote_get( $url, $args = array() ) {
return self::retry_on_error( 'wp_remote_get', $url, $args );
}
/**
* Wrapper for `wp_remote_post()` that retries on error and skips the test on timeout.
*
* @param string $url URL to retrieve.
* @param array $args Optional. Request arguments. Default empty array.
* @return array|WP_Error The response or WP_Error on failure.
*/
protected function wp_remote_post( $url, $args = array() ) {
return self::retry_on_error( 'wp_remote_post', $url, $args );
}
/**
* Wrapper for `wp_remote_head()` that retries on error and skips the test on timeout.
*
* @param string $url URL to retrieve.
* @param array $args Optional. Request arguments. Default empty array.
* @return array|WP_Error The response or WP_Error on failure.
*/
protected function wp_remote_head( $url, $args = array() ) {
return self::retry_on_error( 'wp_remote_head', $url, $args );
}
/**
* Retries an HTTP API request up to three times and skips the test on timeout.
*
* @param callable $callback The HTTP API request function to call.
* @param string $url URL to retrieve.
* @param array $args Request arguments.
* @return array|WP_Error The response or WP_Error on failure.
*/
private function retry_on_error( callable $callback, $url, $args ) {
$attempts = 0;
while ( $attempts < 3 ) {
$result = call_user_func( $callback, $url, $args );
if ( ! is_wp_error( $result ) ) {
return $result;
}
++$attempts;
sleep( 5 );
}
$this->skipTestOnTimeout( $result );
return $result;
}
}
|