登录
首页 >  Golang >  Go问答

停止 Go 例程的测试

来源:stackoverflow

时间:2024-02-29 21:27:25 428浏览 收藏

你在学习Golang相关的知识吗?本文《停止 Go 例程的测试》,主要介绍的内容就涉及到,如果你想提升自己的开发能力,就不要错过这篇文章,大家要知道编程理论基础和实战操作都是不可或缺的哦!

问题内容

我有一个节点想要启动,直到我决定停止它为止。我目前有一个在 contexts done 通道上阻塞的 start 方法,然后有一个调用取消的 stop 函数,在我的测试中,我的 start 似乎永远挂起,而 stop 从未被调用。我不明白为什么没有调用 done 信号并停止我的节点。

var (
    // ctx is the node's main context.
    ctx, cancel = context.withcancel(context.background())

    // cancel is a function used to initiate graceful shutdown.
    cancel = cancel
)

type (
    node struct {
      database *store.store
    }
)

// starts run the node.
func (n *node) start() error {
    var nodeerror error

    defer func() {
        err := n.database.close()
        if err != nil {
            nodeerror = err
        }
    }()

    <-ctx.done()

    return nodeerror
}

// stop stops the node.
func (n *node) stop() {
    cancel()
}

我的测试是:

func TestNode_Start(t *testing.T) {
    n, _ := node.NewNode("1.0")
    err := n.Start()
    n.Stop()
    assert.NoError(t, err)
}

解决方案


您的代码存在几个问题。让我们来分解一下。

var (
    // ctx is the node's main context.
    ctx, cancel = context.withcancel(context.background())

    // cancel is a function used to initiate graceful shutdown.
    cancel = cancel
)

这些不应该是包变量。它们应该是实例变量——也就是说,成员或 node 结构。通过创建这些包变量,如果您有多个使用 node 的测试,它们都会互相踩踏,导致竞争条件和崩溃。因此,请执行以下操作:

type node struct {
    database *store.store
    ctx      context.context
    cancel   context.cancelfunc
}

接下来,我们看到您的 start() 方法中有一个延迟函数:

// starts run the node.
func (n *node) start() error {
    var nodeerror error

    defer func() {
        err := n.database.close()
        if err != nil {
            nodeerror = err
        }
    }()
    /* snip */

这不会达到您的预期。一旦 start() 返回,它就会关闭数据库连接——在任何东西有机会使用它之前。

相反,您应该在 stop() 方法中关闭数据库连接:

// stop stops the node.
func (n *node) stop() error {
    n.cancel()
    return n.database.close()
}

最后,您的 start() 方法会阻塞,因为它等待上下文取消,而在调用 stop() 之前不可能取消该上下文,而 stop() 只在 start() 返回后调用: p>

func (n *node) start() error {
    /* snip */

    <-ctx.done()

    return nodeerror
}

我根本想不出任何理由在 start() 中包含 <-ctx.done,所以我将其删除。

根据我建议的所有更改,您应该得到如下所示的结果:

type Node struct {
    database *store.Store
    ctx      context.Context
    cancel   context.CancelFunc
}

// Starts run the Node.
func (n *Node) Start() {
    n.ctx, n.cancel = context.WithCancel(context.Background())
}

// Stop stops the node.
func (n *Node) Stop() error {
    n.cancel()
    return n.database.Close()
}

当然,这仍然留下了是否/在哪里/如何使用 ctx 的问题。由于您的原始代码不包含该内容,所以我也不包含。

以上就是本文的全部内容了,是否有顺利帮助你解决问题?若是能给你带来学习上的帮助,请大家多多支持golang学习网!更多关于Golang的相关知识,也可关注golang学习网公众号。

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