How to maintain good Go package coverage while handling obscure bugs?

I am trying to maintain 100% code coverage in some of my Go packages. This is unsafe everywhere, even with some tests that I choose with the -integration build tag -integration build system, but this should be possible for my relatively isolated library packages.

I'm having trouble coating coatings for obscure error paths.

Here is an example of one of my methods, which is part of an integration test where there is a real file system:

 func (idx Index) LoadPost(title string) (*PostSpec, string, error) { postFolder := strings.Replace(strings.ToLower(title), " ", "_", -1) spec, err := idx.getSpec(postFolder) if err != nil { return nil, "", err } f, err := os.Open(path.Join(idx.blogdir, postFolder, "content.html")) if err != nil { return nil, "", err } defer f.Close() b, err := ioutil.ReadAll(f) if err != nil { return nil, "", err } return spec, string(b), nil } 

Here's what it looks like in go tool -cover :

go tool cover html output

Pressing this block is not easy. I can think of no way to do this, except by creating a special test directory where the file that it is trying to open is something other than a regular file. This seems like a lot of complexity.

This is not too much for a deal, but that means I have to remember that 97.3% coverage is the right figure. If I see that this number goes down, does this mean that I have violated my tests and now more open source code has appeared? Or was it just that I was able to improve my package with simplification and deletion, or dead code? This leads to the second assumption.

More importantly for some, in the business context, this is an obstacle to a beautiful toolbar.

+7
go testing
source share
1 answer

io/ioutil/ioutil_test.go checks this error simply by calling the ioutil.ReadFile () function with a nonexistent file.

This does not require any configuration.

 filename := "rumpelstilzchen" contents, err := ReadFile(filename) if err == nil { t.Fatalf("ReadFile %s: error expected, none found", filename) } 
+5
source share

All Articles