Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to test "main()" routine from "go test"?

Tags:

testing

go

I want to lock the user-facing command line API of my golang program by writing few anti-regression tests that would focus on testing my binary as a whole. What testing "binary as a whole" means is that go-test should:

  1. be able to feed STDIN to my binary
  2. be able to check that my binary produces correct STDOUT
  3. be able to ensure that error cases are handled properly by binary

However, it is not obvious to me what is the best practice to do that in go? If there is a good go test example, could you point me to it?

P.S. in the past I have been using autotools. And I am looking for something similar to AT_CHECK, for example:

AT_CHECK([echo "XXX" | my_binary -e arg1 -f arg2], [1], [],
  [-f and -e can't be used together])
like image 960
john1234 Avatar asked Jul 26 '16 07:07

john1234


People also ask

How do you test a private function in go?

Simply create a package named internal inside you package, move your shared functions into files inside the internal package and expose them as public functions. Then you can create test files for these functions as you would normally, using the internal_test for the package.

Does go test run tests in parallel?

The 'go test' command may run tests for different packages in parallel as well, according to the setting of the -p flag (see 'go help build'). Allow parallel execution of test functions that call t. Parallel . The value of this flag is the maximum number of tests to run simultaneously.

How do I test a specific file in Golang?

Right-click a test file or a directory with test files and select Run | Go test <object_name> (for directories) or Run <object_name> (for files).

How do you test concurrency in go?

If you want to test concurrency you'll need to make a few go routines and have them run, well, concurrently. You might try taking the locking out and intentionally get it to crash or misbehave by concurrently modifying things and then add the locking in to ensure it solves it.


2 Answers

Just make your main() single line:

import "myapp"

func main() {
    myapp.Start()
}

And test myapp package properly.

EDIT: For example, popular etcd conf server uses this technique: https://github.com/coreos/etcd/blob/master/main.go

like image 143
Sławosz Avatar answered Oct 06 '22 21:10

Sławosz


I think you're trying too hard: I just tried the following

func TestMainProgram(t *testing.T) {
    os.Args = []string{"sherlock",
        "--debug", 
        "--add", "zero",
        "--ruleset", "../scripts/ceph-log-filters/ceph.rules",
        "../scripts/ceph-log-filters/ceph.log"}
    main()
}

and it worked fine. I can make a normal tabular test or a goConvey BDD from it pretty easily...

like image 23
davecb Avatar answered Oct 06 '22 23:10

davecb