我正在编写一个编译 C 源文件并将输出写入另一个文件的包。我正在为这个包编写测试,我需要创建一个临时目录来写入输出文件。我正在使用TestMain函数来做到这一点。出于某种原因,当我刚刚运行测试时,我总是收到“没有要运行的测试”的警告TestMain。我尝试调试该TestMain函数,我可以看到确实创建了临时目录。当我手动创建testoutput目录时,所有测试都通过了。
我正在从目录加载两个 C 源文件testdata,其中一个是故意错误的。
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输出:
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
运行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.
守着星空守着你
米脂
相关分类