test_source.go 2.1 KB

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