Package name missmatch

Issue

I am working on a project where I have created the attached structure.

under tests->gchat_test I have two files init.go and gchat_test.go

//init.go
package gchat_test

//initiation code

//gchat_test.go
package gchat_test

//testing code

for these files I am having the following error in VSCode

found packages gchat (gchat_test.go) and gchat_test (init.go) in /home/<<>>/errornotifier/tests/gchat_test

I tried from console as well just to make sure that this is not a VSCode issue

~/Loans/errornotifier/tests/gchat (feture/initial)$ go test
found packages gchat (gchat_test.go) and gchat_test (init.go) in /home/<<>>/errornotifier/tests/gchat_test

I have a similar structure for another set of tests and I didnt experience this error

under tests->kafka_test I have two files init.go and kafka_test.go

//init.go
package kafka_test

//initiation code

//kafka_test.go
package kafka_test

//testing code

As a quick fix I moved the initiation from tests->gchat_test->init.go to tests->gchat_test->gchat_test.go and remove init.go then it works.

I want to understand why this error is thrown, even though I have the same package name for these files and how to fix it

enter image description here

Solution

Files that don’t have a _test.go suffix will form the source files of the package. Files that have a _test.go suffix are excluded by go build. Test files declaring a package with _test suffix form a different package.

So basically you have a normal package gchat_test defined by the non-test file init.go, and you have a test package gchat_test defined by the test files gchat_test.go. Whether this will work depends on the Go tool implementation.

All in all, package names having _test should not be used in non-test packages. init.go is a non-test file, it should not declare a test package.

Compile packages and dependencies:

When compiling packages, build ignores files that end in ‘_test.go’.


Test packages:

‘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.

Test files that declare a package with the suffix "_test" will be compiled as a separate package, and then linked and run with the main test binary.

Answered By – icza

Answer Checked By – Jay B. (GoLangFix Admin)

Leave a Reply

Your email address will not be published.