shivams
shivams

Reputation: 2717

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 ?

Upvotes: 13

Views: 17864

Answers (4)

salar
salar

Reputation: 1

if you are using linux:

go run `ls PATH_TO_FILES/*.go | grep -v _test.go`

it workes for me.

Upvotes: -1

jeffasante
jeffasante

Reputation: 3279

For BASH

Run go run PATH_TO_FILES/!(*_test).go

NOTE

If you get an event not found error when running this command, you probably need to enable extended globbing in your bash terminal.

Run shopt-s extglob

after you Run go run PATH_TO_FILES/!(*_test).go


For those using ZSH

setopt extendedglob # to get help regarding globbing

next

foo*~*bar* # match everything that starts with foo but doesn't contain bar

So with my case, go run PATH_TO_FILES/*~*_test.go*

Upvotes: 1

jfly
jfly

Reputation: 7990

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.

Upvotes: 15

CrazyCrow
CrazyCrow

Reputation: 4235

You can't name your program files as *_test.go as this is part of integrated Go testing system

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

Just rename package_test.go to packagetest.go

Upvotes: 10

Related Questions