The library provides some custom commands that can be added to the project Codeception configuration file (
+either codeception.yml or codeception.dist.yml).
+
run and codeception:run
+
WordPress extensive use of global variables, constants and side effectes makes it difficult to run multiple test suites
+in the same process without running into conflicts due to leaking state and side effects.
+For this reason the project replaces Codeception run command with one that will run each suite in a separate process.
+You can invoke the original Codeception command using the codeception:run command.
+Just like the original, the run command accepts all the arguments and options of the original Codeception
+command.
+
Run all the suites, each one in a separate process:
If not already running, start the services required to run the tests.
+The started services are read from the Codeception configuration file (either codeception.yml
+or codeception.dist.yml), from the extensions section, under the config key.
Running the command will start ChromeDriver, the built-in PHP server and Docker Compose.
+
dev:stop
+
If running, stop the services required to run the tests.
+The stopped services are read from the Codeception configuration file (either codeception.yml
+or codeception.dist.yml), from the extensions section, under the config key.
You can use WP CLI to interact with your WordPress installation, but WP CLI does not support SQLite databases in
+the context of the wp db import command.
+This command fills that gap by providing a database dump file import command that will support MySQL and SQLite
+databases.
+
wp:db:export
+
You can use WP CLI to interact with your WordPress installation, but WP CLI does not support SQLite databases in
+the context of the wp db export command.
+This command fills that gap by providing a database dump file export command that will support MySQL and SQLite
+databases.
+
chromedriver:update
+
If you're using Chromedriver as a binary installed in the Composer vendor directory (vendor/bin by default), you can
+use this command to update it.
+This command will download the latest version of Chromedriver compatible with the Chrome version installed on your
+machine in the Composer vendor directory.
+
generate:wpunit
+
Generate a test case extending the lucatume\WPBrowser\TestCase\WPTestCase class.
+The class incorporates the WordPress test case from the wordpress-develop repository and adds some utility
+methods to make testing easier in the context of Codeception.
+
The lucatume\WPBrowser\TestCase\WPTestCase class is the one that should be used when writing tests for WordPress
+code when using the WPLoader module.
+
Together with the WPLoader module, the WPTestCase class provides a number of functionalities to clean up the
+database
+after each test method and to reset the global state of WordPress.
+
Every test method runs in a transaction
+
Database queries running in the context of test methods of a test case extending the WPTestCase class will run in a
+transaction that is rolled back after the test method is run. This means that any database change happening in the
+context of a test method will not appear in the database while the test is running and after the test is run.
Any non default configuration is considered a custom configuration.
+If your project requires a tailored set up, this is the configuration for you.
+
Using a custom configuration to run tests
+
If you decide to skip the default configuration, or are working
+on a project that cannot use the default configuration
+you will be able to set up wp-browser to suit your needs using a custom configuration.
+
Choose "no", to not use the default configuration, when running the vendor/bin/codecept init wpbrowser command.
+
The command will set up the file structure to be able to run integration and end-to-end tests and will
+leverage Codeception dynamic configuration using parameters to control the testing stack using the tests/.env
+file.
+
Walkthrough of the tests/.env file
+
+
WORDPRESS_ROOT_DIR - the path to the root WordPress installation directory. This is the directory that contains
+ WordPress files, like wp-load.php. This path can be absolute or relative to the root project directory;
+ e.g. vendor/wordpress (relative) or /var/www/wordpress (absolute) will work.
+
WORDPRESS_URL - the URL of the WordPress installation. This is the URL that will be used by the browser to access
+ the WordPress
+ installation in the context of end-to-end tests; e.g. http://localhost:8080 or https://wordpress.local.
+
WORDPRESS_DOMAIN - the domain of the WordPress installation; this value should follow the WORDPRESS_URL value.
+ E.g. if WORDPRESS_URL is http://localhost:8080 the WORDPRESS_DOMAIN value should be localhost:8080;
+ if WORDPRESS_URL is https://wordpress.local the WORDPRESS_DOMAIN value should be wordpress.local.
+
WORDPRESS_DB_URL - the user, password, host, and name of the database used by the tests. If the database is a MySQL
+ database, the value should be in the form mysql://user:password@host:port/database_name.
+ If the database is a SQLite database, the value should be in the form sqlite://path/to/database/file.
+
WORDPRESS_TABLE_PREFIX - the database table prefix used by the WordPress installation, the one served
+ at WORDPRESS_URL.
+ This value is usually wp_ but can be different if the WordPress installation has been configured to use a different
+ prefix.
+
TEST_TABLE_PREFIX - the database table prefix used by the WPLoader module to
+ install WordPress and run the tests. This value is usually test_ and should be different from
+ the WORDPRESS_TABLE_PREFIX value.
+
WORDPRESS_ADMIN_USER - the username of the WordPress administrator user. E.g. admin.
+
WORDPRESS_ADMIN_PASSWORD - the password of the WordPress administrator user. E.g. secret!password.
+
CHROMEDRIVER_HOST - the host of the Chromedriver server. This value is usually localhost if you're running
+ Chromedriver on the same machine as the tests. If you're running your tests using a container stack, it will be the
+ name of the container running Chromedriver, e.g. chromedriver.
+
CHROMEDRIVER_PORT - the port of the Chromedriver server. This value is usually 9515 if you're running Chromedriver
+ on the same machine as the tests. If you're running your tests using a container stack, it will be the port exposed by
+ the container running Chromedriver, e.g. 4444. Note the default configuration will set
+ this value to a random port during set up to avoid conflicts with other services running on the same machine.
The recommended configuration for most projects.
+It allows you to get into WordPress integration and end-to-end testing quickly and easily.
+
Requirements
+
The default configuration will set up Codeception and wp-browser to use SQLite as the database engine, PHP built-in
+server to serve the test site on localhost and your local version of Chrome, driven by Chromedriver, to run end-to-end
+tests.
+
As such, the default configuration has the following requirements:
+
+
the sqlite3 PHP extension; you can check if if's installed by running php -m | grep sqlite3 in your terminal
+
the pdo_sqlite PHP extension; you can check if if's installed by running php -m | grep pdo_sqlite in your terminal
+
PHP built-in server can work with only one thread, but it will be faster using multiple threads; multiple threads are
+ not supported on Windows, but they are supported on WSL.
+
the Chrome browser installed on your machine
+
+
Overview - plugin and theme project
+
If you're configuring wp-browser for a plugin or theme project, the default configuration will install WordPress in
+the tests/_wordpress directory and configure the installation to run using SQLite as a database engine.
+The SQLite Database Integration plugin) will be placed in the installation must-use plugins directory.
+
If your plugin or theme project requires additional plugins or theme to work, you can place them in
+the tests/_worpdress/wp-content/plugins and tests/_wordpress/wp-content/themes directories respectively.
+
When adding, or removing, plugin and themes, remember to
+update the WPLoader module configuration to load the correct plugins and themes in
+your integration tests.
+
On the same note, update the database dump used by the WPDb module to reflect the
+changes in the dump loaded in the end-to-end tests.
+The easiest way to update the database fixture is to load the current database dump
+using the wp:db:import command, manually setting up the site interacting with it and then
+exporting the database dump using the wp:db:export command.
+
You can find out about the URL of the site served by the PHP built-in web server by
+running the dev:info command.
+
Overview - site project
+
If you're configuring wp-browser for a site project, the default configuration will use a combination of PHP built-in
+web server and the SQLite Database Integration plugin to run the tests and serve your site.
+
The router file used by the PHP built-in web server will force the site, when served on localhost, to use SQLite as
+database engine leaving your existing local MySQL database untouched.
+
Your existing WordPress installation will be picked up as it is, with all the plugins and themes found in the contents
+directory.
+
Existing plugins and themes are not added to WPLoader module configuration by
+wp-browser, you have to do that manually.
+
Similarly, the database dump used by the WPDb module is, by default, an empty WordPress
+installation where no plugins and themes are active.
+You have to update the database dump used by the module to reflect the state of your site.
+You can do that by loading the current database dump using the wp:db:import command,
+manually setting up the site interacting with it and then
+exporting the database dump using the wp:db:export command.
+
You can find out about the URL of the site served by the PHP built-in web server by
+running the dev:info command.
+
When not to use the default configuration
+
The default configuration is the recommended one for most projects, but some projects might require you to use a custom
+configuration to make the most out of wp-browser.
+
Database drop-in
+
The default configuration will use the SQLite Database Integration plugin to use SQLite as the database engine.
+This requires placing a db.php drop-in file in the WordPress content directory.
+
If your project already requires a db.php drop-in file, you will have to use a custom configuration.
+
Multisite with sub-domains
+
While Chrome will handle sub-domains correctly, even on localhost, WordPress will not.
+If you're testing a multisite installation with sub-domains, you will have to use a custom configuration.
+
Custom site structure
+
If your site uses a customized file structure to manage WordPress, you will need to configure wp-browser using a custom
+configuration.
+This is usually true for some site projects, and will most likely not be an issue for plugin and theme projects.
The library provides some custom Codeception extensions that can be added to the project Codeception configuration file,
+in the extensions section.
+
BuiltInServerController
+
This extension will start and stop the PHP built-in web server before and after the tests run.
+
The extension can be configured with the following parameters:
+
+
required
+
docRoot - the document root to use for the PHP Built-in server; it can be either an absolute path or a path
+ relative to the Codeception root directory.
+
+
+
optional
+
suites - an array of Codeception suites to run the server for; if not set the server will be started for all the
+ suites.
+
port - the port to use for the PHP Built-in server, if not set the server will use port 2389.
+
workers - the number of workers to use for the PHP Built-in server, if not set the server will use 5 workers.
+ This is the equivalent of the PHP_CLI_SERVER_WORKERS environment variable.
+
+
+
+
+
Note: if you run PHP built-in server on Windows, the workers parameter will be ignored and the server will always
+run with a single worker. This limit is not present in WSL.
+
+
Example configuration starting the server for all suites:
You can use the chromedriver:update command to download the latest version of
+ChromeDriver
+compatible with your Chrome browser version and place it in the Composer bin directory.
+
This is a service extension that will be started and stopped by the dev:start
+and dev:stop commands.
+
DockerComposeController
+
This extension will start and stop a docker compose stack before and after the tests are run.
+
The extension can be configured with the following parameters:
+
+
required
+
compose-file - the path to the docker compose file to use; it can be either an absolute path or a path
+ relative to the Codeception root directory.
+
+
+
optional
+
env-file- the path to the environment file to use; it can be either an absolute path or a path.
+
+
+
+
Example configuration starting the server for all suites:
This is the documentation for version 4 of the project, the current version.
+Documentation for the previous version of the project, version 3, can be found here.
+
+
The wp-browser library provides a set of Codeception modules and middleware to enable the testing of WordPress sites, plugins and themes.
+
Installation
+
Add wp-browser to your project as a development dependency using Composer
PHP built-in web server to serve the WordPress site on localhost (e.g. http://localhost:8080)
+
Chromedriver to drive the local version of Chrome installed on your machine
+
+
If you're working on a plugin or theme project, the default configuration will add some extra steps:
+
+
install the latest version of WordPress in the tests/_wordpress directory
+
create a tests/_plugins directory: any file or directory in this directory will be symlinked into the WordPress
+ installation in tests/_wordpress/wp-content/plugins
+
create a tests/_themes directory: any file or directory in this directory will be symlinked into the WordPress
+ installation in tests/_wordpress/wp-content/themes
+
+
For most projects this configuration will be enough to get started with testing.
+
You can run your tests immediately using the vendor/bin/codecept run command.
If you decide to skip the default configuration, you will be able to set up wp-browser to suit your needs and local
+setup by editing the tests/.env file.
+The inline documentation in the file will guide you through the configuration process.
Getting support for wp-browser configuration and usage
+
The best place to get support for wp-browser is the project documentation.
+Since this project builds on top of PHPUnit and Codeception, you can also refer to their documentation.
Browse and test the site HTML with a fast browser without Javascript support.
+
This module trades the WPWebDriver module Javascript support for speed and stability. It is a good
+choice for testing sites that don't use Javascript or to make assertions that do not require Javascript support like:
This module is an extension of the Codeception PHPBrowser module, you can reference to the Codeception module
+documentation for more information on the module configuration and usage.
+
This module should be with Cest and Cept test cases.
+
Configuration
+
+
url - required; the start URL of your WordPress project.
+
adminUsername - required; the site administrator username to use in actions like loginAsAdmin.
+
adminPassword - required; the site administrator password to use in actions like loginAsAdmin.
+
adminPath - the path to the WordPress admin directory; defaults to /wp-admin.
headers - default headers are set before each test.
+cookies - default cookies are set before each test.
+auth - default authentication to be set before each test.
Use WP-CLI to interact with the WordPress installation under test and issue commands.
+
This module is used in the context of end-to-end testing, together with, or as a replacement for
+the WPDb module to manipulate the database and the WPFilesystem module to manipulate the
+site file structure.
+
This module should be with Cest and Cept test cases.
+
Configuration
+
+
path - required; the path to the WordPress installation under test. This can be a relative path to the
+ codeception root directory, or an absolute path to the WordPress installation directory. The WordPress installation
+ directory is the directory that contains the wp-load.php file.
+
url - the URL of the WordPress installation under test. Equivalent to the --url option of the wp command.
+
user - the user to use to run the wp command. Equivalent to the --user option of the wp command.
+
skip-plugins - a boolean value to indicate if the wp command should skip loading plugins. Equivalent to the
+ --skip-plugins option of the wp command.
+
skip-themes - a boolean value to indicate if the wp command should skip loading themes. Equivalent to the
+ --skip-themes option of the wp command.
+
skip-packages - a boolean value to indicate if the wp command should skip loading packages. Equivalent to the
+ --skip-packages option of the wp command.
+
require - a list of PHP files to require before running the wp command. Equivalent to the --require option of
+ the wp command.
+
exec - PHP code to execute before running the wp command. Equivalent to the --exec option of the wp command.
+
context - the context to use when running the wp command. Equivalent to the --context option of the wp
+ command.
+
color - a boolean value to indicate if the wp command should output in color. Equivalent to the --color option
+ of the wp command.
+
no-color - a boolean value to indicate if the wp command should not output in color. Equivalent to the
+ --no-color option of the wp command.
+
debug - a boolean value to indicate if the wp command should output debug information. Equivalent to the
+ --debug option of the wp command.
+
quiet - a boolean value to indicate if the wp command should suppress informational messages. Equivalent to the
+ --quiet option of the wp command.
+
throw - a boolean value to indicate if the wp command should throw an exception if the command fails.
+
timeout - the timeout to use when running the wp command. When the timeout is reached the command will be
+ terminated as a failure.
+
cache-dir - the directory to use to cache the files WPCLI might downloads. Equivalent to setting
+ the WP_CLI_CACHE_DIR
+ environment variable.
+
config-path - the path to the wp-cli.yml file to use. Equivalent to setting the WP_CLI_CONFIG_PATH
+ environment variable.
+
custom-shell - the shell to use to run the wp command. Equivalent to setting the WP_CLI_SHELL environment
+ variable.
+
packages-dir - the directory to use to store the packages downloaded by the wp package command. Equivalent to
+ setting the WP_CLI_PACKAGES_DIR environment variable.
+
+
The following is an example of the module configuration to run WPCLI commands on the /var/wordpress directory:
This module allows to manipulate the database of the WordPress installation under test directly, without using the
+WordPress API.
+
The module is used together with the WPBrowser module, WPWebDriver
+and WPFilesystem modules to control the site state, the database, and the site file structure.
+
Note about interaction with the WPLoader module: both this module and the WPLoader one can be used to
+control the state of the database before tests and set up fixtures: use either this or WPLoader, do not use both.
+This module should be used in end-to-end testing, the WPLoader module should be used in integration
+testing.
+If you're using this module to load a database dump before integration tests,
+use the WPLoader moduledump configuration parameter instead.
+
This module should be with Cest and Cept test cases.
+
Configuration
+
This module extends the Codeception Db module adding some configuration options and functions that are specific to
+WordPress.
+
+
dbUrl - required; the URL to use to connect to the database. The URL must be in the form
+ mysql://user:password@host:port/database if you're using a MySQL database for your tests, or in the form
+ sqlite://path/to/database/file if you're using a SQLite database for your tests (
+ like the default configuration does)
+
dsn - required; the DSN to use to connect to the database; required if not using the dbUrl parameter.
+
user - required; the user to use to connect to the database; required if not using the dbUrl parameter.
+
password - required; the password to use to connect to the database; required if not using the dbUrl
+ parameter.
+
url - required;the URL of the WordPress installation under test. E.g. http://localhost:8080
+ or https://wordpress.test.
+
tablePrefix - the table prefix to use when interacting with the database; defaults to wp_.
+
dump - the path to a database dump file, or a set of database files, to load before running tests. The path can be
+ relative to the project root directory, e.g. tests/_data/dump.sql, or absolute.
+
populate - a boolean value to indicate if the database should be populated importing the dump file(s) at the start
+ of the suite.
+
cleanup - a boolean value to indicate if the database should be populated importing the dump file(s) before each
+ test.
+
reconnect - a boolean value to indicate if the database connection should be re-established before each test.
urlReplacement - a boolean value to indicate if the database dump file(s) should be searched for the siteurl
+ and home options and replaced with the url parameter value. This is required since WordPress hard-codes URLs in
+ the database, the original URL is inferred, if the originalUrl parameter is not provided.
+
originalUrl - if provided together with the urlReplacement parameter, the module will not try to infer the
+ original URL from the database dump file(s) but use the provided value instead.
+
waitlock - the number of seconds to wait for a database lock to be released before failing the test. Defaults to
+ 10 meaning that the test will fail if the database lock is not released after 10 seconds.
+
createIfNotExists - a boolean value to indicate if the database should be created if it does not exist. Defaults to
+ false.
+
+
The following is an example of the module configuration to run tests on thehttp://localhost:8080 site:
Interact and make assertions on the WordPress file structure.
+
This module is used together with the WPDb module to manage the state of the WordPress installation in the
+context of end-to-end tests.
+
This module extends the Filesystem module from Codeception, you can reference to the Codeception documentation to
+find out more about the module configuration and usage.
+
This module should be with Cest and Cept test cases.
+
Configuration
+
wpRootFolder - required; the path to the WordPress installation root folder. This can be a relative path to the
+codeception root directory, or an absolute path to the WordPress installation directory. The WordPress installation
+directory is the directory that contains the wp-load.php file.
+themes - the path, relative to the path specified in the wpRootFolder parameter, to the themes directory. By
+default,
+it's /wp-content/themes.
+plugins - the path, relative to the path specified in the wpRootFolder parameter, to the plugins directory. By
+default, it's /wp-content/plugins.
+mu-plugins - the path, relative to the path specified in the wpRootFolder parameter, to the must-use plugins. By
+default, it's /wp-content/mu-plugins. directory.
+uploads - the path, relative to the path specified in the wpRootFolder parameter, to the uploads directory. By
+default, it's /wp-content/uploads.
+
The following is an example of the module configuration to run tests on the /var/wordpress site:
A module to load WordPress and make its code available in tests.
+
Depending on the value of the loadOnly configuration parameter, the module will behave differently:
+
+
loadOnly: false - The module will load WordPress like the Core PHPUnit suite does to run integration tests in a
+ controlled environment. Use the module in this mode with test cases generated
+ using the generate:wpunit command.
+
loadOnly: true - The module will load WordPress to make it available in the context of tests. Use the module in this
+ mode in Cest, Cept and Codeception unit test cases.
+
+
Configuration with loadOnly: false
+
The module will load WordPress like the Core PHPUnit suite does to run integration tests in a controlled
+environment.
+Together with the test case generated by the generate:wpunit command the module
+will:
+
+
take care of running any test method in a database transaction rolled back after each test
+
manage and clean up the global environment and context between tests
+
+
When used in this mode, the module supports the following configuration parameters:
+
+
loadOnly - false to load WordPress and run tests in a controlled environment.
+
wpRootFolder - required; the path to the WordPress installation root folder. This can be a relative path to the
+ codeception root directory, or an absolute path to the WordPress installation directory. The WordPress installation
+ directory is the directory that contains the wp-load.php file.
+
dbUrl - required; the URL to the database to use to run tests. The URL must be in the form
+ mysql://username:password@host:port/database to use a MySQL database, or in the form sqlite://path/to/database to
+ use a SQLite database. Alternatively, you can use the dbName, dbUser, dbPassword, dbHost configuration
+ parameters to specify the database connection details.
+
dump - the path to a database dump, or a set of database dumps, to load before running tests. The dump will be
+ loaded only once, after the tests run.
+
tablePrefix - the database table prefix to use when loading WordPress, defaults to wp_.
+
multisite - a boolean value to indicate if WordPress should be loaded and initialized in multisite mode.
+
dbCharset - the database charset to use when loading WordPress.
+
dbCollate - the database collate to use when loading WordPress.
+
domain - the domain to use when loading WordPress. Equivalent to defining the WP_TESTS_DOMAIN constant.
+
adminEmail - the administrator email to use when loading WordPress. Equivalent to defining the WP_TESTS_EMAIL
+ constant.
+
title - the site title to use when loading WordPress. Equivalent to defining the WP_TESTS_TITLE constant.
+
phpBinary - the path to the PHP binary to use to run tests. Defaults to the WP_PHP_BINARY constant.
+
language - the language to use when loading WordPress. Equivalent to defining the WPLANG constant.
+
configFile - a configuration file, or a set of configuration files, to load before the tests to further customize
+ and control the WordPress testing environment.
+
pluginsFolder - the path to the plugins folder to use when loading WordPress. Equivalent to defining the
+ WP_PLUGIN_DIR constant.
+
plugins - a list of plugins to activate and load in the WordPress installation. Each plugin must be specified in a
+ format like hello.php or my-plugin/my-plugin.php format.
+
bootstrapActions - a list of actions or callbacks to call after WordPress is loaded and before the tests run.
+
theme - the theme to activate and load in the WordPress installation. The theme must be specified in slug format
+ like
+ twentytwentythree.
+
AUTH_KEY - the AUTH_KEY constant value to use when loading WordPress. If the wpRootFolder path points at a
+ configured installation, containing the wp-config.php file, then the value of the constant in the configuration file
+ will be used, else it will be randomly generated.
+
SECURE_AUTH_KEY - the SECURE_AUTH_KEY constant value to use when loading WordPress. If the wpRootFolder path
+ points at a configured installation, containing the wp-config.php file, then the value of the constant in the
+ configuration file will be used, else it will be randomly generated.
+
LOGGED_IN_KEY - the LOGGED_IN_KEY constant value to use when loading WordPress. If the wpRootFolder path points
+ at a configured installation, containing the wp-config.php file, then the value of the constant in the configuration
+ file will be used, else it will be randomly generated.
+
NONCE_KEY - the NONCE_KEY constant value to use when loading WordPress. If the wpRootFolder path points at a
+ configured installation, containing the wp-config.php file, then the value of the constant in the configuration file
+ will be used, else it will be randomly generated.
+
AUTH_SALT - the AUTH_SALT constant value to use when loading WordPress. If the wpRootFolder path points at a
+ configured installation, containing the wp-config.php file, then the value of the constant in the configuration file
+ will be used, else it will be randomly generated.
+
SECURE_AUTH_SALT - the SECURE_AUTH_SALT constant value to use when loading WordPress. If the wpRootFolder path
+ points at a configured installation, containing the wp-config.php file, then the value of the constant in the
+ configuration file will be used, else it will be randomly generated.
+
LOGGED_IN_SALT - the LOGGED_IN_SALT constant value to use when loading WordPress. If the wpRootFolder path
+ points at a configured installation, containing the wp-config.php file, then the value of the constant in the
+ configuration file will be used, else it will be randomly generated.
+
NONCE_SALT - the NONCE_SALT constant value to use when loading WordPress. If the wpRootFolder path points at a
+ configured installation, containing the wp-config.php file, then the value of the constant in the configuration file
+ will be used, else it will be randomly generated.
+
AUTOMATIC_UPDATER_DISABLED - the AUTOMATIC_UPDATER_DISABLED constant value to use when loading WordPress. If
+ the wpRootFolder path points at a configured installation, containing the wp-config.php file, then the value of
+ the constant in the configuration file will be used, else it will be randomly generated.
+
WP_HTTP_BLOCK_EXTERNAL - the WP_HTTP_BLOCK_EXTERNAL constant value to use when loading WordPress. If
+ the wpRootFolder path points at a configured installation, containing the wp-config.php file, then the value of
+ the constant in the configuration file will be used, else it will be randomly generated.
+
+
This is an example of an integration suite configured to use the module:
If you're working on a site project using a custom file structure, e.g. [Bedrock][4], you should
+use a custom configuration and, together with that, configure the WPLoader module to
+load WordPress, plugins and themes code from the correct locations.
+Take care to point the wpRootFolder parameter to the directory containing the wp-load.php file,
+the /var/my-site/web/wp one in the following example, and the module will read the project configuration file to load
+the WordPress code from the correct location.
+
Here's an example of how the module should be configured to run integration tests on a Bedrock installation:
In general, pointing the wpRootFolder parameter to the directory containing the wp-load.php file should take care of
+loading WordPress code from the correct location.
+Should that not be the case, use the configFile parameter to point the module to the project test configuration file:
+a PHP file defining the constants and environment variables to use to load WordPress, plugins and themes correctly.
+
Configuration with loadOnly: true
+
The module will load WordPress from the location specified by the wpRootFodler parameter, relying
+on the WPDb module to manage the database state.
+
When used in this mode, the module supports the following configuration parameters:
+
+
loadOnly - true to load WordPress and make it available in the context of tests.
+
wpRootFolder - required; the path to the WordPress installation root folder. This can be a relative path to the
+ codeception root directory, or an absolute path to the WordPress installation directory. The WordPress installation
+ directory is the directory that contains the wp-load.php file.
+
dbUrl - required; the URL to the database to use to run tests. The URL must be in the form
+ mysql://username:password@host:port/database to use a MySQL database, or in the form sqlite://path/to/database to
+ use a SQLite database. Alternatively, you can use the dbName, dbUser, dbPassword, dbHost configuration
+ parameters to specify the database connection details.
+
domain - the domain to use when loading WordPress. Equivalent to defining the WP_TESTS_DOMAIN constant.
+
+
The following is an example of the module configuration to run end-to-end tests on the site served
+at http://localhost:8080 URL and served from the /var/wordpress directory:
This module provides assertions for WordPress queries.
+
This module can be used in any test context where the global $wpdb variable is defined, this usually means in any
+suite where the WPLoader module is used.
This module drives a browser using a solution like Selenium or Chromedriver to simulate user interactions with
+the WordPress project.
+
The module has full Javascript support, differently from the WPBrowser module, and can be used to test
+sites that use Javascript to render the page or to make assertions that require Javascript support.
The library provides some custom commands that can be added to the project Codeception configuration file (
-either codeception.yml or codeception.dist.yml).
-
run and codeception:run
-
WordPress extensive use of global variables, constants and side effectes makes it difficult to run multiple test suites
-in the same process without running into conflicts due to leaking state and side effects.
-For this reason the project replaces Codeception run command with one that will run each suite in a separate process.
-You can invoke the original Codeception command using the codeception:run command.
-Just like the original, the run command accepts all the arguments and options of the original Codeception
-command.
-
Run all the suites, each one in a separate process:
-
vendor/bin/codecept run
-
-
Run only the Integration suite:
-
vendor/bin/codecept run Integration
-
-
Run a specific test file:
-
vendor/bin/codecept run Integration tests/Integration/MyTest.php
-
-
Run a specific test method:
-
vendor/bin/codecept run Integration tests/Integration/MyTest.php:testMyMethod
-
If not already running, start the services required to run the tests.
-The started services are read from the Codeception configuration file (either codeception.yml
-or codeception.dist.yml), from the extensions section, under the config key.
Running the command will start ChromeDriver, the built-in PHP server and Docker Compose.
-
dev:stop
-
If running, stop the services required to run the tests.
-The stopped services are read from the Codeception configuration file (either codeception.yml
-or codeception.dist.yml), from the extensions section, under the config key.
You can use WP CLI to interact with your WordPress installation, but WP CLI does not support SQLite databases in
-the context of the wp db import command.
-This command fills that gap by providing a database dump file import command that will support MySQL and SQLite
-databases.
-
wp:db:export
-
You can use WP CLI to interact with your WordPress installation, but WP CLI does not support SQLite databases in
-the context of the wp db export command.
-This command fills that gap by providing a database dump file export command that will support MySQL and SQLite
-databases.
-
chromedriver:update
-
If you're using Chromedriver as a binary installed in the Composer vendor directory (vendor/bin by default), you can
-use this command to update it.
-This command will download the latest version of Chromedriver compatible with the Chrome version installed on your
-machine in the Composer vendor directory.
-
generate:wpunit
-
Generate a test case extending the lucatume\WPBrowser\TestCase\WPTestCase class.
-The class incorporates the WordPress test case from the wordpress-develop repository and adds some utility
-methods to make testing easier in the context of Codeception.
-
The lucatume\WPBrowser\TestCase\WPTestCase class is the one that should be used when writing tests for WordPress
-code when using the WPLoader module.
-
Together with the WPLoader module, the WPTestCase class provides a number of functionalities to clean up the
-database
-after each test method and to reset the global state of WordPress.
-
Every test method runs in a transaction
-
Database queries running in the context of test methods of a test case extending the WPTestCase class will run in a
-transaction that is rolled back after the test method is run. This means that any database change happening in the
-context of a test method will not appear in the database while the test is running and after the test is run.
Any non default configuration is considered a custom configuration.
-If your project requires a tailored set up, this is the configuration for you.
-
Using a custom configuration to run tests
-
If you decide to skip the default configuration, or are working
-on a project that cannot use the default configuration
-you will be able to set up wp-browser to suit your needs using a custom configuration.
-
Choose "no", to not use the default configuration, when running the vendor/bin/codecept init wpbrowser command.
-
The command will set up the file structure to be able to run integration and end-to-end tests and will
-leverage Codeception dynamic configuration using parameters to control the testing stack using the tests/.env
-file.
-
Walkthrough of the tests/.env file
-
-
WORDPRESS_ROOT_DIR - the path to the root WordPress installation directory. This is the directory that contains
- WordPress files, like wp-load.php. This path can be absolute or relative to the root project directory;
- e.g. vendor/wordpress (relative) or /var/www/wordpress (absolute) will work.
-
WORDPRESS_URL - the URL of the WordPress installation. This is the URL that will be used by the browser to access
- the WordPress
- installation in the context of end-to-end tests; e.g. http://localhost:8080 or https://wordpress.local.
-
WORDPRESS_DOMAIN - the domain of the WordPress installation; this value should follow the WORDPRESS_URL value.
- E.g. if WORDPRESS_URL is http://localhost:8080 the WORDPRESS_DOMAIN value should be localhost:8080;
- if WORDPRESS_URL is https://wordpress.local the WORDPRESS_DOMAIN value should be wordpress.local.
-
WORDPRESS_DB_URL - the user, password, host, and name of the database used by the tests. If the database is a MySQL
- database, the value should be in the form mysql://user:password@host:port/database_name.
- If the database is a SQLite database, the value should be in the form sqlite://path/to/database/file.
-
WORDPRESS_TABLE_PREFIX - the database table prefix used by the WordPress installation, the one served
- at WORDPRESS_URL.
- This value is usually wp_ but can be different if the WordPress installation has been configured to use a different
- prefix.
-
TEST_TABLE_PREFIX - the database table prefix used by the WPLoader module to
- install WordPress and run the tests. This value is usually test_ and should be different from
- the WORDPRESS_TABLE_PREFIX value.
-
WORDPRESS_ADMIN_USER - the username of the WordPress administrator user. E.g. admin.
-
WORDPRESS_ADMIN_PASSWORD - the password of the WordPress administrator user. E.g. secret!password.
-
CHROMEDRIVER_HOST - the host of the Chromedriver server. This value is usually localhost if you're running
- Chromedriver on the same machine as the tests. If you're running your tests using a container stack, it will be the
- name of the container running Chromedriver, e.g. chromedriver.
-
CHROMEDRIVER_PORT - the port of the Chromedriver server. This value is usually 9515 if you're running Chromedriver
- on the same machine as the tests. If you're running your tests using a container stack, it will be the port exposed by
- the container running Chromedriver, e.g. 4444. Note the default configuration will set
- this value to a random port during set up to avoid conflicts with other services running on the same machine.
The recommended configuration for most projects.
-It allows you to get into WordPress integration and end-to-end testing quickly and easily.
-
Requirements
-
The default configuration will set up Codeception and wp-browser to use SQLite as the database engine, PHP built-in
-server to serve the test site on localhost and your local version of Chrome, driven by Chromedriver, to run end-to-end
-tests.
-
As such, the default configuration has the following requirements:
-
-
the sqlite3 PHP extension; you can check if if's installed by running php -m | grep sqlite3 in your terminal
-
the pdo_sqlite PHP extension; you can check if if's installed by running php -m | grep pdo_sqlite in your terminal
-
PHP built-in server can work with only one thread, but it will be faster using multiple threads; multiple threads are
- not supported on Windows, but they are supported on WSL.
-
the Chrome browser installed on your machine
-
-
Overview - plugin and theme project
-
If you're configuring wp-browser for a plugin or theme project, the default configuration will install WordPress in
-the tests/_wordpress directory and configure the installation to run using SQLite as a database engine.
-The SQLite Database Integration plugin) will be placed in the installation must-use plugins directory.
-
If your plugin or theme project requires additional plugins or theme to work, you can place them in
-the tests/_worpdress/wp-content/plugins and tests/_wordpress/wp-content/themes directories respectively.
-
When adding, or removing, plugin and themes, remember to
-update the WPLoader module configuration to load the correct plugins and themes in
-your integration tests.
-
On the same note, update the database dump used by the WPDb module to reflect the
-changes in the dump loaded in the end-to-end tests.
-The easiest way to update the database fixture is to load the current database dump
-using the wp:db:import command, manually setting up the site interacting with it and then
-exporting the database dump using the wp:db:export command.
-
You can find out about the URL of the site served by the PHP built-in web server by
-running the dev:info command.
-
Overview - site project
-
If you're configuring wp-browser for a site project, the default configuration will use a combination of PHP built-in
-web server and the SQLite Database Integration plugin to run the tests and serve your site.
-
The router file used by the PHP built-in web server will force the site, when served on localhost, to use SQLite as
-database engine leaving your existing local MySQL database untouched.
-
Your existing WordPress installation will be picked up as it is, with all the plugins and themes found in the contents
-directory.
-
Existing plugins and themes are not added to WPLoader module configuration by
-wp-browser, you have to do that manually.
-
Similarly, the database dump used by the WPDb module is, by default, an empty WordPress
-installation where no plugins and themes are active.
-You have to update the database dump used by the module to reflect the state of your site.
-You can do that by loading the current database dump using the wp:db:import command,
-manually setting up the site interacting with it and then
-exporting the database dump using the wp:db:export command.
-
You can find out about the URL of the site served by the PHP built-in web server by
-running the dev:info command.
-
When not to use the default configuration
-
The default configuration is the recommended one for most projects, but some projects might require you to use a custom
-configuration to make the most out of wp-browser.
-
Database drop-in
-
The default configuration will use the SQLite Database Integration plugin to use SQLite as the database engine.
-This requires placing a db.php drop-in file in the WordPress content directory.
-
If your project already requires a db.php drop-in file, you will have to use a custom configuration.
-
Multisite with sub-domains
-
While Chrome will handle sub-domains correctly, even on localhost, WordPress will not.
-If you're testing a multisite installation with sub-domains, you will have to use a custom configuration.
-
Custom site structure
-
If your site uses a customized file structure to manage WordPress, you will need to configure wp-browser using a custom
-configuration.
-This is usually true for some site projects, and will most likely not be an issue for plugin and theme projects.
The library provides some custom Codeception extensions that can be added to the project Codeception configuration file,
-in the extensions section.
-
BuiltInServerController
-
This extension will start and stop the PHP built-in web server before and after the tests run.
-
The extension can be configured with the following parameters:
-
-
required
-
docRoot - the document root to use for the PHP Built-in server; it can be either an absolute path or a path
- relative to the Codeception root directory.
-
-
-
optional
-
suites - an array of Codeception suites to run the server for; if not set the server will be started for all the
- suites.
-
port - the port to use for the PHP Built-in server, if not set the server will use port 2389.
-
workers - the number of workers to use for the PHP Built-in server, if not set the server will use 5 workers.
- This is the equivalent of the PHP_CLI_SERVER_WORKERS environment variable.
-
-
-
-
-
Note: if you run PHP built-in server on Windows, the workers parameter will be ignored and the server will always
-run with a single worker. This limit is not present in WSL.
-
-
Example configuration starting the server for all suites:
You can use the chromedriver:update command to download the latest version of
-ChromeDriver
-compatible with your Chrome browser version and place it in the Composer bin directory.
-
This is a service extension that will be started and stopped by the dev:start
-and dev:stop commands.
-
DockerComposeController
-
This extension will start and stop a docker compose stack before and after the tests are run.
-
The extension can be configured with the following parameters:
-
-
required
-
compose-file - the path to the docker compose file to use; it can be either an absolute path or a path
- relative to the Codeception root directory.
-
-
-
optional
-
env-file- the path to the environment file to use; it can be either an absolute path or a path.
-
-
-
-
Example configuration starting the server for all suites:
The wp-browser library provides a set of Codeception modules and middleware to enable the testing of WordPress sites, plugins and themes.
-
-
This is the documentation for version 4 of the project, the current version.
-Documentation for the previous version of the project, version 3, can be found here.
-
-
Installation
-
Add wp-browser to your project as a development dependency using Composer
-
cd my-wordrpess-project
-composer require --dev lucatume/wp-browser
-
-
Initialize wp-browser to quickly configured to suite your project and setup:
-
vendor/bin/codecept init wpbrowser
-
-
The command will set up your project to run integration and end-to-end tests using:
PHP built-in web server to serve the WordPress site on localhost (e.g. http://localhost:8080)
-
Chromedriver to drive the local version of Chrome installed on your machine
-
-
If you're working on a plugin or theme project, the default configuration will add some extra steps:
-
-
install the latest version of WordPress in the tests/_wordpress directory
-
create a tests/_plugins directory: any file or directory in this directory will be symlinked into the WordPress
- installation in tests/_wordpress/wp-content/plugins
-
create a tests/_themes directory: any file or directory in this directory will be symlinked into the WordPress
- installation in tests/_wordpress/wp-content/themes
-
-
For most projects this configuration will be enough to get started with testing.
-
You can run your tests immediately using the vendor/bin/codecept run command.
If you decide to skip the default configuration, you will be able to set up wp-browser to suit your needs and local
-setup by editing the tests/.env file.
-The inline documentation in the file will guide you through the configuration process.
Getting support for wp-browser configuration and usage
-
The best place to get support for wp-browser is this documentation.
-Since this project builds on top of PHPUnit and Codeception, you can also refer to their documentation.
Browse and test the site HTML with a fast browser without Javascript support.
-
This module trades the WPWebDriver module Javascript support for speed and stability. It is a good
-choice for testing sites that don't use Javascript or to make assertions that do not require Javascript support like:
This module is an extension of the Codeception PHPBrowser module, you can reference to the Codeception module
-documentation for more information on the module configuration and usage.
-
This module should be with Cest and Cept test cases.
-
Configuration
-
-
url - required; the start URL of your WordPress project.
-
adminUsername - required; the site administrator username to use in actions like loginAsAdmin.
-
adminPassword - required; the site administrator password to use in actions like loginAsAdmin.
-
adminPath - the path to the WordPress admin directory; defaults to /wp-admin.
headers - default headers are set before each test.
-cookies - default cookies are set before each test.
-auth - default authentication to be set before each test.
Use WP-CLI to interact with the WordPress installation under test and issue commands.
-
This module is used in the context of end-to-end testing, together with, or as a replacement for
-the WPDb module to manipulate the database and the WPFilesystem module to manipulate the
-site file structure.
-
This module should be with Cest and Cept test cases.
-
Configuration
-
-
path - required; the path to the WordPress installation under test. This can be a relative path to the
- codeception root directory, or an absolute path to the WordPress installation directory. The WordPress installation
- directory is the directory that contains the wp-load.php file.
-
url - the URL of the WordPress installation under test. Equivalent to the --url option of the wp command.
-
user - the user to use to run the wp command. Equivalent to the --user option of the wp command.
-
skip-plugins - a boolean value to indicate if the wp command should skip loading plugins. Equivalent to the
- --skip-plugins option of the wp command.
-
skip-themes - a boolean value to indicate if the wp command should skip loading themes. Equivalent to the
- --skip-themes option of the wp command.
-
skip-packages - a boolean value to indicate if the wp command should skip loading packages. Equivalent to the
- --skip-packages option of the wp command.
-
require - a list of PHP files to require before running the wp command. Equivalent to the --require option of
- the wp command.
-
exec - PHP code to execute before running the wp command. Equivalent to the --exec option of the wp command.
-
context - the context to use when running the wp command. Equivalent to the --context option of the wp
- command.
-
color - a boolean value to indicate if the wp command should output in color. Equivalent to the --color option
- of the wp command.
-
no-color - a boolean value to indicate if the wp command should not output in color. Equivalent to the
- --no-color option of the wp command.
-
debug - a boolean value to indicate if the wp command should output debug information. Equivalent to the
- --debug option of the wp command.
-
quiet - a boolean value to indicate if the wp command should suppress informational messages. Equivalent to the
- --quiet option of the wp command.
-
throw - a boolean value to indicate if the wp command should throw an exception if the command fails.
-
timeout - the timeout to use when running the wp command. When the timeout is reached the command will be
- terminated as a failure.
-
cache-dir - the directory to use to cache the files WPCLI might downloads. Equivalent to setting
- the WP_CLI_CACHE_DIR
- environment variable.
-
config-path - the path to the wp-cli.yml file to use. Equivalent to setting the WP_CLI_CONFIG_PATH
- environment variable.
-
custom-shell - the shell to use to run the wp command. Equivalent to setting the WP_CLI_SHELL environment
- variable.
-
packages-dir - the directory to use to store the packages downloaded by the wp package command. Equivalent to
- setting the WP_CLI_PACKAGES_DIR environment variable.
-
-
The following is an example of the module configuration to run WPCLI commands on the /var/wordpress directory:
This module allows to manipulate the database of the WordPress installation under test directly, without using the
-WordPress API.
-
The module is used together with the WPBrowser module, WPWebDriver
-and WPFilesystem modules to control the site state, the database, and the site file structure.
-
Note about interaction with the WPLoader module: both this module and the WPLoader one can be used to
-control the state of the database before tests and set up fixtures: use either this or WPLoader, do not use both.
-This module should be used in end-to-end testing, the WPLoader module should be used in integration
-testing.
-If you're using this module to load a database dump before integration tests,
-use the WPLoader moduledump configuration parameter instead.
-
This module should be with Cest and Cept test cases.
-
Configuration
-
This module extends the Codeception Db module adding some configuration options and functions that are specific to
-WordPress.
-
-
dbUrl - required; the URL to use to connect to the database. The URL must be in the form
- mysql://user:password@host:port/database if you're using a MySQL database for your tests, or in the form
- sqlite://path/to/database/file if you're using a SQLite database for your tests (
- like the default configuration does)
-
dsn - required; the DSN to use to connect to the database; required if not using the dbUrl parameter.
-
user - required; the user to use to connect to the database; required if not using the dbUrl parameter.
-
password - required; the password to use to connect to the database; required if not using the dbUrl
- parameter.
-
url - required;the URL of the WordPress installation under test. E.g. http://localhost:8080
- or https://wordpress.test.
-
tablePrefix - the table prefix to use when interacting with the database; defaults to wp_.
-
dump - the path to a database dump file, or a set of database files, to load before running tests. The path can be
- relative to the project root directory, e.g. tests/_data/dump.sql, or absolute.
-
populate - a boolean value to indicate if the database should be populated importing the dump file(s) at the start
- of the suite.
-
cleanup - a boolean value to indicate if the database should be populated importing the dump file(s) before each
- test.
-
reconnect - a boolean value to indicate if the database connection should be re-established before each test.
urlReplacement - a boolean value to indicate if the database dump file(s) should be searched for the siteurl
- and home options and replaced with the url parameter value. This is required since WordPress hard-codes URLs in
- the database, the original URL is inferred, if the originalUrl parameter is not provided.
-
originalUrl - if provided together with the urlReplacement parameter, the module will not try to infer the
- original URL from the database dump file(s) but use the provided value instead.
-
waitlock - the number of seconds to wait for a database lock to be released before failing the test. Defaults to
- 10 meaning that the test will fail if the database lock is not released after 10 seconds.
-
createIfNotExists - a boolean value to indicate if the database should be created if it does not exist. Defaults to
- false.
-
-
The following is an example of the module configuration to run tests on thehttp://localhost:8080 site:
Interact and make assertions on the WordPress file structure.
-
This module is used together with the WPDb module to manage the state of the WordPress installation in the
-context of end-to-end tests.
-
This module extends the Filesystem module from Codeception, you can reference to the Codeception documentation to
-find out more about the module configuration and usage.
-
This module should be with Cest and Cept test cases.
-
Configuration
-
wpRootFolder - required; the path to the WordPress installation root folder. This can be a relative path to the
-codeception root directory, or an absolute path to the WordPress installation directory. The WordPress installation
-directory is the directory that contains the wp-load.php file.
-themes - the path, relative to the path specified in the wpRootFolder parameter, to the themes directory. By
-default,
-it's /wp-content/themes.
-plugins - the path, relative to the path specified in the wpRootFolder parameter, to the plugins directory. By
-default, it's /wp-content/plugins.
-mu-plugins - the path, relative to the path specified in the wpRootFolder parameter, to the must-use plugins. By
-default, it's /wp-content/mu-plugins. directory.
-uploads - the path, relative to the path specified in the wpRootFolder parameter, to the uploads directory. By
-default, it's /wp-content/uploads.
-
The following is an example of the module configuration to run tests on the /var/wordpress site:
A module to load WordPress and make its code available in tests.
-
Depending on the value of the loadOnly configuration parameter, the module will behave differently:
-
-
loadOnly: false - The module will load WordPress like the Core PHPUnit suite does to run integration tests in a
- controlled environment. Use the module in this mode with test cases generated
- using the generate:wpunit command.
-
loadOnly: true - The module will load WordPress to make it available in the context of tests. Use the module in this
- mode in Cest, Cept and Codeception unit test cases.
-
-
Configuration with loadOnly: false
-
The module will load WordPress like the Core PHPUnit suite does to run integration tests in a controlled
-environment.
-Together with the test case generated by the generate:wpunit command the module
-will:
-
-
take care of running any test method in a database transaction rolled back after each test
-
manage and clean up the global environment and context between tests
-
-
When used in this mode, the module supports the following configuration parameters:
-
-
loadOnly - false to load WordPress and run tests in a controlled environment.
-
wpRootFolder - required; the path to the WordPress installation root folder. This can be a relative path to the
- codeception root directory, or an absolute path to the WordPress installation directory. The WordPress installation
- directory is the directory that contains the wp-load.php file.
-
dbUrl - required; the URL to the database to use to run tests. The URL must be in the form
- mysql://username:password@host:port/database to use a MySQL database, or in the form sqlite://path/to/database to
- use a SQLite database. Alternatively, you can use the dbName, dbUser, dbPassword, dbHost configuration
- parameters to specify the database connection details.
-
dump - the path to a database dump, or a set of database dumps, to load before running tests. The dump will be
- loaded only once, after the tests run.
-
tablePrefix - the database table prefix to use when loading WordPress, defaults to wp_.
-
multisite - a boolean value to indicate if WordPress should be loaded and initialized in multisite mode.
-
dbCharset - the database charset to use when loading WordPress.
-
dbCollate - the database collate to use when loading WordPress.
-
domain - the domain to use when loading WordPress. Equivalent to defining the WP_TESTS_DOMAIN constant.
-
adminEmail - the administrator email to use when loading WordPress. Equivalent to defining the WP_TESTS_EMAIL
- constant.
-
title - the site title to use when loading WordPress. Equivalent to defining the WP_TESTS_TITLE constant.
-
phpBinary - the path to the PHP binary to use to run tests. Defaults to the WP_PHP_BINARY constant.
-
language - the language to use when loading WordPress. Equivalent to defining the WPLANG constant.
-
configFile - a configuration file, or a set of configuration files, to load before the tests to further customize
- and control the WordPress testing environment.
-
pluginsFolder - the path to the plugins folder to use when loading WordPress. Equivalent to defining the
- WP_PLUGIN_DIR constant.
-
plugins - a list of plugins to activate and load in the WordPress installation. Each plugin must be specified in a
- format like hello.php or my-plugin/my-plugin.php format.
-
bootstrapActions - a list of actions or callbacks to call after WordPress is loaded and before the tests run.
-
theme - the theme to activate and load in the WordPress installation. The theme must be specified in slug format
- like
- twentytwentythree.
-
AUTH_KEY - the AUTH_KEY constant value to use when loading WordPress. If the wpRootFolder path points at a
- configured installation, containing the wp-config.php file, then the value of the constant in the configuration file
- will be used, else it will be randomly generated.
-
SECURE_AUTH_KEY - the SECURE_AUTH_KEY constant value to use when loading WordPress. If the wpRootFolder path
- points at a configured installation, containing the wp-config.php file, then the value of the constant in the
- configuration file will be used, else it will be randomly generated.
-
LOGGED_IN_KEY - the LOGGED_IN_KEY constant value to use when loading WordPress. If the wpRootFolder path points
- at a configured installation, containing the wp-config.php file, then the value of the constant in the configuration
- file will be used, else it will be randomly generated.
-
NONCE_KEY - the NONCE_KEY constant value to use when loading WordPress. If the wpRootFolder path points at a
- configured installation, containing the wp-config.php file, then the value of the constant in the configuration file
- will be used, else it will be randomly generated.
-
AUTH_SALT - the AUTH_SALT constant value to use when loading WordPress. If the wpRootFolder path points at a
- configured installation, containing the wp-config.php file, then the value of the constant in the configuration file
- will be used, else it will be randomly generated.
-
SECURE_AUTH_SALT - the SECURE_AUTH_SALT constant value to use when loading WordPress. If the wpRootFolder path
- points at a configured installation, containing the wp-config.php file, then the value of the constant in the
- configuration file will be used, else it will be randomly generated.
-
LOGGED_IN_SALT - the LOGGED_IN_SALT constant value to use when loading WordPress. If the wpRootFolder path
- points at a configured installation, containing the wp-config.php file, then the value of the constant in the
- configuration file will be used, else it will be randomly generated.
-
NONCE_SALT - the NONCE_SALT constant value to use when loading WordPress. If the wpRootFolder path points at a
- configured installation, containing the wp-config.php file, then the value of the constant in the configuration file
- will be used, else it will be randomly generated.
-
AUTOMATIC_UPDATER_DISABLED - the AUTOMATIC_UPDATER_DISABLED constant value to use when loading WordPress. If
- the wpRootFolder path points at a configured installation, containing the wp-config.php file, then the value of
- the constant in the configuration file will be used, else it will be randomly generated.
-
WP_HTTP_BLOCK_EXTERNAL - the WP_HTTP_BLOCK_EXTERNAL constant value to use when loading WordPress. If
- the wpRootFolder path points at a configured installation, containing the wp-config.php file, then the value of
- the constant in the configuration file will be used, else it will be randomly generated.
-
-
This is an example of an integration suite configured to use the module:
If you're working on a site project using a custom file structure, e.g. [Bedrock][4], you should
-use a custom configuration and, together with that, configure the WPLoader module to
-load WordPress, plugins and themes code from the correct locations.
-Take care to point the wpRootFolder parameter to the directory containing the wp-load.php file,
-the /var/my-site/web/wp one in the following example, and the module will read the project configuration file to load
-the WordPress code from the correct location.
-
Here's an example of how the module should be configured to run integration tests on a Bedrock installation:
In general, pointing the wpRootFolder parameter to the directory containing the wp-load.php file should take care of
-loading WordPress code from the correct location.
-Should that not be the case, use the configFile parameter to point the module to the project test configuration file:
-a PHP file defining the constants and environment variables to use to load WordPress, plugins and themes correctly.
-
Configuration with loadOnly: true
-
The module will load WordPress from the location specified by the wpRootFodler parameter, relying
-on the WPDb module to manage the database state.
-
When used in this mode, the module supports the following configuration parameters:
-
-
loadOnly - true to load WordPress and make it available in the context of tests.
-
wpRootFolder - required; the path to the WordPress installation root folder. This can be a relative path to the
- codeception root directory, or an absolute path to the WordPress installation directory. The WordPress installation
- directory is the directory that contains the wp-load.php file.
-
dbUrl - required; the URL to the database to use to run tests. The URL must be in the form
- mysql://username:password@host:port/database to use a MySQL database, or in the form sqlite://path/to/database to
- use a SQLite database. Alternatively, you can use the dbName, dbUser, dbPassword, dbHost configuration
- parameters to specify the database connection details.
-
domain - the domain to use when loading WordPress. Equivalent to defining the WP_TESTS_DOMAIN constant.
-
-
The following is an example of the module configuration to run end-to-end tests on the site served
-at http://localhost:8080 URL and served from the /var/wordpress directory:
This module provides assertions for WordPress queries.
-
This module can be used in any test context where the global $wpdb variable is defined, this usually means in any
-suite where [the WPLoader module] is used.
This module drives a browser using a solution like Selenium or Chromedriver to simulate user interactions with
-the WordPress project.
-
The module has full Javascript support, differently from the WPBrowser module, and can be used to test
-sites that use Javascript to render the page or to make assertions that require Javascript support.
-
-
-
-
-
-
-
-
-
\ No newline at end of file
diff --git a/docs/public/search/search_index.json b/docs/public/search/search_index.json
deleted file mode 100644
index 6f0684aa1..000000000
--- a/docs/public/search/search_index.json
+++ /dev/null
@@ -1 +0,0 @@
-{"config":{"lang":["en"],"separator":"[\\s\\-]+","pipeline":["stopWordFilter"]},"docs":[{"location":"","title":"Start here","text":"
The wp-browser library provides a set of Codeception modules and middleware to enable the testing of WordPress sites, plugins and themes.
This is the documentation for version 4 of the project, the current version. Documentation for the previous version of the project, version 3, can be found here.
Add wp-browser to your project as a development dependency using Composer
cd my-wordrpess-project\ncomposer require --dev lucatume/wp-browser\n
Initialize wp-browser to quickly configured to suite your project and setup:
vendor/bin/codecept init wpbrowser\n
The command will set up your project to run integration and end-to-end tests using:
SQLite as the database engine, leveraging the SQLite Database Integration plugin
PHP built-in web server to serve the WordPress site on localhost (e.g. http://localhost:8080)
Chromedriver to drive the local version of Chrome installed on your machine
If you're working on a plugin or theme project, the default configuration will add some extra steps:
install the latest version of WordPress in the tests/_wordpress directory
create a tests/_plugins directory: any file or directory in this directory will be symlinked into the WordPress installation in tests/_wordpress/wp-content/plugins
create a tests/_themes directory: any file or directory in this directory will be symlinked into the WordPress installation in tests/_wordpress/wp-content/themes
For most projects this configuration will be enough to get started with testing.
You can run your tests immediately using the vendor/bin/codecept run command.
Read more about the commands provided by the library here.
"},{"location":"#using-a-custom-configuration","title":"Using a custom configuration","text":"
If you decide to skip the default configuration, you will be able to set up wp-browser to suit your needs and local setup by editing the tests/.env file. The inline documentation in the file will guide you through the configuration process.
Read more about using a custom configuration here.
"},{"location":"#getting-support-for-wp-browser-configuration-and-usage","title":"Getting support for wp-browser configuration and usage","text":"
The best place to get support for wp-browser is this documentation. Since this project builds on top of PHPUnit and Codeception, you can also refer to their documentation.
If you can't find the answer to your question here you can ask on the \"Issues\" section of the wp-browser repository taking care to provide as much information as possible.
Finally, you can contact me directly to set up a call to discuss your project needs and how wp-browser can help you.
Table of contents:
The default configuration
Using a custom configuration
Modules
WPBrowser
WPCLI
WPDb
WPFilesystem
WPLoader
WPQueries
WPWebDriver
Extensions
BuiltInServerController
ChromeDriverController
DockerComposeController
Commands
run and codeception:run
dev:start
dev:stop
dev:restart
wp:db:import
wp:db:export
chromedriver:update
generate:wpunit
"},{"location":"commands/","title":"Commands","text":""},{"location":"commands/#codeception-commands-provided-by-the-library","title":"Codeception commands provided by the library","text":"
The library provides some custom commands that can be added to the project Codeception configuration file ( either codeception.yml or codeception.dist.yml).
"},{"location":"commands/#run-and-codeceptionrun","title":"run and codeception:run","text":"
WordPress extensive use of global variables, constants and side effectes makes it difficult to run multiple test suites in the same process without running into conflicts due to leaking state and side effects. For this reason the project replaces Codeception run command with one that will run each suite in a separate process. You can invoke the original Codeception command using the codeception:run command. Just like the original, the run command accepts all the arguments and options of the original Codeception command.
Run all the suites, each one in a separate process:
vendor/bin/codecept run\n
Run only the Integration suite:
vendor/bin/codecept run Integration\n
Run a specific test file:
vendor/bin/codecept run Integration tests/Integration/MyTest.php\n
Run a specific test method:
vendor/bin/codecept run Integration tests/Integration/MyTest.php:testMyMethod\n
Read the Codeception documentation for more information about the run command.
If not already running, start the services required to run the tests. The started services are read from the Codeception configuration file (either codeception.yml or codeception.dist.yml), from the extensions section, under the config key.
If running, stop the services required to run the tests. The stopped services are read from the Codeception configuration file (either codeception.yml or codeception.dist.yml), from the extensions section, under the config key.
Provides information about the local testing stack managed by the DockerComposeController, BuiltInServerController and ChromeDriverController extensions.
You can use WP CLI to interact with your WordPress installation, but WP CLI does not support SQLite databases in the context of the wp db import command. This command fills that gap by providing a database dump file import command that will support MySQL and SQLite databases.
You can use WP CLI to interact with your WordPress installation, but WP CLI does not support SQLite databases in the context of the wp db export command. This command fills that gap by providing a database dump file export command that will support MySQL and SQLite databases.
If you're using Chromedriver as a binary installed in the Composer vendor directory (vendor/bin by default), you can use this command to update it. This command will download the latest version of Chromedriver compatible with the Chrome version installed on your machine in the Composer vendor directory.
Generate a test case extending the lucatume\\WPBrowser\\TestCase\\WPTestCase class. The class incorporates the WordPress test case from the wordpress-develop repository and adds some utility methods to make testing easier in the context of Codeception.
The lucatume\\WPBrowser\\TestCase\\WPTestCase class is the one that should be used when writing tests for WordPress code when using the WPLoader module.
Together with the WPLoader module, the WPTestCase class provides a number of functionalities to clean up the database after each test method and to reset the global state of WordPress.
"},{"location":"commands/#every-test-method-runs-in-a-transaction","title":"Every test method runs in a transaction","text":"
Database queries running in the context of test methods of a test case extending the WPTestCase class will run in a transaction that is rolled back after the test method is run. This means that any database change happening in the context of a test method will not appear in the database while the test is running and after the test is run.
Any non default configuration is considered a custom configuration. If your project requires a tailored set up, this is the configuration for you.
"},{"location":"custom-configuration/#using-a-custom-configuration-to-run-tests","title":"Using a custom configuration to run tests","text":"
If you decide to skip the default configuration, or are working on a project that cannot use the default configuration you will be able to set up wp-browser to suit your needs using a custom configuration.
Choose \"no\", to not use the default configuration, when running the vendor/bin/codecept init wpbrowser command.
The command will set up the file structure to be able to run integration and end-to-end tests and will leverage Codeception dynamic configuration using parameters to control the testing stack using the tests/.env file.
"},{"location":"custom-configuration/#walkthrough-of-the-testsenv-file","title":"Walkthrough of the tests/.env file","text":"
WORDPRESS_ROOT_DIR - the path to the root WordPress installation directory. This is the directory that contains WordPress files, like wp-load.php. This path can be absolute or relative to the root project directory; e.g. vendor/wordpress (relative) or /var/www/wordpress (absolute) will work.
WORDPRESS_URL - the URL of the WordPress installation. This is the URL that will be used by the browser to access the WordPress installation in the context of end-to-end tests; e.g. http://localhost:8080 or https://wordpress.local.
WORDPRESS_DOMAIN - the domain of the WordPress installation; this value should follow the WORDPRESS_URL value. E.g. if WORDPRESS_URL is http://localhost:8080 the WORDPRESS_DOMAIN value should be localhost:8080; if WORDPRESS_URL is https://wordpress.local the WORDPRESS_DOMAIN value should be wordpress.local.
WORDPRESS_DB_URL - the user, password, host, and name of the database used by the tests. If the database is a MySQL database, the value should be in the form mysql://user:password@host:port/database_name. If the database is a SQLite database, the value should be in the form sqlite://path/to/database/file.
WORDPRESS_TABLE_PREFIX - the database table prefix used by the WordPress installation, the one served at WORDPRESS_URL. This value is usually wp_ but can be different if the WordPress installation has been configured to use a different prefix.
TEST_TABLE_PREFIX - the database table prefix used by the WPLoader module to install WordPress and run the tests. This value is usually test_ and should be different from the WORDPRESS_TABLE_PREFIX value.
WORDPRESS_ADMIN_USER - the username of the WordPress administrator user. E.g. admin.
WORDPRESS_ADMIN_PASSWORD - the password of the WordPress administrator user. E.g. secret!password.
CHROMEDRIVER_HOST - the host of the Chromedriver server. This value is usually localhost if you're running Chromedriver on the same machine as the tests. If you're running your tests using a container stack, it will be the name of the container running Chromedriver, e.g. chromedriver.
CHROMEDRIVER_PORT - the port of the Chromedriver server. This value is usually 9515 if you're running Chromedriver on the same machine as the tests. If you're running your tests using a container stack, it will be the port exposed by the container running Chromedriver, e.g. 4444. Note the default configuration will set this value to a random port during set up to avoid conflicts with other services running on the same machine.
If your site uses a customized file structure to manage WordPress, you will need to further configure the WPLoader module to correctly look for the site content. Read more about setting up WPLoader to correctly load plugins and themes from custom locations here.
The default configuration will set up Codeception and wp-browser to use SQLite as the database engine, PHP built-in server to serve the test site on localhost and your local version of Chrome, driven by Chromedriver, to run end-to-end tests.
As such, the default configuration has the following requirements:
the sqlite3 PHP extension; you can check if if's installed by running php -m | grep sqlite3 in your terminal
the pdo_sqlite PHP extension; you can check if if's installed by running php -m | grep pdo_sqlite in your terminal
PHP built-in server can work with only one thread, but it will be faster using multiple threads; multiple threads are not supported on Windows, but they are supported on WSL.
the Chrome browser installed on your machine
"},{"location":"default-configuration/#overview-plugin-and-theme-project","title":"Overview - plugin and theme project","text":"
If you're configuring wp-browser for a plugin or theme project, the default configuration will install WordPress in the tests/_wordpress directory and configure the installation to run using SQLite as a database engine. The SQLite Database Integration plugin) will be placed in the installation must-use plugins directory.
If your plugin or theme project requires additional plugins or theme to work, you can place them in the tests/_worpdress/wp-content/plugins and tests/_wordpress/wp-content/themes directories respectively.
When adding, or removing, plugin and themes, remember to update the WPLoader module configuration to load the correct plugins and themes in your integration tests.
On the same note, update the database dump used by the WPDb module to reflect the changes in the dump loaded in the end-to-end tests. The easiest way to update the database fixture is to load the current database dump using the wp:db:import command, manually setting up the site interacting with it and then exporting the database dump using the wp:db:export command.
You can find out about the URL of the site served by the PHP built-in web server by running the dev:info command.
"},{"location":"default-configuration/#overview-site-project","title":"Overview - site project","text":"
If you're configuring wp-browser for a site project, the default configuration will use a combination of PHP built-in web server and the SQLite Database Integration plugin to run the tests and serve your site.
The router file used by the PHP built-in web server will force the site, when served on localhost, to use SQLite as database engine leaving your existing local MySQL database untouched.
Your existing WordPress installation will be picked up as it is, with all the plugins and themes found in the contents directory.
Existing plugins and themes are not added to WPLoader module configuration by wp-browser, you have to do that manually.
Similarly, the database dump used by the WPDb module is, by default, an empty WordPress installation where no plugins and themes are active. You have to update the database dump used by the module to reflect the state of your site. You can do that by loading the current database dump using the wp:db:import command, manually setting up the site interacting with it and then exporting the database dump using the wp:db:export command.
You can find out about the URL of the site served by the PHP built-in web server by running the dev:info command.
"},{"location":"default-configuration/#when-not-to-use-the-default-configuration","title":"When not to use the default configuration","text":"
The default configuration is the recommended one for most projects, but some projects might require you to use a custom configuration to make the most out of wp-browser.
The default configuration will use the SQLite Database Integration plugin to use SQLite as the database engine. This requires placing a db.php drop-in file in the WordPress content directory.
If your project already requires a db.php drop-in file, you will have to use a custom configuration.
"},{"location":"default-configuration/#multisite-with-sub-domains","title":"Multisite with sub-domains","text":"
While Chrome will handle sub-domains correctly, even on localhost, WordPress will not. If you're testing a multisite installation with sub-domains, you will have to use a custom configuration.
"},{"location":"default-configuration/#custom-site-structure","title":"Custom site structure","text":"
If your site uses a customized file structure to manage WordPress, you will need to configure wp-browser using a custom configuration. This is usually true for some site projects, and will most likely not be an issue for plugin and theme projects.
Using a custom configuration is not that difficult though: read more about using a custom configuration here.
"},{"location":"extensions/","title":"Extensions","text":""},{"location":"extensions/#codeception-extensions-provided-by-the-library","title":"Codeception Extensions provided by the library","text":"
The library provides some custom Codeception extensions that can be added to the project Codeception configuration file, in the extensions section.
This extension will start and stop the PHP built-in web server before and after the tests run.
The extension can be configured with the following parameters:
required
docRoot - the document root to use for the PHP Built-in server; it can be either an absolute path or a path relative to the Codeception root directory.
optional
suites - an array of Codeception suites to run the server for; if not set the server will be started for all the suites.
port - the port to use for the PHP Built-in server, if not set the server will use port 2389.
workers - the number of workers to use for the PHP Built-in server, if not set the server will use 5 workers. This is the equivalent of the PHP_CLI_SERVER_WORKERS environment variable.
Note: if you run PHP built-in server on Windows, the workers parameter will be ignored and the server will always run with a single worker. This limit is not present in WSL.
Example configuration starting the server for all suites:
You can use the chromedriver:update command to download the latest version of ChromeDriver compatible with your Chrome browser version and place it in the Composer bin directory.
This is a service extension that will be started and stopped by the dev:start and dev:stop commands.
Browse and test the site HTML with a fast browser without Javascript support.
This module trades the WPWebDriver module Javascript support for speed and stability. It is a good choice for testing sites that don't use Javascript or to make assertions that do not require Javascript support like:
testing HTTP return codes
testing HTML structure
testing JSON and XML responses from APIs
This module is used together with the WPDb module and the WPFilesystem module to control the site state, the database, and the site file structure.
This module is an extension of the Codeception PHPBrowser module, you can reference to the Codeception module documentation for more information on the module configuration and usage.
This module should be with Cest and Cept test cases.
url - required; the start URL of your WordPress project.
adminUsername - required; the site administrator username to use in actions like loginAsAdmin.
adminPassword - required; the site administrator password to use in actions like loginAsAdmin.
adminPath - the path to the WordPress admin directory; defaults to /wp-admin.
More Guzzle request options are available like:
headers - default headers are set before each test. cookies - default cookies are set before each test. auth - default authentication to be set before each test.
... and more.
The following is an example of the module configuration to run tests on thehttp://localhost:8080 site:
Use WP-CLI to interact with the WordPress installation under test and issue commands.
This module is used in the context of end-to-end testing, together with, or as a replacement for the WPDb module to manipulate the database and the WPFilesystem module to manipulate the site file structure.
This module should be with Cest and Cept test cases.
path - required; the path to the WordPress installation under test. This can be a relative path to the codeception root directory, or an absolute path to the WordPress installation directory. The WordPress installation directory is the directory that contains the wp-load.php file.
url - the URL of the WordPress installation under test. Equivalent to the --url option of the wp command.
user - the user to use to run the wp command. Equivalent to the --user option of the wp command.
skip-plugins - a boolean value to indicate if the wp command should skip loading plugins. Equivalent to the --skip-plugins option of the wp command.
skip-themes - a boolean value to indicate if the wp command should skip loading themes. Equivalent to the --skip-themes option of the wp command.
skip-packages - a boolean value to indicate if the wp command should skip loading packages. Equivalent to the --skip-packages option of the wp command.
require - a list of PHP files to require before running the wp command. Equivalent to the --require option of the wp command.
exec - PHP code to execute before running the wp command. Equivalent to the --exec option of the wp command.
context - the context to use when running the wp command. Equivalent to the --context option of the wp command.
color - a boolean value to indicate if the wp command should output in color. Equivalent to the --color option of the wp command.
no-color - a boolean value to indicate if the wp command should not output in color. Equivalent to the --no-color option of the wp command.
debug - a boolean value to indicate if the wp command should output debug information. Equivalent to the --debug option of the wp command.
quiet - a boolean value to indicate if the wp command should suppress informational messages. Equivalent to the --quiet option of the wp command.
throw - a boolean value to indicate if the wp command should throw an exception if the command fails.
timeout - the timeout to use when running the wp command. When the timeout is reached the command will be terminated as a failure.
cache-dir - the directory to use to cache the files WPCLI might downloads. Equivalent to setting the WP_CLI_CACHE_DIR environment variable.
config-path - the path to the wp-cli.yml file to use. Equivalent to setting the WP_CLI_CONFIG_PATH environment variable.
custom-shell - the shell to use to run the wp command. Equivalent to setting the WP_CLI_SHELL environment variable.
packages-dir - the directory to use to store the packages downloaded by the wp package command. Equivalent to setting the WP_CLI_PACKAGES_DIR environment variable.
The following is an example of the module configuration to run WPCLI commands on the /var/wordpress directory:
This module allows to manipulate the database of the WordPress installation under test directly, without using the WordPress API.
The module is used together with the WPBrowser module, WPWebDriver and WPFilesystem modules to control the site state, the database, and the site file structure.
Note about interaction with the WPLoader module: both this module and the WPLoader one can be used to control the state of the database before tests and set up fixtures: use either this or WPLoader, do not use both. This module should be used in end-to-end testing, the WPLoader module should be used in integration testing. If you're using this module to load a database dump before integration tests, use the WPLoader module dump configuration parameter instead.
This module should be with Cest and Cept test cases.
This module extends the Codeception Db module adding some configuration options and functions that are specific to WordPress.
dbUrl - required; the URL to use to connect to the database. The URL must be in the form mysql://user:password@host:port/database if you're using a MySQL database for your tests, or in the form sqlite://path/to/database/file if you're using a SQLite database for your tests ( like the default configuration does)
dsn - required; the DSN to use to connect to the database; required if not using the dbUrl parameter.
user - required; the user to use to connect to the database; required if not using the dbUrl parameter.
password - required; the password to use to connect to the database; required if not using the dbUrl parameter.
url - required;the URL of the WordPress installation under test. E.g. http://localhost:8080 or https://wordpress.test.
tablePrefix - the table prefix to use when interacting with the database; defaults to wp_.
dump - the path to a database dump file, or a set of database files, to load before running tests. The path can be relative to the project root directory, e.g. tests/_data/dump.sql, or absolute.
populate - a boolean value to indicate if the database should be populated importing the dump file(s) at the start of the suite.
cleanup - a boolean value to indicate if the database should be populated importing the dump file(s) before each test.
reconnect - a boolean value to indicate if the database connection should be re-established before each test.
populator - a command to use to populate the database instead of using PHP; read more on the Codeception documentation.
urlReplacement - a boolean value to indicate if the database dump file(s) should be searched for the siteurl and home options and replaced with the url parameter value. This is required since WordPress hard-codes URLs in the database, the original URL is inferred, if the originalUrl parameter is not provided.
originalUrl - if provided together with the urlReplacement parameter, the module will not try to infer the original URL from the database dump file(s) but use the provided value instead.
waitlock - the number of seconds to wait for a database lock to be released before failing the test. Defaults to 10 meaning that the test will fail if the database lock is not released after 10 seconds.
createIfNotExists - a boolean value to indicate if the database should be created if it does not exist. Defaults to false.
The following is an example of the module configuration to run tests on thehttp://localhost:8080 site:
Interact and make assertions on the WordPress file structure.
This module is used together with the WPDb module to manage the state of the WordPress installation in the context of end-to-end tests.
This module extends the Filesystem module from Codeception, you can reference to the Codeception documentation to find out more about the module configuration and usage.
This module should be with Cest and Cept test cases.
wpRootFolder - required; the path to the WordPress installation root folder. This can be a relative path to the codeception root directory, or an absolute path to the WordPress installation directory. The WordPress installation directory is the directory that contains the wp-load.php file. themes - the path, relative to the path specified in the wpRootFolder parameter, to the themes directory. By default, it's /wp-content/themes. plugins - the path, relative to the path specified in the wpRootFolder parameter, to the plugins directory. By default, it's /wp-content/plugins. mu-plugins - the path, relative to the path specified in the wpRootFolder parameter, to the must-use plugins. By default, it's /wp-content/mu-plugins. directory. uploads - the path, relative to the path specified in the wpRootFolder parameter, to the uploads directory. By default, it's /wp-content/uploads.
The following is an example of the module configuration to run tests on the /var/wordpress site:
A module to load WordPress and make its code available in tests.
Depending on the value of the loadOnly configuration parameter, the module will behave differently:
loadOnly: false - The module will load WordPress like the Core PHPUnit suite does to run integration tests in a controlled environment. Use the module in this mode with test cases generated using the generate:wpunit command.
loadOnly: true - The module will load WordPress to make it available in the context of tests. Use the module in this mode in Cest, Cept and Codeception unit test cases.
"},{"location":"modules/WPLoader/#configuration-with-loadonly-false","title":"Configuration with loadOnly: false","text":"
The module will load WordPress like the Core PHPUnit suite does to run integration tests in a controlled environment. Together with the test case generated by the generate:wpunit command the module will:
take care of running any test method in a database transaction rolled back after each test
manage and clean up the global environment and context between tests
When used in this mode, the module supports the following configuration parameters:
loadOnly - false to load WordPress and run tests in a controlled environment.
wpRootFolder - required; the path to the WordPress installation root folder. This can be a relative path to the codeception root directory, or an absolute path to the WordPress installation directory. The WordPress installation directory is the directory that contains the wp-load.php file.
dbUrl - required; the URL to the database to use to run tests. The URL must be in the form mysql://username:password@host:port/database to use a MySQL database, or in the form sqlite://path/to/database to use a SQLite database. Alternatively, you can use the dbName, dbUser, dbPassword, dbHost configuration parameters to specify the database connection details.
dump - the path to a database dump, or a set of database dumps, to load before running tests. The dump will be loaded only once, after the tests run.
tablePrefix - the database table prefix to use when loading WordPress, defaults to wp_.
multisite - a boolean value to indicate if WordPress should be loaded and initialized in multisite mode.
dbCharset - the database charset to use when loading WordPress.
dbCollate - the database collate to use when loading WordPress.
domain - the domain to use when loading WordPress. Equivalent to defining the WP_TESTS_DOMAIN constant.
adminEmail - the administrator email to use when loading WordPress. Equivalent to defining the WP_TESTS_EMAIL constant.
title - the site title to use when loading WordPress. Equivalent to defining the WP_TESTS_TITLE constant.
phpBinary - the path to the PHP binary to use to run tests. Defaults to the WP_PHP_BINARY constant.
language - the language to use when loading WordPress. Equivalent to defining the WPLANG constant.
configFile - a configuration file, or a set of configuration files, to load before the tests to further customize and control the WordPress testing environment.
pluginsFolder - the path to the plugins folder to use when loading WordPress. Equivalent to defining the WP_PLUGIN_DIR constant.
plugins - a list of plugins to activate and load in the WordPress installation. Each plugin must be specified in a format like hello.php or my-plugin/my-plugin.php format.
bootstrapActions - a list of actions or callbacks to call after WordPress is loaded and before the tests run.
theme - the theme to activate and load in the WordPress installation. The theme must be specified in slug format like twentytwentythree.
AUTH_KEY - the AUTH_KEY constant value to use when loading WordPress. If the wpRootFolder path points at a configured installation, containing the wp-config.php file, then the value of the constant in the configuration file will be used, else it will be randomly generated.
SECURE_AUTH_KEY - the SECURE_AUTH_KEY constant value to use when loading WordPress. If the wpRootFolder path points at a configured installation, containing the wp-config.php file, then the value of the constant in the configuration file will be used, else it will be randomly generated.
LOGGED_IN_KEY - the LOGGED_IN_KEY constant value to use when loading WordPress. If the wpRootFolder path points at a configured installation, containing the wp-config.php file, then the value of the constant in the configuration file will be used, else it will be randomly generated.
NONCE_KEY - the NONCE_KEY constant value to use when loading WordPress. If the wpRootFolder path points at a configured installation, containing the wp-config.php file, then the value of the constant in the configuration file will be used, else it will be randomly generated.
AUTH_SALT - the AUTH_SALT constant value to use when loading WordPress. If the wpRootFolder path points at a configured installation, containing the wp-config.php file, then the value of the constant in the configuration file will be used, else it will be randomly generated.
SECURE_AUTH_SALT - the SECURE_AUTH_SALT constant value to use when loading WordPress. If the wpRootFolder path points at a configured installation, containing the wp-config.php file, then the value of the constant in the configuration file will be used, else it will be randomly generated.
LOGGED_IN_SALT - the LOGGED_IN_SALT constant value to use when loading WordPress. If the wpRootFolder path points at a configured installation, containing the wp-config.php file, then the value of the constant in the configuration file will be used, else it will be randomly generated.
NONCE_SALT - the NONCE_SALT constant value to use when loading WordPress. If the wpRootFolder path points at a configured installation, containing the wp-config.php file, then the value of the constant in the configuration file will be used, else it will be randomly generated.
AUTOMATIC_UPDATER_DISABLED - the AUTOMATIC_UPDATER_DISABLED constant value to use when loading WordPress. If the wpRootFolder path points at a configured installation, containing the wp-config.php file, then the value of the constant in the configuration file will be used, else it will be randomly generated.
WP_HTTP_BLOCK_EXTERNAL - the WP_HTTP_BLOCK_EXTERNAL constant value to use when loading WordPress. If the wpRootFolder path points at a configured installation, containing the wp-config.php file, then the value of the constant in the configuration file will be used, else it will be randomly generated.
This is an example of an integration suite configured to use the module:
"},{"location":"modules/WPLoader/#handling-a-custom-site-structure","title":"Handling a custom site structure","text":"
If you're working on a site project using a custom file structure, e.g. [Bedrock][4], you should use a custom configuration and, together with that, configure the WPLoader module to load WordPress, plugins and themes code from the correct locations. Take care to point the wpRootFolder parameter to the directory containing the wp-load.php file, the /var/my-site/web/wp one in the following example, and the module will read the project configuration file to load the WordPress code from the correct location.
Here's an example of how the module should be configured to run integration tests on a Bedrock installation:
In general, pointing the wpRootFolder parameter to the directory containing the wp-load.php file should take care of loading WordPress code from the correct location. Should that not be the case, use the configFile parameter to point the module to the project test configuration file: a PHP file defining the constants and environment variables to use to load WordPress, plugins and themes correctly.
"},{"location":"modules/WPLoader/#configuration-with-loadonly-true","title":"Configuration with loadOnly: true","text":"
The module will load WordPress from the location specified by the wpRootFodler parameter, relying on the WPDb module to manage the database state.
When used in this mode, the module supports the following configuration parameters:
loadOnly - true to load WordPress and make it available in the context of tests.
wpRootFolder - required; the path to the WordPress installation root folder. This can be a relative path to the codeception root directory, or an absolute path to the WordPress installation directory. The WordPress installation directory is the directory that contains the wp-load.php file.
dbUrl - required; the URL to the database to use to run tests. The URL must be in the form mysql://username:password@host:port/database to use a MySQL database, or in the form sqlite://path/to/database to use a SQLite database. Alternatively, you can use the dbName, dbUser, dbPassword, dbHost configuration parameters to specify the database connection details.
domain - the domain to use when loading WordPress. Equivalent to defining the WP_TESTS_DOMAIN constant.
The following is an example of the module configuration to run end-to-end tests on the site served at http://localhost:8080 URL and served from the /var/wordpress directory:
This module provides assertions for WordPress queries.
This module can be used in any test context where the global $wpdb variable is defined, this usually means in any suite where [the WPLoader module] is used.
This module drives a browser using a solution like Selenium or Chromedriver to simulate user interactions with the WordPress project.
The module has full Javascript support, differently from the WPBrowser module, and can be used to test sites that use Javascript to render the page or to make assertions that require Javascript support.
The method extends the Codeception WebDriver module and is used in the context of Cest and Cept test cases.
waitForElementChange($element, Closure $callback, int [$timeout]) : void
waitForElementClickable($element, int [$timeout]) : void
waitForElementNotVisible($element, int [$timeout]) : void
waitForElementVisible($element, int [$timeout]) : void
waitForJS(string $script, int [$timeout]) : void
waitForJqueryAjax(int [$time]) : void
waitForText(string $text, int [$timeout], [$selector]) : void
Read more in Codeception documentation.
"},{"location":"v3/","title":"Index","text":"
This is the documentation for version 3 of the project. The current version is version 4 and the documentation can be found here.
The wp-browser project provides a Codeception based solution to test WordPress plugins, themes and whole sites at all levels of testing.
The purpose of this documentation is to help you set up, run and iterate over your project and test code using the powerful APIs provided by Codeception while trying to alleviate the pains of setting it up for WordPress projects.
Throughout the documentation you will find references to test terminology: I've tried to condense those into small, digestable chunks to provide a rough idea without and a limited context; where required I tried to provide links to dive deeper into the subjects.
Happy testing!
"},{"location":"v3/#table-of-contents","title":"Table of contents","text":"
Welcome
Frequently asked questions
Codeception, PHPUnit and wp-browser
Using wp-browser with Codeception 4.0
Migration guides
Version 2 to version 3
Levels of testing
Getting started
Requirements
Installation
Setting up a minimum WordPress installation
Configuration
Tutorials
Automatically change database during acceptance and functional tests
Setting up wp-browser on VVV to test a plugin
Setting up wp-browser on MAMP for Mac to test a plugin
Setting up wp-browser on WAMP for Windows to test a plugin
Setting up wp-browser on Local by Flywheel to test a plugin
Modules
WPBrowser
WPCLI
WPDb
WPFilesystem
WPLoader
WPQueries
WPWebDriver
Advanced Usage
Running tests in separate processes
Events API
Extensions
Commands
Contributing
Sponsors
Changelog
"},{"location":"v3/codeception-4-support/","title":"Codeception 4 support","text":""},{"location":"v3/codeception-4-support/#using-wp-browser-with-codeception-40","title":"Using wp-browser with Codeception 4.0","text":"
Codeception version 4.0 introduced a number of new features to the framework and it's the version of wp-browser that will be maintained from now on.
I've made an effort to keep wp-browser compatible with PHP 5.6 and Codeception versions from 2.5 up.
One the biggest changes of Codeception version 4.0 is that modules have been broken out into separate packages. To use wp-browser with Codeception 4.0 all you need to do is to add this to your project composer.json file:
You might not need all the modules listed here, depending on the wp-browser modules you use in your test suites. This is a scheme of what Codeception modules you will need for which wp-browser module to help you choose only the required modules:
\"codeception/module-asserts\" - Required for Codeception 4.0 compatibility.
\"codeception/module-phpbrowser\" - Required by the WPBrowser module.
\"codeception/module-webdriver\" - Required by the WPWebDriver module.
\"codeception/module-db\" - Required by the WPDb module.
\"codeception/module-filesystem\" - Required by the WPFilesystem module.
\"codeception/module-cli\" - Required by the WPCLI module.
\"codeception/util-universalframework\" - Required by the WordPress framework module.
"},{"location":"v3/codeception-phpunit-and-wpbrowser/","title":"Codeception phpunit and wpbrowser","text":""},{"location":"v3/codeception-phpunit-and-wpbrowser/#the-wp-browser-stack","title":"The wp-browser stack","text":"
The wp-browser project is built leveraging the power of a number of open-source projects.
While I'm not listing all of them here it's worth mentioning those that will come up, again and again, in the documentation.
WordPress is open source software you can use to create a beautiful website, blog, or app.
The line is taken directly from WordPress.org site.
In the context of this documentation WordPress is the PHP and JavaScript framework websites and web applications can be built on, the one anyone can download from here.
Codeception (home) is a modern, powerful PHP testing framework written in PHP.
It comes with a number of modules and extensions that are comparable to WordPress plugins and themes.
Modules and extensions are combined in suites to be able to run a specific type of test. Each suite will handle a specific type of test for a specific set of code.
wp-browser is none other than a collection of modules and extensions for Codeception made specifically to test WordPress applications.
PHPUnit is the most widely known PHP testing framework. As the name implies it was born to make unit testing of PHP code easier but its scope and power has grown well below that.
Codeception is based, and uses, PhpUnit to wrap some of its functionalities into an easy-to-use API. The two are so compatible one with the other that Codeception can run PHPUnit tests with little to no changes.
This documentation will not cover this subject and will only deal with Codeception-native test methods but you can find more information here.
"},{"location":"v3/commands/","title":"Custom commands provided by wp-browser","text":"
The project comes with its own set of custom Codeception commands.
The commands provide functionalities to quickly scaffold different types of tests. Any other codecept command remains intact and available.
"},{"location":"v3/commands/#adding-the-commands-to-an-existing-project","title":"Adding the commands to an existing project","text":"
The commands are added to the main Codeception configuration file, codeception.yml, when scaffolding a project via the codecept init wp-browser command.
They can be added to any existing project adding, or editing, the commands section of the configuration file:
The library provides commands to quickly scaffold integration test cases for specific types of WordPress components, see levels of testing for more information.
The tests are almost identical to the ones you could write in a PHPUnit based Core suite with the exception of extending the Codeception\\TestCase\\WPTestCase test case.
Generates a test case extending the \\Codeception\\TestCase\\WPTestCase class using the
codecept generate:wpunit suite SomeClass\n
The command will generate a skeleton test case like
<?php\n\nclass SomeClassTest extends \\Codeception\\TestCase\\WPTestCase\n{\n public function setUp()\n {\n parent::setUp();\n }\n\n public function tearDown()\n {\n parent::tearDown();\n }\n\n // tests\n public function testMe()\n {\n }\n\n}\n
Generates a test case extending the \\Codeception\\TestCase\\WPRestApiTestCase class using the
codecept generate:wprest suite SomeClass\n
The command will generate a skeleton test case like
<?php\n\nclass SomeClassTest extends \\Codeception\\TestCase\\WPRestApiTestCase\n{\n public function setUp()\n {\n parent::setUp();\n }\n\n public function tearDown()\n {\n parent::tearDown();\n }\n\n // tests\n public function testMe()\n {\n }\n\n}\n
Generates a test case extending the \\Codeception\\TestCase\\WPRestControllerTestCase class using the
codecept generate:wprest suite SomeClass\n
The command will generate a skeleton test case like
<?php\n\nclass SomeClassTest extends \\Codeception\\TestCase\\WPRestControllerTestCase\n{\n public function setUp()\n {\n parent::setUp();\n }\n\n public function tearDown()\n {\n parent::tearDown();\n }\n\n // tests\n public function testMe()\n {\n }\n\n}\n
Generates a test case extending the \\Codeception\\TestCase\\WPRestPostTypeControllerTestCase class using the
codecept generate:wprest suite SomeClass\n
The command will generate a skeleton test case like
<?php\n\nclass SomeClassTest extends \\Codeception\\TestCase\\WPRestPostTypeControllerTestCase\n{\n public function setUp()\n {\n parent::setUp();\n }\n\n public function tearDown()\n {\n parent::tearDown();\n }\n\n // tests\n public function testMe()\n {\n }\n\n}\n
Generates a test case extending the \\Codeception\\TestCase\\WPAjaxTestCase class using the
codecept generate:wpajax suite SomeClass\n
The command will generate a skeleton test case like
<?php\n\nclass SomeClassTest extends \\Codeception\\TestCase\\WPAjaxTestCase\n{\n public function setUp()\n {\n parent::setUp();\n }\n\n public function tearDown()\n {\n parent::tearDown();\n }\n\n // tests\n public function testMe()\n {\n }\n\n}\n
Generates a test case extending the \\Codeception\\TestCase\\WPXMLRPCTestCase class using the
codecept generate:wpxmlrpc suite SomeClass\n
The command will generate a skeleton test case like
<?php\n\nclass SomeClassTest extends \\Codeception\\TestCase\\WPXMLRPCTestCase\n{\n public function setUp()\n {\n parent::setUp();\n }\n\n public function tearDown()\n {\n parent::tearDown();\n }\n\n // tests\n public function testMe()\n {\n }\n\n}\n
Generates a test case extending the \\Codeception\\TestCase\\WPCanonicalTestCase class using the
codecept generate:wpcanonical suite SomeClass\n
The command will generate a skeleton test case like
<?php\n\nclass SomeClassTest extends \\Codeception\\TestCase\\WPCanonicalTestCase\n{\n public function setUp()\n {\n parent::setUp();\n }\n\n public function tearDown()\n {\n parent::tearDown();\n }\n\n // tests\n public function testMe()\n {\n }\n\n}\n
While wp-browser can be configured manually creating each file the fastest way to bootstrap its configuration is by using its initialization template.
Throughout the steps below I will use the WordPress setup I've prepared before From the root folder of the project, /Users/luca/Sites/wordpress/wp-content/plugins/acme-plugin in the example, run the command:
vendor/bin/codecept init wpbrowser\n
Composer installed Codeception binary (codecept) in the vendor folder of my project.
With the command above I'm telling Codeception to initialize a wp-browser project in the current folder. When I click enter I'm presented with a list of questions, each answer will be used to configure the wp-browser project for me; one by one.
In the screenshot the answers I've provided to each question, with reference to the setup above:
wp-browser will try to provide a brief explanation of what each question is but below is the long version.
I've tried to condense as much clarity as possible in the questions the codecept init wpbrowser command will ask but, for sake of brevity and space, there's no way I could provide inline a deeper explanation of each.
Below is a longer explanation of each question:
How would you like the acceptance suite to be called?
How would you like the functional suite to be called?
How would you like the WordPress unit and integration suite to be called?
How would you like to call the env configuration file?
Where is WordPress installed?
What is the path, relative to WordPress root URL, of the admin area of the test site?
What is the name of the test database used by the test site?
What is the host of the test database used by the test site?
What is the user of the test database WPLoader should use?
What is the password of the test database WPLoader should use?
What is the table prefix of the test database WPLoader should use?
What is the URL the test site?
What is the email of the test site WordPress administrator?
What is the title of the test site?
What is the login of the administrator user of the test site?
What is the password of the administrator user of the test site?
Are you testing a plugin, a theme or a combination of both?
What is the folder/plugin.php name of the plugin?
Are you developing a child theme?
Are you using a child theme?
What is the slug of the parent theme?
What is the slug of the theme?
What is the slug of the theme you are using?
Does your project needs additional plugins to be activated to work?
"},{"location":"v3/configuration/#how-would-you-like-the-acceptance-suite-to-be-called","title":"How would you like the acceptance suite to be called?","text":"
With reference to the testing levels definition this question provides you with the possibility to change the name of the acceptance-like test suite.
Common, alternative, names are ui, rest and user.
"},{"location":"v3/configuration/#how-would-you-like-the-functional-suite-to-be-called","title":"How would you like the functional suite to be called?","text":"
With reference to the testing levels definition this question provides you with the possibility to change the name of the functional-like test suite.
A common alternative name is service.
"},{"location":"v3/configuration/#how-would-you-like-the-wordpress-unit-and-integration-suite-to-be-called","title":"How would you like the WordPress unit and integration suite to be called?","text":"
With reference to the testing levels definition this question provides you with the possibility to change the name of the suite dedicated to integration and \"WordPress unit\" tests.
A common alternative name is integration.
"},{"location":"v3/configuration/#how-would-you-like-to-call-the-env-configuration-file","title":"How would you like to call the env configuration file?","text":"
Instead of configuring each module in each suite with the same parameters over and over Codeception supports dynamic configuration via environment files.
wp-browser will scaffold such a configuration for you and will use, by default, a file called .env to store the configuration parameters.
The file name might not suit all setups especially and this question allows changing that file name; common, alternative, file names are .env.tests, .env.codeception and similar.
"},{"location":"v3/configuration/#where-is-wordpress-installed","title":"Where is WordPress installed?","text":"
During tests the test code will need to access WordPress code, precisely wp-browser requires being pointed to the folder that contains the wp-load.php file.
The answer can be an absolute path, like /Users/luca/Sites/wordrpress, or a path relative to the folder where Codeception is installed like vendor/wordpress.
This path should be accessible by the machine that is running the tests; if you're running the tests from your machine (e.g. your laptop) that's just the path to the folder where WordPress is installed, /Users/luca/Sites/wordpress in the example configuration above.
If you are, instead, running the tests from within a virtualized machine (e.g. Vagrant or Docker) then the path should be the one used by the virtualized machine.
To make an example:
on my machine WordPress is installed at /Users/luca/Sites/wordpress
I've created a Docker container using the official WordPress image and bound the above folder into the container
internally the container will put WordPress in the /var/www/html folder
If I run the tests from my host machine then WordPress root directory will be /Users/luca/Sites/wordpress, if I run the tests from within the Docker container then WordPress root folder will be /var/www/html.
Another example is Local by Flywheel:
in the host machine the path to the WordPress root folder will be /Users/luca/Local\\ Sites/wordpress/app/public
from within the Docker container managed by Local the path will be /app/public
If you need a solution that will work in both instances use a relative path: wp-browser will accept paths like ./../../../wordpress and will attempt to resolve them.
"},{"location":"v3/configuration/#what-is-the-path-relative-to-wordpress-root-url-of-the-admin-area-of-the-test-site","title":"What is the path, relative to WordPress root URL, of the admin area of the test site?","text":"
This is usually /wp-admin but you might have the web-server, or a plugin, redirect or hide requests for the administration area to another path.
Some examples are /admin, /login and the like.
Mind that this is not the path to the login page but the path to the administrationo area; this will be used by wp-browser to find to the administration area in acceptance and functional tests.
"},{"location":"v3/configuration/#what-is-the-name-of-the-test-database-used-by-the-test-site","title":"What is the name of the test database used by the test site?","text":"
In my example setup it's wordpress.
This is the name of the database that is storing the information used by the site I can reach at http://localhost:8080.
I want to underline the word \"test\". Any site and any database you use and expose to wp-browser should be intended for tests; this means that it does not contain any data you care about as it will be lost.
"},{"location":"v3/configuration/#what-is-the-host-of-the-test-database-used-by-the-test-site","title":"What is the host of the test database used by the test site?","text":"
In my example setup it's 127.0.0.1:3306.
Here the same principle valid for Where is WordPress installed? applies: the database host is relative to the machine that is running the tests.
In my example I'm hosting the database locally, on my laptop, and my machine can reach it at the localhost address (127.0.0.1) on MySQL default port (3306).
If I am using the database of a Local by Flywheel site from my host machine then it might be something like 192.168.92.100:4050 (from the site \"Database\" tab); the same principle applies if I am using a Vagrant-based or Docker-based solution.
If I am running the tests from within a virtualized machine (a Docker container, a Vagrant box et cetera) then it would probably be localhost or 1270.0.0.1.
This detail will be used in the context of acceptance and functional tests by the WPDb module.
"},{"location":"v3/configuration/#what-is-the-user-of-the-test-database-used-by-the-test-site","title":"What is the user of the test database used by the test site?","text":"
In my example setup it's root as I'm using MySQL server root user to access the database during tests.
Depending on your setup it might be different; since wp-browser will need to not only read but write too to the database make sure to use a user that has full access to the database specified in the answer to the What is the host of the test database used by the test site? question.
This detail will be used in the context of acceptance and functional tests by the WPDb module.
"},{"location":"v3/configuration/#what-is-the-password-of-the-test-database-used-by-the-test-site","title":"What is the password of the test database used by the test site?","text":"
In my example setup it's empty as I've not set any password for the root account.
In your case it might be different and it should be the password associated with the user specified in the answer to the What is the user of the test database used by the test site? question.
This detail will be used in the context of acceptance and functional tests by the WPDb module.
"},{"location":"v3/configuration/#what-is-the-table-prefix-of-the-test-database-used-by-the-test-site","title":"What is the table prefix of the test database used by the test site?","text":"
In my example setup it's wp_; that value is taken from the WordPress installation configuration file.
To have any influence on the site wp-browser will need to modify the same database tables WordPress is using; as I did you can take this value from the wp-config.php file directly: it's the value of the $table_prefix variable.
This detail will be used in the context of acceptance and functional tests by the WPDb module.
"},{"location":"v3/configuration/#what-is-the-name-of-the-test-database-wploader-should-use","title":"What is the name of the test database WPLoader should use?","text":"
In my example setup it's tests.
During integration, or WordPress \"unit\" tests, wp-loader will need to load WordPress code.
Since WordPress code is not meant to be \"modular\" it does not support auto-loading or loading just parts of it; it's either almost all or nothing.
One of the first things WordPress does, when loading, is trying to connect to a database: if that database is not available then WordPress will not load.
In the answer to the question Where is WordPress installed? I've told wp-browser where to find WordPress code, in this answer I'm telling wp-browser what database it should use to bootstrap WordPress.
This detail will be used by the WPLoader module to bootstrap WordPress. It's highly recommended to use a different database from the one used for functional and acceptance tests.
"},{"location":"v3/configuration/#what-is-the-host-of-the-test-database-wploader-should-use","title":"What is the host of the test database WPLoader should use?","text":"
In my example setup it's 127.0.0.1:3306.
As in the answer to the question What is the name of the test database WPLoader should use? we're providing connection details about the database that should be used to bootstrap WordPress during integration and WordPress \"unit\" tests.
Again the database host is in relation to the machine running the tests, all the considerations done for What is the host of the test database used by the test site? apply.
This detail will be used by the WPLoader module to bootstrap WordPress.
"},{"location":"v3/configuration/#what-is-the-user-of-the-test-database-wploader-should-use","title":"What is the user of the test database WPLoader should use?","text":"
In my example it's root.
Similar to the question What is the user of the test database used by the test site? but in relation to the database specified in the question What is the name of the test database WPLoader should use?.
This detail will be used by the WPLoader module to bootstrap WordPress.
"},{"location":"v3/configuration/#what-is-the-password-of-the-test-database-wploader-should-use","title":"What is the password of the test database WPLoader should use?","text":"
In my example setup it's empty as I've not set any password for the root account.
Similar to the question What is the password of the test database used by the test site? but in relation to the database specified in the question What is the name of the test database WPLoader should use?.
This detail will be used by the WPLoader module to bootstrap WordPress.
"},{"location":"v3/configuration/#what-is-the-table-prefix-of-the-test-database-wploader-should-use","title":"What is the table prefix of the test database WPLoader should use?","text":"
In my example setup it's wp_.
Similar to the question What is the table prefix of the test database used by the test site? but in relation to the database specified in the question What is the name of the test database WPLoader should use?.
This detail will be used by the WPLoader module to bootstrap WordPress.
"},{"location":"v3/configuration/#what-is-the-url-the-test-site","title":"What is the URL the test site?","text":"
In my example setup it's http://localhost:8080.
This is the full URL you would have to enter in the browser, on the machine that is running the tests, to reach the test WordPress site homepage.
"},{"location":"v3/configuration/#what-is-the-email-of-the-test-site-wordpress-administrator","title":"What is the email of the test site WordPress administrator?","text":"
In my example setup it's admin@wp.localhost.
This detail will be used by the WPLoader module to bootstrap WordPress and, while required, it's usually not relevant unless you're testing email communications.
"},{"location":"v3/configuration/#what-is-the-title-of-the-test-site","title":"What is the title of the test site?","text":"
In my example setup it's Acme Plugin Test Site.
This detail will be used by the WPLoader module to bootstrap WordPress and, while required, it's usually not relevant unless you're testing around the site title.
"},{"location":"v3/configuration/#what-is-the-login-of-the-administrator-user-of-the-test-site","title":"What is the login of the administrator user of the test site?","text":"
In my example setup it's admin.
This detail will be used by the WPBrowser or WPWebDriver modules to fill in the login details for the administrator user.
It should be the same as the one that allows you to access the site administration area in the WordPress test site, http://localhost:8080/wp-admin in my example.
"},{"location":"v3/configuration/#what-is-the-password-of-the-administrator-user-of-the-test-site","title":"What is the password of the administrator user of the test site?","text":"
In my example setup it's password.
This detail will be used by the WPBrowser or WPWebDriver modules to fill in the login details for the administrator user.
It should be the same as the one that allows you to access the site administration area in the WordPress test site, http://localhost:8080/wp-admin in my example.
"},{"location":"v3/configuration/#are-you-testing-a-plugin-a-theme-or-a-combination-of-both","title":"Are you testing a plugin, a theme or a combination of both?","text":"
Depending on the answer the WPLoader module will load, during integration or WordPress \"unit\" tests, your WordPress plugin or theme.
If you replied with both (for \"a combination of both\") then you'll be able to choose the plugins and theme to load in integration and WordPress \"unit\" tests in the following questions.
"},{"location":"v3/configuration/#what-is-the-folderpluginphp-name-of-the-plugin","title":"What is the folder/plugin.php name of the plugin?","text":"
This question will be asked only if you replied plugin to the question Are you testing a plugin, a theme or a combination of both?. In my example setup it's acme-plugin/plugin.php.
This is the <folder>/<main-plugin-file>.php path, relative to the WordPress installation plugins folder, to the plugin you are testing.
The main plugin file is the one that contains the plugin header.
This detail will be used by the WPLoader module to bootstrap WordPress and load your plugin or theme in integration and WordPress \"unit\" tests.
"},{"location":"v3/configuration/#are-you-developing-a-child-theme","title":"Are you developing a child theme?","text":"
This question will be asked only if you replied theme to the question Are you testing a plugin, a theme or a combination of both?. Enter yes if you are developing a child theme.
This detail will be used by the WPLoader module to bootstrap WordPress and load a parent theme along with your theme in integration and WordPress \"unit\" tests.
Please note that wp-browser will not download and install the parent theme in the WordPress installation for you.
"},{"location":"v3/configuration/#are-you-using-a-child-theme","title":"Are you using a child theme?","text":"
This question will be asked only if you replied both to the question Are you testing a plugin, a theme or a combination of both?. Enter yes if you are using a child theme.
This detail will be used by the WPLoader module to bootstrap WordPress and load a parent theme along with your theme in integration and WordPress \"unit\" tests.
Please note that wp-browser will not download and install the parent theme in the WordPress installation for you.
"},{"location":"v3/configuration/#what-is-the-slug-of-the-parent-theme","title":"What is the slug of the parent theme?","text":"
This question will be asked only if you replied yes to the question Are you developing a child theme?.
Reply with the slug of the parent theme, that's usually the name of the folder the parent theme lives in, e.g. twentyseventeen.
This detail will be used by the WPLoader module to bootstrap WordPress and load a parent theme along with your theme in integration and WordPress \"unit\" tests.
Please note that wp-browser will not download and install the parent theme in the WordPress installation for you.
"},{"location":"v3/configuration/#what-is-the-slug-of-the-theme","title":"What is the slug of the theme?","text":"
This question will be asked only if you replied theme to the question Are you testing a plugin, a theme or a combination of both?. Reply with the slug of the theme, that's usually the name of the folder the theme lives in, e.g. twentyseventeen.
This detail will be used by the WPLoader module to bootstrap WordPress and load your theme in integration and WordPress \"unit\" tests.
"},{"location":"v3/configuration/#what-is-the-slug-of-the-theme-you-are-using","title":"What is the slug of the theme you are using?","text":"
This question will be asked only if you replied both to the question Are you testing a plugin, a theme or a combination of both?. Reply with the slug of the theme you are using, that's usually the name of the folder the theme lives in, e.g. twentyseventeen.
This detail will be used by the WPLoader module to bootstrap WordPress and load the theme integration and WordPress \"unit\" tests.
"},{"location":"v3/configuration/#does-your-project-needs-additional-plugins-to-be-activated-to-work","title":"Does your project needs additional plugins to be activated to work?","text":"
Whether you're testing a plugin, a theme or a combination of both you might need some additional plugins to run your tests.
As an example if I'm testing a WooCommerce extension I need the WooCommerce plugin to test it; this is the place where I can define it.
The required plugins follow the same format as the one used in the question What is the folder/plugin.php name of the plugin?: <plugin-folder>/<plugin-main-file>.php; in the case of WooCommerce it would be woocommerce/woocommerce.php.
This detail will be used by the WPLoader module to bootstrap WordPress and load the required plugins in integration and WordPress \"unit\" tests.
Please note that wp-browser will not download and install the required plugins in the WordPress installation for you.
"},{"location":"v3/configuration/#if-you-entered-a-wrong-value","title":"If you entered a wrong value","text":"
No worries, just correct the value in the environment file or in the suites configuration files.
The environment file will have the name you specified in the answer the question How would you like to call the env configuration file?.
The suites configuration files can be found in tests/<suite>.suite.yml; e.g. the wpunit suite configuration file will be tests/wpunit.suite.yml file.
To complete the setup I have removed any demo content from the site and activated my plugin in the plugins administration page.
In the tests/acceptance.suite.yml file and in the tests/functional.suite.yml file, the configuration file for the acceptance and functional suites respectively, the WPDb module configuration contains a dump configuration parameter:
The dump parameter is inherited by the WPDb module from the Codeception Db module and defines the SQL dump file that should be loaded before, and between, tests to reset the testing environment to a base known state.
As for any other database-related operation wp-browser will not create the dump for me. I use MySQL binary to export the database state (a dump) with the command:
There is one last check I need to make before jumping into the creation of tests: making sure all the paths and credentials I've configured wp-browser with are correct.
The bootstrap process generated four suites for me: acceptance, functional, integration and unit. If you have modified the default suite names during the setup your suites names might differ though.
To test the setup I will run each suite and make sure it can run correctly empty of any test. To run a suite of tests I will use the codecept run command:
codecept run acceptance\ncodecept run functional\ncodecept run integration\ncodecept run unit\n
How comes I'm not using the command codecept run (without specifying the suite names)? See the FAQ entry.
If you cannot run all the suites without issues then check your configuration settings again, read the errors and see If you entered a wrong value
"},{"location":"v3/contributing/","title":"Contributing to wp-browser","text":"
There are many ways you can contribute to the project and most of them do not involve having an intimate knowledge of Codeception or wp-browser internals.
"},{"location":"v3/contributing/#reporting-an-issue","title":"Reporting an issue","text":"
It can be done from here.
Whenever you find yourself struggling with something, anything, while using wp-browser, please report an issue.
If your issue is not a real issue it will be quickly closed but still provide two values:
it will remain in the repository issues archive making it searchable for any other user having the same, or similar, issue
it might shine a light on missing documentation, API or clarity in general. Take the time to fill in the issue template provided and provide as many details as you can.
"},{"location":"v3/contributing/#reporting-a-bug","title":"Reporting a bug","text":"
The project pulls a number of components together and will have bugs. If you run into one of them then provide as much detail as possible when opening the issue. Beside what the issue template will ask feel free to provide as much additional detail as you can.
If you feel the documentation is lacking or missing something entirely please report it. No documentation can possibly cover any case ever but there's a good chance you're not alone with the feeling that something is amiss.
"},{"location":"v3/contributing/#requesting-new-features","title":"Requesting new features","text":"
I've not used all the tools, environments and possible setups wp-browser could cover.
If you feel wp-browser is missing a feature open an issue and try to provide as many details as possible:
What problem would the new feature solve?
Is it possible to do what you would like the new feature to do with the existing API?
Could you provide an example of the API/configuration you would like to be able to use? A new feature can be as small as a new module method or as large as a new module entirely: do not be afraid to ask.
If you encounter any of the issues above and have a proposed fix for it then open a pull request alongside an issue.
Any pull-request has to pass tests before being merged and I might add code to your pull request to add tests or update them; I will work with you on the pull request if required.
Codeception comes with a set of events modules and extensions can subscribe to.
Codeception Events API is, but, only available to Modules and Extensions, and while that might be good for most cases, it might not cover a number of edge cases.
Similarly to WordPress add_action function, wp-browser provides the tad\\WPBrowser\\addListener function:
function addListener($eventName, callable $listener, $priority = 0);\n
The priority works the reverse way as it does in WordPress: highest number will be processed first!
Again similarly to WordPress do_action function, the tad\\WPBrowser\\dispatch function:
function dispatch($eventName, $origin = null, array $context = []);\n
This is the kind of API that is better shown with an example, though.
In this example I'm writing acceptance tests and would like to avoid the performance hit that the cleanup configuration parameter of the Db, or WPDb, module implies. The cleanup parameter will trigger the drop of all tables in the test database and the re-import of the SQL dump file, or files, between each test. This will ensure a clean starting fixture between tests, but for larger setup fixtures this might be a long operation that wastes precious seconds when, say, the only change is the addition of 3 posts, as in this example.
The Events API allows implementing a tailored clean-up procedure that can avoid costly clean ups between tests.
In the suite bootstrap file, e.g. tests/acceptance/_bootstrap.php, I add a listener on the my-plugin-test/setup-posts event. The event will contain information about what post IDs I've set up in the tests and will provide an instance of the tester object to handle database manipulation. With that information, the costly cleanup procedure can be avoided.
<?php\n\n$registerPostsCleanup = static function (tad\\WPBrowser\\Events\\WpbrowserEvent $event) {\n $ids = $event->get('ids', []);\n /** @var \\EventsTester $db */\n $db = $event->get('db');\n\n // When tests are done, then remove all the posts we've created at the start of the test, if any.\n tad\\WPBrowser\\addListener(\n Codeception\\Events::TEST_AFTER,\n static function () use ($ids, $db) {\n foreach ($ids as $id) {\n $db->dontHavePostInDatabase([ 'ID' => $id ], true);\n // Ensure the clean up did happen correctly.\n $db->dontSeePostInDatabase([ 'ID' => $id ]);\n $db->dontSeePostMetaInDatabase([ 'post_id' => $id ]);\n }\n }\n );\n};\n\n// Listen for this event to register the posts to remove, along with their custom fields, after the test.\ntad\\WPBrowser\\addListener('test-event-1/setup-posts', $registerPostsCleanup);\n
In this simple test I'm adding 3 posts [using the factory provided by the WPLoader module in loadOnly mode][2] and want to make sure those, and the relative meta, are removed at the end of the tests. The WPDb module, extending the Db module from Codeception, will remove the inserted rows, but will not take care of modified rows, or rows not inserted by the WPDb module.
Mirroring the requirement of the clean up function I've defined above, I'm passing the post IDs of the posts I've created and the current tester to provide the clean up function with database handling capabilities.
<?php\n/** @var Codeception\\Scenario $scenario */\n$I = new AcceptanceTester($scenario);\n$I->wantTo('add posts and clean them up using the Events API');\n\n/*\n * Use WordPress methods, thanks to the `WPLoader` module, to use WordPress, or our own, API to insert posts.\n * This will prevent, but, `WPDb` from removing the inserted rows and clean up, so we remove the posts and meta\n * with an event and our custom clean-up function.\n */\n$ids = $I->factory()->post->create_many(3, [ 'post_type' => 'some_post_type' ]);\n\ntad\\WPBrowser\\dispatch('test-event-1/setup-posts', __FILE__, [\n 'ids' => $ids,\n 'db' => $I\n]);\n
The Codeception testing framework can be extended in a number of ways.
The one this project leverages the most are modules but [extensions are another way].
Modules extend the functionality of Codeception in the context of the tests, while extensions extend its interaction capacities; this is by no means a strict rule but that's usually the case.
The package contains two additional extensions to facilitate testers' life.
The tad\\WPBrowser\\Extension\\Symlinker extension provides an automation to have the Codeception root directory symbolically linked in a WordPress local installation.
Since version 3.9 WordPress supports this feature (with some precautions) and the extension takes charge of:
symbolically linking a plugin or theme folder in the specified destination before any suite boots up
unlinking that symbolic link after all of the suites did run
It's the equivalent of doing something like this from the command line (on a Mac):
mode - can be plugin or theme and indicates whether the current Codeception root folder being symlinked is a plugin or a theme one
destination - the absolute path to the WordPress local installation plugins or themes folder; to take the never ending variety of possible setups into account the extension will make no checks on the nature of the destination: could be any folder.
rootFolder - optional absolute path to the WordPress plugin or theme to be symlinked root folder; will default to the Codeception root folder
The tad\\WPBrowser\\Extension\\Copier extension provides an automation to have specific files and folders copied to specified destination files and folders before the suites run.
While WordPress handles symbolic linking pretty well there are some cases, like themes and drop-ins, where there is a need for \"real\" files to be put in place.
One of such cases is, currently, one where Docker is used to to host and serve the code under test: symbolically linked files cannot be bound inside a container and Docker containers will fail to start in this case.
The extension follows the standard Codeception extension activation and has one configuration parameter only:
The extension will handle absolute and relative paths for sources and destinations and will resolve relative paths from the project root folder.
When copying directories the extension will only create the destination folder and not the folder tree required; in the example configuration above the last entry specifies that a mu-plugin.php file should be copied to the mu-plugins folder: that mu-plugins folder must be there already.
Being able to symlink a plugin or theme folder into a WordPress installation for testing purposes could make sense when trying to test, as an example, a plugin in a single site and in multi site environment.
Codeception supports environments and the extension does as well specifying a destination for each.
As an example the acceptance.suite.yml file might be configured to support single and multisite environments:
In the codeception.yml file specifying a destination for each supported environment will tell the extension to symbolically link the plugin or theme file to different locations according to the current environment:
Due to some internal changes in Codeception 4.0, the internal API (really a collection of low-level hacks on my part) that allowed wp-browser to dispatch, and listen for, events in the modules has been removed.
If you want to leverage [the event system wp-browser provides] with Codeception default events (e.g. suite.init or test.before), then you will need to use this extension.
You will not need this extension if you're not using Codeception version 4.0.
You will need to enable it in your Codeception main configuration file (e.g. codeception.dist.yml).
The extension only configuration is the suites parameter that allows specifying the suites the extension should apply to. If the suites parameter is not specified, then the extension will apply to all suites.
"},{"location":"v3/faq/","title":"Faq","text":""},{"location":"v3/faq/#some-common-questions","title":"Some common questions","text":"
There are questions I keep receiving via email, GitHub or in person at conferences.
No, Codeception, and wp-browser by extension, will require PHP 5.6 minimum.
This does not mean your code cannot be PHP 5.2 compatible: you can test your code using all the possibilities of newer PHP versions and still keep it PHP 5.2 compatible.
Just because you can doesn't mean you should though: this documentation will assume a minimum PHP version, for the example and test code, of PHP 5.6.
"},{"location":"v3/faq/#can-i-run-unit-tests-with-wp-browsercodeception","title":"Can I run unit tests with wp-browser/Codeception?","text":"
Yes, with some distinctions.
In the WordPress ecosystem there's a tendency to call any kind of test a \"unit test\". Under that definition will fall tests that are not \"unit\" tests at all.
Without drowning into a long and painful battle for definitions this guide will use the following definitions for different levels of testing.
The next section will detail the conventions this documentation uses to define different levels of testing in more detail.
No; it's sometimes difficult to test and not as straightforward as other PHP frameworks but it's definitely not untestable.
You are writing code that runs on WordPress, not the Core code for WordPress so the question should really be: will you write testable code?
It's up to you to decide at what level you want to make your code testable and how much you want to test it.
"},{"location":"v3/faq/#do-i-need-to-use-a-specific-local-development-environment-to-use-wp-browser","title":"Do I need to use a specific local development environment to use wp-browser?","text":"
No. I've started using wp-browser on a vanilla PHP built-in server to, then, move to MAMP (or XAMP) and, from there, to other solutions.
I've configured and used wp-browser on Docker, Vagrant, VVV, Valet and various CI solutions.
To this day I keep using different setups on different machines and personally prefer Docker for its portability.
"},{"location":"v3/faq/#can-i-only-test-plugins-with-wp-browser","title":"Can I only test plugins with wp-browser?","text":"
No, you can test any kind of WordPress application.
With \"application\" I mean any PHP software built on top of WordPress: plugins, themes, whole sites.
"},{"location":"v3/faq/#if-im-testing-a-site-do-i-have-to-use-the-default-wordpress-file-structure","title":"If I'm testing a site do I have to use the default WordPress file structure?","text":"
No, you can use any file structure you want.
Some wp-browser modules will need a little help to find your code but, so far, I've never been unable to set it up.
"},{"location":"v3/faq/#can-i-use-wp-browser-even-if-my-wordpress-application-doesnt-use-composer","title":"Can I use wp-browser even if my WordPress application doesn't use Composer?","text":"
Yes, although wp-browser, as a development tool, cannot be installed without Composer.
"},{"location":"v3/faq/#should-i-use-wp-browser-to-test-my-production-servers","title":"Should I use wp-browser to test my production servers?","text":"
No. Unless you know very well what you're doing that's a dangerous idea that might leave you with a broken site and an empty database.
As almost any testing tool, wp-browser should be used locally on local installations of WordPress that do not contain any valuable information.
"},{"location":"v3/faq/#how-can-i-avoid-the-wpdb-module-from-replacing-the-contents-of-my-database","title":"How can I avoid the WPDb module from replacing the contents of my database?","text":"
You should always backup any database that contains any information you care about before running any test.
You can read the answer to this question in the WPDb module documentation.
"},{"location":"v3/faq/#can-i-run-all-my-tests-with-one-command","title":"Can I run all my tests with one command?","text":"
Theoretically: yes, in practice: no.
When you use codecept run Codeception will run all the tests from all the suites.
This, done in the context of other frameworks, will generally not create any problem but, in the context of WordPress it will.
While handling a single HTTP request WordPress will set, and use, a number of constants and globals and, likewise, will do plugins and themes that follow WordPress standards.
This means that the global context (variable scope) will be left \"dirty\" and contain \"left-over\" constants and globals from the previous tests.
An example is one where a test for the handling of Ajax requests sets the DOING_AJAX constant: this will be now set for any test after the one that set it thus breaking, or worse altering, all the following ones.
So, in short, run each suite separately.
"},{"location":"v3/faq/#can-i-have-more-than-one-suite-of-one-kind","title":"Can I have more than one suite of one kind?","text":"
Yes, you should.
As an example you might have a frontend suite running acceptance tests on the site frontend and a backend suite running acceptance tests on the site backend.
Think of suites as a tool to organize your tests: there's a good measure between too organized and not organized at all.
"},{"location":"v3/faq/#ive-used-phpunit-before-for-my-unit-tests-can-i-reuse-that-knowledge-and-code-with-wp-browser","title":"I've used PHPUnit before for my unit tests, can I reuse that knowledge and code with wp-browser?","text":"
Yes.
Codeception uses PHPUnit as one of its main components and can run PHPUnit tests with little or no modification.
As such you can just move your existing PHPUnit tests in a dedicated suite and be ready to run in minutes.
"},{"location":"v3/faq/#ive-already-set-up-my-tests-to-run-using-the-core-phpunit-based-test-suite-can-i-keep-using-my-tests","title":"I've already set up my tests to run using the Core PHPUnit-based test suite, can I keep using my tests?","text":"
Yes.
Codeception uses PHPUnit as one of its main components and can run PHPUnit tests with little or no modification.
One of the goals of wp-browser was to make it easier to test WordPress application at an integration level (or \"WordPress unit\" level).
As such migrating those tests could be a matter of minutes requiring no modification to the tests if not for moving some files and creating a dedicated suite.
"},{"location":"v3/faq/#why-is-the-project-called-wp-browser","title":"Why is the project called wp-browser?","text":"
When I started working with Codeception to run my acceptance tests I kept creating steps that I would reuse over and over in my projects.
I packed them in a module extending the PHPBrowser module.
Being a natural talent in naming things I've called the module WPBrowser and published it. As I started relying on Codeception more and more I kept adding modules but the name remained.
"},{"location":"v3/installation/","title":"Installation","text":""},{"location":"v3/installation/#installation","title":"Installation","text":""},{"location":"v3/installation/#where-should-i-install-wp-browser","title":"Where should I install wp-browser?","text":"
As a rule-of-thumb wp-browser should be installed in the root folder of your project.
If your project is a plugin then it should be installed in the root folder of your plugin; if your project is a theme it should be installed in the root folder of your theme.
If your project is a site I'd, personally install it in the site root folder.
The purpose of installing wp-browser in the root folder of a project is to keep the code and its tests under version control together.
Exceptions apply but, for most projects, that's what I would do.
"},{"location":"v3/installation/#initializing-the-composer-project","title":"Initializing the Composer project","text":"
Since Composer is a requirement of wp-browser and the only way to install it you should, first thing, initialize the Composer project.
If you've already initialized the Composer project you can skip this section.
Once you've decided where to install wp-browser navigate to that folder using the terminal and type:
composer init\n
Composer will take you through a number of questions to setup some meta information about your project.
Do not install any dependency yet when asked (unless you know what you're doing) and, as a suggestion, set wordpress-plugin as \"Package Type\".
Also, since WordPress is licensed under the GPL-2.0+ you might want to set the \"License\" of your project to GPL-2.0-or-later.
"},{"location":"v3/installation/#installing-wp-browser-as-a-development-dependency","title":"Installing wp-browser as a development dependency","text":"
Once you've initialized the Composer project it's time to require wp-browser ; you can read more about the usage of the require command on the Composer documentation.
wp-browser is a testing tool and, as such, should be installed as a project development dependency, not as a normal (production) one.
From the terminal type:
composer require --dev lucatume/wp-browser\n
This will install the latest stable version of wp-browser and, along with it, Codeception and PHPUnit in the vendor folder of your project.
Once that's done it's time to move to the setup and configuration of wp-browser.
"},{"location":"v3/levels-of-testing/","title":"Levels of testing","text":""},{"location":"v3/levels-of-testing/#what-is-a-unit-test-an-acceptance-test","title":"What is a unit test? An acceptance test?","text":"
This page has no pretense to be THE source of truth about what is called how in the context of tests; the purpose of this page is to lay out the terminology that I'll use in the documentation to define the levels and component of testing. Wikipedia, forums and other documents online will offer alternate, and equally valid, definitions.
The user might be tech-savvy as much as I want her to be but still make assertions only on what feedback the site provides.
The code below tests a user can subscribe to the mailing list:
<?php\n// UserSuccessfulSignupTest.php\n\n// Add a page that contains the shortcode that will render the signup form.\n$I->havePageInDatabase( [\n 'post_name' => 'signup',\n 'post_content'=> 'Sign-up for our awesome thing! [signup]',\n] );\n\n// Go to the page.\n$I->amOnPage( '/signup' );\n\n// Submit the form as a user would submit it. \n$I->submitForm( '#signup-form', [\n 'name' => 'Luca',\n 'email' => 'luca@theAverageDev.com',\n] );\n\n// Make sure I see a confirmation message. \n$I->waitForElement( '#signup-confirmation' );\n
The test code below asserts front-end submissions are correctly processed from the developer perspective:
<?php\n// file tests/functional/SignupSubmissionCest.php\n\nclass SignupSubmissionCest {\n\n public function _before( FunctionalTester $I ) {\n // Add a page that contains the shortcode that will render the signup form.\n $I->havePageInDatabase( [\n 'post_name' => 'signup',\n 'post_content'=> 'Sign-up for our awesome thing! [signup]',\n ] );\n\n $I->amOnPage( '/signup' );\n }\n\n public function test_good_signup( FunctionalTester $I ) {\n $I->sendAjaxPostRequest( '/wp-json/acme/v1/signup', [\n '_wpnonce' => $I->grabAttributeFrom( '#signup-nonce', 'value' ),\n 'name' => 'Luca',\n 'email' => 'luca@theAverageDev.com',\n ] );\n\n $I->seeResponseCodeIsSuccessful();\n $I->seeUserInDatabase( [ 'user_login' => 'luca', 'user_email' => 'luca@theaveragedev.com' ] );\n }\n\n public function test_bad_email_signup( FunctionalTester $I ) {\n $I->sendAjaxPostRequest( '/wp-json/acme/v1/signup', [\n '_wpnonce' => $I->grabAttributeFrom( '#signup-nonce', 'value' ),\n 'name' => 'Luca',\n 'email' => 'not-really-an-email',\n ] );\n\n $I->seeResponseCodeIs( 400 );\n $I->dontSeeUserInDatabase( [ 'user_login' => 'luca', 'user_email' => 'not-really-an-email' ] );\n }\n}\n
The code looks, initially, like an acceptance test, but differs in its action and assertion phase: in place of filling a form and clicking \"Submit\" it sends a POST request to a REST API endpoint and checks the effect of the submission in the database.
All of these actions fall squarely into what a developer would do, not into what a user could/should be able to do.
Furthermore, the format of the test is not the same as the one used in the acceptance test.
The acceptance test is written in the most eloquent testing format supported by Codeception, the Cept format, this test uses a more PHPUnit-like format, the Cest format.
While the first is easier to skim for non-developers the second harnesses the power of a re-using pieces of code, the page creation and navigation in the example, to optimize the test code.
In brief: test code modules in the context of a WordPress website.
In this type of test the WordPress, and additional plugins code, is loaded in the same variable scope as the tests; this is why in the example below I'm using classes (WP_REST_Request, WP_REST_Response) and methods (register_rest_route) defined by WordPress, not the plugin code.
The REST API request sent by the application form will be handled by a class, Acme\\Signup\\SubmissionHandler, that's been attached to the /wp-json/acme/v1/signup path:
The test format used is the familiar PhpUnit one; the only difference is the base test class that's being extended (\\Codeception\\TestCase\\WPTestCase) is one provided by wp-browser.
In the context of WordPress \"integration\" might also mean testing that filters used by the code have the expected effect.
In brief: test single classes or functions that require WordPress code in as much isolation as possible.
This is what most people referring to \"unit tests\" in the context of WordPress is talking about.
The purpose of this kind of tests is to test one class of a WordPress application, or one function, that requires a WordPress-defined function or class with a unit testing approach.
In the example below I'm testing the Acme\\Signup\\SubmissionHandler class on a \"unit\" level making sure it will mark a request as bad if the email is not a valid one.
<?php\n// file tests/unit/SubmissionHandlerTest.php\nclass SubmissionHandlerTest extends Codeception\\Test\\Test {\n protected $request;\n protected $validator;\n\n public function setUp() {\n // Mock the request.\n $this->request = $this->prophesize( WP_REST_Request::class );\n // Spy on the validator.\n $this->validator = $this->prophesize( Acme\\Signup\\EmailValidator::class );\n }\n\n public function test_email_is_validated_by_default() {\n $this->request->get_param( 'name' )->willReturn( 'luca' );\n $this->request->get_param( 'email' )->willReturn( 'luca@theaveragedev.com' );\n\n $handler = new Acme\\Signup\\SubmissionHandler( $this->validator->reveal() );\n $handler->set_validator( $this->validator );\n $response = $handler->handle( $this->request->reveal() );\n\n $this->assertInstanceOf( WP_REST_Response::class, $response );\n // Verify on the validator spy.\n $this->validator->validate( 'luca@theaveragedev.com' )->shouldHaveBeenCalled();\n }\n\n public function test_will_not_validate_email_if_missing() {\n $this->request->get_param( 'name' )->willReturn( 'luca' );\n $this->request->get_param( 'email' )->willReturn( '' );\n\n $handler = new Acme\\Signup\\SubmissionHandler( $this->validator->reveal() );\n $handler->set_validator( $this->validator );\n $response = $handler->handle( $this->request->reveal() );\n\n $this->assertInstanceOf( WP_REST_Response::class, $response );\n // Verify on the validator spy.\n $this->validator->validate( Argument::any() )->shouldNotHaveBeenCalled();\n }\n}\n
The class uses the WP_REST_Request and WP_Rest_Response classes as input and output and will probably, internally, use more functions defined by WordPress.
One solution to avoid loading WordPress, could be to rewrite test versions of each and all the WordPress functions and classes needed by all the classes I want to unit test; this would require updating each time the classes requirements change.
Furthermore internationalization (e.g. __()) and filtering (e.g apply_filters) functions would not need to be mocked if not in specific cases and would pretty much be copy and paste versions of the WordPres ones.
Loading single pieces of WordPress is a dangerous and brittle endeavour and it's not supported by the framework.
To avoid all this WordPress \"unit tests\" pay the price of having to bootstrap WordPress, thus requiring a database connection.
This kind of test setup and level is the one you can see in the PHPUnit Core suite of WordPress itself.
wp-browser will not download, install and configure WordPress for you.
It will also not download, install and setup MySQL, Apache, Nginx or any other technology required by a fully functional WordPress installation for you.
You need to set up a local WordPress installation on your own; you can use your preferred solution to do it.
In the documentation I will show automated ways to do this but, for most projects, that's not the best solution.
"},{"location":"v3/setting-up-minimum-wordpress-installation/","title":"Setting up minimum wordpress installation","text":""},{"location":"v3/setting-up-minimum-wordpress-installation/#setting-up-a-minimum-wordpress-installation","title":"Setting up a minimum WordPress installation","text":"
As mentioned in Installation section wp-browser will not download, configure and install WordPress for you.
On a high level, once WordPress is installed and configured, whatever local development environment solution you've used, there are some information you'll need to gather before moving into wp-browser configuration.
While there will be a section dedicated to different environments and setups I will outline below the example setup I will use, in the next section, to configure wp-browser:
WordPress is installed, on my machine, at /Users/luca/Sites/wordpress.
I'm running MySQL server locally; I can connect to the MySQL server with the command mysql -u root -h 127.0.0.1 -P 3306; there is no password.
I've created two databases, wordpress and tests, with the command: bash mysql -u root -h 127.0.0.1 -P 3306 -e \"create database if not exists wordpress; create database if not exists tests\"
require_once ABSPATH . 'wp-settings.php'; * To serve the site I'm using PHP built-in server with the command:bash (cd /Users/luca/Sites/wordpress; php -S localhost:8080) `` * I can access the WordPress homepage athttp://localhost:8080and the administration area athttp://localhost:8080/wp-admin. * I've installed WordPress via its UI (http://localhost:8080/wp-admin), the administrator username isadmin, the administrator password ispassword. * I'm testing a plugin and that plugin is in the folder, relative to the WordPress root folder,wp-content/plugins/acme-plugin`.
With all the steps above done I can now move into the actual wp-browser configuration phase.
I maintain the wp-browser project while working full-time as a freelance and dedicating my spare time to it. I do it with passion and for \"love of the craft,\" but it can become a chore at times.
Appreciation, the most common form of support, goes a long way but does not pay the bills. I want to dedicate more structured time to the project, and that would mean turning down some freelance work offers. To that end, I've applied for GitHub sponsorship system.
My sincere thanks to my sponsors: you make the above easier.
@BenBornschein
@Borlabs
@TimothyBJacobs
@bordoni
@borkweb
@dingo-d
@francescamarano
@jerclarke
@johnbillion
@joppuyo
@kkarpieszuk
@pods-framework
@roborourke
@wp-staging
@zackkatz
"},{"location":"v3/advanced/run-in-separate-process/","title":"Run in separate process","text":""},{"location":"v3/advanced/run-in-separate-process/#running-tests-in-separate-processes","title":"Running tests in separate processes","text":"
PHPUnit offers the possibility to run tests in a separate PHP process; Codeception does not officially support the option as of version 4.0.
The wp-browser project tries to fill that gap by supporting the @runInSeparateProcess annotation. This support comes with some caveats, though:
The support is only for test cases extending the Codeception\\TestCase\\WPTestCase class (the base test case for integration or \"WordPress unit\" tests)
The support wp-browser provides only supports the @preserveGlobalState annotation with the disabled value; this means there is no support for preserving global state between tests.
Read more about what this means in PHPUnit documentation.
"},{"location":"v3/advanced/run-in-separate-process/#why-run-tests-in-a-separate-php-process","title":"Why run tests in a separate PHP process?","text":"
One main reason: isolation.
What does \"isolation\" means?
Before answering that question, it's essential to understand, via an example, why a lack of isolation might be an issue.
I want to test the get_api function. The function will return the correct singleton instance of an API handling class: an instance of Api when the function is called in non-admin context, and an instance of AdminApi when the function is called in admin context. The get_api function is acting as a service locator.
There are two challenges to testing this function:
The is_admin function, defined by WordPress, looks up a WP_ADMIN constant to know if the context of the current request is an administration UI one or not.
The get_api function will check for the context and resolve and build the correct instance only once, the first time it's called in the context of a request.
There are some possible solutions to this problem:
a. Refactor the get_api function into a method of an Api_Factory object taking the context as a dependency, thus allowing injection of the \"context\" (which implies the creation of a Context adapter that will proxy its is_admin method to the is_admin function). You can find the code for such refactoring in the OOP refactoring of get_api section. b. Refactor the get_api function to accept the current is_admin value as an input argument, get_api( $is_admin ), this refactoring moves part of the complexity of getting hold of the correct instance of the API handler on the client code. Adding more build condition and checks, e.g., if the current request is a REST request or not or some tests on the user authorizations, then, requires adding more input arguments to the get_api function: the knowledge of the implementation of the get_api method will \"leak\" to the client code having to replicate complexity throughout the system.
I want to layout possible solutions to the problem to show there is always a design alternative to make code testable that might or might not fit the current time or scope constraint.
In this example, I've inherited the get_api function from the existing code, and it cannot be changed, yet I want to test it dealing with the two problems outlined above.
"},{"location":"v3/advanced/run-in-separate-process/#running-tests-in-separate-php-processes","title":"Running tests in separate PHP processes","text":"
To test the get_api function shown above I've created a new wpunit type of test:
The command scaffolds a test/integration/apiTest.php file that I've modified to ensure full coverage of the get_api function:
<?php\n\nclass apiTest extends \\Codeception\\TestCase\\WPTestCase\n{\n public function test_get_api_exists()\n {\n $this->assertTrue(function_exists('get_api'));\n }\n\n public function test_get_api_will_cache()\n {\n $this->assertSame(get_api(), get_api());\n }\n\n /**\n * @runInSeparateProcess\n * @preserveGlobalState disabled\n */\n public function test_get_api_will_return_api_if_not_admin()\n {\n // Let's make sure we're NOT in admin context.\n define('WP_ADMIN', false);\n\n $api = get_api();\n\n $this->assertInstanceOf(Api::class, $api);\n }\n\n /**\n * @runInSeparateProcess\n * @preserveGlobalState disabled\n */\n public function test_get_api_will_cache_api_if_not_admin()\n {\n // Let's make sure we're NOT in admin context.\n define('WP_ADMIN', false);\n\n $api = get_api();\n\n $this->assertSame(get_api(), $api);\n }\n\n /**\n * @runInSeparateProcess\n * @preserveGlobalState disabled\n */\n public function test_get_api_will_return_api_if_is_admin()\n {\n // Let's make sure we're NOT in admin context.\n define('WP_ADMIN', true);\n\n $api = get_api();\n\n $this->assertInstanceOf(AdminApi::class, $api);\n }\n\n /**\n * @runInSeparateProcess\n * @preserveGlobalState disabled\n */\n public function test_get_api_will_cache_api_if_is_admin()\n {\n // Let's make sure we're NOT in admin context.\n define('WP_ADMIN', true);\n\n $api = get_api();\n\n $this->assertSame(get_api(), $api);\n }\n}\n
Some pieces of this code are worth pointing out:
There are two test methods, test_get_api_exists and test_get_api_will_cache that are not running in a separate process. Running tests in a separate process provide isolation at the cost of speed, only tests that require isolation should run in a separate PHP process.
I instruct the Codeception and PHPUnit test runner to run a test method in a different process by adding two annotations that are both required precisely as shown: ```php /**
@runInSeparateProcess
@preserveGlobalState disabled */ ```
The isolation part of this testing approach shines through when I define, in the last four tests, the WP_ADMIN constant multiple times. If I try to do that in test code running in the same PHP process, then the second define call would cause a fatal error.
The isolation has also taken care of the second issue where the get_api function caches the $api instance after its first resolution in a static variable: since each test happens in a self-contained, dedicated PHP process, the static $api variable will be null at the start of each test.
"},{"location":"v3/advanced/run-in-separate-process/#can-i-run-some-tests-in-the-same-process-and-some-in-a-separate-process","title":"Can I run some tests in the same process and some in a separate process?","text":"
Yes. In the example test code in the previous section, the test_get_api_exists and test_get_api_will_cache test methods are not running in separate processes.
In your test cases extending the Codeception\\TestCase\\WPTestCase, you can mix test methods running in the primary PHP process and those running in a separate PHP process without issues.
"},{"location":"v3/advanced/run-in-separate-process/#oop-refactoring-of-get_api","title":"OOP refactoring of get_api","text":"
In the Why run tests in a separate PHP process? section I've outlined a possible refactoring of the get_api function to make it testable without requiring the use of separate PHP processes.
I'm providing this refactoring code below for the sake of completeness, the judgment of which approach is \"better\" is up to the reader.
<?php\n\nclass Context_Adapter{\n\n public function is_admin(){\n return \\is_admin();\n }\n\n}\n\nclass Api_Factory{\n\n private $api;\n private $context;\n\n public function __construct(Context_Adapter $context){\n $this->context = $context;\n }\n\n public function getApi(){\n if(null !== $this->api){\n return $this->api; \n }\n\n if($this->context->is_admin()){\n $api = new Admin_Api;\n } else {\n $api = new Api;\n }\n\n return $api;\n }\n}\n
Now the Api_Factory class can be injected by injecting a mocked Context_Adapter class, modifying the return value of the Context_Adapter::is_admin method.
Due to the supposed requirement of the API instance being a singleton, this solution will also require some container or service-locator to ensure at most only one instance of the Api_Factory exists at any given time in the context of a request.
"},{"location":"v3/migration/from-version-2-to-version-3/","title":"From version 2 to version 3","text":""},{"location":"v3/migration/from-version-2-to-version-3/#migrating-projects-from-version-2-of-wp-browser-to-version-3","title":"Migrating projects from version 2 of wp-browser to version 3","text":"
Version 3 of wp-browser removed, to allow for broader compatibility with PHP and Composer versions, some of its dependencies and modified some of its methods. Here is a list of changes and the suggested courses of action:
Removed symfony/process to launch and manage external processes; re-add it your project development requirements using composer require --dev symfony/process.
Removed the wp-cli/wp-cli-bundle dependency; if you were relying on non-core packages, then re-add it to your project development requirements using composer require --dev wp-cli/wp-cli-bundle.
Removed the WithWpCli::executeBackgroundWpCliCommand trait method, and, as a consequence, the WPCLI::executeBackgroundWpCliCommand module method; you could have used the latter, if this was the case, then require the symfony/process as explained above and launch processes in background using its API; find out more.
Refactored the WPCLI module to build and escape string command lines differently; the handling of command-line arguments for the WPCLI module has been modified to make it a bit more consistent and robust; as a consequence, you might experience some breakages in string commands that used to work correctly before; should this be the case then either modify your code to provide the command in array format (taking care of the correct escaping in your code), or make sure to pass a correctly structured command string to the WPCLI module.
This module should be used in acceptance and functional tests, see levels of testing for more information.
This module extends the PHPBrowser module adding WordPress-specific configuration parameters and methods.
The module simulates a user interaction with the site without Javascript support; if you need to test your project with Javascript support use the WPWebDriver module.
"},{"location":"v3/modules/WPBrowser/#module-requirements-for-codeception-40","title":"Module requirements for Codeception 4.0+","text":"
This module requires the codeception/module-phpbrowser Composer package to work when wp-browser is used with Codeception 4.0.
Since this module extends the PHPBrowser module provided by Codeception, please refer to the PHPBrowser configuration section for more information about the base configuration parameters.
url required - Start URL of your WordPress project, e.g. http://wp.test.
headers - Default headers are set before each test; this might be useful to simulate a specific user agent during the tests or to identify the request source. Note that the headers defined in the config should be prefaced with HTTP_ in your wp-config.php file. This can be used to select which database to use.
handler (default: curl) - The Guzzle handler to use. By default curl is used, also possible to pass stream, or any valid class name as Handler.
middleware - The Guzzle middlewares to add. An array of valid callables is required; see here for more information.
curl - curl options; only applied if using the curl handler; more options are available.
adminUsername required - This is the login name, not the \"nice\" name, of the administrator user of the WordPress test site. This will be used to fill the username field in WordPress login page.
adminPassword required - This is the the password of the administrator use of the WordPress test site. This will be used to fill the password in WordPress login page.
adminPath required - The path, relative to the WordPress test site home URL, to the administration area, usually /wp-admin.
In the plugin administration screen activates a plugin clicking the \"Activate\" link. The method will not handle authentication to the admin area.
// Activate a plugin.\n $I->loginAsAdmin();\n $I->amOnPluginsPage();\n $I->activatePlugin('hello-dolly');\n // Activate a list of plugins.\n $I->loginAsAdmin();\n $I->amOnPluginsPage();\n $I->activatePlugin(['hello-dolly','another-plugin']);\n
Parameters
string/\\Codeception\\Module\\array $pluginSlug - The plugin slug, like \"hello-dolly\" or a list of plugin slugs. amEditingPostWithId
Go to the admin page to edit the post with the specified ID. The method will not handle authentication the admin area.
Go to the admin-ajax.php page to start a synchronous, and blocking, GET AJAX request. The method will not handle authentication, nonces or authorization.
In the plugin administration screen deactivate a plugin clicking the \"Deactivate\" link. The method will not handle authentication and navigation to the plugins administration page.
// Deactivate one plugin.\n $I->loginAsAdmin();\n $I->amOnPluginsPage();\n $I->deactivatePlugin('hello-dolly');\n // Deactivate a list of plugins.\n $I->loginAsAdmin();\n $I->amOnPluginsPage();\n $I->deactivatePlugin(['hello-dolly', 'my-plugin']);\n
Parameters
string/\\Codeception\\Module\\array $pluginSlug - The plugin slug, like \"hello-dolly\", or a list of plugin slugs. dontSeePluginInstalled
Assert a plugin is not installed in the plugins administration screen. The method will not handle authentication and navigation to the plugin administration screen.
string $cookiePattern - The regular expression pattern to use for the matching.
grabWordPressTestCookie
Returns WordPress default test cookie object if present.
// Grab the default WordPress test cookie.\n $wpTestCookie = $I->grabWordPressTestCookie();\n // Grab a customized version of the test cookie.\n $myTestCookie = $I->grabWordPressTestCookie('my_test_cookie');\n
Parameters
string $name - Optional, overrides the default cookie name.
logOut
Navigate to the default WordPress logout page and click the logout link.
// Log out using the `wp-login.php` form and return to the current page.\n $I->logOut(true);\n // Log out using the `wp-login.php` form and remain there.\n $I->logOut(false);\n // Log out using the `wp-login.php` form and move to another page.\n $I->logOut('/some-other-page');\n
Parameters
bool/bool/string $redirectTo - Whether to redirect to another (optionally specified) page after the logout.
loginAs
Login as the specified user. The method will not follow redirection, after the login, to any page.
string $password - The user password in plain text.
loginAsAdmin
Login as the administrator user using the credentials specified in the module configuration. The method will not follow redirection, after the login, to any page.
In an administration screen look for an error admin notice. The check is class-based to decouple from internationalization. The method will not handle authentication and navigation the administration area. .notice.notice-error ones.
string/string/\\Codeception\\Module\\array $classes - A list of classes the notice should have other than the seeMessage
In an administration screen look for an admin notice. The check is class-based to decouple from internationalization. The method will not handle authentication and navigation the administration area.
string/\\Codeception\\Module\\array/string $classes - A list of classes the message should have in addition to the .notice one. seePluginActivated
Assert a plugin is activated in the plugin administration screen. The method will not handle authentication and navigation to the plugin administration screen.
string $pluginSlug - The plugin slug, like \"hello-dolly\".
seePluginDeactivated
Assert a plugin is not activated in the plugins administration screen. The method will not handle authentication and navigation to the plugin administration screen.
string $pluginSlug - The plugin slug, like \"hello-dolly\".
seePluginInstalled
Assert a plugin is installed, no matter its activation status, in the plugin administration screen. The method will not handle authentication and navigation to the plugin administration screen.
string $pluginSlug - The plugin slug, like \"hello-dolly\".
seeWpDiePage
Checks that the current page is one generated by the wp_die function. The method will try to identify the page based on the default WordPress die page HTML attributes.
This class extends \\Codeception\\Module\\PhpBrowser
This class implements \\Codeception\\Lib\\Interfaces\\MultiSession, \\Codeception\\Lib\\Interfaces\\Remote, \\Codeception\\Lib\\Interfaces\\Web, \\Codeception\\Lib\\Interfaces\\PageSourceSaver, \\Codeception\\Lib\\Interfaces\\ElementLocator, \\Codeception\\Lib\\Interfaces\\ConflictsWithModule
This module should be used in acceptance and functional tests to setup, or verify, tests pre and post conditions using WP-CLI commands. This module allows invoking WP-CLI commands, refer to the official site for more information.
The module will use its own version of WP-CLI, not the one installed in the machine running the tests!
By default, wp-browser will only include the wp-cli/wp-cli package; this package contains the basic files to run WP-CLI and does not contain all the commands that come with a typical wp-cli installation. If, in your tests, you require all the commands that usually come installed with WP-CLI, then you should require the wp-cli/wp-cli-bundle package as a development dependency of your project, see below.
"},{"location":"v3/modules/WPCLI/#fixing-not-a-registered-command-issue","title":"Fixing \"not a registered command\" issue","text":"
To keep the conflicts at a manageable level, the wp-browser project does not include all the commands WP-CLI usually comes bundled with. Running, in the context of an automated test, a WP-CLI command that would work on your machine, e.g. wp plugin list --status=active, will not work on a default installation of wp-browser and you will get the following error message:
[ModuleException] WPCLI: wp-cli terminated with status [1] and output [Error: 'plugin' is not a registered wp command. See 'wp help' for available commands.]\n
To resolve the message just add the package you require as a development dependency or add the whole WP-CLI bundle:
composer require --dev wp-cli/wp-cli-bundle\n
The package will make all the default WP-CLI commands available to the WP-CLI version used in tests.
"},{"location":"v3/modules/WPCLI/#module-requirements-for-codeception-40","title":"Module requirements for Codeception 4.0+","text":"
This module requires the codeception/module-cli Composer package to work when wp-browser is used with Codeception 4.0.
"},{"location":"v3/modules/WPCLI/#detecting-requests-coming-from-this-module","title":"Detecting requests coming from this module","text":"
When it runs this module will set the WPBROWSER_HOST_REQUEST environment variable. You can detect and use that information to, as an example, use the correct database in your test site wp-config.php file:
<?php\nif ( \n // Custom header.\n isset( $_SERVER['HTTP_X_TESTING'] )\n // Custom user agent.\n || ( isset( $_SERVER['HTTP_USER_AGENT'] ) && $_SERVER['HTTP_USER_AGENT'] === 'wp-browser' )\n // The env var set by the WPClIr or WordPress modules.\n || getenv( 'WPBROWSER_HOST_REQUEST' )\n) {\n // Use the test database if the request comes from a test.\n define( 'DB_NAME', 'wordpress_test' );\n} else {\n // Else use the default one.\n define( 'DB_NAME', 'wordpress' );\n}\n
path required - the absolute, or relative, path to the WordPress root folder. This will be mapped to the --path argument of the wp-cli binary.
throw - defaults to true to throw an exception when a wp-cli command does not return an exit status of 0; if set to false then the exit status of the commands will be returned as is.
timeout - defaults to 60 (seconds) to set each process execution timeout to a certain value; set to null, false or 0 to disable timeout completely.
Additionally the module configuration will forward any configuration parameter to wp-cli as a flag or option. In the example configuration below the allow-root flag and the some-option option will be passed to wp-cli directly and prepended to the command as global options.
Note: these extract configuration flags and options will be prepended to all commands executed by wp-cli!
The wp-cli binary supports a set of environment variables to modify its behavior.
These environment variables can be set on the commands ran by the WPCLI module using the optional env array in the module configuration. The example configuration below shows all of them with some example values. Most of the times you won't need any of these, but they are there for more fine-grained control over the module operations.
The module is not validating the environment variables in any way! Those values will be evaluated by wp-cli at runtime and might generate errors if not correctly configured.
modules:\n enabled:\n - WPCLI\n config:\n WPCLI:\n path: /Users/Luca/Sites/wp\n throw: true\n timeout: 60\n # This will be prepended to the command, `wp --allow-root <command>`.\n allow-root: true\n # This will be prepended to the command, `wp --some-option=some-value <command>`.\n some-option: some-value\n env:\n # Any one of these, if provided, will be set as environment variable for the the cli command process. \n # See https://make.wordpress.org/cli/handbook/config/#environment-variables for information.\n # Equivalent to `WP_CLI_STRICT_ARGS_MODE=1 wp <command>'.\n strict-args: true\n # Equivalent to `WP_CLI_CACHE_DIR=/tmp/wp-cli-cache wp <command>'.\n cache-dir: '/tmp/wp-cli-cache'\n # Equivalent to `WP_CLI_CONFIG_PATH=/app/public wp <command>'.\n config-path: '/app/public'\n # Equivalent to `WP_CLI_CUSTOM_SHELL=/bin/zsh wp <command>'.\n custom-shell: '/bin/zsh'\n # Equivalent to `WP_CLI_DISABLE_AUTO_CHECK_UPDATE=1 wp <command>'.\n disable-auto-update: true\n # Equivalent to `WP_CLI_PACKAGES_DIR=/wp-cli/packages wp <command>'.\n packages-dir: '/wp-cli/packages'\n # Equivalent to `WP_CLI_PHP=/usr/local/bin/php/7.2/php wp <command>'.\n php: '/usr/local/bin/php/7.2/php'\n # Equivalent to `WP_CLI_PHP_ARGS='foo=bar some=23' wp <command>'.\n php-args: 'foo=bar some=23'\n
Builds the full command to run including the PHP binary and the wp-cli boot file path.
// This method is defined in the WithWpCli trait.\n // Set the wp-cli path, `$this` is a test case.\n $this->setUpWpCli( '/var/www/html' );\n // Builds the full wp-cli command, including the `path` variable.\n $fullCommand = $this->buildFullCommand(['core', 'version']);\n // The full command can then be used to run it with another process handler.\n $wpCliProcess = new Process($fullCommand);\n $wpCliProcess->run();\n
Parameters
\\Codeception\\Module\\array/string $command - The command to run. cli
Executes a wp-cli command targeting the test WordPress installation. minus wp. For back-compatibility purposes you can still pass the commandline as a string, but the array format is the preferred and supported method.
// Activate a plugin via wp-cli in the test WordPress site.\n $I->cli(['plugin', 'activate', 'my-plugin']);\n // Change a user password.\n $I->cli(['user', 'update', 'luca', '--user_pass=newpassword']);\n
Parameters
string/string/\\Codeception\\Module\\array $userCommand - The string of command and parameters as it would be passed to wp-cli cliToArray
Returns the output of a wp-cli command as an array optionally allowing a callback to process the output. minus wp. For back-compatibility purposes you can still pass the commandline as a string, but the array format is the preferred and supported method.
// Return a list of inactive themes, like ['twentyfourteen', 'twentyfifteen'].\n $inactiveThemes = $I->cliToArray(['theme', 'list', '--status=inactive', '--field=name']);\n // Get the list of installed plugins and only keep the ones starting with \"foo\".\n $fooPlugins = $I->cliToArray(['plugin', 'list', '--field=name'], function($output){\n return array_filter(explode(PHP_EOL, $output), function($name){\n return strpos(trim($name), 'foo') === 0;\n });\n });\n
Parameters
string/string/\\Codeception\\Module\\array $userCommand - The string of command and parameters as it would be passed to wp-cli
\\callable $splitCallback - An optional callback function to split the results array.
cliToString
Returns the output of a wp-cli command as a string. minus wp. For back-compatibility purposes you can still pass the commandline as a string, but the array format is the preferred and supported method.
// Return the current site administrator email, using string command format.\n $adminEmail = $I->cliToString('option get admin_email');\n // Get the list of active plugins in JSON format, two ways.\n $activePlugins = $I->cliToString(['plugin', 'list','--status=active', '--format=json']);\n $activePlugins = $I->cliToString(['option', 'get', 'active_plugins' ,'--format=json']);\n
Parameters
string/\\Codeception\\Module\\array $userCommand - The string of command and parameters as it would be passed to wp-cli dontSeeInShellOutput
Checks that output from last command doesn't contain text.
// Return the current site administrator email, using string command format.\n $I->cli('plugin list --status=active');\n $I->dontSeeInShellOutput('my-inactive/plugin.php');\n
Parameters
string $text - The text to assert is not in the output.
seeInShellOutput
Checks that output from last command contains text.
// Return the current site administrator email, using string command format.\n $I->cli('option get admin_email');\n
Parameters
string $text - The text to assert is in the output.
seeResultCodeIs
Checks the result code from the last command.
// Return the current site administrator email, using string command format.\n $I->cli('option get admin_email');\n $I->seeResultCodeIs(0);\n
Parameters
int $code - The desired result code.
seeResultCodeIsNot
Checks the result code from the last command.
// Return the current site administrator email, using string command format.\n $I->cli('invalid command');\n $I->seeResultCodeIsNot(0);\n
Parameters
int $code - The result code the command should not have exited with.
seeShellOutputMatches
Checks that output from the last command matches a given regular expression.
// Return the current site administrator email, using string command format.\n $I->cli('option get admin_email');\n
Parameters
string $regex - The regex pattern, including delimiters, to assert the output matches against.
This module should be used in acceptance and functional tests, see levels of testing for more information. This module extends the Db module adding WordPress-specific configuration parameters and methods. The module provides methods to read, write and update the WordPress database directly, without relying on WordPress methods, using WordPress functions or triggering WordPress filters.
"},{"location":"v3/modules/WPDb/#module-requirements-for-codeception-40","title":"Module requirements for Codeception 4.0+","text":"
This module requires the codeception/module-db Composer package to work when wp-browser is used with Codeception 4.0.
"},{"location":"v3/modules/WPDb/#backup-your-content","title":"Backup your content","text":"
This module, like the Codeception Db one it extends, by default will load a database dump in the database it's using. This means that the database contents will be replaced by the dump contents on each run of a suite using the module. You can set the populate and cleanup parameters to false to prevent this default behavior but it's usually not what you need in an automated test. Make a backup of any database you're using in tests that contains any information you care about before you run any test!
"},{"location":"v3/modules/WPDb/#change-the-database-used-depending-on-whether-your-running-tests-or-not","title":"Change the database used depending on whether you're running tests or not","text":"
The chore of having to plug different databases, or backup them, depending on whether you're manually testing the site or automatically testing can be mitigated switching them automatically depending on the browser user agent or request headers. This module was born to be used in acceptance and functional tests (see levels of testing for more information) and will often be coupled with modules like the WPBrowser one or the WPWebDriver one. Depending on which of the two modules is being used in the suite there are different ways to automate the \"database switching\".
"},{"location":"v3/modules/WPDb/#automatically-changing-database-based-on-the-browser-user-agent","title":"Automatically changing database based on the browser user agent","text":"
If you would like to automate the \"switching above\" below you will find an example setup. Update the test site wp-config.php file from this:
define( 'DB_NAME', 'wordpress' );\n
to this:
<?php\nif ( \n // Custom header.\n isset( $_SERVER['HTTP_X_TESTING'] )\n // Custom user agent.\n || ( isset( $_SERVER['HTTP_USER_AGENT'] ) && $_SERVER['HTTP_USER_AGENT'] === 'wp-browser' )\n // The env var set by the WPClIr or WordPress modules.\n || getenv( 'WPBROWSER_HOST_REQUEST' )\n) {\n // Use the test database if the request comes from a test.\n define( 'DB_NAME', 'wordpress_test' );\n} else {\n // Else use the default one.\n define( 'DB_NAME', 'wordpress' );\n}\n
If you're using the WPWebDriver module set the user agent in the browser, in this example I'm setting the user agent in Chromedriver:
class_name: AcceptanceTester\nmodules:\n enabled:\n - \\Helper\\Acceptance\n - WPDb\n - WPWebDriver\n config:\n WPDb:\n dsn: 'mysql:host=%WP_DB_HOST%;dbname=%WP_DB_NAME%'\n user: %WP_DB_USER%\n password: %WP_DB_PASSWORD%\n dump: tests/_data/dump.sql\n populate: true\n cleanup: false\n url: '%WP_URL%'\n tablePrefix: %WP_TABLE_PREFIX%\n urlReplacement: true\n WPWebDriver:\n url: '%WP_URL%'\n adminUsername: '%WP_ADMIN_USERNAME%'\n adminPassword: '%WP_ADMIN_PASSWORD%'\n adminPath: '%WP_ADMIN_PATH%'\n browser: chrome\n host: localhost\n port: 4444\n window_size: false\n wait: 5\n capabilities:\n # Used in more recent releases of Selenium.\n \"goog:chromeOptions\":\n args: [\"--no-sandbox\", \"--headless\", \"--disable-gpu\", \"--user-agent=wp-browser\"]\n # Support the old format for back-compatibility purposes. \n \"chromeOptions\":\n args: [\"--no-sandbox\", \"--headless\", \"--disable-gpu\", \"--user-agent=wp-browser\"]\n
If you're using the WPBrowser module send a specific header in the context of test requests:
dsn required - the database POD DSN connection details; read more on PHP PDO documentation. 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 this mysql:unix_socket=/path/to/the/mysql.sock;dbname=wordpress.
user required - the database user.
password required - the database password.
url required - the full URL, including the HTTP scheme, of the website whose database is being accessed. WordPress uses hard-codece URLs in the database, that URL will be set by this module when applying the SQL dump file during population or cleanup.
dump required - defaults to null; sets the path, relative to the project root folder, or absolute to the SQL dump file that will be used to set the tests initial database fixture. If set to null then the populate, cleanup and populator parameters will be ignored.
populate - defaults to true to empty the target database and import the SQL dump(s) specified in the dump argument before the test suite is started.
cleanup - defaults to true empty the target database and import the SQL dump(s) specified in the dump argument before each test.
urlReplacement - defaults to true to replace, while using the built-in, PHP-based, dump import solution the hard-coded WordPress URL in the database with the specified one.
originalUrl - specifies the original URL hard-coded into the version controlled SQL dump files. This can help prevent some URL replacement issues when the urlReplacement configuration parameter is set to true.
populator - defaults to null, if set to an executable shell command then that command will be used to populate the database in place of the built-in PHP solution; URL replacement will not apply in this case. Read more about this on Codeception documentation.
reconnect - defaults to true to force the module to reconnect to the database before each test in place of only connecting at the start of the tests.
waitlock - defaults to 10; wait lock (in seconds) that the database session should use for DDL statements.
tablePrefix - defaults to wp_; sets the prefix of the tables that the module will manipulate.
letAdminEmailVerification - defaults to an empty value to remove the Administrator Email Verification screen introduced in WordPress 5.3. Set to true to not remove the screen and show it when an administrator user first logs in.
letCron - defaults to an empty value to avoid wp-cron from being spawned during tests. Setting this to true will let wp-cron requests to fire during tests.
"},{"location":"v3/modules/WPDb/#using-the-module-with-the-wploader-one","title":"Using the module with the WPLoader one","text":"
This module is often used in conjunction with the WPLoader one to use WordPress-defined functions, classes and methods in acceptance or functional tests. The WPLoader module should be set to only load WordPress and this module should be listed, in the modules.enabled section of the suite configuration file before the WPLoader one:
Returns the number of table rows matching a criteria.
$I->haveManyPostsInDatabase(3, ['post_status' => 'draft' ]);\n $I->haveManyPostsInDatabase(3, ['post_status' => 'private' ]);\n // Make sure there are now the expected number of draft posts.\n $postsTable = $I->grabPostsTableName();\n $draftsCount = $I->countRowsInDatabase($postsTable, ['post_status' => 'draft']);\n
Parameters
string $table - The table to count the rows in.
array/\\Codeception\\Module\\array/array $criteria - Search criteria, if empty all table rows will be counted. dontHaveAttachmentFilesInDatabase
Removes all the files attached with an attachment post, it will not remove the database entries. Requires the WPFilesystem module to be loaded in the suite.
$posts = $I->grabPostsTableName();\n $attachmentIds = $I->grabColumnFromDatabase($posts, 'ID', ['post_type' => 'attachment']);\n // This will only remove the files, not the database entries.\n $I->dontHaveAttachmentFilesInDatabase($attachmentIds);\n
Parameters
\\Codeception\\Module\\array/int $attachmentIds - An attachment post ID or an array of attachment post IDs. dontHaveAttachmentInDatabase
Removes an attachment from the posts table. table. the suite.
$postmeta = $I->grabpostmetatablename();\n $thumbnailId = $I->grabFromDatabase($postmeta, 'meta_value', [\n 'post_id' => $id,\n 'meta_key'=>'thumbnail_id'\n ]);\n // Remove only the database entry (including postmeta) but not the files.\n $I->dontHaveAttachmentInDatabase($thumbnailId);\n // Remove the database entry (including postmeta) and the files.\n $I->dontHaveAttachmentInDatabase($thumbnailId, true, true);\n
Parameters
\\Codeception\\Module\\array/array $criteria - An array of search criteria to find the attachment post in the posts
bool $purgeMeta - If set to true then the meta for the attachment will be purged too.
bool $removeFiles - Remove all files too, requires the WPFilesystem module to be loaded in
dontHaveBlogInDatabase
Removes one ore more blogs from the database.
// Remove the blog, all its tables and files.\n $I->dontHaveBlogInDatabase(['path' => 'test/one']);\n // Remove the blog entry, not the tables though.\n $I->dontHaveBlogInDatabase(['blog_id' => $blogId]);\n // Remove multiple blogs.\n $I->dontHaveBlogInDatabase(['domain' => 'test']);\n
Parameters
\\Codeception\\Module\\array/array $criteria - An array of search criteria to find the blog rows in the blogs table.
bool $removeTables - Remove the blog tables.
bool $removeUploads - Remove the blog uploads; requires the WPFilesystem module.
\\Codeception\\Module\\array/array $criteria - An array of search criteria.
bool $purgeMeta - If set to true then the meta for the comment will be purged too.
dontHaveCommentMetaInDatabase
Removes a post comment meta from the database
// Remove all meta for the comment with an ID of 23.\n $I->dontHaveCommentMetaInDatabase(['comment_id' => 23]);\n // Remove the `count` comment meta for the comment with an ID of 23.\n $I->dontHaveCommentMetaInDatabase(['comment_id' => 23, 'meta_key' => 'count']);\n
Parameters
\\Codeception\\Module\\array/array $criteria - An array of search criteria. dontHaveInDatabase
\\Codeception\\Module\\array/array $criteria - An array of search criteria. dontHaveOptionInDatabase
Removes an entry from the options table.
// Remove the `foo` option.\n $I->dontHaveOptionInDatabase('foo');\n // Remove the 'bar' option only if it has the `baz` value.\n $I->dontHaveOptionInDatabase('bar', 'baz');\n
Parameters
string $key - The option name.
mixed/null $value - If set the option will only be removed if its value matches the passed one.
\\Codeception\\Module\\array/array $criteria - An array of search criteria. dontHavePostThumbnailInDatabase
Remove the thumbnail (featured image) from a post, if any. Please note: the method will NOT remove the attachment post, post meta and file.
$attachmentId = $I->haveAttachmentInDatabase(codecept_data_dir('some-image.png'));\n $postId = $I->havePostInDatabase();\n // Attach the thumbnail to the post.\n $I->havePostThumbnailInDatabase($postId, $attachmentId);\n // Remove the thumbnail from the post.\n $I->dontHavePostThumbnailInDatabase($postId);\n
Parameters
int $postId - The post ID to remove the thumbnail (featured image) from.
dontHaveSiteOptionInDatabase
Removes a site option from the database.
// Remove the `foo_count` option.\n $I->dontHaveSiteOptionInDatabase('foo_count');\n // Remove the `foo_count` option only if its value is `23`.\n $I->dontHaveSiteOptionInDatabase('foo_count', 23);\n
Parameters
string $key - The option name.
mixed/null $value - If set the option will only be removed it its value matches the specified one.
\\Codeception\\Module\\array/array $criteria - An array of search criteria.
bool $purgeMeta - Whether the terms meta should be purged along side with the meta or not.
dontHaveTermMetaInDatabase
Removes a term meta from the database.
// Remove the \"karma\" key.\n $I->dontHaveTermMetaInDatabase(['term_id' => $termId, 'meta_key' => 'karma']);\n // Remove all meta for the term.\n $I->dontHaveTermMetaInDatabase(['term_id' => $termId]);\n
Parameters
\\Codeception\\Module\\array/array $criteria - An array of search criteria. dontHaveTermRelationshipInDatabase
Removes an entry from the term_relationships table.
// Remove the relation between a post and a category.\n $I->dontHaveTermRelationshipInDatabase(['object_id' => $postId, 'term_taxonomy_id' => $ttaxId]);\n // Remove all terms for a post.\n $I->dontHaveTermMetaInDatabase(['object_id' => $postId]);\n
Parameters
\\Codeception\\Module\\array/array $criteria - An array of search criteria. dontHaveTermTaxonomyInDatabase
Removes an entry from the term_taxonomy table.
// Remove a specific term from the genre taxonomy.\n $I->dontHaveTermTaxonomyInDatabase(['term_id' => $postId, 'taxonomy' => 'genre']);\n // Remove all terms for a taxonomy.\n $I->dontHaveTermTaxonomyInDatabase(['taxonomy' => 'genre']);\n
Parameters
\\Codeception\\Module\\array/array $criteria - An array of search criteria. dontHaveTransientInDatabase
Removes a transient from the database.
// Removes the `tweets` transient from the database, if set.\n $I->dontHaveTransientInDatabase('tweets');\n
Parameters
string $transient - The name of the transient to delete.
dontHaveUserInDatabase
Removes a user from the database.
$bob = $I->haveUserInDatabase('bob');\n $alice = $I->haveUserInDatabase('alice');\n // Remove Bob's user and meta.\n $I->dontHaveUserInDatabase('bob');\n // Remove Alice's user but not meta.\n $I->dontHaveUserInDatabase($alice);\n
Parameters
int/string $userIdOrLogin - The user ID or login name.
bool $purgeMeta - Whether the user meta should be purged alongside the user or not.
dontHaveUserInDatabaseWithEmail
Removes a user(s) from the database using the user email address.
string $userEmail - The email of the user to remove.
bool $purgeMeta - Whether the user meta should be purged alongside the user or not.
dontHaveUserMetaInDatabase
Removes an entry from the usermeta table.
// Remove the `karma` user meta for a user.\n $I->dontHaveUserMetaInDatabase(['user_id' => 23, 'meta_key' => 'karma']);\n // Remove all the user meta for a user.\n $I->dontHaveUserMetaInDatabase(['user_id' => 23]);\n
Parameters
\\Codeception\\Module\\array/array $criteria - An array of search criteria. dontSeeAttachmentInDatabase
\\Codeception\\Module\\array/array $criteria - An array of search criteria. dontSeeCommentInDatabase
Checks that a comment is not in the database. Will look up the \"comments\" table.
// Checks for one comment.\n $I->dontSeeCommentInDatabase(['comment_ID' => 23]);\n // Checks for comments from a user.\n $I->dontSeeCommentInDatabase(['user_id' => 89]);\n
Parameters
\\Codeception\\Module\\array/array $criteria - The search criteria. dontSeeCommentMetaInDatabase
Checks that a comment meta value is not in the database. Will look up the \"commentmeta\" table.
// Delete a comment `karma` meta.\n $I->dontSeeCommentMetaInDatabase(['comment_id' => 23, 'meta_key' => 'karma']);\n // Delete all meta for a comment.\n $I->dontSeeCommentMetaInDatabase(['comment_id' => 23]);\n
Parameters
\\Codeception\\Module\\array/array $criteria - An array of search criteria. dontSeeLinkInDatabase
Checks that a link is not in the links database table.
\\Codeception\\Module\\array/string $criteriaOrName - An array of search criteria or the option name.
mixed/null $value - The optional value to try and match, only used if the option name is provided.
dontSeePageInDatabase
Checks that a page is not in the database.
// Assert a page with an ID does not exist.\n $I->dontSeePageInDatabase(['ID' => 23]);\n // Assert a page with a slug and ID.\n $I->dontSeePageInDatabase(['post_name' => 'test', 'ID' => 23]);\n
Parameters
\\Codeception\\Module\\array/array $criteria - An array of search criteria. dontSeePostInDatabase
Checks that a post is not in the database.
// Asserts a post with title 'Test' is not in the database.\n $I->dontSeePostInDatabase(['post_title' => 'Test']);\n // Asserts a post with title 'Test' and content 'Test content' is not in the database.\n $I->dontSeePostInDatabase(['post_title' => 'Test', 'post_content' => 'Test content']);\n
Parameters
\\Codeception\\Module\\array/array $criteria - An array of search criteria. dontSeePostMetaInDatabase
Checks that a post meta value does not exist. If the meta value is an object or an array then the check will be made on its serialized version.
\\Codeception\\Module\\array/array $criteria - An array of search criteria. dontSeePostWithTermInDatabase
Checks that a post to term relation does not exist in the database. The method will check the \"term_relationships\" table.
$fiction = $I->haveTermInDatabase('fiction', 'genre');\n $nonFiction = $I->haveTermInDatabase('non-fiction', 'genre');\n $postId = $I->havePostInDatabase(['tax_input' => ['genre' => ['fiction']]]);\n $I->dontSeePostWithTermInDatabase($postId, $nonFiction['term_taxonomy_id], );\n passed this parameter will be interpreted as a `term_id`, else as a\n the\n term order.\n to build a `taxonomy_term_id` from the `term_id`.\n
Parameters
int $post_id - The post ID.
int $term_taxonomy_id - The term term_id or term_taxonomy_id; if the $taxonomy argument is
int/null $term_order - The order the term applies to the post, defaults to null to not use
string/null $taxonomy - The taxonomy the term_id is for; if passed this parameter will be used
dontSeeSiteOptionInDatabase
Checks that a site option is not in the database.
// Check that the option is not set in the database.\n $I->dontSeeSiteOptionInDatabase('foo_count');\n // Check that the option is not set with a specific value.\n $I->dontSeeSiteOptionInDatabase('foo_count', 23);\n $I->dontSeeSiteOptionInDatabase(['option_name => 'foo_count', 'option_value' => 23]);\n
Parameters
\\Codeception\\Module\\array/string $criteriaOrName - An array of search criteria or the option name.
mixed/null $value - The optional value to try and match, only used if the option name is provided.
string $table - The full table name, including the table prefix.
dontSeeTermInDatabase
Makes sure a term is not in the database. Looks up both the terms table and the term_taxonomy tables. and the term_taxonomy tables.
// Asserts a 'fiction' term is not in the database.\n $I->dontSeeTermInDatabase(['name' => 'fiction']);\n // Asserts a 'fiction' term with slug 'genre--fiction' is not in the database.\n $I->dontSeeTermInDatabase(['name' => 'fiction', 'slug' => 'genre--fiction']);\n
Parameters
\\Codeception\\Module\\array/array $criteria - An array of criteria to search for the term, can be columns from the terms dontSeeTermMetaInDatabase
\\Codeception\\Module\\array/array $criteria - An array of search criteria. dontSeeUserInDatabase
Checks that a user is not in the database.
// Asserts a user does not exist in the database.\n $I->dontSeeUserInDatabase(['user_login' => 'luca']);\n // Asserts a user with email and login is not in the database.\n $I->dontSeeUserInDatabase(['user_login' => 'luca', 'user_email' => 'luca@theaveragedev.com']);\n
Parameters
\\Codeception\\Module\\array/array $criteria - An array of search criteria. dontSeeUserMetaInDatabase
Check that a user meta value is not in the database.
// Asserts a user does not have a 'karma' meta assigned.\n $I->dontSeeUserMetaInDatabase(['user_id' => 23, 'meta_key' => 'karma']);\n // Asserts no user has any 'karma' meta assigned.\n $I->dontSeeUserMetaInDatabase(['meta_key' => 'karma']);\n
Parameters
\\Codeception\\Module\\array/array $criteria - An array of search criteria. getSiteDomain
Returns the site domain inferred from the url set in the config.
$domain = $I->getSiteDomain();\n // We should be redirected to the HTTPS version when visiting the HTTP version.\n $I->amOnPage('http://' . $domain);\n $I->seeCurrentUrlEquals('https://' . $domain);\n
getUsersTableName
Returns the prefixed users table name.
// Given a `wp_` table prefix returns `wp_users`.\n $usersTable = $I->getUsersTableName();\n // Given a `wp_` table prefix returns `wp_users`.\n $I->useBlog(23);\n $usersTable = $I->getUsersTableName();\n
grabAllFromDatabase
Returns all entries matching a criteria from the database.
// Assuming a `wp_` table prefix it will return `wp_blog_versions`.\n $blogVersionsTable = $I->grabBlogVersionsTableName();\n $I->useBlog(23);\n // Assuming a `wp_` table prefix it will return `wp_blog_versions`.\n $blogVersionsTable = $I->grabBlogVersionsTableName();\n
grabBlogsTableName
Gets the prefixed blogs table name.
// Assuming a `wp_` table prefix it will return `wp_blogs`.\n $blogVersionsTable = $I->grabBlogsTableName();\n $I->useBlog(23);\n // Assuming a `wp_` table prefix it will return `wp_blogs`.\n $blogVersionsTable = $I->grabBlogsTableName();\n
grabCommentmetaTableName
Returns the prefixed comment meta table name.
// Get all the values of 'karma' for all comments.\n $commentMeta = $I->grabCommentmetaTableName();\n $I->grabAllFromDatabase($commentMeta, 'meta_value', ['meta_key' => 'karma']);\n
grabCommentsTableName
Gets the comments table name.
// Will be `wp_comments`.\n $comments = $I->grabCommentsTableName();\n // Will be `wp_23_comments`.\n $I->useBlog(23);\n $comments = $I->grabCommentsTableName();\n
// Given a `wp_` table prefix returns `wp_posts`.\n $postsTable = $I->grabPostsTableName();\n // Given a `wp_` table prefix returns `wp_23_posts`.\n $I->useBlog(23);\n $postsTable = $I->grabPostsTableName();\n
grabPrefixedTableNameFor
Returns a prefixed table name for the current blog. If the table is not one to be prefixed (e.g. users) then the proper table name will be returned.
// Will return wp_users.\n $usersTable = $I->grabPrefixedTableNameFor('users');\n // Will return wp_options.\n $optionsTable = $I->grabPrefixedTableNameFor('options');\n // Use a different blog and get its options table.\n $I->useBlog(2);\n $blogOptionsTable = $I->grabPrefixedTableNameFor('options');\n
Parameters
string $tableName - The table name, e.g. options.
grabRegistrationLogTableName
Gets the prefixed registration_log table name.
// Assuming a `wp_` table prefix it will return `wp_registration_log`.\n $blogVersionsTable = $I->grabRegistrationLogTableName();\n $I->useBlog(23);\n // Assuming a `wp_` table prefix it will return `wp_registration_log`.\n $blogVersionsTable = $I->grabRegistrationLogTableName();\n
grabSignupsTableName
Gets the prefixed signups table name.
// Assuming a `wp_` table prefix it will return `wp_signups`.\n $blogVersionsTable = $I->grabSignupsTableName();\n $I->useBlog(23);\n // Assuming a `wp_` table prefix it will return `wp_signups`.\n $blogVersionsTable = $I->grabSignupsTableName();\n
grabSiteMetaTableName
Gets the prefixed sitemeta table name.
// Assuming a `wp_` table prefix it will return `wp_sitemeta`.\n $blogVersionsTable = $I->grabSiteMetaTableName();\n $I->useBlog(23);\n // Assuming a `wp_` table prefix it will return `wp_sitemeta`.\n $blogVersionsTable = $I->grabSiteMetaTableName();\n
string $key - The name of the option to read from the database.
grabSiteTableName
Gets the prefixed site table name.
// Assuming a `wp_` table prefix it will return `wp_site`.\n $blogVersionsTable = $I->grabSiteTableName();\n $I->useBlog(23);\n // Assuming a `wp_` table prefix it will return `wp_site`.\n $blogVersionsTable = $I->grabSiteTableName();\n
string $key - The site transient to fetch the value for, w/o the _site_transient_ prefix.
grabSiteUrl
Returns the current site URL as specified in the module configuration.
$shopPath = $I->grabSiteUrl('/shop');\n
Parameters
string $path - A path that should be appended to the site URL.
grabTablePrefix
Returns the table prefix, namespaced for secondary blogs if selected.
// Assuming a table prefix of `wp_` it will return `wp_`;\n $tablePrefix = $I->grabTablePrefix();\n $I->useBlog(23);\n // Assuming a table prefix of `wp_` it will return `wp_23_`;\n $tablePrefix = $I->grabTablePrefix();\n
grabTermIdFromDatabase
Gets a term ID from the database. Looks up the prefixed terms table, e.g. wp_terms.
// Return the 'fiction' term 'term_id'.\n $termId = $I->grabTermIdFromDatabase(['name' => 'fiction']);\n // Get a term ID by more stringent criteria.\n $termId = $I->grabTermIdFromDatabase(['name' => 'fiction', 'slug' => 'genre--fiction']);\n // Return the 'term_id' of the first term for a group.\n $termId = $I->grabTermIdFromDatabase(['term_group' => 23]);\n
Parameters
\\Codeception\\Module\\array/array $criteria - An array of search criteria. grabTermMetaTableName
Gets the prefixed term relationships table name, e.g. wp_term_relationships.
$I->grabTermRelationshipsTableName();\n
grabTermTaxonomyIdFromDatabase
Gets a term_taxonomy_id from the database. Looks up the prefixed terms_relationships table, e.g. wp_term_relationships.
// Get the `term_taxonomy_id` for a term and a taxonomy.\n $I->grabTermTaxonomyIdFromDatabase(['term_id' => $fictionId, 'taxonomy' => 'genre']);\n // Get the `term_taxonomy_id` for the first term with a count of 23.\n $I->grabTermTaxonomyIdFromDatabase(['count' => 23]);\n
Parameters
\\Codeception\\Module\\array/array $criteria - An array of search criteria. grabTermTaxonomyTableName
Gets the prefixed term and taxonomy table name, e.g. wp_term_taxonomy.
Gets the a user ID from the database using the user login.
$userId = $I->grabUserIdFromDatabase('luca');\n
Parameters
string $userLogin - The user login name.
grabUserMetaFromDatabase
Gets a user meta from the database.
// Returns a user 'karma' value.\n $I->grabUserMetaFromDatabase($userId, 'karma');\n // Returns an array, the unserialized version of the value stored in the database.\n $I->grabUserMetaFromDatabase($userId, 'api_data');\n
Parameters
int $userId - The ID of th user to get the meta for.
string $meta_key - The meta key to fetch the value for.
grabUsermetaTableName
Returns the prefixed users meta table name.
// Given a `wp_` table prefix returns `wp_usermeta`.\n $usermetaTable = $I->grabUsermetaTableName();\n // Given a `wp_` table prefix returns `wp_usermeta`.\n $I->useBlog(23);\n $usermetaTable = $I->grabUsermetaTableName();\n
grabUsersTableName
Returns the prefixed users table name.
// Given a `wp_` table prefix returns `wp_users`.\n $usersTable = $I->grabUsersTableName();\n // Given a `wp_` table prefix returns `wp_users`.\n $I->useBlog(23);\n $usersTable = $I->grabUsersTableName();\n
haveAttachmentInDatabase
Creates the database entries representing an attachment and moves the attachment file to the right location. timestamp that should be used to build the \"year/time\" uploads sub-folder structure. override the image sizes created by default.
array/\\Codeception\\Module\\array/array $overrides - An array of values to override the default ones; {{n}} will be replaced
bool $subdomain - Whether the new blogs should be created as a subdomain or subfolder.
haveManyCommentsInDatabase
Inserts many comments in the database.
// Insert 3 random comments for a post.\n $I->haveManyCommentsInDatabase(3, $postId);\n // Insert 3 random comments for a post.\n $I->haveManyCommentsInDatabase(3, $postId, ['comment_content' => 'Comment {{n}}']);\n
Parameters
int $count - The number of comments to insert.
int $comment_post_ID - The comment parent post ID.
array/\\Codeception\\Module\\array/array $overrides - An associative array to override the defaults. haveManyLinksInDatabase
Inserts many links in the database links table.
// Insert 3 randomly generated links in the database.\n $linkIds = $I->haveManyLinksInDatabase(3);\n // Inserts links in the database replacing the `n` placeholder.\n $linkIds = $I->haveManyLinksInDatabase(3, ['link_url' => 'http://example.org/test-{{n}}']);\n
Parameters
int $count - The number of links to insert.
array/\\Codeception\\Module\\array/array $overrides - Overrides for the default arguments. haveManyPostsInDatabase
Inserts many posts in the database returning their IDs. An array of values to override the defaults. The {{n}} placeholder can be used to have the post count inserted in its place; e.g. Post Title - {{n}} will be set to Post Title - 0 for the first post, Post Title - 1 for the second one and so on. The same applies to meta values as well.
// Insert 3 random posts.\n $I->haveManyPostsInDatabase(3);\n // Insert 3 posts with generated titles.\n $I->haveManyPostsInDatabase(3, ['post_title' => 'Test post {{n}}']);\n
string $menuSlug - The menu slug the item should be added to.
string $title - The menu item title.
int/null $menuOrder - An optional menu order, 1 based.
array/\\Codeception\\Module\\array/array $meta - An associative array that will be prefixed with _menu_item_ for the item haveOptionInDatabase
Inserts an option in the database.
$I->haveOptionInDatabase('posts_per_page', 23);\n $I->haveOptionInDatabase('my_plugin_options', ['key_one' => 'value_one', 'key_two' => 89]);\n If the option value is an object or an array then the value will be serialized.\n
Parameters
string $option_name - The option name.
mixed $option_value - The option value; if an array or object it will be serialized.
string $autoload - Weather the option should be autoloaded by WordPress or not.
havePageInDatabase
Inserts a page in the database.
// Creates a test page in the database with random values.\n $randomPageId = $I->havePageInDatabase();\n // Creates a test page in the database defining its title.\n $testPageId = $I->havePageInDatabase(['post_title' => 'Test page']);\n
Parameters
array/\\Codeception\\Module\\array/array $overrides - An array of values to override the default ones. havePostInDatabase
Inserts a post in the database. values.
// Insert a post with random values in the database.\n $randomPostId = $I->havePostInDatabase();\n // Insert a post with specific values in the database.\n $I->havePostInDatabase([\n 'post_type' => 'book',\n 'post_title' => 'Alice in Wonderland',\n 'meta_input' => [\n 'readers_count' => 23\n ],\n 'tax_input' => [\n ['genre' => 'fiction']\n ]\n ]);\n
Parameters
array/\\Codeception\\Module\\array/array $data - An associative array of post data to override default and random generated havePostThumbnailInDatabase
Assigns the specified attachment ID as thumbnail (featured image) to a post.
int $postId - The post ID to assign the thumbnail (featured image) to.
int $thumbnailId - The post ID of the attachment.
havePostmetaInDatabase
Adds one or more meta key and value couples in the database for a post.
// Set the post-meta for a post.\n $I->havePostmetaInDatabase($postId, 'karma', 23);\n // Set an array post-meta for a post, it will be serialized in the db.\n $I->havePostmetaInDatabase($postId, 'data', ['one', 'two']);\n // Use a loop to insert one meta per row.\n foreach( ['one', 'two'] as $value){\n $I->havePostmetaInDatabase($postId, 'data', $value);\n }\n
Parameters
int $postId - The post ID.
string $meta_key - The meta key.
mixed $meta_value - The value to insert in the database, objects and arrays will be serialized.
haveSiteOptionInDatabase
Inserts a site option in the database. If the value is an array or an object then the value will be serialized.
mixed $value - The value to insert for the option.
haveSiteTransientInDatabase
Inserts a site transient in the database. If the value is an array or an object then the value will be serialized.
$I->haveSiteTransientInDatabase('total_comments_count', 23);\n // This value will be serialized.\n $I->haveSiteTransientInDatabase('api_data', ['user' => 'luca', 'token' => '11ae3ijns-j83']);\n
Parameters
string $key - The key of the site transient to insert, w/o the _site_transient_ prefix.
mixed $value - The value to insert; if serializable the value will be serialized.
haveTermInDatabase
Inserts a term in the database.
// Insert a random 'genre' term in the database.\n $I->haveTermInDatabase('non-fiction', 'genre');\n // Insert a term in the database with term meta.\n $I->haveTermInDatabase('fiction', 'genre', [\n 'slug' => 'genre--fiction',\n 'meta' => [\n 'readers_count' => 23\n ]\n ]);\n
Parameters
string $name - The term name, e.g. \"Fuzzy\".
string $taxonomy - The term taxonomy
array/\\Codeception\\Module\\array/array $overrides - An array of values to override the default ones. haveTermMetaInDatabase
Inserts a term meta row in the database. Objects and array meta values will be serialized.
$I->haveTermMetaInDatabase($fictionId, 'readers_count', 23);\n // Insert some meta that will be serialized.\n $I->haveTermMetaInDatabase($fictionId, 'flags', [3, 4, 89]);\n // Use a loop to insert one meta per row.\n foreach([3, 4, 89] as $value) {\n $I->haveTermMetaInDatabase($fictionId, 'flag', $value);\n }\n
Parameters
int $term_id - The ID of the term to insert the meta for.
string $meta_key - The key of the meta to insert.
mixed $meta_value - The value of the meta to insert, if serializable it will be serialized.
haveTermRelationshipInDatabase
Creates a term relationship in the database. No check about the consistency of the insertion is made. E.g. a post could be assigned a term from a taxonomy that's not registered for that post type.
// Assign the `fiction` term to a book.\n $I->haveTermRelationshipInDatabase($bookId, $fictionId);\n
Parameters
int $object_id - A post ID, a user ID or anything that can be assigned a taxonomy term.
int $term_taxonomy_id - The term_taxonomy_id of the term and taxonomy to create a relation with.
int $term_order - Defaults to 0.
haveTransientInDatabase
Inserts a transient in the database. If the value is an array or an object then the value will be serialized. Since the transients are set in the context of tests it's not possible to set an expiration directly.
// Store an array in the `tweets` transient.\n $I->haveTransientInDatabase('tweets', $tweets);\n
Parameters
string $transient - The transient name.
mixed $value - The transient value.
haveUserCapabilitiesInDatabase
Sets a user capabilities in the database.
// Assign one user a role in a blog.\n $blogId = $I->haveBlogInDatabase('test');\n $editor = $I->haveUserInDatabase('luca', 'editor');\n $capsIds = $I->haveUserCapabilitiesInDatabase($editor, [$blogId => 'editor']);\n // Assign a user two roles in blog 1.\n $capsIds = $I->haveUserCapabilitiesInDatabase($userId, ['editor', 'subscriber']);\n // Assign one user different roles in different blogs.\n $capsIds = $I->haveUserCapabilitiesInDatabase($userId, [$blogId1 => 'editor', $blogId2 => 'author']);\n // Assign a user a role and an additional capability in blog 1.\n $I->haveUserCapabilitiesInDatabase($userId, ['editor' => true, 'edit_themes' => true]);\n // Assign a user a mix of roles and capabilities in different blogs.\n $capsIds = $I->haveUserCapabilitiesInDatabase(\n $userId,\n [\n $blogId1 => ['editor' => true, 'edit_themes' => true],\n $blogId2 => ['administrator' => true, 'edit_themes' => false]\n ]\n );\n associative array of blog IDs/roles for a multisite\n installation (e.g. `[1 => 'administrator`, 2 =>\n 'subscriber']`).\n
Parameters
int $userId - The ID of the user to set the capabilities of.
string/\\Codeception\\Module\\array/\\Codeception\\Module\\array $role - Either a role string (e.g. administrator),an haveUserInDatabase
Inserts a user and its meta in the database. defaults to subscriber. If more than one role is specified, then the first role in the list will be the user primary role and the wp_user_level will be set to that role. in the users and usermeta table.
// Create an editor user in blog 1 w/ specific email.\n $userId = $I->haveUserInDatabase('luca', 'editor', ['user_email' => 'luca@example.org']);\n // Create a subscriber user in blog 1.\n $subscriberId = $I->haveUserInDatabase('subscriber');\n // Create a user editor in blog 1, author in blog 2, administrator in blog 3.\n $userWithMeta = $I->haveUserInDatabase('luca',\n [\n 1 => 'editor',\n 2 => 'author',\n 3 => 'administrator'\n ], [\n 'user_email' => 'luca@example.org'\n 'meta' => ['a meta_key' => 'a_meta_value']\n ]\n );\n // Create editor in blog 1 w/ `edit_themes` cap, author in blog 2, admin in blog 3 w/o `manage_options` cap.\n $userWithMeta = $I->haveUserInDatabase('luca',\n [\n 1 => ['editor', 'edit_themes'],\n 2 => 'author',\n 3 => ['administrator' => true, 'manage_options' => false]\n ]\n );\n // Create a user w/o role.\n $userId = $I->haveUserInDatabase('luca', '');\n