登录
首页 >  Golang >  Go问答

执行 Go 文件时出错:文件不存在

来源:stackoverflow

时间:2024-03-16 22:24:30 453浏览 收藏

在执行 Go 测试时,指定测试文件可能会导致文件不存在的错误。这是因为 Go 测试框架默认在当前目录下运行所有测试,无需指定测试文件。为了解决此问题,应使用 `go test -run` 命令指定要运行的特定测试,而不是文件。此命令允许指定顶级测试名称或子测试匹配模式,从而更精确地控制要执行的测试。

问题内容

我有来自此 google github 存储库的两个 go 文件:

  1. certificate_tag.go
  2. certificate_tag_test.go

我已经克隆了存储库,因此所有相关文件所在的目录结构完全相同:

现在我一一运行此文件中的以下命令来执行它:

go build -o c:/tmp/certificate_tag common/certificate_tag/certificate_tag.go

这会在 c:/tmp/certificate_tag 处创建一个文件,如下所示:

但是现在当我运行下面的命令时会导致错误:

go test common/certificate_tag/certificate_tag_test.go common/certificate_tag/certificate_tag.go -tag-binary-dir "c:/tmp"

错误文字如下:

$ 去测试 common/certificate_tag/certificate_tag_test.go common/certificate_tag/certificate_tag.go -tag-binary-dir "c:/tmp" --- 失败:testprintappishedtag (0.00s) certificate_tag_test.go:74: 执行“c:\tmp\certificate_tag”时出错:exec:“c:\tmp\certificate_tag”: 文件 不存在;输出: --- 失败:testsetsuperfluouscerttag (0.01s) certificate_tag_test.go:101: 测试输入 testdata\chromesetup.exe,执行“c:\tmp\certificate_tag”时出错:exec: “c:\tmp\certificate_tag”: 文件不存在;输出:失败失败 命令行参数 4.640s 失败

testprintappishedtag 的代码如下:

func testprintappendedtag(t *testing.t) {
    cmd := exec.command(tagbinary, "--dump-appended-tag", sourceexe)
    output, err := cmd.combinedoutput()
    if err != nil {
        t.fatalf("error executing %q: %v; output:\n%s", tagbinary, err, output)
    }

    if out := string(output); !strings.contains(out, existingtagsubstring) {
        t.errorf("output of --dump-appended-tag didn't contain %s, as expected. got:\n%s", existingtagsubstring, out)
    }
}

为什么无法找到上面步骤 1 中在 c:/tmp/certificate_tag 创建的文件,即使它在那里?

更新:根据 volker 和 chen 的建议,现在我正在运行以下命令:

go test -run TestPrintAppendedTag

它给出以下错误:

certificate_tag_test.go:75: 执行“\tmp\certificate_tag”时出错: exec: "\tmp\certificate_tag": 文件不存在;


正确答案


运行go测试时,不需要指定测试的.go文件,只需运行go test -run即可运行当前目录下的所有测试。如果您想要更具体的内容,则需要指定测试名称,而不是文件。

go test              # Run all tests.
go test -run Foo     # Run top-level tests matching "Foo", such as "TestFooBar".
go test -run Foo/A=  # For top-level tests matching "Foo", run subtests matching "A=".
go test -run /A=1    # For all top-level tests, run subtests matching "A=1".

查看 go 博客中的 testing 软件包文档和其他 examples

文中关于的知识介绍,希望对你的学习有所帮助!若是受益匪浅,那就动动鼠标收藏这篇《执行 Go 文件时出错:文件不存在》文章吧,也可关注golang学习网公众号了解相关技术文章。

声明:本文转载于:stackoverflow 如有侵犯,请联系study_golang@163.com删除
相关阅读
更多>
最新阅读
更多>
课程推荐
更多>