lipemat/wp-unit

基于Wp-unit,增加了对现有数据库测试和其它环境增强支持的分叉版本。

资助包维护!
lipemat

4.2.1 2024-09-09 19:48 UTC

README

Packagist

wp-unit的分叉版本,支持启动现有数据库和许多其他增强。

注意:版本4与原始WordPress核心测试已分叉。 更多信息。

原始版本可从以下位置克隆: git://develop.git.wordpress.org/tests/phpunit

用法

使用composer安装,可在项目中或全局位置安装以供所有项目使用。

composer require --dev lipemat/wp-unit

example phpunit.xml示例

<?xml version="1.0" encoding="UTF-8"?>
<!-- Version 1.2.0 -->
<phpunit backupGlobals="false"
         backupStaticAttributes="false"
         colors="true"
         convertDeprecationsToExceptions="true"
         convertErrorsToExceptions="true"
         convertNoticesToExceptions="true"
         convertWarningsToExceptions="true"
         processIsolation="false"
         stopOnFailure="true"
         bootstrap="bootstrap.php"
>
    <php>
        <env name="HTTP_HOST" value="starting-point.loc" />
    </php>
    <testsuites>
        <testsuite name="Starting Point">
            <directory>./tests</directory>
        </testsuite>
    </testsuites>
</phpunit>

example bootstrap.php文件示例

<?php
require __DIR__ . '/wp-tests-config.php'
require __DIR__ . '/vendor/autoload.php';
require __DIR__ . '/vendor/lipemat/wp-unit/includes/bootstrap.php';

example wp-tests-config.php示例

<?php
define( 'DB_NAME', 'tests' );
define( 'DB_USER', 'user' );
define( 'DB_PASSWORD', 'password' );
define( 'DB_HOST', 'localhost' );

define( 'ABSPATH', WP_TESTS_DIR . '/' );
define( 'DOMAIN_CURRENT_SITE', 'wp-libs.loc' );
define( 'WP_TESTS_CONFIG_FILE_PATH',  __FILE__ );
define( 'WP_PHP_BINARY', 'php' );
// Root of your site/
define( 'WP_TESTS_DIR', dirname( __DIR__ ) );
define( 'WP_TESTS_DOMAIN', 'tests.loc' );
define( 'WP_TESTS_DOMAIN', 'wp-libs.loc' );
define( 'WP_TESTS_EMAIL', 'unit-tests@test.com' );
define( 'WP_TESTS_TITLE', 'WordPress Unit Tests' );
define( 'WP_UNIT_DIR', __DIR__ . '/vendor/lipemat/wp-unit' );

// If using snapshot testing.
define( 'WP_TESTS_SNAPSHOTS_BASE', 'Lipe\Project' );
define( 'WP_TESTS_SNAPSHOTS_DIR', __DIR__ . '/__snapshots__' );

// If your not bootstrapping an exiting database.
define( 'WP_TESTS_TABLE_PREFIX', 'tests_' );

// If your tests must use `https` URL.
define( 'WP_TESTS_SSL', true );

example 单元测试 /tests/ExampleTest.php示例

<?php
class ExampleTest extends WP_UnitTestCase {
	public function test_examples() : void {
		$this->assertTrue( true );
		$this->assertFalse( false );
	}
}

像其他phpunit套件一样运行测试套件

phpunit

从Composer中排除PHPUnit

如果您正在使用外部PHP Unit可执行文件或.phar,并且不希望phpunit/phpunit作为您composer供应商的一部分安装,您可以在composer.json文件中添加以下配置。

{
  "replace": {
    "phpunit/phpunit": "*"
  }
}

增强功能

网络选项

设置wp_tests_options值也可以用来设置网络选项。像通常一样设置测试选项,它们将自动替换网络选项值。

<?php
$GLOBALS['wp_tests_options'][ 'site_name' ] = 'Example Site Name';

运行所有计划中的cron任务

用于通过运行它们来测试cron任务,如果它们计划运行。

wp_cron_run_all()

本地wp-tests-config.php

您可以在bootstrap.php和phpunit.xml的目录中设置wp-tests.config.php。实际上,您可以将它放在任何地方,只要在bootstrap.php文件中指向它。

<?php
require __DIR__ . '/wp-tests-config.php';

在现有数据库上启动WP

使用bootstrap-no-install.php允许您测试数据库中的当前数据。默认情况下,它支持MySQL事务,允许测试设置和使用数据,而不实际将其存储在数据库中。

  1. 更新您的wp-tests-config.php文件以指向您想要使用的数据库。
  2. 将您的bootstrap.php更改为使用bootstrap-no-install.php文件,如下所示;
<?php
require __DIR__ . '/wp-tests-config.php';
require __DIR__ . '/vendor/lipemat/wp-unit/includes/bootstrap-no-install.php';

注意事项

  1. 如果您在测试类中覆盖了WP_UnitTestCase::setUp()方法,请确保调用parent::setUp()。否则,在测试期间设置的数据将持久化到数据库中。
  2. 如果您的数据库表使用MyISAM存储引擎,数据将持久化。它们可能被转换为InnoDB或任何支持事务的引擎。

