Test Golan Gorutin

I searched around, but so far only gone a similar article written by Ariejan de Vroom.

I would like to know if I can bring goroutine into unit testing so that it can accurately count the number of concurrent # goroutines and can tell me if they spawned goroutine correctly in the number I specified.

I have the following code, for example.

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 } 
+5
source share
3 answers

One option would be to use runtime.Stack() or runtime.debug.PrintStack() output of runtime.debug.PrintStack() to see all the goroutines at a given time.

These options are described in detail in the How to reset gotoutine stacktraces section. "

0
source

Just in your example, can you read the made channels numGoRoutines once to make sure you get a lot of answers?

0
source

As I understand it, you are ready to limit the number of running routines at the same time and check whether it works correctly. I would suggest writing a function that will perform the routine as an argument and use a mock procedure to test it.
In the following spawn example, the function executes fn routines count times, but no more than limit routines at a time. I wrapped it in the main function to run it on the playground, but you can use the same approach for your test method.

 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

0
source

Source: https://habr.com/ru/post/1214706/


All Articles