config_test.go 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749
  1. package conf
  2. import (
  3. "os"
  4. "testing"
  5. "github.com/stretchr/testify/assert"
  6. "github.com/zeromicro/go-zero/core/fs"
  7. "github.com/zeromicro/go-zero/core/hash"
  8. )
  9. var dupErr dupKeyError
  10. func TestLoadConfig_notExists(t *testing.T) {
  11. assert.NotNil(t, Load("not_a_file", nil))
  12. }
  13. func TestLoadConfig_notRecogFile(t *testing.T) {
  14. filename, err := fs.TempFilenameWithText("hello")
  15. assert.Nil(t, err)
  16. defer os.Remove(filename)
  17. assert.NotNil(t, LoadConfig(filename, nil))
  18. }
  19. func TestConfigJson(t *testing.T) {
  20. tests := []string{
  21. ".json",
  22. ".yaml",
  23. ".yml",
  24. }
  25. text := `{
  26. "a": "foo",
  27. "b": 1,
  28. "c": "${FOO}",
  29. "d": "abcd!@#$112"
  30. }`
  31. for _, test := range tests {
  32. test := test
  33. t.Run(test, func(t *testing.T) {
  34. os.Setenv("FOO", "2")
  35. defer os.Unsetenv("FOO")
  36. tmpfile, err := createTempFile(test, text)
  37. assert.Nil(t, err)
  38. defer os.Remove(tmpfile)
  39. var val struct {
  40. A string `json:"a"`
  41. B int `json:"b"`
  42. C string `json:"c"`
  43. D string `json:"d"`
  44. }
  45. MustLoad(tmpfile, &val)
  46. assert.Equal(t, "foo", val.A)
  47. assert.Equal(t, 1, val.B)
  48. assert.Equal(t, "${FOO}", val.C)
  49. assert.Equal(t, "abcd!@#$112", val.D)
  50. })
  51. }
  52. }
  53. func TestLoadFromJsonBytesArray(t *testing.T) {
  54. input := []byte(`{"users": [{"name": "foo"}, {"Name": "bar"}]}`)
  55. var val struct {
  56. Users []struct {
  57. Name string
  58. }
  59. }
  60. assert.NoError(t, LoadConfigFromJsonBytes(input, &val))
  61. var expect []string
  62. for _, user := range val.Users {
  63. expect = append(expect, user.Name)
  64. }
  65. assert.EqualValues(t, []string{"foo", "bar"}, expect)
  66. }
  67. func TestConfigToml(t *testing.T) {
  68. text := `a = "foo"
  69. b = 1
  70. c = "${FOO}"
  71. d = "abcd!@#$112"
  72. `
  73. os.Setenv("FOO", "2")
  74. defer os.Unsetenv("FOO")
  75. tmpfile, err := createTempFile(".toml", text)
  76. assert.Nil(t, err)
  77. defer os.Remove(tmpfile)
  78. var val struct {
  79. A string `json:"a"`
  80. B int `json:"b"`
  81. C string `json:"c"`
  82. D string `json:"d"`
  83. }
  84. MustLoad(tmpfile, &val)
  85. assert.Equal(t, "foo", val.A)
  86. assert.Equal(t, 1, val.B)
  87. assert.Equal(t, "${FOO}", val.C)
  88. assert.Equal(t, "abcd!@#$112", val.D)
  89. }
  90. func TestConfigOptional(t *testing.T) {
  91. text := `a = "foo"
  92. b = 1
  93. c = "FOO"
  94. d = "abcd"
  95. `
  96. tmpfile, err := createTempFile(".toml", text)
  97. assert.Nil(t, err)
  98. defer os.Remove(tmpfile)
  99. var val struct {
  100. A string `json:"a"`
  101. B int `json:"b,optional"`
  102. C string `json:"c,optional=B"`
  103. D string `json:"d,optional=b"`
  104. }
  105. if assert.NoError(t, Load(tmpfile, &val)) {
  106. assert.Equal(t, "foo", val.A)
  107. assert.Equal(t, 1, val.B)
  108. assert.Equal(t, "FOO", val.C)
  109. assert.Equal(t, "abcd", val.D)
  110. }
  111. }
  112. func TestConfigJsonCanonical(t *testing.T) {
  113. text := []byte(`{"a": "foo", "B": "bar"}`)
  114. var val1 struct {
  115. A string `json:"a"`
  116. B string `json:"b"`
  117. }
  118. var val2 struct {
  119. A string
  120. B string
  121. }
  122. assert.NoError(t, LoadFromJsonBytes(text, &val1))
  123. assert.Equal(t, "foo", val1.A)
  124. assert.Equal(t, "bar", val1.B)
  125. assert.NoError(t, LoadFromJsonBytes(text, &val2))
  126. assert.Equal(t, "foo", val2.A)
  127. assert.Equal(t, "bar", val2.B)
  128. }
  129. func TestConfigTomlCanonical(t *testing.T) {
  130. text := []byte(`a = "foo"
  131. B = "bar"`)
  132. var val1 struct {
  133. A string `json:"a"`
  134. B string `json:"b"`
  135. }
  136. var val2 struct {
  137. A string
  138. B string
  139. }
  140. assert.NoError(t, LoadFromTomlBytes(text, &val1))
  141. assert.Equal(t, "foo", val1.A)
  142. assert.Equal(t, "bar", val1.B)
  143. assert.NoError(t, LoadFromTomlBytes(text, &val2))
  144. assert.Equal(t, "foo", val2.A)
  145. assert.Equal(t, "bar", val2.B)
  146. }
  147. func TestConfigYamlCanonical(t *testing.T) {
  148. text := []byte(`a: foo
  149. B: bar`)
  150. var val1 struct {
  151. A string `json:"a"`
  152. B string `json:"b"`
  153. }
  154. var val2 struct {
  155. A string
  156. B string
  157. }
  158. assert.NoError(t, LoadConfigFromYamlBytes(text, &val1))
  159. assert.Equal(t, "foo", val1.A)
  160. assert.Equal(t, "bar", val1.B)
  161. assert.NoError(t, LoadFromYamlBytes(text, &val2))
  162. assert.Equal(t, "foo", val2.A)
  163. assert.Equal(t, "bar", val2.B)
  164. }
  165. func TestConfigTomlEnv(t *testing.T) {
  166. text := `a = "foo"
  167. b = 1
  168. c = "${FOO}"
  169. d = "abcd!@#112"
  170. `
  171. os.Setenv("FOO", "2")
  172. defer os.Unsetenv("FOO")
  173. tmpfile, err := createTempFile(".toml", text)
  174. assert.Nil(t, err)
  175. defer os.Remove(tmpfile)
  176. var val struct {
  177. A string `json:"a"`
  178. B int `json:"b"`
  179. C string `json:"c"`
  180. D string `json:"d"`
  181. }
  182. MustLoad(tmpfile, &val, UseEnv())
  183. assert.Equal(t, "foo", val.A)
  184. assert.Equal(t, 1, val.B)
  185. assert.Equal(t, "2", val.C)
  186. assert.Equal(t, "abcd!@#112", val.D)
  187. }
  188. func TestConfigJsonEnv(t *testing.T) {
  189. tests := []string{
  190. ".json",
  191. ".yaml",
  192. ".yml",
  193. }
  194. text := `{
  195. "a": "foo",
  196. "b": 1,
  197. "c": "${FOO}",
  198. "d": "abcd!@#$a12 3"
  199. }`
  200. for _, test := range tests {
  201. test := test
  202. t.Run(test, func(t *testing.T) {
  203. os.Setenv("FOO", "2")
  204. defer os.Unsetenv("FOO")
  205. tmpfile, err := createTempFile(test, text)
  206. assert.Nil(t, err)
  207. defer os.Remove(tmpfile)
  208. var val struct {
  209. A string `json:"a"`
  210. B int `json:"b"`
  211. C string `json:"c"`
  212. D string `json:"d"`
  213. }
  214. MustLoad(tmpfile, &val, UseEnv())
  215. assert.Equal(t, "foo", val.A)
  216. assert.Equal(t, 1, val.B)
  217. assert.Equal(t, "2", val.C)
  218. assert.Equal(t, "abcd!@# 3", val.D)
  219. })
  220. }
  221. }
  222. func TestToCamelCase(t *testing.T) {
  223. tests := []struct {
  224. input string
  225. expect string
  226. }{
  227. {
  228. input: "",
  229. expect: "",
  230. },
  231. {
  232. input: "A",
  233. expect: "a",
  234. },
  235. {
  236. input: "a",
  237. expect: "a",
  238. },
  239. {
  240. input: "hello_world",
  241. expect: "hello_world",
  242. },
  243. {
  244. input: "Hello_world",
  245. expect: "hello_world",
  246. },
  247. {
  248. input: "hello_World",
  249. expect: "hello_world",
  250. },
  251. {
  252. input: "helloWorld",
  253. expect: "helloworld",
  254. },
  255. {
  256. input: "HelloWorld",
  257. expect: "helloworld",
  258. },
  259. {
  260. input: "hello World",
  261. expect: "hello world",
  262. },
  263. {
  264. input: "Hello World",
  265. expect: "hello world",
  266. },
  267. {
  268. input: "Hello World",
  269. expect: "hello world",
  270. },
  271. {
  272. input: "Hello World foo_bar",
  273. expect: "hello world foo_bar",
  274. },
  275. {
  276. input: "Hello World foo_Bar",
  277. expect: "hello world foo_bar",
  278. },
  279. {
  280. input: "Hello World Foo_bar",
  281. expect: "hello world foo_bar",
  282. },
  283. {
  284. input: "Hello World Foo_Bar",
  285. expect: "hello world foo_bar",
  286. },
  287. {
  288. input: "Hello.World Foo_Bar",
  289. expect: "hello.world foo_bar",
  290. },
  291. {
  292. input: "你好 World Foo_Bar",
  293. expect: "你好 world foo_bar",
  294. },
  295. }
  296. for _, test := range tests {
  297. test := test
  298. t.Run(test.input, func(t *testing.T) {
  299. assert.Equal(t, test.expect, toLowerCase(test.input))
  300. })
  301. }
  302. }
  303. func TestLoadFromJsonBytesError(t *testing.T) {
  304. var val struct{}
  305. assert.Error(t, LoadFromJsonBytes([]byte(`hello`), &val))
  306. }
  307. func TestLoadFromTomlBytesError(t *testing.T) {
  308. var val struct{}
  309. assert.Error(t, LoadFromTomlBytes([]byte(`hello`), &val))
  310. }
  311. func TestLoadFromYamlBytesError(t *testing.T) {
  312. var val struct{}
  313. assert.Error(t, LoadFromYamlBytes([]byte(`':hello`), &val))
  314. }
  315. func TestLoadFromYamlBytes(t *testing.T) {
  316. input := []byte(`layer1:
  317. layer2:
  318. layer3: foo`)
  319. var val struct {
  320. Layer1 struct {
  321. Layer2 struct {
  322. Layer3 string
  323. }
  324. }
  325. }
  326. assert.NoError(t, LoadFromYamlBytes(input, &val))
  327. assert.Equal(t, "foo", val.Layer1.Layer2.Layer3)
  328. }
  329. func TestLoadFromYamlBytesTerm(t *testing.T) {
  330. input := []byte(`layer1:
  331. layer2:
  332. tls_conf: foo`)
  333. var val struct {
  334. Layer1 struct {
  335. Layer2 struct {
  336. Layer3 string `json:"tls_conf"`
  337. }
  338. }
  339. }
  340. assert.NoError(t, LoadFromYamlBytes(input, &val))
  341. assert.Equal(t, "foo", val.Layer1.Layer2.Layer3)
  342. }
  343. func TestLoadFromYamlBytesLayers(t *testing.T) {
  344. input := []byte(`layer1:
  345. layer2:
  346. layer3: foo`)
  347. var val struct {
  348. Value string `json:"Layer1.Layer2.Layer3"`
  349. }
  350. assert.NoError(t, LoadFromYamlBytes(input, &val))
  351. assert.Equal(t, "foo", val.Value)
  352. }
  353. func TestLoadFromYamlItemOverlay(t *testing.T) {
  354. type (
  355. Redis struct {
  356. Host string
  357. Port int
  358. }
  359. RedisKey struct {
  360. Redis
  361. Key string
  362. }
  363. Server struct {
  364. Redis RedisKey
  365. }
  366. TestConfig struct {
  367. Server
  368. Redis Redis
  369. }
  370. )
  371. input := []byte(`Redis:
  372. Host: localhost
  373. Port: 6379
  374. Key: test
  375. `)
  376. var c TestConfig
  377. assert.ErrorAs(t, LoadFromYamlBytes(input, &c), &dupErr)
  378. }
  379. func TestLoadFromYamlItemOverlayReverse(t *testing.T) {
  380. type (
  381. Redis struct {
  382. Host string
  383. Port int
  384. }
  385. RedisKey struct {
  386. Redis
  387. Key string
  388. }
  389. Server struct {
  390. Redis Redis
  391. }
  392. TestConfig struct {
  393. Redis RedisKey
  394. Server
  395. }
  396. )
  397. input := []byte(`Redis:
  398. Host: localhost
  399. Port: 6379
  400. Key: test
  401. `)
  402. var c TestConfig
  403. assert.ErrorAs(t, LoadFromYamlBytes(input, &c), &dupErr)
  404. }
  405. func TestLoadFromYamlItemOverlayWithMap(t *testing.T) {
  406. type (
  407. Redis struct {
  408. Host string
  409. Port int
  410. }
  411. RedisKey struct {
  412. Redis
  413. Key string
  414. }
  415. Server struct {
  416. Redis RedisKey
  417. }
  418. TestConfig struct {
  419. Server
  420. Redis map[string]interface{}
  421. }
  422. )
  423. input := []byte(`Redis:
  424. Host: localhost
  425. Port: 6379
  426. Key: test
  427. `)
  428. var c TestConfig
  429. if assert.NoError(t, LoadFromYamlBytes(input, &c)) {
  430. assert.Equal(t, "localhost", c.Server.Redis.Host)
  431. assert.Equal(t, 6379, c.Server.Redis.Port)
  432. assert.Equal(t, "test", c.Server.Redis.Key)
  433. }
  434. }
  435. func TestUnmarshalJsonBytesMap(t *testing.T) {
  436. input := []byte(`{"foo":{"/mtproto.RPCTos": "bff.bff","bar":"baz"}}`)
  437. var val struct {
  438. Foo map[string]string
  439. }
  440. assert.NoError(t, LoadFromJsonBytes(input, &val))
  441. assert.Equal(t, "bff.bff", val.Foo["/mtproto.RPCTos"])
  442. assert.Equal(t, "baz", val.Foo["bar"])
  443. }
  444. func TestUnmarshalJsonBytesMapWithSliceElements(t *testing.T) {
  445. input := []byte(`{"foo":{"/mtproto.RPCTos": ["bff.bff", "any"],"bar":["baz", "qux"]}}`)
  446. var val struct {
  447. Foo map[string][]string
  448. }
  449. assert.NoError(t, LoadFromJsonBytes(input, &val))
  450. assert.EqualValues(t, []string{"bff.bff", "any"}, val.Foo["/mtproto.RPCTos"])
  451. assert.EqualValues(t, []string{"baz", "qux"}, val.Foo["bar"])
  452. }
  453. func TestUnmarshalJsonBytesMapWithSliceOfStructs(t *testing.T) {
  454. input := []byte(`{"foo":{
  455. "/mtproto.RPCTos": [{"bar": "any"}],
  456. "bar":[{"bar": "qux"}, {"bar": "ever"}]}}`)
  457. var val struct {
  458. Foo map[string][]struct {
  459. Bar string
  460. }
  461. }
  462. assert.NoError(t, LoadFromJsonBytes(input, &val))
  463. assert.Equal(t, 1, len(val.Foo["/mtproto.RPCTos"]))
  464. assert.Equal(t, "any", val.Foo["/mtproto.RPCTos"][0].Bar)
  465. assert.Equal(t, 2, len(val.Foo["bar"]))
  466. assert.Equal(t, "qux", val.Foo["bar"][0].Bar)
  467. assert.Equal(t, "ever", val.Foo["bar"][1].Bar)
  468. }
  469. func TestUnmarshalJsonBytesWithAnonymousField(t *testing.T) {
  470. type (
  471. Int int
  472. InnerConf struct {
  473. Name string
  474. }
  475. Conf struct {
  476. Int
  477. InnerConf
  478. }
  479. )
  480. var (
  481. input = []byte(`{"Name": "hello", "int": 3}`)
  482. c Conf
  483. )
  484. assert.NoError(t, LoadFromJsonBytes(input, &c))
  485. assert.Equal(t, "hello", c.Name)
  486. assert.Equal(t, Int(3), c.Int)
  487. }
  488. func TestUnmarshalJsonBytesWithMapValueOfStruct(t *testing.T) {
  489. type (
  490. Value struct {
  491. Name string
  492. }
  493. Config struct {
  494. Items map[string]Value
  495. }
  496. )
  497. var inputs = [][]byte{
  498. []byte(`{"Items": {"Key":{"Name": "foo"}}}`),
  499. []byte(`{"Items": {"Key":{"Name": "foo"}}}`),
  500. []byte(`{"items": {"key":{"name": "foo"}}}`),
  501. []byte(`{"items": {"key":{"name": "foo"}}}`),
  502. }
  503. for _, input := range inputs {
  504. var c Config
  505. if assert.NoError(t, LoadFromJsonBytes(input, &c)) {
  506. assert.Equal(t, 1, len(c.Items))
  507. for _, v := range c.Items {
  508. assert.Equal(t, "foo", v.Name)
  509. }
  510. }
  511. }
  512. }
  513. func TestUnmarshalJsonBytesWithMapTypeValueOfStruct(t *testing.T) {
  514. type (
  515. Value struct {
  516. Name string
  517. }
  518. Map map[string]Value
  519. Config struct {
  520. Map
  521. }
  522. )
  523. var inputs = [][]byte{
  524. []byte(`{"Map": {"Key":{"Name": "foo"}}}`),
  525. []byte(`{"Map": {"Key":{"Name": "foo"}}}`),
  526. []byte(`{"map": {"key":{"name": "foo"}}}`),
  527. []byte(`{"map": {"key":{"name": "foo"}}}`),
  528. }
  529. for _, input := range inputs {
  530. var c Config
  531. if assert.NoError(t, LoadFromJsonBytes(input, &c)) {
  532. assert.Equal(t, 1, len(c.Map))
  533. for _, v := range c.Map {
  534. assert.Equal(t, "foo", v.Name)
  535. }
  536. }
  537. }
  538. }
  539. func Test_checkInheritOverwrite(t *testing.T) {
  540. t.Run("normal", func(t *testing.T) {
  541. type Base struct {
  542. Name string
  543. }
  544. type St1 struct {
  545. Base
  546. Name2 string
  547. }
  548. type St2 struct {
  549. Base
  550. Name2 string
  551. }
  552. type St3 struct {
  553. *Base
  554. Name2 string
  555. }
  556. type St4 struct {
  557. *Base
  558. Name2 *string
  559. }
  560. validate := func(val any) {
  561. input := []byte(`{"Name": "hello", "Name2": "world"}`)
  562. assert.NoError(t, LoadFromJsonBytes(input, val))
  563. }
  564. validate(&St1{})
  565. validate(&St2{})
  566. validate(&St3{})
  567. validate(&St4{})
  568. })
  569. t.Run("Inherit Override", func(t *testing.T) {
  570. type Base struct {
  571. Name string
  572. }
  573. type St1 struct {
  574. Base
  575. Name string
  576. }
  577. type St2 struct {
  578. Base
  579. Name int
  580. }
  581. type St3 struct {
  582. *Base
  583. Name int
  584. }
  585. type St4 struct {
  586. *Base
  587. Name *string
  588. }
  589. validate := func(val any) {
  590. input := []byte(`{"Name": "hello"}`)
  591. err := LoadFromJsonBytes(input, val)
  592. assert.ErrorAs(t, err, &dupErr)
  593. assert.Equal(t, newDupKeyError("name").Error(), err.Error())
  594. }
  595. validate(&St1{})
  596. validate(&St2{})
  597. validate(&St3{})
  598. validate(&St4{})
  599. })
  600. t.Run("Inherit more", func(t *testing.T) {
  601. type Base1 struct {
  602. Name string
  603. }
  604. type St0 struct {
  605. Base1
  606. Name string
  607. }
  608. type St1 struct {
  609. St0
  610. Name string
  611. }
  612. type St2 struct {
  613. St0
  614. Name int
  615. }
  616. type St3 struct {
  617. *St0
  618. Name int
  619. }
  620. type St4 struct {
  621. *St0
  622. Name *int
  623. }
  624. validate := func(val any) {
  625. input := []byte(`{"Name": "hello"}`)
  626. err := LoadFromJsonBytes(input, val)
  627. assert.ErrorAs(t, err, &dupErr)
  628. assert.Equal(t, newDupKeyError("name").Error(), err.Error())
  629. }
  630. validate(&St0{})
  631. validate(&St1{})
  632. validate(&St2{})
  633. validate(&St3{})
  634. validate(&St4{})
  635. })
  636. }
  637. func createTempFile(ext, text string) (string, error) {
  638. tmpfile, err := os.CreateTemp(os.TempDir(), hash.Md5Hex([]byte(text))+"*"+ext)
  639. if err != nil {
  640. return "", err
  641. }
  642. if err := os.WriteFile(tmpfile.Name(), []byte(text), os.ModeTemporary); err != nil {
  643. return "", err
  644. }
  645. filename := tmpfile.Name()
  646. if err = tmpfile.Close(); err != nil {
  647. return "", err
  648. }
  649. return filename, nil
  650. }