서버 세팅 & tool/postman

[postman] schema validation test

방푸린 2022. 2. 8. 15:18
반응형

이전 글: 2022.02.08 - [서버 세팅 & tool/postman] - [test] environment variable setting & snippets

 

[test] environment variable setting & snippets

이전 글: 2022.02.08 - [서버 세팅, tool 사용법/postman] - [test] before you dive into api testing [test] before you dive into api testing 포스트맨이란 API 개발을 보다 빠르고 쉽게 구현 할 수 있도록..

bangpurin.tistory.com

환경: 포스트맨 Version 9.12.1

포스트맨으로 response의 json format이 맞는지 검사할 수 있는데, 아래와 같이 진행하면 된다.

 

1. 포스트맨으로 api 요청을 하고 결과 json을 복사해 둔다.

 

2. 다음 사이트에 접속한다: https://techbrij.com/brijpad/#json

 

BrijPad 2.0: Online Tool for Web Development & Data Analysis

 

techbrij.com

Json탭을 선택한 후 왼쪽 칸에 1번에서 복사해 둔 json을 붙여 넣기 하고 json to schema버튼을 누른다(min/full 아무거나 무관).

해당 사이트는 json을 분석하여 기본적인 json의 구조를 분석해준다. 타입이 무엇인지(array, object 등), 각 항목이 필수 값인지(우선 json의 모든 값이 필수라고 지정되지만 손으로 수정하면 된다) 어떤 타입인지(string, number 등)를 기본적으로 알려주며 maxItem, maxLength, pattern 등 다양하게 지정 가능하지만 위 사이트에서는 거기까지는 해주지 않고 필요할 경우 직접 수정하면 된다.

참고 json schema 세부 설정 값: https://json-schema.org/understanding-json-schema/index.html

 

Understanding JSON Schema — Understanding JSON Schema 2020-12 documentation

Understanding JSON Schema JSON Schema is a powerful tool for validating the structure of JSON data. However, learning to use it by reading its specification is like learning to drive a car by looking at its blueprints. You don’t need to know how an elect

json-schema.org

우선 기본 테스트이기에 오른쪽의 스키마를 복사하여 진행해보도록 한다.

 

3. 포스트맨 테스트에 스키마 검증 로직 적용

스키마 검사를 위해서는 ajv라는 라이브러리(링크: 공식사이트)가 필요한데, 포스트맨에서는 별도의 설치 없이 사용 가능하다.

검증하고자 하는 api의 테스트 탭에 다음과 같이 작성한다.

var Ajv = require('ajv');  //lib 불러오고
var ajv = new Ajv({logger: console}); //ajv 객체 생성하고(옵션없이 생성 가능하며 옵션은 json포맷이어야 함)
var schema = 
     {
        "items": {
            "required": [
                "id",
                "name",
                "username",
                "email",
                "address",
                "phone",
                "website",
                "company"
            ],
            "properties": {
                "id": {
                    "$id": "#/items/properties/id",
                    "type": "integer"
                },
                "name": {
                    "$id": "#/items/properties/name",
                    "type": "string"
                },
                "username": {
                    "$id": "#/items/properties/username",
                    "type": "string"
                },
                "email": {
                    "$id": "#/items/properties/email",
                    "type": "string"
                },
                "address": {
                    "required": [
                        "street",
                        "suite",
                        "city",
                        "zipcode",
                        "geo"
                    ],
                    "properties": {
                        "street": {
                            "$id": "#/items/properties/address/properties/street",
                            "type": "string"
                        },
                        "suite": {
                            "$id": "#/items/properties/address/properties/suite",
                            "type": "string"
                        },
                        "city": {
                            "$id": "#/items/properties/address/properties/city",
                            "type": "string"
                        },
                        "zipcode": {
                            "$id": "#/items/properties/address/properties/zipcode",
                            "type": "string"
                        },
                        "geo": {
                            "required": [
                                "lat",
                                "lng"
                            ],
                            "properties": {
                                "lat": {
                                    "$id": "#/items/properties/address/properties/geo/properties/lat",
                                    "type": "string"
                                },
                                "lng": {
                                    "$id": "#/items/properties/address/properties/geo/properties/lng",
                                    "type": "string"
                                }
                            },
                            "$id": "#/items/properties/address/properties/geo",
                            "type": "object"
                        }
                    },
                    "$id": "#/items/properties/address",
                    "type": "object"
                },
                "phone": {
                    "$id": "#/items/properties/phone",
                    "type": "string"
                },
                "website": {
                    "$id": "#/items/properties/website",
                    "type": "string"
                },
                "company": {
                    "required": [
                        "name",
                        "catchPhrase",
                        "bs"
                    ],
                    "properties": {
                        "name": {
                            "$id": "#/items/properties/company/properties/name",
                            "type": "string"
                        },
                        "catchPhrase": {
                            "$id": "#/items/properties/company/properties/catchPhrase",
                            "type": "string"
                        },
                        "bs": {
                            "$id": "#/items/properties/company/properties/bs",
                            "type": "string"
                        }
                    },
                    "$id": "#/items/properties/company",
                    "type": "object"
                }
            },
            "$id": "#/items",
            "type": "object"
        },
        "$id": "http://example.org/root.json#",
        "type": "array",
        "definitions": {},
        "$schema": "http://json-schema.org/draft-07/schema#"
    };

변수들이 준비되었으니 테스트 코드를 짜 보자면 아래와 같다.

pm.test('Schema is valid', function() {
    var data = pm.response.json();   //결과 값을 json으로 변환하여 data에 담고
    pm.expect(ajv.validate(schema, data)).to.be.true; //검증 값이 true(참)인지 확인
    //ajv.validate(schema, data) : ajv라이브러리의 validate함수를 이용하여 schema가 data랑 맞는지 검증
});

 

test results 섹션에 테스트 이름과 테스트 통과 여부가 잘 나오는 것을 알 수 있다.

형태가 바뀌어서는 안되는 api를 검증할 경우(특히 외부에 공개해야 하는 api 일 경우 api doc과 일치하는지 확인할 때) 유용하게 쓰일 테스트이다.

728x90
반응형