unmarshaler_test.go 80 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664
  1. package mapping
  2. import (
  3. "encoding/json"
  4. "fmt"
  5. "os"
  6. "strconv"
  7. "strings"
  8. "testing"
  9. "time"
  10. "unicode"
  11. "github.com/google/uuid"
  12. "github.com/stretchr/testify/assert"
  13. "github.com/zeromicro/go-zero/core/stringx"
  14. )
  15. // because json.Number doesn't support strconv.ParseUint(...),
  16. // so we only can test to 62 bits.
  17. const maxUintBitsToTest = 62
  18. func TestUnmarshalWithFullNameNotStruct(t *testing.T) {
  19. var s map[string]interface{}
  20. content := []byte(`{"name":"xiaoming"}`)
  21. err := UnmarshalJsonBytes(content, &s)
  22. assert.Equal(t, errValueNotStruct, err)
  23. }
  24. func TestUnmarshalWithoutTagName(t *testing.T) {
  25. type inner struct {
  26. Optional bool `key:",optional"`
  27. }
  28. m := map[string]interface{}{
  29. "Optional": true,
  30. }
  31. var in inner
  32. assert.Nil(t, UnmarshalKey(m, &in))
  33. assert.True(t, in.Optional)
  34. }
  35. func TestUnmarshalWithoutTagNameWithCanonicalKey(t *testing.T) {
  36. type inner struct {
  37. Name string `key:"name"`
  38. }
  39. m := map[string]interface{}{
  40. "Name": "go-zero",
  41. }
  42. var in inner
  43. unmarshaler := NewUnmarshaler(defaultKeyName, WithCanonicalKeyFunc(func(s string) string {
  44. first := true
  45. return strings.Map(func(r rune) rune {
  46. if first {
  47. first = false
  48. return unicode.ToTitle(r)
  49. }
  50. return r
  51. }, s)
  52. }))
  53. assert.Nil(t, unmarshaler.Unmarshal(m, &in))
  54. assert.Equal(t, "go-zero", in.Name)
  55. }
  56. func TestUnmarshalBool(t *testing.T) {
  57. type inner struct {
  58. True bool `key:"yes"`
  59. False bool `key:"no"`
  60. TrueFromOne bool `key:"yesone,string"`
  61. FalseFromZero bool `key:"nozero,string"`
  62. TrueFromTrue bool `key:"yestrue,string"`
  63. FalseFromFalse bool `key:"nofalse,string"`
  64. DefaultTrue bool `key:"defaulttrue,default=1"`
  65. Optional bool `key:"optional,optional"`
  66. }
  67. m := map[string]interface{}{
  68. "yes": true,
  69. "no": false,
  70. "yesone": "1",
  71. "nozero": "0",
  72. "yestrue": "true",
  73. "nofalse": "false",
  74. }
  75. var in inner
  76. ast := assert.New(t)
  77. ast.Nil(UnmarshalKey(m, &in))
  78. ast.True(in.True)
  79. ast.False(in.False)
  80. ast.True(in.TrueFromOne)
  81. ast.False(in.FalseFromZero)
  82. ast.True(in.TrueFromTrue)
  83. ast.False(in.FalseFromFalse)
  84. ast.True(in.DefaultTrue)
  85. }
  86. func TestUnmarshalDuration(t *testing.T) {
  87. type inner struct {
  88. Duration time.Duration `key:"duration"`
  89. LessDuration time.Duration `key:"less"`
  90. MoreDuration time.Duration `key:"more"`
  91. }
  92. m := map[string]interface{}{
  93. "duration": "5s",
  94. "less": "100ms",
  95. "more": "24h",
  96. }
  97. var in inner
  98. assert.Nil(t, UnmarshalKey(m, &in))
  99. assert.Equal(t, time.Second*5, in.Duration)
  100. assert.Equal(t, time.Millisecond*100, in.LessDuration)
  101. assert.Equal(t, time.Hour*24, in.MoreDuration)
  102. }
  103. func TestUnmarshalDurationDefault(t *testing.T) {
  104. type inner struct {
  105. Int int `key:"int"`
  106. Duration time.Duration `key:"duration,default=5s"`
  107. }
  108. m := map[string]interface{}{
  109. "int": 5,
  110. }
  111. var in inner
  112. assert.Nil(t, UnmarshalKey(m, &in))
  113. assert.Equal(t, 5, in.Int)
  114. assert.Equal(t, time.Second*5, in.Duration)
  115. }
  116. func TestUnmarshalDurationPtr(t *testing.T) {
  117. type inner struct {
  118. Duration *time.Duration `key:"duration"`
  119. }
  120. m := map[string]interface{}{
  121. "duration": "5s",
  122. }
  123. var in inner
  124. assert.Nil(t, UnmarshalKey(m, &in))
  125. assert.Equal(t, time.Second*5, *in.Duration)
  126. }
  127. func TestUnmarshalDurationPtrDefault(t *testing.T) {
  128. type inner struct {
  129. Int int `key:"int"`
  130. Value *int `key:",default=5"`
  131. Duration *time.Duration `key:"duration,default=5s"`
  132. }
  133. m := map[string]interface{}{
  134. "int": 5,
  135. }
  136. var in inner
  137. assert.Nil(t, UnmarshalKey(m, &in))
  138. assert.Equal(t, 5, in.Int)
  139. assert.Equal(t, 5, *in.Value)
  140. assert.Equal(t, time.Second*5, *in.Duration)
  141. }
  142. func TestUnmarshalInt(t *testing.T) {
  143. type inner struct {
  144. Int int `key:"int"`
  145. IntFromStr int `key:"intstr,string"`
  146. Int8 int8 `key:"int8"`
  147. Int8FromStr int8 `key:"int8str,string"`
  148. Int16 int16 `key:"int16"`
  149. Int16FromStr int16 `key:"int16str,string"`
  150. Int32 int32 `key:"int32"`
  151. Int32FromStr int32 `key:"int32str,string"`
  152. Int64 int64 `key:"int64"`
  153. Int64FromStr int64 `key:"int64str,string"`
  154. DefaultInt int64 `key:"defaultint,default=11"`
  155. Optional int `key:"optional,optional"`
  156. }
  157. m := map[string]interface{}{
  158. "int": 1,
  159. "intstr": "2",
  160. "int8": int8(3),
  161. "int8str": "4",
  162. "int16": int16(5),
  163. "int16str": "6",
  164. "int32": int32(7),
  165. "int32str": "8",
  166. "int64": int64(9),
  167. "int64str": "10",
  168. }
  169. var in inner
  170. ast := assert.New(t)
  171. ast.Nil(UnmarshalKey(m, &in))
  172. ast.Equal(1, in.Int)
  173. ast.Equal(2, in.IntFromStr)
  174. ast.Equal(int8(3), in.Int8)
  175. ast.Equal(int8(4), in.Int8FromStr)
  176. ast.Equal(int16(5), in.Int16)
  177. ast.Equal(int16(6), in.Int16FromStr)
  178. ast.Equal(int32(7), in.Int32)
  179. ast.Equal(int32(8), in.Int32FromStr)
  180. ast.Equal(int64(9), in.Int64)
  181. ast.Equal(int64(10), in.Int64FromStr)
  182. ast.Equal(int64(11), in.DefaultInt)
  183. }
  184. func TestUnmarshalIntPtr(t *testing.T) {
  185. type inner struct {
  186. Int *int `key:"int"`
  187. }
  188. m := map[string]interface{}{
  189. "int": 1,
  190. }
  191. var in inner
  192. assert.Nil(t, UnmarshalKey(m, &in))
  193. assert.NotNil(t, in.Int)
  194. assert.Equal(t, 1, *in.Int)
  195. }
  196. func TestUnmarshalIntWithDefault(t *testing.T) {
  197. type inner struct {
  198. Int int `key:"int,default=5"`
  199. }
  200. m := map[string]interface{}{
  201. "int": 1,
  202. }
  203. var in inner
  204. assert.Nil(t, UnmarshalKey(m, &in))
  205. assert.Equal(t, 1, in.Int)
  206. }
  207. func TestUnmarshalBoolSliceRequired(t *testing.T) {
  208. type inner struct {
  209. Bools []bool `key:"bools"`
  210. }
  211. var in inner
  212. assert.NotNil(t, UnmarshalKey(map[string]interface{}{}, &in))
  213. }
  214. func TestUnmarshalBoolSliceNil(t *testing.T) {
  215. type inner struct {
  216. Bools []bool `key:"bools,optional"`
  217. }
  218. var in inner
  219. assert.Nil(t, UnmarshalKey(map[string]interface{}{}, &in))
  220. assert.Nil(t, in.Bools)
  221. }
  222. func TestUnmarshalBoolSliceNilExplicit(t *testing.T) {
  223. type inner struct {
  224. Bools []bool `key:"bools,optional"`
  225. }
  226. var in inner
  227. assert.Nil(t, UnmarshalKey(map[string]interface{}{
  228. "bools": nil,
  229. }, &in))
  230. assert.Nil(t, in.Bools)
  231. }
  232. func TestUnmarshalBoolSliceEmpty(t *testing.T) {
  233. type inner struct {
  234. Bools []bool `key:"bools,optional"`
  235. }
  236. var in inner
  237. assert.Nil(t, UnmarshalKey(map[string]interface{}{
  238. "bools": []bool{},
  239. }, &in))
  240. assert.Empty(t, in.Bools)
  241. }
  242. func TestUnmarshalBoolSliceWithDefault(t *testing.T) {
  243. type inner struct {
  244. Bools []bool `key:"bools,default=[true,false]"`
  245. }
  246. var in inner
  247. assert.Nil(t, UnmarshalKey(nil, &in))
  248. assert.ElementsMatch(t, []bool{true, false}, in.Bools)
  249. }
  250. func TestUnmarshalIntSliceWithDefault(t *testing.T) {
  251. type inner struct {
  252. Ints []int `key:"ints,default=[1,2,3]"`
  253. }
  254. var in inner
  255. assert.Nil(t, UnmarshalKey(nil, &in))
  256. assert.ElementsMatch(t, []int{1, 2, 3}, in.Ints)
  257. }
  258. func TestUnmarshalIntSliceWithDefaultHasSpaces(t *testing.T) {
  259. type inner struct {
  260. Ints []int `key:"ints,default=[1, 2, 3]"`
  261. }
  262. var in inner
  263. assert.Nil(t, UnmarshalKey(nil, &in))
  264. assert.ElementsMatch(t, []int{1, 2, 3}, in.Ints)
  265. }
  266. func TestUnmarshalFloatSliceWithDefault(t *testing.T) {
  267. type inner struct {
  268. Floats []float32 `key:"floats,default=[1.1,2.2,3.3]"`
  269. }
  270. var in inner
  271. assert.Nil(t, UnmarshalKey(nil, &in))
  272. assert.ElementsMatch(t, []float32{1.1, 2.2, 3.3}, in.Floats)
  273. }
  274. func TestUnmarshalStringSliceWithDefault(t *testing.T) {
  275. type inner struct {
  276. Strs []string `key:"strs,default=[foo,bar,woo]"`
  277. }
  278. var in inner
  279. assert.Nil(t, UnmarshalKey(nil, &in))
  280. assert.ElementsMatch(t, []string{"foo", "bar", "woo"}, in.Strs)
  281. }
  282. func TestUnmarshalStringSliceWithDefaultHasSpaces(t *testing.T) {
  283. type inner struct {
  284. Strs []string `key:"strs,default=[foo, bar, woo]"`
  285. }
  286. var in inner
  287. assert.Nil(t, UnmarshalKey(nil, &in))
  288. assert.ElementsMatch(t, []string{"foo", "bar", "woo"}, in.Strs)
  289. }
  290. func TestUnmarshalUint(t *testing.T) {
  291. type inner struct {
  292. Uint uint `key:"uint"`
  293. UintFromStr uint `key:"uintstr,string"`
  294. Uint8 uint8 `key:"uint8"`
  295. Uint8FromStr uint8 `key:"uint8str,string"`
  296. Uint16 uint16 `key:"uint16"`
  297. Uint16FromStr uint16 `key:"uint16str,string"`
  298. Uint32 uint32 `key:"uint32"`
  299. Uint32FromStr uint32 `key:"uint32str,string"`
  300. Uint64 uint64 `key:"uint64"`
  301. Uint64FromStr uint64 `key:"uint64str,string"`
  302. DefaultUint uint `key:"defaultuint,default=11"`
  303. Optional uint `key:"optional,optional"`
  304. }
  305. m := map[string]interface{}{
  306. "uint": uint(1),
  307. "uintstr": "2",
  308. "uint8": uint8(3),
  309. "uint8str": "4",
  310. "uint16": uint16(5),
  311. "uint16str": "6",
  312. "uint32": uint32(7),
  313. "uint32str": "8",
  314. "uint64": uint64(9),
  315. "uint64str": "10",
  316. }
  317. var in inner
  318. ast := assert.New(t)
  319. ast.Nil(UnmarshalKey(m, &in))
  320. ast.Equal(uint(1), in.Uint)
  321. ast.Equal(uint(2), in.UintFromStr)
  322. ast.Equal(uint8(3), in.Uint8)
  323. ast.Equal(uint8(4), in.Uint8FromStr)
  324. ast.Equal(uint16(5), in.Uint16)
  325. ast.Equal(uint16(6), in.Uint16FromStr)
  326. ast.Equal(uint32(7), in.Uint32)
  327. ast.Equal(uint32(8), in.Uint32FromStr)
  328. ast.Equal(uint64(9), in.Uint64)
  329. ast.Equal(uint64(10), in.Uint64FromStr)
  330. ast.Equal(uint(11), in.DefaultUint)
  331. }
  332. func TestUnmarshalFloat(t *testing.T) {
  333. type inner struct {
  334. Float32 float32 `key:"float32"`
  335. Float32Str float32 `key:"float32str,string"`
  336. Float64 float64 `key:"float64"`
  337. Float64Str float64 `key:"float64str,string"`
  338. DefaultFloat float32 `key:"defaultfloat,default=5.5"`
  339. Optional float32 `key:",optional"`
  340. }
  341. m := map[string]interface{}{
  342. "float32": float32(1.5),
  343. "float32str": "2.5",
  344. "float64": float64(3.5),
  345. "float64str": "4.5",
  346. }
  347. var in inner
  348. ast := assert.New(t)
  349. ast.Nil(UnmarshalKey(m, &in))
  350. ast.Equal(float32(1.5), in.Float32)
  351. ast.Equal(float32(2.5), in.Float32Str)
  352. ast.Equal(3.5, in.Float64)
  353. ast.Equal(4.5, in.Float64Str)
  354. ast.Equal(float32(5.5), in.DefaultFloat)
  355. }
  356. func TestUnmarshalInt64Slice(t *testing.T) {
  357. var v struct {
  358. Ages []int64 `key:"ages"`
  359. Slice []int64 `key:"slice"`
  360. }
  361. m := map[string]interface{}{
  362. "ages": []int64{1, 2},
  363. "slice": []interface{}{},
  364. }
  365. ast := assert.New(t)
  366. ast.Nil(UnmarshalKey(m, &v))
  367. ast.ElementsMatch([]int64{1, 2}, v.Ages)
  368. ast.Equal([]int64{}, v.Slice)
  369. }
  370. func TestUnmarshalIntSlice(t *testing.T) {
  371. var v struct {
  372. Ages []int `key:"ages"`
  373. Slice []int `key:"slice"`
  374. }
  375. m := map[string]interface{}{
  376. "ages": []int{1, 2},
  377. "slice": []interface{}{},
  378. }
  379. ast := assert.New(t)
  380. ast.Nil(UnmarshalKey(m, &v))
  381. ast.ElementsMatch([]int{1, 2}, v.Ages)
  382. ast.Equal([]int{}, v.Slice)
  383. }
  384. func TestUnmarshalString(t *testing.T) {
  385. type inner struct {
  386. Name string `key:"name"`
  387. NameStr string `key:"namestr,string"`
  388. NotPresent string `key:",optional"`
  389. NotPresentWithTag string `key:"notpresent,optional"`
  390. DefaultString string `key:"defaultstring,default=hello"`
  391. Optional string `key:",optional"`
  392. }
  393. m := map[string]interface{}{
  394. "name": "kevin",
  395. "namestr": "namewithstring",
  396. }
  397. var in inner
  398. ast := assert.New(t)
  399. ast.Nil(UnmarshalKey(m, &in))
  400. ast.Equal("kevin", in.Name)
  401. ast.Equal("namewithstring", in.NameStr)
  402. ast.Empty(in.NotPresent)
  403. ast.Empty(in.NotPresentWithTag)
  404. ast.Equal("hello", in.DefaultString)
  405. }
  406. func TestUnmarshalStringWithMissing(t *testing.T) {
  407. type inner struct {
  408. Name string `key:"name"`
  409. }
  410. m := map[string]interface{}{}
  411. var in inner
  412. assert.NotNil(t, UnmarshalKey(m, &in))
  413. }
  414. func TestUnmarshalStringSliceFromString(t *testing.T) {
  415. var v struct {
  416. Names []string `key:"names"`
  417. }
  418. m := map[string]interface{}{
  419. "names": `["first", "second"]`,
  420. }
  421. ast := assert.New(t)
  422. ast.Nil(UnmarshalKey(m, &v))
  423. ast.Equal(2, len(v.Names))
  424. ast.Equal("first", v.Names[0])
  425. ast.Equal("second", v.Names[1])
  426. }
  427. func TestUnmarshalIntSliceFromString(t *testing.T) {
  428. var v struct {
  429. Values []int `key:"values"`
  430. }
  431. m := map[string]interface{}{
  432. "values": `[1, 2]`,
  433. }
  434. ast := assert.New(t)
  435. ast.Nil(UnmarshalKey(m, &v))
  436. ast.Equal(2, len(v.Values))
  437. ast.Equal(1, v.Values[0])
  438. ast.Equal(2, v.Values[1])
  439. }
  440. func TestUnmarshalIntMapFromString(t *testing.T) {
  441. var v struct {
  442. Sort map[string]int `key:"sort"`
  443. }
  444. m := map[string]interface{}{
  445. "sort": `{"value":12345,"zeroVal":0,"nullVal":null}`,
  446. }
  447. ast := assert.New(t)
  448. ast.Nil(UnmarshalKey(m, &v))
  449. ast.Equal(3, len(v.Sort))
  450. ast.Equal(12345, v.Sort["value"])
  451. ast.Equal(0, v.Sort["zeroVal"])
  452. ast.Equal(0, v.Sort["nullVal"])
  453. }
  454. func TestUnmarshalBoolMapFromString(t *testing.T) {
  455. var v struct {
  456. Sort map[string]bool `key:"sort"`
  457. }
  458. m := map[string]interface{}{
  459. "sort": `{"value":true,"zeroVal":false,"nullVal":null}`,
  460. }
  461. ast := assert.New(t)
  462. ast.Nil(UnmarshalKey(m, &v))
  463. ast.Equal(3, len(v.Sort))
  464. ast.Equal(true, v.Sort["value"])
  465. ast.Equal(false, v.Sort["zeroVal"])
  466. ast.Equal(false, v.Sort["nullVal"])
  467. }
  468. type CustomStringer string
  469. type UnsupportedStringer string
  470. func (c CustomStringer) String() string {
  471. return fmt.Sprintf("{%s}", string(c))
  472. }
  473. func TestUnmarshalStringMapFromStringer(t *testing.T) {
  474. var v struct {
  475. Sort map[string]string `key:"sort"`
  476. }
  477. m := map[string]interface{}{
  478. "sort": CustomStringer(`"value":"ascend","emptyStr":""`),
  479. }
  480. ast := assert.New(t)
  481. ast.Nil(UnmarshalKey(m, &v))
  482. ast.Equal(2, len(v.Sort))
  483. ast.Equal("ascend", v.Sort["value"])
  484. ast.Equal("", v.Sort["emptyStr"])
  485. }
  486. func TestUnmarshalStringMapFromUnsupportedType(t *testing.T) {
  487. var v struct {
  488. Sort map[string]string `key:"sort"`
  489. }
  490. m := map[string]interface{}{
  491. "sort": UnsupportedStringer(`{"value":"ascend","emptyStr":""}`),
  492. }
  493. ast := assert.New(t)
  494. ast.NotNil(UnmarshalKey(m, &v))
  495. }
  496. func TestUnmarshalStringMapFromNotSettableValue(t *testing.T) {
  497. var v struct {
  498. sort map[string]string `key:"sort"`
  499. psort *map[string]string `key:"psort"`
  500. }
  501. m := map[string]interface{}{
  502. "sort": `{"value":"ascend","emptyStr":""}`,
  503. "psort": `{"value":"ascend","emptyStr":""}`,
  504. }
  505. ast := assert.New(t)
  506. ast.NotNil(UnmarshalKey(m, &v))
  507. }
  508. func TestUnmarshalStringMapFromString(t *testing.T) {
  509. var v struct {
  510. Sort map[string]string `key:"sort"`
  511. }
  512. m := map[string]interface{}{
  513. "sort": `{"value":"ascend","emptyStr":""}`,
  514. }
  515. ast := assert.New(t)
  516. ast.Nil(UnmarshalKey(m, &v))
  517. ast.Equal(2, len(v.Sort))
  518. ast.Equal("ascend", v.Sort["value"])
  519. ast.Equal("", v.Sort["emptyStr"])
  520. }
  521. func TestUnmarshalStructMapFromString(t *testing.T) {
  522. var v struct {
  523. Filter map[string]struct {
  524. Field1 bool `json:"field1"`
  525. Field2 int64 `json:"field2,string"`
  526. Field3 string `json:"field3"`
  527. Field4 *string `json:"field4"`
  528. Field5 []string `json:"field5"`
  529. } `key:"filter"`
  530. }
  531. m := map[string]interface{}{
  532. "filter": `{"obj":{"field1":true,"field2":"1573570455447539712","field3":"this is a string",
  533. "field4":"this is a string pointer","field5":["str1","str2"]}}`,
  534. }
  535. ast := assert.New(t)
  536. ast.Nil(UnmarshalKey(m, &v))
  537. ast.Equal(1, len(v.Filter))
  538. ast.NotNil(v.Filter["obj"])
  539. ast.Equal(true, v.Filter["obj"].Field1)
  540. ast.Equal(int64(1573570455447539712), v.Filter["obj"].Field2)
  541. ast.Equal("this is a string", v.Filter["obj"].Field3)
  542. ast.Equal("this is a string pointer", *v.Filter["obj"].Field4)
  543. ast.ElementsMatch([]string{"str1", "str2"}, v.Filter["obj"].Field5)
  544. }
  545. func TestUnmarshalStringSliceMapFromString(t *testing.T) {
  546. var v struct {
  547. Filter map[string][]string `key:"filter"`
  548. }
  549. m := map[string]interface{}{
  550. "filter": `{"assignType":null,"status":["process","comment"],"rate":[]}`,
  551. }
  552. ast := assert.New(t)
  553. ast.Nil(UnmarshalKey(m, &v))
  554. ast.Equal(3, len(v.Filter))
  555. ast.Equal([]string(nil), v.Filter["assignType"])
  556. ast.Equal(2, len(v.Filter["status"]))
  557. ast.Equal("process", v.Filter["status"][0])
  558. ast.Equal("comment", v.Filter["status"][1])
  559. ast.Equal(0, len(v.Filter["rate"]))
  560. }
  561. func TestUnmarshalStruct(t *testing.T) {
  562. type address struct {
  563. City string `key:"city"`
  564. ZipCode int `key:"zipcode,string"`
  565. DefaultString string `key:"defaultstring,default=hello"`
  566. Optional string `key:",optional"`
  567. }
  568. type inner struct {
  569. Name string `key:"name"`
  570. Address address `key:"address"`
  571. }
  572. m := map[string]interface{}{
  573. "name": "kevin",
  574. "address": map[string]interface{}{
  575. "city": "shanghai",
  576. "zipcode": "200000",
  577. },
  578. }
  579. var in inner
  580. ast := assert.New(t)
  581. ast.Nil(UnmarshalKey(m, &in))
  582. ast.Equal("kevin", in.Name)
  583. ast.Equal("shanghai", in.Address.City)
  584. ast.Equal(200000, in.Address.ZipCode)
  585. ast.Equal("hello", in.Address.DefaultString)
  586. }
  587. func TestUnmarshalStructOptionalDepends(t *testing.T) {
  588. type address struct {
  589. City string `key:"city"`
  590. Optional string `key:",optional"`
  591. OptionalDepends string `key:",optional=Optional"`
  592. }
  593. type inner struct {
  594. Name string `key:"name"`
  595. Address address `key:"address"`
  596. }
  597. tests := []struct {
  598. input map[string]string
  599. pass bool
  600. }{
  601. {
  602. pass: true,
  603. },
  604. {
  605. input: map[string]string{
  606. "OptionalDepends": "b",
  607. },
  608. pass: false,
  609. },
  610. {
  611. input: map[string]string{
  612. "Optional": "a",
  613. },
  614. pass: false,
  615. },
  616. {
  617. input: map[string]string{
  618. "Optional": "a",
  619. "OptionalDepends": "b",
  620. },
  621. pass: true,
  622. },
  623. }
  624. for _, test := range tests {
  625. t.Run(stringx.Rand(), func(t *testing.T) {
  626. m := map[string]interface{}{
  627. "name": "kevin",
  628. "address": map[string]interface{}{
  629. "city": "shanghai",
  630. },
  631. }
  632. for k, v := range test.input {
  633. m["address"].(map[string]interface{})[k] = v
  634. }
  635. var in inner
  636. ast := assert.New(t)
  637. if test.pass {
  638. ast.Nil(UnmarshalKey(m, &in))
  639. ast.Equal("kevin", in.Name)
  640. ast.Equal("shanghai", in.Address.City)
  641. ast.Equal(test.input["Optional"], in.Address.Optional)
  642. ast.Equal(test.input["OptionalDepends"], in.Address.OptionalDepends)
  643. } else {
  644. ast.NotNil(UnmarshalKey(m, &in))
  645. }
  646. })
  647. }
  648. }
  649. func TestUnmarshalStructOptionalDependsNot(t *testing.T) {
  650. type address struct {
  651. City string `key:"city"`
  652. Optional string `key:",optional"`
  653. OptionalDepends string `key:",optional=!Optional"`
  654. }
  655. type inner struct {
  656. Name string `key:"name"`
  657. Address address `key:"address"`
  658. }
  659. tests := []struct {
  660. input map[string]string
  661. pass bool
  662. }{
  663. {
  664. input: map[string]string{},
  665. pass: false,
  666. },
  667. {
  668. input: map[string]string{
  669. "Optional": "a",
  670. "OptionalDepends": "b",
  671. },
  672. pass: false,
  673. },
  674. {
  675. input: map[string]string{
  676. "Optional": "a",
  677. },
  678. pass: true,
  679. },
  680. {
  681. input: map[string]string{
  682. "OptionalDepends": "b",
  683. },
  684. pass: true,
  685. },
  686. }
  687. for _, test := range tests {
  688. t.Run(stringx.Rand(), func(t *testing.T) {
  689. m := map[string]interface{}{
  690. "name": "kevin",
  691. "address": map[string]interface{}{
  692. "city": "shanghai",
  693. },
  694. }
  695. for k, v := range test.input {
  696. m["address"].(map[string]interface{})[k] = v
  697. }
  698. var in inner
  699. ast := assert.New(t)
  700. if test.pass {
  701. ast.Nil(UnmarshalKey(m, &in))
  702. ast.Equal("kevin", in.Name)
  703. ast.Equal("shanghai", in.Address.City)
  704. ast.Equal(test.input["Optional"], in.Address.Optional)
  705. ast.Equal(test.input["OptionalDepends"], in.Address.OptionalDepends)
  706. } else {
  707. ast.NotNil(UnmarshalKey(m, &in))
  708. }
  709. })
  710. }
  711. }
  712. func TestUnmarshalStructOptionalDependsNotErrorDetails(t *testing.T) {
  713. type address struct {
  714. Optional string `key:",optional"`
  715. OptionalDepends string `key:",optional=!Optional"`
  716. }
  717. type inner struct {
  718. Name string `key:"name"`
  719. Address address `key:"address"`
  720. }
  721. m := map[string]interface{}{
  722. "name": "kevin",
  723. }
  724. var in inner
  725. err := UnmarshalKey(m, &in)
  726. assert.NotNil(t, err)
  727. }
  728. func TestUnmarshalStructOptionalDependsNotNested(t *testing.T) {
  729. type address struct {
  730. Optional string `key:",optional"`
  731. OptionalDepends string `key:",optional=!Optional"`
  732. }
  733. type combo struct {
  734. Name string `key:"name,optional"`
  735. Address address `key:"address"`
  736. }
  737. type inner struct {
  738. Name string `key:"name"`
  739. Combo combo `key:"combo"`
  740. }
  741. m := map[string]interface{}{
  742. "name": "kevin",
  743. }
  744. var in inner
  745. err := UnmarshalKey(m, &in)
  746. assert.NotNil(t, err)
  747. }
  748. func TestUnmarshalStructOptionalNestedDifferentKey(t *testing.T) {
  749. type address struct {
  750. Optional string `dkey:",optional"`
  751. OptionalDepends string `key:",optional"`
  752. }
  753. type combo struct {
  754. Name string `key:"name,optional"`
  755. Address address `key:"address"`
  756. }
  757. type inner struct {
  758. Name string `key:"name"`
  759. Combo combo `key:"combo"`
  760. }
  761. m := map[string]interface{}{
  762. "name": "kevin",
  763. }
  764. var in inner
  765. assert.NotNil(t, UnmarshalKey(m, &in))
  766. }
  767. func TestUnmarshalStructOptionalDependsNotEnoughValue(t *testing.T) {
  768. type address struct {
  769. Optional string `key:",optional"`
  770. OptionalDepends string `key:",optional=!"`
  771. }
  772. type inner struct {
  773. Name string `key:"name"`
  774. Address address `key:"address"`
  775. }
  776. m := map[string]interface{}{
  777. "name": "kevin",
  778. "address": map[string]interface{}{},
  779. }
  780. var in inner
  781. err := UnmarshalKey(m, &in)
  782. assert.NotNil(t, err)
  783. }
  784. func TestUnmarshalAnonymousStructOptionalDepends(t *testing.T) {
  785. type AnonAddress struct {
  786. City string `key:"city"`
  787. Optional string `key:",optional"`
  788. OptionalDepends string `key:",optional=Optional"`
  789. }
  790. type inner struct {
  791. Name string `key:"name"`
  792. AnonAddress
  793. }
  794. tests := []struct {
  795. input map[string]string
  796. pass bool
  797. }{
  798. {
  799. pass: true,
  800. },
  801. {
  802. input: map[string]string{
  803. "OptionalDepends": "b",
  804. },
  805. pass: false,
  806. },
  807. {
  808. input: map[string]string{
  809. "Optional": "a",
  810. },
  811. pass: false,
  812. },
  813. {
  814. input: map[string]string{
  815. "Optional": "a",
  816. "OptionalDepends": "b",
  817. },
  818. pass: true,
  819. },
  820. }
  821. for _, test := range tests {
  822. t.Run(stringx.Rand(), func(t *testing.T) {
  823. m := map[string]interface{}{
  824. "name": "kevin",
  825. "city": "shanghai",
  826. }
  827. for k, v := range test.input {
  828. m[k] = v
  829. }
  830. var in inner
  831. ast := assert.New(t)
  832. if test.pass {
  833. ast.Nil(UnmarshalKey(m, &in))
  834. ast.Equal("kevin", in.Name)
  835. ast.Equal("shanghai", in.City)
  836. ast.Equal(test.input["Optional"], in.Optional)
  837. ast.Equal(test.input["OptionalDepends"], in.OptionalDepends)
  838. } else {
  839. ast.NotNil(UnmarshalKey(m, &in))
  840. }
  841. })
  842. }
  843. }
  844. func TestUnmarshalStructPtr(t *testing.T) {
  845. type address struct {
  846. City string `key:"city"`
  847. ZipCode int `key:"zipcode,string"`
  848. DefaultString string `key:"defaultstring,default=hello"`
  849. Optional string `key:",optional"`
  850. }
  851. type inner struct {
  852. Name string `key:"name"`
  853. Address *address `key:"address"`
  854. }
  855. m := map[string]interface{}{
  856. "name": "kevin",
  857. "address": map[string]interface{}{
  858. "city": "shanghai",
  859. "zipcode": "200000",
  860. },
  861. }
  862. var in inner
  863. ast := assert.New(t)
  864. ast.Nil(UnmarshalKey(m, &in))
  865. ast.Equal("kevin", in.Name)
  866. ast.Equal("shanghai", in.Address.City)
  867. ast.Equal(200000, in.Address.ZipCode)
  868. ast.Equal("hello", in.Address.DefaultString)
  869. }
  870. func TestUnmarshalWithStringIgnored(t *testing.T) {
  871. type inner struct {
  872. True bool `key:"yes"`
  873. False bool `key:"no"`
  874. Int int `key:"int"`
  875. Int8 int8 `key:"int8"`
  876. Int16 int16 `key:"int16"`
  877. Int32 int32 `key:"int32"`
  878. Int64 int64 `key:"int64"`
  879. Uint uint `key:"uint"`
  880. Uint8 uint8 `key:"uint8"`
  881. Uint16 uint16 `key:"uint16"`
  882. Uint32 uint32 `key:"uint32"`
  883. Uint64 uint64 `key:"uint64"`
  884. Float32 float32 `key:"float32"`
  885. Float64 float64 `key:"float64"`
  886. }
  887. m := map[string]interface{}{
  888. "yes": "1",
  889. "no": "0",
  890. "int": "1",
  891. "int8": "3",
  892. "int16": "5",
  893. "int32": "7",
  894. "int64": "9",
  895. "uint": "1",
  896. "uint8": "3",
  897. "uint16": "5",
  898. "uint32": "7",
  899. "uint64": "9",
  900. "float32": "1.5",
  901. "float64": "3.5",
  902. }
  903. var in inner
  904. um := NewUnmarshaler("key", WithStringValues())
  905. ast := assert.New(t)
  906. ast.Nil(um.Unmarshal(m, &in))
  907. ast.True(in.True)
  908. ast.False(in.False)
  909. ast.Equal(1, in.Int)
  910. ast.Equal(int8(3), in.Int8)
  911. ast.Equal(int16(5), in.Int16)
  912. ast.Equal(int32(7), in.Int32)
  913. ast.Equal(int64(9), in.Int64)
  914. ast.Equal(uint(1), in.Uint)
  915. ast.Equal(uint8(3), in.Uint8)
  916. ast.Equal(uint16(5), in.Uint16)
  917. ast.Equal(uint32(7), in.Uint32)
  918. ast.Equal(uint64(9), in.Uint64)
  919. ast.Equal(float32(1.5), in.Float32)
  920. ast.Equal(3.5, in.Float64)
  921. }
  922. func TestUnmarshalJsonNumberInt64(t *testing.T) {
  923. for i := 0; i <= maxUintBitsToTest; i++ {
  924. var intValue int64 = 1 << uint(i)
  925. strValue := strconv.FormatInt(intValue, 10)
  926. number := json.Number(strValue)
  927. m := map[string]interface{}{
  928. "ID": number,
  929. }
  930. var v struct {
  931. ID int64
  932. }
  933. assert.Nil(t, UnmarshalKey(m, &v))
  934. assert.Equal(t, intValue, v.ID)
  935. }
  936. }
  937. func TestUnmarshalJsonNumberUint64(t *testing.T) {
  938. for i := 0; i <= maxUintBitsToTest; i++ {
  939. var intValue uint64 = 1 << uint(i)
  940. strValue := strconv.FormatUint(intValue, 10)
  941. number := json.Number(strValue)
  942. m := map[string]interface{}{
  943. "ID": number,
  944. }
  945. var v struct {
  946. ID uint64
  947. }
  948. assert.Nil(t, UnmarshalKey(m, &v))
  949. assert.Equal(t, intValue, v.ID)
  950. }
  951. }
  952. func TestUnmarshalJsonNumberUint64Ptr(t *testing.T) {
  953. for i := 0; i <= maxUintBitsToTest; i++ {
  954. var intValue uint64 = 1 << uint(i)
  955. strValue := strconv.FormatUint(intValue, 10)
  956. number := json.Number(strValue)
  957. m := map[string]interface{}{
  958. "ID": number,
  959. }
  960. var v struct {
  961. ID *uint64
  962. }
  963. ast := assert.New(t)
  964. ast.Nil(UnmarshalKey(m, &v))
  965. ast.NotNil(v.ID)
  966. ast.Equal(intValue, *v.ID)
  967. }
  968. }
  969. func TestUnmarshalMapOfInt(t *testing.T) {
  970. m := map[string]interface{}{
  971. "Ids": map[string]bool{"first": true},
  972. }
  973. var v struct {
  974. Ids map[string]bool
  975. }
  976. assert.Nil(t, UnmarshalKey(m, &v))
  977. assert.True(t, v.Ids["first"])
  978. }
  979. func TestUnmarshalMapOfStructError(t *testing.T) {
  980. m := map[string]interface{}{
  981. "Ids": map[string]interface{}{"first": "second"},
  982. }
  983. var v struct {
  984. Ids map[string]struct {
  985. Name string
  986. }
  987. }
  988. assert.NotNil(t, UnmarshalKey(m, &v))
  989. }
  990. func TestUnmarshalSlice(t *testing.T) {
  991. m := map[string]interface{}{
  992. "Ids": []interface{}{"first", "second"},
  993. }
  994. var v struct {
  995. Ids []string
  996. }
  997. ast := assert.New(t)
  998. ast.Nil(UnmarshalKey(m, &v))
  999. ast.Equal(2, len(v.Ids))
  1000. ast.Equal("first", v.Ids[0])
  1001. ast.Equal("second", v.Ids[1])
  1002. }
  1003. func TestUnmarshalSliceOfStruct(t *testing.T) {
  1004. m := map[string]interface{}{
  1005. "Ids": []map[string]interface{}{
  1006. {
  1007. "First": 1,
  1008. "Second": 2,
  1009. },
  1010. },
  1011. }
  1012. var v struct {
  1013. Ids []struct {
  1014. First int
  1015. Second int
  1016. }
  1017. }
  1018. ast := assert.New(t)
  1019. ast.Nil(UnmarshalKey(m, &v))
  1020. ast.Equal(1, len(v.Ids))
  1021. ast.Equal(1, v.Ids[0].First)
  1022. ast.Equal(2, v.Ids[0].Second)
  1023. }
  1024. func TestUnmarshalWithStringOptionsCorrect(t *testing.T) {
  1025. type inner struct {
  1026. Value string `key:"value,options=first|second"`
  1027. Foo string `key:"foo,options=[bar,baz]"`
  1028. Correct string `key:"correct,options=1|2"`
  1029. }
  1030. m := map[string]interface{}{
  1031. "value": "first",
  1032. "foo": "bar",
  1033. "correct": "2",
  1034. }
  1035. var in inner
  1036. ast := assert.New(t)
  1037. ast.Nil(UnmarshalKey(m, &in))
  1038. ast.Equal("first", in.Value)
  1039. ast.Equal("bar", in.Foo)
  1040. ast.Equal("2", in.Correct)
  1041. }
  1042. func TestUnmarshalOptionsOptional(t *testing.T) {
  1043. type inner struct {
  1044. Value string `key:"value,options=first|second,optional"`
  1045. OptionalValue string `key:"optional_value,options=first|second,optional"`
  1046. Foo string `key:"foo,options=[bar,baz]"`
  1047. Correct string `key:"correct,options=1|2"`
  1048. }
  1049. m := map[string]interface{}{
  1050. "value": "first",
  1051. "foo": "bar",
  1052. "correct": "2",
  1053. }
  1054. var in inner
  1055. ast := assert.New(t)
  1056. ast.Nil(UnmarshalKey(m, &in))
  1057. ast.Equal("first", in.Value)
  1058. ast.Equal("", in.OptionalValue)
  1059. ast.Equal("bar", in.Foo)
  1060. ast.Equal("2", in.Correct)
  1061. }
  1062. func TestUnmarshalOptionsOptionalWrongValue(t *testing.T) {
  1063. type inner struct {
  1064. Value string `key:"value,options=first|second,optional"`
  1065. OptionalValue string `key:"optional_value,options=first|second,optional"`
  1066. WrongValue string `key:"wrong_value,options=first|second,optional"`
  1067. }
  1068. m := map[string]interface{}{
  1069. "value": "first",
  1070. "wrong_value": "third",
  1071. }
  1072. var in inner
  1073. assert.NotNil(t, UnmarshalKey(m, &in))
  1074. }
  1075. func TestUnmarshalStringOptionsWithStringOptionsNotString(t *testing.T) {
  1076. type inner struct {
  1077. Value string `key:"value,options=first|second"`
  1078. Correct string `key:"correct,options=1|2"`
  1079. }
  1080. m := map[string]interface{}{
  1081. "value": "first",
  1082. "correct": 2,
  1083. }
  1084. var in inner
  1085. unmarshaler := NewUnmarshaler(defaultKeyName, WithStringValues())
  1086. ast := assert.New(t)
  1087. ast.NotNil(unmarshaler.Unmarshal(m, &in))
  1088. }
  1089. func TestUnmarshalStringOptionsWithStringOptions(t *testing.T) {
  1090. type inner struct {
  1091. Value string `key:"value,options=first|second"`
  1092. Correct string `key:"correct,options=1|2"`
  1093. }
  1094. m := map[string]interface{}{
  1095. "value": "first",
  1096. "correct": "2",
  1097. }
  1098. var in inner
  1099. unmarshaler := NewUnmarshaler(defaultKeyName, WithStringValues())
  1100. ast := assert.New(t)
  1101. ast.Nil(unmarshaler.Unmarshal(m, &in))
  1102. ast.Equal("first", in.Value)
  1103. ast.Equal("2", in.Correct)
  1104. }
  1105. func TestUnmarshalStringOptionsWithStringOptionsPtr(t *testing.T) {
  1106. type inner struct {
  1107. Value *string `key:"value,options=first|second"`
  1108. Correct *int `key:"correct,options=1|2"`
  1109. }
  1110. m := map[string]interface{}{
  1111. "value": "first",
  1112. "correct": "2",
  1113. }
  1114. var in inner
  1115. unmarshaler := NewUnmarshaler(defaultKeyName, WithStringValues())
  1116. ast := assert.New(t)
  1117. ast.Nil(unmarshaler.Unmarshal(m, &in))
  1118. ast.True(*in.Value == "first")
  1119. ast.True(*in.Correct == 2)
  1120. }
  1121. func TestUnmarshalStringOptionsWithStringOptionsIncorrect(t *testing.T) {
  1122. type inner struct {
  1123. Value string `key:"value,options=first|second"`
  1124. Correct string `key:"correct,options=1|2"`
  1125. }
  1126. m := map[string]interface{}{
  1127. "value": "third",
  1128. "correct": "2",
  1129. }
  1130. var in inner
  1131. unmarshaler := NewUnmarshaler(defaultKeyName, WithStringValues())
  1132. ast := assert.New(t)
  1133. ast.NotNil(unmarshaler.Unmarshal(m, &in))
  1134. }
  1135. func TestUnmarshalStringOptionsWithStringOptionsIncorrectGrouped(t *testing.T) {
  1136. type inner struct {
  1137. Value string `key:"value,options=[first,second]"`
  1138. Correct string `key:"correct,options=1|2"`
  1139. }
  1140. m := map[string]interface{}{
  1141. "value": "third",
  1142. "correct": "2",
  1143. }
  1144. var in inner
  1145. unmarshaler := NewUnmarshaler(defaultKeyName, WithStringValues())
  1146. ast := assert.New(t)
  1147. ast.NotNil(unmarshaler.Unmarshal(m, &in))
  1148. }
  1149. func TestUnmarshalWithStringOptionsIncorrect(t *testing.T) {
  1150. type inner struct {
  1151. Value string `key:"value,options=first|second"`
  1152. Incorrect string `key:"incorrect,options=1|2"`
  1153. }
  1154. m := map[string]interface{}{
  1155. "value": "first",
  1156. "incorrect": "3",
  1157. }
  1158. var in inner
  1159. assert.NotNil(t, UnmarshalKey(m, &in))
  1160. }
  1161. func TestUnmarshalWithIntOptionsCorrect(t *testing.T) {
  1162. type inner struct {
  1163. Value string `key:"value,options=first|second"`
  1164. Number int `key:"number,options=1|2"`
  1165. }
  1166. m := map[string]interface{}{
  1167. "value": "first",
  1168. "number": 2,
  1169. }
  1170. var in inner
  1171. ast := assert.New(t)
  1172. ast.Nil(UnmarshalKey(m, &in))
  1173. ast.Equal("first", in.Value)
  1174. ast.Equal(2, in.Number)
  1175. }
  1176. func TestUnmarshalWithIntOptionsCorrectPtr(t *testing.T) {
  1177. type inner struct {
  1178. Value *string `key:"value,options=first|second"`
  1179. Number *int `key:"number,options=1|2"`
  1180. }
  1181. m := map[string]interface{}{
  1182. "value": "first",
  1183. "number": 2,
  1184. }
  1185. var in inner
  1186. ast := assert.New(t)
  1187. ast.Nil(UnmarshalKey(m, &in))
  1188. ast.True(*in.Value == "first")
  1189. ast.True(*in.Number == 2)
  1190. }
  1191. func TestUnmarshalWithIntOptionsIncorrect(t *testing.T) {
  1192. type inner struct {
  1193. Value string `key:"value,options=first|second"`
  1194. Incorrect int `key:"incorrect,options=1|2"`
  1195. }
  1196. m := map[string]interface{}{
  1197. "value": "first",
  1198. "incorrect": 3,
  1199. }
  1200. var in inner
  1201. assert.NotNil(t, UnmarshalKey(m, &in))
  1202. }
  1203. func TestUnmarshalWithJsonNumberOptionsIncorrect(t *testing.T) {
  1204. type inner struct {
  1205. Value string `key:"value,options=first|second"`
  1206. Incorrect int `key:"incorrect,options=1|2"`
  1207. }
  1208. m := map[string]interface{}{
  1209. "value": "first",
  1210. "incorrect": json.Number("3"),
  1211. }
  1212. var in inner
  1213. assert.NotNil(t, UnmarshalKey(m, &in))
  1214. }
  1215. func TestUnmarshaler_UnmarshalIntOptions(t *testing.T) {
  1216. var val struct {
  1217. Sex int `json:"sex,options=0|1"`
  1218. }
  1219. input := []byte(`{"sex": 2}`)
  1220. assert.NotNil(t, UnmarshalJsonBytes(input, &val))
  1221. }
  1222. func TestUnmarshalWithUintOptionsCorrect(t *testing.T) {
  1223. type inner struct {
  1224. Value string `key:"value,options=first|second"`
  1225. Number uint `key:"number,options=1|2"`
  1226. }
  1227. m := map[string]interface{}{
  1228. "value": "first",
  1229. "number": uint(2),
  1230. }
  1231. var in inner
  1232. ast := assert.New(t)
  1233. ast.Nil(UnmarshalKey(m, &in))
  1234. ast.Equal("first", in.Value)
  1235. ast.Equal(uint(2), in.Number)
  1236. }
  1237. func TestUnmarshalWithUintOptionsIncorrect(t *testing.T) {
  1238. type inner struct {
  1239. Value string `key:"value,options=first|second"`
  1240. Incorrect uint `key:"incorrect,options=1|2"`
  1241. }
  1242. m := map[string]interface{}{
  1243. "value": "first",
  1244. "incorrect": uint(3),
  1245. }
  1246. var in inner
  1247. assert.NotNil(t, UnmarshalKey(m, &in))
  1248. }
  1249. func TestUnmarshalWithOptionsAndDefault(t *testing.T) {
  1250. type inner struct {
  1251. Value string `key:"value,options=first|second|third,default=second"`
  1252. }
  1253. m := map[string]interface{}{}
  1254. var in inner
  1255. assert.Nil(t, UnmarshalKey(m, &in))
  1256. assert.Equal(t, "second", in.Value)
  1257. }
  1258. func TestUnmarshalWithOptionsAndSet(t *testing.T) {
  1259. type inner struct {
  1260. Value string `key:"value,options=first|second|third,default=second"`
  1261. }
  1262. m := map[string]interface{}{
  1263. "value": "first",
  1264. }
  1265. var in inner
  1266. assert.Nil(t, UnmarshalKey(m, &in))
  1267. assert.Equal(t, "first", in.Value)
  1268. }
  1269. func TestUnmarshalNestedKey(t *testing.T) {
  1270. var c struct {
  1271. ID int `json:"Persons.first.ID"`
  1272. }
  1273. m := map[string]interface{}{
  1274. "Persons": map[string]interface{}{
  1275. "first": map[string]interface{}{
  1276. "ID": 1,
  1277. },
  1278. },
  1279. }
  1280. assert.Nil(t, NewUnmarshaler("json").Unmarshal(m, &c))
  1281. assert.Equal(t, 1, c.ID)
  1282. }
  1283. func TestUnmarhsalNestedKeyArray(t *testing.T) {
  1284. var c struct {
  1285. First []struct {
  1286. ID int
  1287. } `json:"Persons.first"`
  1288. }
  1289. m := map[string]interface{}{
  1290. "Persons": map[string]interface{}{
  1291. "first": []map[string]interface{}{
  1292. {"ID": 1},
  1293. {"ID": 2},
  1294. },
  1295. },
  1296. }
  1297. assert.Nil(t, NewUnmarshaler("json").Unmarshal(m, &c))
  1298. assert.Equal(t, 2, len(c.First))
  1299. assert.Equal(t, 1, c.First[0].ID)
  1300. }
  1301. func TestUnmarshalAnonymousOptionalRequiredProvided(t *testing.T) {
  1302. type (
  1303. Foo struct {
  1304. Value string `json:"v"`
  1305. }
  1306. Bar struct {
  1307. Foo `json:",optional"`
  1308. }
  1309. )
  1310. m := map[string]interface{}{
  1311. "v": "anything",
  1312. }
  1313. var b Bar
  1314. assert.Nil(t, NewUnmarshaler("json").Unmarshal(m, &b))
  1315. assert.Equal(t, "anything", b.Value)
  1316. }
  1317. func TestUnmarshalAnonymousOptionalRequiredMissed(t *testing.T) {
  1318. type (
  1319. Foo struct {
  1320. Value string `json:"v"`
  1321. }
  1322. Bar struct {
  1323. Foo `json:",optional"`
  1324. }
  1325. )
  1326. m := map[string]interface{}{}
  1327. var b Bar
  1328. assert.Nil(t, NewUnmarshaler("json").Unmarshal(m, &b))
  1329. assert.True(t, len(b.Value) == 0)
  1330. }
  1331. func TestUnmarshalAnonymousOptionalOptionalProvided(t *testing.T) {
  1332. type (
  1333. Foo struct {
  1334. Value string `json:"v,optional"`
  1335. }
  1336. Bar struct {
  1337. Foo `json:",optional"`
  1338. }
  1339. )
  1340. m := map[string]interface{}{
  1341. "v": "anything",
  1342. }
  1343. var b Bar
  1344. assert.Nil(t, NewUnmarshaler("json").Unmarshal(m, &b))
  1345. assert.Equal(t, "anything", b.Value)
  1346. }
  1347. func TestUnmarshalAnonymousOptionalOptionalMissed(t *testing.T) {
  1348. type (
  1349. Foo struct {
  1350. Value string `json:"v,optional"`
  1351. }
  1352. Bar struct {
  1353. Foo `json:",optional"`
  1354. }
  1355. )
  1356. m := map[string]interface{}{}
  1357. var b Bar
  1358. assert.Nil(t, NewUnmarshaler("json").Unmarshal(m, &b))
  1359. assert.True(t, len(b.Value) == 0)
  1360. }
  1361. func TestUnmarshalAnonymousOptionalRequiredBothProvided(t *testing.T) {
  1362. type (
  1363. Foo struct {
  1364. Name string `json:"n"`
  1365. Value string `json:"v"`
  1366. }
  1367. Bar struct {
  1368. Foo `json:",optional"`
  1369. }
  1370. )
  1371. m := map[string]interface{}{
  1372. "n": "kevin",
  1373. "v": "anything",
  1374. }
  1375. var b Bar
  1376. assert.Nil(t, NewUnmarshaler("json").Unmarshal(m, &b))
  1377. assert.Equal(t, "kevin", b.Name)
  1378. assert.Equal(t, "anything", b.Value)
  1379. }
  1380. func TestUnmarshalAnonymousOptionalRequiredOneProvidedOneMissed(t *testing.T) {
  1381. type (
  1382. Foo struct {
  1383. Name string `json:"n"`
  1384. Value string `json:"v"`
  1385. }
  1386. Bar struct {
  1387. Foo `json:",optional"`
  1388. }
  1389. )
  1390. m := map[string]interface{}{
  1391. "v": "anything",
  1392. }
  1393. var b Bar
  1394. assert.NotNil(t, NewUnmarshaler("json").Unmarshal(m, &b))
  1395. }
  1396. func TestUnmarshalAnonymousOptionalRequiredBothMissed(t *testing.T) {
  1397. type (
  1398. Foo struct {
  1399. Name string `json:"n"`
  1400. Value string `json:"v"`
  1401. }
  1402. Bar struct {
  1403. Foo `json:",optional"`
  1404. }
  1405. )
  1406. m := map[string]interface{}{}
  1407. var b Bar
  1408. assert.Nil(t, NewUnmarshaler("json").Unmarshal(m, &b))
  1409. assert.True(t, len(b.Name) == 0)
  1410. assert.True(t, len(b.Value) == 0)
  1411. }
  1412. func TestUnmarshalAnonymousOptionalOneRequiredOneOptionalBothProvided(t *testing.T) {
  1413. type (
  1414. Foo struct {
  1415. Name string `json:"n,optional"`
  1416. Value string `json:"v"`
  1417. }
  1418. Bar struct {
  1419. Foo `json:",optional"`
  1420. }
  1421. )
  1422. m := map[string]interface{}{
  1423. "n": "kevin",
  1424. "v": "anything",
  1425. }
  1426. var b Bar
  1427. assert.Nil(t, NewUnmarshaler("json").Unmarshal(m, &b))
  1428. assert.Equal(t, "kevin", b.Name)
  1429. assert.Equal(t, "anything", b.Value)
  1430. }
  1431. func TestUnmarshalAnonymousOptionalOneRequiredOneOptionalBothMissed(t *testing.T) {
  1432. type (
  1433. Foo struct {
  1434. Name string `json:"n,optional"`
  1435. Value string `json:"v"`
  1436. }
  1437. Bar struct {
  1438. Foo `json:",optional"`
  1439. }
  1440. )
  1441. m := map[string]interface{}{}
  1442. var b Bar
  1443. assert.Nil(t, NewUnmarshaler("json").Unmarshal(m, &b))
  1444. assert.True(t, len(b.Name) == 0)
  1445. assert.True(t, len(b.Value) == 0)
  1446. }
  1447. func TestUnmarshalAnonymousOptionalOneRequiredOneOptionalRequiredProvidedOptionalMissed(t *testing.T) {
  1448. type (
  1449. Foo struct {
  1450. Name string `json:"n,optional"`
  1451. Value string `json:"v"`
  1452. }
  1453. Bar struct {
  1454. Foo `json:",optional"`
  1455. }
  1456. )
  1457. m := map[string]interface{}{
  1458. "v": "anything",
  1459. }
  1460. var b Bar
  1461. assert.Nil(t, NewUnmarshaler("json").Unmarshal(m, &b))
  1462. assert.True(t, len(b.Name) == 0)
  1463. assert.Equal(t, "anything", b.Value)
  1464. }
  1465. func TestUnmarshalAnonymousOptionalOneRequiredOneOptionalRequiredMissedOptionalProvided(t *testing.T) {
  1466. type (
  1467. Foo struct {
  1468. Name string `json:"n,optional"`
  1469. Value string `json:"v"`
  1470. }
  1471. Bar struct {
  1472. Foo `json:",optional"`
  1473. }
  1474. )
  1475. m := map[string]interface{}{
  1476. "n": "anything",
  1477. }
  1478. var b Bar
  1479. assert.NotNil(t, NewUnmarshaler("json").Unmarshal(m, &b))
  1480. }
  1481. func TestUnmarshalAnonymousOptionalBothOptionalBothProvided(t *testing.T) {
  1482. type (
  1483. Foo struct {
  1484. Name string `json:"n,optional"`
  1485. Value string `json:"v,optional"`
  1486. }
  1487. Bar struct {
  1488. Foo `json:",optional"`
  1489. }
  1490. )
  1491. m := map[string]interface{}{
  1492. "n": "kevin",
  1493. "v": "anything",
  1494. }
  1495. var b Bar
  1496. assert.Nil(t, NewUnmarshaler("json").Unmarshal(m, &b))
  1497. assert.Equal(t, "kevin", b.Name)
  1498. assert.Equal(t, "anything", b.Value)
  1499. }
  1500. func TestUnmarshalAnonymousOptionalBothOptionalOneProvidedOneMissed(t *testing.T) {
  1501. type (
  1502. Foo struct {
  1503. Name string `json:"n,optional"`
  1504. Value string `json:"v,optional"`
  1505. }
  1506. Bar struct {
  1507. Foo `json:",optional"`
  1508. }
  1509. )
  1510. m := map[string]interface{}{
  1511. "v": "anything",
  1512. }
  1513. var b Bar
  1514. assert.Nil(t, NewUnmarshaler("json").Unmarshal(m, &b))
  1515. assert.True(t, len(b.Name) == 0)
  1516. assert.Equal(t, "anything", b.Value)
  1517. }
  1518. func TestUnmarshalAnonymousOptionalBothOptionalBothMissed(t *testing.T) {
  1519. type (
  1520. Foo struct {
  1521. Name string `json:"n,optional"`
  1522. Value string `json:"v,optional"`
  1523. }
  1524. Bar struct {
  1525. Foo `json:",optional"`
  1526. }
  1527. )
  1528. m := map[string]interface{}{}
  1529. var b Bar
  1530. assert.Nil(t, NewUnmarshaler("json").Unmarshal(m, &b))
  1531. assert.True(t, len(b.Name) == 0)
  1532. assert.True(t, len(b.Value) == 0)
  1533. }
  1534. func TestUnmarshalAnonymousRequiredProvided(t *testing.T) {
  1535. type (
  1536. Foo struct {
  1537. Value string `json:"v"`
  1538. }
  1539. Bar struct {
  1540. Foo
  1541. }
  1542. )
  1543. m := map[string]interface{}{
  1544. "v": "anything",
  1545. }
  1546. var b Bar
  1547. assert.Nil(t, NewUnmarshaler("json").Unmarshal(m, &b))
  1548. assert.Equal(t, "anything", b.Value)
  1549. }
  1550. func TestUnmarshalAnonymousRequiredMissed(t *testing.T) {
  1551. type (
  1552. Foo struct {
  1553. Value string `json:"v"`
  1554. }
  1555. Bar struct {
  1556. Foo
  1557. }
  1558. )
  1559. m := map[string]interface{}{}
  1560. var b Bar
  1561. assert.NotNil(t, NewUnmarshaler("json").Unmarshal(m, &b))
  1562. }
  1563. func TestUnmarshalAnonymousOptionalProvided(t *testing.T) {
  1564. type (
  1565. Foo struct {
  1566. Value string `json:"v,optional"`
  1567. }
  1568. Bar struct {
  1569. Foo
  1570. }
  1571. )
  1572. m := map[string]interface{}{
  1573. "v": "anything",
  1574. }
  1575. var b Bar
  1576. assert.Nil(t, NewUnmarshaler("json").Unmarshal(m, &b))
  1577. assert.Equal(t, "anything", b.Value)
  1578. }
  1579. func TestUnmarshalAnonymousOptionalMissed(t *testing.T) {
  1580. type (
  1581. Foo struct {
  1582. Value string `json:"v,optional"`
  1583. }
  1584. Bar struct {
  1585. Foo
  1586. }
  1587. )
  1588. m := map[string]interface{}{}
  1589. var b Bar
  1590. assert.Nil(t, NewUnmarshaler("json").Unmarshal(m, &b))
  1591. assert.True(t, len(b.Value) == 0)
  1592. }
  1593. func TestUnmarshalAnonymousRequiredBothProvided(t *testing.T) {
  1594. type (
  1595. Foo struct {
  1596. Name string `json:"n"`
  1597. Value string `json:"v"`
  1598. }
  1599. Bar struct {
  1600. Foo
  1601. }
  1602. )
  1603. m := map[string]interface{}{
  1604. "n": "kevin",
  1605. "v": "anything",
  1606. }
  1607. var b Bar
  1608. assert.Nil(t, NewUnmarshaler("json").Unmarshal(m, &b))
  1609. assert.Equal(t, "kevin", b.Name)
  1610. assert.Equal(t, "anything", b.Value)
  1611. }
  1612. func TestUnmarshalAnonymousRequiredOneProvidedOneMissed(t *testing.T) {
  1613. type (
  1614. Foo struct {
  1615. Name string `json:"n"`
  1616. Value string `json:"v"`
  1617. }
  1618. Bar struct {
  1619. Foo
  1620. }
  1621. )
  1622. m := map[string]interface{}{
  1623. "v": "anything",
  1624. }
  1625. var b Bar
  1626. assert.NotNil(t, NewUnmarshaler("json").Unmarshal(m, &b))
  1627. }
  1628. func TestUnmarshalAnonymousRequiredBothMissed(t *testing.T) {
  1629. type (
  1630. Foo struct {
  1631. Name string `json:"n"`
  1632. Value string `json:"v"`
  1633. }
  1634. Bar struct {
  1635. Foo
  1636. }
  1637. )
  1638. m := map[string]interface{}{
  1639. "v": "anything",
  1640. }
  1641. var b Bar
  1642. assert.NotNil(t, NewUnmarshaler("json").Unmarshal(m, &b))
  1643. }
  1644. func TestUnmarshalAnonymousOneRequiredOneOptionalBothProvided(t *testing.T) {
  1645. type (
  1646. Foo struct {
  1647. Name string `json:"n,optional"`
  1648. Value string `json:"v"`
  1649. }
  1650. Bar struct {
  1651. Foo
  1652. }
  1653. )
  1654. m := map[string]interface{}{
  1655. "n": "kevin",
  1656. "v": "anything",
  1657. }
  1658. var b Bar
  1659. assert.Nil(t, NewUnmarshaler("json").Unmarshal(m, &b))
  1660. assert.Equal(t, "kevin", b.Name)
  1661. assert.Equal(t, "anything", b.Value)
  1662. }
  1663. func TestUnmarshalAnonymousOneRequiredOneOptionalBothMissed(t *testing.T) {
  1664. type (
  1665. Foo struct {
  1666. Name string `json:"n,optional"`
  1667. Value string `json:"v"`
  1668. }
  1669. Bar struct {
  1670. Foo
  1671. }
  1672. )
  1673. m := map[string]interface{}{}
  1674. var b Bar
  1675. assert.NotNil(t, NewUnmarshaler("json").Unmarshal(m, &b))
  1676. }
  1677. func TestUnmarshalAnonymousOneRequiredOneOptionalRequiredProvidedOptionalMissed(t *testing.T) {
  1678. type (
  1679. Foo struct {
  1680. Name string `json:"n,optional"`
  1681. Value string `json:"v"`
  1682. }
  1683. Bar struct {
  1684. Foo
  1685. }
  1686. )
  1687. m := map[string]interface{}{
  1688. "v": "anything",
  1689. }
  1690. var b Bar
  1691. assert.Nil(t, NewUnmarshaler("json").Unmarshal(m, &b))
  1692. assert.True(t, len(b.Name) == 0)
  1693. assert.Equal(t, "anything", b.Value)
  1694. }
  1695. func TestUnmarshalAnonymousOneRequiredOneOptionalRequiredMissedOptionalProvided(t *testing.T) {
  1696. type (
  1697. Foo struct {
  1698. Name string `json:"n,optional"`
  1699. Value string `json:"v"`
  1700. }
  1701. Bar struct {
  1702. Foo
  1703. }
  1704. )
  1705. m := map[string]interface{}{
  1706. "n": "anything",
  1707. }
  1708. var b Bar
  1709. assert.NotNil(t, NewUnmarshaler("json").Unmarshal(m, &b))
  1710. }
  1711. func TestUnmarshalAnonymousBothOptionalBothProvided(t *testing.T) {
  1712. type (
  1713. Foo struct {
  1714. Name string `json:"n,optional"`
  1715. Value string `json:"v,optional"`
  1716. }
  1717. Bar struct {
  1718. Foo
  1719. }
  1720. )
  1721. m := map[string]interface{}{
  1722. "n": "kevin",
  1723. "v": "anything",
  1724. }
  1725. var b Bar
  1726. assert.Nil(t, NewUnmarshaler("json").Unmarshal(m, &b))
  1727. assert.Equal(t, "kevin", b.Name)
  1728. assert.Equal(t, "anything", b.Value)
  1729. }
  1730. func TestUnmarshalAnonymousBothOptionalOneProvidedOneMissed(t *testing.T) {
  1731. type (
  1732. Foo struct {
  1733. Name string `json:"n,optional"`
  1734. Value string `json:"v,optional"`
  1735. }
  1736. Bar struct {
  1737. Foo
  1738. }
  1739. )
  1740. m := map[string]interface{}{
  1741. "v": "anything",
  1742. }
  1743. var b Bar
  1744. assert.Nil(t, NewUnmarshaler("json").Unmarshal(m, &b))
  1745. assert.True(t, len(b.Name) == 0)
  1746. assert.Equal(t, "anything", b.Value)
  1747. }
  1748. func TestUnmarshalAnonymousBothOptionalBothMissed(t *testing.T) {
  1749. type (
  1750. Foo struct {
  1751. Name string `json:"n,optional"`
  1752. Value string `json:"v,optional"`
  1753. }
  1754. Bar struct {
  1755. Foo
  1756. }
  1757. )
  1758. m := map[string]interface{}{}
  1759. var b Bar
  1760. assert.Nil(t, NewUnmarshaler("json").Unmarshal(m, &b))
  1761. assert.True(t, len(b.Name) == 0)
  1762. assert.True(t, len(b.Value) == 0)
  1763. }
  1764. func TestUnmarshalAnonymousWrappedToMuch(t *testing.T) {
  1765. type (
  1766. Foo struct {
  1767. Name string `json:"n"`
  1768. Value string `json:"v"`
  1769. }
  1770. Bar struct {
  1771. Foo
  1772. }
  1773. )
  1774. m := map[string]interface{}{
  1775. "Foo": map[string]interface{}{
  1776. "n": "name",
  1777. "v": "anything",
  1778. },
  1779. }
  1780. var b Bar
  1781. assert.NotNil(t, NewUnmarshaler("json").Unmarshal(m, &b))
  1782. }
  1783. func TestUnmarshalWrappedObject(t *testing.T) {
  1784. type (
  1785. Foo struct {
  1786. Value string `json:"v"`
  1787. }
  1788. Bar struct {
  1789. Inner Foo
  1790. }
  1791. )
  1792. m := map[string]interface{}{
  1793. "Inner": map[string]interface{}{
  1794. "v": "anything",
  1795. },
  1796. }
  1797. var b Bar
  1798. assert.Nil(t, NewUnmarshaler("json").Unmarshal(m, &b))
  1799. assert.Equal(t, "anything", b.Inner.Value)
  1800. }
  1801. func TestUnmarshalWrappedObjectOptional(t *testing.T) {
  1802. type (
  1803. Foo struct {
  1804. Hosts []string
  1805. Key string
  1806. }
  1807. Bar struct {
  1808. Inner Foo `json:",optional"`
  1809. Name string
  1810. }
  1811. )
  1812. m := map[string]interface{}{
  1813. "Name": "anything",
  1814. }
  1815. var b Bar
  1816. assert.Nil(t, NewUnmarshaler("json").Unmarshal(m, &b))
  1817. assert.Equal(t, "anything", b.Name)
  1818. }
  1819. func TestUnmarshalWrappedObjectOptionalFilled(t *testing.T) {
  1820. type (
  1821. Foo struct {
  1822. Hosts []string
  1823. Key string
  1824. }
  1825. Bar struct {
  1826. Inner Foo `json:",optional"`
  1827. Name string
  1828. }
  1829. )
  1830. hosts := []string{"1", "2"}
  1831. m := map[string]interface{}{
  1832. "Inner": map[string]interface{}{
  1833. "Hosts": hosts,
  1834. "Key": "key",
  1835. },
  1836. "Name": "anything",
  1837. }
  1838. var b Bar
  1839. assert.Nil(t, NewUnmarshaler("json").Unmarshal(m, &b))
  1840. assert.EqualValues(t, hosts, b.Inner.Hosts)
  1841. assert.Equal(t, "key", b.Inner.Key)
  1842. assert.Equal(t, "anything", b.Name)
  1843. }
  1844. func TestUnmarshalWrappedNamedObjectOptional(t *testing.T) {
  1845. type (
  1846. Foo struct {
  1847. Host string
  1848. Key string
  1849. }
  1850. Bar struct {
  1851. Inner Foo `json:",optional"`
  1852. Name string
  1853. }
  1854. )
  1855. m := map[string]interface{}{
  1856. "Inner": map[string]interface{}{
  1857. "Host": "thehost",
  1858. "Key": "thekey",
  1859. },
  1860. "Name": "anything",
  1861. }
  1862. var b Bar
  1863. assert.Nil(t, NewUnmarshaler("json").Unmarshal(m, &b))
  1864. assert.Equal(t, "thehost", b.Inner.Host)
  1865. assert.Equal(t, "thekey", b.Inner.Key)
  1866. assert.Equal(t, "anything", b.Name)
  1867. }
  1868. func TestUnmarshalWrappedObjectNamedPtr(t *testing.T) {
  1869. type (
  1870. Foo struct {
  1871. Value string `json:"v"`
  1872. }
  1873. Bar struct {
  1874. Inner *Foo `json:"foo,optional"`
  1875. }
  1876. )
  1877. m := map[string]interface{}{
  1878. "foo": map[string]interface{}{
  1879. "v": "anything",
  1880. },
  1881. }
  1882. var b Bar
  1883. assert.Nil(t, NewUnmarshaler("json").Unmarshal(m, &b))
  1884. assert.Equal(t, "anything", b.Inner.Value)
  1885. }
  1886. func TestUnmarshalWrappedObjectPtr(t *testing.T) {
  1887. type (
  1888. Foo struct {
  1889. Value string `json:"v"`
  1890. }
  1891. Bar struct {
  1892. Inner *Foo
  1893. }
  1894. )
  1895. m := map[string]interface{}{
  1896. "Inner": map[string]interface{}{
  1897. "v": "anything",
  1898. },
  1899. }
  1900. var b Bar
  1901. assert.Nil(t, NewUnmarshaler("json").Unmarshal(m, &b))
  1902. assert.Equal(t, "anything", b.Inner.Value)
  1903. }
  1904. func TestUnmarshalInt2String(t *testing.T) {
  1905. type inner struct {
  1906. Int string `key:"int"`
  1907. }
  1908. m := map[string]interface{}{
  1909. "int": 123,
  1910. }
  1911. var in inner
  1912. assert.NotNil(t, UnmarshalKey(m, &in))
  1913. }
  1914. func TestUnmarshalZeroValues(t *testing.T) {
  1915. type inner struct {
  1916. False bool `key:"no"`
  1917. Int int `key:"int"`
  1918. String string `key:"string"`
  1919. }
  1920. m := map[string]interface{}{
  1921. "no": false,
  1922. "int": 0,
  1923. "string": "",
  1924. }
  1925. var in inner
  1926. ast := assert.New(t)
  1927. ast.Nil(UnmarshalKey(m, &in))
  1928. ast.False(in.False)
  1929. ast.Equal(0, in.Int)
  1930. ast.Equal("", in.String)
  1931. }
  1932. func TestUnmarshalUsingDifferentKeys(t *testing.T) {
  1933. type inner struct {
  1934. False bool `key:"no"`
  1935. Int int `key:"int"`
  1936. String string `bson:"string"`
  1937. }
  1938. m := map[string]interface{}{
  1939. "no": false,
  1940. "int": 9,
  1941. "string": "value",
  1942. }
  1943. var in inner
  1944. ast := assert.New(t)
  1945. ast.Nil(UnmarshalKey(m, &in))
  1946. ast.False(in.False)
  1947. ast.Equal(9, in.Int)
  1948. ast.True(len(in.String) == 0)
  1949. }
  1950. func TestUnmarshalNumberRangeInt(t *testing.T) {
  1951. type inner struct {
  1952. Value1 int `key:"value1,range=[1:]"`
  1953. Value2 int8 `key:"value2,range=[1:5]"`
  1954. Value3 int16 `key:"value3,range=[1:5]"`
  1955. Value4 int32 `key:"value4,range=[1:5]"`
  1956. Value5 int64 `key:"value5,range=[1:5]"`
  1957. Value6 uint `key:"value6,range=[:5]"`
  1958. Value8 uint8 `key:"value8,range=[1:5],string"`
  1959. Value9 uint16 `key:"value9,range=[1:5],string"`
  1960. Value10 uint32 `key:"value10,range=[1:5],string"`
  1961. Value11 uint64 `key:"value11,range=[1:5],string"`
  1962. }
  1963. m := map[string]interface{}{
  1964. "value1": 10,
  1965. "value2": int8(1),
  1966. "value3": int16(2),
  1967. "value4": int32(4),
  1968. "value5": int64(5),
  1969. "value6": uint(0),
  1970. "value8": "1",
  1971. "value9": "2",
  1972. "value10": "4",
  1973. "value11": "5",
  1974. }
  1975. var in inner
  1976. ast := assert.New(t)
  1977. ast.Nil(UnmarshalKey(m, &in))
  1978. ast.Equal(10, in.Value1)
  1979. ast.Equal(int8(1), in.Value2)
  1980. ast.Equal(int16(2), in.Value3)
  1981. ast.Equal(int32(4), in.Value4)
  1982. ast.Equal(int64(5), in.Value5)
  1983. ast.Equal(uint(0), in.Value6)
  1984. ast.Equal(uint8(1), in.Value8)
  1985. ast.Equal(uint16(2), in.Value9)
  1986. ast.Equal(uint32(4), in.Value10)
  1987. ast.Equal(uint64(5), in.Value11)
  1988. }
  1989. func TestUnmarshalNumberRangeJsonNumber(t *testing.T) {
  1990. type inner struct {
  1991. Value3 uint `key:"value3,range=(1:5]"`
  1992. Value4 uint8 `key:"value4,range=(1:5]"`
  1993. Value5 uint16 `key:"value5,range=(1:5]"`
  1994. }
  1995. m := map[string]interface{}{
  1996. "value3": json.Number("2"),
  1997. "value4": json.Number("4"),
  1998. "value5": json.Number("5"),
  1999. }
  2000. var in inner
  2001. ast := assert.New(t)
  2002. ast.Nil(UnmarshalKey(m, &in))
  2003. ast.Equal(uint(2), in.Value3)
  2004. ast.Equal(uint8(4), in.Value4)
  2005. ast.Equal(uint16(5), in.Value5)
  2006. type inner1 struct {
  2007. Value int `key:"value,range=(1:5]"`
  2008. }
  2009. m = map[string]interface{}{
  2010. "value": json.Number("a"),
  2011. }
  2012. var in1 inner1
  2013. ast.NotNil(UnmarshalKey(m, &in1))
  2014. }
  2015. func TestUnmarshalNumberRangeIntLeftExclude(t *testing.T) {
  2016. type inner struct {
  2017. Value3 uint `key:"value3,range=(1:5]"`
  2018. Value4 uint32 `key:"value4,default=4,range=(1:5]"`
  2019. Value5 uint64 `key:"value5,range=(1:5]"`
  2020. Value9 int `key:"value9,range=(1:5],string"`
  2021. Value10 int `key:"value10,range=(1:5],string"`
  2022. Value11 int `key:"value11,range=(1:5],string"`
  2023. }
  2024. m := map[string]interface{}{
  2025. "value3": uint(2),
  2026. "value4": uint32(4),
  2027. "value5": uint64(5),
  2028. "value9": "2",
  2029. "value10": "4",
  2030. "value11": "5",
  2031. }
  2032. var in inner
  2033. ast := assert.New(t)
  2034. ast.Nil(UnmarshalKey(m, &in))
  2035. ast.Equal(uint(2), in.Value3)
  2036. ast.Equal(uint32(4), in.Value4)
  2037. ast.Equal(uint64(5), in.Value5)
  2038. ast.Equal(2, in.Value9)
  2039. ast.Equal(4, in.Value10)
  2040. ast.Equal(5, in.Value11)
  2041. }
  2042. func TestUnmarshalNumberRangeIntRightExclude(t *testing.T) {
  2043. type inner struct {
  2044. Value2 uint `key:"value2,range=[1:5)"`
  2045. Value3 uint8 `key:"value3,range=[1:5)"`
  2046. Value4 uint16 `key:"value4,range=[1:5)"`
  2047. Value8 int `key:"value8,range=[1:5),string"`
  2048. Value9 int `key:"value9,range=[1:5),string"`
  2049. Value10 int `key:"value10,range=[1:5),string"`
  2050. }
  2051. m := map[string]interface{}{
  2052. "value2": uint(1),
  2053. "value3": uint8(2),
  2054. "value4": uint16(4),
  2055. "value8": "1",
  2056. "value9": "2",
  2057. "value10": "4",
  2058. }
  2059. var in inner
  2060. ast := assert.New(t)
  2061. ast.Nil(UnmarshalKey(m, &in))
  2062. ast.Equal(uint(1), in.Value2)
  2063. ast.Equal(uint8(2), in.Value3)
  2064. ast.Equal(uint16(4), in.Value4)
  2065. ast.Equal(1, in.Value8)
  2066. ast.Equal(2, in.Value9)
  2067. ast.Equal(4, in.Value10)
  2068. }
  2069. func TestUnmarshalNumberRangeIntExclude(t *testing.T) {
  2070. type inner struct {
  2071. Value3 int `key:"value3,range=(1:5)"`
  2072. Value4 int `key:"value4,range=(1:5)"`
  2073. Value9 int `key:"value9,range=(1:5),string"`
  2074. Value10 int `key:"value10,range=(1:5),string"`
  2075. }
  2076. m := map[string]interface{}{
  2077. "value3": 2,
  2078. "value4": 4,
  2079. "value9": "2",
  2080. "value10": "4",
  2081. }
  2082. var in inner
  2083. ast := assert.New(t)
  2084. ast.Nil(UnmarshalKey(m, &in))
  2085. ast.Equal(2, in.Value3)
  2086. ast.Equal(4, in.Value4)
  2087. ast.Equal(2, in.Value9)
  2088. ast.Equal(4, in.Value10)
  2089. }
  2090. func TestUnmarshalNumberRangeIntOutOfRange(t *testing.T) {
  2091. type inner1 struct {
  2092. Value int64 `key:"value,default=3,range=(1:5)"`
  2093. }
  2094. var in1 inner1
  2095. assert.Equal(t, errNumberRange, UnmarshalKey(map[string]interface{}{
  2096. "value": int64(1),
  2097. }, &in1))
  2098. assert.Equal(t, errNumberRange, UnmarshalKey(map[string]interface{}{
  2099. "value": int64(0),
  2100. }, &in1))
  2101. assert.Equal(t, errNumberRange, UnmarshalKey(map[string]interface{}{
  2102. "value": int64(5),
  2103. }, &in1))
  2104. assert.Equal(t, errNumberRange, UnmarshalKey(map[string]interface{}{
  2105. "value": json.Number("6"),
  2106. }, &in1))
  2107. type inner2 struct {
  2108. Value int64 `key:"value,optional,range=[1:5)"`
  2109. }
  2110. var in2 inner2
  2111. assert.Equal(t, errNumberRange, UnmarshalKey(map[string]interface{}{
  2112. "value": int64(0),
  2113. }, &in2))
  2114. assert.Equal(t, errNumberRange, UnmarshalKey(map[string]interface{}{
  2115. "value": int64(5),
  2116. }, &in2))
  2117. type inner3 struct {
  2118. Value int64 `key:"value,range=(1:5]"`
  2119. }
  2120. var in3 inner3
  2121. assert.Equal(t, errNumberRange, UnmarshalKey(map[string]interface{}{
  2122. "value": int64(1),
  2123. }, &in3))
  2124. assert.Equal(t, errNumberRange, UnmarshalKey(map[string]interface{}{
  2125. "value": int64(6),
  2126. }, &in3))
  2127. type inner4 struct {
  2128. Value int64 `key:"value,range=[1:5]"`
  2129. }
  2130. var in4 inner4
  2131. assert.Equal(t, errNumberRange, UnmarshalKey(map[string]interface{}{
  2132. "value": int64(0),
  2133. }, &in4))
  2134. assert.Equal(t, errNumberRange, UnmarshalKey(map[string]interface{}{
  2135. "value": int64(6),
  2136. }, &in4))
  2137. }
  2138. func TestUnmarshalNumberRangeFloat(t *testing.T) {
  2139. type inner struct {
  2140. Value2 float32 `key:"value2,range=[1:5]"`
  2141. Value3 float32 `key:"value3,range=[1:5]"`
  2142. Value4 float64 `key:"value4,range=[1:5]"`
  2143. Value5 float64 `key:"value5,range=[1:5]"`
  2144. Value8 float64 `key:"value8,range=[1:5],string"`
  2145. Value9 float64 `key:"value9,range=[1:5],string"`
  2146. Value10 float64 `key:"value10,range=[1:5],string"`
  2147. Value11 float64 `key:"value11,range=[1:5],string"`
  2148. }
  2149. m := map[string]interface{}{
  2150. "value2": float32(1),
  2151. "value3": float32(2),
  2152. "value4": float64(4),
  2153. "value5": float64(5),
  2154. "value8": "1",
  2155. "value9": "2",
  2156. "value10": "4",
  2157. "value11": "5",
  2158. }
  2159. var in inner
  2160. ast := assert.New(t)
  2161. ast.Nil(UnmarshalKey(m, &in))
  2162. ast.Equal(float32(1), in.Value2)
  2163. ast.Equal(float32(2), in.Value3)
  2164. ast.Equal(float64(4), in.Value4)
  2165. ast.Equal(float64(5), in.Value5)
  2166. ast.Equal(float64(1), in.Value8)
  2167. ast.Equal(float64(2), in.Value9)
  2168. ast.Equal(float64(4), in.Value10)
  2169. ast.Equal(float64(5), in.Value11)
  2170. }
  2171. func TestUnmarshalNumberRangeFloatLeftExclude(t *testing.T) {
  2172. type inner struct {
  2173. Value3 float64 `key:"value3,range=(1:5]"`
  2174. Value4 float64 `key:"value4,range=(1:5]"`
  2175. Value5 float64 `key:"value5,range=(1:5]"`
  2176. Value9 float64 `key:"value9,range=(1:5],string"`
  2177. Value10 float64 `key:"value10,range=(1:5],string"`
  2178. Value11 float64 `key:"value11,range=(1:5],string"`
  2179. }
  2180. m := map[string]interface{}{
  2181. "value3": float64(2),
  2182. "value4": float64(4),
  2183. "value5": float64(5),
  2184. "value9": "2",
  2185. "value10": "4",
  2186. "value11": "5",
  2187. }
  2188. var in inner
  2189. ast := assert.New(t)
  2190. ast.Nil(UnmarshalKey(m, &in))
  2191. ast.Equal(float64(2), in.Value3)
  2192. ast.Equal(float64(4), in.Value4)
  2193. ast.Equal(float64(5), in.Value5)
  2194. ast.Equal(float64(2), in.Value9)
  2195. ast.Equal(float64(4), in.Value10)
  2196. ast.Equal(float64(5), in.Value11)
  2197. }
  2198. func TestUnmarshalNumberRangeFloatRightExclude(t *testing.T) {
  2199. type inner struct {
  2200. Value2 float64 `key:"value2,range=[1:5)"`
  2201. Value3 float64 `key:"value3,range=[1:5)"`
  2202. Value4 float64 `key:"value4,range=[1:5)"`
  2203. Value8 float64 `key:"value8,range=[1:5),string"`
  2204. Value9 float64 `key:"value9,range=[1:5),string"`
  2205. Value10 float64 `key:"value10,range=[1:5),string"`
  2206. }
  2207. m := map[string]interface{}{
  2208. "value2": float64(1),
  2209. "value3": float64(2),
  2210. "value4": float64(4),
  2211. "value8": "1",
  2212. "value9": "2",
  2213. "value10": "4",
  2214. }
  2215. var in inner
  2216. ast := assert.New(t)
  2217. ast.Nil(UnmarshalKey(m, &in))
  2218. ast.Equal(float64(1), in.Value2)
  2219. ast.Equal(float64(2), in.Value3)
  2220. ast.Equal(float64(4), in.Value4)
  2221. ast.Equal(float64(1), in.Value8)
  2222. ast.Equal(float64(2), in.Value9)
  2223. ast.Equal(float64(4), in.Value10)
  2224. }
  2225. func TestUnmarshalNumberRangeFloatExclude(t *testing.T) {
  2226. type inner struct {
  2227. Value3 float64 `key:"value3,range=(1:5)"`
  2228. Value4 float64 `key:"value4,range=(1:5)"`
  2229. Value9 float64 `key:"value9,range=(1:5),string"`
  2230. Value10 float64 `key:"value10,range=(1:5),string"`
  2231. }
  2232. m := map[string]interface{}{
  2233. "value3": float64(2),
  2234. "value4": float64(4),
  2235. "value9": "2",
  2236. "value10": "4",
  2237. }
  2238. var in inner
  2239. ast := assert.New(t)
  2240. ast.Nil(UnmarshalKey(m, &in))
  2241. ast.Equal(float64(2), in.Value3)
  2242. ast.Equal(float64(4), in.Value4)
  2243. ast.Equal(float64(2), in.Value9)
  2244. ast.Equal(float64(4), in.Value10)
  2245. }
  2246. func TestUnmarshalNumberRangeFloatOutOfRange(t *testing.T) {
  2247. type inner1 struct {
  2248. Value float64 `key:"value,range=(1:5)"`
  2249. }
  2250. var in1 inner1
  2251. assert.Equal(t, errNumberRange, UnmarshalKey(map[string]interface{}{
  2252. "value": float64(1),
  2253. }, &in1))
  2254. assert.Equal(t, errNumberRange, UnmarshalKey(map[string]interface{}{
  2255. "value": float64(0),
  2256. }, &in1))
  2257. assert.Equal(t, errNumberRange, UnmarshalKey(map[string]interface{}{
  2258. "value": float64(5),
  2259. }, &in1))
  2260. assert.Equal(t, errNumberRange, UnmarshalKey(map[string]interface{}{
  2261. "value": json.Number("6"),
  2262. }, &in1))
  2263. type inner2 struct {
  2264. Value float64 `key:"value,range=[1:5)"`
  2265. }
  2266. var in2 inner2
  2267. assert.Equal(t, errNumberRange, UnmarshalKey(map[string]interface{}{
  2268. "value": float64(0),
  2269. }, &in2))
  2270. assert.Equal(t, errNumberRange, UnmarshalKey(map[string]interface{}{
  2271. "value": float64(5),
  2272. }, &in2))
  2273. type inner3 struct {
  2274. Value float64 `key:"value,range=(1:5]"`
  2275. }
  2276. var in3 inner3
  2277. assert.Equal(t, errNumberRange, UnmarshalKey(map[string]interface{}{
  2278. "value": float64(1),
  2279. }, &in3))
  2280. assert.Equal(t, errNumberRange, UnmarshalKey(map[string]interface{}{
  2281. "value": float64(6),
  2282. }, &in3))
  2283. type inner4 struct {
  2284. Value float64 `key:"value,range=[1:5]"`
  2285. }
  2286. var in4 inner4
  2287. assert.Equal(t, errNumberRange, UnmarshalKey(map[string]interface{}{
  2288. "value": float64(0),
  2289. }, &in4))
  2290. assert.Equal(t, errNumberRange, UnmarshalKey(map[string]interface{}{
  2291. "value": float64(6),
  2292. }, &in4))
  2293. }
  2294. func TestUnmarshalRangeError(t *testing.T) {
  2295. type inner1 struct {
  2296. Value int `key:",range="`
  2297. }
  2298. var in1 inner1
  2299. assert.Equal(t, errNumberRange, UnmarshalKey(map[string]interface{}{
  2300. "Value": 1,
  2301. }, &in1))
  2302. type inner2 struct {
  2303. Value int `key:",range=["`
  2304. }
  2305. var in2 inner2
  2306. assert.Equal(t, errNumberRange, UnmarshalKey(map[string]interface{}{
  2307. "Value": 1,
  2308. }, &in2))
  2309. type inner3 struct {
  2310. Value int `key:",range=[:"`
  2311. }
  2312. var in3 inner3
  2313. assert.Equal(t, errNumberRange, UnmarshalKey(map[string]interface{}{
  2314. "Value": 1,
  2315. }, &in3))
  2316. type inner4 struct {
  2317. Value int `key:",range=[:]"`
  2318. }
  2319. var in4 inner4
  2320. assert.Equal(t, errNumberRange, UnmarshalKey(map[string]interface{}{
  2321. "Value": 1,
  2322. }, &in4))
  2323. type inner5 struct {
  2324. Value int `key:",range={:]"`
  2325. }
  2326. var in5 inner5
  2327. assert.Equal(t, errNumberRange, UnmarshalKey(map[string]interface{}{
  2328. "Value": 1,
  2329. }, &in5))
  2330. type inner6 struct {
  2331. Value int `key:",range=[:}"`
  2332. }
  2333. var in6 inner6
  2334. assert.Equal(t, errNumberRange, UnmarshalKey(map[string]interface{}{
  2335. "Value": 1,
  2336. }, &in6))
  2337. type inner7 struct {
  2338. Value int `key:",range=[]"`
  2339. }
  2340. var in7 inner7
  2341. assert.Equal(t, errNumberRange, UnmarshalKey(map[string]interface{}{
  2342. "Value": 1,
  2343. }, &in7))
  2344. type inner8 struct {
  2345. Value int `key:",range=[a:]"`
  2346. }
  2347. var in8 inner8
  2348. assert.NotNil(t, UnmarshalKey(map[string]interface{}{
  2349. "Value": 1,
  2350. }, &in8))
  2351. type inner9 struct {
  2352. Value int `key:",range=[:a]"`
  2353. }
  2354. var in9 inner9
  2355. assert.NotNil(t, UnmarshalKey(map[string]interface{}{
  2356. "Value": 1,
  2357. }, &in9))
  2358. type inner10 struct {
  2359. Value int `key:",range"`
  2360. }
  2361. var in10 inner10
  2362. assert.NotNil(t, UnmarshalKey(map[string]interface{}{
  2363. "Value": 1,
  2364. }, &in10))
  2365. type inner11 struct {
  2366. Value int `key:",range=[1,2]"`
  2367. }
  2368. var in11 inner11
  2369. assert.Equal(t, errNumberRange, UnmarshalKey(map[string]interface{}{
  2370. "Value": "a",
  2371. }, &in11))
  2372. }
  2373. func TestUnmarshalNestedMap(t *testing.T) {
  2374. var c struct {
  2375. Anything map[string]map[string]string `json:"anything"`
  2376. }
  2377. m := map[string]interface{}{
  2378. "anything": map[string]map[string]interface{}{
  2379. "inner": {
  2380. "id": "1",
  2381. "name": "any",
  2382. },
  2383. },
  2384. }
  2385. assert.Nil(t, NewUnmarshaler("json").Unmarshal(m, &c))
  2386. assert.Equal(t, "1", c.Anything["inner"]["id"])
  2387. }
  2388. func TestUnmarshalNestedMapMismatch(t *testing.T) {
  2389. var c struct {
  2390. Anything map[string]map[string]map[string]string `json:"anything"`
  2391. }
  2392. m := map[string]interface{}{
  2393. "anything": map[string]map[string]interface{}{
  2394. "inner": {
  2395. "name": "any",
  2396. },
  2397. },
  2398. }
  2399. assert.NotNil(t, NewUnmarshaler("json").Unmarshal(m, &c))
  2400. }
  2401. func TestUnmarshalNestedMapSimple(t *testing.T) {
  2402. var c struct {
  2403. Anything map[string]string `json:"anything"`
  2404. }
  2405. m := map[string]interface{}{
  2406. "anything": map[string]interface{}{
  2407. "id": "1",
  2408. "name": "any",
  2409. },
  2410. }
  2411. assert.Nil(t, NewUnmarshaler("json").Unmarshal(m, &c))
  2412. assert.Equal(t, "1", c.Anything["id"])
  2413. }
  2414. func TestUnmarshalNestedMapSimpleTypeMatch(t *testing.T) {
  2415. var c struct {
  2416. Anything map[string]string `json:"anything"`
  2417. }
  2418. m := map[string]interface{}{
  2419. "anything": map[string]string{
  2420. "id": "1",
  2421. "name": "any",
  2422. },
  2423. }
  2424. assert.Nil(t, NewUnmarshaler("json").Unmarshal(m, &c))
  2425. assert.Equal(t, "1", c.Anything["id"])
  2426. }
  2427. func TestUnmarshalInheritPrimitiveUseParent(t *testing.T) {
  2428. type (
  2429. component struct {
  2430. Name string `key:"name"`
  2431. Discovery string `key:"discovery,inherit"`
  2432. }
  2433. server struct {
  2434. Discovery string `key:"discovery"`
  2435. Component component `key:"component"`
  2436. }
  2437. )
  2438. var s server
  2439. assert.NoError(t, UnmarshalKey(map[string]interface{}{
  2440. "discovery": "localhost:8080",
  2441. "component": map[string]interface{}{
  2442. "name": "test",
  2443. },
  2444. }, &s))
  2445. assert.Equal(t, "localhost:8080", s.Discovery)
  2446. assert.Equal(t, "localhost:8080", s.Component.Discovery)
  2447. }
  2448. func TestUnmarshalInheritPrimitiveUseSelf(t *testing.T) {
  2449. type (
  2450. component struct {
  2451. Name string `key:"name"`
  2452. Discovery string `key:"discovery,inherit"`
  2453. }
  2454. server struct {
  2455. Discovery string `key:"discovery"`
  2456. Component component `key:"component"`
  2457. }
  2458. )
  2459. var s server
  2460. assert.NoError(t, UnmarshalKey(map[string]interface{}{
  2461. "discovery": "localhost:8080",
  2462. "component": map[string]interface{}{
  2463. "name": "test",
  2464. "discovery": "localhost:8888",
  2465. },
  2466. }, &s))
  2467. assert.Equal(t, "localhost:8080", s.Discovery)
  2468. assert.Equal(t, "localhost:8888", s.Component.Discovery)
  2469. }
  2470. func TestUnmarshalInheritPrimitiveNotExist(t *testing.T) {
  2471. type (
  2472. component struct {
  2473. Name string `key:"name"`
  2474. Discovery string `key:"discovery,inherit"`
  2475. }
  2476. server struct {
  2477. Component component `key:"component"`
  2478. }
  2479. )
  2480. var s server
  2481. assert.NotNil(t, UnmarshalKey(map[string]interface{}{
  2482. "component": map[string]interface{}{
  2483. "name": "test",
  2484. },
  2485. }, &s))
  2486. }
  2487. func TestUnmarshalInheritStructUseParent(t *testing.T) {
  2488. type (
  2489. discovery struct {
  2490. Host string `key:"host"`
  2491. Port int `key:"port"`
  2492. }
  2493. component struct {
  2494. Name string `key:"name"`
  2495. Discovery discovery `key:"discovery,inherit"`
  2496. }
  2497. server struct {
  2498. Discovery discovery `key:"discovery"`
  2499. Component component `key:"component"`
  2500. }
  2501. )
  2502. var s server
  2503. assert.NoError(t, UnmarshalKey(map[string]interface{}{
  2504. "discovery": map[string]interface{}{
  2505. "host": "localhost",
  2506. "port": 8080,
  2507. },
  2508. "component": map[string]interface{}{
  2509. "name": "test",
  2510. },
  2511. }, &s))
  2512. assert.Equal(t, "localhost", s.Discovery.Host)
  2513. assert.Equal(t, 8080, s.Discovery.Port)
  2514. assert.Equal(t, "localhost", s.Component.Discovery.Host)
  2515. assert.Equal(t, 8080, s.Component.Discovery.Port)
  2516. }
  2517. func TestUnmarshalInheritStructUseSelf(t *testing.T) {
  2518. type (
  2519. discovery struct {
  2520. Host string `key:"host"`
  2521. Port int `key:"port"`
  2522. }
  2523. component struct {
  2524. Name string `key:"name"`
  2525. Discovery discovery `key:"discovery,inherit"`
  2526. }
  2527. server struct {
  2528. Discovery discovery `key:"discovery"`
  2529. Component component `key:"component"`
  2530. }
  2531. )
  2532. var s server
  2533. assert.NoError(t, UnmarshalKey(map[string]interface{}{
  2534. "discovery": map[string]interface{}{
  2535. "host": "localhost",
  2536. "port": 8080,
  2537. },
  2538. "component": map[string]interface{}{
  2539. "name": "test",
  2540. "discovery": map[string]interface{}{
  2541. "host": "remotehost",
  2542. "port": 8888,
  2543. },
  2544. },
  2545. }, &s))
  2546. assert.Equal(t, "localhost", s.Discovery.Host)
  2547. assert.Equal(t, 8080, s.Discovery.Port)
  2548. assert.Equal(t, "remotehost", s.Component.Discovery.Host)
  2549. assert.Equal(t, 8888, s.Component.Discovery.Port)
  2550. }
  2551. func TestUnmarshalInheritStructNotExist(t *testing.T) {
  2552. type (
  2553. discovery struct {
  2554. Host string `key:"host"`
  2555. Port int `key:"port"`
  2556. }
  2557. component struct {
  2558. Name string `key:"name"`
  2559. Discovery discovery `key:"discovery,inherit"`
  2560. }
  2561. server struct {
  2562. Component component `key:"component"`
  2563. }
  2564. )
  2565. var s server
  2566. assert.NotNil(t, UnmarshalKey(map[string]interface{}{
  2567. "component": map[string]interface{}{
  2568. "name": "test",
  2569. },
  2570. }, &s))
  2571. }
  2572. func TestUnmarshalInheritStructUsePartial(t *testing.T) {
  2573. type (
  2574. discovery struct {
  2575. Host string `key:"host"`
  2576. Port int `key:"port"`
  2577. }
  2578. component struct {
  2579. Name string `key:"name"`
  2580. Discovery discovery `key:"discovery,inherit"`
  2581. }
  2582. server struct {
  2583. Discovery discovery `key:"discovery"`
  2584. Component component `key:"component"`
  2585. }
  2586. )
  2587. var s server
  2588. assert.NoError(t, UnmarshalKey(map[string]interface{}{
  2589. "discovery": map[string]interface{}{
  2590. "host": "localhost",
  2591. "port": 8080,
  2592. },
  2593. "component": map[string]interface{}{
  2594. "name": "test",
  2595. "discovery": map[string]interface{}{
  2596. "port": 8888,
  2597. },
  2598. },
  2599. }, &s))
  2600. assert.Equal(t, "localhost", s.Discovery.Host)
  2601. assert.Equal(t, 8080, s.Discovery.Port)
  2602. assert.Equal(t, "localhost", s.Component.Discovery.Host)
  2603. assert.Equal(t, 8888, s.Component.Discovery.Port)
  2604. }
  2605. func TestUnmarshalInheritStructUseSelfIncorrectType(t *testing.T) {
  2606. type (
  2607. discovery struct {
  2608. Host string `key:"host"`
  2609. Port int `key:"port"`
  2610. }
  2611. component struct {
  2612. Name string `key:"name"`
  2613. Discovery discovery `key:"discovery,inherit"`
  2614. }
  2615. server struct {
  2616. Discovery discovery `key:"discovery"`
  2617. Component component `key:"component"`
  2618. }
  2619. )
  2620. var s server
  2621. assert.NotNil(t, UnmarshalKey(map[string]interface{}{
  2622. "discovery": map[string]interface{}{
  2623. "host": "localhost",
  2624. },
  2625. "component": map[string]interface{}{
  2626. "name": "test",
  2627. "discovery": map[string]string{
  2628. "host": "remotehost",
  2629. },
  2630. },
  2631. }, &s))
  2632. }
  2633. func TestUnmarshaler_InheritFromGrandparent(t *testing.T) {
  2634. type (
  2635. component struct {
  2636. Name string `key:"name"`
  2637. Discovery string `key:"discovery,inherit"`
  2638. }
  2639. middle struct {
  2640. Value component `key:"value"`
  2641. }
  2642. server struct {
  2643. Discovery string `key:"discovery"`
  2644. Middle middle `key:"middle"`
  2645. }
  2646. )
  2647. var s server
  2648. assert.NoError(t, UnmarshalKey(map[string]interface{}{
  2649. "discovery": "localhost:8080",
  2650. "middle": map[string]interface{}{
  2651. "value": map[string]interface{}{
  2652. "name": "test",
  2653. },
  2654. },
  2655. }, &s))
  2656. assert.Equal(t, "localhost:8080", s.Discovery)
  2657. assert.Equal(t, "localhost:8080", s.Middle.Value.Discovery)
  2658. }
  2659. func TestUnmarshaler_InheritSequence(t *testing.T) {
  2660. var testConf = []byte(`
  2661. Nacos:
  2662. NamespaceId: "123"
  2663. RpcConf:
  2664. Nacos:
  2665. NamespaceId: "456"
  2666. Name: hello
  2667. `)
  2668. type (
  2669. NacosConf struct {
  2670. NamespaceId string
  2671. }
  2672. RpcConf struct {
  2673. Nacos NacosConf `json:",inherit"`
  2674. Name string
  2675. }
  2676. Config1 struct {
  2677. RpcConf RpcConf
  2678. Nacos NacosConf
  2679. }
  2680. Config2 struct {
  2681. RpcConf RpcConf
  2682. Nacos NacosConf
  2683. }
  2684. )
  2685. var c1 Config1
  2686. assert.NoError(t, UnmarshalYamlBytes(testConf, &c1))
  2687. assert.Equal(t, "123", c1.Nacos.NamespaceId)
  2688. assert.Equal(t, "456", c1.RpcConf.Nacos.NamespaceId)
  2689. var c2 Config2
  2690. assert.NoError(t, UnmarshalYamlBytes(testConf, &c2))
  2691. assert.Equal(t, "123", c1.Nacos.NamespaceId)
  2692. assert.Equal(t, "456", c1.RpcConf.Nacos.NamespaceId)
  2693. }
  2694. func TestUnmarshaler_InheritNested(t *testing.T) {
  2695. var testConf = []byte(`
  2696. Nacos:
  2697. Value1: "123"
  2698. Server:
  2699. Nacos:
  2700. Value2: "456"
  2701. Rpc:
  2702. Nacos:
  2703. Value3: "789"
  2704. Name: hello
  2705. `)
  2706. type (
  2707. NacosConf struct {
  2708. Value1 string `json:",optional"`
  2709. Value2 string `json:",optional"`
  2710. Value3 string `json:",optional"`
  2711. }
  2712. RpcConf struct {
  2713. Nacos NacosConf `json:",inherit"`
  2714. Name string
  2715. }
  2716. ServerConf struct {
  2717. Nacos NacosConf `json:",inherit"`
  2718. Rpc RpcConf
  2719. }
  2720. Config struct {
  2721. Server ServerConf
  2722. Nacos NacosConf
  2723. }
  2724. )
  2725. var c Config
  2726. assert.NoError(t, UnmarshalYamlBytes(testConf, &c))
  2727. assert.Equal(t, "123", c.Nacos.Value1)
  2728. assert.Empty(t, c.Nacos.Value2)
  2729. assert.Empty(t, c.Nacos.Value3)
  2730. assert.Equal(t, "123", c.Server.Nacos.Value1)
  2731. assert.Equal(t, "456", c.Server.Nacos.Value2)
  2732. assert.Empty(t, c.Nacos.Value3)
  2733. assert.Equal(t, "123", c.Server.Rpc.Nacos.Value1)
  2734. assert.Equal(t, "456", c.Server.Rpc.Nacos.Value2)
  2735. assert.Equal(t, "789", c.Server.Rpc.Nacos.Value3)
  2736. }
  2737. func TestUnmarshalValuer(t *testing.T) {
  2738. unmarshaler := NewUnmarshaler(jsonTagKey)
  2739. var foo string
  2740. err := unmarshaler.UnmarshalValuer(nil, foo)
  2741. assert.NotNil(t, err)
  2742. }
  2743. func TestUnmarshal_EnvString(t *testing.T) {
  2744. type Value struct {
  2745. Name string `key:"name,env=TEST_NAME_STRING"`
  2746. }
  2747. const (
  2748. envName = "TEST_NAME_STRING"
  2749. envVal = "this is a name"
  2750. )
  2751. os.Setenv(envName, envVal)
  2752. defer os.Unsetenv(envName)
  2753. var v Value
  2754. assert.NoError(t, UnmarshalKey(emptyMap, &v))
  2755. assert.Equal(t, envVal, v.Name)
  2756. }
  2757. func TestUnmarshal_EnvStringOverwrite(t *testing.T) {
  2758. type Value struct {
  2759. Name string `key:"name,env=TEST_NAME_STRING"`
  2760. }
  2761. const (
  2762. envName = "TEST_NAME_STRING"
  2763. envVal = "this is a name"
  2764. )
  2765. os.Setenv(envName, envVal)
  2766. defer os.Unsetenv(envName)
  2767. var v Value
  2768. assert.NoError(t, UnmarshalKey(map[string]interface{}{
  2769. "name": "local value",
  2770. }, &v))
  2771. assert.Equal(t, envVal, v.Name)
  2772. }
  2773. func TestUnmarshal_EnvInt(t *testing.T) {
  2774. type Value struct {
  2775. Age int `key:"age,env=TEST_NAME_INT"`
  2776. }
  2777. const envName = "TEST_NAME_INT"
  2778. os.Setenv(envName, "123")
  2779. defer os.Unsetenv(envName)
  2780. var v Value
  2781. assert.NoError(t, UnmarshalKey(emptyMap, &v))
  2782. assert.Equal(t, 123, v.Age)
  2783. }
  2784. func TestUnmarshal_EnvIntOverwrite(t *testing.T) {
  2785. type Value struct {
  2786. Age int `key:"age,env=TEST_NAME_INT"`
  2787. }
  2788. const envName = "TEST_NAME_INT"
  2789. os.Setenv(envName, "123")
  2790. defer os.Unsetenv(envName)
  2791. var v Value
  2792. assert.NoError(t, UnmarshalKey(map[string]interface{}{
  2793. "age": 18,
  2794. }, &v))
  2795. assert.Equal(t, 123, v.Age)
  2796. }
  2797. func TestUnmarshal_EnvFloat(t *testing.T) {
  2798. type Value struct {
  2799. Age float32 `key:"name,env=TEST_NAME_FLOAT"`
  2800. }
  2801. const envName = "TEST_NAME_FLOAT"
  2802. os.Setenv(envName, "123.45")
  2803. defer os.Unsetenv(envName)
  2804. var v Value
  2805. assert.NoError(t, UnmarshalKey(emptyMap, &v))
  2806. assert.Equal(t, float32(123.45), v.Age)
  2807. }
  2808. func TestUnmarshal_EnvFloatOverwrite(t *testing.T) {
  2809. type Value struct {
  2810. Age float32 `key:"age,env=TEST_NAME_FLOAT"`
  2811. }
  2812. const envName = "TEST_NAME_FLOAT"
  2813. os.Setenv(envName, "123.45")
  2814. defer os.Unsetenv(envName)
  2815. var v Value
  2816. assert.NoError(t, UnmarshalKey(map[string]interface{}{
  2817. "age": 18.5,
  2818. }, &v))
  2819. assert.Equal(t, float32(123.45), v.Age)
  2820. }
  2821. func TestUnmarshal_EnvBoolTrue(t *testing.T) {
  2822. type Value struct {
  2823. Enable bool `key:"enable,env=TEST_NAME_BOOL_TRUE"`
  2824. }
  2825. const envName = "TEST_NAME_BOOL_TRUE"
  2826. os.Setenv(envName, "true")
  2827. defer os.Unsetenv(envName)
  2828. var v Value
  2829. assert.NoError(t, UnmarshalKey(emptyMap, &v))
  2830. assert.True(t, v.Enable)
  2831. }
  2832. func TestUnmarshal_EnvBoolFalse(t *testing.T) {
  2833. type Value struct {
  2834. Enable bool `key:"enable,env=TEST_NAME_BOOL_FALSE"`
  2835. }
  2836. const envName = "TEST_NAME_BOOL_FALSE"
  2837. os.Setenv(envName, "false")
  2838. defer os.Unsetenv(envName)
  2839. var v Value
  2840. assert.NoError(t, UnmarshalKey(emptyMap, &v))
  2841. assert.False(t, v.Enable)
  2842. }
  2843. func TestUnmarshal_EnvBoolBad(t *testing.T) {
  2844. type Value struct {
  2845. Enable bool `key:"enable,env=TEST_NAME_BOOL_BAD"`
  2846. }
  2847. const envName = "TEST_NAME_BOOL_BAD"
  2848. os.Setenv(envName, "bad")
  2849. defer os.Unsetenv(envName)
  2850. var v Value
  2851. assert.Error(t, UnmarshalKey(emptyMap, &v))
  2852. }
  2853. func TestUnmarshal_EnvDuration(t *testing.T) {
  2854. type Value struct {
  2855. Duration time.Duration `key:"duration,env=TEST_NAME_DURATION"`
  2856. }
  2857. const envName = "TEST_NAME_DURATION"
  2858. os.Setenv(envName, "1s")
  2859. defer os.Unsetenv(envName)
  2860. var v Value
  2861. assert.NoError(t, UnmarshalKey(emptyMap, &v))
  2862. assert.Equal(t, time.Second, v.Duration)
  2863. }
  2864. func TestUnmarshal_EnvDurationBadValue(t *testing.T) {
  2865. type Value struct {
  2866. Duration time.Duration `key:"duration,env=TEST_NAME_BAD_DURATION"`
  2867. }
  2868. const envName = "TEST_NAME_BAD_DURATION"
  2869. os.Setenv(envName, "bad")
  2870. defer os.Unsetenv(envName)
  2871. var v Value
  2872. assert.NotNil(t, UnmarshalKey(emptyMap, &v))
  2873. }
  2874. func TestUnmarshal_EnvWithOptions(t *testing.T) {
  2875. type Value struct {
  2876. Name string `key:"name,env=TEST_NAME_ENV_OPTIONS_MATCH,options=[abc,123,xyz]"`
  2877. }
  2878. const (
  2879. envName = "TEST_NAME_ENV_OPTIONS_MATCH"
  2880. envVal = "123"
  2881. )
  2882. os.Setenv(envName, envVal)
  2883. defer os.Unsetenv(envName)
  2884. var v Value
  2885. assert.NoError(t, UnmarshalKey(emptyMap, &v))
  2886. assert.Equal(t, envVal, v.Name)
  2887. }
  2888. func TestUnmarshal_EnvWithOptionsWrongValueBool(t *testing.T) {
  2889. type Value struct {
  2890. Enable bool `key:"enable,env=TEST_NAME_ENV_OPTIONS_BOOL,options=[true]"`
  2891. }
  2892. const (
  2893. envName = "TEST_NAME_ENV_OPTIONS_BOOL"
  2894. envVal = "false"
  2895. )
  2896. os.Setenv(envName, envVal)
  2897. defer os.Unsetenv(envName)
  2898. var v Value
  2899. assert.Error(t, UnmarshalKey(emptyMap, &v))
  2900. }
  2901. func TestUnmarshal_EnvWithOptionsWrongValueDuration(t *testing.T) {
  2902. type Value struct {
  2903. Duration time.Duration `key:"duration,env=TEST_NAME_ENV_OPTIONS_DURATION,options=[1s,2s,3s]"`
  2904. }
  2905. const (
  2906. envName = "TEST_NAME_ENV_OPTIONS_DURATION"
  2907. envVal = "4s"
  2908. )
  2909. os.Setenv(envName, envVal)
  2910. defer os.Unsetenv(envName)
  2911. var v Value
  2912. assert.Error(t, UnmarshalKey(emptyMap, &v))
  2913. }
  2914. func TestUnmarshal_EnvWithOptionsWrongValueNumber(t *testing.T) {
  2915. type Value struct {
  2916. Age int `key:"age,env=TEST_NAME_ENV_OPTIONS_AGE,options=[18,19,20]"`
  2917. }
  2918. const (
  2919. envName = "TEST_NAME_ENV_OPTIONS_AGE"
  2920. envVal = "30"
  2921. )
  2922. os.Setenv(envName, envVal)
  2923. defer os.Unsetenv(envName)
  2924. var v Value
  2925. assert.Error(t, UnmarshalKey(emptyMap, &v))
  2926. }
  2927. func TestUnmarshal_EnvWithOptionsWrongValueString(t *testing.T) {
  2928. type Value struct {
  2929. Name string `key:"name,env=TEST_NAME_ENV_OPTIONS_STRING,options=[abc,123,xyz]"`
  2930. }
  2931. const (
  2932. envName = "TEST_NAME_ENV_OPTIONS_STRING"
  2933. envVal = "this is a name"
  2934. )
  2935. os.Setenv(envName, envVal)
  2936. defer os.Unsetenv(envName)
  2937. var v Value
  2938. assert.Error(t, UnmarshalKey(emptyMap, &v))
  2939. }
  2940. func TestUnmarshalJsonReaderMultiArray(t *testing.T) {
  2941. payload := `{"a": "133", "b": [["add", "cccd"], ["eeee"]]}`
  2942. var res struct {
  2943. A string `json:"a"`
  2944. B [][]string `json:"b"`
  2945. }
  2946. reader := strings.NewReader(payload)
  2947. err := UnmarshalJsonReader(reader, &res)
  2948. assert.Nil(t, err)
  2949. assert.Equal(t, 2, len(res.B))
  2950. }
  2951. func TestUnmarshalJsonReaderPtrMultiArrayString(t *testing.T) {
  2952. payload := `{"a": "133", "b": [["add", "cccd"], ["eeee"]]}`
  2953. var res struct {
  2954. A string `json:"a"`
  2955. B [][]*string `json:"b"`
  2956. }
  2957. reader := strings.NewReader(payload)
  2958. err := UnmarshalJsonReader(reader, &res)
  2959. assert.Nil(t, err)
  2960. assert.Equal(t, 2, len(res.B))
  2961. assert.Equal(t, 2, len(res.B[0]))
  2962. }
  2963. func TestUnmarshalJsonReaderPtrMultiArrayString_Int(t *testing.T) {
  2964. payload := `{"a": "133", "b": [[11, 22], [33]]}`
  2965. var res struct {
  2966. A string `json:"a"`
  2967. B [][]*string `json:"b"`
  2968. }
  2969. reader := strings.NewReader(payload)
  2970. err := UnmarshalJsonReader(reader, &res)
  2971. assert.Nil(t, err)
  2972. assert.Equal(t, 2, len(res.B))
  2973. assert.Equal(t, 2, len(res.B[0]))
  2974. }
  2975. func TestUnmarshalJsonReaderPtrMultiArrayInt(t *testing.T) {
  2976. payload := `{"a": "133", "b": [[11, 22], [33]]}`
  2977. var res struct {
  2978. A string `json:"a"`
  2979. B [][]*int `json:"b"`
  2980. }
  2981. reader := strings.NewReader(payload)
  2982. err := UnmarshalJsonReader(reader, &res)
  2983. assert.Nil(t, err)
  2984. assert.Equal(t, 2, len(res.B))
  2985. assert.Equal(t, 2, len(res.B[0]))
  2986. }
  2987. func TestUnmarshalJsonReaderPtrArray(t *testing.T) {
  2988. payload := `{"a": "133", "b": ["add", "cccd", "eeee"]}`
  2989. var res struct {
  2990. A string `json:"a"`
  2991. B []*string `json:"b"`
  2992. }
  2993. reader := strings.NewReader(payload)
  2994. err := UnmarshalJsonReader(reader, &res)
  2995. assert.Nil(t, err)
  2996. assert.Equal(t, 3, len(res.B))
  2997. }
  2998. func TestUnmarshalJsonReaderPtrArray_Int(t *testing.T) {
  2999. payload := `{"a": "133", "b": [11, 22, 33]}`
  3000. var res struct {
  3001. A string `json:"a"`
  3002. B []*string `json:"b"`
  3003. }
  3004. reader := strings.NewReader(payload)
  3005. err := UnmarshalJsonReader(reader, &res)
  3006. assert.Nil(t, err)
  3007. assert.Equal(t, 3, len(res.B))
  3008. }
  3009. func TestUnmarshalJsonReaderPtrInt(t *testing.T) {
  3010. payload := `{"a": "133", "b": [11, 22, 33]}`
  3011. var res struct {
  3012. A string `json:"a"`
  3013. B []*string `json:"b"`
  3014. }
  3015. reader := strings.NewReader(payload)
  3016. err := UnmarshalJsonReader(reader, &res)
  3017. assert.Nil(t, err)
  3018. assert.Equal(t, 3, len(res.B))
  3019. }
  3020. func TestUnmarshalJsonWithoutKey(t *testing.T) {
  3021. payload := `{"A": "1", "B": "2"}`
  3022. var res struct {
  3023. A string `json:""`
  3024. B string `json:","`
  3025. }
  3026. reader := strings.NewReader(payload)
  3027. err := UnmarshalJsonReader(reader, &res)
  3028. assert.Nil(t, err)
  3029. assert.Equal(t, "1", res.A)
  3030. assert.Equal(t, "2", res.B)
  3031. }
  3032. func TestUnmarshalJsonUintNegative(t *testing.T) {
  3033. payload := `{"a": -1}`
  3034. var res struct {
  3035. A uint `json:"a"`
  3036. }
  3037. reader := strings.NewReader(payload)
  3038. err := UnmarshalJsonReader(reader, &res)
  3039. assert.NotNil(t, err)
  3040. }
  3041. func TestUnmarshalJsonDefinedInt(t *testing.T) {
  3042. type Int int
  3043. var res struct {
  3044. A Int `json:"a"`
  3045. }
  3046. payload := `{"a": -1}`
  3047. reader := strings.NewReader(payload)
  3048. err := UnmarshalJsonReader(reader, &res)
  3049. assert.Nil(t, err)
  3050. assert.Equal(t, Int(-1), res.A)
  3051. }
  3052. func TestUnmarshalJsonDefinedString(t *testing.T) {
  3053. type String string
  3054. var res struct {
  3055. A String `json:"a"`
  3056. }
  3057. payload := `{"a": "foo"}`
  3058. reader := strings.NewReader(payload)
  3059. err := UnmarshalJsonReader(reader, &res)
  3060. assert.Nil(t, err)
  3061. assert.Equal(t, String("foo"), res.A)
  3062. }
  3063. func TestUnmarshalJsonDefinedStringPtr(t *testing.T) {
  3064. type String string
  3065. var res struct {
  3066. A *String `json:"a"`
  3067. }
  3068. payload := `{"a": "foo"}`
  3069. reader := strings.NewReader(payload)
  3070. err := UnmarshalJsonReader(reader, &res)
  3071. assert.Nil(t, err)
  3072. assert.Equal(t, String("foo"), *res.A)
  3073. }
  3074. func TestUnmarshalJsonReaderComplex(t *testing.T) {
  3075. type (
  3076. MyInt int
  3077. MyTxt string
  3078. MyTxtArray []string
  3079. Req struct {
  3080. MyInt MyInt `json:"my_int"` // int.. ok
  3081. MyTxtArray MyTxtArray `json:"my_txt_array"`
  3082. MyTxt MyTxt `json:"my_txt"` // but string is not assignable
  3083. Int int `json:"int"`
  3084. Txt string `json:"txt"`
  3085. }
  3086. )
  3087. body := `{
  3088. "my_int": 100,
  3089. "my_txt_array": [
  3090. "a",
  3091. "b"
  3092. ],
  3093. "my_txt": "my_txt",
  3094. "int": 200,
  3095. "txt": "txt"
  3096. }`
  3097. var req Req
  3098. err := UnmarshalJsonReader(strings.NewReader(body), &req)
  3099. assert.Nil(t, err)
  3100. assert.Equal(t, MyInt(100), req.MyInt)
  3101. assert.Equal(t, MyTxt("my_txt"), req.MyTxt)
  3102. assert.EqualValues(t, MyTxtArray([]string{"a", "b"}), req.MyTxtArray)
  3103. assert.Equal(t, 200, req.Int)
  3104. assert.Equal(t, "txt", req.Txt)
  3105. }
  3106. func TestUnmarshalJsonReaderArrayBool(t *testing.T) {
  3107. payload := `{"id": false}`
  3108. var res struct {
  3109. ID []string `json:"id"`
  3110. }
  3111. reader := strings.NewReader(payload)
  3112. err := UnmarshalJsonReader(reader, &res)
  3113. assert.NotNil(t, err)
  3114. }
  3115. func TestUnmarshalJsonReaderArrayInt(t *testing.T) {
  3116. payload := `{"id": 123}`
  3117. var res struct {
  3118. ID []string `json:"id"`
  3119. }
  3120. reader := strings.NewReader(payload)
  3121. err := UnmarshalJsonReader(reader, &res)
  3122. assert.NotNil(t, err)
  3123. }
  3124. func TestUnmarshalJsonReaderArrayString(t *testing.T) {
  3125. payload := `{"id": "123"}`
  3126. var res struct {
  3127. ID []string `json:"id"`
  3128. }
  3129. reader := strings.NewReader(payload)
  3130. err := UnmarshalJsonReader(reader, &res)
  3131. assert.NotNil(t, err)
  3132. }
  3133. func TestGoogleUUID(t *testing.T) {
  3134. var val struct {
  3135. Uid uuid.UUID `json:"uid,optional"`
  3136. Uidp *uuid.UUID `json:"uidp,optional"`
  3137. }
  3138. assert.NoError(t, UnmarshalJsonBytes([]byte(`{
  3139. "uid": "6ba7b810-9dad-11d1-80b4-00c04fd430c8",
  3140. "uidp": "6ba7b810-9dad-11d1-80b4-00c04fd430c9"}`), &val))
  3141. assert.Equal(t, "6ba7b810-9dad-11d1-80b4-00c04fd430c8", val.Uid.String())
  3142. assert.Equal(t, "6ba7b810-9dad-11d1-80b4-00c04fd430c9", val.Uidp.String())
  3143. assert.NoError(t, UnmarshalJsonMap(map[string]interface{}{
  3144. "uid": []byte("6ba7b810-9dad-11d1-80b4-00c04fd430c1"),
  3145. "uidp": []byte("6ba7b810-9dad-11d1-80b4-00c04fd430c2"),
  3146. }, &val))
  3147. assert.Equal(t, "6ba7b810-9dad-11d1-80b4-00c04fd430c1", val.Uid.String())
  3148. assert.Equal(t, "6ba7b810-9dad-11d1-80b4-00c04fd430c2", val.Uidp.String())
  3149. }
  3150. func BenchmarkDefaultValue(b *testing.B) {
  3151. for i := 0; i < b.N; i++ {
  3152. var a struct {
  3153. Ints []int `json:"ints,default=[1,2,3]"`
  3154. Strs []string `json:"strs,default=[foo,bar,baz]"`
  3155. }
  3156. _ = UnmarshalJsonMap(nil, &a)
  3157. if len(a.Strs) != 3 || len(a.Ints) != 3 {
  3158. b.Fatal("failed")
  3159. }
  3160. }
  3161. }
  3162. func BenchmarkUnmarshalString(b *testing.B) {
  3163. type inner struct {
  3164. Value string `key:"value"`
  3165. }
  3166. m := map[string]interface{}{
  3167. "value": "first",
  3168. }
  3169. for i := 0; i < b.N; i++ {
  3170. var in inner
  3171. if err := UnmarshalKey(m, &in); err != nil {
  3172. b.Fatal(err)
  3173. }
  3174. }
  3175. }
  3176. func BenchmarkUnmarshalStruct(b *testing.B) {
  3177. b.ReportAllocs()
  3178. m := map[string]interface{}{
  3179. "Ids": []map[string]interface{}{
  3180. {
  3181. "First": 1,
  3182. "Second": 2,
  3183. },
  3184. },
  3185. }
  3186. for i := 0; i < b.N; i++ {
  3187. var v struct {
  3188. Ids []struct {
  3189. First int
  3190. Second int
  3191. }
  3192. }
  3193. if err := UnmarshalKey(m, &v); err != nil {
  3194. b.Fatal(err)
  3195. }
  3196. }
  3197. }
  3198. func BenchmarkMapToStruct(b *testing.B) {
  3199. data := map[string]interface{}{
  3200. "valid": "1",
  3201. "age": "5",
  3202. "name": "liao",
  3203. }
  3204. type anonymous struct {
  3205. Valid bool
  3206. Age int
  3207. Name string
  3208. }
  3209. for i := 0; i < b.N; i++ {
  3210. var an anonymous
  3211. if valid, ok := data["valid"]; ok {
  3212. an.Valid = valid == "1"
  3213. }
  3214. if age, ok := data["age"]; ok {
  3215. ages, _ := age.(string)
  3216. an.Age, _ = strconv.Atoi(ages)
  3217. }
  3218. if name, ok := data["name"]; ok {
  3219. names, _ := name.(string)
  3220. an.Name = names
  3221. }
  3222. }
  3223. }
  3224. func BenchmarkUnmarshal(b *testing.B) {
  3225. data := map[string]interface{}{
  3226. "valid": "1",
  3227. "age": "5",
  3228. "name": "liao",
  3229. }
  3230. type anonymous struct {
  3231. Valid bool `key:"valid,string"`
  3232. Age int `key:"age,string"`
  3233. Name string `key:"name"`
  3234. }
  3235. for i := 0; i < b.N; i++ {
  3236. var an anonymous
  3237. UnmarshalKey(data, &an)
  3238. }
  3239. }