본문으로 바로가기 본문 바로가기
WIKI 기술 지식 베이스

커스텀 플러그인 테스트 추가

원문 보기 위키 갱신

커스텀 플러그인 테스트 추가 (Add custom plugin testing)

이 문서는 커스텀 플러그인 개발 시리즈의 다음 단계로, Pongo를 사용해 플러그인 테스트 환경을 구성하는 방법을 안내해요. Pongo를 설치하고 pongo init으로 테스트 환경을 초기화한 뒤, spec/ 디렉터리에 테스트 파일을 작성해 자동화 테스트를 실행하는 전 과정을 배울 수 있어요. Pongo는 Docker로 Kong Gateway 환경을 띄워주기 때문에 플러그인을 빠르게 로드하고 여러 게이트웨이 버전에서 동작을 검증하기 좋아요

출처: 문서

본문

TL;DR

커스텀 플러그인의 자동화 테스트는 어떻게 설정하나요? Pongo를 설치하고, 테스트 환경을 초기화한 다음, spec/<plugin-name> 디렉터리 아래에 테스트 파일을 작성해요.

사전 요구 사항

시리즈 사전 요구 사항

이 페이지는 커스텀 플러그인 개발 시작하기 시리즈의 일부예요.

이 페이지를 진행하기 전에 이전 페이지인 커스텀 플러그인 프로젝트 설정하기를 먼저 완료하세요.

Pongo 설치

Pongo는 Kong Gateway용 커스텀 플러그인을 검증하고 배포하는 데 도움을 주는 도구예요.

Pongo는 Docker를 사용해서 Kong Gateway 환경을 빠르게 구축해 줘요. 이 환경에서는 플러그인을 빠르게 로드하고, 자동화 테스트를 실행하고, 다양한 Kong Gateway 버전을 대상으로 플러그인의 동작을 수동으로 검증할 수 있어요.

다음 스크립트를 사용하면 Pongo 설치를 자동화할 수 있어요. 원한다면 대신 수동 설치 안내를 따라해도 돼요.

  1. Pongo를 설치하거나 업데이트하려면 다음을 실행해요:

    curl -Ls https://get.konghq.com/pongo | bash
    
  2. Pongo를 경로에 추가해요. 이전 명령의 결과에 추가 방법에 대한 안내가 포함되어 있을 거예요. 예를 들면 다음과 같아요:

    export PATH=$PATH:~/.local/bin
    
  3. 프로젝트 디렉터리 안에서 명령을 실행해서 pongo 명령어를 PATH에서 사용할 수 있는지 확인해요:

    pongo help
    

테스트 환경 초기화

Pongo는 플러그인이 설치되어 사용 가능한 상태의 Kong Gateway 인스턴스를 빠르게 실행할 수 있는 도구를 제공해서, 플러그인의 동작을 검증할 수 있게 해줘요.

참고: Kong Gateway는 다양한 배포 토폴로지로 실행될 수 있어요. 기본적으로 Pongo는 전통 모드로 Kong Gateway를 실행하는데, 이 모드는 데이터베이스를 사용해 Route, Gateway Service, 플러그인 같은 설정된 엔티티를 저장해요. Kong Gateway와 데이터베이스는 별도의 컨테이너에서 실행되기 때문에, 데이터베이스와 독립적으로 게이트웨이를 재시작할 수 있어요. 이 덕분에 게이트웨이 상태를 데이터베이스에 독립적으로 유지하면서 플러그인의 논리적 동작을 빠르고 반복적으로 검증할 수 있어요.

Pongo는 몇 가지 기본 설정 파일로 프로젝트 디렉터리를 초기화하는 선택적 명령어를 제공해요. 새 프로젝트를 시작할 때 이 명령어를 실행하면 돼요.

