[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 name string
10---@return MiniTest.child, table
11function testutils.setup(name)
12 local child = MiniTest.new_child_neovim()
13 local T = MiniTest.new_set {
14 hooks = {
15 post_once = child.stop,
16 pre_case = function()
17 child.restart { "-u", testutils.mininit_path }
18 end,
19 },
20 }
21
22 T[name] = MiniTest.new_set {}
23 return child, T
24end
25
26---@generic T
27---@param a T
28---@param b T
29---@return boolean
30function testutils.eq(a, b)
31 return MiniTest.expect.equality(a, b)
32end
33
34---@return string
35function testutils.tmpfile()
36 return vim.fn.tempname() .. ".go"
37end
38
39---@param path string
40---@return string
41function testutils.readfile(path)
42 return vim.fn.join(vim.fn.readfile(path), "\n")
43end
44
45---@param fpath string
46---@param contents string
47function testutils.writefile(fpath, contents)
48 vim.fn.writefile(vim.split(contents, "\n"), fpath)
49end
50
51---@param fpath string
52function testutils.deletefile(fpath)
53 vim.fn.delete(fpath)
54end
55
56---@class gopher.TestUtilsFixtures
57---@field input string
58---@field output string
59
60---@param fixture string
61---@return gopher.TestUtilsFixtures
62function testutils.get_fixtures(fixture)
63 return {
64 input = testutils.readfile(vim.fs.joinpath(testutils.fixtures_dir, fixture) .. "_input.go"),
65 output = testutils.readfile(vim.fs.joinpath(testutils.fixtures_dir, fixture) .. "_output.go"),
66 }
67end
68
69---@class gopher.TestUtilsSetup
70---@field tmp string
71---@field fixtures gopher.TestUtilsFixtures
72
73---@param fixture string
74---@param child MiniTest.child
75---@param pos? number[]
76---@return gopher.TestUtilsSetup
77function testutils.setup_test(fixture, child, pos)
78 local tmp = testutils.tmpfile()
79 local fixtures = testutils.get_fixtures(fixture)
80
81 testutils.writefile(tmp, fixtures.input)
82 child.cmd("silent edit " .. tmp)
83
84 if pos then
85 child.fn.setpos(".", { child.fn.bufnr(tmp), unpack(pos) })
86 end
87
88 return {
89 tmp = tmp,
90 fixtures = fixtures,
91 }
92end
93
94---@param inp gopher.TestUtilsSetup
95function testutils.cleanup(inp)
96 testutils.deletefile(inp.tmp)
97end
98
99return testutils