Skip to content

This is the documentation for version 3 of the project. The current version is version 4 and the documentation can be found here.

WPDb module

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.

Module requirements for Codeception 4.0+

This module requires the codeception/module-db Composer package to work when wp-browser is used with Codeception 4.0.

To install the package run:

composer require --dev codeception/module-db:^1.0

Backup your content

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!

Change the database used depending on whether you're running tests or not

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".

Automatically changing database based on the browser user agent

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' );
to this:
<?php
if ( 
    // Custom header.
    isset( $_SERVER['HTTP_X_TESTING'] )
    // Custom user agent.
    || ( isset( $_SERVER['HTTP_USER_AGENT'] ) && $_SERVER['HTTP_USER_AGENT'] === 'wp-browser' )
    // The env var set by the WPClIr or WordPress modules.
    || getenv( 'WPBROWSER_HOST_REQUEST' )
) {
    // Use the test database if the request comes from a test.
    define( 'DB_NAME', 'wordpress_test' );
} else {
    // Else use the default one.
    define( 'DB_NAME', 'wordpress' );
}

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
modules:
    enabled:
        - \Helper\Acceptance
        - WPDb
        - WPWebDriver
    config:
        WPDb:
            dsn: 'mysql:host=%WP_DB_HOST%;dbname=%WP_DB_NAME%'
            user: %WP_DB_USER%
            password: %WP_DB_PASSWORD%
            dump: tests/_data/dump.sql
            populate: true
            cleanup: false
            url: '%WP_URL%'
            tablePrefix: %WP_TABLE_PREFIX%
            urlReplacement: true
        WPWebDriver:
            url: '%WP_URL%'
            adminUsername: '%WP_ADMIN_USERNAME%'
            adminPassword: '%WP_ADMIN_PASSWORD%'
            adminPath: '%WP_ADMIN_PATH%'
            browser: chrome
            host: localhost
            port: 4444
            window_size: false
            wait: 5
            capabilities:
              "goog:chromeOptions":
                args:
                  - "--headless"
                  - "--disable-gpu"
                  - "--disable-dev-shm-usage"
                  - "--proxy-server='direct://'"
                  - "--proxy-bypass-list=*"
                  - "--no-sandbox"

If you're using the WPBrowser module send a specific header in the context of test requests:

class_name: AcceptanceTester
modules:
    enabled:
        - \Helper\Acceptance
        - WPDb
        - WPBrowser
    config:
        WPDb:
              dsn: 'mysql:host=%DB_HOST%;dbname=%WP_DB_NAME%'
              user: %WP_DB_USER%
              password: %WP_DB_PASSWORD%
              dump: 'tests/_data/dump.sql'
              populate: true
              cleanup: true
              reconnect: false
              url: '%WP_URL%'
              tablePrefix: 'wp_'
        WPBrowser:
              url: '%WP_URL%'
              adminUsername: 'admin'
              adminPassword: 'admin'
              adminPath: '/wp-admin'
              headers: 
                X-Testing: 'wp-browser'

Configuration

  • 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.

Example configuration

modules:
  enabled:
      - WPDb
  config:
      WPDb:
          dsn: 'mysql:host=localhost;dbname=wordpress'
          user: 'root'
          password: 'password'
          dump: 'tests/_data/dump.sql'
          populate: true
          cleanup: true
          waitlock: 10
          url: 'http://wordpress.localhost'
          urlReplacement: true
          tablePrefix: 'wp_'

Using the module with the WPLoader one

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:

modules:
  enabled:
      - WPDb # this before...
      - WPLoader # ...this one.
  config:
      WPDb:
        # ...
      WPLoader:
        loadOnly: true
        # ... 
This will avoid issues where the WPLoader module could exit, terminating the test run, due to an inconsistent database state.

Public API

countRowsInDatabase


Returns the number of table rows matching a criteria.

$I->haveManyPostsInDatabase(3, ['post_status' => 'draft' ]);
  $I->haveManyPostsInDatabase(3, ['post_status' => 'private' ]);
  // Make sure there are now the expected number of draft posts.
  $postsTable = $I->grabPostsTableName();
  $draftsCount = $I->countRowsInDatabase($postsTable, ['post_status' => 'draft']);

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();
  $attachmentIds = $I->grabColumnFromDatabase($posts, 'ID', ['post_type' => 'attachment']);
  // This will only remove the files, not the database entries.
  $I->dontHaveAttachmentFilesInDatabase($attachmentIds);

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();
  $thumbnailId = $I->grabFromDatabase($postmeta, 'meta_value', [
  'post_id' => $id,
  'meta_key'=>'thumbnail_id'
  ]);
  // Remove only the database entry (including postmeta) but not the files.
  $I->dontHaveAttachmentInDatabase($thumbnailId);
  // Remove the database entry (including postmeta) and the files.
  $I->dontHaveAttachmentInDatabase($thumbnailId, true, true);

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.
  $I->dontHaveBlogInDatabase(['path' => 'test/one']);
  // Remove the blog entry, not the tables though.
  $I->dontHaveBlogInDatabase(['blog_id' => $blogId]);
  // Remove multiple blogs.
  $I->dontHaveBlogInDatabase(['domain' => 'test']);

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.

dontHaveCommentInDatabase


Removes an entry from the comments table.

$I->dontHaveCommentInDatabase(['comment_post_ID' => 23, 'comment_url' => 'http://example.copm']);

Parameters

  • \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.
  $I->dontHaveCommentMetaInDatabase(['comment_id' => 23]);
  // Remove the `count` comment meta for the comment with an ID of 23.
  $I->dontHaveCommentMetaInDatabase(['comment_id' => 23, 'meta_key' => 'count']);

Parameters

  • \Codeception\Module\array/array $criteria - An array of search criteria.

dontHaveInDatabase


Deletes a database entry. criteria.

$I->dontHaveInDatabase('custom_table', ['book_ID' => 23, 'book_genre' => 'fiction']);

