可以对我的软件包进行单元测试,以确保它不导入特定的软件包吗?

huangapple go评论80阅读模式
英文:

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 (
  &quot;some_db&quot;
  &quot;dal&quot;
)

type UserDalDbSpecific struct {
}

func (_ UserDalDbSpecific) GetUser(id int) User {
  some_db.executeQuery(...)
  ...
  return user
}

register_dal() {
  dal.UserDal = UserDalDbSpecific{}
}

User code package:

import (
  &quot;dal&quot;
  &quot;some_db&quot; &lt;-- Fail here!
)

func someFunc() {
  user := dal.User.GetUser(1) // Right way
  some_db.DoSomething()  &lt;-- 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.

huangapple
  • 本文由 发表于 2017年4月11日 19:26:08
  • 转载请务必保留本文链接:https://go.coder-hub.com/43344584.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定