I have a table-driven test case like this one:
func CountWords(s string) map[string]int
func TestCountWords(t *testing.T) {
var tests = []struct {
input s
What is the idiomatic way to compare two maps in table-driven tests?
You have the project go-test/deep to help.
But: this should be easier with Go 1.12 (February 2019) natively: See release notes.
fmt.Sprint(map1) == fmt.Sprint(map2)
fmt
Maps are now printed in key-sorted order to ease testing.
The ordering rules are:
- When applicable, nil compares low
- ints, floats, and strings order by
<
- NaN compares less than non-NaN floats
bool
comparesfalse
beforetrue
- Complex compares real, then imaginary
- Pointers compare by machine address
- Channel values compare by machine address
- Structs compare each field in turn
- Arrays compare each element in turn
- Interface values compare first by
reflect.Type
describing the concrete type and then by concrete value as described in the previous rules.When printing maps, non-reflexive key values like NaN were previously displayed as
. As of this release, the correct values are printed.
Sources:
The CL adds: (CL stands for "Change List")
To do this, we add a package at the root, internal/fmtsort, that implements a general mechanism for sorting map keys regardless of their type.
This is a little messy and probably slow, but formatted printing of maps has never been fast and is already always reflection-driven.
The new package is internal because we really do not want everyone using this to sort things. It is slow, not general, and only suitable for the subset of types that can be map keys.
Also use the package in text/template
, which already had a weaker version of this mechanism.
You can see that used in src/fmt/print.go#printValue(): case reflect.Map: