lundi 21 août 2017

Testing log.Fatalf in go?

I'd like to achieve 100% test coverage in go code. I am not able to cover the following example - can anyone help me with that?

package example

import (
    "io/ioutil"
    "log"
)

func checkIfReadable(filename string) (string, error) {
    _, err := ioutil.ReadFile(filename)
    if err != nil {
        log.Fatalf("Cannot read the file... how to add coverage test for this line ?!?")
    }
    return "", nil
}

func main() {
    checkIfReadable("dummy.txt")
}

Some dumy test for that:

package example

import (
    "fmt"
    "testing"
)

func TestCheckIfReadable(t *testing.T) {
    someResult, err := checkIfReadable("dummy.txt")
    if len(someResult) > 0 {
        fmt.Println("this will not print")
        t.Fail()
    }
    if err != nil {
        fmt.Println("this will not print")
        t.Fail()
    }
}

func TestMain(t *testing.T) {
...
}

The issue is that log.Fatalf calls os.Exit and go engine dies.

  • I could modify the code and replace built-in library with my own - what makes the tests less reliable.
  • I could modify the code and create a proxy and a wrapper and a .... in other words very complex mechanism to change all calls to "log.Fatalf"
  • I could stop using built-in log package... what is equal to asking "how much is go built-in worth?"
  • I could live with not having 100% coverage
  • I could replace "log.Fataf" with something else - but then what is the point for built-in log.Fatalf?
  • I can try to mangle with system memory and depending on my OS replace memory address for the function (...) so do something obscure and dirty
  • Any other ideas?

Aucun commentaire:

Enregistrer un commentaire