英文:
Is it possible to unit test that my package does not import a specific package?
问题
我想确保我的Go包使用由“dal”包提供的var实例,并且不会意外地导入和直接使用数据库访问包。
我猜我可以在源代码中进行正则表达式搜索,但我想知道是否有一种通过标准的Go测试来确保这个规则的方法?
只是为了给你一个我要做的想法:
接口包:
package dal
type UserDal interface {
GetUser(id int) User
}
实现包:
package dal_db_specific
import (
"some_db"
"dal"
)
type UserDalDbSpecific struct {
}
func (_ UserDalDbSpecific) GetUser(id int) User {
some_db.executeQuery(...)
...
return user
}
register_dal() {
dal.UserDal = UserDalDbSpecific{}
}
用户代码包:
import (
"dal"
"some_db" <-- 这里会失败!
)
func someFunc() {
user := dal.User.GetUser(1) // 正确的方式
some_db.DoSomething() <-- 这里会失败!
}
英文:
I want to make sure my Go package use var instances provided by a "dal" package and does not accidentally import and use db access packages directly.
I guess I can do regexp search on source but I wonder if there is a way to ensure the rule through standard Go testing?
Just to give an idea what I'm going to do:
Interface package:
package dal
type UserDal interface {
GetUser(id int) User
}
Implementation package:
package dal_db_specific
import (
"some_db"
"dal"
)
type UserDalDbSpecific struct {
}
func (_ UserDalDbSpecific) GetUser(id int) User {
some_db.executeQuery(...)
...
return user
}
register_dal() {
dal.UserDal = UserDalDbSpecific{}
}
User code package:
import (
"dal"
"some_db" <-- Fail here!
)
func someFunc() {
user := dal.User.GetUser(1) // Right way
some_db.DoSomething() <-- Fail here!
}
答案1
得分: 5
比grep稍微可靠一些:使用标准的parser
包解析目标源代码,并检查AST。你需要查找与数据库访问包匹配的ImportSpec
节点。如果找到任何节点,则测试失败。
英文:
Slightly more reliable than grep: parse the target source using the standard parser
package and inspect the AST. You'd be looking for ImportSpec
nodes matching the DB access packages. Fail the test if any are found.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论