unmarshaler_test.go 123 KB

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