tauri_test.go 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697
  1. package tauri
  2. import (
  3. "image"
  4. "testing"
  5. )
  6. type foo struct {
  7. Result interface{}
  8. }
  9. func (f *foo) Foo1(a int, b float32) {
  10. f.Result = float64(a) + float64(b)
  11. }
  12. func (f *foo) Foo2(a []int, b [3]float32, c map[int]int) {
  13. f.Result = map[string]interface{}{"a": a, "b": b, "c": c}
  14. }
  15. func (f *foo) Foo3(a []image.Point, b struct{ Z int }) {
  16. f.Result = map[string]interface{}{"a": a, "b": b}
  17. }
  18. func TestBadBinding(t *testing.T) {
  19. x := 123
  20. for _, v := range []interface{}{
  21. nil,
  22. true,
  23. 123,
  24. 123.4,
  25. "hello",
  26. 'a',
  27. make(chan struct{}, 0),
  28. func() {},
  29. map[string]string{},
  30. []int{},
  31. [3]int{0, 0, 0},
  32. &x,
  33. } {
  34. if _, err := newBinding("test", v); err == nil {
  35. t.Errorf("should return an error: %#v", v)
  36. }
  37. }
  38. }
  39. func TestBindingCall(t *testing.T) {
  40. foo := &foo{}
  41. b, err := newBinding("test", foo)
  42. if err != nil {
  43. t.Fatal(err)
  44. }
  45. t.Run("Primitives", func(t *testing.T) {
  46. if !b.Call(`{"scope":"test","method":"Foo1","params":[3,4.5]}`) {
  47. t.Fatal()
  48. }
  49. if foo.Result.(float64) != 7.5 {
  50. t.Fatal(foo)
  51. }
  52. })
  53. t.Run("Collections", func(t *testing.T) {
  54. // Call with slices, arrays and maps
  55. if !b.Call(`{"scope":"test","method":"Foo2","params":[[1,2,3],[4.5,4.6,4.7],{"1":2,"3":4}]}`) {
  56. t.Fatal()
  57. }
  58. m := foo.Result.(map[string]interface{})
  59. if ints := m["a"].([]int); ints[0] != 1 || ints[1] != 2 || ints[2] != 3 {
  60. t.Fatal(foo)
  61. }
  62. if floats := m["b"].([3]float32); floats[0] != 4.5 || floats[1] != 4.6 || floats[2] != 4.7 {
  63. t.Fatal(foo)
  64. }
  65. if dict := m["c"].(map[int]int); len(dict) != 2 || dict[1] != 2 || dict[3] != 4 {
  66. t.Fatal(foo)
  67. }
  68. })
  69. t.Run("Structs", func(t *testing.T) {
  70. if !b.Call(`{"scope":"test","method":"Foo3","params":[[{"X":1,"Y":2},{"X":3,"Y":4}],{"Z":42}]}`) {
  71. t.Fatal()
  72. }
  73. m := foo.Result.(map[string]interface{})
  74. if p := m["a"].([]image.Point); p[0].X != 1 || p[0].Y != 2 || p[1].X != 3 || p[1].Y != 4 {
  75. t.Fatal(foo)
  76. }
  77. if z := m["b"].(struct{ Z int }); z.Z != 42 {
  78. t.Fatal(foo)
  79. }
  80. })
  81. t.Run("Errors", func(t *testing.T) {
  82. if b.Call(`{"scope":"foo"}`) || b.Call(`{"scope":"test", "method":"Bar"}`) {
  83. t.Fatal()
  84. }
  85. if b.Call(`{"scope":"test","method":"Foo1","params":["3",4.5]}`) {
  86. t.Fatal()
  87. }
  88. })
  89. }