Repository navigation
Expand file tree
/
Copy pathabstract-testcase.php
More file actions
2195 lines (1931 loc) · 65.4 KB
/
Copy pathabstract-testcase.php
File metadata and controls
2195 lines (1931 loc) · 65.4 KB
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
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();
/** @var non-empty-string[] */
protected $caught_doing_it_wrong = array();
/**
* URLs of blocked external HTTP requests made during the current test.
*
* @var list<non-falsy-string>
*/
protected array $blocked_http_requests = array();
protected static $hooks_saved = array();
protected static $ignore_files;
/**
* Metadata state before each class's fixtures are created, keyed by class.
*
* @var array[]
*/
private static $meta_before_class = array();
/**
* Metadata state before the current test, or null when setup was bypassed.
*
* @var array|null
*/
private $original_meta_state;
/**
* The options table rows before the first test class ran, keyed by option name.
*
* @var object[]|null
*/
private static $original_options = null;
/**
* The network's super admins before the first test class ran, or null if not multisite or unset.
*
* @var string[]|null
*/
private static $original_site_admins = null;
/**
* The value of $GLOBALS['locale'] before each test, or null if it was unset.
*
* @var string|null
*/
protected $original_locale;
/**
* The translation controller's locale before each test, or null if
* set_up() did not capture it.
*
* @var string|null
*/
protected $original_translation_locale;
/**
* 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.
*
* @global wpdb $wpdb WordPress database abstraction object.
*/
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 );
/*
* Options and super admins to restore after each class, see restore_options().
* An installed site always has options: no rows means the query failed, and
* restoring to an empty snapshot would delete them all.
*/
if ( null === self::$original_options ) {
$rows = self::get_option_rows();
if ( $rows ) {
self::$original_options = $rows;
self::$original_site_admins = is_multisite() ? get_site_option( 'site_admins', null ) : null;
}
}
/*
* Start from the data a fresh install has. A process-isolated test runs this
* again in its own process, on top of the class fixtures the parent process
* already committed, and would collide with them, e.g. a second `User 1`.
*/
_delete_all_data();
self::flush_cache();
$class = get_called_class();
self::$meta_before_class[ $class ] = self::backup_meta_state();
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' ) );
}
if ( isset( self::$meta_before_class[ $class ] ) ) {
self::restore_meta_state( self::$meta_before_class[ $class ] );
unset( self::$meta_before_class[ $class ] );
}
/*
* The cache still holds values the tests' rollbacks undid, and the cleanup reads
* options, e.g. update_site_option() would not restore `site_admins` if a rolled
* back test left the original value in the cache.
*/
self::flush_cache();
_delete_all_data();
self::restore_options();
self::flush_cache();
self::commit_transaction();
parent::tear_down_after_class();
}
/**
* Fetches the options table rows, keyed by option name.
*
* @return object[] The rows.
*/
private static function get_option_rows() {
global $wpdb;
return $wpdb->get_results( "SELECT option_name, option_value, autoload FROM {$wpdb->options}", OBJECT_K );
}
/**
* Restores the options table rows, and the network's super admins, to the ones
* before the first test class ran.
*
* A test class commits the options it changes while setting up or tearing down,
* e.g. a deleted `blogdescription` or super admins replaced with a fixture user,
* and they would leak into the next classes.
*/
private static function restore_options() {
global $wpdb;
// No snapshot if no class ran the parent set_up_before_class(), e.g. Text_Diff_Check_Test.
if ( null === self::$original_options ) {
return;
}
$current = self::get_option_rows();
foreach ( array_keys( array_diff_key( $current, self::$original_options ) ) as $name ) {
$wpdb->delete( $wpdb->options, array( 'option_name' => $name ) );
}
foreach ( self::$original_options as $name => $row ) {
if ( isset( $current[ $name ] ) && (array) $current[ $name ] === (array) $row ) {
continue;
}
$wpdb->replace( $wpdb->options, (array) $row );
}
if ( null !== self::$original_site_admins ) {
update_site_option( 'site_admins', self::$original_site_admins );
}
}
/**
* Runs the routine before each test is executed.
*
* @global WP_Rewrite $wp_rewrite WordPress rewrite rules object.
*/
public function set_up() {
global $wp_rewrite;
set_time_limit( 0 );
$this->factory = static::factory();
if ( null === self::$ignore_files ) {
self::$ignore_files = $this->scan_user_uploads();
}
if ( ! self::$hooks_saved ) {
$this->_backup_hooks();
}
$this->original_meta_state = self::backup_meta_state();
$this->clean_up_global_scope();
$this->original_locale = $GLOBALS['locale'] ?? null;
$this->original_translation_locale = WP_Translation_Controller::get_instance()->get_locale();
/*
* 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_TESTS_DEFAULT_PERMALINK_STRUCTURE !== $wp_rewrite->permalink_structure ) {
$this->set_permalink_structure( WP_TESTS_DEFAULT_PERMALINK_STRUCTURE );
} else {
// Discard endpoints and extra rules added by previous tests.
$wp_rewrite->init();
}
}
$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 );
if ( defined( 'WP_RUN_CORE_TESTS' ) && WP_RUN_CORE_TESTS
&& ! in_array( 'external-http', $this->getGroups(), true )
) {
add_filter( 'pre_http_request', array( $this, 'block_external_http_request' ), PHP_INT_MAX, 3 );
}
}
/**
* Returns the default-excluded groups that apply to a test and were not explicitly requested.
*
* @param string[] $groups Test groups.
* @return string[] Matching excluded groups.
*/
public static function get_default_excluded_groups_for_test( array $groups ) {
$default_excluded_groups = WP_PHPUnit_Util_Getopt::get_skipped_groups();
foreach ( $groups as $group ) {
if ( WP_PHPUnit_Util_Getopt::is_group_requested( $group ) ) {
return array();
}
}
return array_values(
array_filter(
$groups,
static function ( $group ) use ( $default_excluded_groups ) {
return in_array( $group, $default_excluded_groups, true );
}
)
);
}
/**
* Sets the bcrypt cost option for password hashing during tests.
*
* @param array $options The options for password hashing.
* @param string $algorithm The algorithm to use for hashing.
*/
public function wp_hash_password_options( array $options, string $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.
*
* @global wpdb $wpdb WordPress database abstraction object.
* @global WP_Query $wp_the_query Main WordPress query object.
* @global WP_Query $wp_query WordPress query object.
* @global WP $wp WordPress environment object.
* @global WP_Rewrite $wp_rewrite WordPress rewrite rules object.
*/
public function tear_down() {
global $wpdb, $wp_the_query, $wp_query, $wp, $wp_rewrite;
/*
* Reset permalinks before the transaction rolls back so the in-memory rewrite state
* remains synchronized with the restored database option for subsequent class fixtures.
*/
if ( defined( 'WP_RUN_CORE_TESTS' ) && WP_RUN_CORE_TESTS && WP_TESTS_DEFAULT_PERMALINK_STRUCTURE !== $wp_rewrite->permalink_structure ) {
$this->set_permalink_structure( WP_TESTS_DEFAULT_PERMALINK_STRUCTURE );
}
$wpdb->query( 'ROLLBACK' );
/*
* A persistent object cache still holds the values the rollback just undid.
* Flush it now: a process-isolated test bootstraps WordPress against it
* before its own set_up() runs, and would act on the stale values,
* e.g. a rolled back `theme_switched` option rebuilding the sidebars.
*/
if ( wp_using_ext_object_cache() ) {
self::flush_cache();
}
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 the Customizer global so that `is_customize_preview()` is false when the next test runs.
$GLOBALS['wp_customize'] = null;
// Reset comment globals.
$comment_globals = array( 'comment_alt', 'comment_depth', 'comment_thread_alt', 'in_comment_loop' );
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();
if ( null !== $this->original_meta_state ) {
self::restore_meta_state( $this->original_meta_state );
}
wp_set_current_user( 0 );
// Restore the locale captured in set_up(); skip it for tests that bypass parent::set_up().
if ( null !== $this->original_translation_locale ) {
if ( null === $this->original_locale ) {
unset( $GLOBALS['locale'] );
} else {
$GLOBALS['locale'] = $this->original_locale;
}
WP_Translation_Controller::get_instance()->set_locale( $this->original_translation_locale );
}
$this->reset_lazyload_queue();
WP_Style_Engine_CSS_Rules_Store::remove_all_stores();
}
/**
* 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 All of the filters and actions.
* @global array<string, positive-int> $wp_actions The number of times each action was triggered.
* @global array<string, positive-int> $wp_filters The number of times each filter was triggered.
* @global array $wp_current_filter The list of current filters with the current one last.
*/
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 All of the filters and actions.
* @global array<string, positive-int> $wp_actions The number of times each action was triggered.
* @global array<string, positive-int> $wp_filters The number of times each filter was triggered.
* @global array $wp_current_filter The list of current filters with the current one last.
*/
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.
*
* @global WP_Object_Cache $wp_object_cache WordPress Object Cache object.
*/
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' ) );
}
/**
* Captures registrations and their hooks without re-registering metadata.
*
* The hooks also include legacy registrations without a registry entry and
* callbacks added independently of register_meta().
*
* @return array Metadata registry and cloned metadata hooks.
*/
private static function backup_meta_state() {
$state = array(
'keys' => $GLOBALS['wp_meta_keys'] ?? array(),
'hooks' => array(),
);
foreach ( $GLOBALS['wp_filter'] as $name => $hook ) {
if ( self::is_meta_hook( $name ) ) {
$state['hooks'][ $name ] = clone $hook;
}
}
return $state;
}
/**
* Restores metadata hooks after the ordinary hook baseline has been restored.
*
* @param array $state Metadata state captured before the test or class.
*/
private static function restore_meta_state( $state ) {
$GLOBALS['wp_meta_keys'] = $state['keys'];
foreach ( array_keys( $GLOBALS['wp_filter'] ) as $name ) {
if ( self::is_meta_hook( $name ) ) {
unset( $GLOBALS['wp_filter'][ $name ] );
}
}
foreach ( $state['hooks'] as $name => $hook ) {
$GLOBALS['wp_filter'][ $name ] = clone $hook;
}
}
/**
* Identifies the dynamic hooks used by metadata registrations and defaults.
*
* @param string $name Hook name.
* @return bool Whether the hook belongs to the metadata state.
*/
private static function is_meta_hook( $name ) {
return (bool) preg_match( '/^(?:sanitize|auth)_.+_meta_|^default_.+_metadata$/', $name );
}
/**
* Cleans up any registered meta keys.
*
* @since 5.1.0
*
* @global array $wp_meta_keys Global registry for 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.
*
* @global wpdb $wpdb WordPress database abstraction object.
*/
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
*
* @global wpdb $wpdb WordPress database abstraction object.
*/
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() {
$method_name = method_exists( $this, 'name' ) ? $this->name() : $this->getName( false );
$class = new ReflectionClass( $this );
$reflectors = array(
'class' => array_merge( array_values( $class->getTraits() ), array( $class ) ),
'method' => array( $class->getMethod( $method_name ) ),
);
$annotations = array(
'class' => array(),
'method' => array(),
);
foreach ( $reflectors as $depth => $depth_reflectors ) {
foreach ( $depth_reflectors as $reflector ) {
$docblock = substr( (string) $reflector->getDocComment(), 3, -2 );
$doc_annotations = array();
// Parse all tags before filtering so annotation values remain intact.
if ( preg_match_all( '/@([A-Za-z_-]+)(?:[ \t]+(.*?))?[ \t]*\r?$/m', $docblock, $matches, PREG_SET_ORDER ) ) {
foreach ( $matches as $match ) {
if ( in_array( $match[1], array( 'expectedDeprecated', 'expectedIncorrectUsage' ), true ) ) {
$doc_annotations[ $match[1] ][] = $match[2] ?? '';
}
}
}
// Later traits and the class replace earlier values for the same annotation.
$annotations[ $depth ] = array_merge( $annotations[ $depth ], $doc_annotations );
}
}
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 ) );
}
}
/**
* Blocks an external HTTP request that no other filter has answered.
*
* Added by set_up() for tests that are not in the `external-http` group, and
* runs last on the filter so any mock set up by the test itself gets the
* first say. Requests reaching this point are recorded and fail the test in
* assert_post_conditions().
*
* @since 7.2.0
*
* @param false|array|WP_Error $response A preemptive response, or false when none was given.
* @param array $args Request arguments.
* @param string $url The request URL.
* @return array|WP_Error The preemptive response, or an error for a blocked request.
*/
public function block_external_http_request( $response, array $args, string $url ) {
if ( false !== $response ) {
return $response;
}
$this->blocked_http_requests[] = $url;
return new WP_Error(
'test_external_http_blocked',
'External HTTP requests are blocked in tests that are not in the `external-http` group.'
);
}
/**
* 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();