unmarshaler_test.go 85 KB

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