1// Copyright 2017 Google LLC 2// 3// Licensed under the Apache License, Version 2.0 (the "License"); 4// you may not use this file except in compliance with the License. 5// You may obtain a copy of the License at 6// 7// http://www.apache.org/licenses/LICENSE-2.0 8// 9// Unless required by applicable law or agreed to in writing, software 10// distributed under the License is distributed on an "AS IS" BASIS, 11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12// See the License for the specific language governing permissions and 13// limitations under the License. 14 15package testutil 16 17import ( 18 "math" 19 "math/big" 20 21 "github.com/golang/protobuf/proto" 22 "github.com/google/go-cmp/cmp" 23) 24 25var ( 26 alwaysEqual = cmp.Comparer(func(_, _ interface{}) bool { return true }) 27 28 defaultCmpOptions = []cmp.Option{ 29 // Use proto.Equal for protobufs 30 cmp.Comparer(proto.Equal), 31 // Use big.Rat.Cmp for big.Rats 32 cmp.Comparer(func(x, y *big.Rat) bool { 33 if x == nil || y == nil { 34 return x == y 35 } 36 return x.Cmp(y) == 0 37 }), 38 // NaNs compare equal 39 cmp.FilterValues(func(x, y float64) bool { 40 return math.IsNaN(x) && math.IsNaN(y) 41 }, alwaysEqual), 42 cmp.FilterValues(func(x, y float32) bool { 43 return math.IsNaN(float64(x)) && math.IsNaN(float64(y)) 44 }, alwaysEqual), 45 } 46) 47 48// Equal tests two values for equality. 49func Equal(x, y interface{}, opts ...cmp.Option) bool { 50 // Put default options at the end. Order doesn't matter. 51 opts = append(opts[:len(opts):len(opts)], defaultCmpOptions...) 52 return cmp.Equal(x, y, opts...) 53} 54 55// Diff reports the differences between two values. 56// Diff(x, y) == "" iff Equal(x, y). 57func Diff(x, y interface{}, opts ...cmp.Option) string { 58 // Put default options at the end. Order doesn't matter. 59 opts = append(opts[:len(opts):len(opts)], defaultCmpOptions...) 60 return cmp.Diff(x, y, opts...) 61} 62