Automation/Postman

Postman - validation

c29130811 2023. 2. 18. 14:33

Chai 란 TDD/ BDD 스타일의 Assertion Library 이다.

 

공식 문서 https://www.chaijs.com/

 

Chai

  Powered by Open Source Chai is hosted on GitHub. Have a suggestion or found a bug? Fork this project to help make Chai even better. Even this documentation site is open source and available for contribution.

www.chaijs.com

Should, Expect, Assert 세가지 스타일의 인터페이스를 제공함.

 

Should

chai.should();

foo.should.be.a('string');
foo.should.equal('bar');

  

Expect

const expect = chai.expect;

expect(foo).to.be.a('string');
expect(foo).to.equal('bar');

 

Asssert

const assert = chai.assert;

assert.typeOf(foo, 'string');
assert.equal(foo, 'bar');

 

앞단에 Chai를 얘기한 이유는 Postman에서는 pm.expect 지원 해주기 때문에 expect 형태로 작성할 수 있다.

pm.test("Status code is 200", () => {
  pm.expect(pm.response.code).to.eql(200);
});

응답에 대한 code가 200인지 체크를 할 수 있으며, 아래와 같이, 

response의 body 내용의 type까지 체크할 때 사용한다.

let responseJson = pm.response.json();

pm.test("Response Data Type Check", () => {
    pm.expect(responseJson.id).to.be.a("number");
    pm.expect(responseJson.username).to.be.a("string");
});

가령 Client에서 유저의 Id를 number 인데 모종의 이유로 string 이되었다거나 type이 바뀌는 경우 걸러낼 수 있지 않을까?

물론 그럴 경우가 많지 않을테지만,

응답값 뿐 아니라, 값이 비어있을 경우, 또는 특정 값이 확정되어 있을 때도 체크가 가능하다.

  pm.expect(responseJson.user.favorites).to.be.empty;
  pm.expect(responseJson.user.email).to.be.null;

각 validation 체크에 대한 예제는 공식 사이트를 참고하면 좋다.

나도 쓸때마다 보는 중..

https://learning.postman.com/docs/writing-scripts/script-references/test-examples/

이외에 tiny validator (for v4 json Schema)를 통해서도 유효값 검증을 할 수있게 해준다.

let responseJson = pm.response.json();

const schema = {
 "required": [
        "id",
        "username"
 ],
 "properties": {
	"id": {
    	"type": "number"
    },
	"username": {
    	"type": "string"
    }
  }
};

pm.test('Schema is valid', function () {
    pm.expect(tv4.validate(responseJson, searchSchema)).to.be.true;
});

이런 식으로 required와 각 properties의 schema를 정의 후, tv4.validate를 사용 할 수도 있음.

위에 각 검증 값 하나하나 검증하는 것보다, 아래 tv4를 사용해서 검증하는 편이 여러모로 편해보임.

728x90

'Automation > Postman' 카테고리의 다른 글

Postman Flows  (0) 2023.04.28
Postman - new man  (0) 2023.02.18
Environment  (0) 2020.09.23
Tests  (0) 2020.09.22
Postman  (0) 2020.09.22