Golang: How to do experiments with go tests in VSCode
Why
I love python, to a large extend, is because I could quickly see the results from my operations.
But for golang, it can be a little bit different, each time I write software, I have to compile it before I run it.
It’s not a very good idea to put my experiment code in the main loop (or main function).
How
Then an idea came to my mind.
Do you know tests? It’s used to test whether your function works as you expected.
Why don’t we just use tests as our playground where we do all those crazy experiments?
All we have to do is to use the print function inside of our test code:
# main_test.go # make sure your file ends up with '_test.go', and function starts with 'Test', otherwise, it won't work
package main
import (
"log"
"testing"
)
func TestGetExistsPort(t *testing.T) {
ports := get_exists_port()
log.Println(ports)
if len(ports) == 0 {
t.Fatalf("there should has ports")
}
}
vscode has a very cool feature that allows us to click just one button to launch a test (we use ‘debug test’ here):
one more step later, we will be free to go:
https://github.com/golang/go/issues/24573#issuecomment-453578276
If you want to debug the whole program
// .vscode/launch.json
{
"version": "0.2.0",
"configurations": [
{
"name": "Launch Package",
"type": "go",
"request": "launch",
"mode": "auto",
"program": "main.go"
}
]
}
Then, press F5