|
|
|
@ -1,6 +1,10 @@
|
|
|
|
|
package arrays
|
|
|
|
|
|
|
|
|
|
import "testing"
|
|
|
|
|
import (
|
|
|
|
|
"reflect"
|
|
|
|
|
"slices"
|
|
|
|
|
"testing"
|
|
|
|
|
)
|
|
|
|
|
|
|
|
|
|
// go test -cover will show the test coverage for our package.
|
|
|
|
|
|
|
|
|
@ -36,3 +40,44 @@ func TestSum(t *testing.T) {
|
|
|
|
|
// })
|
|
|
|
|
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
func TestSumAll(t *testing.T) {
|
|
|
|
|
|
|
|
|
|
got := SumAll([]int{1, 2}, []int{0, 9})
|
|
|
|
|
expected := []int{3, 9}
|
|
|
|
|
|
|
|
|
|
// can't compare slices...slices can only be compared to nil
|
|
|
|
|
// if got != expected {
|
|
|
|
|
// t.Errorf("got %v expected %v given", got, expected)
|
|
|
|
|
// }
|
|
|
|
|
|
|
|
|
|
// https://pkg.go.dev/reflect#DeepEqual standard lib to the rescue
|
|
|
|
|
|
|
|
|
|
// It's important to note that reflect.DeepEqual is not "type safe"
|
|
|
|
|
// - the code will compile even if you did something a bit silly.
|
|
|
|
|
// To see this in action, temporarily change the test to:
|
|
|
|
|
|
|
|
|
|
// func TestSumAll(t *testing.T) {
|
|
|
|
|
|
|
|
|
|
// got := SumAll([]int{1, 2}, []int{0, 9})
|
|
|
|
|
// want := "bob"
|
|
|
|
|
|
|
|
|
|
// if !reflect.DeepEqual(got, want) {
|
|
|
|
|
// t.Errorf("got %v want %v", got, want)
|
|
|
|
|
// }
|
|
|
|
|
// }
|
|
|
|
|
|
|
|
|
|
if !reflect.DeepEqual(got, expected) {
|
|
|
|
|
t.Errorf("Using reflect.DeepEqual got %v expected %v given", got, expected)
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
// From Go 1.21, slices standard package is available, which has a
|
|
|
|
|
// slices.Equal function to do a simple shallow compare on slices,
|
|
|
|
|
// where you don't need to worry about the types like the above case.
|
|
|
|
|
// Note that this function expects the elements to be comparable
|
|
|
|
|
// So, it can't be applied to slices with non-comparable elements like 2D slices.
|
|
|
|
|
|
|
|
|
|
if !slices.Equal(got, expected) {
|
|
|
|
|
t.Errorf("Using slices.Equal got %v expected %v given", got, expected)
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|