[mirror] Make your go dev experience better
github.com/olexsmir/gopher.nvim
neovim
golang
1---@toc_entry Generating unit tests boilerplate
2---@tag gopher.nvim-gotests
3---@text gotests is utilizing the `gotests` tool to generate unit tests boilerplate.
4---@usage
5--- - Generate unit test for specific function/method:
6--- 1. Place your cursor on the desired function/method.
7--- 2. Run `:GoTestAdd`
8---
9--- - Generate unit tests for *all* functions/methods in current file:
10--- - run `:GoTestsAll`
11---
12--- - Generate unit tests *only* for *exported(public)* functions/methods:
13--- - run `:GoTestsExp`
14---
15--- You can also specify the template to use for generating the tests. See |gopher.nvim-config|
16--- More details about templates can be found at: https://github.com/cweill/gotests
17---
18
19---@tag gopher.nvim-gotests-named
20---@text
21--- You can enable named tests in the config if you prefer using named tests.
22--- See |gopher.nvim-config|.
23
24local c = require "gopher.config"
25local ts_utils = require "gopher._utils.ts"
26local r = require "gopher._utils.runner"
27local u = require "gopher._utils"
28local log = require "gopher._utils.log"
29local gotests = {}
30
31---@param args table
32---@private
33local function add_test(args)
34 if c.gotests.named then
35 table.insert(args, "-named")
36 end
37
38 if c.gotests.template_dir then
39 table.insert(args, "-template_dir")
40 table.insert(args, c.gotests.template_dir)
41 end
42
43 if c.gotests.template ~= "default" then
44 table.insert(args, "-template")
45 table.insert(args, c.gotests.template)
46 end
47
48 table.insert(args, "-w")
49 table.insert(args, vim.fn.expand "%")
50
51 log.debug("generating tests with args: ", args)
52
53 local rs = r.sync { c.commands.gotests, unpack(args) }
54 if rs.code ~= 0 then
55 error("gotests failed: " .. rs.stderr)
56 end
57
58 u.notify "unit test(s) generated"
59end
60
61-- generate unit test for one function
62function gotests.func_test()
63 local bufnr = vim.api.nvim_get_current_buf()
64 local func = ts_utils.get_func_under_cursor(bufnr)
65
66 add_test { "-only", func.name }
67end
68
69-- generate unit tests for all functions in current file
70function gotests.all_tests()
71 add_test { "-all" }
72end
73
74-- generate unit tests for all exported functions
75function gotests.all_exported_tests()
76 add_test { "-exported" }
77end
78
79return gotests