refactor phpunit-swoole to phpunit-zm and move old test cases

This commit is contained in:
crazywhalecc
2022-08-20 17:49:33 +08:00
parent cecdb1681c
commit 4ba74e9f3e
23 changed files with 188 additions and 128 deletions

279
tests_old/ZM/API/CQTest.php Normal file
View File

@@ -0,0 +1,279 @@
<?php
declare(strict_types=1);
namespace Tests\ZM\API;
use PHPUnit\Framework\TestCase;
use ZM\API\CQ;
/**
* @internal
*/
class CQTest extends TestCase
{
/**
* @dataProvider providerShare
* @param mixed $url
* @param mixed $title
* @param mixed $content
* @param mixed $image
* @param mixed $expected
*/
public function testShare($url, $title, $content, $image, $expected)
{
$this->assertEquals($expected, CQ::share($url, $title, $content, $image));
}
public function providerShare(): array
{
return [
'all' => [
'https://www.baidu.com',
'hello',
'world',
'https://www.baidu.com/img/bd_logo1.png',
'[CQ:share,url=https://www.baidu.com,title=hello,content=world,image=https://www.baidu.com/img/bd_logo1.png]',
],
'url title' => [
'https://www.baidu.com',
'123',
null,
null,
'[CQ:share,url=https://www.baidu.com,title=123]',
],
'url title content' => [
'https://www.baidu.com',
'123',
'456',
null,
'[CQ:share,url=https://www.baidu.com,title=123,content=456]',
],
];
}
public function testShake()
{
$this->assertEquals('[CQ:shake]', CQ::shake());
}
public function testLocation()
{
$this->assertEquals('[CQ:location,lat=23.137466,lon=113.352425]', CQ::location(23.137466, 113.352425));
}
public function testVideo()
{
$this->assertEquals('[CQ:video,file=https://www.baidu.com,cache=0,proxy=false,timeout=20]', CQ::video('https://www.baidu.com', false, false, 20));
}
public function testContact()
{
$this->assertEquals('[CQ:contact,type=qq,id=123456789]', CQ::contact('qq', '123456789'));
}
public function testForward()
{
$this->assertEquals('[CQ:forward,id=123456789]', CQ::forward(123456789));
}
public function testAnonymous()
{
$this->assertEquals('[CQ:anonymous,ignore=0]', CQ::anonymous(0));
}
public function testCustom()
{
$this->assertEquals('[CQ:test,type=test,data=hello]', CQ::_custom('test', ['type' => 'test', 'data' => 'hello']));
}
public function testEscape()
{
$this->assertEquals('hello&#91;&#93;,', CQ::escape('hello[],'));
}
/**
* @dataProvider providerMusic
* @param mixed $data
* @param mixed $expected
*/
public function testMusic($data, $expected)
{
$this->assertEquals($expected, CQ::music(...$data));
}
public function providerMusic(): array
{
return [
'music qq' => [
['qq', '123456789'],
'[CQ:music,type=qq,id=123456789]',
],
'music 163' => [
['163', '123456789'],
'[CQ:music,type=163,id=123456789]',
],
'music xiami' => [
['xiami', '123456789'],
'[CQ:music,type=xiami,id=123456789]',
],
'music custom' => [
['custom', '123456789'],
' ',
],
'music custom url audio title' => [
['custom', '123456789', 'test', 'test1'],
'[CQ:music,type=custom,url=123456789,audio=test,title=test1]',
],
'music custom url audio title content' => [
['custom', '123456789', 'test', 'test1', 'test2'],
'[CQ:music,type=custom,url=123456789,audio=test,title=test1,content=test2]',
],
'music custom url audio title content image' => [
['custom', '123456789', 'test', 'test1', 'test2', 'test3'],
'[CQ:music,type=custom,url=123456789,audio=test,title=test1,content=test2,image=test3]',
],
'music custom test' => [
['custom test', '123456789', 'test', 'test1', 'test2', 'test3'],
' ',
],
];
}
public function testPoke()
{
$this->assertEquals('[CQ:poke,type=id,id=123456789]', CQ::poke('id', '123456789'));
}
public function testJson()
{
$this->assertEquals('[CQ:json,data={"a":"b&#91;"},resid=1]', CQ::json(json_encode(['a' => 'b[']), 1));
}
public function testEncode()
{
$this->assertEquals('hello&#91;&#93;,', CQ::encode('hello[],'));
}
public function testDice()
{
$this->assertEquals('[CQ:dice]', CQ::dice());
}
public function testRecord()
{
$this->assertEquals('[CQ:record,file=https://www.baidu.com,cache=0]', CQ::record('https://www.baidu.com', false, false));
}
public function testDecode()
{
$this->assertEquals('hello[],', CQ::decode('hello&#91;&#93;,'));
}
/**
* @dataProvider providerRemoveCQ
* @param mixed $msg
* @param mixed $expected
*/
public function testRemoveCQ($msg, $expected)
{
$this->assertEquals($expected, CQ::removeCQ($msg));
}
public function providerRemoveCQ(): array
{
return [
'remove cq 1' => ['hello[CQ:at,qq=123456789],', 'hello,'],
'remove cq 2' => ['hello[CQ:at,qq=123456789,', 'hello[CQ:at,qq=123456789,'],
'remove cq 3' => ['[CQ:dice]hello[CQ:at,qq=123456789]', 'hello'],
];
}
public function testGetAllCQ()
{
$array = CQ::getAllCQ('[CQ:dice][CQ:at,qq=123456789]');
$this->assertEquals([
[
'type' => 'dice',
'start' => 0,
'end' => 8,
],
[
'type' => 'at',
'params' => [
'qq' => '123456789',
],
'start' => 9,
'end' => 28,
],
], $array);
}
/**
* @dataProvider providerGetCQ
* @param mixed $cq
* @param mixed $expected
*/
public function testGetCQ($cq, $expected)
{
$this->assertEquals($expected, CQ::getCQ($cq));
}
public function providerGetCQ(): array
{
return [
'one dice' => ['[CQ:dice]', [
'type' => 'dice',
'start' => 0,
'end' => 8,
]],
'one at' => ['[CQ:at,qq=123456789]', [
'type' => 'at',
'params' => [
'qq' => '123456789',
],
'start' => 0,
'end' => 19,
]],
'invalid cq 1' => ['[CQ:at,qq=123456789', null],
'invalid cq 2' => ['[CQ;at,qq=123456789]', null],
];
}
public function testImage()
{
$this->assertEquals('[CQ:image,file=https://www.baidu.com]', CQ::image('https://www.baidu.com'));
}
public function testRps()
{
$this->assertEquals('[CQ:rps]', CQ::rps());
}
public function testReplace()
{
$this->assertEquals('[]', CQ::replace('{{}}'));
}
public function testAt()
{
$this->assertEquals('[CQ:at,qq=123456789]', CQ::at('123456789'));
$this->assertEquals(' ', CQ::at(null));
}
public function testXml()
{
$this->assertEquals('[CQ:xml,data=<xml></xml>]', CQ::xml('<xml></xml>'));
}
public function testFace()
{
$this->assertEquals('[CQ:face,id=1]', CQ::face(1));
$this->assertEquals(' ', CQ::face(null));
}
public function testNode()
{
$this->assertEquals('[CQ:node,user_id=test,nickname=content,content=blah]', CQ::node('test', 'content', 'blah'));
}
}

