robin/laufey

git clone https://git.robinwobin.dev/robin/laufey

Justin M. KeyesMerge #40865 from justinmk/fixcif907614088

master
1.8 KiB81 linesraw
1--- @class test.assert
2local M = {}
3
4local FORMAT_DEPTH = 100
5
6--- @param value any
7--- @return string
8local function fmt(value)
9  if type(value) == 'string' then
10    return string.format('%q', value)
11  end
12
13  local ok, inspected = pcall(vim.inspect, value, { depth = FORMAT_DEPTH })
14  if ok then
15    return inspected
16  end
17
18  return tostring(value)
19end
20
21--- @param condition boolean
22--- @param value any
23--- @param context any
24--- @param message string
25local function assert_value(condition, value, context, message)
26  if not condition then
27    error((context ~= nil and tostring(context) .. ': ' or '') .. message, 0)
28  end
29  return value
30end
31
32--- @param expected any
33--- @param actual any
34--- @param comparator string
35--- @return string
36local function comparison_message(expected, actual, comparator)
37  return ('Expected values to be %s.\nExpected:\n%s\nActual:\n%s'):format(
38    comparator,
39    fmt(expected),
40    fmt(actual)
41  )
42end
43
44--- @param expected any
45--- @param actual any
46--- @param context? any
47--- @return any
48function M.eq(expected, actual, context)
49  return assert_value(
50    vim.deep_equal(expected, actual),
51    actual,
52    context,
53    comparison_message(expected, actual, 'equal')
54  )
55end
56
57--- @param expected any
58--- @param actual any
59--- @param context? any
60--- @return any
61function M.neq(expected, actual, context)
62  return assert_value(
63    not vim.deep_equal(expected, actual),
64    actual,
65    context,
66    ('Expected values to differ.\nValue:\n%s'):format(fmt(actual))
67  )
68end
69
70return setmetatable(M, {
71  --- @param condition any
72  --- @param message? string
73  --- @param level? integer
74  __call = function(_, condition, message, level, ...)
75    if condition then
76      return condition, message, level, ...
77    end
78
79    error(message or 'assertion failed!', (type(level) == 'number' and level or 1) + 1)
80  end,
81})