首页 > 解决方案 > 添加测试用例并运行 go test 后导致“没有这样的文件或目录”的原因是什么?

问题描述

问题

在向现有测试文件添加另一个测试功能后,由于添加另一个测试用例后出现go test -v ./...多个构建错误,运行失败。no such file or directory但是,错误消息似乎与更改无关。

添加的测试用例可以在底部的相关代码部分中找到。

错误消息是:

open /tmp/go-build842273301/b118/vet.cfg: no such file or directory
open /tmp/go-build842273301/b155/vet.cfg: no such file or directory
# tornadowarnung.xyz/riotwatch/riot/static
vet: in tornadowarnung.xyz/riotwatch/riot/static, can't import facts for package "encoding/json": open $WORK/b036/vet.out: no such file or directory
# tornadowarnung.xyz/riotwatch/web/server/endpoint/static
vet: open $WORK/b121/vet.cfg: no such file or directory
open /tmp/go-build842273301/b115/vet.cfg: no such file or directory
open /tmp/go-build842273301/b001/vet.cfg: no such file or directory
# tornadowarnung.xyz/riotwatch/web/server
vet: open $WORK/b152/vet.cfg: no such file or directory
# tornadowarnung.xyz/riotwatch/web/server/endpoint/static
vet: open $WORK/b159/vet.cfg: no such file or directory

因此,一些包显示它们的构建失败:

FAIL    tornadowarnung.xyz/riotwatch/riot/static [build failed]
FAIL    tornadowarnung.xyz/riotwatch/web/server [build failed]
FAIL    tornadowarnung.xyz/riotwatch/web/server/endpoint [build failed]
FAIL    tornadowarnung.xyz/riotwatch/web/server/endpoint/static [build failed]

相关代码

func TestLoader_ProfileIcon(t *testing.T) {
    tempDir := os.TempDir()
    l := Loader{
        profileIconPath: tempDir,
    }
    defer os.RemoveAll(tempDir)

    t.Run("returns expected content", func(t *testing.T) {
        want := bytes.NewBufferString("image data")
        fileName := "123456"
        if err := createTestFile(t, tempDir, fileName, want); err != nil {
            t.Fatal(err)
        }

        got, err := l.ProfileIcon(123456)
        if err != nil {
            t.Error(err)
        }

        if !reflect.DeepEqual(got, want) {
            t.Errorf("got %v, want %v", got, want)
        }
    })

    t.Run("does not panic on missing file", func(t *testing.T) {
        res, err := l.ProfileIcon(-1)

        if err == nil {
            t.Errorf("Expected an error but got error %v and result %v", nil, res)
        }
    })
}

func createTestFile(t *testing.T, tempDir string, fileName string, content *bytes.Buffer) error {
    t.Helper()
    f, err := os.Create(path2.Join(tempDir, fmt.Sprintf("%v.png", fileName)))
    if err != nil {
        return err
    }
    _, err = f.Write(content.Bytes())
    if err != nil {
        return err
    }
    return nil
}

重现错误很困难

在我安装了 go 1.15 的 Ubuntu 机器上,只有在我再次克隆存储库或清理测试缓存时才会出现错误。

在本地运行 Gitlab 作业中使用的图像golang:alpine并运行相同的命令时,我无法每次都重现此错误。有时会发生,但大多数时候不会。

我试过的

我尝试在 go 版本 1.13、1.14 和 1.15 之间切换,但每个版本都会产生相同的结果。

切换到任何其他图像golang:latest,如golang:1.14golang:1.13也无济于事。

我已经尝试使用谷歌搜索发生的错误,但我没有找到任何相关的结果或包含我尚未尝试过的任何解决方案。

恢复所述提交将使测试再次通过。我还恢复了提交并慢慢尝试手动再次引入更改。这使得问题再次出现。

标签: go

解决方案


os.TempDir 不会为您创建新的临时目录,它会返回系统的临时目录。通过在其上调用 os.RemoveAll,您将把整个事情吹走,包括构建和测试过程使用的一些暂存文件。


推荐阅读