View File

@@ -0,0 +1,164 @@
<?php
declare(strict_types=1);
namespace Tests\ZM\Config;
use PHPUnit\Framework\TestCase;
use ZM\Config\ZMConfig;
use ZM\Console\Console;
use ZM\Exception\ConfigException;
use ZM\Utils\DataProvider;
/**
* @internal
*/
class ZMConfigTest extends TestCase
{
public static function setUpBeforeClass(): void
{
$mock_dir = __DIR__ . '/config_mock';
ZMConfig::reload();
ZMConfig::setDirectory(__DIR__ . '/config_mock');
if (!is_dir($mock_dir)) {
mkdir($mock_dir, 0755, true);
}
// 下方测试需要临时写入的文件
file_put_contents($mock_dir . '/global.patch.php', '<?php return ["port" => 30055];');
file_put_contents($mock_dir . '/php_exception.php', '<?php return true;');
file_put_contents($mock_dir . '/json_exception.json', '"string"');
file_put_contents($mock_dir . '/global.development.patch.php', '<?php return ["port" => 30055];');
file_put_contents($mock_dir . '/global.invalid.development.php', '<?php return ["port" => 30055];');
file_put_contents($mock_dir . '/fake.development.json', '{"multi":{"level":"test"}}');
file_put_contents($mock_dir . '/no_main_only_patch.patch.json', '{"multi":{"level":"test"}}');
}
public static function tearDownAfterClass(): void
{
ZMConfig::reload();
ZMConfig::restoreDirectory();
foreach (DataProvider::scanDirFiles(__DIR__ . '/config_mock', true, false) as $file) {
unlink($file);
}
rmdir(__DIR__ . '/config_mock');
}
/**
* @throws ConfigException
*/
public function testReload()
{
$this->markTestIncomplete('logger level change in need');
$this->expectOutputRegex('/没读取过,正在从文件加载/');
$this->assertEquals('0.0.0.0', ZMConfig::get('global.host'));
ZMConfig::reload();
Console::setLevel(4);
$this->assertEquals('0.0.0.0', ZMConfig::get('global.host'));
Console::setLevel(0);
}
public function testSetAndRestoreDirectory()
{
$origin = ZMConfig::getDirectory();
ZMConfig::setDirectory('.');
$this->assertEquals('.', ZMConfig::getDirectory());
ZMConfig::restoreDirectory();
$this->assertEquals($origin, ZMConfig::getDirectory());
}
public function testSetAndGetEnv()
{
$this->expectException(ConfigException::class);
ZMConfig::setEnv('production');
$this->assertEquals('production', ZMConfig::getEnv());
ZMConfig::setEnv();
ZMConfig::setEnv('reee');
}
/**
* @dataProvider providerTestGet
* @param mixed $expected
* @throws ConfigException
*/
public function testGet(array $data_params, $expected)
{
$this->assertEquals($expected, ZMConfig::get(...$data_params));
}
public function providerTestGet(): array
{
return [
'get port' => [['global.port'], 30055],
'get port key 2' => [['global', 'port'], 30055],
'get invalid key' => [['global', 'invalid'], null],
'get another environment' => [['fake.multi.level'], 'test'],
];
}
public function testGetPhpException()
{
$this->expectException(ConfigException::class);
ZMConfig::get('php_exception');
}
public function testGetJsonException()
{
$this->expectException(ConfigException::class);
ZMConfig::get('json_exception');
}
public function testOnlyPatchException()
{
$this->expectException(ConfigException::class);
ZMConfig::get('no_main_only_patch.test');
}
public function testSmartPatch()
{
$array = [
'key-1-1' => 'value-1-1',
'key-1-2' => [
'key-2-1' => [
'key-3-1' => [
'value-3-1',
'value-3-2',
],
],
],
'key-1-3' => [
'key-4-1' => 'value-4-1',
],
];
$patch = [
'key-1-2' => [
'key-2-1' => [
'key-3-1' => [
'value-3-3',
],
],
],
'key-1-3' => [
'key-4-2' => [
'key-5-1' => 'value-5-1',
],
],
];
$expected = [
'key-1-1' => 'value-1-1',
'key-1-2' => [
'key-2-1' => [
'key-3-1' => [
'value-3-3',
],
],
],
'key-1-3' => [
'key-4-1' => 'value-4-1',
'key-4-2' => [
'key-5-1' => 'value-5-1',
],
],
];
$this->assertEquals($expected, ZMConfig::smartPatch($array, $patch));
}
}

