at backyard

Color my life with the chaos of trouble.

go: cannot run *_test.go filesというエラーについて

Goを触る上での前提知識になるかと思うが、知らないで軽くハマったのでメモ書き。

そもそもGoでは *_test.go というファイル名のファイルはテスト用のファイルとなるため go run では実行できない。

*_test.go のファイルを実行しようとすると( 例えば go run hoge_test.go )、タイトルにも書いたように下記のエラーが出る。

go: cannot run *_test.go files

こちらについては下記のドキュメントに記載がある。

pkg.go.dev

To write a new test suite, create a file whose name ends _test.go that contains the TestXxx functions as described here. Put the file in the same package as the one being tested. The file will be excluded from regular package builds but will be included when the "go test" command is run. For more detail, run "go help test" and "go help testflag".

_test.go で終わる名前のファイルは通常のパッケージビルドからは除外されると書かれているとおり、特別に扱われるようだ。

また、下記のコマンドからも該当しそうな記述を見つけられる。
(そもそも上のドキュメントに go help testgo help testfunc で見てみてと書かれている)

go help test

で表示される下記の部分が参考になる。

'Go test' recompiles each package along with any files with names matching the file pattern "*test.go". These additional files can contain test functions, benchmark functions, fuzz tests and example functions. See 'go help testfunc' for more. Each listed package causes the execution of a separate test binary. Files whose names begin with "" (including "_test.go") or "." are ignored

更に上の説明に従い、下記のコマンドではtestfuncに関する説明文がある。

go help testfunc

※ここには貼らないので、直接打って参照してみてください。

というわけで、たぶんGoやっている人には常識的な話かと思うのだけど、個人的にちょいとハマったメモ書きでした。

余談: go-te

Goで下記のような感じでテストが書けるライブラリを作っていて、たまたまテストで hoge_test.go というファイルを作ったらこれにあたったので、何かなと思い、これを書いたわけです。

   t.Describe("Expect to be sample", func() {
        t.It("Expect b is true", func() {
            b := true
            t.Expect(b).ToBe(true)
        })
    })

ちなみに go-te といいます。
Goは標準でtesting packageがあるので誰得パッケージですが、まあ、自分で使っているので良いのです。

github.com