unmarshaler_test.go 119 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655
  1. package mapping
  2. import (
  3. "encoding/json"
  4. "fmt"
  5. "reflect"
  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 TestUnmarshalWithLowerField(t *testing.T) {
  49. type (
  50. Lower struct {
  51. value int `key:"lower"`
  52. }
  53. inner struct {
  54. Lower
  55. Optional bool `key:",optional"`
  56. }
  57. )
  58. m := map[string]any{
  59. "Optional": true,
  60. "lower": 1,
  61. }
  62. var in inner
  63. if assert.NoError(t, UnmarshalKey(m, &in)) {
  64. assert.True(t, in.Optional)
  65. assert.Equal(t, 0, in.value)
  66. }
  67. }
  68. func TestUnmarshalWithLowerAnonymousStruct(t *testing.T) {
  69. type (
  70. lower struct {
  71. Value int `key:"lower"`
  72. }
  73. inner struct {
  74. lower
  75. Optional bool `key:",optional"`
  76. }
  77. )
  78. m := map[string]any{
  79. "Optional": true,
  80. "lower": 1,
  81. }
  82. var in inner
  83. if assert.NoError(t, UnmarshalKey(m, &in)) {
  84. assert.True(t, in.Optional)
  85. assert.Equal(t, 1, in.Value)
  86. }
  87. }
  88. func TestUnmarshalWithoutTagNameWithCanonicalKey(t *testing.T) {
  89. type inner struct {
  90. Name string `key:"name"`
  91. }
  92. m := map[string]any{
  93. "Name": "go-zero",
  94. }
  95. var in inner
  96. unmarshaler := NewUnmarshaler(defaultKeyName, WithCanonicalKeyFunc(func(s string) string {
  97. first := true
  98. return strings.Map(func(r rune) rune {
  99. if first {
  100. first = false
  101. return unicode.ToTitle(r)
  102. }
  103. return r
  104. }, s)
  105. }))
  106. if assert.NoError(t, unmarshaler.Unmarshal(m, &in)) {
  107. assert.Equal(t, "go-zero", in.Name)
  108. }
  109. }
  110. func TestUnmarshalWithoutTagNameWithCanonicalKeyOptionalDep(t *testing.T) {
  111. type inner struct {
  112. FirstName string `key:",optional"`
  113. LastName string `key:",optional=FirstName"`
  114. }
  115. m := map[string]any{
  116. "firstname": "go",
  117. "lastname": "zero",
  118. }
  119. var in inner
  120. unmarshaler := NewUnmarshaler(defaultKeyName, WithCanonicalKeyFunc(func(s string) string {
  121. return strings.ToLower(s)
  122. }))
  123. if assert.NoError(t, unmarshaler.Unmarshal(m, &in)) {
  124. assert.Equal(t, "go", in.FirstName)
  125. assert.Equal(t, "zero", in.LastName)
  126. }
  127. }
  128. func TestUnmarshalBool(t *testing.T) {
  129. type inner struct {
  130. True bool `key:"yes"`
  131. False bool `key:"no"`
  132. TrueFromOne bool `key:"yesone,string"`
  133. FalseFromZero bool `key:"nozero,string"`
  134. TrueFromTrue bool `key:"yestrue,string"`
  135. FalseFromFalse bool `key:"nofalse,string"`
  136. DefaultTrue bool `key:"defaulttrue,default=1"`
  137. Optional bool `key:"optional,optional"`
  138. }
  139. m := map[string]any{
  140. "yes": true,
  141. "no": false,
  142. "yesone": "1",
  143. "nozero": "0",
  144. "yestrue": "true",
  145. "nofalse": "false",
  146. }
  147. var in inner
  148. ast := assert.New(t)
  149. if ast.NoError(UnmarshalKey(m, &in)) {
  150. ast.True(in.True)
  151. ast.False(in.False)
  152. ast.True(in.TrueFromOne)
  153. ast.False(in.FalseFromZero)
  154. ast.True(in.TrueFromTrue)
  155. ast.False(in.FalseFromFalse)
  156. ast.True(in.DefaultTrue)
  157. }
  158. }
  159. func TestUnmarshalDuration(t *testing.T) {
  160. type inner struct {
  161. Duration time.Duration `key:"duration"`
  162. LessDuration time.Duration `key:"less"`
  163. MoreDuration time.Duration `key:"more"`
  164. PtrDuration *time.Duration `key:"ptr"`
  165. PtrPtrDuration **time.Duration `key:"ptrptr"`
  166. }
  167. m := map[string]any{
  168. "duration": "5s",
  169. "less": "100ms",
  170. "more": "24h",
  171. "ptr": "1h",
  172. "ptrptr": "2h",
  173. }
  174. var in inner
  175. if assert.NoError(t, UnmarshalKey(m, &in)) {
  176. assert.Equal(t, time.Second*5, in.Duration)
  177. assert.Equal(t, time.Millisecond*100, in.LessDuration)
  178. assert.Equal(t, time.Hour*24, in.MoreDuration)
  179. assert.Equal(t, time.Hour, *in.PtrDuration)
  180. assert.Equal(t, time.Hour*2, **in.PtrPtrDuration)
  181. }
  182. }
  183. func TestUnmarshalDurationDefault(t *testing.T) {
  184. type inner struct {
  185. Int int `key:"int"`
  186. Duration time.Duration `key:"duration,default=5s"`
  187. }
  188. m := map[string]any{
  189. "int": 5,
  190. }
  191. var in inner
  192. if assert.NoError(t, UnmarshalKey(m, &in)) {
  193. assert.Equal(t, 5, in.Int)
  194. assert.Equal(t, time.Second*5, in.Duration)
  195. }
  196. }
  197. func TestUnmarshalDurationPtr(t *testing.T) {
  198. type inner struct {
  199. Duration *time.Duration `key:"duration"`
  200. }
  201. m := map[string]any{
  202. "duration": "5s",
  203. }
  204. var in inner
  205. if assert.NoError(t, UnmarshalKey(m, &in)) {
  206. assert.Equal(t, time.Second*5, *in.Duration)
  207. }
  208. }
  209. func TestUnmarshalDurationPtrDefault(t *testing.T) {
  210. type inner struct {
  211. Int int `key:"int"`
  212. Value *int `key:",default=5"`
  213. Duration *time.Duration `key:"duration,default=5s"`
  214. }
  215. m := map[string]any{
  216. "int": 5,
  217. }
  218. var in inner
  219. if assert.NoError(t, UnmarshalKey(m, &in)) {
  220. assert.Equal(t, 5, in.Int)
  221. assert.Equal(t, 5, *in.Value)
  222. assert.Equal(t, time.Second*5, *in.Duration)
  223. }
  224. }
  225. func TestUnmarshalInt(t *testing.T) {
  226. type inner struct {
  227. Int int `key:"int"`
  228. IntFromStr int `key:"intstr,string"`
  229. Int8 int8 `key:"int8"`
  230. Int8FromStr int8 `key:"int8str,string"`
  231. Int16 int16 `key:"int16"`
  232. Int16FromStr int16 `key:"int16str,string"`
  233. Int32 int32 `key:"int32"`
  234. Int32FromStr int32 `key:"int32str,string"`
  235. Int64 int64 `key:"int64"`
  236. Int64FromStr int64 `key:"int64str,string"`
  237. DefaultInt int64 `key:"defaultint,default=11"`
  238. Optional int `key:"optional,optional"`
  239. }
  240. m := map[string]any{
  241. "int": 1,
  242. "intstr": "2",
  243. "int8": int8(3),
  244. "int8str": "4",
  245. "int16": int16(5),
  246. "int16str": "6",
  247. "int32": int32(7),
  248. "int32str": "8",
  249. "int64": int64(9),
  250. "int64str": "10",
  251. }
  252. var in inner
  253. ast := assert.New(t)
  254. if ast.NoError(UnmarshalKey(m, &in)) {
  255. ast.Equal(1, in.Int)
  256. ast.Equal(2, in.IntFromStr)
  257. ast.Equal(int8(3), in.Int8)
  258. ast.Equal(int8(4), in.Int8FromStr)
  259. ast.Equal(int16(5), in.Int16)
  260. ast.Equal(int16(6), in.Int16FromStr)
  261. ast.Equal(int32(7), in.Int32)
  262. ast.Equal(int32(8), in.Int32FromStr)
  263. ast.Equal(int64(9), in.Int64)
  264. ast.Equal(int64(10), in.Int64FromStr)
  265. ast.Equal(int64(11), in.DefaultInt)
  266. }
  267. }
  268. func TestUnmarshalIntPtr(t *testing.T) {
  269. type inner struct {
  270. Int *int `key:"int"`
  271. }
  272. m := map[string]any{
  273. "int": 1,
  274. }
  275. var in inner
  276. if assert.NoError(t, UnmarshalKey(m, &in)) {
  277. assert.NotNil(t, in.Int)
  278. assert.Equal(t, 1, *in.Int)
  279. }
  280. }
  281. func TestUnmarshalIntSliceOfPtr(t *testing.T) {
  282. t.Run("int slice", func(t *testing.T) {
  283. type inner struct {
  284. Ints []*int `key:"ints"`
  285. Intps []**int `key:"intps"`
  286. }
  287. m := map[string]any{
  288. "ints": []int{1, 2, 3},
  289. "intps": []int{1, 2, 3, 4},
  290. }
  291. var in inner
  292. if assert.NoError(t, UnmarshalKey(m, &in)) {
  293. assert.NotEmpty(t, in.Ints)
  294. var ints []int
  295. for _, i := range in.Ints {
  296. ints = append(ints, *i)
  297. }
  298. assert.EqualValues(t, []int{1, 2, 3}, ints)
  299. var intps []int
  300. for _, i := range in.Intps {
  301. intps = append(intps, **i)
  302. }
  303. assert.EqualValues(t, []int{1, 2, 3, 4}, intps)
  304. }
  305. })
  306. t.Run("int slice with error", func(t *testing.T) {
  307. type inner struct {
  308. Ints []*int `key:"ints"`
  309. Intps []**int `key:"intps"`
  310. }
  311. m := map[string]any{
  312. "ints": []any{1, 2, "a"},
  313. "intps": []int{1, 2, 3, 4},
  314. }
  315. var in inner
  316. assert.Error(t, UnmarshalKey(m, &in))
  317. })
  318. t.Run("int slice with nil", func(t *testing.T) {
  319. type inner struct {
  320. Ints []int `key:"ints"`
  321. }
  322. m := map[string]any{
  323. "ints": []any{nil},
  324. }
  325. var in inner
  326. if assert.NoError(t, UnmarshalKey(m, &in)) {
  327. assert.Empty(t, in.Ints)
  328. }
  329. })
  330. }
  331. func TestUnmarshalIntWithDefault(t *testing.T) {
  332. type inner struct {
  333. Int int `key:"int,default=5"`
  334. Intp *int `key:"intp,default=5"`
  335. Intpp **int `key:"intpp,default=5"`
  336. }
  337. m := map[string]any{
  338. "int": 1,
  339. "intp": 2,
  340. "intpp": 3,
  341. }
  342. var in inner
  343. if assert.NoError(t, UnmarshalKey(m, &in)) {
  344. assert.Equal(t, 1, in.Int)
  345. assert.Equal(t, 2, *in.Intp)
  346. assert.Equal(t, 3, **in.Intpp)
  347. }
  348. }
  349. func TestUnmarshalIntWithString(t *testing.T) {
  350. t.Run("int without options", func(t *testing.T) {
  351. type inner struct {
  352. Int int64 `key:"int,string"`
  353. Intp *int64 `key:"intp,string"`
  354. Intpp **int64 `key:"intpp,string"`
  355. }
  356. m := map[string]any{
  357. "int": json.Number("1"),
  358. "intp": json.Number("2"),
  359. "intpp": json.Number("3"),
  360. }
  361. var in inner
  362. if assert.NoError(t, UnmarshalKey(m, &in)) {
  363. assert.Equal(t, int64(1), in.Int)
  364. assert.Equal(t, int64(2), *in.Intp)
  365. assert.Equal(t, int64(3), **in.Intpp)
  366. }
  367. })
  368. t.Run("int wrong range", func(t *testing.T) {
  369. type inner struct {
  370. Int int64 `key:"int,string,range=[2:3]"`
  371. Intp *int64 `key:"intp,range=[2:3]"`
  372. Intpp **int64 `key:"intpp,range=[2:3]"`
  373. }
  374. m := map[string]any{
  375. "int": json.Number("1"),
  376. "intp": json.Number("2"),
  377. "intpp": json.Number("3"),
  378. }
  379. var in inner
  380. assert.ErrorIs(t, UnmarshalKey(m, &in), errNumberRange)
  381. })
  382. t.Run("int with wrong type", func(t *testing.T) {
  383. type (
  384. myString string
  385. inner struct {
  386. Int int64 `key:"int,string"`
  387. Intp *int64 `key:"intp,string"`
  388. Intpp **int64 `key:"intpp,string"`
  389. }
  390. )
  391. m := map[string]any{
  392. "int": myString("1"),
  393. "intp": myString("2"),
  394. "intpp": myString("3"),
  395. }
  396. var in inner
  397. assert.Error(t, UnmarshalKey(m, &in))
  398. })
  399. t.Run("int with ptr", func(t *testing.T) {
  400. type inner struct {
  401. Int *int64 `key:"int"`
  402. }
  403. m := map[string]any{
  404. "int": json.Number("1"),
  405. }
  406. var in inner
  407. if assert.NoError(t, UnmarshalKey(m, &in)) {
  408. assert.Equal(t, int64(1), *in.Int)
  409. }
  410. })
  411. t.Run("int with invalid value", func(t *testing.T) {
  412. type inner struct {
  413. Int int64 `key:"int"`
  414. }
  415. m := map[string]any{
  416. "int": json.Number("a"),
  417. }
  418. var in inner
  419. assert.Error(t, UnmarshalKey(m, &in))
  420. })
  421. t.Run("uint with invalid value", func(t *testing.T) {
  422. type inner struct {
  423. Int uint64 `key:"int"`
  424. }
  425. m := map[string]any{
  426. "int": json.Number("a"),
  427. }
  428. var in inner
  429. assert.Error(t, UnmarshalKey(m, &in))
  430. })
  431. t.Run("float with invalid value", func(t *testing.T) {
  432. type inner struct {
  433. Value float64 `key:"float"`
  434. }
  435. m := map[string]any{
  436. "float": json.Number("a"),
  437. }
  438. var in inner
  439. assert.Error(t, UnmarshalKey(m, &in))
  440. })
  441. t.Run("float with invalid value", func(t *testing.T) {
  442. type inner struct {
  443. Value string `key:"value"`
  444. }
  445. m := map[string]any{
  446. "value": json.Number("a"),
  447. }
  448. var in inner
  449. assert.Error(t, UnmarshalKey(m, &in))
  450. })
  451. t.Run("int with ptr of ptr", func(t *testing.T) {
  452. type inner struct {
  453. Int **int64 `key:"int"`
  454. }
  455. m := map[string]any{
  456. "int": json.Number("1"),
  457. }
  458. var in inner
  459. if assert.NoError(t, UnmarshalKey(m, &in)) {
  460. assert.Equal(t, int64(1), **in.Int)
  461. }
  462. })
  463. t.Run("int with options", func(t *testing.T) {
  464. type inner struct {
  465. Int int64 `key:"int,string,options=[0,1]"`
  466. }
  467. m := map[string]any{
  468. "int": json.Number("1"),
  469. }
  470. var in inner
  471. if assert.NoError(t, UnmarshalKey(m, &in)) {
  472. assert.Equal(t, int64(1), in.Int)
  473. }
  474. })
  475. t.Run("int with options", func(t *testing.T) {
  476. type inner struct {
  477. Int int64 `key:"int,string,options=[0,1]"`
  478. }
  479. m := map[string]any{
  480. "int": nil,
  481. }
  482. var in inner
  483. assert.Error(t, UnmarshalKey(m, &in))
  484. })
  485. t.Run("int with options", func(t *testing.T) {
  486. type (
  487. StrType string
  488. inner struct {
  489. Int int64 `key:"int,string,options=[0,1]"`
  490. }
  491. )
  492. m := map[string]any{
  493. "int": StrType("1"),
  494. }
  495. var in inner
  496. assert.Error(t, UnmarshalKey(m, &in))
  497. })
  498. t.Run("invalid options", func(t *testing.T) {
  499. type Value struct {
  500. Name string `key:"name,options="`
  501. }
  502. var v Value
  503. assert.Error(t, UnmarshalKey(emptyMap, &v))
  504. })
  505. }
  506. func TestUnmarshalInt8WithOverflow(t *testing.T) {
  507. t.Run("int8 from string", func(t *testing.T) {
  508. type inner struct {
  509. Value int8 `key:"int,string"`
  510. }
  511. m := map[string]any{
  512. "int": "8589934592", // overflow
  513. }
  514. var in inner
  515. assert.Error(t, UnmarshalKey(m, &in))
  516. })
  517. t.Run("int8 from json.Number", func(t *testing.T) {
  518. type inner struct {
  519. Value int8 `key:"int"`
  520. }
  521. m := map[string]any{
  522. "int": json.Number("8589934592"), // overflow
  523. }
  524. var in inner
  525. assert.Error(t, UnmarshalKey(m, &in))
  526. })
  527. t.Run("int8 from json.Number", func(t *testing.T) {
  528. type inner struct {
  529. Value int8 `key:"int"`
  530. }
  531. m := map[string]any{
  532. "int": json.Number("-8589934592"), // overflow
  533. }
  534. var in inner
  535. assert.Error(t, UnmarshalKey(m, &in))
  536. })
  537. t.Run("int8 from int64", func(t *testing.T) {
  538. type inner struct {
  539. Value int8 `key:"int"`
  540. }
  541. m := map[string]any{
  542. "int": int64(1) << 36, // overflow
  543. }
  544. var in inner
  545. assert.Error(t, UnmarshalKey(m, &in))
  546. })
  547. }
  548. func TestUnmarshalInt16WithOverflow(t *testing.T) {
  549. t.Run("int16 from string", func(t *testing.T) {
  550. type inner struct {
  551. Value int16 `key:"int,string"`
  552. }
  553. m := map[string]any{
  554. "int": "8589934592", // overflow
  555. }
  556. var in inner
  557. assert.Error(t, UnmarshalKey(m, &in))
  558. })
  559. t.Run("int16 from json.Number", func(t *testing.T) {
  560. type inner struct {
  561. Value int16 `key:"int"`
  562. }
  563. m := map[string]any{
  564. "int": json.Number("8589934592"), // overflow
  565. }
  566. var in inner
  567. assert.Error(t, UnmarshalKey(m, &in))
  568. })
  569. t.Run("int16 from json.Number", func(t *testing.T) {
  570. type inner struct {
  571. Value int16 `key:"int"`
  572. }
  573. m := map[string]any{
  574. "int": json.Number("-8589934592"), // overflow
  575. }
  576. var in inner
  577. assert.Error(t, UnmarshalKey(m, &in))
  578. })
  579. t.Run("int16 from int64", func(t *testing.T) {
  580. type inner struct {
  581. Value int16 `key:"int"`
  582. }
  583. m := map[string]any{
  584. "int": int64(1) << 36, // overflow
  585. }
  586. var in inner
  587. assert.Error(t, UnmarshalKey(m, &in))
  588. })
  589. }
  590. func TestUnmarshalInt32WithOverflow(t *testing.T) {
  591. t.Run("int32 from string", func(t *testing.T) {
  592. type inner struct {
  593. Value int32 `key:"int,string"`
  594. }
  595. m := map[string]any{
  596. "int": "8589934592", // overflow
  597. }
  598. var in inner
  599. assert.Error(t, UnmarshalKey(m, &in))
  600. })
  601. t.Run("int32 from json.Number", func(t *testing.T) {
  602. type inner struct {
  603. Value int32 `key:"int"`
  604. }
  605. m := map[string]any{
  606. "int": json.Number("8589934592"), // overflow
  607. }
  608. var in inner
  609. assert.Error(t, UnmarshalKey(m, &in))
  610. })
  611. t.Run("int32 from json.Number", func(t *testing.T) {
  612. type inner struct {
  613. Value int32 `key:"int"`
  614. }
  615. m := map[string]any{
  616. "int": json.Number("-8589934592"), // overflow
  617. }
  618. var in inner
  619. assert.Error(t, UnmarshalKey(m, &in))
  620. })
  621. t.Run("int32 from int64", func(t *testing.T) {
  622. type inner struct {
  623. Value int32 `key:"int"`
  624. }
  625. m := map[string]any{
  626. "int": int64(1) << 36, // overflow
  627. }
  628. var in inner
  629. assert.Error(t, UnmarshalKey(m, &in))
  630. })
  631. }
  632. func TestUnmarshalUint8WithOverflow(t *testing.T) {
  633. t.Run("uint8 from string", func(t *testing.T) {
  634. type inner struct {
  635. Value uint8 `key:"int,string"`
  636. }
  637. m := map[string]any{
  638. "int": "8589934592", // overflow
  639. }
  640. var in inner
  641. assert.Error(t, UnmarshalKey(m, &in))
  642. })
  643. t.Run("uint8 from json.Number", func(t *testing.T) {
  644. type inner struct {
  645. Value uint8 `key:"int"`
  646. }
  647. m := map[string]any{
  648. "int": json.Number("8589934592"), // overflow
  649. }
  650. var in inner
  651. assert.Error(t, UnmarshalKey(m, &in))
  652. })
  653. t.Run("uint8 from json.Number", func(t *testing.T) {
  654. type inner struct {
  655. Value uint8 `key:"int"`
  656. }
  657. m := map[string]any{
  658. "int": json.Number("-1"), // overflow
  659. }
  660. var in inner
  661. assert.Error(t, UnmarshalKey(m, &in))
  662. })
  663. t.Run("uint8 from int64", func(t *testing.T) {
  664. type inner struct {
  665. Value uint8 `key:"int"`
  666. }
  667. m := map[string]any{
  668. "int": int64(1) << 36, // overflow
  669. }
  670. var in inner
  671. assert.Error(t, UnmarshalKey(m, &in))
  672. })
  673. }
  674. func TestUnmarshalUint16WithOverflow(t *testing.T) {
  675. t.Run("uint16 from string", func(t *testing.T) {
  676. type inner struct {
  677. Value uint16 `key:"int,string"`
  678. }
  679. m := map[string]any{
  680. "int": "8589934592", // overflow
  681. }
  682. var in inner
  683. assert.Error(t, UnmarshalKey(m, &in))
  684. })
  685. t.Run("uint16 from json.Number", func(t *testing.T) {
  686. type inner struct {
  687. Value uint16 `key:"int"`
  688. }
  689. m := map[string]any{
  690. "int": json.Number("8589934592"), // overflow
  691. }
  692. var in inner
  693. assert.Error(t, UnmarshalKey(m, &in))
  694. })
  695. t.Run("uint16 from json.Number", func(t *testing.T) {
  696. type inner struct {
  697. Value uint16 `key:"int"`
  698. }
  699. m := map[string]any{
  700. "int": json.Number("-1"), // overflow
  701. }
  702. var in inner
  703. assert.Error(t, UnmarshalKey(m, &in))
  704. })
  705. t.Run("uint16 from int64", func(t *testing.T) {
  706. type inner struct {
  707. Value uint16 `key:"int"`
  708. }
  709. m := map[string]any{
  710. "int": int64(1) << 36, // overflow
  711. }
  712. var in inner
  713. assert.Error(t, UnmarshalKey(m, &in))
  714. })
  715. }
  716. func TestUnmarshalUint32WithOverflow(t *testing.T) {
  717. t.Run("uint32 from string", func(t *testing.T) {
  718. type inner struct {
  719. Value uint32 `key:"int,string"`
  720. }
  721. m := map[string]any{
  722. "int": "8589934592", // overflow
  723. }
  724. var in inner
  725. assert.Error(t, UnmarshalKey(m, &in))
  726. })
  727. t.Run("uint32 from json.Number", func(t *testing.T) {
  728. type inner struct {
  729. Value uint32 `key:"int"`
  730. }
  731. m := map[string]any{
  732. "int": json.Number("8589934592"), // overflow
  733. }
  734. var in inner
  735. assert.Error(t, UnmarshalKey(m, &in))
  736. })
  737. t.Run("uint32 from json.Number", func(t *testing.T) {
  738. type inner struct {
  739. Value uint32 `key:"int"`
  740. }
  741. m := map[string]any{
  742. "int": json.Number("-1"), // overflow
  743. }
  744. var in inner
  745. assert.Error(t, UnmarshalKey(m, &in))
  746. })
  747. t.Run("uint32 from int64", func(t *testing.T) {
  748. type inner struct {
  749. Value uint32 `key:"int"`
  750. }
  751. m := map[string]any{
  752. "int": int64(1) << 36, // overflow
  753. }
  754. var in inner
  755. assert.Error(t, UnmarshalKey(m, &in))
  756. })
  757. }
  758. func TestUnmarshalBoolSliceRequired(t *testing.T) {
  759. type inner struct {
  760. Bools []bool `key:"bools"`
  761. }
  762. var in inner
  763. assert.NotNil(t, UnmarshalKey(map[string]any{}, &in))
  764. }
  765. func TestUnmarshalBoolSliceNil(t *testing.T) {
  766. type inner struct {
  767. Bools []bool `key:"bools,optional"`
  768. }
  769. var in inner
  770. if assert.NoError(t, UnmarshalKey(map[string]any{}, &in)) {
  771. assert.Nil(t, in.Bools)
  772. }
  773. }
  774. func TestUnmarshalBoolSliceNilExplicit(t *testing.T) {
  775. type inner struct {
  776. Bools []bool `key:"bools,optional"`
  777. }
  778. var in inner
  779. if assert.NoError(t, UnmarshalKey(map[string]any{
  780. "bools": nil,
  781. }, &in)) {
  782. assert.Nil(t, in.Bools)
  783. }
  784. }
  785. func TestUnmarshalBoolSliceEmpty(t *testing.T) {
  786. type inner struct {
  787. Bools []bool `key:"bools,optional"`
  788. }
  789. var in inner
  790. if assert.NoError(t, UnmarshalKey(map[string]any{
  791. "bools": []bool{},
  792. }, &in)) {
  793. assert.Empty(t, in.Bools)
  794. }
  795. }
  796. func TestUnmarshalBoolSliceWithDefault(t *testing.T) {
  797. t.Run("slice with default", func(t *testing.T) {
  798. type inner struct {
  799. Bools []bool `key:"bools,default=[true,false]"`
  800. }
  801. var in inner
  802. if assert.NoError(t, UnmarshalKey(nil, &in)) {
  803. assert.ElementsMatch(t, []bool{true, false}, in.Bools)
  804. }
  805. })
  806. t.Run("slice with default error", func(t *testing.T) {
  807. type inner struct {
  808. Bools []bool `key:"bools,default=[true,fal]"`
  809. }
  810. var in inner
  811. assert.Error(t, UnmarshalKey(nil, &in))
  812. })
  813. }
  814. func TestUnmarshalIntSliceWithDefault(t *testing.T) {
  815. type inner struct {
  816. Ints []int `key:"ints,default=[1,2,3]"`
  817. }
  818. var in inner
  819. if assert.NoError(t, UnmarshalKey(nil, &in)) {
  820. assert.ElementsMatch(t, []int{1, 2, 3}, in.Ints)
  821. }
  822. }
  823. func TestUnmarshalIntSliceWithDefaultHasSpaces(t *testing.T) {
  824. type inner struct {
  825. Ints []int `key:"ints,default=[1, 2, 3]"`
  826. Intps []*int `key:"intps,default=[1, 2, 3, 4]"`
  827. Intpps []**int `key:"intpps,default=[1, 2, 3, 4, 5]"`
  828. }
  829. var in inner
  830. if assert.NoError(t, UnmarshalKey(nil, &in)) {
  831. assert.ElementsMatch(t, []int{1, 2, 3}, in.Ints)
  832. var intps []int
  833. for _, i := range in.Intps {
  834. intps = append(intps, *i)
  835. }
  836. assert.ElementsMatch(t, []int{1, 2, 3, 4}, intps)
  837. var intpps []int
  838. for _, i := range in.Intpps {
  839. intpps = append(intpps, **i)
  840. }
  841. assert.ElementsMatch(t, []int{1, 2, 3, 4, 5}, intpps)
  842. }
  843. }
  844. func TestUnmarshalFloatSliceWithDefault(t *testing.T) {
  845. type inner struct {
  846. Floats []float32 `key:"floats,default=[1.1,2.2,3.3]"`
  847. }
  848. var in inner
  849. if assert.NoError(t, UnmarshalKey(nil, &in)) {
  850. assert.ElementsMatch(t, []float32{1.1, 2.2, 3.3}, in.Floats)
  851. }
  852. }
  853. func TestUnmarshalStringSliceWithDefault(t *testing.T) {
  854. t.Run("slice with default", func(t *testing.T) {
  855. type inner struct {
  856. Strs []string `key:"strs,default=[foo,bar,woo]"`
  857. Strps []*string `key:"strs,default=[foo,bar,woo]"`
  858. Strpps []**string `key:"strs,default=[foo,bar,woo]"`
  859. }
  860. var in inner
  861. if assert.NoError(t, UnmarshalKey(nil, &in)) {
  862. assert.ElementsMatch(t, []string{"foo", "bar", "woo"}, in.Strs)
  863. var ss []string
  864. for _, s := range in.Strps {
  865. ss = append(ss, *s)
  866. }
  867. assert.ElementsMatch(t, []string{"foo", "bar", "woo"}, ss)
  868. var sss []string
  869. for _, s := range in.Strpps {
  870. sss = append(sss, **s)
  871. }
  872. assert.ElementsMatch(t, []string{"foo", "bar", "woo"}, sss)
  873. }
  874. })
  875. t.Run("slice with default on errors", func(t *testing.T) {
  876. type (
  877. holder struct {
  878. Chan []chan int
  879. }
  880. inner struct {
  881. Strs []holder `key:"strs,default=[foo,bar,woo]"`
  882. }
  883. )
  884. var in inner
  885. assert.Error(t, UnmarshalKey(nil, &in))
  886. })
  887. t.Run("slice with default on errors", func(t *testing.T) {
  888. type inner struct {
  889. Strs []complex64 `key:"strs,default=[foo,bar,woo]"`
  890. }
  891. var in inner
  892. assert.Error(t, UnmarshalKey(nil, &in))
  893. })
  894. }
  895. func TestUnmarshalStringSliceWithDefaultHasSpaces(t *testing.T) {
  896. type inner struct {
  897. Strs []string `key:"strs,default=[foo, bar, woo]"`
  898. }
  899. var in inner
  900. if assert.NoError(t, UnmarshalKey(nil, &in)) {
  901. assert.ElementsMatch(t, []string{"foo", "bar", "woo"}, in.Strs)
  902. }
  903. }
  904. func TestUnmarshalUint(t *testing.T) {
  905. type inner struct {
  906. Uint uint `key:"uint"`
  907. UintFromStr uint `key:"uintstr,string"`
  908. Uint8 uint8 `key:"uint8"`
  909. Uint8FromStr uint8 `key:"uint8str,string"`
  910. Uint16 uint16 `key:"uint16"`
  911. Uint16FromStr uint16 `key:"uint16str,string"`
  912. Uint32 uint32 `key:"uint32"`
  913. Uint32FromStr uint32 `key:"uint32str,string"`
  914. Uint64 uint64 `key:"uint64"`
  915. Uint64FromStr uint64 `key:"uint64str,string"`
  916. DefaultUint uint `key:"defaultuint,default=11"`
  917. Optional uint `key:"optional,optional"`
  918. }
  919. m := map[string]any{
  920. "uint": uint(1),
  921. "uintstr": "2",
  922. "uint8": uint8(3),
  923. "uint8str": "4",
  924. "uint16": uint16(5),
  925. "uint16str": "6",
  926. "uint32": uint32(7),
  927. "uint32str": "8",
  928. "uint64": uint64(9),
  929. "uint64str": "10",
  930. }
  931. var in inner
  932. ast := assert.New(t)
  933. if ast.NoError(UnmarshalKey(m, &in)) {
  934. ast.Equal(uint(1), in.Uint)
  935. ast.Equal(uint(2), in.UintFromStr)
  936. ast.Equal(uint8(3), in.Uint8)
  937. ast.Equal(uint8(4), in.Uint8FromStr)
  938. ast.Equal(uint16(5), in.Uint16)
  939. ast.Equal(uint16(6), in.Uint16FromStr)
  940. ast.Equal(uint32(7), in.Uint32)
  941. ast.Equal(uint32(8), in.Uint32FromStr)
  942. ast.Equal(uint64(9), in.Uint64)
  943. ast.Equal(uint64(10), in.Uint64FromStr)
  944. ast.Equal(uint(11), in.DefaultUint)
  945. }
  946. }
  947. func TestUnmarshalFloat(t *testing.T) {
  948. type inner struct {
  949. Float32 float32 `key:"float32"`
  950. Float32Str float32 `key:"float32str,string"`
  951. Float64 float64 `key:"float64"`
  952. Float64Str float64 `key:"float64str,string"`
  953. DefaultFloat float32 `key:"defaultfloat,default=5.5"`
  954. Optional float32 `key:",optional"`
  955. }
  956. m := map[string]any{
  957. "float32": float32(1.5),
  958. "float32str": "2.5",
  959. "float64": float64(3.5),
  960. "float64str": "4.5",
  961. }
  962. var in inner
  963. ast := assert.New(t)
  964. if ast.NoError(UnmarshalKey(m, &in)) {
  965. ast.Equal(float32(1.5), in.Float32)
  966. ast.Equal(float32(2.5), in.Float32Str)
  967. ast.Equal(3.5, in.Float64)
  968. ast.Equal(4.5, in.Float64Str)
  969. ast.Equal(float32(5.5), in.DefaultFloat)
  970. }
  971. }
  972. func TestUnmarshalInt64Slice(t *testing.T) {
  973. var v struct {
  974. Ages []int64 `key:"ages"`
  975. Slice []int64 `key:"slice"`
  976. }
  977. m := map[string]any{
  978. "ages": []int64{1, 2},
  979. "slice": []any{},
  980. }
  981. ast := assert.New(t)
  982. if ast.NoError(UnmarshalKey(m, &v)) {
  983. ast.ElementsMatch([]int64{1, 2}, v.Ages)
  984. ast.Equal([]int64{}, v.Slice)
  985. }
  986. }
  987. func TestUnmarshalIntSlice(t *testing.T) {
  988. var v struct {
  989. Ages []int `key:"ages"`
  990. Slice []int `key:"slice"`
  991. }
  992. m := map[string]any{
  993. "ages": []int{1, 2},
  994. "slice": []any{},
  995. }
  996. ast := assert.New(t)
  997. if ast.NoError(UnmarshalKey(m, &v)) {
  998. ast.ElementsMatch([]int{1, 2}, v.Ages)
  999. ast.Equal([]int{}, v.Slice)
  1000. }
  1001. }
  1002. func TestUnmarshalString(t *testing.T) {
  1003. type inner struct {
  1004. Name string `key:"name"`
  1005. NameStr string `key:"namestr,string"`
  1006. NotPresent string `key:",optional"`
  1007. NotPresentWithTag string `key:"notpresent,optional"`
  1008. DefaultString string `key:"defaultstring,default=hello"`
  1009. Optional string `key:",optional"`
  1010. }
  1011. m := map[string]any{
  1012. "name": "kevin",
  1013. "namestr": "namewithstring",
  1014. }
  1015. var in inner
  1016. ast := assert.New(t)
  1017. if ast.NoError(UnmarshalKey(m, &in)) {
  1018. ast.Equal("kevin", in.Name)
  1019. ast.Equal("namewithstring", in.NameStr)
  1020. ast.Empty(in.NotPresent)
  1021. ast.Empty(in.NotPresentWithTag)
  1022. ast.Equal("hello", in.DefaultString)
  1023. }
  1024. }
  1025. func TestUnmarshalStringWithMissing(t *testing.T) {
  1026. type inner struct {
  1027. Name string `key:"name"`
  1028. }
  1029. m := map[string]any{}
  1030. var in inner
  1031. assert.Error(t, UnmarshalKey(m, &in))
  1032. }
  1033. func TestUnmarshalStringSliceFromString(t *testing.T) {
  1034. t.Run("slice from string", func(t *testing.T) {
  1035. var v struct {
  1036. Names []string `key:"names"`
  1037. }
  1038. m := map[string]any{
  1039. "names": `["first", "second"]`,
  1040. }
  1041. ast := assert.New(t)
  1042. if ast.NoError(UnmarshalKey(m, &v)) {
  1043. ast.Equal(2, len(v.Names))
  1044. ast.Equal("first", v.Names[0])
  1045. ast.Equal("second", v.Names[1])
  1046. }
  1047. })
  1048. t.Run("slice from string with slice error", func(t *testing.T) {
  1049. var v struct {
  1050. Names []int `key:"names"`
  1051. }
  1052. m := map[string]any{
  1053. "names": `["first", 1]`,
  1054. }
  1055. assert.Error(t, UnmarshalKey(m, &v))
  1056. })
  1057. t.Run("slice from string with error", func(t *testing.T) {
  1058. type myString string
  1059. var v struct {
  1060. Names []string `key:"names"`
  1061. }
  1062. m := map[string]any{
  1063. "names": myString("not a slice"),
  1064. }
  1065. assert.Error(t, UnmarshalKey(m, &v))
  1066. })
  1067. }
  1068. func TestUnmarshalIntSliceFromString(t *testing.T) {
  1069. var v struct {
  1070. Values []int `key:"values"`
  1071. }
  1072. m := map[string]any{
  1073. "values": `[1, 2]`,
  1074. }
  1075. ast := assert.New(t)
  1076. if ast.NoError(UnmarshalKey(m, &v)) {
  1077. ast.Equal(2, len(v.Values))
  1078. ast.Equal(1, v.Values[0])
  1079. ast.Equal(2, v.Values[1])
  1080. }
  1081. }
  1082. func TestUnmarshalIntMapFromString(t *testing.T) {
  1083. var v struct {
  1084. Sort map[string]int `key:"sort"`
  1085. }
  1086. m := map[string]any{
  1087. "sort": `{"value":12345,"zeroVal":0,"nullVal":null}`,
  1088. }
  1089. ast := assert.New(t)
  1090. if ast.NoError(UnmarshalKey(m, &v)) {
  1091. ast.Equal(3, len(v.Sort))
  1092. ast.Equal(12345, v.Sort["value"])
  1093. ast.Equal(0, v.Sort["zeroVal"])
  1094. ast.Equal(0, v.Sort["nullVal"])
  1095. }
  1096. }
  1097. func TestUnmarshalBoolMapFromString(t *testing.T) {
  1098. var v struct {
  1099. Sort map[string]bool `key:"sort"`
  1100. }
  1101. m := map[string]any{
  1102. "sort": `{"value":true,"zeroVal":false,"nullVal":null}`,
  1103. }
  1104. ast := assert.New(t)
  1105. if ast.NoError(UnmarshalKey(m, &v)) {
  1106. ast.Equal(3, len(v.Sort))
  1107. ast.Equal(true, v.Sort["value"])
  1108. ast.Equal(false, v.Sort["zeroVal"])
  1109. ast.Equal(false, v.Sort["nullVal"])
  1110. }
  1111. }
  1112. type CustomStringer string
  1113. type UnsupportedStringer string
  1114. func (c CustomStringer) String() string {
  1115. return fmt.Sprintf("{%s}", string(c))
  1116. }
  1117. func TestUnmarshalStringMapFromStringer(t *testing.T) {
  1118. t.Run("CustomStringer", func(t *testing.T) {
  1119. var v struct {
  1120. Sort map[string]string `key:"sort"`
  1121. }
  1122. m := map[string]any{
  1123. "sort": CustomStringer(`"value":"ascend","emptyStr":""`),
  1124. }
  1125. ast := assert.New(t)
  1126. if ast.NoError(UnmarshalKey(m, &v)) {
  1127. ast.Equal(2, len(v.Sort))
  1128. ast.Equal("ascend", v.Sort["value"])
  1129. ast.Equal("", v.Sort["emptyStr"])
  1130. }
  1131. })
  1132. t.Run("CustomStringer incorrect", func(t *testing.T) {
  1133. var v struct {
  1134. Sort map[string]string `key:"sort"`
  1135. }
  1136. m := map[string]any{
  1137. "sort": CustomStringer(`"value"`),
  1138. }
  1139. assert.Error(t, UnmarshalKey(m, &v))
  1140. })
  1141. }
  1142. func TestUnmarshalStringMapFromUnsupportedType(t *testing.T) {
  1143. var v struct {
  1144. Sort map[string]string `key:"sort"`
  1145. }
  1146. m := map[string]any{
  1147. "sort": UnsupportedStringer(`{"value":"ascend","emptyStr":""}`),
  1148. }
  1149. ast := assert.New(t)
  1150. ast.Error(UnmarshalKey(m, &v))
  1151. }
  1152. func TestUnmarshalStringMapFromNotSettableValue(t *testing.T) {
  1153. var v struct {
  1154. sort map[string]string `key:"sort"`
  1155. psort *map[string]string `key:"psort"`
  1156. }
  1157. m := map[string]any{
  1158. "sort": `{"value":"ascend","emptyStr":""}`,
  1159. "psort": `{"value":"ascend","emptyStr":""}`,
  1160. }
  1161. ast := assert.New(t)
  1162. ast.NoError(UnmarshalKey(m, &v))
  1163. assert.Empty(t, v.sort)
  1164. assert.Nil(t, v.psort)
  1165. }
  1166. func TestUnmarshalStringMapFromString(t *testing.T) {
  1167. var v struct {
  1168. Sort map[string]string `key:"sort"`
  1169. }
  1170. m := map[string]any{
  1171. "sort": `{"value":"ascend","emptyStr":""}`,
  1172. }
  1173. ast := assert.New(t)
  1174. if ast.NoError(UnmarshalKey(m, &v)) {
  1175. ast.Equal(2, len(v.Sort))
  1176. ast.Equal("ascend", v.Sort["value"])
  1177. ast.Equal("", v.Sort["emptyStr"])
  1178. }
  1179. }
  1180. func TestUnmarshalStructMapFromString(t *testing.T) {
  1181. var v struct {
  1182. Filter map[string]struct {
  1183. Field1 bool `json:"field1"`
  1184. Field2 int64 `json:"field2,string"`
  1185. Field3 string `json:"field3"`
  1186. Field4 *string `json:"field4"`
  1187. Field5 []string `json:"field5"`
  1188. } `key:"filter"`
  1189. }
  1190. m := map[string]any{
  1191. "filter": `{"obj":{"field1":true,"field2":"1573570455447539712","field3":"this is a string",
  1192. "field4":"this is a string pointer","field5":["str1","str2"]}}`,
  1193. }
  1194. ast := assert.New(t)
  1195. if ast.NoError(UnmarshalKey(m, &v)) {
  1196. ast.Equal(1, len(v.Filter))
  1197. ast.NotNil(v.Filter["obj"])
  1198. ast.Equal(true, v.Filter["obj"].Field1)
  1199. ast.Equal(int64(1573570455447539712), v.Filter["obj"].Field2)
  1200. ast.Equal("this is a string", v.Filter["obj"].Field3)
  1201. ast.Equal("this is a string pointer", *v.Filter["obj"].Field4)
  1202. ast.ElementsMatch([]string{"str1", "str2"}, v.Filter["obj"].Field5)
  1203. }
  1204. }
  1205. func TestUnmarshalStringSliceMapFromString(t *testing.T) {
  1206. var v struct {
  1207. Filter map[string][]string `key:"filter"`
  1208. }
  1209. m := map[string]any{
  1210. "filter": `{"assignType":null,"status":["process","comment"],"rate":[]}`,
  1211. }
  1212. ast := assert.New(t)
  1213. if ast.NoError(UnmarshalKey(m, &v)) {
  1214. ast.Equal(3, len(v.Filter))
  1215. ast.Equal([]string(nil), v.Filter["assignType"])
  1216. ast.Equal(2, len(v.Filter["status"]))
  1217. ast.Equal("process", v.Filter["status"][0])
  1218. ast.Equal("comment", v.Filter["status"][1])
  1219. ast.Equal(0, len(v.Filter["rate"]))
  1220. }
  1221. }
  1222. func TestUnmarshalStruct(t *testing.T) {
  1223. t.Run("struct", func(t *testing.T) {
  1224. type address struct {
  1225. City string `key:"city"`
  1226. ZipCode int `key:"zipcode,string"`
  1227. DefaultString string `key:"defaultstring,default=hello"`
  1228. Optional string `key:",optional"`
  1229. }
  1230. type inner struct {
  1231. Name string `key:"name"`
  1232. Address address `key:"address"`
  1233. AddressP *address `key:"addressp"`
  1234. AddressPP **address `key:"addresspp"`
  1235. }
  1236. m := map[string]any{
  1237. "name": "kevin",
  1238. "address": map[string]any{
  1239. "city": "shanghai",
  1240. "zipcode": "200000",
  1241. },
  1242. "addressp": map[string]any{
  1243. "city": "beijing",
  1244. "zipcode": "300000",
  1245. },
  1246. "addresspp": map[string]any{
  1247. "city": "guangzhou",
  1248. "zipcode": "400000",
  1249. },
  1250. }
  1251. var in inner
  1252. ast := assert.New(t)
  1253. if ast.NoError(UnmarshalKey(m, &in)) {
  1254. ast.Equal("kevin", in.Name)
  1255. ast.Equal("shanghai", in.Address.City)
  1256. ast.Equal(200000, in.Address.ZipCode)
  1257. ast.Equal("hello", in.AddressP.DefaultString)
  1258. ast.Equal("beijing", in.AddressP.City)
  1259. ast.Equal(300000, in.AddressP.ZipCode)
  1260. ast.Equal("hello", in.AddressP.DefaultString)
  1261. ast.Equal("guangzhou", (*in.AddressPP).City)
  1262. ast.Equal(400000, (*in.AddressPP).ZipCode)
  1263. ast.Equal("hello", (*in.AddressPP).DefaultString)
  1264. }
  1265. })
  1266. t.Run("struct with error", func(t *testing.T) {
  1267. type address struct {
  1268. City string `key:"city"`
  1269. ZipCode int `key:"zipcode,string"`
  1270. DefaultString string `key:"defaultstring,default=hello"`
  1271. Optional string `key:",optional"`
  1272. }
  1273. type inner struct {
  1274. Name string `key:"name"`
  1275. Address address `key:"address"`
  1276. AddressP *address `key:"addressp"`
  1277. AddressPP **address `key:"addresspp"`
  1278. }
  1279. m := map[string]any{
  1280. "name": "kevin",
  1281. "address": map[string]any{
  1282. "city": "shanghai",
  1283. "zipcode": "200000",
  1284. },
  1285. "addressp": map[string]any{
  1286. "city": "beijing",
  1287. "zipcode": "300000",
  1288. },
  1289. "addresspp": map[string]any{
  1290. "city": "guangzhou",
  1291. "zipcode": "a",
  1292. },
  1293. }
  1294. var in inner
  1295. assert.Error(t, UnmarshalKey(m, &in))
  1296. })
  1297. }
  1298. func TestUnmarshalStructOptionalDepends(t *testing.T) {
  1299. type address struct {
  1300. City string `key:"city"`
  1301. Optional string `key:",optional"`
  1302. OptionalDepends string `key:",optional=Optional"`
  1303. }
  1304. type inner struct {
  1305. Name string `key:"name"`
  1306. Address address `key:"address"`
  1307. }
  1308. tests := []struct {
  1309. input map[string]string
  1310. pass bool
  1311. }{
  1312. {
  1313. pass: true,
  1314. },
  1315. {
  1316. input: map[string]string{
  1317. "OptionalDepends": "b",
  1318. },
  1319. pass: false,
  1320. },
  1321. {
  1322. input: map[string]string{
  1323. "Optional": "a",
  1324. },
  1325. pass: false,
  1326. },
  1327. {
  1328. input: map[string]string{
  1329. "Optional": "a",
  1330. "OptionalDepends": "b",
  1331. },
  1332. pass: true,
  1333. },
  1334. }
  1335. for _, test := range tests {
  1336. t.Run(stringx.Rand(), func(t *testing.T) {
  1337. m := map[string]any{
  1338. "name": "kevin",
  1339. "address": map[string]any{
  1340. "city": "shanghai",
  1341. },
  1342. }
  1343. for k, v := range test.input {
  1344. m["address"].(map[string]any)[k] = v
  1345. }
  1346. var in inner
  1347. ast := assert.New(t)
  1348. if test.pass {
  1349. if ast.NoError(UnmarshalKey(m, &in)) {
  1350. ast.Equal("kevin", in.Name)
  1351. ast.Equal("shanghai", in.Address.City)
  1352. ast.Equal(test.input["Optional"], in.Address.Optional)
  1353. ast.Equal(test.input["OptionalDepends"], in.Address.OptionalDepends)
  1354. }
  1355. } else {
  1356. ast.Error(UnmarshalKey(m, &in))
  1357. }
  1358. })
  1359. }
  1360. }
  1361. func TestUnmarshalStructOptionalDependsNot(t *testing.T) {
  1362. type address struct {
  1363. City string `key:"city"`
  1364. Optional string `key:",optional"`
  1365. OptionalDepends string `key:",optional=!Optional"`
  1366. }
  1367. type inner struct {
  1368. Name string `key:"name"`
  1369. Address address `key:"address"`
  1370. }
  1371. tests := []struct {
  1372. input map[string]string
  1373. pass bool
  1374. }{
  1375. {
  1376. input: map[string]string{},
  1377. pass: false,
  1378. },
  1379. {
  1380. input: map[string]string{
  1381. "Optional": "a",
  1382. "OptionalDepends": "b",
  1383. },
  1384. pass: false,
  1385. },
  1386. {
  1387. input: map[string]string{
  1388. "Optional": "a",
  1389. },
  1390. pass: true,
  1391. },
  1392. {
  1393. input: map[string]string{
  1394. "OptionalDepends": "b",
  1395. },
  1396. pass: true,
  1397. },
  1398. }
  1399. for _, test := range tests {
  1400. t.Run(stringx.Rand(), func(t *testing.T) {
  1401. m := map[string]any{
  1402. "name": "kevin",
  1403. "address": map[string]any{
  1404. "city": "shanghai",
  1405. },
  1406. }
  1407. for k, v := range test.input {
  1408. m["address"].(map[string]any)[k] = v
  1409. }
  1410. var in inner
  1411. ast := assert.New(t)
  1412. if test.pass {
  1413. if ast.NoError(UnmarshalKey(m, &in)) {
  1414. ast.Equal("kevin", in.Name)
  1415. ast.Equal("shanghai", in.Address.City)
  1416. ast.Equal(test.input["Optional"], in.Address.Optional)
  1417. ast.Equal(test.input["OptionalDepends"], in.Address.OptionalDepends)
  1418. }
  1419. } else {
  1420. ast.Error(UnmarshalKey(m, &in))
  1421. }
  1422. })
  1423. }
  1424. }
  1425. func TestUnmarshalStructOptionalDependsNotErrorDetails(t *testing.T) {
  1426. t.Run("mutal optionals", func(t *testing.T) {
  1427. type address struct {
  1428. Optional string `key:",optional"`
  1429. OptionalDepends string `key:",optional=!Optional"`
  1430. }
  1431. type inner struct {
  1432. Name string `key:"name"`
  1433. Address address `key:"address"`
  1434. }
  1435. m := map[string]any{
  1436. "name": "kevin",
  1437. }
  1438. var in inner
  1439. assert.Error(t, UnmarshalKey(m, &in))
  1440. })
  1441. t.Run("with default", func(t *testing.T) {
  1442. type address struct {
  1443. Optional string `key:",optional"`
  1444. OptionalDepends string `key:",default=value,optional"`
  1445. }
  1446. type inner struct {
  1447. Name string `key:"name"`
  1448. Address address `key:"address"`
  1449. }
  1450. m := map[string]any{
  1451. "name": "kevin",
  1452. }
  1453. var in inner
  1454. if assert.NoError(t, UnmarshalKey(m, &in)) {
  1455. assert.Equal(t, "kevin", in.Name)
  1456. assert.Equal(t, "value", in.Address.OptionalDepends)
  1457. }
  1458. })
  1459. }
  1460. func TestUnmarshalStructOptionalDependsNotNested(t *testing.T) {
  1461. t.Run("mutal optionals", func(t *testing.T) {
  1462. type address struct {
  1463. Optional string `key:",optional"`
  1464. OptionalDepends string `key:",optional=!Optional"`
  1465. }
  1466. type combo struct {
  1467. Name string `key:"name,optional"`
  1468. Address address `key:"address"`
  1469. }
  1470. type inner struct {
  1471. Name string `key:"name"`
  1472. Combo combo `key:"combo"`
  1473. }
  1474. m := map[string]any{
  1475. "name": "kevin",
  1476. }
  1477. var in inner
  1478. assert.Error(t, UnmarshalKey(m, &in))
  1479. })
  1480. t.Run("bad format", func(t *testing.T) {
  1481. type address struct {
  1482. Optional string `key:",optional"`
  1483. OptionalDepends string `key:",optional=!Optional=abcd"`
  1484. }
  1485. type combo struct {
  1486. Name string `key:"name,optional"`
  1487. Address address `key:"address"`
  1488. }
  1489. type inner struct {
  1490. Name string `key:"name"`
  1491. Combo combo `key:"combo"`
  1492. }
  1493. m := map[string]any{
  1494. "name": "kevin",
  1495. }
  1496. var in inner
  1497. assert.Error(t, UnmarshalKey(m, &in))
  1498. })
  1499. t.Run("invalid option", func(t *testing.T) {
  1500. type address struct {
  1501. Optional string `key:",optional"`
  1502. OptionalDepends string `key:",opt=abcd"`
  1503. }
  1504. type combo struct {
  1505. Name string `key:"name,optional"`
  1506. Address address `key:"address"`
  1507. }
  1508. type inner struct {
  1509. Name string `key:"name"`
  1510. Combo combo `key:"combo"`
  1511. }
  1512. m := map[string]any{
  1513. "name": "kevin",
  1514. }
  1515. var in inner
  1516. assert.Error(t, UnmarshalKey(m, &in))
  1517. })
  1518. }
  1519. func TestUnmarshalStructOptionalNestedDifferentKey(t *testing.T) {
  1520. type address struct {
  1521. Optional string `dkey:",optional"`
  1522. OptionalDepends string `key:",optional"`
  1523. }
  1524. type combo struct {
  1525. Name string `key:"name,optional"`
  1526. Address address `key:"address"`
  1527. }
  1528. type inner struct {
  1529. Name string `key:"name"`
  1530. Combo combo `key:"combo"`
  1531. }
  1532. m := map[string]any{
  1533. "name": "kevin",
  1534. }
  1535. var in inner
  1536. assert.Error(t, UnmarshalKey(m, &in))
  1537. }
  1538. func TestUnmarshalStructOptionalDependsNotEnoughValue(t *testing.T) {
  1539. type address struct {
  1540. Optional string `key:",optional"`
  1541. OptionalDepends string `key:",optional=!"`
  1542. }
  1543. type inner struct {
  1544. Name string `key:"name"`
  1545. Address address `key:"address"`
  1546. }
  1547. m := map[string]any{
  1548. "name": "kevin",
  1549. "address": map[string]any{},
  1550. }
  1551. var in inner
  1552. assert.Error(t, UnmarshalKey(m, &in))
  1553. }
  1554. func TestUnmarshalStructOptionalDependsMoreValues(t *testing.T) {
  1555. type address struct {
  1556. Optional string `key:",optional"`
  1557. OptionalDepends string `key:",optional=a=b"`
  1558. }
  1559. type inner struct {
  1560. Name string `key:"name"`
  1561. Address address `key:"address"`
  1562. }
  1563. m := map[string]any{
  1564. "name": "kevin",
  1565. "address": map[string]any{},
  1566. }
  1567. var in inner
  1568. assert.Error(t, UnmarshalKey(m, &in))
  1569. }
  1570. func TestUnmarshalStructMissing(t *testing.T) {
  1571. type address struct {
  1572. Optional string `key:",optional"`
  1573. OptionalDepends string `key:",optional=a=b"`
  1574. }
  1575. type inner struct {
  1576. Name string `key:"name"`
  1577. Address address `key:"address"`
  1578. }
  1579. m := map[string]any{
  1580. "name": "kevin",
  1581. }
  1582. var in inner
  1583. assert.Error(t, UnmarshalKey(m, &in))
  1584. }
  1585. func TestUnmarshalNestedStructMissing(t *testing.T) {
  1586. type mostInner struct {
  1587. Name string `key:"name"`
  1588. }
  1589. type address struct {
  1590. Optional string `key:",optional"`
  1591. OptionalDepends string `key:",optional=a=b"`
  1592. MostInner mostInner
  1593. }
  1594. type inner struct {
  1595. Name string `key:"name"`
  1596. Address address `key:"address"`
  1597. }
  1598. m := map[string]any{
  1599. "name": "kevin",
  1600. "address": map[string]any{},
  1601. }
  1602. var in inner
  1603. assert.Error(t, UnmarshalKey(m, &in))
  1604. }
  1605. func TestUnmarshalAnonymousStructOptionalDepends(t *testing.T) {
  1606. type AnonAddress struct {
  1607. City string `key:"city"`
  1608. Optional string `key:",optional"`
  1609. OptionalDepends string `key:",optional=Optional"`
  1610. }
  1611. type inner struct {
  1612. Name string `key:"name"`
  1613. AnonAddress
  1614. }
  1615. tests := []struct {
  1616. input map[string]string
  1617. pass bool
  1618. }{
  1619. {
  1620. pass: true,
  1621. },
  1622. {
  1623. input: map[string]string{
  1624. "OptionalDepends": "b",
  1625. },
  1626. pass: false,
  1627. },
  1628. {
  1629. input: map[string]string{
  1630. "Optional": "a",
  1631. },
  1632. pass: false,
  1633. },
  1634. {
  1635. input: map[string]string{
  1636. "Optional": "a",
  1637. "OptionalDepends": "b",
  1638. },
  1639. pass: true,
  1640. },
  1641. }
  1642. for _, test := range tests {
  1643. t.Run(stringx.Rand(), func(t *testing.T) {
  1644. m := map[string]any{
  1645. "name": "kevin",
  1646. "city": "shanghai",
  1647. }
  1648. for k, v := range test.input {
  1649. m[k] = v
  1650. }
  1651. var in inner
  1652. ast := assert.New(t)
  1653. if test.pass {
  1654. if ast.NoError(UnmarshalKey(m, &in)) {
  1655. ast.Equal("kevin", in.Name)
  1656. ast.Equal("shanghai", in.City)
  1657. ast.Equal(test.input["Optional"], in.Optional)
  1658. ast.Equal(test.input["OptionalDepends"], in.OptionalDepends)
  1659. }
  1660. } else {
  1661. ast.Error(UnmarshalKey(m, &in))
  1662. }
  1663. })
  1664. }
  1665. }
  1666. func TestUnmarshalStructPtr(t *testing.T) {
  1667. type address struct {
  1668. City string `key:"city"`
  1669. ZipCode int `key:"zipcode,string"`
  1670. DefaultString string `key:"defaultstring,default=hello"`
  1671. Optional string `key:",optional"`
  1672. }
  1673. type inner struct {
  1674. Name string `key:"name"`
  1675. Address *address `key:"address"`
  1676. }
  1677. m := map[string]any{
  1678. "name": "kevin",
  1679. "address": map[string]any{
  1680. "city": "shanghai",
  1681. "zipcode": "200000",
  1682. },
  1683. }
  1684. var in inner
  1685. ast := assert.New(t)
  1686. if ast.NoError(UnmarshalKey(m, &in)) {
  1687. ast.Equal("kevin", in.Name)
  1688. ast.Equal("shanghai", in.Address.City)
  1689. ast.Equal(200000, in.Address.ZipCode)
  1690. ast.Equal("hello", in.Address.DefaultString)
  1691. }
  1692. }
  1693. func TestUnmarshalWithStringIgnored(t *testing.T) {
  1694. type inner struct {
  1695. True bool `key:"yes"`
  1696. False bool `key:"no"`
  1697. Int int `key:"int"`
  1698. Int8 int8 `key:"int8"`
  1699. Int16 int16 `key:"int16"`
  1700. Int32 int32 `key:"int32"`
  1701. Int64 int64 `key:"int64"`
  1702. Uint uint `key:"uint"`
  1703. Uint8 uint8 `key:"uint8"`
  1704. Uint16 uint16 `key:"uint16"`
  1705. Uint32 uint32 `key:"uint32"`
  1706. Uint64 uint64 `key:"uint64"`
  1707. Float32 float32 `key:"float32"`
  1708. Float64 float64 `key:"float64"`
  1709. }
  1710. m := map[string]any{
  1711. "yes": "1",
  1712. "no": "0",
  1713. "int": "1",
  1714. "int8": "3",
  1715. "int16": "5",
  1716. "int32": "7",
  1717. "int64": "9",
  1718. "uint": "1",
  1719. "uint8": "3",
  1720. "uint16": "5",
  1721. "uint32": "7",
  1722. "uint64": "9",
  1723. "float32": "1.5",
  1724. "float64": "3.5",
  1725. }
  1726. var in inner
  1727. um := NewUnmarshaler("key", WithStringValues())
  1728. ast := assert.New(t)
  1729. if ast.NoError(um.Unmarshal(m, &in)) {
  1730. ast.True(in.True)
  1731. ast.False(in.False)
  1732. ast.Equal(1, in.Int)
  1733. ast.Equal(int8(3), in.Int8)
  1734. ast.Equal(int16(5), in.Int16)
  1735. ast.Equal(int32(7), in.Int32)
  1736. ast.Equal(int64(9), in.Int64)
  1737. ast.Equal(uint(1), in.Uint)
  1738. ast.Equal(uint8(3), in.Uint8)
  1739. ast.Equal(uint16(5), in.Uint16)
  1740. ast.Equal(uint32(7), in.Uint32)
  1741. ast.Equal(uint64(9), in.Uint64)
  1742. ast.Equal(float32(1.5), in.Float32)
  1743. ast.Equal(3.5, in.Float64)
  1744. }
  1745. }
  1746. func TestUnmarshalJsonNumberInt64(t *testing.T) {
  1747. for i := 0; i <= maxUintBitsToTest; i++ {
  1748. var intValue int64 = 1 << uint(i)
  1749. strValue := strconv.FormatInt(intValue, 10)
  1750. number := json.Number(strValue)
  1751. m := map[string]any{
  1752. "ID": number,
  1753. }
  1754. var v struct {
  1755. ID int64
  1756. }
  1757. if assert.NoError(t, UnmarshalKey(m, &v)) {
  1758. assert.Equal(t, intValue, v.ID)
  1759. }
  1760. }
  1761. }
  1762. func TestUnmarshalJsonNumberUint64(t *testing.T) {
  1763. for i := 0; i <= maxUintBitsToTest; i++ {
  1764. var intValue uint64 = 1 << uint(i)
  1765. strValue := strconv.FormatUint(intValue, 10)
  1766. number := json.Number(strValue)
  1767. m := map[string]any{
  1768. "ID": number,
  1769. }
  1770. var v struct {
  1771. ID uint64
  1772. }
  1773. if assert.NoError(t, UnmarshalKey(m, &v)) {
  1774. assert.Equal(t, intValue, v.ID)
  1775. }
  1776. }
  1777. }
  1778. func TestUnmarshalJsonNumberUint64Ptr(t *testing.T) {
  1779. for i := 0; i <= maxUintBitsToTest; i++ {
  1780. var intValue uint64 = 1 << uint(i)
  1781. strValue := strconv.FormatUint(intValue, 10)
  1782. number := json.Number(strValue)
  1783. m := map[string]any{
  1784. "ID": number,
  1785. }
  1786. var v struct {
  1787. ID *uint64
  1788. }
  1789. ast := assert.New(t)
  1790. if ast.NoError(UnmarshalKey(m, &v)) {
  1791. ast.NotNil(v.ID)
  1792. ast.Equal(intValue, *v.ID)
  1793. }
  1794. }
  1795. }
  1796. func TestUnmarshalMapOfInt(t *testing.T) {
  1797. m := map[string]any{
  1798. "Ids": map[string]bool{"first": true},
  1799. }
  1800. var v struct {
  1801. Ids map[string]bool
  1802. }
  1803. if assert.NoError(t, UnmarshalKey(m, &v)) {
  1804. assert.True(t, v.Ids["first"])
  1805. }
  1806. }
  1807. func TestUnmarshalMapOfStruct(t *testing.T) {
  1808. t.Run("map of struct with error", func(t *testing.T) {
  1809. m := map[string]any{
  1810. "Ids": map[string]any{"first": "second"},
  1811. }
  1812. var v struct {
  1813. Ids map[string]struct {
  1814. Name string
  1815. }
  1816. }
  1817. assert.Error(t, UnmarshalKey(m, &v))
  1818. })
  1819. t.Run("map of struct", func(t *testing.T) {
  1820. m := map[string]any{
  1821. "Ids": map[string]any{
  1822. "foo": map[string]any{"Name": "foo"},
  1823. },
  1824. }
  1825. var v struct {
  1826. Ids map[string]struct {
  1827. Name string
  1828. }
  1829. }
  1830. if assert.NoError(t, UnmarshalKey(m, &v)) {
  1831. assert.Equal(t, "foo", v.Ids["foo"].Name)
  1832. }
  1833. })
  1834. t.Run("map of struct error", func(t *testing.T) {
  1835. m := map[string]any{
  1836. "Ids": map[string]any{
  1837. "foo": map[string]any{"name": "foo"},
  1838. },
  1839. }
  1840. var v struct {
  1841. Ids map[string]struct {
  1842. Name string
  1843. }
  1844. }
  1845. assert.Error(t, UnmarshalKey(m, &v))
  1846. })
  1847. }
  1848. func TestUnmarshalSlice(t *testing.T) {
  1849. t.Run("slice of string", func(t *testing.T) {
  1850. m := map[string]any{
  1851. "Ids": []any{"first", "second"},
  1852. }
  1853. var v struct {
  1854. Ids []string
  1855. }
  1856. ast := assert.New(t)
  1857. if ast.NoError(UnmarshalKey(m, &v)) {
  1858. ast.Equal(2, len(v.Ids))
  1859. ast.Equal("first", v.Ids[0])
  1860. ast.Equal("second", v.Ids[1])
  1861. }
  1862. })
  1863. t.Run("slice with type mismatch", func(t *testing.T) {
  1864. var v struct {
  1865. Ids string
  1866. }
  1867. assert.Error(t, NewUnmarshaler(jsonTagKey).Unmarshal([]any{1, 2}, &v))
  1868. })
  1869. t.Run("slice", func(t *testing.T) {
  1870. var v []int
  1871. ast := assert.New(t)
  1872. if ast.NoError(NewUnmarshaler(jsonTagKey).Unmarshal([]any{1, 2}, &v)) {
  1873. ast.Equal(2, len(v))
  1874. ast.Equal(1, v[0])
  1875. ast.Equal(2, v[1])
  1876. }
  1877. })
  1878. t.Run("slice with unsupported type", func(t *testing.T) {
  1879. var v int
  1880. assert.Error(t, NewUnmarshaler(jsonTagKey).Unmarshal(1, &v))
  1881. })
  1882. }
  1883. func TestUnmarshalSliceOfStruct(t *testing.T) {
  1884. t.Run("slice of struct", func(t *testing.T) {
  1885. m := map[string]any{
  1886. "Ids": []map[string]any{
  1887. {
  1888. "First": 1,
  1889. "Second": 2,
  1890. },
  1891. },
  1892. }
  1893. var v struct {
  1894. Ids []struct {
  1895. First int
  1896. Second int
  1897. }
  1898. }
  1899. ast := assert.New(t)
  1900. if ast.NoError(UnmarshalKey(m, &v)) {
  1901. ast.Equal(1, len(v.Ids))
  1902. ast.Equal(1, v.Ids[0].First)
  1903. ast.Equal(2, v.Ids[0].Second)
  1904. }
  1905. })
  1906. t.Run("slice of struct", func(t *testing.T) {
  1907. m := map[string]any{
  1908. "Ids": []map[string]any{
  1909. {
  1910. "First": "a",
  1911. "Second": 2,
  1912. },
  1913. },
  1914. }
  1915. var v struct {
  1916. Ids []struct {
  1917. First int
  1918. Second int
  1919. }
  1920. }
  1921. assert.Error(t, UnmarshalKey(m, &v))
  1922. })
  1923. }
  1924. func TestUnmarshalWithStringOptionsCorrect(t *testing.T) {
  1925. type inner struct {
  1926. Value string `key:"value,options=first|second"`
  1927. Foo string `key:"foo,options=[bar,baz]"`
  1928. Correct string `key:"correct,options=1|2"`
  1929. }
  1930. m := map[string]any{
  1931. "value": "first",
  1932. "foo": "bar",
  1933. "correct": "2",
  1934. }
  1935. var in inner
  1936. ast := assert.New(t)
  1937. if ast.NoError(UnmarshalKey(m, &in)) {
  1938. ast.Equal("first", in.Value)
  1939. ast.Equal("bar", in.Foo)
  1940. ast.Equal("2", in.Correct)
  1941. }
  1942. }
  1943. func TestUnmarshalOptionsOptional(t *testing.T) {
  1944. type inner struct {
  1945. Value string `key:"value,options=first|second,optional"`
  1946. OptionalValue string `key:"optional_value,options=first|second,optional"`
  1947. Foo string `key:"foo,options=[bar,baz]"`
  1948. Correct string `key:"correct,options=1|2"`
  1949. }
  1950. m := map[string]any{
  1951. "value": "first",
  1952. "foo": "bar",
  1953. "correct": "2",
  1954. }
  1955. var in inner
  1956. ast := assert.New(t)
  1957. if ast.NoError(UnmarshalKey(m, &in)) {
  1958. ast.Equal("first", in.Value)
  1959. ast.Equal("", in.OptionalValue)
  1960. ast.Equal("bar", in.Foo)
  1961. ast.Equal("2", in.Correct)
  1962. }
  1963. }
  1964. func TestUnmarshalOptionsOptionalWrongValue(t *testing.T) {
  1965. type inner struct {
  1966. Value string `key:"value,options=first|second,optional"`
  1967. OptionalValue string `key:"optional_value,options=first|second,optional"`
  1968. WrongValue string `key:"wrong_value,options=first|second,optional"`
  1969. }
  1970. m := map[string]any{
  1971. "value": "first",
  1972. "wrong_value": "third",
  1973. }
  1974. var in inner
  1975. assert.Error(t, UnmarshalKey(m, &in))
  1976. }
  1977. func TestUnmarshalOptionsMissingValues(t *testing.T) {
  1978. type inner struct {
  1979. Value string `key:"value,options"`
  1980. }
  1981. m := map[string]any{
  1982. "value": "first",
  1983. }
  1984. var in inner
  1985. assert.Error(t, UnmarshalKey(m, &in))
  1986. }
  1987. func TestUnmarshalStringOptionsWithStringOptionsNotString(t *testing.T) {
  1988. type inner struct {
  1989. Value string `key:"value,options=first|second"`
  1990. Correct string `key:"correct,options=1|2"`
  1991. }
  1992. m := map[string]any{
  1993. "value": "first",
  1994. "correct": 2,
  1995. }
  1996. var in inner
  1997. unmarshaler := NewUnmarshaler(defaultKeyName, WithStringValues())
  1998. assert.Error(t, unmarshaler.Unmarshal(m, &in))
  1999. }
  2000. func TestUnmarshalStringOptionsWithStringOptions(t *testing.T) {
  2001. type inner struct {
  2002. Value string `key:"value,options=first|second"`
  2003. Correct string `key:"correct,options=1|2"`
  2004. }
  2005. m := map[string]any{
  2006. "value": "first",
  2007. "correct": "2",
  2008. }
  2009. var in inner
  2010. unmarshaler := NewUnmarshaler(defaultKeyName, WithStringValues())
  2011. ast := assert.New(t)
  2012. if ast.NoError(unmarshaler.Unmarshal(m, &in)) {
  2013. ast.Equal("first", in.Value)
  2014. ast.Equal("2", in.Correct)
  2015. }
  2016. }
  2017. func TestUnmarshalStringOptionsWithStringOptionsPtr(t *testing.T) {
  2018. type inner struct {
  2019. Value *string `key:"value,options=first|second"`
  2020. ValueP **string `key:"valuep,options=first|second"`
  2021. Correct *int `key:"correct,options=1|2"`
  2022. }
  2023. m := map[string]any{
  2024. "value": "first",
  2025. "valuep": "second",
  2026. "correct": "2",
  2027. }
  2028. var in inner
  2029. unmarshaler := NewUnmarshaler(defaultKeyName, WithStringValues())
  2030. ast := assert.New(t)
  2031. if ast.NoError(unmarshaler.Unmarshal(m, &in)) {
  2032. ast.True(*in.Value == "first")
  2033. ast.True(**in.ValueP == "second")
  2034. ast.True(*in.Correct == 2)
  2035. }
  2036. }
  2037. func TestUnmarshalStringOptionsWithStringOptionsIncorrect(t *testing.T) {
  2038. type inner struct {
  2039. Value string `key:"value,options=first|second"`
  2040. Correct string `key:"correct,options=1|2"`
  2041. }
  2042. m := map[string]any{
  2043. "value": "third",
  2044. "correct": "2",
  2045. }
  2046. var in inner
  2047. unmarshaler := NewUnmarshaler(defaultKeyName, WithStringValues())
  2048. assert.Error(t, unmarshaler.Unmarshal(m, &in))
  2049. }
  2050. func TestUnmarshalStringOptionsWithStringOptionsIncorrectGrouped(t *testing.T) {
  2051. type inner struct {
  2052. Value string `key:"value,options=[first,second]"`
  2053. Correct string `key:"correct,options=1|2"`
  2054. }
  2055. m := map[string]any{
  2056. "value": "third",
  2057. "correct": "2",
  2058. }
  2059. var in inner
  2060. unmarshaler := NewUnmarshaler(defaultKeyName, WithStringValues())
  2061. assert.Error(t, unmarshaler.Unmarshal(m, &in))
  2062. }
  2063. func TestUnmarshalWithStringOptionsIncorrect(t *testing.T) {
  2064. type inner struct {
  2065. Value string `key:"value,options=first|second"`
  2066. Incorrect string `key:"incorrect,options=1|2"`
  2067. }
  2068. m := map[string]any{
  2069. "value": "first",
  2070. "incorrect": "3",
  2071. }
  2072. var in inner
  2073. assert.Error(t, UnmarshalKey(m, &in))
  2074. }
  2075. func TestUnmarshalWithIntOptionsCorrect(t *testing.T) {
  2076. type inner struct {
  2077. Value string `key:"value,options=first|second"`
  2078. Number int `key:"number,options=1|2"`
  2079. }
  2080. m := map[string]any{
  2081. "value": "first",
  2082. "number": 2,
  2083. }
  2084. var in inner
  2085. ast := assert.New(t)
  2086. if ast.NoError(UnmarshalKey(m, &in)) {
  2087. ast.Equal("first", in.Value)
  2088. ast.Equal(2, in.Number)
  2089. }
  2090. }
  2091. func TestUnmarshalWithIntOptionsCorrectPtr(t *testing.T) {
  2092. type inner struct {
  2093. Value *string `key:"value,options=first|second"`
  2094. Number *int `key:"number,options=1|2"`
  2095. }
  2096. m := map[string]any{
  2097. "value": "first",
  2098. "number": 2,
  2099. }
  2100. var in inner
  2101. ast := assert.New(t)
  2102. if ast.NoError(UnmarshalKey(m, &in)) {
  2103. ast.True(*in.Value == "first")
  2104. ast.True(*in.Number == 2)
  2105. }
  2106. }
  2107. func TestUnmarshalWithIntOptionsIncorrect(t *testing.T) {
  2108. type inner struct {
  2109. Value string `key:"value,options=first|second"`
  2110. Incorrect int `key:"incorrect,options=1|2"`
  2111. }
  2112. m := map[string]any{
  2113. "value": "first",
  2114. "incorrect": 3,
  2115. }
  2116. var in inner
  2117. assert.Error(t, UnmarshalKey(m, &in))
  2118. }
  2119. func TestUnmarshalWithJsonNumberOptionsIncorrect(t *testing.T) {
  2120. type inner struct {
  2121. Value string `key:"value,options=first|second"`
  2122. Incorrect int `key:"incorrect,options=1|2"`
  2123. }
  2124. m := map[string]any{
  2125. "value": "first",
  2126. "incorrect": json.Number("3"),
  2127. }
  2128. var in inner
  2129. assert.Error(t, UnmarshalKey(m, &in))
  2130. }
  2131. func TestUnmarshaler_UnmarshalIntOptions(t *testing.T) {
  2132. var val struct {
  2133. Sex int `json:"sex,options=0|1"`
  2134. }
  2135. input := []byte(`{"sex": 2}`)
  2136. assert.Error(t, UnmarshalJsonBytes(input, &val))
  2137. }
  2138. func TestUnmarshalWithUintOptionsCorrect(t *testing.T) {
  2139. type inner struct {
  2140. Value string `key:"value,options=first|second"`
  2141. Number uint `key:"number,options=1|2"`
  2142. }
  2143. m := map[string]any{
  2144. "value": "first",
  2145. "number": uint(2),
  2146. }
  2147. var in inner
  2148. ast := assert.New(t)
  2149. if ast.NoError(UnmarshalKey(m, &in)) {
  2150. ast.Equal("first", in.Value)
  2151. ast.Equal(uint(2), in.Number)
  2152. }
  2153. }
  2154. func TestUnmarshalWithUintOptionsIncorrect(t *testing.T) {
  2155. type inner struct {
  2156. Value string `key:"value,options=first|second"`
  2157. Incorrect uint `key:"incorrect,options=1|2"`
  2158. }
  2159. m := map[string]any{
  2160. "value": "first",
  2161. "incorrect": uint(3),
  2162. }
  2163. var in inner
  2164. assert.Error(t, UnmarshalKey(m, &in))
  2165. }
  2166. func TestUnmarshalWithOptionsAndDefault(t *testing.T) {
  2167. type inner struct {
  2168. Value string `key:"value,options=first|second|third,default=second"`
  2169. }
  2170. m := map[string]any{}
  2171. var in inner
  2172. if assert.NoError(t, UnmarshalKey(m, &in)) {
  2173. assert.Equal(t, "second", in.Value)
  2174. }
  2175. }
  2176. func TestUnmarshalWithOptionsAndSet(t *testing.T) {
  2177. type inner struct {
  2178. Value string `key:"value,options=first|second|third,default=second"`
  2179. }
  2180. m := map[string]any{
  2181. "value": "first",
  2182. }
  2183. var in inner
  2184. if assert.NoError(t, UnmarshalKey(m, &in)) {
  2185. assert.Equal(t, "first", in.Value)
  2186. }
  2187. }
  2188. func TestUnmarshalNestedKey(t *testing.T) {
  2189. var c struct {
  2190. ID int `json:"Persons.first.ID"`
  2191. }
  2192. m := map[string]any{
  2193. "Persons": map[string]any{
  2194. "first": map[string]any{
  2195. "ID": 1,
  2196. },
  2197. },
  2198. }
  2199. if assert.NoError(t, NewUnmarshaler(jsonTagKey).Unmarshal(m, &c)) {
  2200. assert.Equal(t, 1, c.ID)
  2201. }
  2202. }
  2203. func TestUnmarhsalNestedKeyArray(t *testing.T) {
  2204. var c struct {
  2205. First []struct {
  2206. ID int
  2207. } `json:"Persons.first"`
  2208. }
  2209. m := map[string]any{
  2210. "Persons": map[string]any{
  2211. "first": []map[string]any{
  2212. {"ID": 1},
  2213. {"ID": 2},
  2214. },
  2215. },
  2216. }
  2217. if assert.NoError(t, NewUnmarshaler(jsonTagKey).Unmarshal(m, &c)) {
  2218. assert.Equal(t, 2, len(c.First))
  2219. assert.Equal(t, 1, c.First[0].ID)
  2220. }
  2221. }
  2222. func TestUnmarshalAnonymousOptionalRequiredProvided(t *testing.T) {
  2223. type (
  2224. Foo struct {
  2225. Value string `json:"v"`
  2226. }
  2227. Bar struct {
  2228. Foo `json:",optional"`
  2229. }
  2230. )
  2231. m := map[string]any{
  2232. "v": "anything",
  2233. }
  2234. var b Bar
  2235. if assert.NoError(t, NewUnmarshaler(jsonTagKey).Unmarshal(m, &b)) {
  2236. assert.Equal(t, "anything", b.Value)
  2237. }
  2238. }
  2239. func TestUnmarshalAnonymousOptionalRequiredMissed(t *testing.T) {
  2240. type (
  2241. Foo struct {
  2242. Value string `json:"v"`
  2243. }
  2244. Bar struct {
  2245. Foo `json:",optional"`
  2246. }
  2247. )
  2248. m := map[string]any{}
  2249. var b Bar
  2250. if assert.NoError(t, NewUnmarshaler(jsonTagKey).Unmarshal(m, &b)) {
  2251. assert.True(t, len(b.Value) == 0)
  2252. }
  2253. }
  2254. func TestUnmarshalAnonymousOptionalOptionalProvided(t *testing.T) {
  2255. type (
  2256. Foo struct {
  2257. Value string `json:"v,optional"`
  2258. }
  2259. Bar struct {
  2260. Foo `json:",optional"`
  2261. }
  2262. )
  2263. m := map[string]any{
  2264. "v": "anything",
  2265. }
  2266. var b Bar
  2267. if assert.NoError(t, NewUnmarshaler(jsonTagKey).Unmarshal(m, &b)) {
  2268. assert.Equal(t, "anything", b.Value)
  2269. }
  2270. }
  2271. func TestUnmarshalAnonymousOptionalOptionalMissed(t *testing.T) {
  2272. type (
  2273. Foo struct {
  2274. Value string `json:"v,optional"`
  2275. }
  2276. Bar struct {
  2277. Foo `json:",optional"`
  2278. }
  2279. )
  2280. m := map[string]any{}
  2281. var b Bar
  2282. if assert.NoError(t, NewUnmarshaler(jsonTagKey).Unmarshal(m, &b)) {
  2283. assert.True(t, len(b.Value) == 0)
  2284. }
  2285. }
  2286. func TestUnmarshalAnonymousOptionalRequiredBothProvided(t *testing.T) {
  2287. type (
  2288. Foo struct {
  2289. Name string `json:"n"`
  2290. Value string `json:"v"`
  2291. }
  2292. Bar struct {
  2293. Foo `json:",optional"`
  2294. }
  2295. )
  2296. m := map[string]any{
  2297. "n": "kevin",
  2298. "v": "anything",
  2299. }
  2300. var b Bar
  2301. if assert.NoError(t, NewUnmarshaler(jsonTagKey).Unmarshal(m, &b)) {
  2302. assert.Equal(t, "kevin", b.Name)
  2303. assert.Equal(t, "anything", b.Value)
  2304. }
  2305. }
  2306. func TestUnmarshalAnonymousOptionalRequiredOneProvidedOneMissed(t *testing.T) {
  2307. type (
  2308. Foo struct {
  2309. Name string `json:"n"`
  2310. Value string `json:"v"`
  2311. }
  2312. Bar struct {
  2313. Foo `json:",optional"`
  2314. }
  2315. )
  2316. m := map[string]any{
  2317. "v": "anything",
  2318. }
  2319. var b Bar
  2320. assert.Error(t, NewUnmarshaler(jsonTagKey).Unmarshal(m, &b))
  2321. }
  2322. func TestUnmarshalAnonymousOptionalRequiredBothMissed(t *testing.T) {
  2323. type (
  2324. Foo struct {
  2325. Name string `json:"n"`
  2326. Value string `json:"v"`
  2327. }
  2328. Bar struct {
  2329. Foo `json:",optional"`
  2330. }
  2331. )
  2332. m := map[string]any{}
  2333. var b Bar
  2334. if assert.NoError(t, NewUnmarshaler(jsonTagKey).Unmarshal(m, &b)) {
  2335. assert.True(t, len(b.Name) == 0)
  2336. assert.True(t, len(b.Value) == 0)
  2337. }
  2338. }
  2339. func TestUnmarshalAnonymousOptionalOneRequiredOneOptionalBothProvided(t *testing.T) {
  2340. type (
  2341. Foo struct {
  2342. Name string `json:"n,optional"`
  2343. Value string `json:"v"`
  2344. }
  2345. Bar struct {
  2346. Foo `json:",optional"`
  2347. }
  2348. )
  2349. m := map[string]any{
  2350. "n": "kevin",
  2351. "v": "anything",
  2352. }
  2353. var b Bar
  2354. if assert.NoError(t, NewUnmarshaler(jsonTagKey).Unmarshal(m, &b)) {
  2355. assert.Equal(t, "kevin", b.Name)
  2356. assert.Equal(t, "anything", b.Value)
  2357. }
  2358. }
  2359. func TestUnmarshalAnonymousOptionalOneRequiredOneOptionalBothMissed(t *testing.T) {
  2360. type (
  2361. Foo struct {
  2362. Name string `json:"n,optional"`
  2363. Value string `json:"v"`
  2364. }
  2365. Bar struct {
  2366. Foo `json:",optional"`
  2367. }
  2368. )
  2369. m := map[string]any{}
  2370. var b Bar
  2371. if assert.NoError(t, NewUnmarshaler(jsonTagKey).Unmarshal(m, &b)) {
  2372. assert.True(t, len(b.Name) == 0)
  2373. assert.True(t, len(b.Value) == 0)
  2374. }
  2375. }
  2376. func TestUnmarshalAnonymousOptionalOneRequiredOneOptionalRequiredProvidedOptionalMissed(t *testing.T) {
  2377. type (
  2378. Foo struct {
  2379. Name string `json:"n,optional"`
  2380. Value string `json:"v"`
  2381. }
  2382. Bar struct {
  2383. Foo `json:",optional"`
  2384. }
  2385. )
  2386. m := map[string]any{
  2387. "v": "anything",
  2388. }
  2389. var b Bar
  2390. if assert.NoError(t, NewUnmarshaler(jsonTagKey).Unmarshal(m, &b)) {
  2391. assert.True(t, len(b.Name) == 0)
  2392. assert.Equal(t, "anything", b.Value)
  2393. }
  2394. }
  2395. func TestUnmarshalAnonymousOptionalOneRequiredOneOptionalRequiredMissedOptionalProvided(t *testing.T) {
  2396. type (
  2397. Foo struct {
  2398. Name string `json:"n,optional"`
  2399. Value string `json:"v"`
  2400. }
  2401. Bar struct {
  2402. Foo `json:",optional"`
  2403. }
  2404. )
  2405. m := map[string]any{
  2406. "n": "anything",
  2407. }
  2408. var b Bar
  2409. assert.Error(t, NewUnmarshaler(jsonTagKey).Unmarshal(m, &b))
  2410. }
  2411. func TestUnmarshalAnonymousOptionalBothOptionalBothProvided(t *testing.T) {
  2412. type (
  2413. Foo struct {
  2414. Name string `json:"n,optional"`
  2415. Value string `json:"v,optional"`
  2416. }
  2417. Bar struct {
  2418. Foo `json:",optional"`
  2419. }
  2420. )
  2421. m := map[string]any{
  2422. "n": "kevin",
  2423. "v": "anything",
  2424. }
  2425. var b Bar
  2426. if assert.NoError(t, NewUnmarshaler(jsonTagKey).Unmarshal(m, &b)) {
  2427. assert.Equal(t, "kevin", b.Name)
  2428. assert.Equal(t, "anything", b.Value)
  2429. }
  2430. }
  2431. func TestUnmarshalAnonymousOptionalBothOptionalOneProvidedOneMissed(t *testing.T) {
  2432. type (
  2433. Foo struct {
  2434. Name string `json:"n,optional"`
  2435. Value string `json:"v,optional"`
  2436. }
  2437. Bar struct {
  2438. Foo `json:",optional"`
  2439. }
  2440. )
  2441. m := map[string]any{
  2442. "v": "anything",
  2443. }
  2444. var b Bar
  2445. if assert.NoError(t, NewUnmarshaler(jsonTagKey).Unmarshal(m, &b)) {
  2446. assert.True(t, len(b.Name) == 0)
  2447. assert.Equal(t, "anything", b.Value)
  2448. }
  2449. }
  2450. func TestUnmarshalAnonymousOptionalBothOptionalBothMissed(t *testing.T) {
  2451. type (
  2452. Foo struct {
  2453. Name string `json:"n,optional"`
  2454. Value string `json:"v,optional"`
  2455. }
  2456. Bar struct {
  2457. Foo `json:",optional"`
  2458. }
  2459. )
  2460. m := map[string]any{}
  2461. var b Bar
  2462. if assert.NoError(t, NewUnmarshaler(jsonTagKey).Unmarshal(m, &b)) {
  2463. assert.True(t, len(b.Name) == 0)
  2464. assert.True(t, len(b.Value) == 0)
  2465. }
  2466. }
  2467. func TestUnmarshalAnonymousRequiredProvided(t *testing.T) {
  2468. type (
  2469. Foo struct {
  2470. Value string `json:"v"`
  2471. }
  2472. Bar struct {
  2473. Foo
  2474. }
  2475. )
  2476. m := map[string]any{
  2477. "v": "anything",
  2478. }
  2479. var b Bar
  2480. if assert.NoError(t, NewUnmarshaler(jsonTagKey).Unmarshal(m, &b)) {
  2481. assert.Equal(t, "anything", b.Value)
  2482. }
  2483. }
  2484. func TestUnmarshalAnonymousRequiredMissed(t *testing.T) {
  2485. type (
  2486. Foo struct {
  2487. Value string `json:"v"`
  2488. }
  2489. Bar struct {
  2490. Foo
  2491. }
  2492. )
  2493. m := map[string]any{}
  2494. var b Bar
  2495. assert.Error(t, NewUnmarshaler(jsonTagKey).Unmarshal(m, &b))
  2496. }
  2497. func TestUnmarshalAnonymousOptionalProvided(t *testing.T) {
  2498. type (
  2499. Foo struct {
  2500. Value string `json:"v,optional"`
  2501. }
  2502. Bar struct {
  2503. Foo
  2504. }
  2505. )
  2506. m := map[string]any{
  2507. "v": "anything",
  2508. }
  2509. var b Bar
  2510. if assert.NoError(t, NewUnmarshaler(jsonTagKey).Unmarshal(m, &b)) {
  2511. assert.Equal(t, "anything", b.Value)
  2512. }
  2513. }
  2514. func TestUnmarshalAnonymousOptionalMissed(t *testing.T) {
  2515. type (
  2516. Foo struct {
  2517. Value string `json:"v,optional"`
  2518. }
  2519. Bar struct {
  2520. Foo
  2521. }
  2522. )
  2523. m := map[string]any{}
  2524. var b Bar
  2525. if assert.NoError(t, NewUnmarshaler(jsonTagKey).Unmarshal(m, &b)) {
  2526. assert.True(t, len(b.Value) == 0)
  2527. }
  2528. }
  2529. func TestUnmarshalAnonymousRequiredBothProvided(t *testing.T) {
  2530. type (
  2531. Foo struct {
  2532. Name string `json:"n"`
  2533. Value string `json:"v"`
  2534. }
  2535. Bar struct {
  2536. Foo
  2537. }
  2538. )
  2539. m := map[string]any{
  2540. "n": "kevin",
  2541. "v": "anything",
  2542. }
  2543. var b Bar
  2544. if assert.NoError(t, NewUnmarshaler(jsonTagKey).Unmarshal(m, &b)) {
  2545. assert.Equal(t, "kevin", b.Name)
  2546. assert.Equal(t, "anything", b.Value)
  2547. }
  2548. }
  2549. func TestUnmarshalAnonymousRequiredOneProvidedOneMissed(t *testing.T) {
  2550. type (
  2551. Foo struct {
  2552. Name string `json:"n"`
  2553. Value string `json:"v"`
  2554. }
  2555. Bar struct {
  2556. Foo
  2557. }
  2558. )
  2559. m := map[string]any{
  2560. "v": "anything",
  2561. }
  2562. var b Bar
  2563. assert.Error(t, NewUnmarshaler(jsonTagKey).Unmarshal(m, &b))
  2564. }
  2565. func TestUnmarshalAnonymousRequiredBothMissed(t *testing.T) {
  2566. type (
  2567. Foo struct {
  2568. Name string `json:"n"`
  2569. Value string `json:"v"`
  2570. }
  2571. Bar struct {
  2572. Foo
  2573. }
  2574. )
  2575. m := map[string]any{
  2576. "v": "anything",
  2577. }
  2578. var b Bar
  2579. assert.Error(t, NewUnmarshaler(jsonTagKey).Unmarshal(m, &b))
  2580. }
  2581. func TestUnmarshalAnonymousOneRequiredOneOptionalBothProvided(t *testing.T) {
  2582. type (
  2583. Foo struct {
  2584. Name string `json:"n,optional"`
  2585. Value string `json:"v"`
  2586. }
  2587. Bar struct {
  2588. Foo
  2589. }
  2590. )
  2591. m := map[string]any{
  2592. "n": "kevin",
  2593. "v": "anything",
  2594. }
  2595. var b Bar
  2596. if assert.NoError(t, NewUnmarshaler(jsonTagKey).Unmarshal(m, &b)) {
  2597. assert.Equal(t, "kevin", b.Name)
  2598. assert.Equal(t, "anything", b.Value)
  2599. }
  2600. }
  2601. func TestUnmarshalAnonymousOneRequiredOneOptionalBothMissed(t *testing.T) {
  2602. type (
  2603. Foo struct {
  2604. Name string `json:"n,optional"`
  2605. Value string `json:"v"`
  2606. }
  2607. Bar struct {
  2608. Foo
  2609. }
  2610. )
  2611. m := map[string]any{}
  2612. var b Bar
  2613. assert.Error(t, NewUnmarshaler(jsonTagKey).Unmarshal(m, &b))
  2614. }
  2615. func TestUnmarshalAnonymousOneRequiredOneOptionalRequiredProvidedOptionalMissed(t *testing.T) {
  2616. type (
  2617. Foo struct {
  2618. Name string `json:"n,optional"`
  2619. Value string `json:"v"`
  2620. }
  2621. Bar struct {
  2622. Foo
  2623. }
  2624. )
  2625. m := map[string]any{
  2626. "v": "anything",
  2627. }
  2628. var b Bar
  2629. if assert.NoError(t, NewUnmarshaler(jsonTagKey).Unmarshal(m, &b)) {
  2630. assert.True(t, len(b.Name) == 0)
  2631. assert.Equal(t, "anything", b.Value)
  2632. }
  2633. }
  2634. func TestUnmarshalAnonymousOneRequiredOneOptionalRequiredMissedOptionalProvided(t *testing.T) {
  2635. type (
  2636. Foo struct {
  2637. Name string `json:"n,optional"`
  2638. Value string `json:"v"`
  2639. }
  2640. Bar struct {
  2641. Foo
  2642. }
  2643. )
  2644. m := map[string]any{
  2645. "n": "anything",
  2646. }
  2647. var b Bar
  2648. assert.Error(t, NewUnmarshaler(jsonTagKey).Unmarshal(m, &b))
  2649. }
  2650. func TestUnmarshalAnonymousBothOptionalBothProvided(t *testing.T) {
  2651. type (
  2652. Foo struct {
  2653. Name string `json:"n,optional"`
  2654. Value string `json:"v,optional"`
  2655. }
  2656. Bar struct {
  2657. Foo
  2658. }
  2659. )
  2660. m := map[string]any{
  2661. "n": "kevin",
  2662. "v": "anything",
  2663. }
  2664. var b Bar
  2665. if assert.NoError(t, NewUnmarshaler(jsonTagKey).Unmarshal(m, &b)) {
  2666. assert.Equal(t, "kevin", b.Name)
  2667. assert.Equal(t, "anything", b.Value)
  2668. }
  2669. }
  2670. func TestUnmarshalAnonymousBothOptionalOneProvidedOneMissed(t *testing.T) {
  2671. type (
  2672. Foo struct {
  2673. Name string `json:"n,optional"`
  2674. Value string `json:"v,optional"`
  2675. }
  2676. Bar struct {
  2677. Foo
  2678. }
  2679. )
  2680. m := map[string]any{
  2681. "v": "anything",
  2682. }
  2683. var b Bar
  2684. if assert.NoError(t, NewUnmarshaler(jsonTagKey).Unmarshal(m, &b)) {
  2685. assert.True(t, len(b.Name) == 0)
  2686. assert.Equal(t, "anything", b.Value)
  2687. }
  2688. }
  2689. func TestUnmarshalAnonymousBothOptionalBothMissed(t *testing.T) {
  2690. type (
  2691. Foo struct {
  2692. Name string `json:"n,optional"`
  2693. Value string `json:"v,optional"`
  2694. }
  2695. Bar struct {
  2696. Foo
  2697. }
  2698. )
  2699. m := map[string]any{}
  2700. var b Bar
  2701. if assert.NoError(t, NewUnmarshaler(jsonTagKey).Unmarshal(m, &b)) {
  2702. assert.True(t, len(b.Name) == 0)
  2703. assert.True(t, len(b.Value) == 0)
  2704. }
  2705. }
  2706. func TestUnmarshalAnonymousWrappedToMuch(t *testing.T) {
  2707. type (
  2708. Foo struct {
  2709. Name string `json:"n"`
  2710. Value string `json:"v"`
  2711. }
  2712. Bar struct {
  2713. Foo
  2714. }
  2715. )
  2716. m := map[string]any{
  2717. "Foo": map[string]any{
  2718. "n": "name",
  2719. "v": "anything",
  2720. },
  2721. }
  2722. var b Bar
  2723. assert.Error(t, NewUnmarshaler(jsonTagKey).Unmarshal(m, &b))
  2724. }
  2725. func TestUnmarshalWrappedObject(t *testing.T) {
  2726. type (
  2727. Foo struct {
  2728. Value string `json:"v"`
  2729. }
  2730. Bar struct {
  2731. Inner Foo
  2732. }
  2733. )
  2734. m := map[string]any{
  2735. "Inner": map[string]any{
  2736. "v": "anything",
  2737. },
  2738. }
  2739. var b Bar
  2740. if assert.NoError(t, NewUnmarshaler(jsonTagKey).Unmarshal(m, &b)) {
  2741. assert.Equal(t, "anything", b.Inner.Value)
  2742. }
  2743. }
  2744. func TestUnmarshalWrappedObjectOptional(t *testing.T) {
  2745. type (
  2746. Foo struct {
  2747. Hosts []string
  2748. Key string
  2749. }
  2750. Bar struct {
  2751. Inner Foo `json:",optional"`
  2752. Name string
  2753. }
  2754. )
  2755. m := map[string]any{
  2756. "Name": "anything",
  2757. }
  2758. var b Bar
  2759. if assert.NoError(t, NewUnmarshaler(jsonTagKey).Unmarshal(m, &b)) {
  2760. assert.Equal(t, "anything", b.Name)
  2761. }
  2762. }
  2763. func TestUnmarshalWrappedObjectOptionalFilled(t *testing.T) {
  2764. type (
  2765. Foo struct {
  2766. Hosts []string
  2767. Key string
  2768. }
  2769. Bar struct {
  2770. Inner Foo `json:",optional"`
  2771. Name string
  2772. }
  2773. )
  2774. hosts := []string{"1", "2"}
  2775. m := map[string]any{
  2776. "Inner": map[string]any{
  2777. "Hosts": hosts,
  2778. "Key": "key",
  2779. },
  2780. "Name": "anything",
  2781. }
  2782. var b Bar
  2783. if assert.NoError(t, NewUnmarshaler(jsonTagKey).Unmarshal(m, &b)) {
  2784. assert.EqualValues(t, hosts, b.Inner.Hosts)
  2785. assert.Equal(t, "key", b.Inner.Key)
  2786. assert.Equal(t, "anything", b.Name)
  2787. }
  2788. }
  2789. func TestUnmarshalWrappedNamedObjectOptional(t *testing.T) {
  2790. type (
  2791. Foo struct {
  2792. Host string
  2793. Key string
  2794. }
  2795. Bar struct {
  2796. Inner Foo `json:",optional"`
  2797. Name string
  2798. }
  2799. )
  2800. m := map[string]any{
  2801. "Inner": map[string]any{
  2802. "Host": "thehost",
  2803. "Key": "thekey",
  2804. },
  2805. "Name": "anything",
  2806. }
  2807. var b Bar
  2808. if assert.NoError(t, NewUnmarshaler(jsonTagKey).Unmarshal(m, &b)) {
  2809. assert.Equal(t, "thehost", b.Inner.Host)
  2810. assert.Equal(t, "thekey", b.Inner.Key)
  2811. assert.Equal(t, "anything", b.Name)
  2812. }
  2813. }
  2814. func TestUnmarshalWrappedObjectNamedPtr(t *testing.T) {
  2815. type (
  2816. Foo struct {
  2817. Value string `json:"v"`
  2818. }
  2819. Bar struct {
  2820. Inner *Foo `json:"foo,optional"`
  2821. }
  2822. )
  2823. m := map[string]any{
  2824. "foo": map[string]any{
  2825. "v": "anything",
  2826. },
  2827. }
  2828. var b Bar
  2829. if assert.NoError(t, NewUnmarshaler(jsonTagKey).Unmarshal(m, &b)) {
  2830. assert.Equal(t, "anything", b.Inner.Value)
  2831. }
  2832. }
  2833. func TestUnmarshalWrappedObjectPtr(t *testing.T) {
  2834. type (
  2835. Foo struct {
  2836. Value string `json:"v"`
  2837. }
  2838. Bar struct {
  2839. Inner *Foo
  2840. }
  2841. )
  2842. m := map[string]any{
  2843. "Inner": map[string]any{
  2844. "v": "anything",
  2845. },
  2846. }
  2847. var b Bar
  2848. if assert.NoError(t, NewUnmarshaler(jsonTagKey).Unmarshal(m, &b)) {
  2849. assert.Equal(t, "anything", b.Inner.Value)
  2850. }
  2851. }
  2852. func TestUnmarshalInt2String(t *testing.T) {
  2853. type inner struct {
  2854. Int string `key:"int"`
  2855. }
  2856. m := map[string]any{
  2857. "int": 123,
  2858. }
  2859. var in inner
  2860. assert.Error(t, UnmarshalKey(m, &in))
  2861. }
  2862. func TestUnmarshalZeroValues(t *testing.T) {
  2863. type inner struct {
  2864. False bool `key:"no"`
  2865. Int int `key:"int"`
  2866. String string `key:"string"`
  2867. }
  2868. m := map[string]any{
  2869. "no": false,
  2870. "int": 0,
  2871. "string": "",
  2872. }
  2873. var in inner
  2874. ast := assert.New(t)
  2875. if ast.NoError(UnmarshalKey(m, &in)) {
  2876. ast.False(in.False)
  2877. ast.Equal(0, in.Int)
  2878. ast.Equal("", in.String)
  2879. }
  2880. }
  2881. func TestUnmarshalUsingDifferentKeys(t *testing.T) {
  2882. type inner struct {
  2883. False bool `key:"no"`
  2884. Int int `key:"int"`
  2885. String string `bson:"string"`
  2886. }
  2887. m := map[string]any{
  2888. "no": false,
  2889. "int": 9,
  2890. "string": "value",
  2891. }
  2892. var in inner
  2893. ast := assert.New(t)
  2894. if ast.NoError(UnmarshalKey(m, &in)) {
  2895. ast.False(in.False)
  2896. ast.Equal(9, in.Int)
  2897. ast.True(len(in.String) == 0)
  2898. }
  2899. }
  2900. func TestUnmarshalNumberRangeInt(t *testing.T) {
  2901. type inner struct {
  2902. Value1 int `key:"value1,range=[1:]"`
  2903. Value2 int8 `key:"value2,range=[1:5]"`
  2904. Value3 int16 `key:"value3,range=[1:5]"`
  2905. Value4 int32 `key:"value4,range=[1:5]"`
  2906. Value5 int64 `key:"value5,range=[1:5]"`
  2907. Value6 uint `key:"value6,range=[:5]"`
  2908. Value8 uint8 `key:"value8,range=[1:5],string"`
  2909. Value9 uint16 `key:"value9,range=[1:5],string"`
  2910. Value10 uint32 `key:"value10,range=[1:5],string"`
  2911. Value11 uint64 `key:"value11,range=[1:5],string"`
  2912. }
  2913. m := map[string]any{
  2914. "value1": 10,
  2915. "value2": int8(1),
  2916. "value3": int16(2),
  2917. "value4": int32(4),
  2918. "value5": int64(5),
  2919. "value6": uint(0),
  2920. "value8": "1",
  2921. "value9": "2",
  2922. "value10": "4",
  2923. "value11": "5",
  2924. }
  2925. var in inner
  2926. ast := assert.New(t)
  2927. if ast.NoError(UnmarshalKey(m, &in)) {
  2928. ast.Equal(10, in.Value1)
  2929. ast.Equal(int8(1), in.Value2)
  2930. ast.Equal(int16(2), in.Value3)
  2931. ast.Equal(int32(4), in.Value4)
  2932. ast.Equal(int64(5), in.Value5)
  2933. ast.Equal(uint(0), in.Value6)
  2934. ast.Equal(uint8(1), in.Value8)
  2935. ast.Equal(uint16(2), in.Value9)
  2936. ast.Equal(uint32(4), in.Value10)
  2937. ast.Equal(uint64(5), in.Value11)
  2938. }
  2939. }
  2940. func TestUnmarshalNumberRangeJsonNumber(t *testing.T) {
  2941. type inner struct {
  2942. Value3 uint `key:"value3,range=(1:5]"`
  2943. Value4 uint8 `key:"value4,range=(1:5]"`
  2944. Value5 uint16 `key:"value5,range=(1:5]"`
  2945. }
  2946. m := map[string]any{
  2947. "value3": json.Number("2"),
  2948. "value4": json.Number("4"),
  2949. "value5": json.Number("5"),
  2950. }
  2951. var in inner
  2952. ast := assert.New(t)
  2953. if ast.NoError(UnmarshalKey(m, &in)) {
  2954. ast.Equal(uint(2), in.Value3)
  2955. ast.Equal(uint8(4), in.Value4)
  2956. ast.Equal(uint16(5), in.Value5)
  2957. }
  2958. type inner1 struct {
  2959. Value int `key:"value,range=(1:5]"`
  2960. }
  2961. m = map[string]any{
  2962. "value": json.Number("a"),
  2963. }
  2964. var in1 inner1
  2965. ast.Error(UnmarshalKey(m, &in1))
  2966. }
  2967. func TestUnmarshalNumberRangeIntLeftExclude(t *testing.T) {
  2968. type inner struct {
  2969. Value3 uint `key:"value3,range=(1:5]"`
  2970. Value4 uint32 `key:"value4,default=4,range=(1:5]"`
  2971. Value5 uint64 `key:"value5,range=(1:5]"`
  2972. Value9 int `key:"value9,range=(1:5],string"`
  2973. Value10 int `key:"value10,range=(1:5],string"`
  2974. Value11 int `key:"value11,range=(1:5],string"`
  2975. }
  2976. m := map[string]any{
  2977. "value3": uint(2),
  2978. "value4": uint32(4),
  2979. "value5": uint64(5),
  2980. "value9": "2",
  2981. "value10": "4",
  2982. "value11": "5",
  2983. }
  2984. var in inner
  2985. ast := assert.New(t)
  2986. if ast.NoError(UnmarshalKey(m, &in)) {
  2987. ast.Equal(uint(2), in.Value3)
  2988. ast.Equal(uint32(4), in.Value4)
  2989. ast.Equal(uint64(5), in.Value5)
  2990. ast.Equal(2, in.Value9)
  2991. ast.Equal(4, in.Value10)
  2992. ast.Equal(5, in.Value11)
  2993. }
  2994. }
  2995. func TestUnmarshalNumberRangeIntRightExclude(t *testing.T) {
  2996. type inner struct {
  2997. Value2 uint `key:"value2,range=[1:5)"`
  2998. Value3 uint8 `key:"value3,range=[1:5)"`
  2999. Value4 uint16 `key:"value4,range=[1:5)"`
  3000. Value8 int `key:"value8,range=[1:5),string"`
  3001. Value9 int `key:"value9,range=[1:5),string"`
  3002. Value10 int `key:"value10,range=[1:5),string"`
  3003. }
  3004. m := map[string]any{
  3005. "value2": uint(1),
  3006. "value3": uint8(2),
  3007. "value4": uint16(4),
  3008. "value8": "1",
  3009. "value9": "2",
  3010. "value10": "4",
  3011. }
  3012. var in inner
  3013. ast := assert.New(t)
  3014. if ast.NoError(UnmarshalKey(m, &in)) {
  3015. ast.Equal(uint(1), in.Value2)
  3016. ast.Equal(uint8(2), in.Value3)
  3017. ast.Equal(uint16(4), in.Value4)
  3018. ast.Equal(1, in.Value8)
  3019. ast.Equal(2, in.Value9)
  3020. ast.Equal(4, in.Value10)
  3021. }
  3022. }
  3023. func TestUnmarshalNumberRangeIntExclude(t *testing.T) {
  3024. type inner struct {
  3025. Value3 int `key:"value3,range=(1:5)"`
  3026. Value4 int `key:"value4,range=(1:5)"`
  3027. Value9 int `key:"value9,range=(1:5),string"`
  3028. Value10 int `key:"value10,range=(1:5),string"`
  3029. }
  3030. m := map[string]any{
  3031. "value3": 2,
  3032. "value4": 4,
  3033. "value9": "2",
  3034. "value10": "4",
  3035. }
  3036. var in inner
  3037. ast := assert.New(t)
  3038. if ast.NoError(UnmarshalKey(m, &in)) {
  3039. ast.Equal(2, in.Value3)
  3040. ast.Equal(4, in.Value4)
  3041. ast.Equal(2, in.Value9)
  3042. ast.Equal(4, in.Value10)
  3043. }
  3044. }
  3045. func TestUnmarshalNumberRangeIntOutOfRange(t *testing.T) {
  3046. type inner1 struct {
  3047. Value int64 `key:"value,default=3,range=(1:5)"`
  3048. }
  3049. var in1 inner1
  3050. assert.Equal(t, errNumberRange, UnmarshalKey(map[string]any{
  3051. "value": int64(1),
  3052. }, &in1))
  3053. assert.Equal(t, errNumberRange, UnmarshalKey(map[string]any{
  3054. "value": int64(0),
  3055. }, &in1))
  3056. assert.Equal(t, errNumberRange, UnmarshalKey(map[string]any{
  3057. "value": int64(5),
  3058. }, &in1))
  3059. assert.Equal(t, errNumberRange, UnmarshalKey(map[string]any{
  3060. "value": json.Number("6"),
  3061. }, &in1))
  3062. type inner2 struct {
  3063. Value int64 `key:"value,optional,range=[1:5)"`
  3064. }
  3065. var in2 inner2
  3066. assert.Equal(t, errNumberRange, UnmarshalKey(map[string]any{
  3067. "value": int64(0),
  3068. }, &in2))
  3069. assert.Equal(t, errNumberRange, UnmarshalKey(map[string]any{
  3070. "value": int64(5),
  3071. }, &in2))
  3072. type inner3 struct {
  3073. Value int64 `key:"value,range=(1:5]"`
  3074. }
  3075. var in3 inner3
  3076. assert.Equal(t, errNumberRange, UnmarshalKey(map[string]any{
  3077. "value": int64(1),
  3078. }, &in3))
  3079. assert.Equal(t, errNumberRange, UnmarshalKey(map[string]any{
  3080. "value": int64(6),
  3081. }, &in3))
  3082. type inner4 struct {
  3083. Value int64 `key:"value,range=[1:5]"`
  3084. }
  3085. var in4 inner4
  3086. assert.Equal(t, errNumberRange, UnmarshalKey(map[string]any{
  3087. "value": int64(0),
  3088. }, &in4))
  3089. assert.Equal(t, errNumberRange, UnmarshalKey(map[string]any{
  3090. "value": int64(6),
  3091. }, &in4))
  3092. }
  3093. func TestUnmarshalNumberRangeFloat(t *testing.T) {
  3094. type inner struct {
  3095. Value2 float32 `key:"value2,range=[1:5]"`
  3096. Value3 float32 `key:"value3,range=[1:5]"`
  3097. Value4 float64 `key:"value4,range=[1:5]"`
  3098. Value5 float64 `key:"value5,range=[1:5]"`
  3099. Value8 float64 `key:"value8,range=[1:5],string"`
  3100. Value9 float64 `key:"value9,range=[1:5],string"`
  3101. Value10 float64 `key:"value10,range=[1:5],string"`
  3102. Value11 float64 `key:"value11,range=[1:5],string"`
  3103. }
  3104. m := map[string]any{
  3105. "value2": float32(1),
  3106. "value3": float32(2),
  3107. "value4": float64(4),
  3108. "value5": float64(5),
  3109. "value8": "1",
  3110. "value9": "2",
  3111. "value10": "4",
  3112. "value11": "5",
  3113. }
  3114. var in inner
  3115. ast := assert.New(t)
  3116. if ast.NoError(UnmarshalKey(m, &in)) {
  3117. ast.Equal(float32(1), in.Value2)
  3118. ast.Equal(float32(2), in.Value3)
  3119. ast.Equal(float64(4), in.Value4)
  3120. ast.Equal(float64(5), in.Value5)
  3121. ast.Equal(float64(1), in.Value8)
  3122. ast.Equal(float64(2), in.Value9)
  3123. ast.Equal(float64(4), in.Value10)
  3124. ast.Equal(float64(5), in.Value11)
  3125. }
  3126. }
  3127. func TestUnmarshalNumberRangeFloatLeftExclude(t *testing.T) {
  3128. type inner struct {
  3129. Value3 float64 `key:"value3,range=(1:5]"`
  3130. Value4 float64 `key:"value4,range=(1:5]"`
  3131. Value5 float64 `key:"value5,range=(1:5]"`
  3132. Value9 float64 `key:"value9,range=(1:5],string"`
  3133. Value10 float64 `key:"value10,range=(1:5],string"`
  3134. Value11 float64 `key:"value11,range=(1:5],string"`
  3135. }
  3136. m := map[string]any{
  3137. "value3": float64(2),
  3138. "value4": float64(4),
  3139. "value5": float64(5),
  3140. "value9": "2",
  3141. "value10": "4",
  3142. "value11": "5",
  3143. }
  3144. var in inner
  3145. ast := assert.New(t)
  3146. if ast.NoError(UnmarshalKey(m, &in)) {
  3147. ast.Equal(float64(2), in.Value3)
  3148. ast.Equal(float64(4), in.Value4)
  3149. ast.Equal(float64(5), in.Value5)
  3150. ast.Equal(float64(2), in.Value9)
  3151. ast.Equal(float64(4), in.Value10)
  3152. ast.Equal(float64(5), in.Value11)
  3153. }
  3154. }
  3155. func TestUnmarshalNumberRangeFloatRightExclude(t *testing.T) {
  3156. type inner struct {
  3157. Value2 float64 `key:"value2,range=[1:5)"`
  3158. Value3 float64 `key:"value3,range=[1:5)"`
  3159. Value4 float64 `key:"value4,range=[1:5)"`
  3160. Value8 float64 `key:"value8,range=[1:5),string"`
  3161. Value9 float64 `key:"value9,range=[1:5),string"`
  3162. Value10 float64 `key:"value10,range=[1:5),string"`
  3163. }
  3164. m := map[string]any{
  3165. "value2": float64(1),
  3166. "value3": float64(2),
  3167. "value4": float64(4),
  3168. "value8": "1",
  3169. "value9": "2",
  3170. "value10": "4",
  3171. }
  3172. var in inner
  3173. ast := assert.New(t)
  3174. if ast.NoError(UnmarshalKey(m, &in)) {
  3175. ast.Equal(float64(1), in.Value2)
  3176. ast.Equal(float64(2), in.Value3)
  3177. ast.Equal(float64(4), in.Value4)
  3178. ast.Equal(float64(1), in.Value8)
  3179. ast.Equal(float64(2), in.Value9)
  3180. ast.Equal(float64(4), in.Value10)
  3181. }
  3182. }
  3183. func TestUnmarshalNumberRangeFloatExclude(t *testing.T) {
  3184. type inner struct {
  3185. Value3 float64 `key:"value3,range=(1:5)"`
  3186. Value4 float64 `key:"value4,range=(1:5)"`
  3187. Value9 float64 `key:"value9,range=(1:5),string"`
  3188. Value10 float64 `key:"value10,range=(1:5),string"`
  3189. }
  3190. m := map[string]any{
  3191. "value3": float64(2),
  3192. "value4": float64(4),
  3193. "value9": "2",
  3194. "value10": "4",
  3195. }
  3196. var in inner
  3197. ast := assert.New(t)
  3198. if ast.NoError(UnmarshalKey(m, &in)) {
  3199. ast.Equal(float64(2), in.Value3)
  3200. ast.Equal(float64(4), in.Value4)
  3201. ast.Equal(float64(2), in.Value9)
  3202. ast.Equal(float64(4), in.Value10)
  3203. }
  3204. }
  3205. func TestUnmarshalNumberRangeFloatOutOfRange(t *testing.T) {
  3206. type inner1 struct {
  3207. Value float64 `key:"value,range=(1:5)"`
  3208. }
  3209. var in1 inner1
  3210. assert.Equal(t, errNumberRange, UnmarshalKey(map[string]any{
  3211. "value": float64(1),
  3212. }, &in1))
  3213. assert.Equal(t, errNumberRange, UnmarshalKey(map[string]any{
  3214. "value": float64(0),
  3215. }, &in1))
  3216. assert.Equal(t, errNumberRange, UnmarshalKey(map[string]any{
  3217. "value": float64(5),
  3218. }, &in1))
  3219. assert.Equal(t, errNumberRange, UnmarshalKey(map[string]any{
  3220. "value": json.Number("6"),
  3221. }, &in1))
  3222. type inner2 struct {
  3223. Value float64 `key:"value,range=[1:5)"`
  3224. }
  3225. var in2 inner2
  3226. assert.Equal(t, errNumberRange, UnmarshalKey(map[string]any{
  3227. "value": float64(0),
  3228. }, &in2))
  3229. assert.Equal(t, errNumberRange, UnmarshalKey(map[string]any{
  3230. "value": float64(5),
  3231. }, &in2))
  3232. type inner3 struct {
  3233. Value float64 `key:"value,range=(1:5]"`
  3234. }
  3235. var in3 inner3
  3236. assert.Equal(t, errNumberRange, UnmarshalKey(map[string]any{
  3237. "value": float64(1),
  3238. }, &in3))
  3239. assert.Equal(t, errNumberRange, UnmarshalKey(map[string]any{
  3240. "value": float64(6),
  3241. }, &in3))
  3242. type inner4 struct {
  3243. Value float64 `key:"value,range=[1:5]"`
  3244. }
  3245. var in4 inner4
  3246. assert.Equal(t, errNumberRange, UnmarshalKey(map[string]any{
  3247. "value": float64(0),
  3248. }, &in4))
  3249. assert.Equal(t, errNumberRange, UnmarshalKey(map[string]any{
  3250. "value": float64(6),
  3251. }, &in4))
  3252. }
  3253. func TestUnmarshalRangeError(t *testing.T) {
  3254. type inner1 struct {
  3255. Value int `key:",range="`
  3256. }
  3257. var in1 inner1
  3258. assert.Equal(t, errNumberRange, UnmarshalKey(map[string]any{
  3259. "Value": 1,
  3260. }, &in1))
  3261. type inner2 struct {
  3262. Value int `key:",range=["`
  3263. }
  3264. var in2 inner2
  3265. assert.Equal(t, errNumberRange, UnmarshalKey(map[string]any{
  3266. "Value": 1,
  3267. }, &in2))
  3268. type inner3 struct {
  3269. Value int `key:",range=[:"`
  3270. }
  3271. var in3 inner3
  3272. assert.Equal(t, errNumberRange, UnmarshalKey(map[string]any{
  3273. "Value": 1,
  3274. }, &in3))
  3275. type inner4 struct {
  3276. Value int `key:",range=[:]"`
  3277. }
  3278. var in4 inner4
  3279. assert.Equal(t, errNumberRange, UnmarshalKey(map[string]any{
  3280. "Value": 1,
  3281. }, &in4))
  3282. type inner5 struct {
  3283. Value int `key:",range={:]"`
  3284. }
  3285. var in5 inner5
  3286. assert.Equal(t, errNumberRange, UnmarshalKey(map[string]any{
  3287. "Value": 1,
  3288. }, &in5))
  3289. type inner6 struct {
  3290. Value int `key:",range=[:}"`
  3291. }
  3292. var in6 inner6
  3293. assert.Equal(t, errNumberRange, UnmarshalKey(map[string]any{
  3294. "Value": 1,
  3295. }, &in6))
  3296. type inner7 struct {
  3297. Value int `key:",range=[]"`
  3298. }
  3299. var in7 inner7
  3300. assert.Equal(t, errNumberRange, UnmarshalKey(map[string]any{
  3301. "Value": 1,
  3302. }, &in7))
  3303. type inner8 struct {
  3304. Value int `key:",range=[a:]"`
  3305. }
  3306. var in8 inner8
  3307. assert.Error(t, UnmarshalKey(map[string]any{
  3308. "Value": 1,
  3309. }, &in8))
  3310. type inner9 struct {
  3311. Value int `key:",range=[:a]"`
  3312. }
  3313. var in9 inner9
  3314. assert.Error(t, UnmarshalKey(map[string]any{
  3315. "Value": 1,
  3316. }, &in9))
  3317. type inner10 struct {
  3318. Value int `key:",range"`
  3319. }
  3320. var in10 inner10
  3321. assert.Error(t, UnmarshalKey(map[string]any{
  3322. "Value": 1,
  3323. }, &in10))
  3324. type inner11 struct {
  3325. Value int `key:",range=[1,2]"`
  3326. }
  3327. var in11 inner11
  3328. assert.Equal(t, errNumberRange, UnmarshalKey(map[string]any{
  3329. "Value": "a",
  3330. }, &in11))
  3331. }
  3332. func TestUnmarshalNestedMap(t *testing.T) {
  3333. t.Run("nested map", func(t *testing.T) {
  3334. var c struct {
  3335. Anything map[string]map[string]string `json:"anything"`
  3336. }
  3337. m := map[string]any{
  3338. "anything": map[string]map[string]any{
  3339. "inner": {
  3340. "id": "1",
  3341. "name": "any",
  3342. },
  3343. },
  3344. }
  3345. if assert.NoError(t, NewUnmarshaler(jsonTagKey).Unmarshal(m, &c)) {
  3346. assert.Equal(t, "1", c.Anything["inner"]["id"])
  3347. }
  3348. })
  3349. t.Run("nested map with slice element", func(t *testing.T) {
  3350. var c struct {
  3351. Anything map[string][]string `json:"anything"`
  3352. }
  3353. m := map[string]any{
  3354. "anything": map[string][]any{
  3355. "inner": {
  3356. "id",
  3357. "name",
  3358. },
  3359. },
  3360. }
  3361. if assert.NoError(t, NewUnmarshaler(jsonTagKey).Unmarshal(m, &c)) {
  3362. assert.Equal(t, []string{"id", "name"}, c.Anything["inner"])
  3363. }
  3364. })
  3365. t.Run("nested map with slice element error", func(t *testing.T) {
  3366. var c struct {
  3367. Anything map[string][]string `json:"anything"`
  3368. }
  3369. m := map[string]any{
  3370. "anything": map[string][]any{
  3371. "inner": {
  3372. "id",
  3373. 1,
  3374. },
  3375. },
  3376. }
  3377. assert.Error(t, NewUnmarshaler(jsonTagKey).Unmarshal(m, &c))
  3378. })
  3379. }
  3380. func TestUnmarshalNestedMapMismatch(t *testing.T) {
  3381. var c struct {
  3382. Anything map[string]map[string]map[string]string `json:"anything"`
  3383. }
  3384. m := map[string]any{
  3385. "anything": map[string]map[string]any{
  3386. "inner": {
  3387. "name": "any",
  3388. },
  3389. },
  3390. }
  3391. assert.Error(t, NewUnmarshaler(jsonTagKey).Unmarshal(m, &c))
  3392. }
  3393. func TestUnmarshalNestedMapSimple(t *testing.T) {
  3394. var c struct {
  3395. Anything map[string]string `json:"anything"`
  3396. }
  3397. m := map[string]any{
  3398. "anything": map[string]any{
  3399. "id": "1",
  3400. "name": "any",
  3401. },
  3402. }
  3403. if assert.NoError(t, NewUnmarshaler(jsonTagKey).Unmarshal(m, &c)) {
  3404. assert.Equal(t, "1", c.Anything["id"])
  3405. }
  3406. }
  3407. func TestUnmarshalNestedMapSimpleTypeMatch(t *testing.T) {
  3408. var c struct {
  3409. Anything map[string]string `json:"anything"`
  3410. }
  3411. m := map[string]any{
  3412. "anything": map[string]string{
  3413. "id": "1",
  3414. "name": "any",
  3415. },
  3416. }
  3417. if assert.NoError(t, NewUnmarshaler(jsonTagKey).Unmarshal(m, &c)) {
  3418. assert.Equal(t, "1", c.Anything["id"])
  3419. }
  3420. }
  3421. func TestUnmarshalInheritPrimitiveUseParent(t *testing.T) {
  3422. type (
  3423. component struct {
  3424. Name string `key:"name"`
  3425. Discovery string `key:"discovery,inherit"`
  3426. }
  3427. server struct {
  3428. Discovery string `key:"discovery"`
  3429. Component component `key:"component"`
  3430. }
  3431. )
  3432. var s server
  3433. if assert.NoError(t, UnmarshalKey(map[string]any{
  3434. "discovery": "localhost:8080",
  3435. "component": map[string]any{
  3436. "name": "test",
  3437. },
  3438. }, &s)) {
  3439. assert.Equal(t, "localhost:8080", s.Discovery)
  3440. assert.Equal(t, "localhost:8080", s.Component.Discovery)
  3441. }
  3442. }
  3443. func TestUnmarshalInheritPrimitiveUseSelf(t *testing.T) {
  3444. type (
  3445. component struct {
  3446. Name string `key:"name"`
  3447. Discovery string `key:"discovery,inherit"`
  3448. }
  3449. server struct {
  3450. Discovery string `key:"discovery"`
  3451. Component component `key:"component"`
  3452. }
  3453. )
  3454. var s server
  3455. if assert.NoError(t, UnmarshalKey(map[string]any{
  3456. "discovery": "localhost:8080",
  3457. "component": map[string]any{
  3458. "name": "test",
  3459. "discovery": "localhost:8888",
  3460. },
  3461. }, &s)) {
  3462. assert.Equal(t, "localhost:8080", s.Discovery)
  3463. assert.Equal(t, "localhost:8888", s.Component.Discovery)
  3464. }
  3465. }
  3466. func TestUnmarshalInheritPrimitiveNotExist(t *testing.T) {
  3467. type (
  3468. component struct {
  3469. Name string `key:"name"`
  3470. Discovery string `key:"discovery,inherit"`
  3471. }
  3472. server struct {
  3473. Component component `key:"component"`
  3474. }
  3475. )
  3476. var s server
  3477. assert.Error(t, UnmarshalKey(map[string]any{
  3478. "component": map[string]any{
  3479. "name": "test",
  3480. },
  3481. }, &s))
  3482. }
  3483. func TestUnmarshalInheritStructUseParent(t *testing.T) {
  3484. type (
  3485. discovery struct {
  3486. Host string `key:"host"`
  3487. Port int `key:"port"`
  3488. }
  3489. component struct {
  3490. Name string `key:"name"`
  3491. Discovery discovery `key:"discovery,inherit"`
  3492. }
  3493. server struct {
  3494. Discovery discovery `key:"discovery"`
  3495. Component component `key:"component"`
  3496. }
  3497. )
  3498. var s server
  3499. if assert.NoError(t, UnmarshalKey(map[string]any{
  3500. "discovery": map[string]any{
  3501. "host": "localhost",
  3502. "port": 8080,
  3503. },
  3504. "component": map[string]any{
  3505. "name": "test",
  3506. },
  3507. }, &s)) {
  3508. assert.Equal(t, "localhost", s.Discovery.Host)
  3509. assert.Equal(t, 8080, s.Discovery.Port)
  3510. assert.Equal(t, "localhost", s.Component.Discovery.Host)
  3511. assert.Equal(t, 8080, s.Component.Discovery.Port)
  3512. }
  3513. }
  3514. func TestUnmarshalInheritStructUseSelf(t *testing.T) {
  3515. type (
  3516. discovery struct {
  3517. Host string `key:"host"`
  3518. Port int `key:"port"`
  3519. }
  3520. component struct {
  3521. Name string `key:"name"`
  3522. Discovery discovery `key:"discovery,inherit"`
  3523. }
  3524. server struct {
  3525. Discovery discovery `key:"discovery"`
  3526. Component component `key:"component"`
  3527. }
  3528. )
  3529. var s server
  3530. if assert.NoError(t, UnmarshalKey(map[string]any{
  3531. "discovery": map[string]any{
  3532. "host": "localhost",
  3533. "port": 8080,
  3534. },
  3535. "component": map[string]any{
  3536. "name": "test",
  3537. "discovery": map[string]any{
  3538. "host": "remotehost",
  3539. "port": 8888,
  3540. },
  3541. },
  3542. }, &s)) {
  3543. assert.Equal(t, "localhost", s.Discovery.Host)
  3544. assert.Equal(t, 8080, s.Discovery.Port)
  3545. assert.Equal(t, "remotehost", s.Component.Discovery.Host)
  3546. assert.Equal(t, 8888, s.Component.Discovery.Port)
  3547. }
  3548. }
  3549. func TestUnmarshalInheritStructNotExist(t *testing.T) {
  3550. type (
  3551. discovery struct {
  3552. Host string `key:"host"`
  3553. Port int `key:"port"`
  3554. }
  3555. component struct {
  3556. Name string `key:"name"`
  3557. Discovery discovery `key:"discovery,inherit"`
  3558. }
  3559. server struct {
  3560. Component component `key:"component"`
  3561. }
  3562. )
  3563. var s server
  3564. assert.Error(t, UnmarshalKey(map[string]any{
  3565. "component": map[string]any{
  3566. "name": "test",
  3567. },
  3568. }, &s))
  3569. }
  3570. func TestUnmarshalInheritStructUsePartial(t *testing.T) {
  3571. type (
  3572. discovery struct {
  3573. Host string `key:"host"`
  3574. Port int `key:"port"`
  3575. }
  3576. component struct {
  3577. Name string `key:"name"`
  3578. Discovery discovery `key:"discovery,inherit"`
  3579. }
  3580. server struct {
  3581. Discovery discovery `key:"discovery"`
  3582. Component component `key:"component"`
  3583. }
  3584. )
  3585. var s server
  3586. if assert.NoError(t, UnmarshalKey(map[string]any{
  3587. "discovery": map[string]any{
  3588. "host": "localhost",
  3589. "port": 8080,
  3590. },
  3591. "component": map[string]any{
  3592. "name": "test",
  3593. "discovery": map[string]any{
  3594. "port": 8888,
  3595. },
  3596. },
  3597. }, &s)) {
  3598. assert.Equal(t, "localhost", s.Discovery.Host)
  3599. assert.Equal(t, 8080, s.Discovery.Port)
  3600. assert.Equal(t, "localhost", s.Component.Discovery.Host)
  3601. assert.Equal(t, 8888, s.Component.Discovery.Port)
  3602. }
  3603. }
  3604. func TestUnmarshalInheritStructUseSelfIncorrectType(t *testing.T) {
  3605. type (
  3606. discovery struct {
  3607. Host string `key:"host"`
  3608. Port int `key:"port"`
  3609. }
  3610. component struct {
  3611. Name string `key:"name"`
  3612. Discovery discovery `key:"discovery,inherit"`
  3613. }
  3614. server struct {
  3615. Discovery discovery `key:"discovery"`
  3616. Component component `key:"component"`
  3617. }
  3618. )
  3619. var s server
  3620. assert.Error(t, UnmarshalKey(map[string]any{
  3621. "discovery": map[string]any{
  3622. "host": "localhost",
  3623. },
  3624. "component": map[string]any{
  3625. "name": "test",
  3626. "discovery": map[string]string{
  3627. "host": "remotehost",
  3628. },
  3629. },
  3630. }, &s))
  3631. }
  3632. func TestUnmarshaler_InheritFromGrandparent(t *testing.T) {
  3633. type (
  3634. component struct {
  3635. Name string `key:"name"`
  3636. Discovery string `key:"discovery,inherit"`
  3637. }
  3638. middle struct {
  3639. Value component `key:"value"`
  3640. }
  3641. server struct {
  3642. Discovery string `key:"discovery"`
  3643. Middle middle `key:"middle"`
  3644. }
  3645. )
  3646. var s server
  3647. if assert.NoError(t, UnmarshalKey(map[string]any{
  3648. "discovery": "localhost:8080",
  3649. "middle": map[string]any{
  3650. "value": map[string]any{
  3651. "name": "test",
  3652. },
  3653. },
  3654. }, &s)) {
  3655. assert.Equal(t, "localhost:8080", s.Discovery)
  3656. assert.Equal(t, "localhost:8080", s.Middle.Value.Discovery)
  3657. }
  3658. }
  3659. func TestUnmarshaler_InheritSequence(t *testing.T) {
  3660. var testConf = []byte(`
  3661. Nacos:
  3662. NamespaceId: "123"
  3663. RpcConf:
  3664. Nacos:
  3665. NamespaceId: "456"
  3666. Name: hello
  3667. `)
  3668. type (
  3669. NacosConf struct {
  3670. NamespaceId string
  3671. }
  3672. RpcConf struct {
  3673. Nacos NacosConf `json:",inherit"`
  3674. Name string
  3675. }
  3676. Config1 struct {
  3677. RpcConf RpcConf
  3678. Nacos NacosConf
  3679. }
  3680. Config2 struct {
  3681. RpcConf RpcConf
  3682. Nacos NacosConf
  3683. }
  3684. )
  3685. var c1 Config1
  3686. if assert.NoError(t, UnmarshalYamlBytes(testConf, &c1)) {
  3687. assert.Equal(t, "123", c1.Nacos.NamespaceId)
  3688. assert.Equal(t, "456", c1.RpcConf.Nacos.NamespaceId)
  3689. }
  3690. var c2 Config2
  3691. if assert.NoError(t, UnmarshalYamlBytes(testConf, &c2)) {
  3692. assert.Equal(t, "123", c1.Nacos.NamespaceId)
  3693. assert.Equal(t, "456", c1.RpcConf.Nacos.NamespaceId)
  3694. }
  3695. }
  3696. func TestUnmarshaler_InheritNested(t *testing.T) {
  3697. var testConf = []byte(`
  3698. Nacos:
  3699. Value1: "123"
  3700. Server:
  3701. Nacos:
  3702. Value2: "456"
  3703. Rpc:
  3704. Nacos:
  3705. Value3: "789"
  3706. Name: hello
  3707. `)
  3708. type (
  3709. NacosConf struct {
  3710. Value1 string `json:",optional"`
  3711. Value2 string `json:",optional"`
  3712. Value3 string `json:",optional"`
  3713. }
  3714. RpcConf struct {
  3715. Nacos NacosConf `json:",inherit"`
  3716. Name string
  3717. }
  3718. ServerConf struct {
  3719. Nacos NacosConf `json:",inherit"`
  3720. Rpc RpcConf
  3721. }
  3722. Config struct {
  3723. Server ServerConf
  3724. Nacos NacosConf
  3725. }
  3726. )
  3727. var c Config
  3728. if assert.NoError(t, UnmarshalYamlBytes(testConf, &c)) {
  3729. assert.Equal(t, "123", c.Nacos.Value1)
  3730. assert.Empty(t, c.Nacos.Value2)
  3731. assert.Empty(t, c.Nacos.Value3)
  3732. assert.Equal(t, "123", c.Server.Nacos.Value1)
  3733. assert.Equal(t, "456", c.Server.Nacos.Value2)
  3734. assert.Empty(t, c.Nacos.Value3)
  3735. assert.Equal(t, "123", c.Server.Rpc.Nacos.Value1)
  3736. assert.Equal(t, "456", c.Server.Rpc.Nacos.Value2)
  3737. assert.Equal(t, "789", c.Server.Rpc.Nacos.Value3)
  3738. }
  3739. }
  3740. func TestUnmarshalValuer(t *testing.T) {
  3741. unmarshaler := NewUnmarshaler(jsonTagKey)
  3742. var foo string
  3743. err := unmarshaler.UnmarshalValuer(nil, foo)
  3744. assert.Error(t, err)
  3745. }
  3746. func TestUnmarshal_EnvString(t *testing.T) {
  3747. t.Run("valid env", func(t *testing.T) {
  3748. type Value struct {
  3749. Name string `key:"name,env=TEST_NAME_STRING"`
  3750. }
  3751. const (
  3752. envName = "TEST_NAME_STRING"
  3753. envVal = "this is a name"
  3754. )
  3755. t.Setenv(envName, envVal)
  3756. var v Value
  3757. if assert.NoError(t, UnmarshalKey(emptyMap, &v)) {
  3758. assert.Equal(t, envVal, v.Name)
  3759. }
  3760. })
  3761. t.Run("invalid env", func(t *testing.T) {
  3762. type Value struct {
  3763. Name string `key:"name,env=TEST_NAME_STRING=invalid"`
  3764. }
  3765. const (
  3766. envName = "TEST_NAME_STRING"
  3767. envVal = "this is a name"
  3768. )
  3769. t.Setenv(envName, envVal)
  3770. var v Value
  3771. assert.Error(t, UnmarshalKey(emptyMap, &v))
  3772. })
  3773. }
  3774. func TestUnmarshal_EnvStringOverwrite(t *testing.T) {
  3775. type Value struct {
  3776. Name string `key:"name,env=TEST_NAME_STRING"`
  3777. }
  3778. const (
  3779. envName = "TEST_NAME_STRING"
  3780. envVal = "this is a name"
  3781. )
  3782. t.Setenv(envName, envVal)
  3783. var v Value
  3784. if assert.NoError(t, UnmarshalKey(map[string]any{
  3785. "name": "local value",
  3786. }, &v)) {
  3787. assert.Equal(t, envVal, v.Name)
  3788. }
  3789. }
  3790. func TestUnmarshal_EnvInt(t *testing.T) {
  3791. type Value struct {
  3792. Age int `key:"age,env=TEST_NAME_INT"`
  3793. }
  3794. const (
  3795. envName = "TEST_NAME_INT"
  3796. envVal = "123"
  3797. )
  3798. t.Setenv(envName, envVal)
  3799. var v Value
  3800. if assert.NoError(t, UnmarshalKey(emptyMap, &v)) {
  3801. assert.Equal(t, 123, v.Age)
  3802. }
  3803. }
  3804. func TestUnmarshal_EnvIntOverwrite(t *testing.T) {
  3805. type Value struct {
  3806. Age int `key:"age,env=TEST_NAME_INT"`
  3807. }
  3808. const (
  3809. envName = "TEST_NAME_INT"
  3810. envVal = "123"
  3811. )
  3812. t.Setenv(envName, envVal)
  3813. var v Value
  3814. if assert.NoError(t, UnmarshalKey(map[string]any{
  3815. "age": 18,
  3816. }, &v)) {
  3817. assert.Equal(t, 123, v.Age)
  3818. }
  3819. }
  3820. func TestUnmarshal_EnvFloat(t *testing.T) {
  3821. type Value struct {
  3822. Age float32 `key:"name,env=TEST_NAME_FLOAT"`
  3823. }
  3824. const (
  3825. envName = "TEST_NAME_FLOAT"
  3826. envVal = "123.45"
  3827. )
  3828. t.Setenv(envName, envVal)
  3829. var v Value
  3830. if assert.NoError(t, UnmarshalKey(emptyMap, &v)) {
  3831. assert.Equal(t, float32(123.45), v.Age)
  3832. }
  3833. }
  3834. func TestUnmarshal_EnvFloatOverwrite(t *testing.T) {
  3835. type Value struct {
  3836. Age float32 `key:"age,env=TEST_NAME_FLOAT"`
  3837. }
  3838. const (
  3839. envName = "TEST_NAME_FLOAT"
  3840. envVal = "123.45"
  3841. )
  3842. t.Setenv(envName, envVal)
  3843. var v Value
  3844. if assert.NoError(t, UnmarshalKey(map[string]any{
  3845. "age": 18.5,
  3846. }, &v)) {
  3847. assert.Equal(t, float32(123.45), v.Age)
  3848. }
  3849. }
  3850. func TestUnmarshal_EnvBoolTrue(t *testing.T) {
  3851. type Value struct {
  3852. Enable bool `key:"enable,env=TEST_NAME_BOOL_TRUE"`
  3853. }
  3854. const (
  3855. envName = "TEST_NAME_BOOL_TRUE"
  3856. envVal = "true"
  3857. )
  3858. t.Setenv(envName, envVal)
  3859. var v Value
  3860. if assert.NoError(t, UnmarshalKey(emptyMap, &v)) {
  3861. assert.True(t, v.Enable)
  3862. }
  3863. }
  3864. func TestUnmarshal_EnvBoolFalse(t *testing.T) {
  3865. type Value struct {
  3866. Enable bool `key:"enable,env=TEST_NAME_BOOL_FALSE"`
  3867. }
  3868. const (
  3869. envName = "TEST_NAME_BOOL_FALSE"
  3870. envVal = "false"
  3871. )
  3872. t.Setenv(envName, envVal)
  3873. var v Value
  3874. if assert.NoError(t, UnmarshalKey(emptyMap, &v)) {
  3875. assert.False(t, v.Enable)
  3876. }
  3877. }
  3878. func TestUnmarshal_EnvBoolBad(t *testing.T) {
  3879. type Value struct {
  3880. Enable bool `key:"enable,env=TEST_NAME_BOOL_BAD"`
  3881. }
  3882. const (
  3883. envName = "TEST_NAME_BOOL_BAD"
  3884. envVal = "bad"
  3885. )
  3886. t.Setenv(envName, envVal)
  3887. var v Value
  3888. assert.Error(t, UnmarshalKey(emptyMap, &v))
  3889. }
  3890. func TestUnmarshal_EnvDuration(t *testing.T) {
  3891. type Value struct {
  3892. Duration time.Duration `key:"duration,env=TEST_NAME_DURATION"`
  3893. }
  3894. const (
  3895. envName = "TEST_NAME_DURATION"
  3896. envVal = "1s"
  3897. )
  3898. t.Setenv(envName, envVal)
  3899. var v Value
  3900. if assert.NoError(t, UnmarshalKey(emptyMap, &v)) {
  3901. assert.Equal(t, time.Second, v.Duration)
  3902. }
  3903. }
  3904. func TestUnmarshal_EnvDurationBadValue(t *testing.T) {
  3905. type Value struct {
  3906. Duration time.Duration `key:"duration,env=TEST_NAME_BAD_DURATION"`
  3907. }
  3908. const (
  3909. envName = "TEST_NAME_BAD_DURATION"
  3910. envVal = "bad"
  3911. )
  3912. t.Setenv(envName, envVal)
  3913. var v Value
  3914. assert.Error(t, UnmarshalKey(emptyMap, &v))
  3915. }
  3916. func TestUnmarshal_EnvWithOptions(t *testing.T) {
  3917. t.Run("valid options", func(t *testing.T) {
  3918. type Value struct {
  3919. Name string `key:"name,env=TEST_NAME_ENV_OPTIONS_MATCH,options=[abc,123,xyz]"`
  3920. }
  3921. const (
  3922. envName = "TEST_NAME_ENV_OPTIONS_MATCH"
  3923. envVal = "123"
  3924. )
  3925. t.Setenv(envName, envVal)
  3926. var v Value
  3927. if assert.NoError(t, UnmarshalKey(emptyMap, &v)) {
  3928. assert.Equal(t, envVal, v.Name)
  3929. }
  3930. })
  3931. }
  3932. func TestUnmarshal_EnvWithOptionsWrongValueBool(t *testing.T) {
  3933. type Value struct {
  3934. Enable bool `key:"enable,env=TEST_NAME_ENV_OPTIONS_BOOL,options=[true]"`
  3935. }
  3936. const (
  3937. envName = "TEST_NAME_ENV_OPTIONS_BOOL"
  3938. envVal = "false"
  3939. )
  3940. t.Setenv(envName, envVal)
  3941. var v Value
  3942. assert.Error(t, UnmarshalKey(emptyMap, &v))
  3943. }
  3944. func TestUnmarshal_EnvWithOptionsWrongValueDuration(t *testing.T) {
  3945. type Value struct {
  3946. Duration time.Duration `key:"duration,env=TEST_NAME_ENV_OPTIONS_DURATION,options=[1s,2s,3s]"`
  3947. }
  3948. const (
  3949. envName = "TEST_NAME_ENV_OPTIONS_DURATION"
  3950. envVal = "4s"
  3951. )
  3952. t.Setenv(envName, envVal)
  3953. var v Value
  3954. assert.Error(t, UnmarshalKey(emptyMap, &v))
  3955. }
  3956. func TestUnmarshal_EnvWithOptionsWrongValueNumber(t *testing.T) {
  3957. type Value struct {
  3958. Age int `key:"age,env=TEST_NAME_ENV_OPTIONS_AGE,options=[18,19,20]"`
  3959. }
  3960. const (
  3961. envName = "TEST_NAME_ENV_OPTIONS_AGE"
  3962. envVal = "30"
  3963. )
  3964. t.Setenv(envName, envVal)
  3965. var v Value
  3966. assert.Error(t, UnmarshalKey(emptyMap, &v))
  3967. }
  3968. func TestUnmarshal_EnvWithOptionsWrongValueString(t *testing.T) {
  3969. type Value struct {
  3970. Name string `key:"name,env=TEST_NAME_ENV_OPTIONS_STRING,options=[abc,123,xyz]"`
  3971. }
  3972. const (
  3973. envName = "TEST_NAME_ENV_OPTIONS_STRING"
  3974. envVal = "this is a name"
  3975. )
  3976. t.Setenv(envName, envVal)
  3977. var v Value
  3978. assert.Error(t, UnmarshalKey(emptyMap, &v))
  3979. }
  3980. func TestUnmarshalJsonReaderMultiArray(t *testing.T) {
  3981. t.Run("reader multi array", func(t *testing.T) {
  3982. var res struct {
  3983. A string `json:"a"`
  3984. B [][]string `json:"b"`
  3985. }
  3986. payload := `{"a": "133", "b": [["add", "cccd"], ["eeee"]]}`
  3987. reader := strings.NewReader(payload)
  3988. if assert.NoError(t, UnmarshalJsonReader(reader, &res)) {
  3989. assert.Equal(t, 2, len(res.B))
  3990. }
  3991. })
  3992. t.Run("reader multi array with error", func(t *testing.T) {
  3993. var res struct {
  3994. A string `json:"a"`
  3995. B [][]string `json:"b"`
  3996. }
  3997. payload := `{"a": "133", "b": ["eeee"]}`
  3998. reader := strings.NewReader(payload)
  3999. assert.Error(t, UnmarshalJsonReader(reader, &res))
  4000. })
  4001. }
  4002. func TestUnmarshalJsonReaderPtrMultiArrayString(t *testing.T) {
  4003. var res struct {
  4004. A string `json:"a"`
  4005. B [][]*string `json:"b"`
  4006. }
  4007. payload := `{"a": "133", "b": [["add", "cccd"], ["eeee"]]}`
  4008. reader := strings.NewReader(payload)
  4009. if assert.NoError(t, UnmarshalJsonReader(reader, &res)) {
  4010. assert.Equal(t, 2, len(res.B))
  4011. assert.Equal(t, 2, len(res.B[0]))
  4012. }
  4013. }
  4014. func TestUnmarshalJsonReaderPtrMultiArrayString_Int(t *testing.T) {
  4015. var res struct {
  4016. A string `json:"a"`
  4017. B [][]*string `json:"b"`
  4018. }
  4019. payload := `{"a": "133", "b": [[11, 22], [33]]}`
  4020. reader := strings.NewReader(payload)
  4021. if assert.NoError(t, UnmarshalJsonReader(reader, &res)) {
  4022. assert.Equal(t, 2, len(res.B))
  4023. assert.Equal(t, 2, len(res.B[0]))
  4024. }
  4025. }
  4026. func TestUnmarshalJsonReaderPtrMultiArrayInt(t *testing.T) {
  4027. var res struct {
  4028. A string `json:"a"`
  4029. B [][]*int `json:"b"`
  4030. }
  4031. payload := `{"a": "133", "b": [[11, 22], [33]]}`
  4032. reader := strings.NewReader(payload)
  4033. if assert.NoError(t, UnmarshalJsonReader(reader, &res)) {
  4034. assert.Equal(t, 2, len(res.B))
  4035. assert.Equal(t, 2, len(res.B[0]))
  4036. }
  4037. }
  4038. func TestUnmarshalJsonReaderPtrArray(t *testing.T) {
  4039. var res struct {
  4040. A string `json:"a"`
  4041. B []*string `json:"b"`
  4042. }
  4043. payload := `{"a": "133", "b": ["add", "cccd", "eeee"]}`
  4044. reader := strings.NewReader(payload)
  4045. if assert.NoError(t, UnmarshalJsonReader(reader, &res)) {
  4046. assert.Equal(t, 3, len(res.B))
  4047. }
  4048. }
  4049. func TestUnmarshalJsonReaderPtrArray_Int(t *testing.T) {
  4050. var res struct {
  4051. A string `json:"a"`
  4052. B []*string `json:"b"`
  4053. }
  4054. payload := `{"a": "133", "b": [11, 22, 33]}`
  4055. reader := strings.NewReader(payload)
  4056. if assert.NoError(t, UnmarshalJsonReader(reader, &res)) {
  4057. assert.Equal(t, 3, len(res.B))
  4058. }
  4059. }
  4060. func TestUnmarshalJsonReaderPtrInt(t *testing.T) {
  4061. var res struct {
  4062. A string `json:"a"`
  4063. B []*string `json:"b"`
  4064. }
  4065. payload := `{"a": "133", "b": [11, 22, 33]}`
  4066. reader := strings.NewReader(payload)
  4067. if assert.NoError(t, UnmarshalJsonReader(reader, &res)) {
  4068. assert.Equal(t, 3, len(res.B))
  4069. }
  4070. }
  4071. func TestUnmarshalJsonWithoutKey(t *testing.T) {
  4072. var res struct {
  4073. A string `json:""`
  4074. B string `json:","`
  4075. }
  4076. payload := `{"A": "1", "B": "2"}`
  4077. reader := strings.NewReader(payload)
  4078. if assert.NoError(t, UnmarshalJsonReader(reader, &res)) {
  4079. assert.Equal(t, "1", res.A)
  4080. assert.Equal(t, "2", res.B)
  4081. }
  4082. }
  4083. func TestUnmarshalJsonUintNegative(t *testing.T) {
  4084. var res struct {
  4085. A uint `json:"a"`
  4086. }
  4087. payload := `{"a": -1}`
  4088. reader := strings.NewReader(payload)
  4089. assert.Error(t, UnmarshalJsonReader(reader, &res))
  4090. }
  4091. func TestUnmarshalJsonDefinedInt(t *testing.T) {
  4092. type Int int
  4093. var res struct {
  4094. A Int `json:"a"`
  4095. }
  4096. payload := `{"a": -1}`
  4097. reader := strings.NewReader(payload)
  4098. if assert.NoError(t, UnmarshalJsonReader(reader, &res)) {
  4099. assert.Equal(t, Int(-1), res.A)
  4100. }
  4101. }
  4102. func TestUnmarshalJsonDefinedString(t *testing.T) {
  4103. type String string
  4104. var res struct {
  4105. A String `json:"a"`
  4106. }
  4107. payload := `{"a": "foo"}`
  4108. reader := strings.NewReader(payload)
  4109. if assert.NoError(t, UnmarshalJsonReader(reader, &res)) {
  4110. assert.Equal(t, String("foo"), res.A)
  4111. }
  4112. }
  4113. func TestUnmarshalJsonDefinedStringPtr(t *testing.T) {
  4114. type String string
  4115. var res struct {
  4116. A *String `json:"a"`
  4117. }
  4118. payload := `{"a": "foo"}`
  4119. reader := strings.NewReader(payload)
  4120. if assert.NoError(t, UnmarshalJsonReader(reader, &res)) {
  4121. assert.Equal(t, String("foo"), *res.A)
  4122. }
  4123. }
  4124. func TestUnmarshalJsonReaderComplex(t *testing.T) {
  4125. type (
  4126. MyInt int
  4127. MyTxt string
  4128. MyTxtArray []string
  4129. Req struct {
  4130. MyInt MyInt `json:"my_int"` // int.. ok
  4131. MyTxtArray MyTxtArray `json:"my_txt_array"`
  4132. MyTxt MyTxt `json:"my_txt"` // but string is not assignable
  4133. Int int `json:"int"`
  4134. Txt string `json:"txt"`
  4135. }
  4136. )
  4137. body := `{
  4138. "my_int": 100,
  4139. "my_txt_array": [
  4140. "a",
  4141. "b"
  4142. ],
  4143. "my_txt": "my_txt",
  4144. "int": 200,
  4145. "txt": "txt"
  4146. }`
  4147. var req Req
  4148. if assert.NoError(t, UnmarshalJsonReader(strings.NewReader(body), &req)) {
  4149. assert.Equal(t, MyInt(100), req.MyInt)
  4150. assert.Equal(t, MyTxt("my_txt"), req.MyTxt)
  4151. assert.EqualValues(t, MyTxtArray([]string{"a", "b"}), req.MyTxtArray)
  4152. assert.Equal(t, 200, req.Int)
  4153. assert.Equal(t, "txt", req.Txt)
  4154. }
  4155. }
  4156. func TestUnmarshalJsonReaderArrayBool(t *testing.T) {
  4157. var res struct {
  4158. ID []string `json:"id"`
  4159. }
  4160. payload := `{"id": false}`
  4161. reader := strings.NewReader(payload)
  4162. assert.Error(t, UnmarshalJsonReader(reader, &res))
  4163. }
  4164. func TestUnmarshalJsonReaderArrayInt(t *testing.T) {
  4165. var res struct {
  4166. ID []string `json:"id"`
  4167. }
  4168. payload := `{"id": 123}`
  4169. reader := strings.NewReader(payload)
  4170. assert.Error(t, UnmarshalJsonReader(reader, &res))
  4171. }
  4172. func TestUnmarshalJsonReaderArrayString(t *testing.T) {
  4173. var res struct {
  4174. ID []string `json:"id"`
  4175. }
  4176. payload := `{"id": "123"}`
  4177. reader := strings.NewReader(payload)
  4178. assert.Error(t, UnmarshalJsonReader(reader, &res))
  4179. }
  4180. func TestGoogleUUID(t *testing.T) {
  4181. var val struct {
  4182. Uid uuid.UUID `json:"uid,optional"`
  4183. Uidp *uuid.UUID `json:"uidp,optional"`
  4184. Uidpp **uuid.UUID `json:"uidpp,optional"`
  4185. Uidppp ***uuid.UUID `json:"uidppp,optional"`
  4186. }
  4187. t.Run("bytes", func(t *testing.T) {
  4188. if assert.NoError(t, UnmarshalJsonBytes([]byte(`{
  4189. "uid": "6ba7b810-9dad-11d1-80b4-00c04fd430c8",
  4190. "uidp": "a0b3d4af-4232-4c7d-b722-7ae879620518",
  4191. "uidpp": "a0b3d4af-4232-4c7d-b722-7ae879620519",
  4192. "uidppp": "6ba7b810-9dad-11d1-80b4-00c04fd430c9"}`), &val)) {
  4193. assert.Equal(t, "6ba7b810-9dad-11d1-80b4-00c04fd430c8", val.Uid.String())
  4194. assert.Equal(t, "a0b3d4af-4232-4c7d-b722-7ae879620518", val.Uidp.String())
  4195. assert.Equal(t, "a0b3d4af-4232-4c7d-b722-7ae879620519", (*val.Uidpp).String())
  4196. assert.Equal(t, "6ba7b810-9dad-11d1-80b4-00c04fd430c9", (**val.Uidppp).String())
  4197. }
  4198. })
  4199. t.Run("map", func(t *testing.T) {
  4200. if assert.NoError(t, UnmarshalJsonMap(map[string]any{
  4201. "uid": []byte("6ba7b810-9dad-11d1-80b4-00c04fd430c1"),
  4202. "uidp": []byte("6ba7b810-9dad-11d1-80b4-00c04fd430c2"),
  4203. "uidpp": []byte("6ba7b810-9dad-11d1-80b4-00c04fd430c3"),
  4204. "uidppp": []byte("6ba7b810-9dad-11d1-80b4-00c04fd430c4"),
  4205. }, &val)) {
  4206. assert.Equal(t, "6ba7b810-9dad-11d1-80b4-00c04fd430c1", val.Uid.String())
  4207. assert.Equal(t, "6ba7b810-9dad-11d1-80b4-00c04fd430c2", val.Uidp.String())
  4208. assert.Equal(t, "6ba7b810-9dad-11d1-80b4-00c04fd430c3", (*val.Uidpp).String())
  4209. assert.Equal(t, "6ba7b810-9dad-11d1-80b4-00c04fd430c4", (**val.Uidppp).String())
  4210. }
  4211. })
  4212. }
  4213. func TestUnmarshalJsonReaderWithTypeMismatchBool(t *testing.T) {
  4214. var req struct {
  4215. Params map[string]bool `json:"params"`
  4216. }
  4217. body := `{"params":{"a":"123"}}`
  4218. assert.Equal(t, errTypeMismatch, UnmarshalJsonReader(strings.NewReader(body), &req))
  4219. }
  4220. func TestUnmarshalJsonReaderWithTypeString(t *testing.T) {
  4221. t.Run("string type", func(t *testing.T) {
  4222. var req struct {
  4223. Params map[string]string `json:"params"`
  4224. }
  4225. body := `{"params":{"a":"b"}}`
  4226. if assert.NoError(t, UnmarshalJsonReader(strings.NewReader(body), &req)) {
  4227. assert.Equal(t, "b", req.Params["a"])
  4228. }
  4229. })
  4230. t.Run("string type mismatch", func(t *testing.T) {
  4231. var req struct {
  4232. Params map[string]string `json:"params"`
  4233. }
  4234. body := `{"params":{"a":{"a":123}}}`
  4235. assert.Equal(t, errTypeMismatch, UnmarshalJsonReader(strings.NewReader(body), &req))
  4236. })
  4237. t.Run("customized string type", func(t *testing.T) {
  4238. type myString string
  4239. var req struct {
  4240. Params map[string]myString `json:"params"`
  4241. }
  4242. body := `{"params":{"a":"b"}}`
  4243. assert.Equal(t, errTypeMismatch, UnmarshalJsonReader(strings.NewReader(body), &req))
  4244. })
  4245. }
  4246. func TestUnmarshalJsonReaderWithMismatchType(t *testing.T) {
  4247. type Req struct {
  4248. Params map[string]string `json:"params"`
  4249. }
  4250. var req Req
  4251. body := `{"params":{"a":{"a":123}}}`
  4252. assert.Equal(t, errTypeMismatch, UnmarshalJsonReader(strings.NewReader(body), &req))
  4253. }
  4254. func TestUnmarshalJsonReaderWithTypeBool(t *testing.T) {
  4255. t.Run("bool type", func(t *testing.T) {
  4256. type Req struct {
  4257. Params map[string]bool `json:"params"`
  4258. }
  4259. tests := []struct {
  4260. name string
  4261. input string
  4262. expect bool
  4263. }{
  4264. {
  4265. name: "int",
  4266. input: `{"params":{"a":1}}`,
  4267. expect: true,
  4268. },
  4269. {
  4270. name: "int",
  4271. input: `{"params":{"a":0}}`,
  4272. expect: false,
  4273. },
  4274. }
  4275. for _, test := range tests {
  4276. test := test
  4277. t.Run(test.name, func(t *testing.T) {
  4278. var req Req
  4279. if assert.NoError(t, UnmarshalJsonReader(strings.NewReader(test.input), &req)) {
  4280. assert.Equal(t, test.expect, req.Params["a"])
  4281. }
  4282. })
  4283. }
  4284. })
  4285. t.Run("bool type mismatch", func(t *testing.T) {
  4286. type Req struct {
  4287. Params map[string]bool `json:"params"`
  4288. }
  4289. tests := []struct {
  4290. name string
  4291. input string
  4292. }{
  4293. {
  4294. name: "int",
  4295. input: `{"params":{"a":123}}`,
  4296. },
  4297. {
  4298. name: "int",
  4299. input: `{"params":{"a":"123"}}`,
  4300. },
  4301. }
  4302. for _, test := range tests {
  4303. test := test
  4304. t.Run(test.name, func(t *testing.T) {
  4305. var req Req
  4306. assert.Equal(t, errTypeMismatch, UnmarshalJsonReader(strings.NewReader(test.input), &req))
  4307. })
  4308. }
  4309. })
  4310. }
  4311. func TestUnmarshalJsonReaderWithTypeBoolMap(t *testing.T) {
  4312. t.Run("bool map", func(t *testing.T) {
  4313. var req struct {
  4314. Params map[string]bool `json:"params"`
  4315. }
  4316. if assert.NoError(t, UnmarshalJsonMap(map[string]any{
  4317. "params": map[string]any{
  4318. "a": true,
  4319. },
  4320. }, &req)) {
  4321. assert.Equal(t, map[string]bool{
  4322. "a": true,
  4323. }, req.Params)
  4324. }
  4325. })
  4326. t.Run("bool map with error", func(t *testing.T) {
  4327. var req struct {
  4328. Params map[string]string `json:"params"`
  4329. }
  4330. assert.Equal(t, errTypeMismatch, UnmarshalJsonMap(map[string]any{
  4331. "params": map[string]any{
  4332. "a": true,
  4333. },
  4334. }, &req))
  4335. })
  4336. }
  4337. func TestUnmarshalJsonBytesSliceOfMaps(t *testing.T) {
  4338. input := []byte(`{
  4339. "order_id": "1234567",
  4340. "refund_reason": {
  4341. "reason_code": [
  4342. 123,
  4343. 234
  4344. ],
  4345. "desc": "not wanted",
  4346. "show_reason": [
  4347. {
  4348. "123": "not enough",
  4349. "234": "closed"
  4350. }
  4351. ]
  4352. },
  4353. "product_detail": {
  4354. "product_id": "123",
  4355. "sku_id": "123",
  4356. "name": "cake",
  4357. "actual_amount": 100
  4358. }
  4359. }`)
  4360. type (
  4361. RefundReasonData struct {
  4362. ReasonCode []int `json:"reason_code"`
  4363. Desc string `json:"desc"`
  4364. ShowReason []map[string]string `json:"show_reason"`
  4365. }
  4366. ProductDetailData struct {
  4367. ProductId string `json:"product_id"`
  4368. SkuId string `json:"sku_id"`
  4369. Name string `json:"name"`
  4370. ActualAmount int `json:"actual_amount"`
  4371. }
  4372. OrderApplyRefundReq struct {
  4373. OrderId string `json:"order_id"`
  4374. RefundReason RefundReasonData `json:"refund_reason,optional"`
  4375. ProductDetail ProductDetailData `json:"product_detail,optional"`
  4376. }
  4377. )
  4378. var req OrderApplyRefundReq
  4379. assert.NoError(t, UnmarshalJsonBytes(input, &req))
  4380. }
  4381. func TestUnmarshalJsonBytesWithAnonymousField(t *testing.T) {
  4382. type (
  4383. Int int
  4384. InnerConf struct {
  4385. Name string
  4386. }
  4387. Conf struct {
  4388. Int
  4389. InnerConf
  4390. }
  4391. )
  4392. var (
  4393. input = []byte(`{"Name": "hello", "Int": 3}`)
  4394. c Conf
  4395. )
  4396. if assert.NoError(t, UnmarshalJsonBytes(input, &c)) {
  4397. assert.Equal(t, "hello", c.Name)
  4398. assert.Equal(t, Int(3), c.Int)
  4399. }
  4400. }
  4401. func TestUnmarshalJsonBytesWithAnonymousFieldOptional(t *testing.T) {
  4402. type (
  4403. Int int
  4404. InnerConf struct {
  4405. Name string
  4406. }
  4407. Conf struct {
  4408. Int `json:",optional"`
  4409. InnerConf
  4410. }
  4411. )
  4412. var (
  4413. input = []byte(`{"Name": "hello", "Int": 3}`)
  4414. c Conf
  4415. )
  4416. if assert.NoError(t, UnmarshalJsonBytes(input, &c)) {
  4417. assert.Equal(t, "hello", c.Name)
  4418. assert.Equal(t, Int(3), c.Int)
  4419. }
  4420. }
  4421. func TestUnmarshalJsonBytesWithAnonymousFieldBadTag(t *testing.T) {
  4422. type (
  4423. Int int
  4424. InnerConf struct {
  4425. Name string
  4426. }
  4427. Conf struct {
  4428. Int `json:",optional=123"`
  4429. InnerConf
  4430. }
  4431. )
  4432. var (
  4433. input = []byte(`{"Name": "hello", "Int": 3}`)
  4434. c Conf
  4435. )
  4436. assert.Error(t, UnmarshalJsonBytes(input, &c))
  4437. }
  4438. func TestUnmarshalJsonBytesWithAnonymousFieldBadValue(t *testing.T) {
  4439. type (
  4440. Int int
  4441. InnerConf struct {
  4442. Name string
  4443. }
  4444. Conf struct {
  4445. Int
  4446. InnerConf
  4447. }
  4448. )
  4449. var (
  4450. input = []byte(`{"Name": "hello", "Int": "3"}`)
  4451. c Conf
  4452. )
  4453. assert.Error(t, UnmarshalJsonBytes(input, &c))
  4454. }
  4455. func TestUnmarshalJsonBytesWithAnonymousFieldBadTagInStruct(t *testing.T) {
  4456. type (
  4457. InnerConf struct {
  4458. Name string `json:",optional=123"`
  4459. }
  4460. Conf struct {
  4461. InnerConf `json:",optional"`
  4462. }
  4463. )
  4464. var (
  4465. input = []byte(`{"Name": "hello"}`)
  4466. c Conf
  4467. )
  4468. assert.Error(t, UnmarshalJsonBytes(input, &c))
  4469. }
  4470. func TestUnmarshalJsonBytesWithAnonymousFieldNotInOptions(t *testing.T) {
  4471. type (
  4472. InnerConf struct {
  4473. Name string `json:",options=[a,b]"`
  4474. }
  4475. Conf struct {
  4476. InnerConf `json:",optional"`
  4477. }
  4478. )
  4479. var (
  4480. input = []byte(`{"Name": "hello"}`)
  4481. c Conf
  4482. )
  4483. assert.Error(t, UnmarshalJsonBytes(input, &c))
  4484. }
  4485. func TestUnmarshalNestedPtr(t *testing.T) {
  4486. type inner struct {
  4487. Int **int `key:"int"`
  4488. }
  4489. m := map[string]any{
  4490. "int": 1,
  4491. }
  4492. var in inner
  4493. if assert.NoError(t, UnmarshalKey(m, &in)) {
  4494. assert.NotNil(t, in.Int)
  4495. assert.Equal(t, 1, **in.Int)
  4496. }
  4497. }
  4498. func TestUnmarshalStructPtrOfPtr(t *testing.T) {
  4499. type inner struct {
  4500. Int int `key:"int"`
  4501. }
  4502. m := map[string]any{
  4503. "int": 1,
  4504. }
  4505. in := new(inner)
  4506. if assert.NoError(t, UnmarshalKey(m, &in)) {
  4507. assert.Equal(t, 1, in.Int)
  4508. }
  4509. }
  4510. func TestUnmarshalOnlyPublicVariables(t *testing.T) {
  4511. type demo struct {
  4512. age int `key:"age"`
  4513. Name string `key:"name"`
  4514. }
  4515. m := map[string]any{
  4516. "age": 3,
  4517. "name": "go-zero",
  4518. }
  4519. var in demo
  4520. if assert.NoError(t, UnmarshalKey(m, &in)) {
  4521. assert.Equal(t, 0, in.age)
  4522. assert.Equal(t, "go-zero", in.Name)
  4523. }
  4524. }
  4525. func TestFillDefaultUnmarshal(t *testing.T) {
  4526. fillDefaultUnmarshal := NewUnmarshaler(jsonTagKey, WithDefault())
  4527. t.Run("nil", func(t *testing.T) {
  4528. type St struct{}
  4529. err := fillDefaultUnmarshal.Unmarshal(map[string]any{}, St{})
  4530. assert.Error(t, err)
  4531. })
  4532. t.Run("not nil", func(t *testing.T) {
  4533. type St struct{}
  4534. err := fillDefaultUnmarshal.Unmarshal(map[string]any{}, &St{})
  4535. assert.NoError(t, err)
  4536. })
  4537. t.Run("default", func(t *testing.T) {
  4538. type St struct {
  4539. A string `json:",default=a"`
  4540. B string
  4541. }
  4542. var st St
  4543. err := fillDefaultUnmarshal.Unmarshal(map[string]any{}, &st)
  4544. assert.NoError(t, err)
  4545. assert.Equal(t, "a", st.A)
  4546. })
  4547. t.Run("env", func(t *testing.T) {
  4548. type St struct {
  4549. A string `json:",default=a"`
  4550. B string
  4551. C string `json:",env=TEST_C"`
  4552. }
  4553. t.Setenv("TEST_C", "c")
  4554. var st St
  4555. err := fillDefaultUnmarshal.Unmarshal(map[string]any{}, &st)
  4556. assert.NoError(t, err)
  4557. assert.Equal(t, "a", st.A)
  4558. assert.Equal(t, "c", st.C)
  4559. })
  4560. t.Run("has value", func(t *testing.T) {
  4561. type St struct {
  4562. A string `json:",default=a"`
  4563. B string
  4564. }
  4565. var st = St{
  4566. A: "b",
  4567. }
  4568. err := fillDefaultUnmarshal.Unmarshal(map[string]any{}, &st)
  4569. assert.Error(t, err)
  4570. })
  4571. t.Run("handling struct", func(t *testing.T) {
  4572. type St struct {
  4573. A string `json:",default=a"`
  4574. B string
  4575. }
  4576. type St2 struct {
  4577. St
  4578. St1 St
  4579. St3 *St
  4580. C string `json:",default=c"`
  4581. D string
  4582. Child *St2
  4583. }
  4584. var st2 St2
  4585. err := fillDefaultUnmarshal.Unmarshal(map[string]any{}, &st2)
  4586. assert.NoError(t, err)
  4587. assert.Equal(t, "a", st2.St.A)
  4588. assert.Equal(t, "a", st2.St1.A)
  4589. assert.Nil(t, st2.St3)
  4590. assert.Equal(t, "c", st2.C)
  4591. assert.Nil(t, st2.Child)
  4592. })
  4593. }
  4594. func Test_UnmarshalMap(t *testing.T) {
  4595. t.Run("type mismatch", func(t *testing.T) {
  4596. type Customer struct {
  4597. Names map[int]string `key:"names"`
  4598. }
  4599. input := map[string]any{
  4600. "names": map[string]any{
  4601. "19": "Tom",
  4602. },
  4603. }
  4604. var customer Customer
  4605. assert.ErrorIs(t, UnmarshalKey(input, &customer), errTypeMismatch)
  4606. })
  4607. t.Run("map type mismatch", func(t *testing.T) {
  4608. type Customer struct {
  4609. Names struct {
  4610. Values map[string]string
  4611. } `key:"names"`
  4612. }
  4613. input := map[string]any{
  4614. "names": map[string]string{
  4615. "19": "Tom",
  4616. },
  4617. }
  4618. var customer Customer
  4619. assert.ErrorIs(t, UnmarshalKey(input, &customer), errTypeMismatch)
  4620. })
  4621. t.Run("map from string", func(t *testing.T) {
  4622. type Customer struct {
  4623. Names map[string]string `key:"names,string"`
  4624. }
  4625. input := map[string]any{
  4626. "names": `{"name": "Tom"}`,
  4627. }
  4628. var customer Customer
  4629. assert.NoError(t, UnmarshalKey(input, &customer))
  4630. assert.Equal(t, "Tom", customer.Names["name"])
  4631. })
  4632. t.Run("map from string with error", func(t *testing.T) {
  4633. type Customer struct {
  4634. Names map[string]any `key:"names,string"`
  4635. }
  4636. input := map[string]any{
  4637. "names": `"name"`,
  4638. }
  4639. var customer Customer
  4640. assert.Error(t, UnmarshalKey(input, &customer))
  4641. })
  4642. }
  4643. func TestUnmarshaler_Unmarshal(t *testing.T) {
  4644. t.Run("not struct", func(t *testing.T) {
  4645. var i int
  4646. unmarshaler := NewUnmarshaler(jsonTagKey)
  4647. err := unmarshaler.UnmarshalValuer(nil, &i)
  4648. assert.Error(t, err)
  4649. })
  4650. t.Run("slice element missing error", func(t *testing.T) {
  4651. type inner struct {
  4652. S []struct {
  4653. Name string `json:"name"`
  4654. Age int `json:"age"`
  4655. } `json:"s"`
  4656. }
  4657. content := []byte(`{"s": [{"name": "foo"}]}`)
  4658. var s inner
  4659. err := UnmarshalJsonBytes(content, &s)
  4660. assert.Error(t, err)
  4661. assert.Contains(t, err.Error(), "s[0].age")
  4662. })
  4663. t.Run("map element missing error", func(t *testing.T) {
  4664. type inner struct {
  4665. S map[string]struct {
  4666. Name string `json:"name"`
  4667. Age int `json:"age"`
  4668. } `json:"s"`
  4669. }
  4670. content := []byte(`{"s": {"a":{"name": "foo"}}}`)
  4671. var s inner
  4672. err := UnmarshalJsonBytes(content, &s)
  4673. assert.Error(t, err)
  4674. assert.Contains(t, err.Error(), "s[a].age")
  4675. })
  4676. }
  4677. // TestUnmarshalerProcessFieldPrimitiveWithJSONNumber test the number type check.
  4678. func TestUnmarshalerProcessFieldPrimitiveWithJSONNumber(t *testing.T) {
  4679. t.Run("wrong type", func(t *testing.T) {
  4680. expectValue := "1"
  4681. realValue := 1
  4682. fieldType := reflect.TypeOf(expectValue)
  4683. value := reflect.ValueOf(&realValue) // pass a pointer to the value
  4684. v := json.Number(expectValue)
  4685. m := NewUnmarshaler("field")
  4686. err := m.processFieldPrimitiveWithJSONNumber(fieldType, value.Elem(), v,
  4687. &fieldOptionsWithContext{}, "field")
  4688. assert.Error(t, err)
  4689. assert.Equal(t, `type mismatch for field "field", expect "string", actual "int"`, err.Error())
  4690. })
  4691. t.Run("right type", func(t *testing.T) {
  4692. expectValue := int64(1)
  4693. realValue := int64(1)
  4694. fieldType := reflect.TypeOf(expectValue)
  4695. value := reflect.ValueOf(&realValue) // pass a pointer to the value
  4696. v := json.Number(strconv.FormatInt(expectValue, 10))
  4697. m := NewUnmarshaler("field")
  4698. err := m.processFieldPrimitiveWithJSONNumber(fieldType, value.Elem(), v,
  4699. &fieldOptionsWithContext{}, "field")
  4700. assert.NoError(t, err)
  4701. })
  4702. }
  4703. func TestGetValueWithChainedKeys(t *testing.T) {
  4704. t.Run("no key", func(t *testing.T) {
  4705. _, ok := getValueWithChainedKeys(nil, []string{})
  4706. assert.False(t, ok)
  4707. })
  4708. t.Run("one key", func(t *testing.T) {
  4709. v, ok := getValueWithChainedKeys(mockValuerWithParent{
  4710. value: "bar",
  4711. ok: true,
  4712. }, []string{"foo"})
  4713. assert.True(t, ok)
  4714. assert.Equal(t, "bar", v)
  4715. })
  4716. t.Run("two keys", func(t *testing.T) {
  4717. v, ok := getValueWithChainedKeys(mockValuerWithParent{
  4718. value: map[string]any{
  4719. "bar": "baz",
  4720. },
  4721. ok: true,
  4722. }, []string{"foo", "bar"})
  4723. assert.True(t, ok)
  4724. assert.Equal(t, "baz", v)
  4725. })
  4726. t.Run("two keys not found", func(t *testing.T) {
  4727. _, ok := getValueWithChainedKeys(mockValuerWithParent{
  4728. value: "bar",
  4729. ok: false,
  4730. }, []string{"foo", "bar"})
  4731. assert.False(t, ok)
  4732. })
  4733. t.Run("two keys type mismatch", func(t *testing.T) {
  4734. _, ok := getValueWithChainedKeys(mockValuerWithParent{
  4735. value: "bar",
  4736. ok: true,
  4737. }, []string{"foo", "bar"})
  4738. assert.False(t, ok)
  4739. })
  4740. }
  4741. func TestUnmarshalFromStringSliceForTypeMismatch(t *testing.T) {
  4742. var v struct {
  4743. Values map[string][]string `key:"values"`
  4744. }
  4745. assert.Error(t, UnmarshalKey(map[string]any{
  4746. "values": map[string]any{
  4747. "foo": "bar",
  4748. },
  4749. }, &v))
  4750. }
  4751. func TestUnmarshalWithOpaqueKeys(t *testing.T) {
  4752. var v struct {
  4753. Opaque string `key:"opaque.key"`
  4754. Value string `key:"value"`
  4755. }
  4756. unmarshaler := NewUnmarshaler("key", WithOpaqueKeys())
  4757. if assert.NoError(t, unmarshaler.Unmarshal(map[string]any{
  4758. "opaque.key": "foo",
  4759. "value": "bar",
  4760. }, &v)) {
  4761. assert.Equal(t, "foo", v.Opaque)
  4762. assert.Equal(t, "bar", v.Value)
  4763. }
  4764. }
  4765. func TestUnmarshalWithIgnoreFields(t *testing.T) {
  4766. type (
  4767. Foo struct {
  4768. Value string
  4769. IgnoreString string `json:"-"`
  4770. IgnoreInt int `json:"-"`
  4771. }
  4772. Bar struct {
  4773. Foo1 Foo
  4774. Foo2 *Foo
  4775. Foo3 []Foo
  4776. Foo4 []*Foo
  4777. Foo5 map[string]Foo
  4778. Foo6 map[string]Foo
  4779. }
  4780. Bar1 struct {
  4781. Foo `json:"-"`
  4782. }
  4783. Bar2 struct {
  4784. *Foo `json:"-"`
  4785. }
  4786. )
  4787. var bar Bar
  4788. unmarshaler := NewUnmarshaler(jsonTagKey)
  4789. if assert.NoError(t, unmarshaler.Unmarshal(map[string]any{
  4790. "Foo1": map[string]any{
  4791. "Value": "foo",
  4792. "IgnoreString": "any",
  4793. "IgnoreInt": 2,
  4794. },
  4795. "Foo2": map[string]any{
  4796. "Value": "foo",
  4797. "IgnoreString": "any",
  4798. "IgnoreInt": 2,
  4799. },
  4800. "Foo3": []map[string]any{
  4801. {
  4802. "Value": "foo",
  4803. "IgnoreString": "any",
  4804. "IgnoreInt": 2,
  4805. },
  4806. },
  4807. "Foo4": []map[string]any{
  4808. {
  4809. "Value": "foo",
  4810. "IgnoreString": "any",
  4811. "IgnoreInt": 2,
  4812. },
  4813. },
  4814. "Foo5": map[string]any{
  4815. "key": map[string]any{
  4816. "Value": "foo",
  4817. "IgnoreString": "any",
  4818. "IgnoreInt": 2,
  4819. },
  4820. },
  4821. "Foo6": map[string]any{
  4822. "key": map[string]any{
  4823. "Value": "foo",
  4824. "IgnoreString": "any",
  4825. "IgnoreInt": 2,
  4826. },
  4827. },
  4828. }, &bar)) {
  4829. assert.Equal(t, "foo", bar.Foo1.Value)
  4830. assert.Empty(t, bar.Foo1.IgnoreString)
  4831. assert.Equal(t, 0, bar.Foo1.IgnoreInt)
  4832. assert.Equal(t, "foo", bar.Foo2.Value)
  4833. assert.Empty(t, bar.Foo2.IgnoreString)
  4834. assert.Equal(t, 0, bar.Foo2.IgnoreInt)
  4835. assert.Equal(t, "foo", bar.Foo3[0].Value)
  4836. assert.Empty(t, bar.Foo3[0].IgnoreString)
  4837. assert.Equal(t, 0, bar.Foo3[0].IgnoreInt)
  4838. assert.Equal(t, "foo", bar.Foo4[0].Value)
  4839. assert.Empty(t, bar.Foo4[0].IgnoreString)
  4840. assert.Equal(t, 0, bar.Foo4[0].IgnoreInt)
  4841. assert.Equal(t, "foo", bar.Foo5["key"].Value)
  4842. assert.Empty(t, bar.Foo5["key"].IgnoreString)
  4843. assert.Equal(t, 0, bar.Foo5["key"].IgnoreInt)
  4844. assert.Equal(t, "foo", bar.Foo6["key"].Value)
  4845. assert.Empty(t, bar.Foo6["key"].IgnoreString)
  4846. assert.Equal(t, 0, bar.Foo6["key"].IgnoreInt)
  4847. }
  4848. var bar1 Bar1
  4849. if assert.NoError(t, unmarshaler.Unmarshal(map[string]any{
  4850. "Value": "foo",
  4851. "IgnoreString": "any",
  4852. "IgnoreInt": 2,
  4853. }, &bar1)) {
  4854. assert.Empty(t, bar1.Value)
  4855. assert.Empty(t, bar1.IgnoreString)
  4856. assert.Equal(t, 0, bar1.IgnoreInt)
  4857. }
  4858. var bar2 Bar2
  4859. if assert.NoError(t, unmarshaler.Unmarshal(map[string]any{
  4860. "Value": "foo",
  4861. "IgnoreString": "any",
  4862. "IgnoreInt": 2,
  4863. }, &bar2)) {
  4864. assert.Nil(t, bar2.Foo)
  4865. }
  4866. }
  4867. func BenchmarkDefaultValue(b *testing.B) {
  4868. for i := 0; i < b.N; i++ {
  4869. var a struct {
  4870. Ints []int `json:"ints,default=[1,2,3]"`
  4871. Strs []string `json:"strs,default=[foo,bar,baz]"`
  4872. }
  4873. _ = UnmarshalJsonMap(nil, &a)
  4874. if len(a.Strs) != 3 || len(a.Ints) != 3 {
  4875. b.Fatal("failed")
  4876. }
  4877. }
  4878. }
  4879. func BenchmarkUnmarshalString(b *testing.B) {
  4880. type inner struct {
  4881. Value string `key:"value"`
  4882. }
  4883. m := map[string]any{
  4884. "value": "first",
  4885. }
  4886. for i := 0; i < b.N; i++ {
  4887. var in inner
  4888. if err := UnmarshalKey(m, &in); err != nil {
  4889. b.Fatal(err)
  4890. }
  4891. }
  4892. }
  4893. func BenchmarkUnmarshalStruct(b *testing.B) {
  4894. b.ReportAllocs()
  4895. m := map[string]any{
  4896. "Ids": []map[string]any{
  4897. {
  4898. "First": 1,
  4899. "Second": 2,
  4900. },
  4901. },
  4902. }
  4903. for i := 0; i < b.N; i++ {
  4904. var v struct {
  4905. Ids []struct {
  4906. First int
  4907. Second int
  4908. }
  4909. }
  4910. if err := UnmarshalKey(m, &v); err != nil {
  4911. b.Fatal(err)
  4912. }
  4913. }
  4914. }
  4915. func BenchmarkMapToStruct(b *testing.B) {
  4916. data := map[string]any{
  4917. "valid": "1",
  4918. "age": "5",
  4919. "name": "liao",
  4920. }
  4921. type anonymous struct {
  4922. Valid bool
  4923. Age int
  4924. Name string
  4925. }
  4926. for i := 0; i < b.N; i++ {
  4927. var an anonymous
  4928. if valid, ok := data["valid"]; ok {
  4929. an.Valid = valid == "1"
  4930. }
  4931. if age, ok := data["age"]; ok {
  4932. ages, _ := age.(string)
  4933. an.Age, _ = strconv.Atoi(ages)
  4934. }
  4935. if name, ok := data["name"]; ok {
  4936. names, _ := name.(string)
  4937. an.Name = names
  4938. }
  4939. }
  4940. }
  4941. func BenchmarkUnmarshal(b *testing.B) {
  4942. data := map[string]any{
  4943. "valid": "1",
  4944. "age": "5",
  4945. "name": "liao",
  4946. }
  4947. type anonymous struct {
  4948. Valid bool `key:"valid,string"`
  4949. Age int `key:"age,string"`
  4950. Name string `key:"name"`
  4951. }
  4952. for i := 0; i < b.N; i++ {
  4953. var an anonymous
  4954. UnmarshalKey(data, &an)
  4955. }
  4956. }
  4957. type mockValuerWithParent struct {
  4958. parent valuerWithParent
  4959. value any
  4960. ok bool
  4961. }
  4962. func (m mockValuerWithParent) Value(key string) (any, bool) {
  4963. return m.value, m.ok
  4964. }
  4965. func (m mockValuerWithParent) Parent() valuerWithParent {
  4966. return m.parent
  4967. }