View File

@@ -0,0 +1,130 @@
<?php
declare(strict_types=1);
namespace Tests\ZM\Container;
use PHPUnit\Framework\TestCase;
use ZM\Container\Container;
/**
* @internal
*/
class ContainerCallTest extends TestCase
{
public function testCallInvokableClass(): void
{
$container = new Container();
$this->assertEquals('foo', $container->call(Invokable::class, ['echo' => 'foo']));
}
public function testCallClassMethodWithDependencies(): void
{
$container = new Container();
$name = 'Steve' . time();
$container->bind(FooDependency::class, FooDependencyImpl::class);
$container->bind(BarDependency::class, function () use ($name) {
return new BarDependencyImpl($name);
});
$this->assertEquals("hello, {$name}", $container->call([Foo::class, 'sayHello']));
}
public function testCallClassStaticMethodWithDependencies(): void
{
$container = new Container();
$name = 'Alex' . time();
$container->bind(FooDependency::class, FooDependencyImpl::class);
$container->bind(BarDependency::class, function () use ($name) {
return new BarDependencyImpl($name);
});
$this->assertEquals("hello, {$name}", $container->call([Foo::class, 'staticSayHello']));
}
public function testCallClassMethodWithDependenciesInjectedByConstructor(): void
{
$container = new Container();
$name = 'Donny' . time();
$container->bind(FooDependency::class, FooDependencyImpl::class);
$container->bind(BarDependency::class, function () use ($name) {
return new BarDependencyImpl($name);
});
$this->assertEquals('goodbye', $container->call([Foo::class, 'sayGoodbye']));
}
public function testCallClassStaticMethodViaDoubleColons(): void
{
$container = new Container();
$name = 'Herobrine' . time();
$container->bind(FooDependency::class, FooDependencyImpl::class);
$container->bind(BarDependency::class, function () use ($name) {
return new BarDependencyImpl($name);
});
$this->assertEquals("hello, {$name}", $container->call(Foo::class . '::staticSayHello'));
}
}
class Invokable
{
public function __invoke(string $echo)
{
return $echo;
}
}
interface FooDependency
{
public function sayGoodbye(): string;
}
class FooDependencyImpl implements FooDependency
{
public function sayGoodbye(): string
{
return 'goodbye';
}
}
interface BarDependency
{
public function getName(): string;
}
class BarDependencyImpl implements BarDependency
{
private $name;
public function __construct(string $name)
{
$this->name = $name;
}
public function getName(): string
{
return $this->name;
}
}
class Foo
{
private $fooDependency;
public function __construct(FooDependency $fooDependency)
{
$this->fooDependency = $fooDependency;
}
public function sayHello(BarDependency $barDependency): string
{
return 'hello, ' . $barDependency->getName();
}
public static function staticSayHello(BarDependency $barDependency): string
{
return 'hello, ' . $barDependency->getName();
}
public function sayGoodbye(): string
{
return $this->fooDependency->sayGoodbye();
}
}

View File

