How to create unit test coverage when using subprocess testing in golang?

I have unit tests for most of our code. But I can't figure out how to create unit tests for specific code in main () in the main package.

The main function is pretty simple. This is basically a block of choice. It reads the flags, then either calls another function / does something, or simply prints help on the screen. However, if the command line options are not set correctly, it will exit with various error codes. Therefore, the need for testing the subprocess.

I tried the subprocess testing method, but modified the code to include a flag for coverage:

cmd := exec.Command(os.Args[0], "-test.run=TestMain -test.coverprofile=/vagrant/ucover/coverage2.out") 

Here is the source code: https://talks.golang.org/2014/testing.slide#23 Explanation of the above slide: http://youtu.be/ndmB0bj7eyw?t=47m16s

But he does not create a cover profile. I could not understand why not. It generates a cover profile for basic process execution tests, but any code executed in a subprocess is, of course, not marked as executed.

I try to cover the code as much as possible. I'm not sure if I missed something, or if there is an easier way to do this. Or if it is simply not possible.

Any help is appreciated.

thanks

Amer

+2
source share
2 answers

I would define the logic to be tested from main() :

 func main() { start(os.Args) } func start(args []string) { // old main() logic } 

This way you can execute unit-test start() without the os.Args mutation.

+3
source

I went with another approach that did not include main () refactoring: see this commit :

I use a global (unfulfilled) variable:

 var args []string 

And then in main() , I use os.Args if private var args not set:

 a := os.Args[1:] if args != nil { a = args } flag.CommandLine.Parse(a) 

In my test, I can set the necessary parameters:

 args = []string{"-v", "-audit", "_tests/p1/conf/gitolite.conf"} main() 

And I still get 100% code coverage, even above main() .

+4
source

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


All Articles