unmarshaler_test.go 94 KB

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