@@ -0,0 +1,52 @@
<?php
declare(strict_types=1);
namespace Tests\ZM\Container;
use PHPUnit\Framework\TestCase;
use ZM\Container\Container;
use ZM\Container\WorkerContainer;
/**
* @internal
*/
class ContainerTest extends TestCase
{
public function testCanInheritParentBinding(): void
{
$worker_container = new WorkerContainer();
$worker_container->instance('foo', 'bar');
$container = new Container();
$container->instance('baz', 'qux');
// 获取父容器的实例
$this->assertEquals('bar', $container->get('foo'));
// 获取自身容器的实例
$this->assertEquals('qux', $container->get('baz'));
}
public function testCanOverrideParentBinding(): void
{
$worker_container = new WorkerContainer();
$worker_container->instance('foo', 'bar');
$container = new Container();
$container->instance('foo', 'qux');
$this->assertEquals('qux', $container->get('foo'));
}
public function testCannotModifyParentBinding(): void
{
$worker_container = new WorkerContainer();
$worker_container->instance('foo', 'bar');
$container = new Container();
$container->instance('foo', 'qux');
$this->assertEquals('bar', $worker_container->get('foo'));
}
}

View File

@@ -0,0 +1,120 @@
<?php
declare(strict_types=1);
namespace Tests\ZM\Container;
use PHPUnit\Framework\TestCase;
use ZM\Container\EntryResolutionException;
use ZM\Container\WorkerContainer;
use ZM\Utils\MessageUtil;
/**
* @internal
*/
class WorkerContainerTest extends TestCase
{
private $container;
protected function setUp(): void
{
$this->container = new WorkerContainer();
$this->container->flush();
}
public function testInstance(): void
{
$this->container->instance('test', 'test');
$this->assertEquals('test', $this->container->make('test'));
$t2 = new WorkerContainer();
$this->assertEquals('test', $t2->make('test'));
}
public function testAlias(): void
{
$this->container->alias(MessageUtil::class, 'bar');
$this->container->alias('bar', 'baz');
$this->container->alias('baz', 'bas');
$this->assertInstanceOf(MessageUtil::class, $this->container->make('bas'));
}
public function testGetAlias(): void
{
$this->container->alias(MessageUtil::class, 'bar');
$this->assertEquals(MessageUtil::class, $this->container->getAlias('bar'));
}
public function testBindClosure(): void
{
$this->container->bind('test', function () {
return 'test';
});
$this->assertEquals('test', $this->container->make('test'));
}
public function testFlush(): void
{
$this->container->bind('test', function () {
return 'test';
});
$this->container->flush();
$this->expectException(EntryResolutionException::class);
$this->container->make('test');
}
public function testBindIf(): void
{
$this->container->bind('test', function () {
return 'test';
});
$this->container->bindIf('test', function () {
return 'test2';
});
$this->assertEquals('test', $this->container->make('test'));
}
public function testGet(): void
{
$this->testMake();
}
public function testBound(): void
{
$this->container->bind('test', function () {
return 'test';
});
$this->assertTrue($this->container->bound('test'));
$this->assertFalse($this->container->bound('test2'));
}
public function testFactory(): void
{
$this->container->bind('test', function () {
return 'test';
});
$factory = $this->container->factory('test');
$this->assertEquals($this->container->make('test'), $factory());
}
public function testMake(): void
{
$this->container->bind('test', function () {
return 'test';
});
$this->assertEquals('test', $this->container->make('test'));
}
public function testHas(): void
{
$this->testBound();
}
public function testBuild(): void
{
$this->assertEquals('test', $this->container->build(function () {
return 'test';
}));
$this->assertInstanceOf(MessageUtil::class, $this->container->build(MessageUtil::class));
}
}

View File

@@ -0,0 +1,31 @@
<?php
declare(strict_types=1);
namespace Tests\ZM\Event;
use Module\Example\Hello;
use PHPUnit\Framework\TestCase;
use ZM\Annotation\CQ\CommandArgument;
use ZM\Event\EventMapIterator;
/**
* @internal
*/
class EventMapIteratorTest extends TestCase
{
public function testIterator(): void
{
$iterator = new EventMapIterator(Hello::class, 'randNum', CommandArgument::class);
$arr = iterator_to_array($iterator);
$this->assertArrayNotHasKey(0, $arr);
$this->assertArrayNotHasKey(1, $arr);
$this->assertArrayHasKey(2, $arr);
$this->assertArrayHasKey(3, $arr);
$this->assertInstanceOf(CommandArgument::class, $arr[2]);
$this->assertInstanceOf(CommandArgument::class, $arr[3]);
$iterator = new EventMapIterator(Hello::class, 'closeUnknownConn', CommandArgument::class);
$ls = iterator_to_array($iterator);
$this->assertCount(0, $ls);
}
}

View File

