summaryrefslogtreecommitdiff
path: root/lua/99/test/logger_spec.lua
blob: c7bda8420e1ad011f91004fb07715a10bf445f43 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
-- luacheck: globals describe it assert before_each after_each
local Logger = require("99.logger.logger")
local time = require("99.time")
local eq = assert.are.same

local now = 0
time.now = function()
  return now
end

--- @class _99.Test.Logger.RequestLogs
--- @field last_access number
--- @field logs table<string, any>

--- @param all_logs string[][]
--- @return _99.Test.Logger.RequestLogs
local function l(all_logs)
  local out = {}
  for _, logs in ipairs(all_logs) do
    local lines = {}
    table.insert(out, lines)
    for _, log_line in ipairs(logs) do
      table.insert(lines, vim.json.decode(log_line))
    end
  end
  return out
end

describe("Logger", function()
  after_each(function()
    Logger.reset()
    now = 0
    Logger.set_max_cached_requests(2)
  end)

  it("no caching of non ID'd logs.  Global logs", function()
    eq({}, Logger.logs())

    local ok = pcall(Logger.debug, Logger, "test log")
    eq({}, Logger.logs())
    eq(ok, false)
  end)

  it("cache logs, keep max count", function()
    eq({}, Logger.logs())
    local logger = Logger:set_id(69)

    logger:debug("test log")

    eq({
      {
        { level = "DEBUG", id = 69, msg = "test log" },
      },
    }, l(Logger.logs()))

    local logger2 = logger:set_id(420)
    now = 1000
    logger2:error("error log")

    eq({
      {
        { level = "ERROR", id = 420, msg = "error log" },
      },
      {
        { level = "DEBUG", id = 69, msg = "test log" },
      },
    }, l(Logger.logs()))

    now = 1001
    logger:warn("warn log")

    eq({
      {
        { level = "DEBUG", id = 69, msg = "test log" },
        { level = "WARN", id = 69, msg = "warn log" },
      },
      {
        { level = "ERROR", id = 420, msg = "error log" },
      },
    }, l(Logger.logs()))

    local logger3 = logger:set_id(1337)
    now = 1002
    logger3:info("info log")

    eq({
      {
        { level = "INFO", id = 1337, msg = "info log" },
      },
      {
        { level = "DEBUG", id = 69, msg = "test log" },
        { level = "WARN", id = 69, msg = "warn log" },
      },
    }, l(Logger.logs()))
  end)
end)