osi-open-source/codeception-json-schema

用于验证Codeception测试框架响应的Json schema模块

v0.4.0 2021-04-05 12:51 UTC

This package is auto-updated.

Last update: 2024-09-05 20:29:31 UTC


README

用于在schema上验证json的Codeception模块。

安装

composer require osi-open-source/codeception-json-schema

用法

<?php
class MessageApiCest
{
    public function aTest(ApiTester $I)
    {
        /* call api */
        $I->wantTo('Ensure API Returns Json which matches schema file.');
        $I->sendGET('/path/to/api');

        /* check if api matches schema */
        $I->seeResponseIsValidOnSchemaFile('/path/to/schema.json');
    }

    public function bTest(ApiTester $I)
    {
        /* call api */
        $I->wantTo('Ensure API Returns Json which matches schema file.');
        $I->sendGET('/path/to/api');

        /* alternative syntax, check if api matches schema */
        $I->canSeeResponseIsValidOnSchemaFile('/path/to/schema.json');
    }

    public function cTest(ApiTester $I)
    {
        /* call api */
        $I->wantTo('Ensure API Returns Json which matches inline schema.');
        $I->sendGET('/path/to/api');

        /* if you don't have a separate schema file, that is alright, you can use inline schema */
        /* this schema expects the api to return something like {"message": "SOME_STRING"} */
        /* schema as php objects */
        $schema = (object)[
            'type' => 'object',
            'properties' => (object)[
                'message' => (object)[
                    'type' => 'string',
                ],
            ],
            'required' => ['message'],
        ];

        $I->seeResponseIsValidOnSchema($schema);
    }

    public function dTest(ApiTester $I)
    {
        /* call api */
        $I->wantTo('Ensure API Returns Json which matches inline schema.');
        $I->sendGET('/path/to/api');

        /* if you don't have a separate schema file, that is alright, you can use inline schema */
        /* this schema expects the api to return something like {"message": "SOME_STRING"} */
        /* json string, must be decoded before checking if response is valid */
        $jsonSchema = '{"type":"object","properties":{"message":{"type":"string"}},"required":["message"]}';

        /* alternative syntax, notice we decoded the json string */
        $I->canSeeResponseIsValidOnSchema(json_decode($jsonSchema));
    }
}

另请参阅

Codeception有一个内置的简单json匹配语法,但是它不兼容json schema,因此创建了此模块。

<?php
class MessageApiCest
{
    public function eTest(ApiTester $I)
    {
        /* call api */
        $I->wantTo('Ensure API Returns Json which matches type.');
        $I->sendGET('/path/to/api');

        /* this type expects the api to return something like {"message": "SOME_STRING"} */
        $I->seeResponseMatchesJsonType([
            'message' => 'string',
        ]);
    }
}

贡献

如果您发现任何错误或有任何改进建议,请提出一个issue。