How to check passing arguments in Golang?

package main

import (
    "flag"
    "fmt"
)

func main() {
    passArguments()
}

func passArguments() string {
    username := flag.String("user", "root", "Username for this server")
    flag.Parse()
    fmt.Printf("Your username is %q.", *username)

    usernameToString := *username
    return usernameToString
}

Passing an argument to compiled code:

./args -user=bla

leads to:

Your username is "bla"

The name of the user that was transferred is displayed.


The goal: to prevent code from being collected and run each time, in order to test the code, the goal is to write a test capable of checking for passing arguments.


Attempt

Perform the following test:

package main

import (
    "os"
    "testing"
)

func TestArgs(t *testing.T) {
    expected := "bla"
    os.Args = []string{"-user=bla"}

    actual := passArguments()

    if actual != expected {
        t.Errorf("Test failed, expected: '%s', got:  '%s'", expected, actual)
    }
}

leads to:

Your username is "root".Your username is "root".--- FAIL: TestArgs (0.00s)
    args_test.go:15: Test failed, expected: 'bla', got:  'root'
FAIL
coverage: 87.5% of statements
FAIL    tool    0.008s

Problem

It seems that os.Args = []string{"-user=blait cannot pass this argument to the function, because the result rootinsteadbla

+4
source share
1 answer

os.Args - ( ), os.Args = []string{"cmd", "-user=bla"} . test , - .

, os.Args " ", . :

oldArgs := os.Args
defer func() { os.Args = oldArgs }()

, , , , go test.

+7

Source: https://habr.com/ru/post/1615980/


All Articles