config_test.go 12 KB

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