unmarshaler_test.go 114 KB

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