unmarshaler_test.go 92 KB

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