robin/laufey

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

robinmerge: 1dc9728daa1d8a2702

master
11.2 KiB359 linesraw
1local n = require('test.functional.testnvim')()
2local t = require('test.testutil')
3local describe, it, before_each = t.describe, t.it, t.before_each
4local skip_integ = os.getenv('NVIM_TEST_INTEG') ~= '1'
5
6local exec_lua = n.exec_lua
7
8-- Serve one request and record what curl sent.
9local function http_server(body, status)
10  t.skip(n.fn.executable('curl') == 0, 'curl not found')
11  return exec_lua(function()
12    vim.env.no_proxy = '127.0.0.1'
13    local server = assert(vim.uv.new_tcp())
14    assert(server:bind('127.0.0.1', 0))
15    assert(server:listen(1, function(err)
16      assert(not err, err)
17      local client = assert(vim.uv.new_tcp())
18      assert(server:accept(client))
19      server:close()
20      local data = ''
21      client:read_start(function(read_err, chunk)
22        assert(not read_err, read_err)
23        assert(chunk, 'Connection closed before the request was complete')
24        data = data .. chunk
25        -- TCP can split the headers and body across reads.
26        local header_end = data:find('\r\n\r\n', 1, true)
27        if not header_end then
28          return
29        end
30        local headers = {}
31        for name, value in data:sub(1, header_end + 1):gmatch('\r\n([^:]+):[ \t]*([^\r\n]*)') do
32          headers[name:lower()] = value
33        end
34        local request_body = data:sub(header_end + 4)
35        if #request_body < (tonumber(headers['content-length']) or 0) then
36          return
37        end
38        client:read_stop()
39        local method = data:match('^(%S+)')
40        _G.http_request = { method = method, headers = headers, body = request_body }
41        local response = ('HTTP/1.1 %s\r\nContent-Length: %d\r\nConnection: close\r\n\r\n%s'):format(
42          status or '200 OK',
43          #body,
44          method == 'HEAD' and '' or body
45        )
46        client:write(response, function(write_err)
47          assert(not write_err, write_err)
48          client:close()
49        end)
50      end)
51    end))
52    return ('http://127.0.0.1:%d/'):format(server:getsockname().port)
53  end)
54end
55
56---@param method vim.net.HttpMethod
57---@param url string
58---@param opts? vim.net.request.Opts
59---@return table
60local function request(method, url, opts)
61  exec_lua(function()
62    vim.net.request(method, url, opts, function(err, res)
63      vim.rpcnotify(1, 'response', { error = err, response = res and res.body })
64    end)
65  end)
66
67  local msg = assert(n.next_msg(), 'Timed out waiting for HTTP response')
68  t.eq({ 'notification', 'response' }, { msg[1], msg[2] })
69  return msg[3][1]
70end
71
72describe('vim.net.request', function()
73  before_each(function()
74    n:clear()
75  end)
76
77  it('fetches a URL into memory (async success)', function()
78    ---@type table
79    local result = request('GET', http_server('hello'))
80
81    t.eq(nil, result.error)
82    t.eq('hello', result.response)
83  end)
84
85  it("detects filetype, sets 'nomodified'", function()
86    t.skip(skip_integ, 'NVIM_TEST_INTEG not set (network integration test)')
87
88    local rv = exec_lua(function()
89      vim.cmd('runtime! plugin/nvim/net.lua')
90      vim.cmd('runtime! filetype.lua')
91      -- github raw dump of a small lua file in the neovim repo
92      vim.cmd(
93        'edit https://raw.githubusercontent.com/neovim/neovim/master/runtime/syntax/tutor.lua'
94      )
95      vim.wait(2000, function()
96        return vim.bo.filetype ~= ''
97      end)
98      -- wait for buffer to have content
99      vim.wait(2000, function()
100        return vim.fn.wordcount().bytes > 0
101      end)
102      vim.wait(2000, function()
103        return vim.bo.modified == false
104      end)
105      return { vim.bo.filetype, vim.bo.modified }
106    end)
107
108    t.eq('lua', rv[1])
109    t.eq(false, rv[2], 'Expected buffer to be unmodified for remote content')
110  end)
111
112  it('calls on_response with error on 404 (async failure)', function()
113    local result = request('GET', http_server('', '404 Not Found'))
114    t.matches('404', result.error)
115  end)
116
117  it('plugin writes output to buffer', function()
118    local url = http_server('<html>test</html>')
119
120    local content = exec_lua(function()
121      ---@type string[]
122      local lines
123
124      local buf = vim.api.nvim_create_buf(false, true)
125      ---@diagnostic disable-next-line: param-type-mismatch
126      vim.net.request(url, { outbuf = buf })
127
128      vim.wait(2000, function()
129        lines = vim.api.nvim_buf_get_lines(buf, 0, -1, false)
130        return lines[1] ~= ''
131      end)
132
133      return lines
134    end)
135    assert(content and content[1]:find('html'))
136  end)
137
138  it('works with :read', function()
139    t.skip(skip_integ, 'NVIM_TEST_INTEG not set (network integration test)')
140
141    local content = exec_lua(function()
142      vim.cmd('runtime plugin/net.lua')
143      ---@type string[]
144      local lines
145
146      vim.api.nvim_buf_set_lines(0, 0, -1, false, { 'Here is some text' })
147      vim.cmd(':read https://example.com')
148
149      vim.wait(2000, function()
150        lines = vim.api.nvim_buf_get_lines(0, 0, -1, false)
151        return #lines > 1
152      end)
153
154      return lines
155    end)
156
157    t.eq(true, content ~= nil)
158    t.eq(true, content[1]:find('Here') ~= nil)
159    t.eq(true, content[2]:find('html') ~= nil)
160  end)
161
162  it('opens remote tar.gz URLs as tar archives', function()
163    t.skip(skip_integ, 'NVIM_TEST_INTEG not set (network integration test)')
164
165    local rv = exec_lua(function()
166      vim.cmd('runtime! plugin/net.lua')
167      vim.cmd('runtime! plugin/tarPlugin.vim')
168
169      vim.cmd(
170        'edit https://github.com/neovim/neovim/releases/download/nightly/nvim-macos-x86_64.tar.gz'
171      )
172
173      vim.wait(2500, function()
174        return vim.bo.filetype == 'tar' or vim.b.tarfile ~= nil
175      end)
176
177      return {
178        filetype = vim.bo.filetype,
179        modified = vim.bo.modified,
180        tarfile = vim.b.tarfile ~= nil,
181      }
182    end)
183
184    t.eq('tar', rv.filetype)
185    t.eq(false, rv.modified)
186    t.eq(true, rv.tarfile)
187  end)
188
189  it('dispatches remote zip URLs to zip.lua', function()
190    n.clear({ args_rm = { '-u' } })
191    local fixture =
192      vim.fs.joinpath(t.paths.test_source_path, 'test/functional/fixtures/zip/browser.zip')
193    local rv = exec_lua(function(path)
194      vim.net.request = function(_, opts, callback)
195        assert(vim.uv.fs_copyfile(path, opts.outpath))
196        callback(nil)
197      end
198      vim.cmd.edit('https://example.com/browser.zip')
199      vim.wait(1000, function()
200        return vim.b.nvim_zip ~= nil
201      end)
202      require('nvim.zip').open_parent(0, vim.api.nvim_buf_get_name(0))
203      return {
204        legacy = vim.g.loaded_zip ~= nil,
205        name = vim.api.nvim_buf_get_name(0),
206        nvim_zip = vim.b.nvim_zip ~= nil,
207      }
208    end, fixture)
209
210    t.eq(false, rv.legacy)
211    t.eq('https://example.com/browser.zip', rv.name)
212    t.eq(true, rv.nvim_zip)
213  end)
214
215  it('downloads a live remote zip URL', function()
216    t.skip(skip_integ, 'NVIM_TEST_INTEG not set (network integration test)')
217    n.clear({ args = { '--clean' } })
218
219    local rv = exec_lua(function()
220      vim.cmd('edit https://github.com/neovim/neovim/releases/download/nightly/nvim-win-arm64.zip')
221
222      vim.wait(2500, function()
223        return vim.bo.filetype == 'zip' or vim.b.zipfile ~= nil
224      end)
225
226      require('nvim.zip').open_parent(0, vim.api.nvim_buf_get_name(0))
227      return {
228        filetype = vim.bo.filetype,
229        legacy = vim.g.loaded_zip ~= nil,
230        modified = vim.bo.modified,
231        name = vim.api.nvim_buf_get_name(0),
232        nvim_zip = vim.b.nvim_zip ~= nil,
233        zipfile = vim.b.zipfile ~= nil,
234      }
235    end)
236
237    t.eq('zip', rv.filetype)
238    t.eq(false, rv.legacy)
239    t.eq(false, rv.modified)
240    t.eq('https://github.com/neovim/neovim/releases/download/nightly/nvim-win-arm64.zip', rv.name)
241    t.eq(true, rv.nvim_zip)
242    t.eq(false, rv.zipfile)
243  end)
244
245  it('accepts custom headers', function()
246    ---@type table
247    local result = request('GET', http_server('hello'), {
248      headers = {
249        Authorization = 'Bearer test-token',
250        ['X-Custom-Header'] = 'custom-value',
251        ['Empty'] = '',
252      },
253    })
254
255    t.eq(nil, result.error)
256    local headers = exec_lua('return http_request.headers')
257    t.eq('Bearer test-token', headers.authorization, 'Expected Authorization header')
258    t.eq('custom-value', headers['x-custom-header'], 'Expected X-Custom-Header')
259    t.eq('', headers.empty, 'Expected Empty header')
260  end)
261
262  it('accepts multiple HTTP methods', function()
263    local function assert_accept_method(method)
264      local result = request(method, http_server('hello'))
265      t.eq(nil, result.error)
266      t.eq(method, exec_lua('return http_request.method'))
267    end
268
269    assert_accept_method('GET')
270    assert_accept_method('PUT')
271    assert_accept_method('PATCH')
272    assert_accept_method('DELETE')
273
274    -- HEAD request
275    local result = request('HEAD', http_server('hello'))
276    t.eq(nil, result.error)
277    t.eq('HEAD', exec_lua('return http_request.method'))
278
279    -- testing body payload
280    result = request('POST', http_server('hello'), {
281      body = '{"a": 1}',
282      headers = {
283        ['Content-Type'] = 'application/json',
284      },
285    })
286    t.eq(nil, result.error)
287    local sent = exec_lua('return http_request')
288    t.eq('POST', sent.method)
289    t.eq('application/json', sent.headers['content-type'])
290    t.eq('{"a": 1}', sent.body)
291  end)
292
293  it('validation', function()
294    local function assert_wrong_request(expected_err, method, opts)
295      if type(method) ~= 'string' then
296        opts = method
297        method = 'GET'
298      end
299
300      local result = t.pcall_err(exec_lua, function()
301        vim.net.request(method, 'https://example.com', opts)
302      end)
303      t.matches(expected_err, result)
304    end
305
306    -- headers asserts
307    assert_wrong_request('opts.headers: expected table, got number', { headers = 123 })
308
309    --- FIXME(ellisonleao): this special assert is failing because the opts table is putting [""] in
310    --- the key value instead of [123] upon calling the helper method
311    -- assert_wrong_request(
312    --   'headers keys and values must be strings',
313    --   { headers = { [123] = 'value' } }
314    -- )
315
316    assert_wrong_request('headers keys and values must be strings', { headers = { Header = 123 } })
317    assert_wrong_request(
318      'header keys must not start with @ or end with : and ;',
319      { headers = { ['Header:'] = 'value' } }
320    )
321    assert_wrong_request(
322      'header keys must not start with @ or end with : and ;',
323      { headers = { ['Header;'] = 'value' } }
324    )
325    assert_wrong_request(
326      'header keys must not start with @ or end with : and ;',
327      { headers = { ['@filename'] = '' } }
328    )
329
330    -- body asserts
331    assert_wrong_request(
332      'opts.body: expected body should be string and not start with @',
333      { body = 123 }
334    )
335    assert_wrong_request(
336      'opts.body: expected body should be string and not start with @',
337      { body = {} }
338    )
339    assert_wrong_request(
340      'opts.body: expected body should be string and not start with @',
341      { body = '@test' }
342    )
343
344    -- OPTIONS is not accepted
345    assert_wrong_request(
346      'expected method should be one of GET, POST, PUT, PATCH, HEAD, DELETE, got OPTIONS',
347      'OPTIONS'
348    )
349    -- lowercase methods are not accepted as well
350    assert_wrong_request(
351      'expected method should be one of GET, POST, PUT, PATCH, HEAD, DELETE, got options',
352      'options'
353    )
354    assert_wrong_request(
355      'expected method should be one of GET, POST, PUT, PATCH, HEAD, DELETE, got get',
356      'get'
357    )
358  end)
359end)