@@ -0,0 +1,79 @@
<?php
declare(strict_types=1);
namespace Tests\ZM;
use PHPUnit\Framework\TestCase;
/**
* @internal
*/
class GlobalFunctionsTest extends TestCase
{
public function testChain(): void
{
$mock = $this->getMockBuilder(\stdClass::class)
->addMethods(['foo', 'bar', 'baz'])
->getMock();
$mock->expects($this->once())
->method('foo')
->willReturn('foo');
$mock->expects($this->once())
->method('bar')
->with('foo')
->willReturn('bar');
$mock->expects($this->once())
->method('baz')
->with('bar')
->willReturn('baz');
$result = chain($mock)->foo()->bar(CARRY)->baz(CARRY);
$this->assertEquals('baz', $result);
}
public function testStopwatch(): void
{
$time = stopwatch(static function () {
usleep(10000);
});
$this->assertLessThan(0.1, $time);
}
/**
* @dataProvider providerTestMatchPattern
*/
public function testMatchPattern(string $pattern, string $subject, bool $expected): void
{
$this->assertEquals($expected, match_pattern($pattern, $subject));
}
public function providerTestMatchPattern(): array
{
return [
'empty' => ['', '', true],
'empty subject' => ['foo', '', false],
'empty pattern' => ['', 'foo', false],
'simple' => ['foo', 'foo', true],
'simple case insensitive' => ['FOO', 'foo', true],
'simple case insensitive 2' => ['foo', 'FOO', true],
'unicode' => ['föö', 'föö', true],
'chinese' => ['中文', '中文', true],
'wildcard' => ['foo*', 'foo', true],
'wildcard 2' => ['foo*', 'foobar', true],
'wildcard 3' => ['foo*bar', 'foo with bar', true],
'wildcard 4' => ['foo*bar', 'foo but no bar with it', false],
'wildcard with chinese' => ['中文*', '中文', true],
'wildcard with chinese 2' => ['全世界*中国话', '全世界都在说中国话', true],
'complex' => ['foo*bar*baz', 'foo with bar and baz', true],
'regex' => ['[a-z]+', 'foo', false], // regex is not supported yet
'escaped' => ['foo\\*bar', 'foo*bar', true],
];
}
public function testZmExec(): void
{
$this->assertEquals(['code' => 0, 'signal' => 0, 'output' => "foo\n"], zm_exec('echo foo'));
}
}

View File

@@ -0,0 +1,84 @@
<?php
declare(strict_types=1);
namespace Tests\ZM\Store;
use PHPUnit\Framework\TestCase;
use ZM\Store\LightCache;
/**
* @internal
*/
class LightCacheTest extends TestCase
{
protected function tearDown(): void
{
LightCache::unset('test');
LightCache::unset('test2');
}
public function testSetAndGet(): void
{
$result = LightCache::set('test', 'value');
$this->assertTrue($result);
$this->assertSame('value', LightCache::get('test'));
}
public function testUnset(): void
{
LightCache::set('test', 'value');
$this->assertTrue(LightCache::unset('test'));
$this->assertNull(LightCache::get('test'));
$this->assertFalse(LightCache::unset('test'));
}
public function testGetAll(): void
{
LightCache::set('test', 'value');
LightCache::set('test2', 'value2');
$this->assertSame(['test' => 'value', 'test2' => 'value2'], LightCache::getAll());
}
public function testItemCanExpire(): void
{
LightCache::set('test', 'value', 1);
$this->assertSame('value', LightCache::get('test'));
zm_sleep(2);
$this->assertNull(LightCache::get('test'));
}
public function testGetExpire(): void
{
LightCache::set('test', 'value', 10);
$this->assertSame(10, LightCache::getExpire('test'));
}
public function testGetExpireTS(): void
{
LightCache::set('test', 'value', 10);
$this->assertSame(time() + 10, LightCache::getExpireTS('test'));
}
public function testIsset(): void
{
LightCache::set('test', 'value');
$this->assertTrue(LightCache::isset('test'));
$this->assertFalse(LightCache::isset('test2'));
}
public function testGetMemoryUsage(): void
{
LightCache::set('test', 'value');
$this->assertGreaterThan(0, LightCache::getMemoryUsage());
}
public function testUpdate(): void
{
LightCache::set('test', 'value');
$this->assertTrue(LightCache::update('test', 'value2'));
$this->assertSame('value2', LightCache::get('test'));
}
}

View File

@@ -0,0 +1,71 @@
<?php
declare(strict_types=1);
namespace Tests\ZM\Utils;
use PHPUnit\Framework\TestCase;
use ZM\Annotation\CQ\CommandArgument;
use ZM\Annotation\CQ\CQCommand;
use ZM\Event\EventManager;
use ZM\Utils\CommandInfoUtil;
/**
* @internal
*/
class CommandInfoUtilTest extends TestCase
{
/**
* @var CommandInfoUtil
*/
private static $util;
/**
* @var string
*/
private static $command_id;
public static function setUpBeforeClass(): void
{
$cmd = new CQCommand('测试命令');
$cmd->class = self::class;
$cmd->method = __FUNCTION__;
$args = [
new CommandArgument('文本', '一个神奇的文本', 'string', true),
new CommandArgument('数字', '一个神奇的数字', 'int', false, '', '233'),
];
self::$command_id = "{$cmd->class}@{$cmd->method}";
EventManager::$events[CQCommand::class] = [];
EventManager::$event_map = [];
EventManager::addEvent(CQCommand::class, $cmd);
EventManager::$event_map[$cmd->class][$cmd->method] = $args;
self::$util = resolve(CommandInfoUtil::class);
}
public function testGet(): void
{
$commands = self::$util->get();
$this->assertIsArray($commands);
$this->assertCount(1, $commands);
$this->assertArrayHasKey(self::$command_id, $commands);
}
public function testGetHelp(): void
{
$help = self::$util->getHelp(self::$command_id);
$this->assertIsString($help);
$this->assertNotEmpty($help);
$expected = <<<'EOF'
测试命令 <文本: string> [数字: number = 233]
作者很懒,啥也没说
文本;一个神奇的文本
数字;一个神奇的数字
EOF;
$this->assertEquals($expected, $help);
}
}

