adding tests for report.Counters.String

This commit is contained in:
Paul Bellamy
2016-03-23 16:20:57 +00:00
parent 80dc714c1e
commit 30b81a581b
2 changed files with 46 additions and 12 deletions

View File

@@ -88,21 +88,25 @@ func (c Counters) Merge(other Counters) Counters {
return Counters{output}
}
func (c Counters) String() string {
if c.psMap == nil {
return "{}"
func (c Counters) ForEach(f func(key string, val int)) {
if c.psMap != nil {
keys := c.psMap.Keys()
sort.Strings(keys)
for _, key := range keys {
if val, ok := c.psMap.Lookup(key); ok {
f(key, val.(int))
}
}
}
keys := []string{}
for _, k := range c.psMap.Keys() {
keys = append(keys, k)
}
sort.Strings(keys)
}
func (c Counters) String() string {
buf := bytes.NewBufferString("{")
for _, key := range keys {
val, _ := c.psMap.Lookup(key)
fmt.Fprintf(buf, "%s: %d, ", key, val)
}
prefix := ""
c.ForEach(func(k string, v int) {
fmt.Fprintf(buf, "%s%s: %d", prefix, k, v)
prefix = ", "
})
fmt.Fprintf(buf, "}")
return buf.String()
}

View File

@@ -132,3 +132,33 @@ func TestCountersEncoding(t *testing.T) {
}
}
func TestCountersString(t *testing.T) {
{
var c Counters
have := c.String()
want := `{}`
if want != have {
t.Errorf("Expected: %s, Got %s", want, have)
}
}
{
have := EmptyCounters.String()
want := `{}`
if want != have {
t.Errorf("Expected: %s, Got %s", want, have)
}
}
{
have := EmptyCounters.
Add("foo", 1).
Add("bar", 2).String()
want := `{bar: 2, foo: 1}`
if want != have {
t.Errorf("Expected: %s, Got %s", want, have)
}
}
}