Swoole 模块测试
本指南介绍如何测试 Kuiper Swoole 模块的功能,包括协程环境测试、连接池测试和并发测试。
测试概述
Swoole 模块测试主要包括:
- 协程环境测试 - 验证协程检测和上下文管理
- 协程功能测试 - 测试协程基本功能
- 连接池测试 - 测试连接池的各种场景
- 并发测试 - 测试并发场景下的正确性
- 集成测试 - 测试与其他组件的集成
测试环境设置
基本测试类
php
<?php
declare(strict_types=1);
namespace Tests\swoole;
use PHPUnit\Framework\TestCase;
use kuiper\swoole\SwooleHelper;
use kuiper\swoole\coroutine\Coroutine;
class SwooleTestCase extends TestCase
{
protected function setUp(): void
{
parent::setUp();
if (!SwooleHelper::isEnabled()) {
$this->markTestSkipped('Swoole 扩展未安装');
}
}
protected function needsCoroutine(): void
{
if (!Coroutine::isEnabled()) {
$this->markTestSkipped('需要在协程环境中运行');
}
}
}协程环境测试
SwooleHelper 测试
php
<?php
declare(strict_types=1);
namespace Tests\swoole;
use PHPUnit\Framework\TestCase;
use kuiper\swoole\SwooleHelper;
class SwooleHelperTest extends TestCase
{
public function testIsEnabled(): void
{
$this->assertIsBool(SwooleHelper::isEnabled());
}
public function testRequireSwooleWhenEnabled(): void
{
if (SwooleHelper::isEnabled()) {
$this->expectNotToPerformAssertions();
SwooleHelper::requireSwoole();
} else {
$this->markTestSkipped('Swoole 扩展未安装');
}
}
public function testRequireSwooleWhenDisabled(): void
{
if (!SwooleHelper::isEnabled()) {
$this->expectException(\RuntimeException::class);
$this->expectExceptionMessage('Swoole extension is required');
SwooleHelper::requireSwoole();
} else {
$this->markTestSkipped('Swoole 扩展已安装');
}
}
}协程检测测试
php
<?php
declare(strict_types=1);
namespace Tests\swoole;
use PHPUnit\Framework\TestCase;
use kuiper\swoole\coroutine\Coroutine;
use kuiper\swoole\SwooleHelper;
class CoroutineDetectionTest extends TestCase
{
protected function setUp(): void
{
parent::setUp();
if (!SwooleHelper::isEnabled()) {
$this->markTestSkipped('Swoole 扩展未安装');
}
}
public function testIsEnabledInCoroutine(): void
{
\Swoole\Coroutine\run(function () {
$this->assertTrue(Coroutine::isEnabled());
});
}
public function testIsDisabledOutsideCoroutine(): void
{
$this->assertFalse(Coroutine::isEnabled());
}
public function testGetCoroutineIdInCoroutine(): void
{
\Swoole\Coroutine\run(function () {
$coroutineId = Coroutine::getCoroutineId();
$this->assertGreaterThan(0, $coroutineId);
});
}
public function testGetCoroutineIdOutsideCoroutine(): void
{
$coroutineId = Coroutine::getCoroutineId();
$this->assertSame(0, $coroutineId);
}
}协程测试
上下文管理测试
php
<?php
declare(strict_types=1);
namespace Tests\swoole;
use PHPUnit\Framework\TestCase;
use kuiper\swoole\coroutine\Coroutine;
use kuiper\swoole\SwooleHelper;
class CoroutineContextTest extends TestCase
{
protected function setUp(): void
{
parent::setUp();
if (!SwooleHelper::isEnabled()) {
$this->markTestSkipped('Swoole 扩展未安装');
}
}
public function testGetContext(): void
{
\Swoole\Coroutine\run(function () {
$context = Coroutine::getContext();
$this->assertInstanceOf(\ArrayObject::class, $context);
});
}
public function testContextStorage(): void
{
\Swoole\Coroutine\run(function () {
$context = Coroutine::getContext();
// 存储数据
$context['userId'] = 123;
$context['userName'] = 'John';
// 读取数据
$this->assertSame(123, $context['userId']);
$this->assertSame('John', $context['userName']);
});
}
public function testContextIsolation(): void
{
\Swoole\Coroutine\run(function () {
$parentContext = Coroutine::getContext();
$parentContext['data'] = 'parent';
go(function () {
$childContext = Coroutine::getContext();
$childContext['data'] = 'child';
// 子协程的上下文与父协程相互独立(Swoole 6.2.3 实测,不会继承父协程数据)
$this->assertSame('child', $childContext['data']);
});
\Swoole\Coroutine::sleep(0.001);
// 父协程的上下文未被子协程改动
$this->assertNull($parentContext['data'] ?? null);
});
}
public function testGetOtherCoroutineContext(): void
{
\Swoole\Coroutine\run(function () {
$parentId = Coroutine::getCoroutineId();
Coroutine::getContext()['parentId'] = $parentId;
go(function () use ($parentId) {
$childId = Coroutine::getCoroutineId();
Coroutine::getContext()['childId'] = $childId;
// 获取父协程的上下文
$parentContext = Coroutine::getContext($parentId);
$this->assertSame($parentId, $parentContext['parentId']);
});
});
}
}延迟执行测试
php
<?php
declare(strict_types=1);
namespace Tests\swoole;
use PHPUnit\Framework\TestCase;
use kuiper\swoole\coroutine\Coroutine;
use kuiper\swoole\SwooleHelper;
class CoroutineDeferTest extends TestCase
{
protected function setUp(): void
{
parent::setUp();
if (!SwooleHelper::isEnabled()) {
$this->markTestSkipped('Swoole 扩展未安装');
}
}
public function testDeferExecution(): void
{
\Swoole\Coroutine\run(function () {
$result = [];
Coroutine::defer(function () use (&$result) {
$result[] = 'defer 1';
});
Coroutine::defer(function () use (&$result) {
$result[] = 'defer 2';
});
$result[] = 'main';
// 协程结束时 defer 会被执行
});
// 由于协程已结束,这里无法直接测试
// 需要在协程内部验证
}
public function testDeferExecutionOrder(): void
{
\Swoole\Coroutine\run(function () {
$order = [];
Coroutine::defer(function () use (&$order) {
$order[] = 3;
});
Coroutine::defer(function () use (&$order) {
$order[] = 2;
});
Coroutine::defer(function () use (&$order) {
$order[] = 1;
});
// LIFO 顺序
$this->assertSame([], $order); // defer 还未执行
});
}
}连接池测试
基本连接池测试
php
<?php
declare(strict_types=1);
namespace Tests\swoole;
use PHPUnit\Framework\TestCase;
use kuiper\swoole\pool\DefaultConnectionPool;
use kuiper\swoole\pool\PoolConfig;
use kuiper\swoole\coroutine\Coroutine;
use kuiper\swoole\SwooleHelper;
class ConnectionPoolTest extends TestCase
{
protected function setUp(): void
{
parent::setUp();
if (!SwooleHelper::isEnabled()) {
$this->markTestSkipped('Swoole 扩展未安装');
}
}
public function testCreatePool(): void
{
$config = new PoolConfig([
'min_connections' => 2,
'max_connections' => 5,
]);
$pool = new DefaultConnectionPool(
'test-pool',
function (int $connId) {
return new \stdClass();
},
$config
);
$this->assertSame('test-pool', $pool->getName());
$this->assertSame(2, $pool->getIdleConnections());
$pool->close();
}
public function testTakeAndReleaseConnection(): void
{
\Swoole\Coroutine\run(function () {
$config = new PoolConfig([
'min_connections' => 1,
'max_connections' => 2,
]);
$pool = new DefaultConnectionPool(
'test-pool',
function (int $connId) {
return new \stdClass();
},
$config
);
// 获取连接
$connection = $pool->take();
$this->assertSame(1, $pool->getActiveConnections());
$this->assertSame(0, $pool->getIdleConnections());
// 释放连接
$pool->release($connection);
$this->assertSame(0, $pool->getActiveConnections());
$this->assertSame(1, $pool->getIdleConnections());
$pool->close();
});
}
public function testAutoReleaseInCoroutine(): void
{
\Swoole\Coroutine\run(function () {
$config = new PoolConfig([
'min_connections' => 1,
'max_connections' => 2,
]);
$pool = new DefaultConnectionPool(
'test-pool',
function (int $connId) {
return new \stdClass();
},
$config
);
// 获取连接
$connection = $pool->take();
$this->assertSame(1, $pool->getActiveConnections());
// 协程结束时会自动释放
});
// 协程结束后连接应该被释放
}
public function testConnectionReuse(): void
{
\Swoole\Coroutine\run(function () {
$config = new PoolConfig([
'min_connections' => 1,
'max_connections' => 2,
]);
$createdConnections = 0;
$pool = new DefaultConnectionPool(
'test-pool',
function (int $connId) use (&$createdConnections) {
$createdConnections++;
return new \stdClass();
},
$config
);
// 初始化时创建 1 个连接
$this->assertSame(1, $createdConnections);
// 获取连接
$conn1 = $pool->take();
$this->assertSame(1, $createdConnections);
// 释放连接
$pool->release($conn1);
// 再次获取连接,应该复用
$conn2 = $pool->take();
$this->assertSame(1, $createdConnections); // 没有创建新连接
$this->assertSame($conn1, $conn2); // 同一个连接
$pool->close();
});
}
}连接池超时测试
php
<?php
declare(strict_types=1);
namespace Tests\swoole;
use PHPUnit\Framework\TestCase;
use kuiper\swoole\pool\DefaultConnectionPool;
use kuiper\swoole\pool\PoolConfig;
use kuiper\swoole\exception\PoolTimeoutException;
use kuiper\swoole\coroutine\Coroutine;
use kuiper\swoole\SwooleHelper;
class ConnectionPoolTimeoutTest extends TestCase
{
protected function setUp(): void
{
parent::setUp();
if (!SwooleHelper::isEnabled()) {
$this->markTestSkipped('Swoole 扩展未安装');
}
}
public function testWaitTimeout(): void
{
\Swoole\Coroutine\run(function () {
$config = new PoolConfig([
'min_connections' => 1,
'max_connections' => 1,
'wait_timeout' => 0.1, // 100ms 超时
]);
$pool = new DefaultConnectionPool(
'test-pool',
function (int $connId) {
return new \stdClass();
},
$config
);
// 获取唯一的连接
$conn1 = $pool->take();
// 尝试获取第二个连接(会超时)
try {
$conn2 = $pool->take();
$this->fail('应该抛出超时异常');
} catch (PoolTimeoutException $e) {
$this->assertInstanceOf(PoolTimeoutException::class, $e);
}
$pool->close();
});
}
}连接池并发测试
php
<?php
declare(strict_types=1);
namespace Tests\swoole;
use PHPUnit\Framework\TestCase;
use kuiper\swoole\pool\DefaultConnectionPool;
use kuiper\swoole\pool\PoolConfig;
use kuiper\swoole\coroutine\Coroutine;
use kuiper\swoole\SwooleHelper;
class ConnectionPoolConcurrencyTest extends TestCase
{
protected function setUp(): void
{
parent::setUp();
if (!SwooleHelper::isEnabled()) {
$this->markTestSkipped('Swoole 扩展未安装');
}
}
public function testConcurrentAccess(): void
{
\Swoole\Coroutine\run(function () {
$config = new PoolConfig([
'min_connections' => 2,
'max_connections' => 5,
]);
$pool = new DefaultConnectionPool(
'test-pool',
function (int $connId) {
return new \stdClass();
},
$config
);
$results = [];
$channel = new \Swoole\Coroutine\Channel(10);
// 启动 10 个协程并发获取连接
for ($i = 0; $i < 10; $i++) {
go(function () use ($pool, $i, $channel) {
$conn = $pool->take();
$results[] = $i;
\Swoole\Coroutine::sleep(0.01);
$pool->release($conn);
$channel->push(true);
});
}
// 等待所有协程完成
for ($i = 0; $i < 10; $i++) {
$channel->pop();
}
$this->assertCount(10, $results);
$pool->close();
});
}
public function testMaxConnectionsLimit(): void
{
\Swoole\Coroutine\run(function () {
$config = new PoolConfig([
'min_connections' => 1,
'max_connections' => 3,
]);
$createdConnections = 0;
$pool = new DefaultConnectionPool(
'test-pool',
function (int $connId) use (&$createdConnections) {
$createdConnections++;
return new \stdClass();
},
$config
);
// 初始连接数
$initial = $createdConnections;
// 获取所有连接
$conn1 = $pool->take();
$conn2 = $pool->take();
$conn3 = $pool->take();
// 最多创建 max_connections 个连接
$this->assertLessThanOrEqual(3, $createdConnections);
$this->assertGreaterThanOrEqual($initial, $createdConnections);
$pool->release($conn1);
$pool->release($conn2);
$pool->release($conn3);
$pool->close();
});
}
}并发测试
并发原语测试
php
<?php
declare(strict_types=1);
namespace Tests\swoole;
use PHPUnit\Framework\TestCase;
use kuiper\swoole\concurrency\ConcurrencyFactory;
use kuiper\swoole\coroutine\Coroutine;
use kuiper\swoole\SwooleHelper;
use Swoole\Coroutine\Lock;
use Swoole\Coroutine\Channel;
class ConcurrencyPrimitiveTest extends TestCase
{
protected function setUp(): void
{
parent::setUp();
if (!SwooleHelper::isEnabled()) {
$this->markTestSkipped('Swoole 扩展未安装');
}
}
public function testLock(): void
{
\Swoole\Coroutine\run(function () {
$lock = new Lock();
$result = [];
// 协程 1
go(function () use ($lock, &$result) {
$lock->lock();
$result[] = 'lock 1';
\Swoole\Coroutine::sleep(0.01);
$result[] = 'unlock 1';
$lock->unlock();
});
// 协程 2
go(function () use ($lock, &$result) {
\Swoole\Coroutine::sleep(0.005);
$result[] = 'wait 2';
$lock->lock();
$result[] = 'lock 2';
$lock->unlock();
});
\Swoole\Coroutine::sleep(0.02);
// 验证锁的正确性
$this->assertContains('lock 1', $result);
$this->assertContains('unlock 1', $result);
$this->assertContains('wait 2', $result);
});
}
public function testCounter(): void
{
\Swoole\Coroutine\run(function () {
// Swoole\Coroutine\Counter 在 Swoole 5.x 后已移除,
// 使用模块提供的基于 \Swoole\Atomic 的计数器
$counter = ConcurrencyFactory::createCounter(0);
$done = new Channel(3);
$results = [];
for ($i = 1; $i <= 3; $i++) {
go(function () use ($i, $counter, $done, &$results) {
\Swoole\Coroutine::sleep(0.01);
$results[] = $i;
$counter->add();
$done->push(true);
});
}
// 等待 3 个协程完成
for ($i = 0; $i < 3; $i++) {
$done->pop(1.0);
}
$this->assertSame(3, $counter->get());
$this->assertCount(3, $results);
$this->assertContains(1, $results);
$this->assertContains(2, $results);
$this->assertContains(3, $results);
});
}
}测试最佳实践
1. 使用协程包装测试
php
// ✅ 在协程环境中运行测试
public function testSomethingInCoroutine(): void
{
\Swoole\Coroutine\run(function () {
// 测试代码
$this->assertTrue(Coroutine::isEnabled());
});
}
// ❌ 不要在协程外测试协程功能
public function testSomethingOutsideCoroutine(): void
{
$this->assertFalse(Coroutine::isEnabled()); // 只能测试非协程环境
}2. 清理资源
php
// ✅ 在测试后清理资源
public function testPool(): void
{
\Swoole\Coroutine\run(function () {
$pool = new DefaultConnectionPool(...);
// 测试代码
$pool->close(); // 清理资源
});
}
// ❌ 不要忘记清理资源
public function testPool(): void
{
\Swoole\Coroutine\run(function () {
$pool = new DefaultConnectionPool(...);
// 测试代码,但忘记关闭连接池
});
}3. 使用数据提供器
php
// ✅ 使用数据提供器测试多种场景
/**
* @return array<array{int, int}>
*/
public static function poolConfigProvider(): array
{
return [
[1, 5],
[2, 10],
[5, 20],
];
}
/**
* @dataProvider poolConfigProvider
*/
public function testPoolWithDifferentConfigs(int $min, int $max): void
{
\Swoole\Coroutine\run(function () use ($min, $max) {
$config = new PoolConfig([
'min_connections' => $min,
'max_connections' => $max,
]);
$pool = new DefaultConnectionPool('test', fn() => new \stdClass(), $config);
$this->assertGreaterThanOrEqual($min, $pool->getIdleConnections());
$pool->close();
});
}4. 超时处理
php
// ✅ 设置合理的超时
public function testWithTimeout(): void
{
\Swoole\Coroutine\run(function () {
$config = new PoolConfig([
'wait_timeout' => 0.1, // 100ms 超时
]);
$pool = new DefaultConnectionPool('test', fn() => new \stdClass(), $config);
try {
// 可能超时的操作
$conn = $pool->take();
} catch (PoolTimeoutException $e) {
// 处理超时
$this->assertInstanceOf(PoolTimeoutException::class, $e);
}
$pool->close();
});
}运行测试
运行所有 Swoole 测试
bash
# 运行所有 Swoole 测试
./vendor/bin/phpunit tests/swoole
# 运行特定测试文件
./vendor/bin/phpunit tests/swoole/ConnectionPoolTest.php
# 运行特定测试方法
./vendor/bin/phpunit --filter testTakeAndReleaseConnection tests/swoole/ConnectionPoolTest.php
# 生成代码覆盖率报告
./vendor/bin/phpunit --coverage-html coverage/ tests/swoole在协程环境中运行测试
bash
# 使用 Swoole 测试运行器
php -d swoole.enable_coroutine=on ./vendor/bin/phpunit tests/swoole测试注意事项
1. 协程环境检测
php
// 在测试前检查环境
protected function setUp(): void
{
parent::setUp();
if (!Coroutine::isEnabled()) {
$this->markTestSkipped('需要在协程环境中运行');
}
}2. 资源清理
php
// 使用 tearDown 清理资源
protected function tearDown(): void
{
parent::tearDown();
// 清理连接池
if (isset($this->pool)) {
$this->pool->close();
}
}3. 并发测试的同步
php
// 使用 Channel 同步协程;Swoole\Coroutine\Counter 已移除,
// 需要计数时用 ConcurrencyFactory::createCounter()(基于 \Swoole\Atomic)
public function testConcurrentOperation(): void
{
\Swoole\Coroutine\run(function () {
$channel = new \Swoole\Coroutine\Channel(10);
for ($i = 0; $i < 10; $i++) {
go(function () use ($channel) {
// 执行操作
$channel->push(true);
});
}
// 等待所有协程完成
for ($i = 0; $i < 10; $i++) {
$channel->pop();
}
});
}