Go test and examples

I have a project with the following simplified structure:

chessImager
  ..
  examples (folder)
  tests (folder)
  ...
  chessImager.go
  ...

If I run my go test ./... from the tests folder, all the tests works fine. But if I run go test ./... from the chessImager folder, I get the following error:

# github.com/Hultan/chessImager/examples
examples/medium.go:10:6: main redeclared in this block
	examples/advanced.go:10:6: other declaration of main
examples/other.go:10:6: main redeclared in this block
	examples/advanced.go:10:6: other declaration of main
examples/simple.go:10:6: main redeclared in this block
	examples/advanced.go:10:6: other declaration of main
?   	github.com/Hultan/chessImager	[no test files]
ok  	github.com/Hultan/chessImager/test	1.997s
FAIL

The examples folder does not contain any testable files (*_test.go), so why is it complaining about that folder? Should I instead create sub folders for each example, to avoid problems like this?

My project:

1 Like

This is because all files in the example directory are declared with package main and are in the same package. Go will try to compile them all together, except fails when it hits main for a second time. I recommend making a subdirectory for each example with a main function in the examples directory.

I understand that part, let me clarify my question.

There are no testable files in the example folder (no files that ends with _test), so what I wonder is why it even bothers to try to compile that folder?

I thought that it looked for test files and compiled what it needed for that?

And as I wrote the last sentence I think I realized what the problem is. I have a file called examples_test.go, that tests that the examples work. That test must trigger the compilation of the example folder.

So your suggestion to use sub folders for each example should fix that…Thanx…

Go test also attempts to build all packages, when specified with the wildcard syntax as you did. If you don’t want it to try to build main, then you’ll have to specify the packages one by one.

Go test also attempts to build all packages, when specified with the wildcard syntax as you did. If you don’t want it to try to build main, then you’ll have to specify the packages one by one.

Then that is the explanation for this behavior.

I talked about examples_test.go before, but that test file has its own copies of the example code in the test file, so that should not trigger the building of the examples folder. I didn’t have the code in front of me when I replied the first time.

Thanks for the help…

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.