Prakash P
Prakash P

Reputation: 4058

Test func can't read environment from launch.json | Golang | VSCode

I want to read os the environment in my Test Func. I have added the variable launch .json. When I run or debug the test, the env values are empty.

Please see the conf file below:

File Name : launch.json

{
    // 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": "Launch Package",
            "type": "go",
            "request": "launch",
            "mode": "debug",
            "program": "${fileDirname}",
            "env": {
                "HI": "Hi from env!"
            },
        }
    ]
}

I tried mode="test", but the same result.

My test file: main_test.go package: main_test

package main_test

import (
    "os"
    "testing"
)

func Test_hi(t *testing.T) {
    hi := os.Getenv("HI")
    _ = hi
    t.Fail()
    t.Log("Hello from test. ", hi)
}

I am running or debugging my test by clicking on the button as seen in the below screenshot: line number 8 (run test | debug test)

main_test.go

run test

debug test

Version: 1.81.0
Commit: 6445d93c81ebe42c4cbd7a60712e0b17d9463e97
Date: 2023-08-02T12:36:11.334Z
Electron: 22.3.18
ElectronBuildId: 22689846
Chromium: 108.0.5359.215
Node.js: 16.17.1
V8: 10.8.168.25-electron.0
OS: Linux x64 5.19.0-50-generic
Delve Debugger
Version: 1.20.2
Build: $Id: e0c278ad8e0126a312b553b8e171e81bcbd37f60

I think this is not a Golang problem but a VSCode conf problem. I must be doing something very silly. Please let me know if you need any more information.

Upvotes: 2

Views: 1014

Answers (1)

Prakash P
Prakash P

Reputation: 4058

I solved this problem by creating the file .vscode/settings.json.

Here is the sample content of the file.

{
    "go.testEnvVars": {
        "HI": "Hello from test env"
    },
    "go.testFlags": ["-v", "-count=1"]
}

Upvotes: 3

Related Questions