View File

@@ -0,0 +1,70 @@
<?php
declare(strict_types=1);
namespace Tests\ZM\Utils;
use PHPUnit\Framework\TestCase;
use ZM\Utils\DataProvider;
/**
* @internal
*/
class DataProviderTest extends TestCase
{
public function testGetSourceRootDir(): void
{
$this->assertEquals(SOURCE_ROOT_DIR, DataProvider::getSourceRootDir());
}
public function testGetDataFolder(): void
{
$this->assertEquals(SOURCE_ROOT_DIR . '/zm_data/', DataProvider::getDataFolder());
}
public function testGetResourceFolder(): void
{
$this->assertEquals(SOURCE_ROOT_DIR . '/resources/', DataProvider::getResourceFolder());
}
public function testScanDirFiles(): void
{
$files = DataProvider::scanDirFiles(SOURCE_ROOT_DIR . '/src/Module');
$this->assertContains(SOURCE_ROOT_DIR . '/src/Module/Example/Hello.php', $files);
}
public function testGetFrameworkRootDir(): void
{
$this->assertEquals(FRAMEWORK_ROOT_DIR, DataProvider::getFrameworkRootDir());
}
public function testGetWorkingDir(): void
{
$this->assertEquals(SOURCE_ROOT_DIR, DataProvider::getWorkingDir());
}
public function testSaveLoadJson(): void
{
$data = [
'a' => 1,
'b' => 2,
'c' => 3,
];
$file = 'test.json';
DataProvider::saveToJson($file, $data);
$this->assertEquals($data, DataProvider::loadFromJson($file));
}
public function testGetFrameworkLink(): void
{
$this->assertNotFalse(filter_var(DataProvider::getFrameworkLink(), FILTER_VALIDATE_URL));
}
public function testIsRelativePath(): void
{
$this->assertTrue(DataProvider::isRelativePath('./'));
$this->assertTrue(DataProvider::isRelativePath('../'));
$this->assertFalse(DataProvider::isRelativePath('/'));
$this->assertTrue(DataProvider::isRelativePath('test.php'));
}
}

View File

@@ -0,0 +1,57 @@
<?php
declare(strict_types=1);
namespace Tests\ZM\Utils;
use PHPUnit\Framework\TestCase;
use Swoole\Http\Request;
use Symfony\Component\Routing\RouteCollection;
use ZM\Annotation\Http\RequestMapping;
use ZM\Annotation\Http\RequestMethod;
use ZM\Utils\HttpUtil;
use ZM\Utils\Manager\RouteManager;
/**
* @internal
*/
class HttpUtilTest extends TestCase
{
public function providerTestHandleStaticPage(): array
{
return [
'exists page' => ['/static.html', true],
'not exists page' => ['/not_exists.html', false],
];
}
public function providerTestGetHttpCodePage(): array
{
return [
'code 404' => [404, true],
'code 500' => [500, false],
'code 403' => [403, false],
];
}
public function testParseUri(): void
{
RouteManager::$routes = new RouteCollection();
RouteManager::importRouteByAnnotation(
new RequestMapping('/test', 'test', RequestMethod::GET),
__FUNCTION__,
__CLASS__,
[]
);
$r = new Request();
$r->server['request_uri'] = '/test';
$r->server['request_method'] = 'GET';
$this->assertTrue(HttpUtil::parseUri(
$r,
null,
'/test',
$node,
$params
));
}
}

View File

@@ -0,0 +1,65 @@
<?php
declare(strict_types=1);
namespace Tests\ZM\Utils;
use PHPUnit\Framework\TestCase;
use ZM\Exception\MethodNotFoundException;
use ZM\Utils\Macroable;
/**
* @internal
*/
class MacroableTest extends TestCase
{
private $macroable;
protected function setUp(): void
{
$this->macroable = new class() {
use Macroable;
private $secret = 'secret';
private static function anotherSecret()
{
return 'another secret';
}
};
}
public function testMacroCanBeDefined(): void
{
$this->macroable::macro('getSecret', function () {
return $this->secret;
});
$this->assertEquals('secret', $this->macroable->getSecret());
}
public function testMacroCanBeDefinedStatically(): void
{
$this->macroable::macro('getSecret', static function () {
return 'static secret';
});
$this->assertEquals('static secret', $this->macroable::getSecret());
}
public function testMacroCanBeDefinedWithParameters(): void
{
$this->macroable::macro('getParam', function ($param) {
return $param;
});
$this->assertEquals('param', $this->macroable->getParam('param'));
}
public function testExceptionIsThrownWhenMacroIsNotDefined(): void
{
$this->expectException(MethodNotFoundException::class);
$this->macroable->unknownMacro();
}
}

View File

