How to pass arguments such as username and password in a test

Issue

I use below code to initialize connection to avi controller,

func TestAvi(t *testing.T) {
    aviClient, err := clients.NewAviClient("<CONTROLLERNAME>", "<USERID>",
        session.SetPassword("<PASSWORD"),
        session.SetTenant("<TENANT>"),
        session.SetInsecure)
    if err != nil {
        t.Error(err)
    }

And then I run go test command to run the code.
I would like to externalize CONTROLLERNAME, USERID, PASSWORD and TENANT. So that I can pass those as arguments to go test command.

Any assistance please?

Solution

I don’t recommend passing those via CLI args, they are often logged.

A simple and most widely used solution is to pass such information via environment variables, which you can read using the os.Getenv() function.

How you set the environment variables is entirely up to you and may vary from system to system.

For example:

func TestAvi(t *testing.T) {
    controller := os.Getenv("AVI_CONTROLLERNAME")
    password := os.Getenv("AVI_PASSWORD")
    tenant := os.Getenv("AVI_TENANT")
    userID := os.Getenv("AVI_USERID")
    
    aviClient, err := clients.NewAviClient(controller, userID,
        session.SetPassword(password),
        session.SetTenant(tenant),
        session.SetInsecure)

    // ...
}

Answered By – icza

Answer Checked By – Gilberto Lyons (GoLangFix Admin)

Leave a Reply

Your email address will not be published.