vendredi 27 février 2015

Go Lang Concurrent Unit Test for Method with Mutex

Writing a very simply "load test" application in go lang for a homework assignment. I'm functionally complete, but am trying to write a concurrent unit test for a method that effectively resets a counter.



func (c *Counter) Reset(statistic string) {
c.Lock()
c.counters[statistic] = START_VALUE
c.Unlock()
}


Counter is a struct with a sync.RWMutex and a map[string]int. Here's the associated unit test function:



func TestReset(t *testing.T) {
counter := stats.New()
var wg sync.WaitGroup
wg.Add(3)
go func() {
defer wg.Done()
increment(counter, dataSetOne)
}()
go func() {
defer wg.Done()
counter.Reset(stats.KEY_100)
}()
go func() {
defer wg.Done()
increment(counter, dataSetTwo)
}()
wg.Wait()

actual := counter.Copy()

for k, v := range expectedReset {
if v != actual[k] {
t.Errorf("counter %s: expected %d, got %d", k, v, actual[k])
}
}
}


All I'm doing is adding a bunch of data to some set of keys, resetting one key to zero, then adding a bunch more data. The problem, I feel, is that my assertion for what's expected changes depending on the order of operations. The test assumes that each go routine will acquire the lock sequentially.


With the understanding that its a bit late to change the implementation to use channels, is there something I'm missing, or a better way to do this?


Aucun commentaire:

Enregistrer un commentaire