Writing tests

If you are serious about your plugin, you probably want to write tests for it. Unit testing Lua is easy, and many testing frameworks are available. However, you might also want to write integration tests. Again, Kong has your back.

Write integration tests

The preferred testing framework for Kong is busted running with the resty-cli interpreter, though you are free to use a different one. In the Kong repository, the busted executable can be found at bin/busted.

Kong provides you with a helper to start and stop it from Lua in your test suite: spec.helpers. This helper also provides you with ways to insert fixtures in your datastore before running your tests, as well as dropping it, and various other helpers.

If you are writing your plugin in your own repository, you will need to copy the following files until the Kong testing framework is released:

  • bin/busted: the busted executable running with the resty-cli interpreter
  • spec/helpers.lua: helper functions to start/stop Kong from busted
  • spec/kong_tests.conf: a configuration file for your running your test Kong instances with the helpers module

Assuming that the spec.helpers module is available in your LUA_PATH, you can use the following Lua code in busted to start and stop 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. end
  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

With the test Kong configuration file, Kong is running with its proxy listening on port 9000 (HTTP), 9443 (HTTPS) and Admin API on port 9001.

For a real-world example, see the Key-Auth plugin specs.


Previous Extending the Admin API

Next Installation and Distribution