Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

go not running program with name package_test.go

I have following code under package pack1. Name of file is pack1.go

package pack1

var Pack1Int int = 42
var pack1Float = 3.14

func ReturnStr() string {
    return "Hello world!"
}

And following code in main program. Name of file is package_test.go

package main

import (
    "fmt"
    "./pack1"
)

func main() {
    var test1 string
    test1 = pack1.ReturnStr()
    fmt.Printf("Return string from pack1 : %s\n", test1)
    fmt.Printf("Integer from pack1 : %d\n", pack1.Pack1Int)
}

When I try to run it with command go run package_test.go I get following error:

go run: cannot run *_test.go files (package_test.go)

But if I rename file to abc.go then I am getting proper output i.e.

Return string from pack1 : Hello world!
Integer from pack1 : 42

I am curious about what is wrong with using package_test.go as file name. For code with only main package this name is working fine.

Is this a bug in Go or I am doing something wrong ?

like image 954
shivams Avatar asked Jan 30 '16 07:01

shivams


People also ask

How do I run a test file in go?

At the command line in the greetings directory, run the go test command to execute the test. The go test command executes test functions (whose names begin with Test ) in test files (whose names end with _test.go). You can add the -v flag to get verbose output that lists all of the tests and their results.

Should go tests be in the same package?

By convention, Go testing files are always located in the same folder, or package, where the code they are testing resides. These files are not built by the compiler when you run the go build command, so you needn't worry about them ending up in deployments.

Does go test run go build?

It will have two functions: a constructor NewPerson and a function older , which will take a *Person and return if one *Person is more senior than another *Person . This way, the go test locates the package, builds it, and runs its tests.


1 Answers

Not a bug, it's designed so. go run detects the _test files and consider them as test files for a package, test files will be compiled as a separate package, and then linked and run with the main test binary.
It's recommended to put your package file to GOPATH/src/PACK_NAME/, then run your *_test.go with go test.

like image 117
jfly Avatar answered Nov 12 '22 04:11

jfly