Debugging a specific golang unit test with VSCode - go

I am trying to debug one specific unit test in VSCode with breakpoints.
On the command line, this works perfectly to execute:
go test -v ./cmd/bacalhau -run TestCommands
However, when I select the below to run, I get the following:
{
"name": "Debug Specific Test",
"type": "go",
"request": "launch",
"mode": "debug",
"program": "${workspaceFolder}/cmd/bacalhau/devstack_test.go",
"args": [
"-test.run",
"TestCommands"
],
"env": {
"LOG_LEVEL": "debug"
},
"showLog": true
}
Output:
Starting: /home/user/go/bin/dlv dap --check-go-version=false --log=true --log-output=debugger --listen=127.0.0.1:43095 --log-dest=3 from /home/user/code/bacalhau
DAP server listening at: 127.0.0.1:43095
2022-03-12T19:31:11Z info layer=debugger launching process with args: [/home/user/code/bacalhau/__debug_bin -test.run TestCommands]
2022-03-12T19:31:11Z error layer=debugger can't find build-id note on binary
Type 'dlv help' for list of commands.
2022-03-12T19:31:12Z debug layer=debugger continuing
19h31m12.78 DEBUG runtime/proc.go:6498 Log level from LOG_LEVEL_ENV_VAR: debug
Zap log level: debug
19h31m12.82 DEBUG bacalhau/main.go:12 Top of execution - 2022-03-12 19:31:12.824219499 +0000 UTC
Error: unknown command "TestCommands" for "bacalhau"
Run 'bacalhau --help' for usage.
unknown command "TestCommands" for "bacalhau"
Process 3552701 has exited with status 1
Detaching
2022-03-12T19:31:12Z debug layer=debugger detaching
dlv dap (3552580) exited with code: 0
I have also tried setting "program": "${workspaceFolder}/cmd/bacalhau/devstack_test.go", which results in
Starting: /home/user/go/bin/dlv dap --check-go-version=false --log=true --log-output=debugger --listen=127.0.0.1:33479 --log-dest=3 from /home/user/code/bacalhau/cmd/bacalhau
DAP server listening at: 127.0.0.1:33479
Build Error: go build -o /home/user/code/bacalhau/cmd/bacalhau/__debug_bin -gcflags all=-N -l ./devstack_test.go
no packages to build (exit status 1)`
I have looked at the following resources:
Debugging Go tests in Visual Studio Code
https://github.com/golang/vscode-go/blob/master/docs/debugging.md
#1 in the above list looks almost perfect, but I could not get it to work (I don't want to debug ${file} I want the same unit test to run no matter what file I have open).
How do I set this up correctly?

Modify the "mode" property in your launch.json:
"mode": "test", // This should be "auto" or "test"
"program": "${workspaceFolder}/cmd/bacalhau/devstack_test.go",
"args": [],
Or, if you only want to execute the test automatically, you can config it as a task, it's simpler:
{
"version": "2.0.0",
"tasks": [
{
"label": "tmp test",
"type": "shell",
"command": "go test -v ./cmd/bacalhau -run TestCommands",
"problemMatcher": [
"$go"
]
}
]
}

I also wanted to run just some specific tests, and I got it working for me by setting the argument "-test.run=<regexp>", so you could try:
{
"name": "Debug Specific Test",
"type": "go",
"request": "launch",
"mode": "debug",
"program": "${workspaceFolder}/cmd/bacalhau/devstack_test.go",
"args": [
"-test.run=TestCommands"
],
"env": {
"LOG_LEVEL": "debug"
},
"showLog": true
}

Related

Can't debug Golang with breakpoints in VSCode

I debug Golang application with breakpoints in VS Code.
Debugger complains that can't find file, which exists.
Does anyone of you know how to enable breakpoints for Go application in VS Code?
Debugger logs:
Debuggee is not running. Setting breakpoints without halting.
All cleared
Creating on: /home/gbajson/Sync/clickr/clickr-node-api/clickr-node-api.go:63
Creating on: /home/gbajson/Sync/clickr/clickr-node-api/clickr-node-api.go:84
All cleared
All set:[]
SetBreakPointsResponse
2021-10-21T12:52:17+02:00 debug layer=rpc <- RPCServer.CreateBreakpoint(rpc2.CreateBreakpointIn{"Breakpoint":{"id":0,"name":"","addr":0,"addrs":null,"file":"/home/gbajson/Sync/clickr/clickr-node-api/clickr-node-api.go","line":63,"Cond":"","HitCond":"","continue":false,"traceReturn":false,"goroutine":false,"stacktrace":0,"LoadArgs":{"FollowPointers":true,"MaxVariableRecurse":1,"MaxStringLen":64,"MaxArrayValues":64,"MaxStructFields":-1},"LoadLocals":{"FollowPointers":true,"MaxVariableRecurse":1,"MaxStringLen":64,"MaxArrayValues":64,"MaxStructFields":-1},"WatchExpr":"","WatchType":0,"hitCount":null,"totalHitCount":0,"disabled":false}})
2021-10-21T12:52:17+02:00 debug layer=rpc -> *rpc2.CreateBreakpointOut{"Breakpoint":{"id":0,"name":"","addr":0,"addrs":null,"file":"","line":0,"Cond":"","HitCond":"","continue":false,"traceReturn":false,"goroutine":false,"stacktrace":0,"LoadArgs":null,"LoadLocals":null,"WatchExpr":"","WatchType":0,"hitCount":null,"totalHitCount":0,"disabled":false}} error: "could not find file /home/gbajson/Sync/clickr/clickr-node-api/clickr-node-api.go"
2021-10-21T12:52:17+02:00 debug layer=rpc <- RPCServer.CreateBreakpoint(rpc2.CreateBreakpointIn{"Breakpoint":{"id":0,"name":"","addr":0,"addrs":null,"file":"/home/gbajson/Sync/clickr/clickr-node-api/clickr-node-api.go","line":84,"Cond":"","HitCond":"","continue":false,"traceReturn":false,"goroutine":false,"stacktrace":0,"LoadArgs":{"FollowPointers":true,"MaxVariableRecurse":1,"MaxStringLen":64,"MaxArrayValues":64,"MaxStructFields":-1},"LoadLocals":{"FollowPointers":true,"MaxVariableRecurse":1,"MaxStringLen":64,"MaxArrayValues":64,"MaxStructFields":-1},"WatchExpr":"","WatchType":0,"hitCount":null,"totalHitCount":0,"disabled":false}})
2021-10-21T12:52:17+02:00 debug layer=rpc -> *rpc2.CreateBreakpointOut{"Breakpoint":{"id":0,"name":"","addr":0,"addrs":null,"file":"","line":0,"Cond":"","HitCond":"","continue":false,"traceReturn":false,"goroutine":false,"stacktrace":0,"LoadArgs":null,"LoadLocals":null,"WatchExpr":"","WatchType":0,"hitCount":null,"totalHitCount":0,"disabled":false}} error: "could not find file /home/gbajson/Sync/clickr/clickr-node-api/clickr-node-api.go"
2
Error on CreateBreakpoint: could not find file /home/gbajson/Sync/clickr/clickr-node-api/clickr-node-api.go
File exists:
gbajson#misio:~$ ls -l /home/gbajson/Sync/clickr/clickr-node-api/clickr-node-api.go
-rw-r--r-- 1 gbajson gbajson 2961 Oct 21 12:22 /home/gbajson/Sync/clickr/clickr-node-api/clickr-node-api.go
I already checked that it's not a problem with file permissions.
I also followed up the procedure for the lagacy version of dlv:
https://github.com/golang/vscode-go/blob/master/docs/debugging-legacy.md#selecting-legacy-debug-adapter
Debugger configuration
workspace.code-workspace
"launch": {
"version": "0.2.0",
"configurations": [
{
"name": "Debug Go",
"type": "go",
"request": "launch",
"mode": "auto",
"program": "${fileDirname}",
"debugAdapter": "legacy",
"env": {},
"args": [],
"showLog": true,
"logOutput": "rpc",
"trace": "log"
},
settings.json
{
"go.delveConfig": {
"debugAdapter": "legacy",
},
I found the problem. VS Code doesn't handle symbolic links well.
When I set up a project in VS Code in real path debugger started to work properly.
gbajson#misio:~$ realpath /home/gbajson/Sync/clickr/clickr-node-api/clickr-node-api.go
/storage/amoje/Sync/clickr/clickr-node-api/clickr-node-api.go
This problem is also described in: https://github.com/golang/vscode-go/issues/1677
Wanted to share my solution here.
After reading a few github issues vs-code-go, seems like the issue was a result of remotePath or substitutePath. After a few attempts, setting remotePath to "" finally did the trick.
"version": "0.2.0",
"configurations": [
{
"name": "Connect to server",
"type": "go",
"request": "attach",
"mode": "remote",
"remotePath": "",
"port": 40000,
"host": "<host>",
}
]
}
This is a follow-on from the answer by gbajson.
Symbolic links were the problem for me. Using this configuration in launch.json resolved the issue, while allowing me to keep my symlinks:
{
"version": "0.2.0",
"configurations": [
{
"name": "Launch",
"type": "go",
"request": "launch",
"mode": "auto",
"program": "${workspaceFolder}/cmd/server/main.go",
"envFile": "${workspaceFolder}/.env",
"substitutePath": [
{
"from": "/home/me/go-workspaces",
"to": "/data/projects/workspaces"
}
]
}
]
}
Specifically, it is the "substitutePath" part.
My workspace directory was actually symlinked from "/home/me/go-workspaces" to the real directory "/data/projects/workspaces".
See: https://github.com/golang/vscode-go/blob/master/docs/debugging.md#debugging-symlink-directories
You can use "sudo ps aux | fgrep {your process name}" to check your process.If it start more than 1 process, maybe you should change your process start mode without daemon process.

How do I debug rebar3 erlang in vscode with the erlang plugin?

I am using the Erlang language plugin for vscode. I created a new rebar3 app and created a simple app that doesnt use a supervisor:
-module(test_app_app).
-behaviour(application).
-export([start/2, stop/1]).
start(_StartType, _StartArgs) ->
load_file("input.txt").
stop(_State) ->
ok.
load_file(Filename) ->
case file:read_file(Filename) of
{ok, Bin} ->
Bin;
{error, Reason} ->
erlang:error(Reason)
end.
I have configured a launch.json file like so:
{
"version": "0.2.0",
"configurations": [
{
"name": "Launch erlang",
"type": "erlang",
"request": "launch",
"cwd": "${workspaceRoot}",
"arguments": "-s test_app_app start",
"preLaunchTask": "rebar3 compile"
}
]
}
and a tasks.json for the compile:
{
"version": "2.0.0",
"tasks": [
{
"label": "rebar3 compile",
"type": "shell",
"command": "rebar3 compile",
"group": {
"kind": "build",
"isDefault": true
},
"problemMatcher": "$erlang"
}
]
}
When I hit F5 I get the following output:
compiling erlang bridge to '/home/peter/.vscode/extensions/pgourlain.erlang-0.8.1/_build/default/lib/ebin'
Compiling arguments file "/tmp/bp_1454870.erl"
Compile result: sucess
Module bp_1454870 loaded
{"init terminating in do_boot",{undef,[{t
est_app_app,start,[],[]},{init,start_em,1,[]},{init,do_boot,3,[]}]}}
init terminating in do_boot ({undef,[{test_app_app,start,[],[]},{init,start_em,1,[]},{init,do_boot,3,[]}]})
Crash dump is being written to: erl_crash.dump...
done
erl exit code:1
erl exit with code 1
Does anyone have a clue as to why this isnt working for me?
The problem is in your launch.json. You try to run a function start/0 from module test_app_app and such function does not exist.
Try to use
"arguments": "-eval \"application:start(test_app)\""

Using vscode debug console with rust

I'm a little uncertain who's console I'm using. But let's say I have following debug configuration:
{
"version": "0.2.0",
"inputs": [
...
],
"configurations": [
{
"type": "lldb",
"request": "attach",
"name": "Attach to...",
"program": "${workspaceFolder}/src/lib/${input:pickPackage}/target/debug/${input:pickPackage}"
}
]
}
my program is running in macos terminal with cargo run -p ...
vscode's debugger provides me with debug console to lldb
say, I'm in a breakpoint and want to try things out...
I so far tried rust
script println!("{:?}", &t[op_end_index..])
File "<input>", line 1
println!("{:?}", &t[op_end_index..])
^
SyntaxError: invalid syntax
script &t[op_end_index..]
File "<input>", line 1
&t[op_end_index..]
^
SyntaxError: invalid syntax
script fn main () {println!("{:?}", &t[op_end_index..])}
File "<input>", line 1
fn main () {println!("{:?}", &t[op_end_index..])}
^
SyntaxError: invalid syntax
What I found in the lldb dos
script print "Here is some text"
File "<input>", line 1
print "Here is some text"
^
SyntaxError: Missing parentheses in call to 'print'. Did you mean print("Here is some text")?
and finally what it suggest from the error:
script print ("Here is some text")
Here is some text
Hello word is nice but how do I get to my actual scope?
Am I supposed to use lldb's script command for that?
What's my syntax there?
Update
#ForceBru thanks for the hint about python.
What I'm interacting with is vscode-lldb debugger api
It seems I should be able to do something like script debugger.evaluate("/se t[0]") after adding "sourceLanguages": ["rust"] from https://github.com/vadimcn/vscode-lldb/blob/v1.6.0/MANUAL.md#rust-language-support to my configuration
but no luck
script debugger.evaluate("/se t[0]")
Traceback (most recent call last):
File "<input>", line 1, in <module>
File "/Users/anvlkv/.vscode/extensions/vadimcn.vscode-lldb-1.6.0/adapter/debugger.py", line 8, in evaluate
value = codelldb.evaluate_in_context(expr, True, exec_context)
File "/Users/anvlkv/.vscode/extensions/vadimcn.vscode-lldb-1.6.0/adapter/codelldb.py", line 276, in evaluate_in_context
return eval(code, eval_globals, eval_locals)
File "<string>", line 1
/se t[0]
^
SyntaxError: invalid syntax
I'm still in python
script debugger.evaluate("locals().keys()")
dict_keys([])
As someone commented, it looks like your configuration is not correct and it is trying to debug your source code as Python. The easiest way to get the right configuration is to use the provided templates. In your case, you can probably skip to the end of this answer and use one of the "attach" profiles, but the rest might be useful to someone else.
In the debug panel, there is a dropdown:
If you choose "Add Configuration...", you'll get a choice of templates to add:
Choosing "LLDB: Debug Cargo Output" will add this to your launch.json file:
{
"type": "lldb",
"request": "launch",
"name": "Cargo launch",
"cargo": {
"args": [
"build",
"--lib"
]
},
"program": "${cargo:program}",
"args": []
},
If your crate is a binary, you'll want to change that --lib to --bin and specify which binary to run:
{
"type": "lldb",
"request": "launch",
"name": "Cargo launch",
"cargo": {
"args": [
"build",
"--bin=foo"
]
},
"program": "${cargo:program}",
"args": []
},
For tests, you can choose "LLDB: Debug Cargo Tests". It will generate something like this:
{
"type": "lldb",
"request": "launch",
"name": "Cargo test",
"cargo": {
"args": [
"test",
"--no-run",
"--lib"
]
},
"program": "${cargo:program}",
"args": []
},
You probably want to delete the --lib argument so that it will run all of the tests in your project. You can filter it to just debug the tests that you are interested in by adding that as a trailing argument. e.g. to only run tests whose names contain "foo":
{
"type": "lldb",
"request": "launch",
"name": "Cargo test",
"cargo": {
"args": [
"test",
"--no-run",
"--lib"
]
},
"program": "${cargo:program}",
"args": ["foo"]
},
To debug a program that is already running, you can use the template "LLDB: Attach by Name", which generates:
{
"type": "lldb",
"request": "attach",
"name": "Attach",
"program": "${workspaceFolder}/foo"
},
or "LLDB: Attach by PID":
{
"type": "lldb",
"request": "attach",
"name": "Attach",
"pid": "${command:pickMyProcess}" // use ${command:pickProcess} to pick other users' processes
},
This will give you a filterable list of processes that are running, so you can pick the one you want to debug.
For these last two configurations, you may run into permissions issues (on Linux at least, but probably Mac too). You can address that by running the executables as a different user or by elevating the permissions of VS Code (e.g. by starting it with sudo).

How to add user input while debugging C++ on vscode on macOS

How does one add user input when debugging on VScode?
I have tried the following
Edited my launch.json to set externalConsole : true
Tried giving input as a command line argument as mentioned here
Irrespective of following step by step the above methods, something was off.
I kept getting a window where I couldn't do anything. The step up / down / in buttons went inactive.
Here in my launch.json file
{
// Use IntelliSense to learn about possible attributes.
// Hover to view descriptions of existing attributes.
// For more information, visit: https://go.microsoft.com/fwlink/?linkid=830387
"version": "0.2.0",
"configurations": [
{
"name": "g++-10 - Build and debug active file",
"type": "cppdbg",
"request": "launch",
"program": "${fileDirname}/${fileBasenameNoExtension}",
"args": [],
"stopAtEntry": false,
"cwd": "${workspaceFolder}",
"environment": [],
"externalConsole": true,
"MIMode": "lldb",
"preLaunchTask": "C/C++: g++-10 build active file"
}
]
}
and here is my tasks.json file
{
"tasks": [
{
"type": "shell",
"label": "C/C++: g++-10 build active file",
"command": "g++",
"args": [
"-g",
"${file}",
"-std=c++17",
],
"options": {
"cwd": "${workspaceFolder}"
},
"problemMatcher": [
"$gcc"
],
"group": {
"kind": "build",
"isDefault": true
}
}
],
"version": "2.0.0"
}
System details
Version: 1.48.1
Commit: 3dd905126b34dcd4de81fa624eb3a8cbe7485f13
Date: 2020-08-19T17:09:41.484Z
Electron: 7.3.2
Chrome: 78.0.3904.130
Node.js: 12.8.1
V8: 7.8.279.23-electron.0
OS: Darwin x64 20.0.0
The resolve is given in a gist here
The issue is when VSCode launches the debug adapter, then the debug adapter launches lldb-mi, then lldb-mi launches Terminal. There is a prompt that should appear, but somehow the DebugAdapter is not forwarding this permissions request.
The work around is to have VS Code launch the terminal once. You can do this by adding and running this tasks in your tasks.json:
{
"label": "Open Terminal",
"type": "shell",
"command": "osascript -e 'tell application \"Terminal\"\ndo script \"echo hello\"\nend tell'",
"problemMatcher": []
}
You can run this specific task using Command + Shift + p. Type Tasks and look for Tasks: Run Tasks then select Open Terminal.
I have written a small blog post about the same, detailing each and every step with images which can be found here.

Is it possible to debug go revel framework from Visual Studio Code?

I'm trying to debug a revel app with visual studio but I can't get it to work.
I've seen this question how to debug revel framework(golang) application in visual studio code(vscode) but no answers yet...
I've tried with this config:
{
"version": "0.2.0",
"configurations": [
{
"name": "Launch",
"type": "go",
"request": "launch",
"mode": "debug",
"remotePath": "",
"port": 2345,
"host": "127.0.0.1",
"program": "~/code/go/bin/revel",
"env": {},
"args": [],
"showLog": true
}
]
}
But I'm getting this error:
Failed to continue: "The program attribute must point to valid directory, .go file or executable."
I think it must be the rebel binary the one to be run here, but I don't know how to pass the app path, should it go in "args"?
Yes it's possible.
Suppose that the GOPATH is C:\Work\golang
Revel project name is myapp, thus the location of the project (workspace) will be C:\Work\golang\src\myapp.
Make some changes to the controllers etc...
Run the application with revel run myapp, then press CTRL+C to exit. This step is necessary to generate corresponding go files. The generated file, i.e. the main package will be available under ${workspaceRoot}/app/tmp/main.go
Configure launch.json as follows:
{
"version": "0.2.0",
"configurations": [
{
"name": "Launch",
"type": "go",
"request": "launch",
"mode": "debug",
"remotePath": "",
"port": 2345,
"host": "127.0.0.1",
"env": {},
"showLog": true,
"program": "${workspaceRoot}/app/tmp/",
"args": ["-importPath", "myapp", "-srcPath", "c:\\work\\golang\\src", "-runMode", "dev"]
}
]
}
The important parts are program and args parameters, while the other parameters are unmodified.
Set breakpoint and start the delve debugger...
EDIT:
Setting args parameter to ["-importPath", "myapp", "-srcPath", "${workspaceRoot}/..", "-runMode", "dev"] also work, and I think this should work in other platforms (Mac, Linux) too.
The error message is related to delve issue. See https://github.com/Microsoft/vscode-go/issues/986

Resources