首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >测试Golang Goroutine

测试Golang Goroutine
EN

Stack Overflow用户
提问于 2015-03-05 09:47:47
回答 2查看 7.8K关注 0票数 6

我一直在到处寻找,但到目前为止只有Ariejan de Vroom写的类似的here文章。

我想知道我是否可以在单元测试中引入goroutine,这样它就可以精确地计算正在运行的goroutines的并发数量,并且可以告诉我它们是否正确地产生了我所说的数量的goroutine。

例如,我有以下代码。

代码语言:javascript
复制
import (
    "testing"
    "github.com/stretchr/testify/assert"
)

func createList(job int, done chan bool) {
    time.Sleep(500)
    // do something
    time.Sleep(500)
    done <- true
    return
}

func TestNewList(t *testing.T) {
  list := NewList()
  if assert.NotNil(t, list) {
    const numGoRoutines = 16
    jobs := make(chan int, numGoRoutines)
    done := make(chan bool, 1)

    for j := 1; j <= numGoRoutines; j++ {
        jobs <- j
        go createList(j, done)
        fmt.Println("sent job", j)
    }
    close(jobs)
    fmt.Println("sent all jobs")
    <-done
}
EN

回答 2

Stack Overflow用户

发布于 2015-03-07 19:55:48

据我所知,您愿意限制同时运行的例程的数量,并验证它是否正常工作。我建议写一个函数,它将一个例程作为参数,并使用模拟例程来测试它。

在下面的示例中,spawn函数运行fn例程count次,但并发次数不超过limit例程。我将它封装到main函数中,以便在游乐场上运行它,但是您可以对您的测试方法使用相同的方法。

代码语言:javascript
复制
package main

import (
    "fmt"
    "sync"
    "time"
)

func spawn(fn func(), count int, limit int) {
    limiter := make(chan bool, limit)

    spawned := func() {
        defer func() { <-limiter }()
        fn()
    }

    for i := 0; i < count; i++ {
        limiter <- true
        go spawned()
    }
}

func main() {

    count := 10
    limit := 3

    var wg sync.WaitGroup
    wg.Add(count)

    concurrentCount := 0
    failed := false

    var mock = func() {
        defer func() {
            wg.Done()
            concurrentCount--
        }()

        concurrentCount++
        if concurrentCount > limit {
            failed = true // test could be failed here without waiting all routines finish
        }

        time.Sleep(100)
    }

    spawn(mock, count, limit)

    wg.Wait()

    if failed {
        fmt.Println("Test failed")
    } else {
        fmt.Println("Test passed")
    }
}

Playground

票数 1
EN

Stack Overflow用户

发布于 2015-03-05 15:02:36

一种可能的方法是使用runtime.Stack()或分析runtime.debug.PrintStack()的输出,以便在给定时间查看所有goroutines。

这些选项在"How to dump goroutine stacktraces?“中有详细介绍。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/28868596

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档