Postman의 자동 테스트 개발자 설명서Newman CLI를 사용하여 Docker 내부에서 우편 배달부 모음을 실행합니다.
TL;박사 01 명
Docker 용기에서postman 집합을 작성하고 실행하는 실제 예시를 참고하십시오.소스 코드https://github.com/NikiforovAll/testing-with-newman-demo.
소개하다.
자동화 테스트란 무엇입니까?
Tests are automated by creating test suites that can run again and again. Postman can be used to automate many types of tests including unit tests, functional tests, integration tests, end-to-end tests, regression tests, mock tests, etc. Automated testing prevents human error and streamlines testing.
Postman은 자동 테스트를 쉽게 설정할 수 있는 포괄적인API testing tool 시스템을 제공합니다.요청을 우체부 집합으로 구성하면 일련의 요청을 실행하고 자동화할 수 있습니다.
하나의 예
예를 들어, 우리는 주문 서비스라는 마이크로 서비스를 재구성하기 시작하려고 한다.재구성을 시작하기 전에, 우리는 이 기간에 어떤 것도 파괴되지 않도록 확보해야 한다.매우 흔히 볼 수 있는 이전 전략은 회귀 오류와 이전 오류의 위험을 낮추기 위해 테스트를 작성하는 데 시간을 투자하는 것이다.Postman을 사용하고 자동화된 API 테스트를 통해 "주문 서비스"를 덮어써서 성공적인 이전을 확보할 것입니다.
본 예에서'주문 서비스'는 매우 작아서 주문 처리만 책임진다.
사용 사례:
public static class OrderApiRoutes
{
public static WebApplication MapOrderApiRoutes(this WebApplication app)
{
app.MapPost("/orders/", CreateOrder);
app.MapGet("/orders", GetOrders);
app.MapGet("/orders/{id}", GetOrderById).WithName(nameof(GetOrderById));
app.MapPut("/orders/{id}/cancel", CancelOrderById);
return app;
}
private static async Task<IResult> CancelOrderById(ulong id, IMongoClient mongoClient)
{
var db = mongoClient.GetOrderCollection();
var order = await db.Find(x => x.Id == id).FirstOrDefaultAsync();
if(order is null)
{
return Results.NotFound();
}
order.Cancel();
await db.ReplaceOneAsync(x => x.Id == id, order);
return Results.NoContent();
}
private static async Task<Order> GetOrderById(ulong id, IMongoClient mongoClient)
{
var db = mongoClient.GetOrderCollection();
return await db.Find(x => x.Id == id).FirstOrDefaultAsync();
}
private static async Task<IResult> CreateOrder(
Order order, IMongoClient mongoClient, Generator idGenerator)
{
order = order with
{
Id = idGenerator.NextLong(),
CreatedAt = DateTime.Now
};
var db = mongoClient.GetOrderCollection();
await db.InsertOneAsync(order);
return Results.CreatedAtRoute(nameof(GetOrderById), new { id = order.Id });
}
private static async Task<IEnumerable<Order>> GetOrders(IMongoClient mongoClient)
{
var db = mongoClient.GetOrderCollection();
return await db.Find(x => true).ToListAsync();
}
}
자세한 내용은 소스 코드 참조: https://github.com/NikiforovAll/testing-with-newman-demo서면 요청
개인적으로 Postman은 직관적인 UI가 있어서 당신의 성능을 크게 향상시킬 수 있기 때문에 매우 좋아합니다.나는 네가 그것을 배우는 데 시간을 좀 쓸 것을 건의한다.
간단명료하게 하고 시스템에서 주문서를 만들고 닫는 방법을 보여 드리겠습니다.HTTP 요청을 보내기 전에 우리는'집배원 집합'과'집배원 환경'을 만들기를 희망합니다.
base-url
와 rabbitmq-host
변수를 추가합니다.오른쪽 상단의 새 환경을 선택하십시오.{base-url}/orders
에 보내기를 희망합니다.현재, 우리는 요청이 어떻게 작동하는지 볼 준비가 되어 있다.pm.test("Status code is 201", function () {
pm.response.to.have.status(201);
});
pm.sendRequest(pm.response.headers.get("Location"), function (err, res) {
pm.test("Order created", function () {
pm.expect(res.code).to.eql(200);
pm.environment.set("orderId", res.json().id);
pm.test("Order has customer", function () {
pm.expect(res.json().customer).to.eql('John Doe');
});
});
});
"201 작성됨" 요청을 작성합니다.RabbitMQ에 게시
또한 Postman에서 RabbitMQ에 메시지를 게시할 수도 있습니다.RabbitMQ에서 관리 기능을 사용하는 HTTP 클라이언트를 공개했기 때문에 가능합니다.메시지를 게시하려면 URL
cd ./src/OrderService && dotnet run
에 스왑을 지정하고 메시지를 JSON 본문의 일부로 제공해야 합니다.주의% 2F는 url 인코딩의 기본 가상 호스트 "/"입니다.{
"properties": {
"content_type": "application/json"
},
"routing_key": "order-paid",
"payload": "{\"orderId\": \"244165178826752\"}",
"payload_encoding": "string"
}
발표 메시지는 본질적으로 비동기적이기 때문이다.이때 우리가 할 수 있는 일은 그것이 대기열에 저장되어 있는지 확인하는 것이다.pm.test("Is Routed", function () {
var jsonData = pm.response.json();
pm.expect(jsonData.routed).to.eql(true);
});
마지막으로, 우리는 이전의 작업으로 인해 주문이 이미 완성되었음을 보고, 우리는 발송{rabbitmq-host}/api/exchanges/%2F/amq.default/publish
을 통해 테스트를 실행하여 완성하기를 희망한다.pm.test("Status code is 200", function () {
pm.response.to.have.status(200);
});
pm.test("Order is Completed", function () {
pm.expect(pm.response.json().status).to.eql("Completed");
});
이것이 바로 주류다.나는 네가 스스로 데이터 취소를 검사할 것을 건의한다.CLI에서 Postman collections를 실행하는 방법을 살펴보겠습니다.GET{base url}/orders/{orderId}를 통해 CLI에서 우체부 집합 실행
Postman UI에서 컬렉션과 환경을 내보내고 내보낸 파일을 로컬에서 사용할 수 있습니다.우리는 내부에 집합 달리기를 설치할 것이다
newman
Docker 내부에서 postman collections를 실행하면 다음과 같은 여러 가지 이점이 있습니다.docker-compose
입니다.version: "3.4"
services:
main-flow:
image: postman/newman_alpine33
command:
run testing-with-newman.postman_collection.json
--environment testing-with-newman.postman_environment.json
--folder main-flow
-r cli
--delay-request 500
--iteration-count 1
--color on
volumes:
- ./tests/postman:/etc/newman
networks:
- newman-tests
cancel-flow:
image: postman/newman_alpine33
command:
run testing-with-newman.postman_collection.json
--environment testing-with-newman.postman_environment.json
--folder cancel-flow
-r cli
--iteration-count 1
--color on
volumes:
- ./tests/postman:/etc/newman
networks:
- newman-tests
networks:
newman-tests:
external: true
name: newman-tests
e2e 장면을 실행하려면docker compose -f docker-compose.postman.yml up main-flow
docker compose -f docker-compose.postman.yml up cancel-flow
뉴먼을 지속적인 집적 과정의 일부로 운행하다.GitHub 운영 예
docker-compose.postman.yml
의 가장 큰 장점 중 하나는 CI의 일부로 사용할 수 있다는 것입니다.GitHub의 워크플로우는 다음과 같습니다.name: tests
on:
push:
jobs:
build:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v2
- name: Setup network
run: docker network create newman-tests
- name: Build the docker-compose stack
run: docker-compose -f docker-compose.override.yml -f docker-compose.yml up -d
- name: Check running containers
run: docker ps -a
- name: Check logs
run: docker-compose logs order-service
- name: Run test suite main-flow
run: docker-compose -f docker-compose.postman.yml up main-flow
- name: Run test suite cancel-flow
run: docker-compose -f docker-compose.postman.yml up cancel-flow
💡 알림:github 작업을 로컬에서 실행하려면
https://github.com/nektos/act
요약
작성 테스트는 우수 개발자가 우수 개발자가 되는 관건이다.이 블로그에서, 우리는 Docker 내부에서 통합 테스트를 실행 가능한postman 집합으로 설정하는 방법을 소개했다.
참고 문헌
Reference
이 문제에 관하여(Postman의 자동 테스트 개발자 설명서Newman CLI를 사용하여 Docker 내부에서 우편 배달부 모음을 실행합니다.), 우리는 이곳에서 더 많은 자료를 발견하고 링크를 클릭하여 보았다 https://dev.to/nikiforovall/a-developer-guide-to-automated-testing-with-postman-run-postman-collections-inside-docker-via-newman-cli-524텍스트를 자유롭게 공유하거나 복사할 수 있습니다.하지만 이 문서의 URL은 참조 URL로 남겨 두십시오.
우수한 개발자 콘텐츠 발견에 전념 (Collection and Share based on the CC Protocol.)