test_source.go 1.7 KB

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