reenexe / compare-data-structure
此包最新版本(1.0.0)没有可用的许可证信息。
1.0.0
2015-01-24 19:46 UTC
Requires
- php: >=5.4
Requires (Dev)
- phpunit/phpunit: 4.4.*
This package is not auto-updated.
Last update: 2024-09-24 16:38:34 UTC
README
针对测试 REST API JSON 响应的本地 PHP assert
在 composer.json 文件中包含依赖
{
"require": {
"reenexe/compare-data-structure": "1.0.0"
}
}
示例
你有 REST API 方法返回类似
{
"id": 3,
"name": "Alex",
"location": 3,
"gender": "men",
"joined": {
"source": 1,
"at": "2011-11-11 11:11:11"
},
"friends": [
{
"id": 7,
"name": "Alice"
},
{
"id": 8,
"name": "Bob"
}
],
"interests": ["programming", "books", "sport"],
"games": null,
"books": [
{
"author": "Достоевский Фёдор Михайлович",
"title": "Преступление и наказание"
},
{
"author": "Steve McConnell",
"title": "Code Complete"
}
],
"social": ["GitHub", "LinkedIn"]
}
我们想通过设置检查这些结构
[
'assoc' => [
'id' => 'integer',
'name' => 'string',
'location' => 'integer',
'gender' => [
'set' => ['men', 'women', null]
],
'joined' => [
'assoc' => [
'source' => 'integer|null',
'at' => 'string'
]
],
'friends' => [
'type' => 'null',
'values' => [
'id' => 'integer',
'name' => 'string'
]
],
'interests' => [
'type' => 'null',
'values' => 'string'
],
'games' => [
'type' => 'null',
'values' => [
'title' => 'string'
]
],
'books' => [
'values' => [
'author' => 'string',
'title' => 'string',
]
],
'social' => [
'set' => [
'GitHub', 'LinkedIn', 'Facebook', 'Google', 'Twitter',
]
]
]
]
在这个示例中,试图描述完整的范围
另外
我们可以测试简单类型
1
'integer'
或者
array_merge( range(1, 100), range('a', 'z'), [true, false] )
['values' => 'integer|string|boolean']
使用
/** * @return StructureDiffInfo */ Comparator::check($data, $structure) /** * @method public bool StructureDiffInfo::isEqual * @method public string StructureDiffInfo::getMessage * @method public string StructureDiffInfo::getPath */
在 PHPUnit 中轻松使用
use ReenExe\CompareDataStructure\Comparator; class Test extends PHPUnit_Framework_TestCase{ public function testSimple() { $diff = Comparator::check(1, 'integer'); $this->assertTrue($diff->isEqual(), $diff); } }
自定义类型(或 用户类型)
我们可以设置一次用户定义的类型,并在
Comparator::addCustom(array $custom)
示例
Comparator::addCustom( [ 'profile' => [ 'assoc' => [ 'id' => 'integer', 'name' => 'string' ] ] ]); ... Comparator::check($profile, 'profile'); ... Comparator::check($response, 'profile'); ...
还可以建立一次性检查的类型
Comparator::check( $data = [ 'value' => 1, 'next' => [ 'value' => 3, 'next' => [ 'value' => 5, 'next' => null ] ] ], $structure = 'link', $custom = [ 'link' => [ 'assoc' => [ 'value' => 'integer', 'next' => 'link|null' ] ] ] );
在 用户类型 - 允许递归检查的可能性
@TODO 或待续...
与 assoc、values、set 结构一起 - 有添加 range 结构的愿望,添加 strict
替代方案
AssertJsonStructure: https://github.com/t4web/AssertJsonStructure - 其中一部分用于创建,也使用了 检查结构的想法
json-schema: https://github.com/justinrainbow/json-schema