GO单元测试无关紧要的错误“主机名解决错误”
我正在尝试为此编写 project
看来我需要经常进行重新操作,目前正在工作,在上面。为了在project/api/handlers中测试功能。go
我试图编写一些单元测试代码,但是总是要处理与DB初始化有关的错误。 DB来自PSQL Docker容器。错误说给定的主机名是无效的,但是如果不测试它无问题。另外,对于Dockerized PostgreSQL,容器名称被用作主机名,这应该不是问题。
错误是:
db连接错误:无法连接到
完成host = postgresdbt user = postgres database = worth2watchdb
:hostName解决错误(lookup postgresdbt:no这样的主机) 流程用退出代码1
无论如何,我做了几个重构,并从数据库查询功能管理了抽象功能,但是此错误仍然发生,我无法执行测试。因此,最后我决定在同一软件包中进行完全空白的测试,只需使用BCRypt软件包检查即可。
func TestCheckPasswordHash(t *testing.T) {
ret, err := HashPassword("password")
assert.Nil(t, err)
ok := CheckPasswordHash("password", ret)
if !ok {
t.Fail()
}
}
//HashPassword function hashes password with bcrypt algorithm as Cost value and return hashed string value with an error
func HashPassword(password string) (string, error) {
bytes, err := bcrypt.GenerateFromPassword([]byte(password), 4)
return string(bytes), err
}
//CheckPasswordHash function checks two inputs and returns TRUE if matches
func CheckPasswordHash(password, hash string) bool {
err := bcrypt.CompareHashAndPassword([]byte(hash), []byte(password))
return err == nil
}
但是,当我尝试使用testCheckPasswordHash
命令GO test -run testcheckpasswordhash ./api
的命令时,它仍然给出相同的错误。顺便说一句,文件是handlers_test.go,函数在handlers.go文件中,包装名称均为API。
与任何类型的DB相关功能没有联系,但是我一次又一次地存在相同的错误。当我在另一个项目或project/util/util_test.go
中运行此testcheckpasswordhash
代码代码时,它会按预期进行检查和通过。
我不知道该怎么办,除非弄清楚,否则我似乎无法在此软件包中执行任何测试。
提前致谢。最好的祝愿。
I am trying to write unit test for this project
It appears that i need to refactor a lot and currently working on it. In order to test functions in project/api/handlers.go
i was trying to write some unit test code however always taking error related with DB initializing. DB is from Psql Docker container. Error says given hostname is not valid, however without testing it works as no problem. Also, for Dockerized postgresql, container name is being used as hostname and this shouldn't be a problem.
The error is:
DB connection error: failed to connect to
host=postgresdbT user=postgres database=worth2watchdb
: hostname resolving error (lookup postgresdbT: no such host)
Process finished with the exit code 1
Anyway, i did a couple refactor and managed abstracting functions from DB query functions however this error still occurs and i cannot perform the test. So finally i decided to perform a totally blank test within same package simply checks with bcrypt package.
func TestCheckPasswordHash(t *testing.T) {
ret, err := HashPassword("password")
assert.Nil(t, err)
ok := CheckPasswordHash("password", ret)
if !ok {
t.Fail()
}
}
//HashPassword function hashes password with bcrypt algorithm as Cost value and return hashed string value with an error
func HashPassword(password string) (string, error) {
bytes, err := bcrypt.GenerateFromPassword([]byte(password), 4)
return string(bytes), err
}
//CheckPasswordHash function checks two inputs and returns TRUE if matches
func CheckPasswordHash(password, hash string) bool {
err := bcrypt.CompareHashAndPassword([]byte(hash), []byte(password))
return err == nil
}
However when I've tried to perform test for only TestCheckPasswordHash
function with command of go test -run TestCheckPasswordHash ./api
, it still gives same error. Btw, File is handlers_test.go, functions are at handlers.go file, package name is api for both .
There is no contact with any kind of DB related functions however i am having same error again and again. When i run this TestCheckPasswordHash
code in another project or at project/util/util_test.go
, it checks and passes as expected.
I don't know what to do, it seems that i cannot perform any test in this package unless figure this out.
Thanks in advance. Best wishes.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
正在检查您的存储库,不错的实现,整洁的好工作!
我认为您的问题是在Init功能中,请尝试将其评论,看看它对单个测试是否有效。
解释Init函数的工作方式有点复杂,没有文件图作为例如,但是您可以检查官方文档:
https://go.dev/doc/doc/effective_go#init
工作请给我回去
Was checking your repo, nice implementation, neat an simple good job!
I think your issue is in the init function, please try commenting it out and see if it work for that single test.
Is a bit complex to explain how the init function works without a graph of files as example but you can check the official documentation:
https://go.dev/doc/effective_go#init
PD: if this doesn't work please write me back
我找到了发生此错误的原因,现在已经解决了。
这与Docker的工作原理有部分相关,该原理是必须宣布DB_Hostname的工作原理,但我们对此无能为力。因此,我们需要一种更好的方法来克服。
当执行(偶数)函数的GO测试命令时,请按照执行顺序进行测试逻辑检查整个软件包(不是整个项目),例如首先变量声明和init()函数稍后。如果调用外部软件包项目,运行时也绕开该项目的包装。
即使您仅测试无关的功能,也应该考虑在执行测试之前,运行时会评估整个软件包。
为了防止这种情况,我将包装级变量(即使在另一个软件包中)包装,直接调用DB和CACHE。在初始阶段,可以将其分配为新变量。但是,将通过main或main.init()确保它们的连接
,现在,在测试之前,检查了所有相关变量(以同一软件包或外部)进行检查。假设是否需要DB代理(Redis.Client或PGXPool.Pool),我们正在创建一个新代理,编译器不会抱怨并且开始测试。代理只能通过MAIN或我们想要的地方的函数调用来运行。
对于更可维护的代码,这是更好的(可能不是最好的)实践。受抚养人的初始化应能够谨慎地和功能需求进行谨慎处理。至少,通过简单的重构,应该解决问题。
I've found the reason why this error occured and now it's solved.
This is partially related with Docker's working principle of how DB_Hostname must be declared but we can do nothing about it. So we need a better approach to overcome.
When go test command executed for (even) a function, Go testing logic checks whole package(not whole project) as per execution order, such as firstly variable declarations and init() function later. In case of calling an external package item, runtime detours that package for the item also.
Even if you are testing only an irrelevant function, you should consider that, before performing the test, Go runtime will evaluate whole package.
In order to prevent this, i wrapped the package level variables(even though they are in another package) that directly calls DB and cache. On initial stage, these can be allocated as a new variable. However, their connection will be ensured by main or main.init()
And now, prior to testing, all relevant variables (in same package or via external) are checked. Let's say if DB agent (redis.client or pgxpool.Pool) is needed, we are creating a new agent, compiler doesn't complain and testing begins. Agent will be operational only by a function call from main or somewhere we want to.
This is a better(may be not best) practice for a more maintainable code. Initialization of dependants should be able to be handled cautiously and in context with the functional needs. At least, with a simple refactoring, problem should be solvable.