test_source.go 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  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. "github.com/lf-edge/ekuiper/internal/converter"
  18. "github.com/lf-edge/ekuiper/internal/topo/context"
  19. "github.com/lf-edge/ekuiper/pkg/api"
  20. "github.com/lf-edge/ekuiper/pkg/ast"
  21. "reflect"
  22. "sync/atomic"
  23. "testing"
  24. "time"
  25. )
  26. var count atomic.Value
  27. func TestSourceOpen(r api.Source, exp []api.SourceTuple, t *testing.T) {
  28. c := count.Load()
  29. if c == nil {
  30. count.Store(1)
  31. c = 0
  32. }
  33. ctx, cancel := NewMockContext(fmt.Sprintf("rule%d", c), "op1").WithCancel()
  34. cv, _ := converter.GetOrCreateConverter(&ast.Options{FORMAT: "json"})
  35. ctx = context.WithValue(ctx.(*context.DefaultContext), context.DecodeKey, cv)
  36. count.Store(c.(int) + 1)
  37. consumer := make(chan api.SourceTuple)
  38. errCh := make(chan error)
  39. go r.Open(ctx, consumer, errCh)
  40. ticker := time.After(10 * time.Second)
  41. limit := len(exp)
  42. var result []api.SourceTuple
  43. outerloop:
  44. for {
  45. select {
  46. case err := <-errCh:
  47. t.Errorf("received error: %v", err)
  48. cancel()
  49. return
  50. case tuple := <-consumer:
  51. result = append(result, tuple)
  52. limit--
  53. if limit <= 0 {
  54. break outerloop
  55. }
  56. case <-ticker:
  57. t.Errorf("stop after timeout")
  58. t.Errorf("expect %v, but got %v", exp, result)
  59. cancel()
  60. return
  61. }
  62. }
  63. err := r.Close(ctx)
  64. if err != nil {
  65. t.Errorf(err.Error())
  66. return
  67. }
  68. cancel()
  69. if !reflect.DeepEqual(exp, result) {
  70. t.Errorf("result mismatch:\n exp=%s\n got=%s\n\n", exp, result)
  71. }
  72. }