unmarshaler_test.go 82 KB

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