Automattic / wordbless

WorDBless allows you to use WordPress core functions in your PHPUnit tests without having to set up a database and the whole WordPress environment
Other
130 stars 6 forks source link

How to test 'init' hook? #27

Open szepeviktor opened 3 years ago

szepeviktor commented 3 years ago

As we run code in wp-settings.php we execute a lot of actions.

do_action( 'plugins_loaded' );
do_action( 'sanitize_comment_cookies' );
do_action( 'setup_theme' );
do_action( 'after_setup_theme' );
do_action( 'init' );
do_action( 'wp_loaded' );

How to test code hooked to e.g. after_setup_theme?

szepeviktor commented 3 years ago

Does official WordPress unit testing run these hooks on every test?

szepeviktor commented 3 years ago

@leogermani Please advise.

leogermani commented 3 years ago

Sorry I missed that.

We still have to see how to adapt it to WorDBless but it shouldn't be difficult.

What the official WP test suite does is to use the special tests_add_filter() function to schedule the inclusion of the code to be tested.

Here's an example:

// Give access to tests_add_filter() function.
require_once $_tests_dir . '/includes/functions.php';
/**
 * Manually load the plugin being tested.
 */
function _manually_load_plugin() {
    require dirname( dirname( __FILE__ ) ) . '/src/tainacan.php';
    add_action('plugins_loaded', function() {
        do_action('activate_' . substr(dirname( dirname( __FILE__ ) ), 1) . '/src/tainacan.php');
    }); 
}
tests_add_filter( 'muplugins_loaded', '_manually_load_plugin' );

Most of it is code generated by wp scaffold plugin-tests my-plugin.

We need to do something similar. Will look into it as soon as I can.

szepeviktor commented 3 years ago

What the official WP test suite does is to use the special tests_add_filter() function to schedule the inclusion of the code to be tested.

I see! So the official one also triggers these filters manually :) https://github.com/timber/starter-theme/pull/113#issuecomment-706737128

szepeviktor commented 3 years ago

No :(

Adds hooks before loading WP.

https://github.com/WordPress/wordpress-develop/blob/3439a14e57b1fb6c1b9ecdb7a740a76df1385bd4/tests/phpunit/includes/functions.php#L37-L66