Search code examples
unit-testingluafirst-class-functions

Lua: how to verify that a table contains a specific function


I'm developing a module that returns a table full of functions based on the arguments that are passed in. Specifically, the module returns a set of data transformation rules (functions) that need to be applied to a data set depending on which customer is sending it.

I decided to decouple my rule library (biz logic) from the code that decides which of the rules should be applied (config logic).

Here's the unit test I'm writing to verify that the ruleBuilder is adding the correct rule (function) based on one of my scenarios:

ruleBuilder = require("ruleBuilder")
ruleLibrary = require("ruleLibrary")
local rules = ruleBuilder.assembleRules("Customer1231")

assert(rules[1] == ruleLibrary.missingSSNRule)

Is this the correct way to do that verification? Will this work even if the ruleLibrary.missingSSNRule function has references to several other functions via a closure or parameter?


Solution

  • To verify that a table contains a particular function you may use the fact that keys in Lua tables can be anything (including functions). In your assembleRules code you can write something like this:

    function assembleRules(...)
      ...
      return {
        [someOtherCoolModule.coolFunction] = someOtherCoolModule.coolFunction,
        [yetAnotherModule.anotherFunction] = yetAnotherModule.anotherFunction,
      }
    end
    

    Then later you can simply check if the key exists:

    local rules = ruleBuilder.assembleRules("somedata")
    assert(rules[someOtherCoolModule.coolFunction])