2015-03-05 19 views
5

Ho cercato in giro, ma finora è andato solo articolo simile scritto here di Ariejan de Vroom.Test Golang Goroutine

Vorrei sapere se riesco a portare la goroutine nei test di unità in modo tale che possa contare con precisione il numero simultaneo di goroutine in esecuzione e può dirmi se sono generati correttamente goroutine nel numero che ho indicato.

ho il seguente codice di esempio ..

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 
} 
+1

Che cosa stai cercando di verificare? Che stai iniziando 16 goroutine? Non sto seguendo il problema che stai cercando di risolvere. – sberry

+0

Perché si invia l'int al canale di lavoro? Sembra che tu abbia 2 disegni lì. – LenW

risposta

0

Semplicemente nell'esempio è possibile leggere il canale numerGoRoutines fatto per verificare che si ottengano così tante risposte?

0

Come ho capito, si è disposti a limitare il numero di routine in esecuzione contemporaneamente e verificare se funziona correttamente. Suggerirei di scrivere una funzione che utilizzi una routine come argomento e utilizzi la routine di simulazione per testarla.
Nell'esempio seguente la funzione spawn esegue le routine fncount ma non più delle routine limit contemporaneamente. L'ho spostato nella funzione principale per eseguirlo al campo da gioco, ma puoi usare lo stesso approccio per il tuo metodo di prova.

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