diff --git a/btcec/v2/field_test.go b/btcec/v2/field_test.go index c416f27c..866ae98c 100644 --- a/btcec/v2/field_test.go +++ b/btcec/v2/field_test.go @@ -8,11 +8,35 @@ package btcec import ( "math/rand" + "reflect" + "unsafe" "encoding/hex" "testing" ) +// unsafeGetInternalState returns the field value's internal state by using +// reflection and is therefore considered to be unsafe and should be used in +// tests only. +func unsafeGetInternalState(f *FieldVal) [10]uint32 { + fieldType := reflect.ValueOf(f).Elem().FieldByName("n") + fieldValueType := reflect.NewAt( + fieldType.Type(), unsafe.Pointer(fieldType.UnsafeAddr()), + ) + return fieldValueType.Elem().Interface().([10]uint32) +} + +// unsafeSetInternalState sets the field value's internal state by using +// reflection and is therefore considered to be unsafe and should be used in +// tests only. +func unsafeSetInternalState(f *FieldVal, n [10]uint32) { + fieldType := reflect.ValueOf(f).Elem().FieldByName("n") + fieldValueType := reflect.NewAt( + fieldType.Type(), unsafe.Pointer(fieldType.UnsafeAddr()), + ) + fieldValueType.Elem().Set(reflect.ValueOf(n)) +} + // TestFieldSetInt ensures that setting a field value to various native // integers works as expected. func TestFieldSetInt(t *testing.T) { @@ -35,13 +59,13 @@ func TestFieldSetInt(t *testing.T) { }} for _, test := range tests { - _ = new(FieldVal).SetInt(test.in) - // TODO(roasbeef): don't have access to internal state - /*if !reflect.DeepEqual(f.n, test.expected) { - t.Errorf("%s: wrong result\ngot: %v\nwant: %v", test.name, f.n, - test.expected) + f := new(FieldVal).SetInt(test.in) + n := unsafeGetInternalState(f) + if !reflect.DeepEqual(n, test.expected) { + t.Errorf("%s: wrong result\ngot: %v\nwant: %v", + test.name, n, test.expected) continue - }*/ + } } } @@ -306,16 +330,16 @@ func TestNormalize(t *testing.T) { } t.Logf("Running %d tests", len(tests)) - for range tests { - // TODO(roasbeef): can't access internal state - /*f := new(FieldVal) - f.n = test.raw + for i, test := range tests { + f := new(FieldVal) + unsafeSetInternalState(f, test.raw) f.Normalize() - if !reflect.DeepEqual(f.n, test.normalized) { + n := unsafeGetInternalState(f) + if !reflect.DeepEqual(n, test.normalized) { t.Errorf("FieldVal.Normalize #%d wrong result\n"+ - "got: %x\nwant: %x", i, f.n, test.normalized) + "got: %x\nwant: %x", i, n, test.normalized) continue - }*/ + } } }