중요: Pongo가 플러그인 코드를 제대로 패키징해서 실행 중인 Kong Gateway에 포함시키도록, 이 명령어들은 반드시 my-plugin 프로젝트 루트 디렉터리 안에서 실행해야 해요.

  1. 프로젝트 폴더를 초기화해요:

    pongo init
    
  2. 의존성을 시작해요. 이 예제에서는 PostgreSQL만 포함돼요:

    pongo up
    

    의존성이 성공적으로 실행되고 나면, Kong Gateway 컨테이너를 실행하고 그 안에서 셸을 열 수 있어요. Pongo는 테스트에 도움이 되는 다양한 CLI 도구가 미리 설치된 Kong Gateway 컨테이너를 실행해요.

  3. Kong Gateway를 시작하고 셸을 열어요:

    pongo shell
    

    이제 터미널이 Kong Gateway 컨테이너 안에서 셸을 실행하고 있어요. 셸 프롬프트가 바뀌면서 Kong Gateway 버전, 호스트의 플러그인 디렉터리, 컨테이너 안에서의 현재 경로를 보여줄 거예요. 예를 들어 프롬프트는 다음과 같이 보일 수 있어요:

    [Kong-3.9.0:my-plugin:/kong]$
    

    {:.no-copy-code}

  4. 데이터베이스 마이그레이션을 실행하고 Kong Gateway를 시작해요:

    kms
    

    Kong Gateway가 시작되었다는 성공 메시지가 표시될 거예요.

  5. curl로 Admin API에 쿼리하고 jq로 응답을 필터링해서 플러그인이 설치되어 있는지 검증해요:

    curl -s localhost:8001 | \
      jq '.plugins.available_on_server."my-plugin"'
    

    플러그인 테이블의 정보와 일치하는 응답이 표시될 거예요:

    {
      "priority": 1000,
      "version": "0.0.1"
    }
    

플러그인 수동 테스트

플러그인이 설치되었으니, 이제 Kong Gateway 엔티티를 설정해서 플러그인의 동작을 호출하고 검증할 수 있어요.

다음에서 Admin API로 보내는 각 POST 요청에 대해, 엔티티가 성공적으로 생성되었다는 의미의 HTTP/1.1 201 Created 응답을 Kong Gateway로부터 받게 돼요.

  1. Kong Gateway 컨테이너 셸에 그대로 있는 상태에서 새 Gateway Service를 추가해요:

    curl -X POST "http://localhost:8001/services" \
         --no-progress-meter --fail-with-body  \
         --json '{
           "name": "example_service",
           "url": "https://httpbin.konghq.com"
         }'
    
  2. example_service Service에서 커스텀 플러그인을 활성화해요:

    curl -X POST "http://localhost:8001/services/example_service/plugins" \
         --no-progress-meter --fail-with-body  \
         --json '{
           "name": "my-plugin"
         }'
    
  3. example_service를 통해 요청을 보내기 위한 새 Route를 추가해요:

    curl -X POST "http://localhost:8001/services/example_service/routes" \
         --no-progress-meter --fail-with-body  \
         --json '{
           "name": "example_route",
           "paths": [
             "/mock"
           ]
         }'
    

이제 플러그인이 구성되었고, Kong Gateway가 example_service를 통해 요청을 프록시할 때 플러그인이 호출될 거예요. 업스트림에서 받은 응답을 전달하기 전에, 플러그인은 X-MyPlugin 헤더를 응답 헤더 목록에 추가하도록 되어 있어요.

  1. 동작을 테스트하려면 요청을 보내고, -i 플래그를 사용해서 응답 헤더를 표시해요:

    curl -i "http://localhost:8000/mock/anything" \
         --no-progress-meter --fail-with-body 
    

헤더 목록에서 X-MyPlugin: response를 볼 수 있을 거예요. 이는 플러그인의 로직이 호출되었다는 뜻이에요.

  1. 다음 단계로 넘어가기 전에 Kong Gateway 셸을 종료해요:
    exit
    

자동화 테스트 작성

빠르게 시작하기에는 Pongo 셸을 사용해 플러그인을 수동으로 검증하는 방식이 잘 맞아요. 프로덕션 시나리오에서는 자동화 테스트를 도입하고, 어쩌면 테스트 주도 개발(TDD) 방법론까지 활용하고 싶을 거예요. Pongo가 이 부분에도 어떻게 도움을 줄 수 있는지 살펴봐요.

