github.com/Jeffail/benthos/v3@v3.65.0/lib/input/plugin_test.go (about)

     1  package input
     2  
     3  import (
     4  	"errors"
     5  	"testing"
     6  
     7  	"github.com/Jeffail/benthos/v3/lib/log"
     8  	"github.com/Jeffail/benthos/v3/lib/metrics"
     9  	"github.com/Jeffail/benthos/v3/lib/types"
    10  	yaml "gopkg.in/yaml.v3"
    11  )
    12  
    13  type mockPluginConf struct {
    14  	Foo string `json:"foo" yaml:"foo"`
    15  	Bar string `json:"bar" yaml:"bar"`
    16  	Baz int    `json:"baz" yaml:"baz"`
    17  }
    18  
    19  func newMockPluginConf() interface{} {
    20  	return &mockPluginConf{
    21  		Foo: "default",
    22  		Bar: "change this",
    23  		Baz: 10,
    24  	}
    25  }
    26  
    27  func TestYAMLPlugin(t *testing.T) {
    28  	errTest := errors.New("test err")
    29  
    30  	RegisterPlugin("foo", newMockPluginConf,
    31  		func(conf interface{}, mgr types.Manager, logger log.Modular, stats metrics.Type) (types.Input, error) {
    32  			mConf, ok := conf.(*mockPluginConf)
    33  			if !ok {
    34  				t.Fatalf("failed to cast config: %T", conf)
    35  			}
    36  			if exp, act := "default", mConf.Foo; exp != act {
    37  				t.Errorf("Wrong config value: %v != %v", act, exp)
    38  			}
    39  			if exp, act := "custom", mConf.Bar; exp != act {
    40  				t.Errorf("Wrong config value: %v != %v", act, exp)
    41  			}
    42  			if exp, act := 10, mConf.Baz; exp != act {
    43  				t.Errorf("Wrong config value: %v != %v", act, exp)
    44  			}
    45  			return nil, errTest
    46  		})
    47  
    48  	confStr := `type: foo
    49  plugin:
    50    bar: custom`
    51  
    52  	conf := NewConfig()
    53  	if err := yaml.Unmarshal([]byte(confStr), &conf); err != nil {
    54  		t.Fatal(err)
    55  	}
    56  
    57  	_, err := New(conf, nil, log.Noop(), metrics.Noop())
    58  	if !errors.Is(err, errTest) {
    59  		t.Errorf("Wrong error returned: %v != %v", err, errTest)
    60  	}
    61  }
    62  
    63  func TestYAMLPluginNilConf(t *testing.T) {
    64  	errTest := errors.New("test err")
    65  
    66  	RegisterPlugin("foo", func() interface{} { return &struct{}{} },
    67  		func(conf interface{}, mgr types.Manager, logger log.Modular, stats metrics.Type) (types.Input, error) {
    68  			return nil, errTest
    69  		})
    70  
    71  	confStr := `type: foo
    72  plugin:
    73    foo: this will be ignored`
    74  
    75  	conf := NewConfig()
    76  	if err := yaml.Unmarshal([]byte(confStr), &conf); err != nil {
    77  		t.Fatal(err)
    78  	}
    79  
    80  	_, err := New(conf, nil, log.Noop(), metrics.Noop())
    81  	if !errors.Is(err, errTest) {
    82  		t.Errorf("Wrong error returned: %v != %v", err, errTest)
    83  	}
    84  }