英文:
Go module package not found when executing the tests
问题
我知道我对Go如何寻找包的基本理解还不够,但让我强调一下我的想法,如果需要的话-你可以给我点踩。
这是我的Go模块结构:
├── go.mod
├── gopher.json
├── main.go
├── story.go
├── template.html
└── tests
├── cyow_test.go
└── gopher.json
没有太复杂的地方,专门有一个/tests目录用于放置测试。
这是我的cyow_test.go文件:
import (
"io/ioutil"
"story"
"testing"
)
func TestUnmarshallOverStoryStruct(t *testing.T) {
t.Parallel()
content, fileError := ioutil.ReadFile("gopher.json")
if fileError != nil {
t.Error("找不到章节文件。")
}
story := story.Story{}
fmt.Println("故事已初始化")
err := json.Unmarshal([]byte(content), &story)
fmt.PRintln("执行了Json解组语句。")
if err != nil {
panic(err)
}
}
你可以忽略这个函数,它主要是为了学习目的。重要的部分是,我依赖一个名为story的包,它已经被声明为模块的一部分。
当我进入/tests目录并运行'go test'时,我收到以下错误:
cyow_test.go:5:2: package story is not in GOROOT (/usr/local/go/src/story)
我在模块根目录下运行了'go mod tidy',我的简单问题是:
- 为什么Go默认情况下找不到这个包?它是模块的一部分,所以它应该是本地的-这是我的假设。
- 这是否意味着引用包的唯一方式(即使在你的模块内部)是通过远程仓库URL引用它们,比如github.com...或者最终只是将包复制到/usr/local/go/src(这样做并不友好)。
英文:
I know I am lacking a fundamental understanding how Go is seeking for a package, but let me just emphasize my thoughts and if needed - you could downvote.
This is my structure of the Go module:
├── go.mod
├── gopher.json
├── main.go
├── story.go
├── template.html
└── tests
├── cyow_test.go
└── gopher.json
Nothing too outside of the straightforward, dedicated /tests directory where the tests are supposed to be placed.
This is my cyow_test.go file:
import (
"io/ioutil"
"story"
"testing"
)
func TestUnmarshallOverStoryStruct(t *testing.T) {
t.Parallel()
content, fileError := ioutil.ReadFile("gopher.json")
if fileError != nil {
t.Error("The file for Chapter is not found.")
}
story := story.Story{}
fmt.Println("Story has been initialized")
err := json.Unmarshal([]byte(content), &story)
fmt.PRintln("Json unmarshall statement has been executed.")
if err != nil {
panic(err)
}
}
You could ignore the function, it's mainly for some learning purposes. The important part is that I am relying on a story package, which has been declared as part of the module.
When I go inside /tests and run 'go test' I receive:
cyow_test.go:5:2: package story is not in GOROOT (/usr/local/go/src/story)
I have ran 'go mod tidy' inside the module root directory and my simple questions are:
- Why Go does not find out the package by default ? It's a package part of the module, so it schould come natively - this is my assumption.
- Does that mean that the only way to refer to packages ( even inside your module ) is to reference them through a remote repo URL, like github.com ... or eventually just copy the package to /usr/local/go/src ( which is not friendly at all )
答案1
得分: 3
你的假设是错误的。导入包的方式是'module/package'。模块名称不必包含存储库名称。不要将包复制到Go源代码目录中。
英文:
Your assumption is wrong. The way to import a package is 'module/package'. The module name does not have to include a repository name. Do not copy packages to go source directory.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论