Pongo는 Busted Lua 테스트 프레임워크를 사용한 자동화 테스트 실행을 지원해요. 플러그인 프로젝트에서는 테스트 파일이 spec/<plugin-name> 디렉터리 아래에 위치해요. 이 프로젝트의 경우 앞서 만들어 둔 spec/my-plugin 폴더가 바로 그곳이에요.

  1. 플러그인 디렉터리에서 테스트 파일을 만들어요:

    touch spec/my-plugin/01-integration_spec.lua
    
  2. 이 코드를 복사해서 테스트 파일에 붙여넣어요:

    -- Helper functions provided by Kong Gateway, see https://github.com/Kong/kong/blob/master/spec/helpers.lua
    local helpers = require "spec.helpers"
    
    -- matches our plugin name defined in the plugins's schema.lua
    local PLUGIN_NAME = "my-plugin"
    
    -- Run the tests for each strategy. Strategies include "postgres" and "off"
    --   which represent the deployment topologies for Kong Gateway
    for _, strategy in helpers.all_strategies() do
    
      describe(PLUGIN_NAME .. ": [#" .. strategy .. "]", function()
        -- Will be initialized before_each nested test
        local client
    
        setup(function()
    
          -- A BluePrint gives us a helpful database wrapper to
          --    manage Kong Gateway entities directly.
          -- This function also truncates any existing data in an existing db.
          -- The custom plugin name is provided to this function so it mark as loaded
          local blue_print = helpers.get_db_utils(strategy, nil, { PLUGIN_NAME })
    
          -- Using the BluePrint to create a test Route, automatically attaches it
          --    to the default "echo" Service that will be created by the test framework
          local test_route = blue_print.routes:insert({
            paths = { "/mock" },
          })
    
          -- Add the custom plugin to the test Route
          blue_print.plugins:insert {
            name = PLUGIN_NAME,
            route = { id = test_route.id },
          }
    
          -- start kong
          assert(helpers.start_kong({
            -- use the custom test template to create a local mock server
            nginx_conf = "spec/fixtures/custom_nginx.template",
            -- make sure our plugin gets loaded
            plugins = "bundled," .. PLUGIN_NAME,
          }))
    
        end)
    
        -- teardown runs after its parent describe block
        teardown(function()
          helpers.stop_kong(nil, true)
        end)
    
        -- before_each runs before each child describe
        before_each(function()
          client = helpers.proxy_client()
        end)
    
        -- after_each runs after each child describe
        after_each(function()
          if client then client:close() end
        end)
    
        -- a nested describe defines an actual test on the plugin behavior
        describe("The response", function()
    
          it("gets the expected header", function()
    
            -- invoke a test request
            local r = client:get("/mock/anything", {})
    
            -- validate that the request succeeded, response status 200
            assert.response(r).has.status(200)
    
            -- now validate and retrieve the expected response header 
            local header_value = assert.response(r).has.header("X-MyPlugin")
    
            -- validate the value of that header
            assert.equal("response", header_value)
    
          end)
        end)
      end)
    end
    

    이 테스트는 플러그인의 현재 동작을 검증해요. 테스트 설계 방식과 Kong Gateway가 제공하는 테스트 헬퍼에 대한 자세한 내용은 코드 주석을 참고하세요.

테스트 실행

Pongo는 pongo run 명령어로 자동화 테스트를 실행할 수 있어요. 이 명령을 실행하면 Pongo는 의존성 컨테이너가 이미 실행 중인지 확인하고, 실행 중이라면 그 컨테이너들을 그대로 사용해요. 테스트 실행 사이에 기존 데이터를 비우는 작업은 테스트 라이브러리가 알아서 처리해요.

테스트를 실행해 보세요:

pongo run

다음과 비슷한 성공 리포트가 표시될 거예요:

[pongo-INFO] auto-starting the test environment, use the 'pongo down' action to stop it
Kong version: 3.9.0

[==========] Running tests from scanned files.
[----------] Global test environment setup.
[----------] Running tests from /kong-plugin/spec/my-plugin/01-integration_spec.lua
[ RUN      ] /kong-plugin/spec/my-plugin/01-integration_spec.lua:63: my-plugin: [#postgres] The response gets the expected header
[       OK ] /kong-plugin/spec/my-plugin/01-integration_spec.lua:63: my-plugin: [#postgres] The response gets the expected header (12.56 ms)
[ RUN      ] /kong-plugin/spec/my-plugin/01-integration_spec.lua:63: my-plugin: [#off] The response gets the expected header
[       OK ] /kong-plugin/spec/my-plugin/01-integration_spec.lua:63: my-plugin: [#off] The response gets the expected header (11.42 ms)
[----------] 2 tests from /kong-plugin/spec/my-plugin/01-integration_spec.lua (48425.41 ms total)

[----------] Global test environment teardown.
[==========] 2 tests from 1 test file ran. (48436.36 ms total)
[  PASSED  ] 2 tests.

{:.no-copy-code}

Pongo는 지속적 통합(CI) 시스템의 일부로도 실행할 수 있어요. 자세한 내용은 저장소 문서를 참고하세요.

관련 리소스

더 알아보기 (Learn more)

  • 이 페이지가 속한 시리즈의 이전 단계로, 커스텀 플러그인 프로젝트를 먼저 설정하는 방법을 설명해요 — Get started with custom plugin development
  • 커스텀 플러그인 개발 전반을 다루는 상위 문서예요 — Custom plugins
  • Pongo가 기본으로 사용하는 데이터베이스 기반 실행 모드를 설명해요 — traditional mode
  • Kong Gateway가 지원하는 다양한 배포 토폴로지를 소개해요 — deployment topologies
  • Route, Gateway Service 같은 Kong Gateway 엔티티 개념을 정리해요 — Kong Gateway entities