unmarshaler_test.go 86 KB

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