unmarshaler_test.go 93 KB

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