unmarshaler_test.go 95 KB

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