Postman의 자동 테스트 개발자 설명서Newman CLI를 사용하여 Docker 내부에서 우편 배달부 모음을 실행합니다.

26175 단어

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 요청을 보내기 전에 우리는'집배원 집합'과'집배원 환경'을 만들기를 희망합니다.
  • 참조: "Creating your first collection"
  • "뉴먼과 함께 테스트"집합 만들기
  • 폴더 마스터 프로세스 추가
  • 환경'뉴먼과 함께 테스트'를 만들고 base-urlrabbitmq-host 변수를 추가합니다.오른쪽 상단의 새 환경을 선택하십시오.

  • 메인스트림 폴더에 주문 작성 요청을 추가합니다.보시다시피 Google은 HTTP POST를 JSON 본문으로 {base-url}/orders 에 보내기를 희망합니다.현재, 우리는 요청이 어떻게 작동하는지 볼 준비가 되어 있다.

  • 서버를 시작하고 Postman UI를 통해 HTTP 요청을 보냅니다.주문이 수락된 것으로 보이며 to send 반송되었습니다.작성한 리소스의 주소를 보려면 Location 헤더를 볼 수 있습니다.

  • 만약에 우리가 우체부와'주문 서비스'에 만족한다면 우리는'우체부 테스트'를 작성하여 기대하는 행위를 검증할 수 있다.테스트는 JavaScript를 기반으로 작성되었습니다.Postman UI는 다양한 예제를 제공하여 테스트를 작성하는 데 도움을 줍니다. 오른쪽 사이드바를 참조하십시오.다음은 주문 요청 반품 상태가 201이고 고객 필드에 "John Doe"가 포함되어 있는지 확인합니다.보시다시피 다음 요청에서 사용할 수 있도록 "orderId"를 환경 변수에 기록합니다.
  • 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 클라이언트를 공개했기 때문에 가능합니다.메시지를 게시하려면 URLcd ./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에서 컬렉션과 환경을 내보내고 내보낸 파일을 로컬에서 사용할 수 있습니다.우리는 내부에 집합 달리기를 설치할 것이다newmanDocker 내부에서 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 집합으로 설정하는 방법을 소개했다.

    참고 문헌

  • https://www.postman.com/automated-testing/
  • https://www.sm-cloud.com/testing-api-with-postman/
  • 좋은 웹페이지 즐겨찾기