Search code examples
perlnginxtestingapache-apisix

How to add a linebreak in test::base/test::nginx/perl test case?


I was writing test cases while implementing a feature in Apache APISIX where I came across a stubborn error where there is an extra linebreak in the "got" part in comparison to the "expected" part.

Test result

Here is the code for the test:

=== TEST 8: get value from vault: token env var wrong/missing
--- config
    location /t {
        content_by_lua_block {
            local vault = require("apisix.secret.vault")
            local conf = {
                prefix = "kv/apisix",
                token = "$ENV://VALT_TOKEN",
                uri = "http://127.0.0.1:8200"
            }
            local value, err = vault.get(conf, "/apisix-key/jack/key")
            if err then
                return ngx.say(err)
            end

            ngx.print("value")
        }
    }
--- request
GET /t
--- response_body
failed to decode result, res: {"errors":["permission denied"]}



=== TEST 9: get value from vault: token env var contains wrong token
--- config
    location /t {
        content_by_lua_block {
            local vault = require("apisix.secret.vault")
            local conf = {
                prefix = "kv/apisix",
                token = "$ENV://WRONG_VAULT_TOKEN",
                uri = "http://127.0.0.1:8200"
            }
            local value, err = vault.get(conf, "/apisix-key/jack/key")
            if err then
                return ngx.say(err)
            end

            ngx.print("value")
        }
    }
--- request
GET /t
--- response_body
failed to decode result, res: {"errors":["permission denied"]}

I tried adding "\n" at the end of the expected part like so:

--- response_body
failed to decode result, res: {"errors":["permission denied"]}\n

But that didn't work. So I tried to surround the "expected" part in quotes "..." so that the linebreak gets included that didn't work either.

Another approach would be to remove the linebreak from the "got" part by writing some code but I think that wouldn't be an ideal thing to do (modifying the response).

Thanks in advance!!

Here's the link to the workflow action run.


Solution

  • It was simple! I didn't know we could use regex to match "got" with "expected". This is how I did it.

    I replaced this:

    --- response_body
    failed to decode result, res: {"errors":["permission denied"]}
    

    With this:

    --- response_body_like
    failed to decode result, res: {\"errors\":\[\"permission denied\"\]}\n
    

    The idea was to use the response_body_like construct to be able to use regex for expression matching. Thanks to this blog.