登录
首页 >  Golang >  Go问答

分享Golang包测试数据文件的最佳实践

来源:stackoverflow

时间:2024-03-09 10:18:26 102浏览 收藏

积累知识,胜过积蓄金银!毕竟在Golang开发的过程中,会遇到各种各样的问题,往往都是一些细节知识点还没有掌握好而导致的,因此基础知识点的积累是很重要的。下面本文《分享Golang包测试数据文件的最佳实践》,就带大家讲解一下知识点,若是你对本文感兴趣,或者是想搞懂其中某个知识点,就请你继续往下看吧~

问题内容

我们创建了一个私有go库(实用程序包)来在服务之间共享通用的api方法和业务逻辑。在实用程序包中,我们在“.json”文件中有数十个模拟 json 响应,用于模拟 api 测试。

使用此实用程序包的服务也希望访问相同的模拟文件,因为它们依赖相同的模拟 api 响应来测试各种内部业务逻辑。有没有办法可以通过一些相对文件路径或预编译它们(字节或字符串)来共享这些文件,以允许消费者测试在导入后通过标准 pkg 变量或方法引用相同的 .json 文件(文件路径或数据)通过 go 获取 github.com/whatever/utility-library

理想情况下,消费者测试可以通过子包(如“http/httptest”)访问这些文件,然后在自己的模拟服务器中引用内部 .json 文件(如 httptest.getbusinessobject.response []byteresponsefilepath string , etc)。我们希望继续将模拟响应存储在同一实用程序模块内的 .json 文件中,但只是将它们公开给消费者测试文件,严格用于测试目的。

my-api-pkg
├── go.mod
└── api
    └── api.go
    └── api_test.go // <= we currently access .json files here like utiltest.apiresponse []byte
    └── apitest // <= sub pkg that contains testing methods and .json accessors
        └── apitest.go
        └── responses
            └── api.response.json
my-service-pkg
├── go.mod
├── server.go
├── server_test.go
└── sub-pkg
    └── subpkg.go
    └── subpkg_test.go // <= want to access utiltest.apiResponse []byte for api mocks here

正确答案


非 go 文件和 _test.go 文件不会编译到模块中。要发布 _test.go 文件,请将其重命名为 .go 文件并导出要向客户端公开的变量和函数。

对于非 go 文件,从 go 1.16 开始,embed

package mycompany.com/common/testing

import _ "embed"

//go:embed responses/api.response.json
var mockapijsonresponse []byte // or string

目录树如下所示:

testing 
└── testing.go
└── responses
    └── api.response.json

然后您的客户将能够像往常一样引用这些导出的变量和函数:

package mycompany.com/service

import (
    "testing"
    common_testing "mycompany.com/common/testing"
)

func testthings(t *testing.t) {
    mock := common_testing.mockapijsonresponse
    // ...
}

op答案!我的问题似乎是我的 apitest 包中有一个导入的实用程序 fn,来自它自己的内部testing.go 文件,这意味着它的 init() 函数正在运行并污染上游 pkg 测试运行。

我最初的方法是合理的,但是在我删除了内部testing.go 导入后,erptest pkg 不再被下载到上游服务。我更改了结构以引用根目录下的测试目录,如下所示,这恢复了 apitest pkg 的 upsrtream 下载:

/my-api-pkg
├── go.mod
└── /api
    └── api.go
    └── api_test.go // <= we currently access .json files here like utiltest.apiresponse []byte
    └── /apitest // <= sub pkg that contains testing methods and .json accessors
        └── apitest.go
└── /testing // <= moving the files here re-enabled download and access or erptest code to upstream consumers
    └── /files
        └── /api.response.json

这是我的 apitest pkg 导出的基本结构,用于通过 apitest.domain().getapiroute1.res1 访问上游文件(作为 []byte)

// accessor
type domainaccessor struct {
    getapiroute1 getapiroute1
    ...
}

func domainaccessor() domainaccessor {
    return domainaccessor{
        getapiroute1: _getapiroute1,
        ...
    }
}

// individual file accessors for each route
type getapiroute1 struct {
    res1 []byte
    res2 []byte
}

var _getapiroute1 = getapiroute1{
    res1: loadfile("testing/files/api/v1/domain/getapiroute1.res.json"),
    res2: loadfile("testing/files/api/v1/domain/getapiroute2.res.json"),
}

将文件读取到 []byte 的加载文件 fn

func loadFile(filepath string) []byte {
    dir := ""
    _, filename, _, ok := runtime.Caller(0)
    if ok {
        dir = path.Join(path.Dir(filename), "..", "..", "..")
    }
    fullPath := path.Join(dir, filepath)
    body, err := ioutil.ReadFile(fullPath)
    if err != nil {
        log.Println("Error apitest.loadFile: unable to read file", err)
        panic(err)
    }
    return body
}

理论要掌握,实操不能落!以上关于《分享Golang包测试数据文件的最佳实践》的详细介绍,大家都掌握了吧!如果想要继续提升自己的能力,那么就来关注golang学习网公众号吧!

声明:本文转载于:stackoverflow 如有侵犯,请联系study_golang@163.com删除
相关阅读
更多>
最新阅读
更多>
课程推荐
更多>