单元测试

本文原文链接:https://docs.konghq.com/1.1.x/plugin-development/tests/

介绍

如果你认真对待你写的插件,你可能想为它编写一些测试。Lua的单元测试很简单,并且可以使用许多测试框架。但是,您可能还想编写集成测试。Kong可以再次为您提供支援。

编写集成测试

Kong的首选测试框架是busted,它与resty-cli解释器一起运行,但如果您愿意,可以自由使用另一个。在Kong存储库中,可以在bin/busted找到 busted 的可执行文件。

Kong为您提供了一个帮助程序,可以在测试套件中从Lua启动和停止它:spec.helpers。此助手还提供了在运行测试之前在数据存储区中插入fixtures的方法,以及删除,以及各种其他helper。

如果您在自己的存储库中编写插件,则需要复制以下文件,直到Kong测试框架发布:

  • bin/busted: 与resty-cli解释器一起运行的 busted 的可执行文件
  • spec/helpers.lua:Kong的helper函数 可以从busted中 启动/关闭kong
  • spec/kong_tests.conf:使用helpers模块运行的Kong实例的配置文件

假设您的LUA_PATH中有spec.helpers模块,您可以使用以下Lua代码来启动和停止Kong:

  1. local helpers = require "spec.helpers"
  2. for _, strategy in helpers.each_strategy() do
  3. describe("my plugin", function()
  4. local bp = helpers.get_db_utils(strategy)
  5. setup(function()
  6. local service = bp.services:insert {
  7. name = "test-service",
  8. host = "httpbin.org"
  9. }
  10. bp.routes:insert({
  11. hosts = { "test.com" },
  12. service = { id = service.id }
  13. })
  14. -- start Kong with your testing Kong configuration (defined in "spec.helpers")
  15. assert(helpers.start_kong( { plugins = "bundled,my-plugin" }))
  16. admin_client = helpers.admin_client()
  17. end)
  18. teardown(function()
  19. if admin_client then
  20. admin_client:close()
  21. endhttps://github.com/Kong/kong/tree/master/spec/03-plugins/09-key-auth
  22. helpers.stop_kong()
  23. end)
  24. before_each(function()
  25. proxy_client = helpers.proxy_client()
  26. end)
  27. after_each(function()
  28. if proxy_client then
  29. proxy_client:close()
  30. end
  31. end)
  32. describe("thing", function()
  33. it("should do thing", function()
  34. -- send requests through Kong
  35. local res = proxy_client:get("/get", {
  36. headers = {
  37. ["Host"] = "test.com"
  38. }
  39. })
  40. local body = assert.res_status(200, res)
  41. -- body is a string containing the response
  42. end)
  43. end)
  44. end)
  45. end

提醒:通过test Kong配置文件,Kong运行在代理监听端口9000(HTTP),9443 (HTTPS)和端口9001上的Admin API。

如果想看一下真实的例子,可以来这里看一看 Key-Auth plugin specs