Using the ctx · 58 / 69
Simulate a cache with a function fake
YOUR TASK
Make this happen
Return the fallback for a miss or failed call, and keep valid cached values. The spy checks how often the host was called and which key it received. Each test case has fresh mocks and call history.
Read the cases in
lesson.test.lua, then choose Check solution to see what needs to change.Update
subject.luauntil every test passes. Keep the supplied tests unchanged.
Read the starter and tests
subject.lua
exports.lookup = function(key: string, fallback: string) local ok, value = ctx.cache.get(key) return value end
lesson.test.lua
local t = require("test")
local subject = require("cococo.subject")
t.it("returns values by key and handles a miss", function()
t.mock.host("ctx.cache.get"):using(function(key)
if key == "job:42" then
return true, "ready"
end
return true, nil
end)
local s = subject.load()
t.expect(s.lookup("job:42", "unknown")):eq("ready")
t.expect(s.lookup("job:99", "unknown")):eq("unknown")
t.expect(t.mock.spy("ctx.cache.get")):called_times(2)
t.expect(t.mock.spy("ctx.cache.get")):called_with("job:99")
end)
t.it("handles a failed cache call", function()
t.mock.host("ctx.cache.get"):returns(false, "offline")
local s = subject.load()
t.expect(s.lookup("job:42", "unknown")):eq("unknown")
end)