unmarshaler_test.go 78 KB

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