unmarshaler_test.go 85 KB

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