登录
首页 >  Golang >  Go问答

解决死锁问题:等待失败测试信号指南

来源:stackoverflow

时间:2024-02-10 14:09:14 243浏览 收藏

IT行业相对于一般传统行业,发展更新速度更快,一旦停止了学习,很快就会被行业所淘汰。所以我们需要踏踏实实的不断学习,精进自己的技术,尤其是初学者。今天golang学习网给大家整理了《解决死锁问题:等待失败测试信号指南》,聊聊,我们一起来看看吧!

问题内容

我有两个 goroutine,它们是测试期间的两个 testxxx 函数。我使用条件变量来同步这些 goroutine。然而,一旦其中一个测试失败,而另一个正在等待信号。僵局来了。另外,如果 testfunctionb 失败,我希望 testfunctiona 也失败。

var cond sync.cond
func testfunctiona(t *testing.t){
   // ... some codes...
   cond.wait()
}
func testfunctionb(t *testing.t){
   // ... some codes...
   t.fail()
   // ... some codes...
   cond.broadcast()
}

我尝试过一些方法,例如:

var cond sync.Cond
var A_t *testing.T
func TestFunctionA(t *testing.T){
   // ... Some codes...
   A_t = t
   // ... Some codes...
   cond.Wait()
}
func TestFunctionB(t *testing.T){
   // ... Some codes...
   t.Cleanup(func(){
      if !A_t.Failed(){
          A_t.Fail()
      }
      cond.Broadcast()
   })
   t.Fail()
   // ... Some codes...
   cond.Broadcast()
}

但是当functionb没有错误时,a_t.fail()仍然会被触发。

我也在考虑使用 context.context()。但是,我不知道如何在上下文中运行测试函数。 感谢您阅读我的问题!我感谢任何评论或讨论!


正确答案


一个测试不应与另一个测试交互。但是,当使用子测试时,我们可以在测试用例之间共享任何内容。

这是一个示例:

package main

import (
    "errors"
    "testing"
)

func TestFruits(t *testing.T) {
    var err error
    t.Run("test apple", getTestAppleFunc(&err))
    t.Run("test banana", getTestBananaFunc(&err))
}

func handleError(t *testing.T, err *error) {
    if err != nil && *err != nil {
        t.Error(*err)
    }
}

func getTestAppleFunc(err *error) func(*testing.T) {
    return func(t *testing.T) {
        handleError(t, err)
        *err = errors.New("Apple failed")
    }
}

func getTestBananaFunc(err *error) func(*testing.T) {
    return func(t *testing.T) {
        handleError(t, err)
    }
}
  • 在函数 gettestbananafuncgettestapplefunc 中,错误指针作为参数传递。
  • 在上面的例子中,首先执行的是gettestapplefunc
  • 如果在 gettestapplefunc 中赋值错误(如上例所示),则 gettestbananafunc 函数将失败。

文中关于的知识介绍,希望对你的学习有所帮助!若是受益匪浅,那就动动鼠标收藏这篇《解决死锁问题:等待失败测试信号指南》文章吧,也可关注golang学习网公众号了解相关技术文章。

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