github.com/altipla-consulting/ravendb-go-client@v0.1.3/generate_id_test.go (about) 1 package ravendb 2 3 import ( 4 "testing" 5 6 "github.com/stretchr/testify/assert" 7 ) 8 9 type WithID struct { 10 N int 11 B bool 12 ID string 13 } 14 15 type WithId struct { 16 N int 17 B bool 18 Id string 19 } 20 21 type Withid struct { 22 N int 23 B bool 24 id string 25 } 26 27 type NoID struct { 28 N int 29 B bool 30 } 31 32 type WithIntID struct { 33 N int 34 B bool 35 ID int 36 } 37 38 func TestTryGetSetIDFromInstance(t *testing.T) { 39 { 40 // verify can get/set field name ID of type string 41 exp := "hello" 42 s := WithID{ID: exp} 43 got, ok := tryGetIDFromInstance(s) 44 assert.True(t, ok) 45 assert.Equal(t, exp, got) 46 47 got, ok = tryGetIDFromInstance(&s) 48 assert.True(t, ok) 49 assert.Equal(t, exp, got) 50 51 exp = "new" 52 ok = trySetIDOnEntity(s, exp) 53 54 // can't set on structs, only on pointer to structs 55 assert.False(t, ok) 56 assert.NotEqual(t, exp, s.ID) 57 58 ok = trySetIDOnEntity(&s, exp) 59 assert.True(t, ok) 60 assert.Equal(t, exp, s.ID) 61 } 62 63 { 64 // id that is empty string is not valid 65 s := WithID{} 66 got, ok := tryGetIDFromInstance(s) 67 assert.False(t, ok) 68 assert.Equal(t, "", got) 69 70 exp := "new" 71 ok = trySetIDOnEntity(&s, exp) 72 assert.True(t, ok) 73 assert.Equal(t, exp, s.ID) 74 } 75 76 { 77 // "Id" is not valid name for id field, must be "ID" 78 exp := "hello" 79 s := WithId{Id: exp} 80 got, ok := tryGetIDFromInstance(s) 81 assert.False(t, ok) 82 assert.Equal(t, "", got) 83 84 got, ok = tryGetIDFromInstance(&s) 85 assert.False(t, ok) 86 assert.Equal(t, "", got) 87 88 exp = "new" 89 ok = trySetIDOnEntity(s, exp) 90 // can't set on structs, only on pointer to structs 91 assert.False(t, ok) 92 assert.NotEqual(t, exp, s.Id) 93 94 ok = trySetIDOnEntity(&s, exp) 95 assert.False(t, ok) 96 } 97 98 { 99 // verify doesn't get/set unexported field 100 exp := "hello" 101 s := Withid{id: exp} 102 got, ok := tryGetIDFromInstance(s) 103 assert.False(t, ok) 104 assert.Equal(t, "", got) 105 106 exp = "new" 107 ok = trySetIDOnEntity(s, exp) 108 assert.False(t, ok) 109 assert.Equal(t, "hello", s.id) 110 } 111 112 { 113 // verify doesn't get/set if there's no ID field 114 exp := "new" 115 s := NoID{} 116 got, ok := tryGetIDFromInstance(s) 117 assert.False(t, ok) 118 assert.Equal(t, "", got) 119 ok = trySetIDOnEntity(s, exp) 120 assert.False(t, ok) 121 } 122 123 { 124 // verify doesn't get/set if ID is not string 125 exp := "new" 126 s := WithIntID{ID: 5} 127 got, ok := tryGetIDFromInstance(s) 128 assert.False(t, ok) 129 assert.Equal(t, "", got) 130 131 ok = trySetIDOnEntity(s, exp) 132 assert.False(t, ok) 133 } 134 }