diff --git a/README.md b/README.md index 41aab48..09e5707 100644 --- a/README.md +++ b/README.md @@ -14,7 +14,7 @@ Neovim (from v0.5) embeds a built-in Language Server Protocol (LSP) client. And - Auto format with `:GoFormat` (via `goimports`, `gofmt`, `gofumpt` and `lsp`) when saving. - Run linters with `:GoLint` (via `revive`) automatically. -- Quickly test with `:GoTest`, `:GoTestFunc`, `:GoTestFile` and `:GoTestAll`. Generate test with `:GoAddTest`. +- Quickly test with `:GoTest`, `:GoTestFunc`, `:GoTestName`, `:GoTestFile` and `:GoTestAll`. Generate test with `:GoAddTest`. - Import packages with `:GoGet` and `:GoImport`. - Modify struct tags with `:GoAddTags`, `:GoRemoveTags`, `:GoClearTags`, `:GoAddTagOptions`, `:GoRemoveTagOptions` and `:GoClearTagOptions`. - Generates JSON models with `:GoQuickType` (via `quicktype`). diff --git a/after/ftplugin/go.lua b/after/ftplugin/go.lua index b0416ec..b0254a6 100644 --- a/after/ftplugin/go.lua +++ b/after/ftplugin/go.lua @@ -63,6 +63,13 @@ vim.api.nvim_create_user_command( nargs = 0, } ) +vim.api.nvim_create_user_command( + 'GoTestName', + 'lua require("go.test").test_name()', + { + nargs = 0, + } +) vim.api.nvim_create_user_command( 'GoTestFile', 'lua require("go.test").test_file()', diff --git a/lua/go/test.lua b/lua/go/test.lua index 1d45229..81ea8e2 100644 --- a/lua/go/test.lua +++ b/lua/go/test.lua @@ -173,6 +173,61 @@ function M.test_func(opt) do_test(prefix, build_args(cmd)) end +local function replace_spaces_with_underscore(str) + return str:gsub('%s', '_') +end + +local function process_line_test_name() + local line = vim.api.nvim_get_current_line() + local start_idx, end_idx = string.find(line, '%b""') + + if start_idx and end_idx then + local value_inside_parentheses = line:sub(start_idx + 1, end_idx - 1) + return replace_spaces_with_underscore(value_inside_parentheses) + end +end + +function M.test_name(opt) + if not util.binary_exists('go') then + return + end + + local prefix = 'GoTestName' + local func_name = '' + -- this is not available now actually + if opt and opt.func then + func_name = opt.func + else + local line = vim.fn.search([[func \(Test\|Example\)]], 'bcnW') + if line == 0 then + output.show_error( + prefix, + string.format('Test func not found: %s', func_name) + ) + return + end + local cur_line = vim.fn.getline(line) + func_name = split_file_name(cur_line) + end + if not valid_func_name(func_name) then + output.show_error( + 'GoTestFunc', + string.format('Invalid test func: %s', func_name) + ) + return + end + + local name_test = process_line_test_name() + + local cmd = { + 'go', + 'test', + '-run', + vim.fn.shellescape(string.format('^%s/%s$', func_name, name_test)), + } + do_test(prefix, build_args(cmd)) +end + function M.test_file() if not util.binary_exists('go') then return