0

I searched around and couldn't find a way to test the main function when using kingpin library, and my program is written very similar to below

package main

import (
  "os"
  "strings"
  "gopkg.in/alecthomas/kingpin.v2"
)

var (
  app      = kingpin.New("chat", "A command-line chat application.")
  serverIP = app.Flag("server", "Server address.").Default("127.0.0.1").IP()

  register     = app.Command("register", "Register a new user.")
  registerNick = register.Arg("nick", "Nickname for user.").Required().String()
  registerName = register.Arg("name", "Name of user.").Required().String()
)

func main() {
  switch kingpin.MustParse(app.Parse(os.Args[1:])) {
  // Register user
  case register.FullCommand():
    println(*registerNick)
  }
}
blackmamba24
  • 119
  • 1
  • 1
  • 9
  • If you just want to know how to pass in arguments when testing then see [this answer](https://stackoverflow.com/a/33723649/11810946). Otherwise please provide more information regarding what you are trying to accomplish. – Brits Feb 15 '21 at 03:55
  • Hi @Brits, I guess the purposes are test coverage and integration testing. It would be good to specify some parameters and let it run without failures. – blackmamba24 Feb 15 '21 at 04:18
  • The answer I linked to shows how to pass in parameters as part of a test (that should work whatever library you are using to parse them). The same technique is used in the standard library [flags package](https://golang.org/src/flag/flag_test.go#L324). – Brits Feb 15 '21 at 04:30
  • Yup, I tried this and worked ``` func TestMain(m *testing.M) { os.Args = []string{"blah", "blah2", "blah3"} os.Exit(m.Run()) kingpin.MustParse(app.Parse(os.Args)) } ``` – blackmamba24 Feb 15 '21 at 04:41
  • 1
    Does this answer your question? [How to test the passing of arguments in Golang?](https://stackoverflow.com/questions/33723300/how-to-test-the-passing-of-arguments-in-golang) – Brits Feb 15 '21 at 04:47
  • (flagged as duplicate so this question will be closed off) – Brits Feb 15 '21 at 04:47
  • @Brits, not really. Your reference to the post tells me how to get the command args. But doesn't tell me how to test the main properly. – blackmamba24 Feb 21 '21 at 10:07
  • That really depends upon the specific requirements. A fairly common approach is to split out command line parsing and implementation. Then unit test each piece separately (for example [etcd](https://github.com/etcd-io/etcd/blob/master/server/etcdmain/config_test.go#L30)). – Brits Feb 21 '21 at 20:48
  • Thanks @Brits, feel free to close the thread now. Cheers. – blackmamba24 Feb 21 '21 at 21:58

0 Answers0