Parameters

  • string $table - The table name.
  • \Codeception\Module\array/array $criteria - An associative array of the column names and values to use as deletion

dontHaveLinkInDatabase


Removes a link from the database.

$I->dontHaveLinkInDatabase(['link_url' => 'http://example.com']);

Parameters

  • \Codeception\Module\array/array $criteria - An array of search criteria.

dontHaveOptionInDatabase


Removes an entry from the options table.

// Remove the `foo` option.
  $I->dontHaveOptionInDatabase('foo');
  // Remove the 'bar' option only if it has the `baz` value.
  $I->dontHaveOptionInDatabase('bar', 'baz');

Parameters

  • string $key - The option name.
  • mixed/null $value - If set the option will only be removed if its value matches the passed one.

dontHavePostInDatabase


Removes an entry from the posts table.

$posts = $I->haveManyPostsInDatabase(3, ['post_title' => 'Test {{n}}']);
  $I->dontHavePostInDatabase(['post_title' => 'Test 2']);

Parameters

  • \Codeception\Module\array/array $criteria - An array of search criteria.
  • bool $purgeMeta - If set to true then the meta for the post will be purged too.

dontHavePostMetaInDatabase


Removes an entry from the postmeta table.

$postId = $I->havePostInDatabase(['meta_input' => ['rating' => 23]]);
  $I->dontHavePostMetaInDatabase(['post_id' => $postId, 'meta_key' => 'rating']);

Parameters

  • \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'));
  $postId = $I->havePostInDatabase();
  // Attach the thumbnail to the post.
  $I->havePostThumbnailInDatabase($postId, $attachmentId);
  // Remove the thumbnail from the post.
  $I->dontHavePostThumbnailInDatabase($postId);

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.
  $I->dontHaveSiteOptionInDatabase('foo_count');
  // Remove the `foo_count` option only if its value is `23`.
  $I->dontHaveSiteOptionInDatabase('foo_count', 23);

Parameters

  • string $key - The option name.
  • mixed/null $value - If set the option will only be removed it its value matches the specified one.

dontHaveSiteTransientInDatabase


Removes a site transient from the database.

$I->dontHaveSiteTransientInDatabase(['my_plugin_site_buffer']);

Parameters

  • string $key - The name of the transient to delete.

dontHaveTableInDatabase


Removes a table from the database. The case where a table does not exist is handled without raising an error.

$ordersTable = $I->grabPrefixedTableNameFor('orders');
  $I->dontHaveTableInDatabase($ordersTable);

Parameters

  • string $fullTableName - The full table name, including the table prefix.

dontHaveTermInDatabase


Removes a term from the database.

$I->dontHaveTermInDatabase(['name' => 'romance']);
  $I->dontHaveTermInDatabase(['slug' => 'genre--romance']);

Parameters

  • \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.
  $I->dontHaveTermMetaInDatabase(['term_id' => $termId, 'meta_key' => 'karma']);
  // Remove all meta for the term.
  $I->dontHaveTermMetaInDatabase(['term_id' => $termId]);

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.
  $I->dontHaveTermRelationshipInDatabase(['object_id' => $postId, 'term_taxonomy_id' => $ttaxId]);
  // Remove all terms for a post.
  $I->dontHaveTermMetaInDatabase(['object_id' => $postId]);

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.
  $I->dontHaveTermTaxonomyInDatabase(['term_id' => $postId, 'taxonomy' => 'genre']);
  // Remove all terms for a taxonomy.
  $I->dontHaveTermTaxonomyInDatabase(['taxonomy' => 'genre']);

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.
  $I->dontHaveTransientInDatabase('tweets');

Parameters

  • string $transient - The name of the transient to delete.

dontHaveUserInDatabase


Removes a user from the database.

$bob = $I->haveUserInDatabase('bob');
  $alice = $I->haveUserInDatabase('alice');
  // Remove Bob's user and meta.
  $I->dontHaveUserInDatabase('bob');
  // Remove Alice's user but not meta.
  $I->dontHaveUserInDatabase($alice);

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.

$luca = $I->haveUserInDatabase('luca', 'editor', ['user_email' => 'luca@example.org']);

Parameters

  • 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.
  $I->dontHaveUserMetaInDatabase(['user_id' => 23, 'meta_key' => 'karma']);
  // Remove all the user meta for a user.
  $I->dontHaveUserMetaInDatabase(['user_id' => 23]);

Parameters

  • \Codeception\Module\array/array $criteria - An array of search criteria.

dontSeeAttachmentInDatabase


Checks that an attachment is not in the database.

$url = 'https://example.org/images/foo.png';
  $I->dontSeeAttachmentInDatabase(['guid' => $url]);

Parameters

  • \Codeception\Module\array/array $criteria - An array of search criteria.

dontSeeBlogInDatabase


Checks that a row is not present in the blogs table.

$I->haveManyBlogsInDatabase(2, ['path' => 'test-{{n}}'], false)
  $I->dontSeeBlogInDatabase(['path' => '/test-3/'])

Parameters

  • \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.
  $I->dontSeeCommentInDatabase(['comment_ID' => 23]);
  // Checks for comments from a user.
  $I->dontSeeCommentInDatabase(['user_id' => 89]);

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.
  $I->dontSeeCommentMetaInDatabase(['comment_id' => 23, 'meta_key' => 'karma']);
  // Delete all meta for a comment.
  $I->dontSeeCommentMetaInDatabase(['comment_id' => 23]);

Parameters

  • \Codeception\Module\array/array $criteria - An array of search criteria.

dontSeeLinkInDatabase


Checks that a link is not in the links database table.

$I->dontSeeLinkInDatabase(['link_url' => 'http://example.com']);
  $I->dontSeeLinkInDatabase(['link_url' => 'http://example.com', 'link_name' => 'example']);

Parameters

  • \Codeception\Module\array/array $criteria - An array of search criteria.