@@ -0,0 +1,176 @@
<?php
declare(strict_types=1);
namespace Tests\ZM\Utils;
use Exception;
use PHPUnit\Framework\TestCase;
use Throwable;
use ZM\Annotation\CQ\CQCommand;
use ZM\Event\EventManager;
use ZM\Utils\DataProvider;
use ZM\Utils\MessageUtil;
/**
* @internal
*/
class MessageUtilTest extends TestCase
{
/**
* @throws Exception
*/
public function testAddShortCommand(): void
{
EventManager::$events[CQCommand::class] = [];
MessageUtil::addShortCommand('test', 'test');
$this->assertCount(1, EventManager::$events[CQCommand::class]);
}
/**
* @dataProvider providerTestContainsImage
*/
public function testContainsImage(string $msg, bool $expected): void
{
$this->assertEquals($expected, MessageUtil::containsImage($msg));
}
public function providerTestContainsImage(): array
{
return [
'empty' => ['', false],
'text only' => ['hello world', false],
'image only' => ['[CQ:image,file=123456.jpg]', true],
'image' => ['hello world![CQ:image,file=123456.jpg]', true],
'two image' => ['hello world![CQ:image,file=123456.jpg][CQ:image,file=123456.jpg]', true],
// 'malformed image' => ['[CQ:image,file=]', false],
];
}
/**
* @dataProvider providerTestArrayToStr
*/
public function testArrayToStr(array $array, string $expected): void
{
$this->assertEquals($expected, MessageUtil::arrayToStr($array));
}
public function providerTestArrayToStr(): array
{
$tmp = $this->providerTestStrToArray();
$result = [];
foreach ($tmp as $desc => $case) {
$result[$desc] = [$case[1], $case[0]];
}
return $result;
}
public function testMatchCommand(): void
{
// 这里理论上需要覆盖所有条件,但先暂时这样好了
EventManager::$events[CQCommand::class] = [
new CQCommand('测试命令'),
];
$this->assertEquals(true, MessageUtil::matchCommand('测试命令', [
'user_id' => '123456',
'group_id' => '123456',
'message_type' => 'group',
])->status);
}
/**
* @dataProvider providerTestIsAtMe
*/
public function testIsAtMe(string $msg, bool $expected): void
{
$this->assertEquals($expected, MessageUtil::isAtMe($msg, 123456789));
}
public function providerTestIsAtMe(): array
{
return [
'me only' => ['[CQ:at,qq=123456789]', true],
'empty qq' => ['[CQ:at,qq=]', false],
'message behind' => ['[CQ:at,qq=123456789] hello', true],
'message front' => ['hello [CQ:at,qq=123456789]', true],
'message surround' => ['hello [CQ:at,qq=123456789] world', true],
'not at me' => ['hello world', false],
'other' => ['[CQ:at,qq=123456789] hello [CQ:at,qq=987654321]', true],
'other only' => ['[CQ:at,qq=987654321]', false],
];
}
public function testGetImageCQFromLocal(): void
{
file_put_contents('/tmp/test.jpg', 'test');
$this->assertEquals('[CQ:image,file=base64://' . base64_encode('test') . ']', MessageUtil::getImageCQFromLocal('/tmp/test.jpg'));
unlink('/tmp/test.jpg');
}
/**
* @dataProvider providerTestStrToArray
*/
public function testStrToArray(string $str, array $expected): void
{
$this->assertEquals($expected, MessageUtil::strToArray($str));
}
public function providerTestStrToArray(): array
{
$text = static function ($str): array {
return ['type' => 'text', 'data' => ['text' => $str]];
};
return [
'empty string' => ['', []],
'pure string' => ['foobar', [$text('foobar')]],
'spaced string' => ['hello world', [$text('hello world')]],
'spaced and multiline string' => ["hello\n world", [$text("hello\n world")]],
'string containing CQ' => ['[CQ:at,qq=123456789]', [['type' => 'at', 'data' => ['qq' => '123456789']]]],
];
}
/**
* @dataProvider providerTestSplitCommand
*/
public function testSplitCommand(string $msg, array $expected): void
{
$this->assertEquals($expected, MessageUtil::splitCommand($msg));
}
public function providerTestSplitCommand(): array
{
return [
'empty' => ['', ['']],
'spaced' => ['hello world', ['hello', 'world']],
'multiline' => ["hello\nworld", ['hello', 'world']],
'many spaces' => ['hello world', ['hello', 'world']],
'many spaces and multiline' => ["hello\n world", ['hello', 'world']],
'many parts' => ['hello world foo bar', ['hello', 'world', 'foo', 'bar']],
];
}
/**
* @throws Throwable
*/
public function testDownloadCQImage(): void
{
if (file_exists(DataProvider::getDataFolder('images') . '/test.png')) {
unlink(DataProvider::getDataFolder('images') . '/test.png');
}
$msg = '[CQ:image,file=test.png,url=https://zhamao.xin/file/hello.png]';
try {
$result = MessageUtil::downloadCQImage($msg);
$this->assertIsArray($result);
$this->assertCount(1, $result);
$this->assertFileExists(DataProvider::getDataFolder('images') . '/test.png');
unlink(DataProvider::getDataFolder('images') . '/test.png');
} catch (Throwable $e) {
if (strpos($e->getMessage(), 'enable-openssl') !== false) {
$this->markTestSkipped('OpenSSL is not enabled');
}
throw $e;
}
}
}

