在Go中轻松安全地从一种数据类型转换为另一种数据类型
Nevar pievienot vairāk kā 25 tēmas Tēmai ir jāsākas ar burtu vai ciparu, tā var saturēt domu zīmes ('-') un var būt līdz 35 simboliem gara.
 
 
 

70 rindas
2.1 KiB

  1. // Copyright © 2014 Steve Francia <spf@spf13.com>.
  2. //
  3. // Use of this source code is governed by an MIT-style
  4. // license that can be found in the LICENSE file.
  5. package cast
  6. import (
  7. "testing"
  8. "github.com/stretchr/testify/assert"
  9. "html/template"
  10. )
  11. func TestToInt(t *testing.T) {
  12. var eight interface{} = 8
  13. assert.Equal(t, ToInt(8), 8)
  14. assert.Equal(t, ToInt(8.31), 8)
  15. assert.Equal(t, ToInt("8"), 8)
  16. assert.Equal(t, ToInt(true), 1)
  17. assert.Equal(t, ToInt(false), 0)
  18. assert.Equal(t, ToInt(eight), 8)
  19. }
  20. func TestToFloat64(t *testing.T) {
  21. var eight interface{} = 8
  22. assert.Equal(t, ToFloat64(8), 8.00)
  23. assert.Equal(t, ToFloat64(8.31), 8.31)
  24. assert.Equal(t, ToFloat64("8.31"), 8.31)
  25. assert.Equal(t, ToFloat64(eight), 8.0)
  26. }
  27. func TestToString(t *testing.T) {
  28. var foo interface{} = "one more time"
  29. assert.Equal(t, ToString(8), "8")
  30. assert.Equal(t, ToString(8.12), "8.12")
  31. assert.Equal(t, ToString([]byte("one time")), "one time")
  32. assert.Equal(t, ToString(template.HTML("one time")), "one time")
  33. assert.Equal(t, ToString(foo), "one more time")
  34. assert.Equal(t, ToString(nil), "")
  35. }
  36. func TestMaps(t *testing.T) {
  37. var taxonomies = map[interface{}]interface{}{"tag": "tags", "group": "groups"}
  38. var stringMapBool = map[interface{}]interface{}{"v1": true, "v2": false}
  39. assert.Equal(t, ToStringMap(taxonomies), map[string]interface{}{"tag": "tags", "group": "groups"})
  40. assert.Equal(t, ToStringMapBool(stringMapBool), map[string]bool{"v1": true, "v2": false})
  41. }
  42. func TestToBool(t *testing.T) {
  43. assert.Equal(t, ToBool(0), false)
  44. assert.Equal(t, ToBool(nil), false)
  45. assert.Equal(t, ToBool("false"), false)
  46. assert.Equal(t, ToBool("FALSE"), false)
  47. assert.Equal(t, ToBool("False"), false)
  48. assert.Equal(t, ToBool("f"), false)
  49. assert.Equal(t, ToBool("F"), false)
  50. assert.Equal(t, ToBool(false), false)
  51. assert.Equal(t, ToBool("foo"), false)
  52. assert.Equal(t, ToBool("true"), true)
  53. assert.Equal(t, ToBool("TRUE"), true)
  54. assert.Equal(t, ToBool("True"), true)
  55. assert.Equal(t, ToBool("t"), true)
  56. assert.Equal(t, ToBool("T"), true)
  57. assert.Equal(t, ToBool(1), true)
  58. assert.Equal(t, ToBool(true), true)
  59. assert.Equal(t, ToBool(-1), true)
  60. }