robin/laufey

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

Justin M. KeyesMerge #40579 from barrettruth/fix/del-keymap-lhs-only-30258256a88d0ac

master
13.2 KiB385 linesraw
1local t = require('test.testutil')
2local n = require('test.functional.testnvim')()
3
4local describe, it, before_each, setup = t.describe, t.it, t.before_each, t.setup
5local clear, fn, eq = n.clear, n.fn, t.eq
6local api = n.api
7local matches = t.matches
8local pcall_err = t.pcall_err
9
10local function read_mpack_file(fname)
11  if vim.fn.filereadable(fname) == 0 then
12    return nil
13  end
14  return vim.mpack.Unpacker()(vim.fn.readblob(fname))
15end
16
17describe("api_info()['version']", function()
18  before_each(clear)
19
20  it('returns API level', function()
21    local version = fn.api_info()['version']
22    local current = version['api_level']
23    local compat = version['api_compatible']
24    eq('number', type(current))
25    eq('number', type(compat))
26    assert(current >= compat)
27  end)
28
29  it('returns Nvim version', function()
30    local version = fn.api_info()['version']
31    local major = version['major']
32    local minor = version['minor']
33    local patch = version['patch']
34    local prerelease = version['prerelease']
35    local build = version['build']
36    eq('number', type(major))
37    eq('number', type(minor))
38    eq('number', type(patch))
39    eq('boolean', type(prerelease))
40    eq(1, fn.has('nvim-' .. major .. '.' .. minor .. '.' .. patch))
41    eq(0, fn.has('nvim-' .. major .. '.' .. minor .. '.' .. (patch + 1)))
42    eq(0, fn.has('nvim-' .. major .. '.' .. (minor + 1) .. '.' .. patch))
43    eq(0, fn.has('nvim-' .. (major + 1) .. '.' .. minor .. '.' .. patch))
44    assert(build == vim.NIL or type(build) == 'string')
45  end)
46end)
47
48describe('api metadata', function()
49  local function name_table(entries)
50    local by_name = {}
51    for _, e in ipairs(entries) do
52      by_name[e.name] = e
53    end
54    return by_name
55  end
56
57  --- Remove or patch metadata that is not essential to backwards-compatibility.
58  --- @param f gen_api_dispatch.Function.Exported
59  local function normalize_func_metadata(f)
60    -- Dictionary was renamed to Dict. That doesn't break back-compat because it names the
61    -- same RPC map type.
62    f.return_type = f.return_type:gsub('Dictionary', 'Dict')
63    f.return_type = f.return_type:gsub('^ArrayOf%(.*', 'Array')
64
65    f.deprecated_since = nil
66    for idx, _ in ipairs(f.parameters) do
67      -- Dictionary was renamed to Dict. That doesn't break back-compat because it names the
68      -- same RPC map type.
69      f.parameters[idx][1] = f.parameters[idx][1]:gsub('Dictionary', 'Dict')
70      f.parameters[idx][1] = f.parameters[idx][1]:gsub('ArrayOf%(.*', 'Array')
71
72      f.parameters[idx][2] = '' -- Remove parameter name.
73      -- Strip the `optional` flag: `assert_func_backcompat` checks it asymmetrically (relaxing a
74      -- param to optional is allowed, the reverse is breaking).
75      f.parameters[idx][3] = nil
76    end
77
78    if string.sub(f.name, 1, 4) ~= 'nvim' then
79      f.method = nil
80    end
81    return f
82  end
83
84  --- Checks that the current signature of a function is backwards-compatible with the previous
85  --- version, per ":help api-contract".
86  --- @param old_fn gen_api_dispatch.Function.Exported
87  --- @param new_fn gen_api_dispatch.Function.Exported
88  local function assert_func_backcompat(old_fn, new_fn)
89    -- Optional param must stay optional.
90    for idx, old_param in ipairs(old_fn.parameters) do
91      local new_param = new_fn.parameters[idx]
92      if old_param[3] and new_param and not new_param[3] then
93        error(('"%s": parameter %d was optional, now required'):format(old_fn.name, idx))
94      end
95    end
96    while #new_fn.parameters > #old_fn.parameters and new_fn.parameters[#new_fn.parameters][3] do
97      table.remove(new_fn.parameters)
98    end
99    old_fn = normalize_func_metadata(old_fn)
100    new_fn = normalize_func_metadata(new_fn)
101    if old_fn.return_type == 'void' then
102      old_fn.return_type = new_fn.return_type
103    end
104    eq(old_fn, new_fn)
105  end
106
107  local function check_ui_event_compatible(old_e, new_e)
108    -- check types of existing params are the same
109    -- adding parameters is ok, but removing params is not (gives nil error)
110    eq(old_e.since, new_e.since, old_e.name)
111    for i, p in ipairs(old_e.parameters) do
112      eq(new_e.parameters[i][1], p[1], old_e.name)
113    end
114  end
115
116  --- Level 0 represents methods from 0.1.5 and earlier, when 'since' was not
117  --- yet defined, and metadata was not filtered of internal keys like 'async'.
118  ---
119  --- @param metadata { functions: gen_api_dispatch.Function[] }
120  local function clean_level_0(metadata)
121    for _, f in ipairs(metadata.functions) do
122      f.can_fail = nil
123      f.async = nil -- XXX: renamed to "fast".
124      f.receives_channel_id = nil
125      f.since = 0
126    end
127  end
128
129  local api_info --[[@type table]]
130  local compat --[[@type integer]]
131  local stable --[[@type integer]]
132  local api_level --[[@type integer]]
133  local old_api = {} ---@type { functions: gen_api_dispatch.Function[] }[]
134  setup(function()
135    clear() -- Ensure a session before requesting api_info.
136    --[[@type {  functions: gen_api_dispatch.Function[], version: {api_compatible: integer, api_level: integer, api_prerelease: boolean} }]]
137    api_info = api.nvim_get_api_info()[2]
138    compat = api_info.version.api_compatible
139    api_level = api_info.version.api_level
140    stable = api_info.version.api_prerelease and api_level - 1 or api_level
141
142    for level = compat, stable do
143      local path = ('test/functional/fixtures/api_level_' .. tostring(level) .. '.mpack')
144      old_api[level] = read_mpack_file(path)
145      if old_api[level] == nil then
146        local errstr = 'missing metadata fixture for stable level ' .. level .. '. '
147        if level == api_level and not api_info.version.api_prerelease then
148          errstr = (
149            errstr
150            .. 'If NVIM_API_CURRENT was bumped, '
151            .. "don't forget to set NVIM_API_PRERELEASE to true."
152          )
153        end
154        error(errstr)
155      end
156
157      if level == 0 then
158        clean_level_0(old_api[level])
159      end
160    end
161    -- No Nvim session will be used in the following tests.
162    n.check_close()
163  end)
164
165  it('preserves ArrayOf type metadata', function()
166    local funcs = name_table(api_info.functions)
167    eq('ArrayOf(String)', funcs.nvim_list_runtime_paths.return_type)
168    eq('ArrayOf(Integer, 2)', funcs.nvim_buf_get_mark.return_type)
169    eq('ArrayOf(String)', funcs.nvim_buf_set_lines.parameters[5][1])
170  end)
171
172  it('function parameters', function()
173    local funcs = name_table(api_info.functions)
174    eq({ 'String', 'src', false }, funcs.nvim_exec2.parameters[1])
175    eq({ 'Dict', 'opts', true }, funcs.nvim_exec2.parameters[2])
176    eq({ 'Dict', 'opts', true }, funcs.nvim_get_context.parameters[1])
177    eq({ 'String', 'name', false }, funcs.nvim_get_var.parameters[1])
178  end)
179
180  it('functions are compatible with old metadata or have new level', function()
181    local funcs_new = name_table(api_info.functions)
182    local funcs_compat = {}
183    for level = compat, stable do
184      for _, f in ipairs(old_api[level].functions) do
185        if funcs_new[f.name] == nil then
186          if f.since >= compat then
187            local msg =
188              'function "%s" was removed but exists in level %s which Nvim claims to be compatible with'
189            error((msg):format(f.name, f.since))
190          end
191        else
192          assert_func_backcompat(f --[[@as any]], funcs_new[f.name])
193        end
194      end
195      funcs_compat[level] = name_table(old_api[level].functions)
196    end
197
198    for _, f in ipairs(api_info.functions) do
199      if f.since <= stable then
200        local f_old = funcs_compat[f.since][f.name]
201        if f_old == nil then
202          if string.sub(f.name, 1, 4) == 'nvim' then
203            local errstr = ('function "%s" has too low `since` value. For new functions set it to "%s".'):format(
204              f.name,
205              (stable + 1)
206            )
207            if not api_info.version.api_prerelease then
208              errstr = (
209                errstr
210                .. ' Also bump NVIM_API_CURRENT and set '
211                .. 'NVIM_API_PRERELEASE to true in CMakeLists.txt.'
212              )
213            end
214            error(errstr)
215          else
216            error("function name '" .. f.name .. "' doesn't begin with 'nvim_'")
217          end
218        end
219      elseif f.since > api_level then
220        if api_info.version.api_prerelease then
221          error('New function ' .. f.name .. ' should use since value ' .. api_level)
222        else
223          error(
224            'function '
225              .. f.name
226              .. ' has since value > api_level. '
227              .. 'Bump NVIM_API_CURRENT and set '
228              .. 'NVIM_API_PRERELEASE to true in CMakeLists.txt.'
229          )
230        end
231      end
232    end
233  end)
234
235  it('param may not change from optional to required', function()
236    local function example_fn(opts_optional)
237      return {
238        name = 'nvim_example',
239        method = false,
240        since = 1,
241        return_type = 'void',
242        parameters = { { 'String', 'src', false }, { 'Dict', 'opts', opts_optional } },
243      }
244    end
245    -- "Required -> Optional" is allowed.
246    assert_func_backcompat(example_fn(false), example_fn(true))
247    -- "Optional -> Required" is breaking.
248    matches(
249      '"nvim_example": parameter 2 was optional, now required',
250      pcall_err(assert_func_backcompat, example_fn(true), example_fn(false))
251    )
252  end)
253
254  it('optional param may be added', function()
255    assert_func_backcompat({
256      name = 'nvim_example',
257      method = false,
258      since = 1,
259      return_type = 'void',
260      parameters = { { 'String', 'src', false } },
261    }, {
262      name = 'nvim_example',
263      method = false,
264      since = 1,
265      return_type = 'void',
266      parameters = { { 'String', 'src', false }, { 'Dict', 'opts', true } },
267    })
268  end)
269
270  it('UI events are compatible with old metadata or have new level', function()
271    local ui_events_new = name_table(api_info.ui_events)
272    local ui_events_compat = {}
273
274    -- UI events were formalized in level 3
275    for level = 3, stable do
276      for _, e in ipairs(old_api[level].ui_events) do
277        local new_e = ui_events_new[e.name]
278        if new_e ~= nil then
279          check_ui_event_compatible(e, new_e)
280        end
281      end
282      ui_events_compat[level] = name_table(old_api[level].ui_events)
283    end
284
285    for _, e in ipairs(api_info.ui_events) do
286      if e.since <= stable then
287        local e_old = ui_events_compat[e.since][e.name]
288        if e_old == nil then
289          local errstr = (
290            'UI event '
291            .. e.name
292            .. ' has too low since value. '
293            .. 'For new events set it to '
294            .. (stable + 1)
295            .. '.'
296          )
297          if not api_info.version.api_prerelease then
298            errstr = (
299              errstr
300              .. ' Also bump NVIM_API_CURRENT and set '
301              .. 'NVIM_API_PRERELEASE to true in CMakeLists.txt.'
302            )
303          end
304          error(errstr)
305        end
306      elseif e.since > api_level then
307        if api_info.version.api_prerelease then
308          error('New UI event ' .. e.name .. ' should use since value ' .. api_level)
309        else
310          error(
311            'UI event '
312              .. e.name
313              .. ' has since value > api_level. '
314              .. 'Bump NVIM_API_CURRENT and set '
315              .. 'NVIM_API_PRERELEASE to true in CMakeLists.txt.'
316          )
317        end
318      end
319    end
320  end)
321
322  it('ui_options are preserved from older levels', function()
323    local available_options = {}
324    for _, option in ipairs(api_info.ui_options) do
325      available_options[option] = true
326    end
327    -- UI options were versioned from level 4
328    for level = 4, stable do
329      for _, option in ipairs(old_api[level].ui_options) do
330        if not available_options[option] then
331          error('UI option ' .. option .. ' from stable metadata is missing')
332        end
333      end
334    end
335  end)
336end)
337
338describe('api: optional parameters', function()
339  before_each(clear)
340
341  it('may be omitted', function()
342    eq('table', type(api.nvim_get_context({})))
343    eq('table', type(api.nvim_get_context()))
344
345    api.nvim_exec2('let g:x = 41')
346    eq(41, api.nvim_get_var('x'))
347    eq({ output = 'hi' }, api.nvim_exec2('echo "hi"', { output = true }))
348
349    -- Lua bridge: vim.api
350    n.exec_lua([[vim.api.nvim_exec2('let g:y = 7')]])
351    eq(7, api.nvim_get_var('y'))
352    eq('table', n.exec_lua('return type(vim.api.nvim_get_context())'))
353  end)
354
355  it('omitted is equivalent to empty dict', function()
356    eq(n.parse_context(api.nvim_get_context({})), n.parse_context(api.nvim_get_context())) -- RPC path
357    eq(
358      n.parse_context(n.exec_lua('return vim.api.nvim_get_context({})')),
359      n.parse_context(n.exec_lua('return vim.api.nvim_get_context()'))
360    ) -- Lua-binding path
361  end)
362
363  it('validation', function()
364    matches(
365      'Wrong number of arguments: expecting 1 to 2 but got 3',
366      pcall_err(api.nvim_exec2, 'echo 1', {}, 'surplus')
367    )
368    matches(
369      'Wrong number of arguments: expecting at most 1 but got 2',
370      pcall_err(api.nvim_get_context, {}, 'surplus')
371    )
372    matches('Wrong number of arguments: expecting 1 to 2 but got 0', pcall_err(api.nvim_exec2))
373
374    -- Lua bridge: vim.api
375    matches(
376      'Expected 1 to 2 arguments',
377      pcall_err(n.exec_lua, [[vim.api.nvim_exec2('echo 1', {}, 'surplus')]])
378    )
379    matches('Expected 1 to 2 arguments', pcall_err(n.exec_lua, [[vim.api.nvim_exec2()]]))
380    matches(
381      'Expected at most 1 argument',
382      pcall_err(n.exec_lua, [[vim.api.nvim_get_context({}, 'surplus')]])
383    )
384  end)
385end)