test_source.go 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788
  1. // Copyright 2021-2023 EMQ Technologies Co., Ltd.
  2. //
  3. // Licensed under the Apache License, Version 2.0 (the "License");
  4. // you may not use this file except in compliance with the License.
  5. // You may obtain a copy of the License at
  6. //
  7. // http://www.apache.org/licenses/LICENSE-2.0
  8. //
  9. // Unless required by applicable law or agreed to in writing, software
  10. // distributed under the License is distributed on an "AS IS" BASIS,
  11. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. // See the License for the specific language governing permissions and
  13. // limitations under the License.
  14. package mock
  15. import (
  16. "fmt"
  17. "sync/atomic"
  18. "testing"
  19. "time"
  20. "github.com/stretchr/testify/assert"
  21. "github.com/lf-edge/ekuiper/internal/converter"
  22. mockContext "github.com/lf-edge/ekuiper/internal/io/mock/context"
  23. "github.com/lf-edge/ekuiper/internal/topo/context"
  24. "github.com/lf-edge/ekuiper/pkg/api"
  25. "github.com/lf-edge/ekuiper/pkg/ast"
  26. )
  27. var count atomic.Value
  28. func TestSourceOpen(r api.Source, exp []api.SourceTuple, t *testing.T) {
  29. result, err := RunMockSource(r, len(exp))
  30. if err != nil {
  31. t.Error(err)
  32. }
  33. for i, v := range result {
  34. switch v.(type) {
  35. case *api.DefaultSourceTuple:
  36. assert.Equal(t, exp[i].Message(), v.Message())
  37. assert.Equal(t, exp[i].Meta(), v.Meta())
  38. default:
  39. assert.Equal(t, exp[i], v)
  40. }
  41. }
  42. }
  43. func RunMockSource(r api.Source, limit int) ([]api.SourceTuple, error) {
  44. c := count.Load()
  45. if c == nil {
  46. count.Store(1)
  47. c = 0
  48. }
  49. ctx, cancel := mockContext.NewMockContext(fmt.Sprintf("rule%d", c), "op1").WithCancel()
  50. cv, _ := converter.GetOrCreateConverter(&ast.Options{FORMAT: "json"})
  51. ctx = context.WithValue(ctx.(*context.DefaultContext), context.DecodeKey, cv)
  52. count.Store(c.(int) + 1)
  53. consumer := make(chan api.SourceTuple)
  54. errCh := make(chan error)
  55. go r.Open(ctx, consumer, errCh)
  56. ticker := time.After(10 * time.Second)
  57. var result []api.SourceTuple
  58. outerloop:
  59. for {
  60. select {
  61. case err := <-errCh:
  62. cancel()
  63. return nil, err
  64. case tuple := <-consumer:
  65. result = append(result, tuple)
  66. limit--
  67. if limit <= 0 {
  68. break outerloop
  69. }
  70. case <-ticker:
  71. cancel()
  72. return nil, fmt.Errorf("timeout")
  73. }
  74. }
  75. err := r.Close(ctx)
  76. if err != nil {
  77. return nil, err
  78. }
  79. cancel()
  80. return result, nil
  81. }