适用于所有测试的全局过滤器

在您的wp-tests-config.php文件中添加一些过滤器到$GLOBALS[ 'wp_tests_filters' ]

<?php
$GLOBALS[ 'wp_tests_filters' ][ 'the_title' ] = function ( $title ) {
	return 'Example Title';
};

开启邮件发送

<?php
define( 'WP_TESTS_SEND_MAIL', true );

设置内存限制

在您的wp-tests.config.php中添加自定义内存限制。

<?php
define( 'WP_MEMORY_LIMIT', '128M' );

允许外部语言目录

在您的wp-tests.config.php中添加自定义语言目录。

<?php
define( 'WP_LANG_DIR', __DIR__ . '/languages' );

防止插件破坏MySQL事务

一些第三方插件使用自己的事务,这导致与wp-unit使用的事务产生不可预测的结果。

此库自动考虑外部事务。

支持自定义Ajax方法。

有时您想使用Ajax响应调用位于wp_ajax动作之外的方法。

此库向WP_Ajax_UnitTestCase添加方法

  1. _handleAjaxCustom,它将任何可调用对象转换为wp_ajax动作,然后通过_handleAjax调用它。
  2. _getJsonResult 调用任何使用 wp_send_json_successwp_send_json_error 的可调用函数,并返回结果。

支持原始请求测试。

有时您想验证请求实际上已经发出,而不仅仅是断言发送请求的方法已被调用。

  1. 从您的测试类扩展 WP_Http_Remote_Post_TestCase
  2. 所有请求都不会发送,而是存储在测试类的属性中。
  3. 通过 $this->get_sent() 获取发送的内容。
  4. 通过 $this->mock_response 模拟原始响应。

支持对象缓存测试

对于测试您的对象缓存,有一个可用的辅助测试用例。自动在测试之间重置对象缓存以获得全新的对象缓存。

  1. 从您的测试类扩展 Object_Cache_TestCase
  2. 通过 $this->object_cache 交互以访问您的对象缓存。
  3. 使用包含辅助断言和工具。
    1. assertNotCacheExternal - 断言键在外部缓存中不可用。
    2. assertCacheExternal - 断言键在外部缓存中可用。
    3. assertCachePropertyAndExternal - 断言值在运行时缓存与外部缓存中相同。
    4. get_cache_key - 获取发送到外部缓存的解析键。

自动为附件工厂生成文件。

许多后续的附件调用需要附件实际上附加了文件。例如,如果没有文件存在,则 get_the_post_thumbnail_url 总是会为空。

这会自动通过 self::factory()->attachment 将文件添加到 create 调用。

<?php
$post = self::factory()->post->create_and_get();
$attachment = self::factory()->attachment->create_and_get();
set_post_thumbnail( $post->ID, $attachment->ID );
// Will return something like `https:///wp-content/uploads//tmp/canola.jpg`
get_the_post_thumbnail_url( $post->ID );

支持所有 TestCases 上的 assertEqualSetsValues

支持测试两个值数组,同时考虑顺序但忽略数组键。这对于测试分页等事物很有用。

示例

$categories = \get_categories( [
			'orderby' => 'term_id',
			'order'   => 'ASC',
		] );
$per_page = 20;
$this->assertEqualSetsValues(
			wp_list_pluck( array_slice( $categories, $per_page * 4, $per_page ), 'term_id' ),
			wp_list_pluck( $this->get_results( 5 )->categories, 'id' )
		)

支持所有 TestCases 上的 assertEqualSetsIndex

断言两个数组的关键字相等,无论内容如何,而不考虑元素的顺序。

支持模拟 final 类。

包含一个工具库,以启用任何最终类的模拟。

db/bypass-finals

通过。

DG\BypassFinals::enable();

扩展 WP_UnitTestCase

某些项目需要在每个测试用例中添加额外的功能。最常见的这种情况是为自定义数据库适配器回滚事务。

使用您自己的 WP_UnitTestCase 版本

  1. 在您的本地项目中创建一个 WP_UnitTestCase 类。
  2. 在您的类中扩展 WP_UnitTestCase_Base
  3. 将您的自定义测试方法添加到您的类中。
  4. 定义一个 WP_UNIT_TESTCASE_BASE 常量,其中包含您的类路径。

SQLite3 数据库的示例

在您的项目中创建一个 WP_UnitTestCase.php 文件。

class WP_UnitTestCase extends WP_UnitTestCase_Base {
    // Normally live somewhere in your project.
    static SQLite3 $sqlite_db;
    
	protected function setUp(): void {
		parent::setUp();
	    self::sqlite_db = new SQLite3( ':memory:' );
		self::sqlite_db->exec( 'BEGIN TRANSACTION' );
	}


	protected function tearDown(): void {
		self::sqlite_db->exec( 'ROLLBACK' );
		parent::tearDown();
	}
}

在您的 bootstrap.php 文件中添加以下行。

const WP_UNIT_TESTCASE_BASE = __DIR__ . '/WP_UnitTestCase.php';