View File

@@ -0,0 +1,104 @@
<?php
declare(strict_types=1);
namespace Tests\ZM\Utils;
use Closure;
use PHPUnit\Framework\TestCase;
use ReflectionFunctionAbstract;
use ZM\Utils\ReflectionUtil;
/**
* @internal
*/
class ReflectionUtilTest extends TestCase
{
public function testDetermineStaticMethod(): void
{
$this->assertFalse(ReflectionUtil::isNonStaticMethod([ReflectionUtilTestClass::class, 'staticMethod']));
}
public function testDetermineNonStaticMethod(): void
{
$this->assertTrue(ReflectionUtil::isNonStaticMethod([ReflectionUtilTestClass::class, 'method']));
}
public function testGetParameterClassName(): void
{
$class = new \ReflectionClass(ReflectionUtilTestClass::class);
$method = $class->getMethod('method');
[$string_parameter, $object_parameter] = $method->getParameters();
$this->assertNull(ReflectionUtil::getParameterClassName($string_parameter));
$this->assertSame(ReflectionUtilTestClass::class, ReflectionUtil::getParameterClassName($object_parameter));
}
/**
* @dataProvider provideTestVariableToString
* @param mixed $variable
*/
public function testVariableToString($variable, string $expected): void
{
$this->assertSame($expected, ReflectionUtil::variableToString($variable));
}
public function provideTestVariableToString(): array
{
return [
'callable' => [[new ReflectionUtilTestClass(), 'method'], ReflectionUtilTestClass::class . '@method'],
'static callable' => [[ReflectionUtilTestClass::class, 'staticMethod'], ReflectionUtilTestClass::class . '::staticMethod'],
'closure' => [Closure::fromCallable([$this, 'testVariableToString']), 'closure'],
'string' => ['string', 'string'],
'array' => [['123', '42', 'hello', 122], 'array["123","42","hello",122]'],
'object' => [new \stdClass(), 'stdClass'],
'resource' => [fopen('php://memory', 'rb'), 'resource(stream)'],
'null' => [null, 'null'],
'boolean 1' => [true, 'true'],
'boolean 2' => [false, 'false'],
'float' => [123.456, '123.456'],
'integer' => [123, '123'],
];
}
/**
* @dataProvider provideTestGetCallReflector
* @param mixed $callback
*/
public function testGetCallReflector($callback, ReflectionFunctionAbstract $expected): void
{
$this->assertEquals($expected, ReflectionUtil::getCallReflector($callback));
}
public function provideTestGetCallReflector(): array
{
$closure = function () {
};
return [
'callable' => [[new ReflectionUtilTestClass(), 'method'], new \ReflectionMethod(ReflectionUtilTestClass::class, 'method')],
'static callable' => [[ReflectionUtilTestClass::class, 'staticMethod'], new \ReflectionMethod(ReflectionUtilTestClass::class, 'staticMethod')],
'class::method' => [ReflectionUtilTestClass::class . '::staticMethod', new \ReflectionMethod(ReflectionUtilTestClass::class, 'staticMethod')],
'invokable class' => [new InvokableClass(), new \ReflectionMethod(InvokableClass::class, '__invoke')],
'closure' => [$closure, new \ReflectionFunction($closure)],
];
}
}
class ReflectionUtilTestClass
{
public function method(string $string, ReflectionUtilTestClass $class): void
{
}
public static function staticMethod(string $string, ReflectionUtilTestClass $class): void
{
}
}
class InvokableClass
{
public function __invoke(): void
{
}
}

View File

@@ -0,0 +1,20 @@
<?php
declare(strict_types=1);
namespace Tests\ZM\Utils;
use PHPUnit\Framework\TestCase;
use ZM\Utils\SingletonTrait;
/**
* @internal
*/
class SingletonTraitTest extends TestCase
{
public function testGetInstance(): void
{
$mock = $this->getObjectForTrait(SingletonTrait::class);
$this->assertEquals($mock, $mock::getInstance());
}
}

View File

@@ -0,0 +1,37 @@
<?php
declare(strict_types=1);
namespace Tests\ZM\Utils;
use PHPUnit\Framework\TestCase;
use Throwable;
use ZM\Console\Console;
use ZM\Utils\Terminal;
/**
* @internal
*/
class TerminalTest extends TestCase
{
public function testInit()
{
$this->markTestIncomplete('logger level change in need');
Console::setLevel(4);
Terminal::init();
Console::setLevel(0);
$this->expectOutputRegex('/Initializing\ Terminal/');
}
/**
* @throws Throwable
*/
public function testExecuteCommand()
{
$this->markTestIncomplete('logger level change in need');
Console::setLevel(2);
Terminal::executeCommand('echo zhamao-framework');
Console::setLevel(0);
$this->expectOutputRegex('/zhamao-framework/');
}
}

5
tests_old/bootstrap.php Normal file
View File

@@ -0,0 +1,5 @@
<?php
declare(strict_types=1);
require_once __DIR__ . '/../vendor/autoload.php';