Testing Nginx Lua scripts with Busted

423 views
Skip to first unread message

Eugene Shvartsman

unread,
Mar 4, 2021, 5:14:33 PM3/4/21
to openresty-en
I am trying to write test code for Lua scripts that are run I Nginx via `init_by_lua_file` 

The script file I am testing reads a bunch of values, like `ngx.req.get_headers()["User-Agent"], and returns a result based on their combination. 

To set up testing I wrote a `busted` test file executed via `resty` CLI that attempts to set the headers and get the results from my script's function:

```
describe("Initilization code", function()
  describe("block some things", function()
    it("should block some request", function()
      ngx.header["User-Agent"] = "Mozilla/5.0"
```
When I run this code via `resty` I get the following error:
`API disabled in the current context` on the `ngx.header["User-Agent"] = "Mozilla/5.0"` line

I am completely new to Nginx, Lua and Busted so it's kind of difficult to figure this out. Can I even run these tests using Busted? Or do I need to use the OpenResty Perl framework? 

If I am on the right track how do I switch context to (I assume) `init_by_lua_file`?

Thanks!

Piotr Przybylski

unread,
Apr 12, 2021, 7:33:39 AM4/12/21
to openresty-en
It's been some time since you asked, but maybe you will still find it useful.

For my project, I divided my code into two parts:
1. nginx integration (*_by_lua_file) - the only layer that accesses ngx.var and other nginx APIs that require access to live requests, tested by:
* Perl, when I need to check for some low-level stuff
* busted - a helper script starts nginx and sets up test environment (ngx.pipe + resty.signal), tests use resty.http to verify application behavior - when I need to test something simple
* integration tests that start my application in Docker container and use HTTP to verify behavior - when I need something complex and statically typed language helps to stay sane
2. library code: tested using busted
Reply all
Reply to author
Forward
0 new messages