dontSeeOptionInDatabase


Checks that an option is not in the database for the current blog. If the value is an object or an array then the serialized option will be checked.

$I->dontHaveOptionInDatabase('posts_per_page');
  $I->dontSeeOptionInDatabase('posts_per_page');
  $I->dontSeeOptionInDatabase('posts_per_page', 23);
  $I->dontSeeOptionInDatabase(['option_name' => 'posts_per_page']);
  $I->dontSeeOptionInDatabase(['option_name' => 'posts_per_page', 'option_value' => 23]);

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.

dontSeePageInDatabase


Checks that a page is not in the database.

// Assert a page with an ID does not exist.
  $I->dontSeePageInDatabase(['ID' => 23]);
  // Assert a page with a slug and ID.
  $I->dontSeePageInDatabase(['post_name' => 'test', 'ID' => 23]);

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.
  $I->dontSeePostInDatabase(['post_title' => 'Test']);
  // Asserts a post with title 'Test' and content 'Test content' is not in the database.
  $I->dontSeePostInDatabase(['post_title' => 'Test', 'post_content' => 'Test content']);

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.

$postId = $I->havePostInDatabase(['meta_input' => ['foo' => 'bar']]);
  $I->dontSeePostMetaInDatabase(['post_id' => $postId, 'meta_key' => 'woot']);

