go.mercari.io/datastore@v1.8.2/testbed/reflect_test.go (about)

     1  package testbed
     2  
     3  import (
     4  	"context"
     5  	"fmt"
     6  	"reflect"
     7  	"testing"
     8  
     9  	"go.mercari.io/datastore"
    10  	cdatastore "go.mercari.io/datastore/clouddatastore"
    11  )
    12  
    13  var _ datastore.PropertyTranslator = UserKey(1)
    14  
    15  type UserKey int64
    16  
    17  func (v UserKey) ToPropertyValue(ctx context.Context) (interface{}, error) {
    18  	client, err := cdatastore.FromContext(ctx)
    19  	if err != nil {
    20  		return datastore.Property{}, err
    21  	}
    22  
    23  	key := client.IDKey("User", int64(v), nil)
    24  	return key, nil
    25  }
    26  
    27  func (v UserKey) FromPropertyValue(ctx context.Context, p datastore.Property) (dst interface{}, err error) {
    28  	userKey, ok := p.Value.(datastore.Key)
    29  	if !ok {
    30  		return nil, fmt.Errorf("unknown type: %t", p.Value)
    31  	}
    32  
    33  	return UserKey(userKey.ID()), nil
    34  }
    35  
    36  func TestPropertyTranslaterMockup(t *testing.T) {
    37  	ctx := context.Background()
    38  
    39  	userKey := UserKey(100)
    40  	v, err := userKey.ToPropertyValue(ctx)
    41  	if err != nil {
    42  		t.Fatal(err)
    43  	}
    44  
    45  	if v, ok := v.(datastore.Key); !ok || v.Kind() != "User" || v.ID() != 100 {
    46  		t.Fatalf("unexpected: %v", v)
    47  	}
    48  
    49  	f, ok := reflect.TypeOf(struct{ F UserKey }{}).FieldByName("F")
    50  	if !ok {
    51  		t.Fatalf("unexpected: %v", ok)
    52  	}
    53  	typeOfPropertyTranslater := reflect.TypeOf((*datastore.PropertyTranslator)(nil)).Elem()
    54  	if v := f.Type.AssignableTo(typeOfPropertyTranslater); !v {
    55  		t.Fatalf("unexpected: %v", ok)
    56  	}
    57  
    58  	newV := reflect.New(f.Type)
    59  	pt := newV.Elem().Interface().(datastore.PropertyTranslator)
    60  	dst, err := pt.FromPropertyValue(ctx, datastore.Property{Value: v})
    61  	if err != nil {
    62  		t.Fatal(err)
    63  	}
    64  
    65  	if v := dst.(UserKey); v != 100 {
    66  		t.Fatalf("unexpected: %v", ok)
    67  	}
    68  }