On Sun, Apr 25, 2021 at 7:10 AM Shivendra Singh
<shivendra.singh3...@gmail.com> wrote:
>
> Yes @Jan Mercl  absolutely correct!!
>
> Able to figure out a solution.
> Basically the go mod i am using as part of the code is doing something like 
> this :
> func init() {
> //reads vars
> flag.Parse()
> }
>
> The problem arises when doing flag.Parse() as part of the init.
> https://github.com/golang/go/issues/31859#issuecomment-489889428 gives very 
> valuable insights to the issue.
>
> High Level Problems that may occur :
> 1. if i am reading any command line args anywhere else it will fail, since in 
> this code flag.Parse() is happening during init()
> 2. The code snippet :
> var _ = func() bool {
> testing.Init()
> return true
> }()
> This somewhat of a hack to explicitly invoke init() method and only helps in 
> a very few cases.
>
> As a solution, i went ahead to remove the flag.Parse() from init() because it 
> is really wrong and rather call it from my main().
> Just doing this change unblocked me for testing as now from test method i can 
> easily invoke a setup call to do flag.Parse() as Jan Mercl pointed out.

I would also recommend that you create a new FlagSet object
(https://golang.org/pkg/flag/#NewFlagSet) and use that to write more
testable applications. So, for example:

func setupFlagsAndParse(args []string) {
        fs := flag.NewFlagSet(..)
        # setup the flag and options as usual
        fs.Parse(args)
       ...
}

Then, you call this function from main() as
setupFlagsAndParse(os.Args[1:]) or your tests with any slice of
strings that you may want to test.

-- 
You received this message because you are subscribed to the Google Groups 
"golang-nuts" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to golang-nuts+unsubscr...@googlegroups.com.
To view this discussion on the web visit 
https://groups.google.com/d/msgid/golang-nuts/CANODV3m9tth_4OA3yDdg2JX6guVe8aj7EbCygwMBYcShUZGnhg%40mail.gmail.com.

Reply via email to