jk's blog

WordPress Unit Tests in the Main Directory

I’m hacking some of the original WP files. Not the smartest thing to do, but the options are to replace the functions, or alter them, because a plugin isn’t going to work.

So, I needed to run tests in the main program. Here’s the quck howto.

Install wp-cli and get it working.

Then, go into your wp root and type:

wp scaffold plugin-tests --dir=.

Then run the installer script:

bin/install-wp-tests.sh wordpress_test root '--password--'

That sets up your test environment, but it should also not work. If you are testing other things, like plugins, the old install might interfere.

Edit bootstrap.php, and remove the function _manually_load_plugin() and the function call that adds to filter to muplugins_loaded. It should look like this:

$_tests_dir = getenv( 'WP_TESTS_DIR' );
if ( ! $_tests_dir ) {
    $_tests_dir = '/tmp/wordpress-tests-lib';

require_once $_tests_dir . '/includes/functions.php';

require $_tests_dir . '/includes/bootstrap.php';

Now, you should be able to run ‘phpunit’ from the WP root, and see the sample test run.

The boostrap doesn’t load up all the functions defined in the pages in the root directory – those functions aren’t defined until you execute the file, via a URL like wp-signup.php or wp-activate.php.

So, you’ll need to load your scripts via include()s. This is fine if your functions are in a file like my-functions.php.

If you want to modify functions in a file like wp-signup.php, you’re “somewhat out of luck”. You need to separate out the function definitions from the rest of the page. For example, in wp-signup, you could move the function definitions to another file, and then, in wp-signup, include it.

wp-signup will then contain only the code at the top of the page, and the code at the bottom of the page. There are around 80 lines at the top, and around 150 lines at the bottom.

An alternative technique is to copy all the functions to a separate file, then rename them. Then, alter all the function calls to use the new names. This way, the original is mostly untouched, and you are free to alter the functions.