test_source.go 2.2 KB

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