[mirror] Make your go dev experience better
github.com/olexsmir/gopher.nvim
neovim
golang
1local base_dir = vim.env.GOPHER_DIR or vim.fn.expand "%:p:h"
2
3---@class gopher.TestUtils
4local testutils = {}
5
6testutils.mininit_path = vim.fs.joinpath(base_dir, "scripts", "minimal_init.lua")
7testutils.fixtures_dir = vim.fs.joinpath(base_dir, "spec/fixtures")
8
9---@param mod string Module name for which to create a nested test set.
10---@return MiniTest.child child nvim client.
11---@return table T root test set created by `MiniTest.new_set()`.
12---@return table mod_name nested set of tests in `T[mod]`.
13function testutils.setup(mod)
14 local child = MiniTest.new_child_neovim()
15 local T = MiniTest.new_set {
16 hooks = {
17 post_once = child.stop,
18 pre_case = function()
19 child.restart { "-u", testutils.mininit_path }
20 end,
21 },
22 }
23
24 T[mod] = MiniTest.new_set {}
25 return child, T, T[mod]
26end
27
28---@generic T
29---@param a T
30---@param b T
31---@return boolean
32function testutils.eq(a, b)
33 return MiniTest.expect.equality(a, b)
34end
35
36---@return string
37function testutils.tmpfile()
38 return vim.fn.tempname() .. ".go"
39end
40
41---@param path string
42---@return string
43function testutils.readfile(path)
44 return vim.fn.join(vim.fn.readfile(path), "\n")
45end
46
47---@param fpath string
48---@param contents string
49function testutils.writefile(fpath, contents)
50 vim.fn.writefile(vim.split(contents, "\n"), fpath)
51end
52
53---@param fpath string
54function testutils.deletefile(fpath)
55 vim.fn.delete(fpath)
56end
57
58---@class gopher.TestUtilsFixtures
59---@field input string
60---@field output string
61
62---@param fixture string
63---@return gopher.TestUtilsFixtures
64function testutils.get_fixtures(fixture)
65 return {
66 input = testutils.readfile(vim.fs.joinpath(testutils.fixtures_dir, fixture) .. "_input.go"),
67 output = testutils.readfile(vim.fs.joinpath(testutils.fixtures_dir, fixture) .. "_output.go"),
68 }
69end
70
71---@class gopher.TestUtilsSetup
72---@field tmp string
73---@field fixtures gopher.TestUtilsFixtures
74---@field bufnr number
75
76---@param fixture string
77---@param child MiniTest.child
78---@param pos? number[]
79---@return gopher.TestUtilsSetup
80function testutils.setup_test(fixture, child, pos)
81 vim.validate("pos", pos, "table", true)
82
83 local tmp = testutils.tmpfile()
84 local fixtures = testutils.get_fixtures(fixture)
85
86 testutils.writefile(tmp, fixtures.input)
87 child.cmd("silent edit " .. tmp)
88
89 local bufnr = child.fn.bufnr(tmp)
90 if pos then
91 assert(#pos == 2, "invalid cursor position")
92
93 child.fn.setpos(".", { bufnr, unpack(pos) })
94 end
95
96 return {
97 tmp = tmp,
98 bufnr = bufnr,
99 fixtures = fixtures,
100 }
101end
102
103---@param inp gopher.TestUtilsSetup
104function testutils.cleanup(inp)
105 testutils.deletefile(inp.tmp)
106end
107
108return testutils