This is the documentation for version 3 of the project. The current version is version 4 and the documentation can be found here.
WPLoader module
This module should be used in integration tests, see levels of testing for more information, to bootstrap WordPress code in the context of the tests.
Setting the loadOnly
parameter to true
the module can be additionally used in acceptance and functional tests to access WordPress code in the tests context.
This module is a wrapper around the functionalities provided by the WordPress PHPUnit Core test suite, as such it provides the same method and facilities.
The parameters provided to the module duplicate the ones used in the WordPress configuration file: the WPLoader
module will not bootstrap WordPress using the wp-config.php
file, it will define and use its own WordPress configuration built from the module parameters.
Everything happens in a transaction
When used to bootstrap and install WordPress (loadOnly: false
) exactly as the the WordPress PHPUnit Core test suite it is based on, this module will operate any change to the database in a transaction.
This means that, in the context of integration tests, the result of any write or delete operation done during the tests will be rolled back at the end of each test method; this is done for a number of reasons like performance and tests independence.
Inspection of the database during tests, e.g. stopping execution using XDebug, will not show any change in the database.
Keep this in mind while trying to debug integration tests using the WPLoader
module.
When configured to only load WordPress (loadOnly: true
) then any database operation will be committed and written to the database.
Configuration
wpRootFolder
required The absolute, or relative to the project root folder, path to the root WordPress installation folder. The WordPress installation root folder is the one that contains thewp-load.php
file.dbName
required - The name of the database used by the WordPress installation, same as theDB_NAME
constant.dbHost
required - The host of the database used by the WordPress installation, same as theDB_HOST
constant. If the database is accessible (as is the case on the latest version of [Local by Flywheel][http://localwp.com]) via unix socket, then the string to insert here should look like thislocalhost:/path/to/the/mysql.sock
.dbUser
required - The user of the database used by the WordPress installation, same as theDB_USER
constant.dbPassword
required - The password of the database used by the WordPress installation, same asDB_PASSWORD
constant.loadOnly
- defaults tofalse
; whether to only load WordPress, without bootstrapping a fresh installation for tests or not. Read more in the "Using WPLoader in acceptance and functional tests" section. If this parameter is set totrue
the following parameters will not apply.isolatedInstall
- defaults totrue
, whether to install and bootstrap the WordPress installation in a secondary PHP thread for thread safety or not. Maintained for back-compatibility purposes with wp-browser first versions: to get a replica of the bootstrap process used by WordPress Core PHPUnit tests leave this totrue
.installationTableHandling
- defaults toempty
; it controls how tables created by WordPress and plugins will be handled during the installation of WordPress during tests. By default tables will be emptied of any content, but some plugins might require tables to be dropped before WordPress is installed and after plugins are activated (this used to be the default behavior). Supported values aredrop
to drop the tables,empty
to just empty the tables andlet
to do nothing about the tables. If you get errors from database queries while theWPLoader
module installs the tests, then try changing this parameter value.wpDebug
- defaults totrue
, the value theWP_DEBUG
constant will be set to.multisite
- defaults tofalse
, the value theMULTISITE
constant will be set to.skipPluggables
- defaults tofalse
, if set totrue
will skip the definition of pluggable functions.dbCharset
- defaults toutf8
, the value theDB_CHARSET
constant will be set to.dbCollate
- defaults to an empty string, the value theDB_COLLATE
constant will be set to.tablePrefix
- defaults towptests_
, the value the$table_prefix
variable will be set to.domain
- defaults toexample.org
, the domain of the WordPress site to scaffold for the tests.adminEmail
- defaults toadmin@example.org
, the email of the WordPress site to scaffold for the tests.title
- defaults toTest Blog
, the title of the WordPress site to scaffolded for the tests.phpBinary
- defaults tophp
, the PHP binary the host machine will have to use to bootstrap and load the test WordPress installation.language
- defaults to an empty string, the language of the WordPress installation to scaffold.configFile
- defaults to an empty string, an additional configuration file to include before loading WordPress. Any instruction in this fill will run before any WordPress file is included.contentFolder
- defaults to an empty string; the path, relative to thewpRootFolder
or absolute, to the content folder if different from the default one or the one defined by theWP_CONTENT_DIR
constant; if theWP_CONTENT_DIR
constant is defined in a config file (see theconfigFile
parameter) this will be ignored.pluginsFolder
- defaults to an empty string; the path, relative to thewpRootFolder
or absolute, to the plugins folder from thewpRootFolder
if different from the default one or the one defined by theWP_PLUGIN_DIR
constant; if theWP_PLUGIN_DIR
constant is defined in a config file (see theconfigFile
parameter) this will be ignored.plugins
- defaults to an empty array; a list of plugins that should be loaded before any test case runs and after mu-plugins have been loaded; these should be defined in thefolder/plugin-file.php
format.activateplugins
- defaults to an empty array, a list of plugins that will be activated before any test case runs and after wordpress is fully loaded and set up; these should be defined in thefolder/plugin-file.php
format; when themultisite
option is set totrue
the plugins will be network activated during the installation.activatePluginsSilently
- defaults to an empty array, a list of plugins that will be silently activated, thus not firing the plugins' activation actions, before any test case runs and after wordpress is fully loaded and set up; these should be defined in thefolder/plugin-file.php
format; when themultisite
option is set totrue
the plugins will be network activated during the installation.bootstrapActions
- defaults to an empty string, a list of actions, static functions or functions that should be called after before any test case runs, after plugins have been loaded and activated; static functions should be defined in the YAML array format:-
theme
- defaults to an empty string, the theme that should be activated for the tests; if a string is passed then bothtemplate
andstylesheet
options will be set to the passed value; if an array is passed then thetemplate
andstylesheet
will be set in that order:The theme will be set to
my-theme
.The
template
will be set toparent
, thestylesheet
will be set tochild
.
A word of caution: right now the only way to write tests able to take advantage of the suite is to use the WP_UnitTestCase
test case class; while the module will load fine and will raise no problems WP_UnitTestCase
will take care of handling the database as intended and using another test case class will almost certainly result in an error if the test case defines more than one test method.
Example configuration
modules:
enabled:
- WPLoader
config:
WPLoader:
multisite: false
wpRootFolder: "/Users/luca/www/wordpress"
dbName: "wordpress_tests"
dbHost: "localhost"
dbUser: "root"
dbPassword: "password"
isolatedInstall: true
installationTableHandling: drop
tablePrefix: "wptests_"
domain: "wordrpess.localhost"
adminEmail: "admin@wordpress.localhost"
title: "Test Blog"
theme: my-theme
plugins: ['hello.php', 'my-plugin/my-plugin.php']
activatePlugins: ['hello.php', 'my-plugin/my-plugin.php']
Usage in integration or "WordPress unit" tests
The most common use of this module is to run integration, or "WordPress unit" tests (see levels of testing for more information).
As a first step generate a WPTestCase
using Codeception command-line utility (see the commands provided by wp-browser):
Codeception will generate the tests/my_suite/Acme/UserTest.php
class.
The class extends the Codeception\TestCase\WPTestCase
class provided by wp-browser; this looks like a normal PHPUnit test case but has some perks due to it's mixed breed nature.
Understanding them might help you work with it:
- WordPress is installed and configured for the tests before the test case is loaded; WordPress defined functions and classes (and those of the plugins and themes loaded with it) will be available in the
setUpBeforeClass
method. - WordPress is not loaded when PHPUnit will call the data provider methods; this means the
post_provider
method will generate a function not found exception when the test case runs as the WordPress defined methods are not loaded yet:public function post_provider(){ // `wp_insert_post` is loaded with WordPress and WordPress has not been loaded yet! return [ [wp_insert_post(['post_title' => 'Test', 'post_status' => 'publish'])] ]; } public function test_posts($post_id){ $this->assertInstanceOf(WP_Post::class, get_post($post_id)); }
- WordPress is reset to an initial known state before each test runs; the database transaction is rolled back to wipe any data and tables you might have manipulated in the tests, the global space is cleaned. See Everything happens in a transaction.
- This is a Codeception Unit test, as such it does provide access to the
$this->tester
property to access the methods defined in other modules loaded in the suite and to Codeception test doubles - This is a PhpUnit test case too; there are way too many testing functions to cover to report them here but, to highlight a few: mocking with Prophecy and the wealth of PHPUnit assertion methods.
- This is kind of a WordPress Core suite test case; as such it provides access to its functions and to the often-overlooked
static::factory()
method; in this instance too there are too many methods to list them all but it's worth noting how easy it is to set up test fixtures with the factory: - The
factory
property can be accessed on thetester
property too and will work the same way as if called usingstatic::factory()
:
WPLoader to only bootstrap WordPress
If the need is to just bootstrap the WordPress installation in the context of the tests variable scope then the WPLoader
module loadOnly
parameter should be set to true
; this could be the case for functional tests in need to access WordPress provided methods, functions and values.
An example configuration for the module in this mode is this one:
modules:
enabled:
- WPDb # BEFORE the WPLoader one!
- WPLoader # AFTER the WPDb one!
config:
WPDb:
dsn: 'mysql:host=localhost;dbname=wordpress'
user: 'root'
password: 'password'
dump: 'tests/_data/dump.sql'
populate: true
cleanup: true
waitlock: 10
url: 'http://wordpress.localhost'
urlReplacement: true
tablePrefix: 'wp_'
WPLoader:
loadOnly: true
wpRootFolder: "/Users/User/www/wordpress"
dbName: "wpress-tests"
dbHost: "localhost"
dbUser: "root"
dbPassword: "root"
domain: "wordpress.localhost"
With reference to the table above the module will not take care of the test WordPress installation state before and after the tests, the installed and activated plugins, and theme.
The module can be used in conjunction with a WPDb
module to provide the tests with a WordPress installation suiting the tests at hand; when doing so please take care to list, in the suite configuration file modules
section (see example above) the WPDb
module before the WPLoader
one.
Codeception will initialize the modules in the same order they are listed in the modules section of the suite configuration file and the WPLoader module needs the database to be populated by the WPDb
module before it runs!
As an example this is a correct suite configuration:
modules:
enabled:
- WPDb # this before...
- WPLoader # ...this one.
config:
WPDb:
# ...
WPLoader:
loadOnly: true
# ...
Public API
debugWpActionFinal
Debugs a single WordPress action final call using Codeception debug functions. The output will show following the selected output verbosity (--debug
and -vvv
CLI options).
// Start debugging all WordPress actions final value.
add_action('all', [$this,'debugWpActionFinal']);
// Run some code firing actions and debug them.
// Stop debugging all WordPress actions final value.
remove_action('all', [$this,'debugWpActionFinal']);
Parameters
mixed
$args
debugWpActionInitial
Debugs a single WordPress action initial call using Codeception debug functions. The output will show following the selected output verbosity (--debug
and -vvv
CLI options).
// Start debugging all WordPress actions initial value.
add_action('all', [$this,'debugWpActionInitial']);
// Run some code firing actions and debug them.
// Stop debugging all WordPress actions initial value.
remove_action('all', [$this,'debugWpActionInitial']);
Parameters
mixed
$args
debugWpFilterFinal
Debugs a single WordPress filter final call using Codeception debug functions. The output will show following the selected output verbosity (--debug
and -vvv
CLI options).
// Start debugging all WordPress filters final value.
add_filter('all', [$this,'debugWpFilterFinal']);
// Run some code firing filters and debug them.
// Stop debugging all WordPress filters final value.
remove_filter('all', [$this,'debugWpFilterFinal']);
Parameters
mixed
$args
debugWpFilterInitial
Debugs a single WordPress filter initial call using Codeception debug functions. The output will show following the selected output verbosity (--debug
and -vvv
CLI options).
// Start debugging all WordPress filters initial value.
add_filter('all', [$this,'debugWpFilterInitial']);
// Run some code firing filters and debug them.
// Stop debugging all WordPress filters initial value.
remove_filter('all', [$this,'debugWpFilterInitial']);
Parameters
mixed
$args
factory
Accessor method to get the object storing the factories for things. This methods gives access to the same factories provided by the Core test suite.
$postId = $I->factory()->post->create();
$userId = $I->factory()->user->create(['role' => 'administrator']);
getContentFolder
Returns the absolute path to the WordPress content directory.
$content = $this->getContentFolder();
$themes = $this->getContentFolder('themes');
$twentytwenty = $this->getContentFolder('themes/twentytwenty');
Parameters
string
$path - An optional path to append to the content directory absolute path.
getPluginsFolder
Returns the absolute path to the plugins directory. The value will first look at the WP_PLUGIN_DIR
constant, then the pluginsFolder
configuration parameter and will, finally, look in the default path from the WordPress root directory.
Parameters
string
$path - A relative path to append to te plugins directory absolute path.
startWpFiltersDebug
Starts the debug of all WordPress filters and actions. The method hook on all
filters and actions to debug their value.
// Start debugging all WordPress filters and action final and initial values.
$this->startWpFiltersDebug();
// Run some code firing filters and debug them.
// Stop debugging all WordPress filters and action final and initial values.
$this->stopWpFiltersDebug();
the array of arguments as input.
Parameters
\callable
$format - A callback function to format the arguments debug output; the callback will receive
stopWpFiltersDebug
Stops the debug of all WordPress filters and actions.
// Start debugging all WordPress filters and action final and initial values.
$this->startWpFiltersDebug();
// Run some code firing filters and debug them.
// Stop debugging all WordPress filters and action final and initial values.
$this->stopWpFiltersDebug();
This class extends \Codeception\Module