Parameters

  • \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');
  $nonFiction = $I->haveTermInDatabase('non-fiction', 'genre');
  $postId = $I->havePostInDatabase(['tax_input' => ['genre' => ['fiction']]]);
  $I->dontSeePostWithTermInDatabase($postId, $nonFiction['term_taxonomy_id], );
  passed this parameter will be interpreted as a `term_id`, else as a
  the
  term order.
  to build a `taxonomy_term_id` from the `term_id`.

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.
  $I->dontSeeSiteOptionInDatabase('foo_count');
  // Check that the option is not set with a specific value.
  $I->dontSeeSiteOptionInDatabase('foo_count', 23);
  $I->dontSeeSiteOptionInDatabase(['option_name => 'foo_count', 'option_value' => 23]);

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.

dontSeeTableInDatabase


Checks that a table is not in the database.

$options = $I->grabPrefixedTableNameFor('options');
  $I->dontHaveTableInDatabase($options)
  $I->dontSeeTableInDatabase($options);

Parameters

  • 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.
  $I->dontSeeTermInDatabase(['name' => 'fiction']);
  // Asserts a 'fiction' term with slug 'genre--fiction' is not in the database.
  $I->dontSeeTermInDatabase(['name' => 'fiction', 'slug' => 'genre--fiction']);

Parameters

  • \Codeception\Module\array/array $criteria - An array of criteria to search for the term, can be columns from the terms

dontSeeTermMetaInDatabase


Checks that a term meta is not in the database.

list($termId, $termTaxonomyId) = $I->haveTermInDatabase('fiction', 'genre');
  $I->haveTermMetaInDatabase($termId, 'rating', 4);
  $I->dontSeeTermMetaInDatabase(['term_id' => $termId,'meta_key' => 'average_review']);

Parameters

  • \Codeception\Module\array/array $criteria - An array of search criteria.

dontSeeTermTaxonomyInDatabase


Checks that a term taxonomy is not in the database.

list($termId, $termTaxonomyId) = $I->haveTermInDatabase('fiction', 'genre');
  $I->dontSeeTermTaxonomyInDatabase(['term_id' => $termId, 'taxonomy' => 'country']);

Parameters

  • \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.
  $I->dontSeeUserInDatabase(['user_login' => 'luca']);
  // Asserts a user with email and login is not in the database.
  $I->dontSeeUserInDatabase(['user_login' => 'luca', 'user_email' => 'luca@theaveragedev.com']);

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.
  $I->dontSeeUserMetaInDatabase(['user_id' => 23, 'meta_key' => 'karma']);
  // Asserts no user has any 'karma' meta assigned.
  $I->dontSeeUserMetaInDatabase(['meta_key' => 'karma']);

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();
  // We should be redirected to the HTTPS version when visiting the HTTP version.
  $I->amOnPage('http://' . $domain);
  $I->seeCurrentUrlEquals('https://' . $domain);

getUsersTableName


Returns the prefixed users table name.

// Given a `wp_` table prefix returns `wp_users`.
  $usersTable = $I->getUsersTableName();
  // Given a `wp_` table prefix returns `wp_users`.
  $I->useBlog(23);
  $usersTable = $I->getUsersTableName();

grabAllFromDatabase


Returns all entries matching a criteria from the database.

$books = $I->grabPrefixedTableNameFor('books');
  $I->grabAllFromDatabase($books, 'title', ['genre' => 'fiction']);

Parameters

  • string $table - The table to grab the values from.
  • string $column - The column to fetch.
  • \Codeception\Module\array $criteria - The search criteria.

grabAttachmentAttachedFile


Returns the path, as stored in the database, of an attachment _wp_attached_file meta. The attached file is, usually, an attachment origal file.

$file = $I->grabAttachmentAttachedFile($attachmentId);
  $fileInfo = new SplFileInfo($file);
  $I->assertEquals('jpg', $fileInfo->getExtension());

Parameters

  • int $attachmentPostId - The attachment post ID.

grabAttachmentMetadata


Returns the metadata array for an attachment post. This is the value of the _wp_attachment_metadata meta.

$metadata = $I->grabAttachmentMetadata($attachmentId);
  $I->assertEquals(['thumbnail', 'medium', 'medium_large'], array_keys($metadata['sizes']);

Parameters

  • int $attachmentPostId - The attachment post ID.

grabBlogDomain


Returns a blog domain given its ID.

$blogIds = $I->haveManyBlogsInDatabase(3);
  $domains = array_map(function($blogId){
  return $I->grabBlogDomain($blogId);
  }, $blogIds);

Parameters

  • int $blogId - The blog ID.

grabBlogPath


Grabs a blog domain from the blogs table.

$blogId = $I->haveBlogInDatabase('test');
  $path = $I->grabBlogDomain($blogId);
  $I->amOnSubdomain($path);
  $I->amOnPage('/');

Parameters

  • int $blogId - The blog ID.

grabBlogTableName


Returns the full name of a table for a blog from a multisite installation database.

$blogOptionTable = $I->grabBlogTableName($blogId, 'option');

Parameters

  • int $blogId - The blog ID.
  • string $table - The table name, without table prefix.

grabBlogTableNames


Returns a list of tables for a blog ID.

$blogId = $I->haveBlogInDatabase('test');
  $tables = $I->grabBlogTableNames($blogId);
  $options = array_filter($tables, function($tableName){
  return str_pos($tableName, 'options') !== false;
  });

Parameters

  • int $blogId - The ID of the blog to fetch the tables for.

grabBlogTablePrefix


Returns the table prefix for a blog.

$blogId = $I->haveBlogInDatabase('test');
  $blogTablePrefix = $I->getBlogTablePrefix($blogId);
  $blogOrders = $I->blogTablePrefix . 'orders';

Parameters

  • int $blogId - The blog ID.

grabBlogVersionsTableName


Gets the prefixed blog_versions table name.

// Assuming a `wp_` table prefix it will return `wp_blog_versions`.
  $blogVersionsTable = $I->grabBlogVersionsTableName();
  $I->useBlog(23);
  // Assuming a `wp_` table prefix it will return `wp_blog_versions`.
  $blogVersionsTable = $I->grabBlogVersionsTableName();

grabBlogsTableName


Gets the prefixed blogs table name.

// Assuming a `wp_` table prefix it will return `wp_blogs`.
  $blogVersionsTable = $I->grabBlogsTableName();
  $I->useBlog(23);
  // Assuming a `wp_` table prefix it will return `wp_blogs`.
  $blogVersionsTable = $I->grabBlogsTableName();

grabCommentmetaTableName


Returns the prefixed comment meta table name.

// Get all the values of 'karma' for all comments.
  $commentMeta = $I->grabCommentmetaTableName();
  $I->grabAllFromDatabase($commentMeta, 'meta_value', ['meta_key' => 'karma']);

grabCommentsTableName


Gets the comments table name.

// Will be `wp_comments`.
  $comments = $I->grabCommentsTableName();
  // Will be `wp_23_comments`.
  $I->useBlog(23);
  $comments = $I->grabCommentsTableName();

grabLatestEntryByFromDatabase


Returns the id value of the last table entry.

$I->haveManyPostsInDatabase();
  $postsTable = $I->grabPostsTableName();
  $last = $I->grabLatestEntryByFromDatabase($postsTable, 'ID');
  items.

Parameters

  • string $tableName - The table to fetch the last insertion for.
  • string $idColumn - The column that is used, in the table, to uniquely identify

grabLinksTableName


Returns the prefixed links table name.

// Given a `wp_` table prefix returns `wp_links`.
  $linksTable = $I->grabLinksTableName();
  // Given a `wp_` table prefix returns `wp_23_links`.
  $I->useBlog(23);
  $linksTable = $I->grabLinksTableName();

grabOptionFromDatabase


Gets an option value from the database.

$count = $I->grabOptionFromDatabase('foo_count');

Parameters

  • string $option_name - The name of the option to grab from the database.

grabPostMetaFromDatabase


Gets the value of one or more post meta values from the database.

$thumbnail_id = $I->grabPostMetaFromDatabase($postId, '_thumbnail_id', true);

Parameters

  • int $postId - The post ID.
  • string $metaKey - The key of the meta to retrieve.
  • bool $single - Whether to return a single meta value or an array of all available meta values.

grabPostmetaTableName


Returns the prefixed post meta table name.

// Returns 'wp_postmeta'.
  $I->grabPostmetaTableName();
  // Returns 'wp_23_postmeta'.
  $I->useBlog(23);
  $I->grabPostmetaTableName();

grabPostsTableName


Gets the posts prefixed table name.

// Given a `wp_` table prefix returns `wp_posts`.
  $postsTable = $I->grabPostsTableName();
  // Given a `wp_` table prefix returns `wp_23_posts`.
  $I->useBlog(23);
  $postsTable = $I->grabPostsTableName();

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.
  $usersTable = $I->grabPrefixedTableNameFor('users');
  // Will return wp_options.
  $optionsTable = $I->grabPrefixedTableNameFor('options');
  // Use a different blog and get its options table.
  $I->useBlog(2);
  $blogOptionsTable = $I->grabPrefixedTableNameFor('options');

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`.
  $blogVersionsTable = $I->grabRegistrationLogTableName();
  $I->useBlog(23);
  // Assuming a `wp_` table prefix it will return `wp_registration_log`.
  $blogVersionsTable = $I->grabRegistrationLogTableName();

grabSignupsTableName


Gets the prefixed signups table name.

// Assuming a `wp_` table prefix it will return `wp_signups`.
  $blogVersionsTable = $I->grabSignupsTableName();
  $I->useBlog(23);
  // Assuming a `wp_` table prefix it will return `wp_signups`.
  $blogVersionsTable = $I->grabSignupsTableName();

grabSiteMetaTableName


Gets the prefixed sitemeta table name.

// Assuming a `wp_` table prefix it will return `wp_sitemeta`.
  $blogVersionsTable = $I->grabSiteMetaTableName();
  $I->useBlog(23);
  // Assuming a `wp_` table prefix it will return `wp_sitemeta`.
  $blogVersionsTable = $I->grabSiteMetaTableName();

grabSiteOptionFromDatabase


Gets a site option from the database.

$fooCountOptionId = $I->haveSiteOptionInDatabase('foo_count','23');

Parameters

  • 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`.
  $blogVersionsTable = $I->grabSiteTableName();
  $I->useBlog(23);
  // Assuming a `wp_` table prefix it will return `wp_site`.
  $blogVersionsTable = $I->grabSiteTableName();

grabSiteTransientFromDatabase


Gets a site transient from the database.

$I->grabSiteTransientFromDatabase('total_comments');
  $I->grabSiteTransientFromDatabase('api_data');

Parameters

  • 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');

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_`;
  $tablePrefix = $I->grabTablePrefix();
  $I->useBlog(23);
  // Assuming a table prefix of `wp_` it will return `wp_23_`;
  $tablePrefix = $I->grabTablePrefix();

grabTermIdFromDatabase


Gets a term ID from the database. Looks up the prefixed terms table, e.g. wp_terms.

// Return the 'fiction' term 'term_id'.
  $termId = $I->grabTermIdFromDatabase(['name' => 'fiction']);
  // Get a term ID by more stringent criteria.
  $termId = $I->grabTermIdFromDatabase(['name' => 'fiction', 'slug' => 'genre--fiction']);
  // Return the 'term_id' of the first term for a group.
  $termId = $I->grabTermIdFromDatabase(['term_group' => 23]);

Parameters

  • \Codeception\Module\array/array $criteria - An array of search criteria.

grabTermMetaTableName


Gets the terms meta table prefixed name.

// Returns 'wp_termmeta'.
  $I->grabTermMetaTableName();
  // Returns 'wp_23_termmeta'.
  $I->useBlog(23);
  $I->grabTermMetaTableName();

grabTermRelationshipsTableName


Gets the prefixed term relationships table name, e.g. wp_term_relationships.

$I->grabTermRelationshipsTableName();

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.
  $I->grabTermTaxonomyIdFromDatabase(['term_id' => $fictionId, 'taxonomy' => 'genre']);
  // Get the `term_taxonomy_id` for the first term with a count of 23.
  $I->grabTermTaxonomyIdFromDatabase(['count' => 23]);

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.

// Returns 'wp_term_taxonomy'.
  $I->grabTermTaxonomyTableName();
  // Returns 'wp_23_term_taxonomy'.
  $I->useBlog(23);
  $I->grabTermTaxonomyTableName();

grabTermsTableName


Gets the prefixed terms table name, e.g. wp_terms.

// Returns 'wp_terms'.
  $I->grabTermsTableName();
  // Returns 'wp_23_terms'.
  $I->useBlog(23);
  $I->grabTermsTableName();

grabUserIdFromDatabase


Gets the a user ID from the database using the user login.

$userId = $I->grabUserIdFromDatabase('luca');

Parameters

  • string $userLogin - The user login name.

grabUserMetaFromDatabase


Gets a user meta from the database.

// Returns a user 'karma' value.
  $I->grabUserMetaFromDatabase($userId, 'karma');
  // Returns an array, the unserialized version of the value stored in the database.
  $I->grabUserMetaFromDatabase($userId, 'api_data');

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`.
  $usermetaTable = $I->grabUsermetaTableName();
  // Given a `wp_` table prefix returns `wp_usermeta`.
  $I->useBlog(23);
  $usermetaTable = $I->grabUsermetaTableName();

grabUsersTableName


Returns the prefixed users table name.

// Given a `wp_` table prefix returns `wp_users`.
  $usersTable = $I->grabUsersTableName();
  // Given a `wp_` table prefix returns `wp_users`.
  $I->useBlog(23);
  $usersTable = $I->grabUsersTableName();

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.

$file = codecept_data_dir('images/test.png');
  $attachmentId = $I->haveAttachmentInDatabase($file);
  $image = codecept_data_dir('images/test-2.png');
  $lastWeekAttachment = $I->haveAttachmentInDatabase($image, '-1 week');
  Requires the WPFilesystem module.

Parameters

  • string $file - The absolute path to the attachment file.
  • string/string/int $date - Either a string supported by the strtotime function or a UNIX
  • array/\Codeception\Module\array/array $overrides - An associative array of values overriding the default ones.
  • \Codeception\Module\array> $imageSizes - An associative array in the format [ => [,]] to

haveBlogInDatabase


Inserts a blog in the blogs table.

// Create the `test` subdomain blog.
  $blogId = $I->haveBlogInDatabase('test', ['administrator' => $userId]);
  // Create the `/test` subfolder blog.
  $blogId = $I->haveBlogInDatabase('test', ['administrator' => $userId], false);
  or subfolder (`true`)

Parameters

  • string $domainOrPath - The subdomain or the path to the be used for the blog.
  • array/\Codeception\Module\array/array $overrides - An array of values to override the defaults.
  • bool $subdomain - Whether the new blog should be created as a subdomain (true)

haveCommentInDatabase


Inserts a comment in the database.

$I->haveCommentInDatabase($postId, ['comment_content' => 'Test Comment', 'comment_karma' => 23]);

Parameters

  • int $comment_post_ID - The id of the post the comment refers to.
  • array/\Codeception\Module\array/array $data - The comment data overriding default and random generated values.

haveCommentMetaInDatabase


Inserts a comment meta field in the database. Array and object meta values will be serialized.

$I->haveCommentMetaInDatabase($commentId, 'api_ID', 23);
  // The value will be serialized.
  $apiData = ['ID' => 23, 'user' => 89, 'origin' => 'twitter'];
  $I->haveCommentMetaInDatabase($commentId, 'api_data', $apiData);

Parameters

  • int $comment_id - The ID of the comment to insert the meta for.
  • string $meta_key - The key of the comment meta to insert.
  • mixed $meta_value - The value of the meta to insert, if serializable it will be serialized.

haveLinkInDatabase


Inserts a link in the database.

$linkId = $I->haveLinkInDatabase(['link_url' => 'http://example.org']);

Parameters

  • array/\Codeception\Module\array/array $overrides - The data to insert.

haveManyBlogsInDatabase


Inserts many blogs in the database. by the count.

$blogIds = $I->haveManyBlogsInDatabase(3, ['domain' =>'test-{{n}}']);
  foreach($blogIds as $blogId){
  $I->useBlog($blogId);
  $I->haveManuPostsInDatabase(3);
  }

Parameters

  • int $count - The number of blogs to create.
  • 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.
  $I->haveManyCommentsInDatabase(3, $postId);
  // Insert 3 random comments for a post.
  $I->haveManyCommentsInDatabase(3, $postId, ['comment_content' => 'Comment {{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.
  $linkIds = $I->haveManyLinksInDatabase(3);
  // Inserts links in the database replacing the `n` placeholder.
  $linkIds = $I->haveManyLinksInDatabase(3, ['link_url' => 'http://example.org/test-{{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.
  $I->haveManyPostsInDatabase(3);
  // Insert 3 posts with generated titles.
  $I->haveManyPostsInDatabase(3, ['post_title' => 'Test post {{n}}']);

Parameters

  • int $count - The number of posts to insert.
  • array/\Codeception\Module\array/array $overrides

haveManyTermsInDatabase


Inserts many terms in the database.

$terms = $I->haveManyTermsInDatabase(3, 'genre-{{n}}', 'genre');
  $termIds = array_column($terms, 0);
  $termTaxonomyIds = array_column($terms, 1);

Parameters

  • int $count - The number of terms to insert.
  • string $name - The term name template, can include the {{n}} placeholder.
  • string $taxonomy - The taxonomy to insert the terms for.
  • array/\Codeception\Module\array/array $overrides - An associative array of default overrides.

haveManyUsersInDatabase


Inserts many users in the database.

$subscribers = $I->haveManyUsersInDatabase(5, 'user-{{n}}');
  $editors = $I->haveManyUsersInDatabase(
  5,
  'user-{{n}}',
  'editor',
  ['user_email' => 'user-{{n}}@example.org']
  );

Parameters

  • int $count - The number of users to insert.
  • string $user_login - The user login name.
  • string $role - The user role.
  • array/\Codeception\Module\array/array $overrides - An array of values to override the default ones.

haveMenuInDatabase


Creates and adds a menu to a theme location in the database.

list($termId, $termTaxId) = $I->haveMenuInDatabase('test', 'sidebar');

Parameters

  • string $slug - The menu slug.
  • string $location - The theme menu location the menu will be assigned to.
  • array/\Codeception\Module\array/array $overrides - An array of values to override the defaults.

haveMenuItemInDatabase


Adds a menu element to a menu for the current theme. post meta.

$I->haveMenuInDatabase('test', 'sidebar');
  $I->haveMenuItemInDatabase('test', 'Test one', 0);
  $I->haveMenuItemInDatabase('test', 'Test two', 1);

Parameters

  • 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);
  $I->haveOptionInDatabase('my_plugin_options', ['key_one' => 'value_one', 'key_two' => 89]);
  If the option value is an object or an array then the value will be serialized.

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.
  $randomPageId = $I->havePageInDatabase();
  // Creates a test page in the database defining its title.
  $testPageId = $I->havePageInDatabase(['post_title' => 'Test page']);

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.
  $randomPostId = $I->havePostInDatabase();
  // Insert a post with specific values in the database.
  $I->havePostInDatabase([
  'post_type' => 'book',
  'post_title' => 'Alice in Wonderland',
  'meta_input' => [
  'readers_count' => 23
  ],
  'tax_input' => [
  ['genre' => 'fiction']
  ]
  ]);

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.

$attachmentId = $I->haveAttachmentInDatabase(codecept_data_dir('some-image.png'));
  $postId = $I->havePostInDatabase();
  $I->havePostThumbnailInDatabase($postId, $attachmentId);

Parameters

  • 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.
  $I->havePostmetaInDatabase($postId, 'karma', 23);
  // Set an array post-meta for a post, it will be serialized in the db.
  $I->havePostmetaInDatabase($postId, 'data', ['one', 'two']);
  // Use a loop to insert one meta per row.
  foreach( ['one', 'two'] as $value){
  $I->havePostmetaInDatabase($postId, 'data', $value);
  }

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.

$fooCountOptionId = $I->haveSiteOptionInDatabase('foo_count','23');

Parameters

  • string $key - The name of the option to insert.
  • 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);
  // This value will be serialized.
  $I->haveSiteTransientInDatabase('api_data', ['user' => 'luca', 'token' => '11ae3ijns-j83']);

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.
  $I->haveTermInDatabase('non-fiction', 'genre');
  // Insert a term in the database with term meta.
  $I->haveTermInDatabase('fiction', 'genre', [
  'slug' => 'genre--fiction',
  'meta' => [
  'readers_count' => 23
  ]
  ]);

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);
  // Insert some meta that will be serialized.
  $I->haveTermMetaInDatabase($fictionId, 'flags', [3, 4, 89]);
  // Use a loop to insert one meta per row.
  foreach([3, 4, 89] as $value) {
  $I->haveTermMetaInDatabase($fictionId, 'flag', $value);
  }

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.
  $I->haveTermRelationshipInDatabase($bookId, $fictionId);

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.
  $I->haveTransientInDatabase('tweets', $tweets);

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.
  $blogId = $I->haveBlogInDatabase('test');
  $editor = $I->haveUserInDatabase('luca', 'editor');
  $capsIds = $I->haveUserCapabilitiesInDatabase($editor, [$blogId => 'editor']);
  // Assign a user two roles in blog 1.
  $capsIds = $I->haveUserCapabilitiesInDatabase($userId, ['editor', 'subscriber']);
  // Assign one user different roles in different blogs.
  $capsIds = $I->haveUserCapabilitiesInDatabase($userId, [$blogId1 => 'editor', $blogId2 => 'author']);
  // Assign a user a role and an additional capability in blog 1.
  $I->haveUserCapabilitiesInDatabase($userId, ['editor' => true, 'edit_themes' => true]);
  // Assign a user a mix of roles and capabilities in different blogs.
  $capsIds = $I->haveUserCapabilitiesInDatabase(
  $userId,
  [
  $blogId1 => ['editor' => true, 'edit_themes' => true],
  $blogId2 => ['administrator' => true, 'edit_themes' => false]
  ]
  );
  associative array of blog IDs/roles for a multisite
  installation (e.g. `[1 => 'administrator`, 2 =>
  'subscriber']`).

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.
  $userId = $I->haveUserInDatabase('luca', 'editor', ['user_email' => 'luca@example.org']);
  // Create a subscriber user in blog 1.
  $subscriberId = $I->haveUserInDatabase('subscriber');
  // Create a user editor in blog 1, author in blog 2, administrator in blog 3.
  $userWithMeta = $I->haveUserInDatabase('luca',
  [
  1 => 'editor',
  2 => 'author',
  3 => 'administrator'
  ], [
  'user_email' => 'luca@example.org'
  'meta' => ['a meta_key' => 'a_meta_value']
  ]
  );
  // Create editor in blog 1 w/ `edit_themes` cap, author in blog 2, admin in blog 3 w/o `manage_options` cap.
  $userWithMeta = $I->haveUserInDatabase('luca',
  [
  1 => ['editor', 'edit_themes'],
  2 => 'author',
  3 => ['administrator' => true, 'manage_options' => false]
  ]
  );
  // Create a user w/o role.
  $userId = $I->haveUserInDatabase('luca', '');

Parameters

  • string $user_login - The user login name.
  • string/string/\Codeception\Module\array $role - The user role slug(s), e.g. administrator or ['author', 'editor'];
  • array/\Codeception\Module\array/array $overrides - An associative array of column names and values overriding defaults

haveUserLevelsInDatabase


Sets the user access level meta in the database for a user. IDs/roles for a multisite installation (e.g. [1 => 'administrator, 2 => 'subscriber']`).

$userId = $I->haveUserInDatabase('luca', 'editor');
  $moreThanAnEditorLessThanAnAdmin = 8;
  $I->haveUserLevelsInDatabase($userId, $moreThanAnEditorLessThanAnAdmin);

Parameters

  • int $userId - The ID of the user to set the level for.
  • \Codeception\Module\array/string $role - Either a role string (e.g. administrator) or an array of blog

haveUserMetaInDatabase


Sets a user meta in the database.

$userId = $I->haveUserInDatabase('luca', 'editor');
  $I->haveUserMetaInDatabase($userId, 'karma', 23);
  values will trigger the insertion of multiple rows.

Parameters

  • int $userId - The user ID.
  • string $meta_key - The meta key to set the value for.
  • mixed $meta_value - Either a single value or an array of values; objects will be serialized while array of

importSql


Loads a set SQL code lines in the current database.

// Import a SQL string.
  $I->importSql([$sqlString]);
  // Import a set of SQL strings.
  $I->importSql($sqlStrings);
  // Import a prepared set of SQL strings.
  $preparedSqlStrings = array_map(function($line){
  return str_replace('{{date}}', date('Y-m-d H:i:s'), $line);
  }, $sqlTemplate);
  $I->importSql($preparedSqlStrings);

Parameters

  • \Codeception\Module\array/array $sql - The SQL strings to load.

importSqlDumpFile


Import the SQL dump file if populate is enabled.

// Import a dump file passing the absolute path.
  $I->importSqlDumpFile(codecept_data_dir('dumps/start.sql'));
  Specifying a dump file that file will be imported.

Parameters

  • string/null $dumpFile - The dump file that should be imported in place of the default one.

seeAttachmentInDatabase


Checks for an attachment in the database.

$url = 'https://example.org/images/foo.png';
  $I->seeAttachmentInDatabase(['guid' => $url]);

Parameters

  • \Codeception\Module\array/array $criteria - An array of search criteria.

seeBlogInDatabase


Checks for a blog in the blogs table.

// Search for a blog by `blog_id`.
  $I->seeBlogInDatabase(['blog_id' => 23]);
  // Search for all blogs on a path.
  $I->seeBlogInDatabase(['path' => '/sub-path/']);

Parameters

  • \Codeception\Module\array/array $criteria - An array of search criteria.

seeCommentInDatabase


Checks for a comment in the database. Will look up the "comments" table.

$I->seeCommentInDatabase(['comment_ID' => 23]);

Parameters

  • \Codeception\Module\array/array $criteria - An array of search criteria.

seeCommentMetaInDatabase


Checks that a comment meta value is in the database. Will look up the "commentmeta" table.

// Assert a specified meta for a comment exists.
  $I->seeCommentMetaInDatabase(['comment_ID' => $commentId, 'meta_key' => 'karma', 'meta_value' => 23]);
  // Assert the comment has at least one meta set.
  $I->seeCommentMetaInDatabase(['comment_ID' => $commentId]);

Parameters

  • \Codeception\Module\array/array $criteria - An array of search criteria.

seeLinkInDatabase


Checks for a link in the links table of the database.

// Asserts a link exists by name.
  $I->seeLinkInDatabase(['link_name' => 'my-link']);
  // Asserts at least one link exists for the user.
  $I->seeLinkInDatabase(['link_owner' => $userId]);

Parameters

  • \Codeception\Module\array/array $criteria - An array of search criteria.

seeOptionInDatabase


Checks if an option is in the database for the current blog, either by criteria or by name and value. If checking for an array or an object then the serialized version will be checked for.

// Checks an option is in the database.
  $I->seeOptionInDatabase('tables_version');
  // Checks an option is in the database and has a specific value.
  $I->seeOptionInDatabase('tables_version', '1.0');
  $I->seeOptionInDatabase(['option_name' => 'tables_version', 'option_value' => 1.0']);

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.

seePageInDatabase


Checks for a page in the database.

// Asserts a page with an exists in the database.
  $I->seePageInDatabase(['ID' => 23]);
  // Asserts a page with a slug and ID exists in the database.
  $I->seePageInDatabase(['post_title' => 'Test Page', 'ID' => 23]);

Parameters

  • \Codeception\Module\array/array $criteria - An array of search criteria.

seePostInDatabase


Checks for a post in the database.

// Assert a post exists in the database.
  $I->seePostInDatabase(['ID' => 23]);
  // Assert a post with a slug and ID exists in the database.
  $I->seePostInDatabase(['post_content' => 'test content', 'ID' => 23]);

Parameters

  • \Codeception\Module\array/array $criteria - An array of search criteria.

seePostMetaInDatabase


Checks for a post meta value in the database for the current blog. If the meta_value is an object or an array then the check will be made for serialized values.

$postId = $I->havePostInDatabase(['meta_input' => ['foo' => 'bar']];
  $I->seePostMetaInDatabase(['post_id' => '$postId', 'meta_key' => 'foo']);

Parameters

  • \Codeception\Module\array/array $criteria - An array of search criteria.

seePostWithTermInDatabase


Checks that a post to term relation exists in the database. The method will check the "term_relationships" table.

$fiction = $I->haveTermInDatabase('fiction', 'genre');
  $postId = $I->havePostInDatabase(['tax_input' => ['genre' => ['fiction']]]);
  $I->seePostWithTermInDatabase($postId, $fiction['term_taxonomy_id']);
  passed this parameter will be interpreted as a `term_id`, else as a
  the
  term order.
  to build a `taxonomy_term_id` from the `term_id`.

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

seeSiteOptionInDatabase


Checks that a site option is in the database.

// Check that the option is set in the database.
  $I->seeSiteOptionInDatabase('foo_count');
  // Check that the option is set and has a specific value.
  $I->seeSiteOptionInDatabase('foo_count', 23);

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.

seeSiteSiteTransientInDatabase


Checks that a site option is in the database.

// Check a transient exists.
  $I->seeSiteSiteTransientInDatabase('total_counts');
  // Check a transient exists and has a specific value.
  $I->seeSiteSiteTransientInDatabase('total_counts', 23);

Parameters

  • string $key - The name of the transient to check for, w/o the _site_transient_ prefix.
  • mixed/null $value - If provided then the assertion will include the value.

seeTableInDatabase


Checks that a table is in the database.

$options = $I->grabPrefixedTableNameFor('options');
  $I->seeTableInDatabase($options);

Parameters

  • string $table - The full table name, including the table prefix.

seeTermInDatabase


Checks for a term in the database. Looks up the terms and term_taxonomy prefixed tables. and the term_taxonomy tables.

$I->seeTermInDatabase(['slug' => 'genre--fiction']);
  $I->seeTermInDatabase(['name' => 'Fiction', 'slug' => 'genre--fiction']);

Parameters

  • \Codeception\Module\array/array $criteria - An array of criteria to search for the term, can be columns from the terms

seeTermMetaInDatabase


Checks for a term meta in the database.

list($termId, $termTaxonomyId) = $I->haveTermInDatabase('fiction', 'genre');
  $I->haveTermMetaInDatabase($termId, 'rating', 4);
  $I->seeTermMetaInDatabase(['term_id' => $termId,'meta_key' => 'rating', 'meta_value' => 4]);

Parameters

  • \Codeception\Module\array/array $criteria - An array of search criteria.

seeTermRelationshipInDatabase


Checks for a term relationship in the database.

$postId = $I->havePostInDatabase(['tax_input' => ['category' => 'one']]);
  $I->seeTermRelationshipInDatabase(['object_id' => $postId, 'term_taxonomy_id' => $oneTermTaxId]);

Parameters

  • \Codeception\Module\array/array $criteria - An array of search criteria.

seeTermTaxonomyInDatabase


Checks for a taxonomy taxonomy in the database.

list($termId, $termTaxonomyId) = $I->haveTermInDatabase('fiction', 'genre');
  $I->seeTermTaxonomyInDatabase(['term_id' => $termId, 'taxonomy' => 'genre']);

Parameters

  • \Codeception\Module\array/array $criteria - An array of search criteria.

seeUserInDatabase


Checks that a user is in the database. The method will check the "users" table.

$I->seeUserInDatabase([
  "user_email" => "test@example.org",
  "user_login" => "login name"
  ])

Parameters

  • \Codeception\Module\array/array $criteria - An array of search criteria.

seeUserMetaInDatabase


Checks for a user meta value in the database.

$I->seeUserMetaInDatabase(['user_id' => 23, 'meta_key' => 'karma']);

Parameters

  • \Codeception\Module\array/array $criteria - An array of search criteria.

useBlog


Sets the blog to be used. This has nothing to do with WordPress switch_to_blog function, this code will affect the table prefixes used.

// Switch to the blog with ID 23.
  $I->useBlog(23);
  // Switch back to the main blog.
  $I->useMainBlog();

Parameters

  • int $blogId - The ID of the blog to use.

useMainBlog


Sets the current blog to the main one (blog_id 1).

// Switch to the blog with ID 23.
  $I->useBlog(23);
  // Switch back to the main blog.
  $I->useMainBlog();

useTheme


Sets the current theme options.

$I->useTheme('twentyseventeen');
  $I->useTheme('child-of-twentyseventeen', 'twentyseventeen');
  $I->useTheme('acme', 'acme', 'Acme Theme');

Parameters

  • string $stylesheet - The theme stylesheet slug, e.g. twentysixteen.
  • string $template - The theme template slug, e.g. twentysixteen, defaults to $stylesheet.
  • string $themeName - The theme name, e.g. Acme, defaults to the "title" version of

This class extends \Codeception\Module\Db

This class implements \Codeception\Lib\Interfaces\Db