dimanche 10 février 2019

TestMain - no tests to run

I am writing a package which compiles a C source file and writes the output to another file. I am writing tests for this package, and I need to create a temporary directory to write the output files. I am using TestMain function to do this. For some reason, I always get the warning "no tests to run" when I just run the TestMain test. I tried to debug the TestMain function and I can see that the temporary directory is indeed created. When I create the testoutput directory manually, all tests pass.

I am loading two C source files from testdata directory, one of which is intentionally wrong.

gcc.go:

package gcc

import (
    "os/exec"
)

func Compile(inPath, outPath string) error {
    cmd := exec.Command("gcc", inPath, "-o", outPath)
    return cmd.Run()
}

gcc_test.go:

package gcc

import (
    "os"
    "path/filepath"
    "testing"
)

func TestOuputFileCreated(t *testing.T) {
    var inFile = filepath.Join("testdata", "correct.c")
    var outFile = filepath.Join("testoutput", "correct_out")

    if err := Compile(inFile, outFile); err != nil {
        t.Errorf("Expected err to be nil, got %s", err.Error())
    }

    if _, err := os.Stat(outFile); os.IsNotExist(err) {
        t.Error("Expected output file to be created")
    }
}

func TestOuputFileNotCreatedForIncorrectSource(t *testing.T) {
    var inFile = filepath.Join("testdata", "wrong.c")
    var outFile = filepath.Join("testoutput", "wrong_out")

    if err := Compile(inFile, outFile); err == nil {
        t.Errorf("Expected err to be nil, got %v", err)
    }

    if _, err := os.Stat(outFile); os.IsExist(err) {
        t.Error("Expected output file to not be created")
    }
}

func TestMain(m *testing.M) {
    os.Mkdir("testoutput", 666)
    code := m.Run()
    os.RemoveAll("testoutput")
    os.Exit(code)
}

go test output:

sriram@sriram-Vostro-15:~/go/src/github.com/sriram-kailasam/relab/pkg/gcc$ go test
--- FAIL: TestOuputFileCreated (0.22s)
        gcc_test.go:14: Expected err to be nil, got exit status 1
FAIL
FAIL    github.com/sriram-kailasam/relab/pkg/gcc        0.257s

Running TestMain:

Running tool: /usr/bin/go test -timeout 30s github.com/sriram-kailasam/relab/pkg/gcc -run ^(TestMain)$

ok      github.com/sriram-kailasam/relab/pkg/gcc    0.001s [no tests to run]
Success: Tests passed.

Aucun commentaire:

Enregistrer un commentaire