[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--- If you prefer named tests, you can enable them in |gopher.nvim-config|.
19
20local c = require "gopher.config"
21local ts_utils = require "gopher._utils.ts"
22local r = require "gopher._utils.runner"
23local u = require "gopher._utils"
24local log = require "gopher._utils.log"
25local gotests = {}
26
27---@param args table
28---@dochide
29local function add_test(args)
30 if c.gotests.named then
31 table.insert(args, "-named")
32 end
33
34 if c.gotests.template_dir then
35 table.insert(args, "-template_dir")
36 table.insert(args, c.gotests.template_dir)
37 end
38
39 if c.gotests.template ~= "default" then
40 table.insert(args, "-template")
41 table.insert(args, c.gotests.template)
42 end
43
44 table.insert(args, "-w")
45 table.insert(args, vim.fn.expand "%")
46
47 log.debug("generating tests with args: ", args)
48
49 local rs = r.sync { c.commands.gotests, unpack(args) }
50 if rs.code ~= 0 then
51 error("gotests failed: " .. rs.stderr)
52 end
53
54 u.notify "unit test(s) generated"
55end
56
57-- generate unit test for one function
58function gotests.func_test()
59 local bufnr = vim.api.nvim_get_current_buf()
60 local func = ts_utils.get_func_under_cursor(bufnr)
61
62 add_test { "-only", func.name }
63end
64
65-- generate unit tests for all functions in current file
66function gotests.all_tests()
67 add_test { "-all" }
68end
69
70-- generate unit tests for all exported functions
71function gotests.all_exported_tests()
72 add_test { "-exported" }
73end
74
75return gotests