I'm teaching myself Go for the fun of it but am running into similar
problems whenever I try to check for errors. Here's some code that
reproduces the problem:-
package mytest
import (
"fmt"
"reflect"
)
func inRange5(data interface{}) (interface{}, error) {
r := reflect.ValueOf(data)
k := r.Kind()
switch k {
case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32,
reflect.Uint64:
n := r.Uint()
if n >= 0 && n < 5 {
return n, nil
}
case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32,
reflect.Int64:
n := r.Int()
if n >= 0 && n < 5 {
return n, nil
}
default:
return nil, fmt.Errorf("data '%#v' type '%T' is invalid", data,
data)
}
switch k {
case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32,
reflect.Uint64:
return nil, fmt.Errorf("'%v' is out of range", r.Uint())
case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32,
reflect.Int64:
return nil, fmt.Errorf("'%v' is out of range", r.Int())
}
return nil, fmt.Errorf("Handling of %#v %T is wrong", data, data)
}
My test code:-
package mytest
import (
"errors"
"fmt"
"testing"
)
func TestInRange5(t *testing.T) {
i3 := int64(3)
testCases := []struct {
par interface{}
want interface{}
err error
}{
{i3, i3, nil},
{-1, nil, errors.New("'-1' is out of range")},
{5, nil, errors.New("'5' is out of range")},
{3.33, nil, errors.New("data '3.33' type 'float64' is
invalid")},
}
for i, tc := range testCases {
t.Run(fmt.Sprintf("Test inRange5 %d", i), func(t
*testing.T) {
got, err := inRange5(tc.par)
if got != tc.want || err != tc.err {
t.Errorf("got %#v %v; want %#v %v", got,
err, tc.want, tc.err)
}
})
}
}
The test output:-
--- FAIL: TestInRange5 (0.00s)
--- FAIL: TestInRange5/Test_inRange5_1 (0.00s)
mytest_test.go:25: got <nil> '-1' is out of range; want <nil> '-1'
is out of range
--- FAIL: TestInRange5/Test_inRange5_2 (0.00s)
mytest_test.go:25: got <nil> '5' is out of range; want <nil> '5' is
out of range
--- FAIL: TestInRange5/Test_inRange5_3 (0.00s)
mytest_test.go:25: got <nil> data '3.33' type 'float64' is invalid;
want <nil> data '3.33' type 'float64' is invalid
FAIL
exit status 1
FAIL mytest 0.820s
I'm convinced that I'm making a daft newbie error that's staring me in the
face, but I'm blowed if I can see it. Can somebody, please put me out of
my misery, TIA.
Kindest regards.
Mark Lawrence.
--
You received this message because you are subscribed to the Google Groups
"golang-nuts" group.
To unsubscribe from this group and stop receiving emails from it, send an email
to [email protected].
For more options, visit https://groups.google.com/d/optout.