本文整理匯總了Golang中github.com/mozilla-services/heka/pipelinemock.NewMockInputRunner函數的典型用法代碼示例。如果您正苦於以下問題:Golang NewMockInputRunner函數的具體用法?Golang NewMockInputRunner怎麽用?Golang NewMockInputRunner使用的例子?那麽, 這裏精選的函數代碼示例或許可以為您提供幫助。
在下文中一共展示了NewMockInputRunner函數的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Golang代碼示例。
示例1: HttpListenInputSpec
func HttpListenInputSpec(c gs.Context) {
t := &pipeline_ts.SimpleT{}
ctrl := gomock.NewController(t)
defer ctrl.Finish()
pConfig := NewPipelineConfig(nil)
httpListenInput := HttpListenInput{}
ith := new(plugins_ts.InputTestHelper)
ith.MockHelper = pipelinemock.NewMockPluginHelper(ctrl)
ith.MockInputRunner = pipelinemock.NewMockInputRunner(ctrl)
startInput := func() {
go func() {
httpListenInput.Run(ith.MockInputRunner, ith.MockHelper)
}()
}
ith.Pack = NewPipelinePack(pConfig.InputRecycleChan())
ith.PackSupply = make(chan *PipelinePack, 1)
config := httpListenInput.ConfigStruct().(*HttpListenInputConfig)
config.Address = "127.0.0.1:8325"
config.Decoder = "PayloadJsonDecoder"
ith.MockHelper.EXPECT().PipelineConfig().Return(pConfig)
mockDecoderRunner := pipelinemock.NewMockDecoderRunner(ctrl)
dRunnerInChan := make(chan *PipelinePack, 1)
mockDecoderRunner.EXPECT().InChan().Return(dRunnerInChan).AnyTimes()
ith.MockInputRunner.EXPECT().InChan().Return(ith.PackSupply).AnyTimes()
ith.MockInputRunner.EXPECT().Name().Return("HttpListenInput").AnyTimes()
ith.MockHelper.EXPECT().DecoderRunner("PayloadJsonDecoder", "HttpListenInput-PayloadJsonDecoder").Return(mockDecoderRunner, true)
err := httpListenInput.Init(config)
c.Assume(err, gs.IsNil)
ith.MockInputRunner.EXPECT().LogMessage(gomock.Any())
startInput()
c.Specify("A HttpListenInput", func() {
c.Specify("Adds query parameters to the message pack as fields", func() {
ith.PackSupply <- ith.Pack
resp, err := http.Get("http://127.0.0.1:8325/?test=Hello%20World")
c.Assume(err, gs.IsNil)
resp.Body.Close()
c.Assume(resp.StatusCode, gs.Equals, 200)
pack := <-dRunnerInChan
fieldValue, ok := pack.Message.GetFieldValue("test")
c.Assume(ok, gs.IsTrue)
c.Expect(fieldValue, gs.Equals, "Hello World")
})
httpListenInput.Stop()
})
}
示例2: TcpInputSpec
func TcpInputSpec(c gs.Context) {
t := &pipeline_ts.SimpleT{}
ctrl := gomock.NewController(t)
defer ctrl.Finish()
config := NewPipelineConfig(nil)
ith := new(plugins_ts.InputTestHelper)
ith.Msg = pipeline_ts.GetTestMessage()
ith.Pack = NewPipelinePack(config.InputRecycleChan())
ith.AddrStr = "localhost:55565"
ith.ResolvedAddrStr = "127.0.0.1:55565"
// set up mock helper, decoder set, and packSupply channel
ith.MockHelper = pipelinemock.NewMockPluginHelper(ctrl)
ith.MockInputRunner = pipelinemock.NewMockInputRunner(ctrl)
ith.Decoder = pipelinemock.NewMockDecoderRunner(ctrl)
ith.PackSupply = make(chan *PipelinePack, 1)
ith.DecodeChan = make(chan *PipelinePack)
key := "testkey"
signers := map[string]Signer{"test_1": {key}}
signer := "test"
c.Specify("A TcpInput protobuf parser", func() {
ith.MockInputRunner.EXPECT().Name().Return("TcpInput")
tcpInput := TcpInput{}
err := tcpInput.Init(&TcpInputConfig{Net: "tcp", Address: ith.AddrStr,
Signers: signers,
Decoder: "ProtobufDecoder",
ParserType: "message.proto"})
c.Assume(err, gs.IsNil)
realListener := tcpInput.listener
c.Expect(realListener.Addr().String(), gs.Equals, ith.ResolvedAddrStr)
realListener.Close()
mockConnection := pipeline_ts.NewMockConn(ctrl)
mockListener := pipeline_ts.NewMockListener(ctrl)
tcpInput.listener = mockListener
addr := new(address)
addr.str = "123"
mockConnection.EXPECT().RemoteAddr().Return(addr)
mbytes, _ := proto.Marshal(ith.Msg)
header := &message.Header{}
header.SetMessageLength(uint32(len(mbytes)))
err = errors.New("connection closed") // used in the read return(s)
readCall := mockConnection.EXPECT().Read(gomock.Any())
readEnd := mockConnection.EXPECT().Read(gomock.Any()).After(readCall)
readEnd.Return(0, err)
mockConnection.EXPECT().SetReadDeadline(gomock.Any()).Return(nil).AnyTimes()
mockConnection.EXPECT().Close()
neterr := pipeline_ts.NewMockError(ctrl)
neterr.EXPECT().Temporary().Return(false)
acceptCall := mockListener.EXPECT().Accept().Return(mockConnection, nil)
acceptCall.Do(func() {
acceptCall = mockListener.EXPECT().Accept()
acceptCall.Return(nil, neterr)
})
mockDecoderRunner := ith.Decoder.(*pipelinemock.MockDecoderRunner)
mockDecoderRunner.EXPECT().InChan().Return(ith.DecodeChan)
ith.MockInputRunner.EXPECT().InChan().Return(ith.PackSupply)
enccall := ith.MockHelper.EXPECT().DecoderRunner("ProtobufDecoder", "TcpInput-123-ProtobufDecoder").AnyTimes()
enccall.Return(ith.Decoder, true)
ith.MockHelper.EXPECT().StopDecoderRunner(ith.Decoder)
cleanup := func() {
mockListener.EXPECT().Close()
tcpInput.Stop()
tcpInput.wg.Wait()
}
c.Specify("reads a message from its connection", func() {
hbytes, _ := proto.Marshal(header)
buflen := 3 + len(hbytes) + len(mbytes)
readCall.Return(buflen, nil)
readCall.Do(getPayloadBytes(hbytes, mbytes))
go tcpInput.Run(ith.MockInputRunner, ith.MockHelper)
defer cleanup()
ith.PackSupply <- ith.Pack
packRef := <-ith.DecodeChan
c.Expect(ith.Pack, gs.Equals, packRef)
c.Expect(string(ith.Pack.MsgBytes), gs.Equals, string(mbytes))
})
c.Specify("reads a MD5 signed message from its connection", func() {
header.SetHmacHashFunction(message.Header_MD5)
header.SetHmacSigner(signer)
header.SetHmacKeyVersion(uint32(1))
hm := hmac.New(md5.New, []byte(key))
hm.Write(mbytes)
header.SetHmac(hm.Sum(nil))
hbytes, _ := proto.Marshal(header)
buflen := 3 + len(hbytes) + len(mbytes)
readCall.Return(buflen, nil)
readCall.Do(getPayloadBytes(hbytes, mbytes))
go tcpInput.Run(ith.MockInputRunner, ith.MockHelper)
defer cleanup()
//.........這裏部分代碼省略.........
示例3: TestReceivePayloadMessage
func TestReceivePayloadMessage(t *testing.T) {
b1 := sarama.NewMockBroker(t, 1)
b2 := sarama.NewMockBroker(t, 2)
ctrl := gomock.NewController(t)
tmpDir, tmpErr := ioutil.TempDir("", "kafkainput-tests")
if tmpErr != nil {
t.Errorf("Unable to create a temporary directory: %s", tmpErr)
}
defer func() {
if err := os.RemoveAll(tmpDir); err != nil {
t.Errorf("Cleanup failed: %s", err)
}
ctrl.Finish()
}()
topic := "test"
mdr := new(sarama.MetadataResponse)
mdr.AddBroker(b2.Addr(), b2.BrokerID())
mdr.AddTopicPartition(topic, 0, 2)
b1.Returns(mdr)
or := new(sarama.OffsetResponse)
or.AddTopicPartition(topic, 0, 0)
b2.Returns(or)
fr := new(sarama.FetchResponse)
fr.AddMessage(topic, 0, nil, sarama.ByteEncoder([]byte{0x41, 0x42}), 0)
b2.Returns(fr)
pConfig := NewPipelineConfig(nil)
pConfig.Globals.BaseDir = tmpDir
ki := new(KafkaInput)
ki.SetName(topic)
ki.SetPipelineConfig(pConfig)
config := ki.ConfigStruct().(*KafkaInputConfig)
config.Addrs = append(config.Addrs, b1.Addr())
config.Topic = topic
ith := new(plugins_ts.InputTestHelper)
ith.Pack = NewPipelinePack(pConfig.InputRecycleChan())
ith.MockHelper = pipelinemock.NewMockPluginHelper(ctrl)
ith.MockInputRunner = pipelinemock.NewMockInputRunner(ctrl)
ith.MockSplitterRunner = pipelinemock.NewMockSplitterRunner(ctrl)
err := ki.Init(config)
if err != nil {
t.Fatalf("%s", err)
}
ith.MockInputRunner.EXPECT().NewSplitterRunner("").Return(ith.MockSplitterRunner)
ith.MockSplitterRunner.EXPECT().UseMsgBytes().Return(false)
decChan := make(chan func(*PipelinePack), 1)
decCall := ith.MockSplitterRunner.EXPECT().SetPackDecorator(gomock.Any())
decCall.Do(func(dec func(pack *PipelinePack)) {
decChan <- dec
})
bytesChan := make(chan []byte, 1)
splitCall := ith.MockSplitterRunner.EXPECT().SplitBytes(gomock.Any(), nil)
splitCall.Do(func(recd []byte, del Deliverer) {
bytesChan <- recd
})
errChan := make(chan error)
go func() {
errChan <- ki.Run(ith.MockInputRunner, ith.MockHelper)
}()
recd := <-bytesChan
if string(recd) != "AB" {
t.Errorf("Invalid Payload Expected: AB received: %s", string(recd))
}
packDec := <-decChan
packDec(ith.Pack)
if ith.Pack.Message.GetType() != "heka.kafka" {
t.Errorf("Invalid Type %s", ith.Pack.Message.GetType())
}
// There is a hang on the consumer close with the mock broker
// closing the brokers before the consumer works around the issue
// and is good enough for this test.
b1.Close()
b2.Close()
ki.Stop()
err = <-errChan
if err != nil {
t.Fatal(err)
}
filename := filepath.Join(tmpDir, "kafka", "test.test.0.offset.bin")
if o, err := readCheckpoint(filename); err != nil {
t.Errorf("Could not read the checkpoint file: %s", filename)
} else {
if o != 1 {
t.Errorf("Incorrect offset Expected: 1 Received: %d", o)
//.........這裏部分代碼省略.........
示例4: HttpListenInputSpec
func HttpListenInputSpec(c gs.Context) {
t := &pipeline_ts.SimpleT{}
ctrl := gomock.NewController(t)
defer ctrl.Finish()
pConfig := NewPipelineConfig(nil)
ith := new(plugins_ts.InputTestHelper)
ith.Pack = NewPipelinePack(pConfig.InputRecycleChan())
httpListenInput := HttpListenInput{}
ith.MockHelper = pipelinemock.NewMockPluginHelper(ctrl)
ith.MockInputRunner = pipelinemock.NewMockInputRunner(ctrl)
ith.MockSplitterRunner = pipelinemock.NewMockSplitterRunner(ctrl)
errChan := make(chan error, 1)
startInput := func() {
go func() {
err := httpListenInput.Run(ith.MockInputRunner, ith.MockHelper)
errChan <- err
}()
}
config := httpListenInput.ConfigStruct().(*HttpListenInputConfig)
config.Address = "127.0.0.1:58325"
c.Specify("A HttpListenInput", func() {
startedChan := make(chan bool, 1)
defer close(startedChan)
ts := httptest.NewUnstartedServer(nil)
httpListenInput.starterFunc = func(hli *HttpListenInput) error {
if hli.conf.UseTls {
ts.StartTLS()
} else {
ts.Start()
}
startedChan <- true
return nil
}
// These EXPECTs imply that every spec below will send exactly one
// HTTP request to the input.
ith.MockInputRunner.EXPECT().NewSplitterRunner(gomock.Any()).Return(
ith.MockSplitterRunner)
ith.MockSplitterRunner.EXPECT().UseMsgBytes().Return(false)
ith.MockSplitterRunner.EXPECT().Done()
decChan := make(chan func(*PipelinePack), 1)
feedDecorator := func(decorator func(*PipelinePack)) {
decChan <- decorator
}
setDecCall := ith.MockSplitterRunner.EXPECT().SetPackDecorator(gomock.Any())
setDecCall.Do(feedDecorator)
splitCall := ith.MockSplitterRunner.EXPECT().SplitStreamNullSplitterToEOF(gomock.Any(),
nil)
bytesChan := make(chan []byte, 1)
splitAndDeliver := func(r io.Reader, del Deliverer) {
msgBytes, _ := ioutil.ReadAll(r)
bytesChan <- msgBytes
}
c.Specify("Adds query parameters to the message pack as fields", func() {
err := httpListenInput.Init(config)
c.Assume(err, gs.IsNil)
ts.Config = httpListenInput.server
splitCall.Return(io.EOF)
startInput()
<-startedChan
resp, err := http.Get(ts.URL + "/?test=Hello%20World")
resp.Body.Close()
c.Assume(err, gs.IsNil)
c.Assume(resp.StatusCode, gs.Equals, 200)
packDec := <-decChan
packDec(ith.Pack)
fieldValue, ok := ith.Pack.Message.GetFieldValue("test")
c.Assume(ok, gs.IsTrue)
c.Expect(fieldValue, gs.Equals, "Hello World")
})
c.Specify("Add custom headers", func() {
config.Headers = http.Header{
"One": []string{"two", "three"},
"Four": []string{"five", "six", "seven"},
}
err := httpListenInput.Init(config)
c.Assume(err, gs.IsNil)
ts.Config = httpListenInput.server
splitCall.Return(io.EOF)
startInput()
<-startedChan
resp, err := http.Get(ts.URL)
c.Assume(err, gs.IsNil)
resp.Body.Close()
c.Assume(resp.StatusCode, gs.Equals, 200)
//.........這裏部分代碼省略.........
示例5: HttpInputSpec
func HttpInputSpec(c gs.Context) {
t := &pipeline_ts.SimpleT{}
ctrl := gomock.NewController(t)
defer ctrl.Finish()
pConfig := NewPipelineConfig(nil)
json_post := `{"uuid": "xxBI3zyeXU+spG8Uiveumw==", "timestamp": 1372966886023588, "hostname": "Victors-MacBook-Air.local", "pid": 40183, "fields": [{"representation": "", "value_type": "STRING", "name": "cef_meta.syslog_priority", "value_string": [""]}, {"representation": "", "value_type": "STRING", "name": "cef_meta.syslog_ident", "value_string": [""]}, {"representation": "", "value_type": "STRING", "name": "cef_meta.syslog_facility", "value_string": [""]}, {"representation": "", "value_type": "STRING", "name": "cef_meta.syslog_options", "value_string": [""]}], "logger": "", "env_version": "0.8", "type": "cef", "payload": "Jul 04 15:41:26 Victors-MacBook-Air.local CEF:0|mozilla|weave|3|xx\\\\|x|xx\\\\|x|5|cs1Label=requestClientApplication cs1=MySuperBrowser requestMethod=GET request=/ src=127.0.0.1 dest=127.0.0.1 suser=none", "severity": 6}'`
c.Specify("A HttpInput", func() {
httpInput := HttpInput{}
ith := new(plugins_ts.InputTestHelper)
ith.MockHelper = pipelinemock.NewMockPluginHelper(ctrl)
ith.MockInputRunner = pipelinemock.NewMockInputRunner(ctrl)
c.Specify("honors time ticker to flush", func() {
startInput := func() {
go func() {
err := httpInput.Run(ith.MockInputRunner, ith.MockHelper)
c.Expect(err, gs.IsNil)
}()
}
ith.Pack = NewPipelinePack(pConfig.InputRecycleChan())
ith.PackSupply = make(chan *PipelinePack, 1)
ith.PackSupply <- ith.Pack
// Spin up a http server
server, err := plugins_ts.NewOneHttpServer(json_post, "localhost", 9876)
c.Expect(err, gs.IsNil)
go server.Start("/")
time.Sleep(10 * time.Millisecond)
config := httpInput.ConfigStruct().(*HttpInputConfig)
decoderName := "TestDecoder"
config.DecoderName = decoderName
config.Url = "http://localhost:9876/"
tickChan := make(chan time.Time)
ith.MockInputRunner.EXPECT().LogMessage(gomock.Any()).Times(2)
ith.MockHelper.EXPECT().PipelineConfig().Return(pConfig)
ith.MockInputRunner.EXPECT().InChan().Return(ith.PackSupply)
ith.MockInputRunner.EXPECT().Ticker().Return(tickChan)
mockDecoderRunner := pipelinemock.NewMockDecoderRunner(ctrl)
// Stub out the DecoderRunner input channel so that we can
// inspect bytes later on
dRunnerInChan := make(chan *PipelinePack, 1)
mockDecoderRunner.EXPECT().InChan().Return(dRunnerInChan)
ith.MockInputRunner.EXPECT().Name().Return("HttpInput")
ith.MockHelper.EXPECT().DecoderRunner(decoderName, "HttpInput-TestDecoder").Return(mockDecoderRunner, true)
err = httpInput.Init(config)
c.Assume(err, gs.IsNil)
startInput()
tickChan <- time.Now()
// We need for the pipeline to finish up
time.Sleep(50 * time.Millisecond)
})
c.Specify("short circuits packs into the router", func() {
startInput := func() {
go func() {
err := httpInput.Run(ith.MockInputRunner, ith.MockHelper)
c.Expect(err, gs.IsNil)
}()
}
ith.Pack = NewPipelinePack(pConfig.InputRecycleChan())
ith.PackSupply = make(chan *PipelinePack, 1)
ith.PackSupply <- ith.Pack
config := httpInput.ConfigStruct().(*HttpInputConfig)
config.Url = "http://localhost:9876/"
tickChan := make(chan time.Time)
ith.MockInputRunner.EXPECT().LogMessage(gomock.Any()).Times(2)
ith.MockHelper.EXPECT().PipelineConfig().Return(pConfig)
ith.MockInputRunner.EXPECT().InChan().Return(ith.PackSupply)
ith.MockInputRunner.EXPECT().Ticker().Return(tickChan)
err := httpInput.Init(config)
c.Assume(err, gs.IsNil)
startInput()
tickChan <- time.Now()
// We need for the pipeline to finish up
time.Sleep(50 * time.Millisecond)
})
c.Specify("supports configuring HTTP Basic Authentication", func() {
//.........這裏部分代碼省略.........
示例6: ProcessDirectoryInputSpec
func ProcessDirectoryInputSpec(c gs.Context) {
t := &pipeline_ts.SimpleT{}
ctrl := gomock.NewController(t)
defer ctrl.Finish()
pConfig := NewPipelineConfig(nil)
ith := new(plugins_ts.InputTestHelper)
ith.Msg = pipeline_ts.GetTestMessage()
ith.Pack = NewPipelinePack(pConfig.InputRecycleChan())
// set up mock helper, decoder set, and packSupply channel
ith.MockHelper = pipelinemock.NewMockPluginHelper(ctrl)
ith.MockInputRunner = pipelinemock.NewMockInputRunner(ctrl)
ith.MockDeliverer = pipelinemock.NewMockDeliverer(ctrl)
ith.MockSplitterRunner = pipelinemock.NewMockSplitterRunner(ctrl)
ith.PackSupply = make(chan *PipelinePack, 1)
ith.PackSupply <- ith.Pack
err := pConfig.RegisterDefault("NullSplitter")
c.Assume(err, gs.IsNil)
c.Specify("A ProcessDirectoryInput", func() {
pdiInput := ProcessDirectoryInput{}
pdiInput.SetPipelineConfig(pConfig)
config := pdiInput.ConfigStruct().(*ProcessDirectoryInputConfig)
workingDir, err := os.Getwd()
c.Assume(err, gs.IsNil)
config.ProcessDir = filepath.Join(workingDir, "testsupport", "processes")
// `Ticker` is the last thing called during the setup part of the
// input's `Run` method, so it triggers a waitgroup that tests can
// wait on when they need to ensure initialization has finished.
var started sync.WaitGroup
started.Add(1)
tickChan := make(chan time.Time, 1)
ith.MockInputRunner.EXPECT().Ticker().Return(tickChan).Do(
func() {
started.Done()
})
// Similarly we use a waitgroup to signal when LogMessage has been
// called to know when reloads have completed. Warning: If you call
// expectLogMessage with a msg that is never passed to LogMessage and
// then you call loaded.Wait() then your test will hang and never
// complete.
var loaded sync.WaitGroup
expectLogMessage := func(msg string) {
loaded.Add(1)
ith.MockInputRunner.EXPECT().LogMessage(msg).Do(
func(msg string) {
loaded.Done()
})
}
// Same name => same content.
paths := []string{
filepath.Join(config.ProcessDir, "100", "h0.toml"),
filepath.Join(config.ProcessDir, "100", "h1.toml"),
filepath.Join(config.ProcessDir, "200", "h0.toml"),
filepath.Join(config.ProcessDir, "300", "h1.toml"),
}
copyFile := func(src, dest string) {
inFile, err := os.Open(src)
c.Assume(err, gs.IsNil)
outFile, err := os.Create(dest)
c.Assume(err, gs.IsNil)
_, err = io.Copy(outFile, inFile)
c.Assume(err, gs.IsNil)
inFile.Close()
outFile.Close()
}
err = pdiInput.Init(config)
c.Expect(err, gs.IsNil)
for _, p := range paths {
expectLogMessage("Added: " + p)
}
go pdiInput.Run(ith.MockInputRunner, ith.MockHelper)
defer func() {
pdiInput.Stop()
for _, entry := range pdiInput.inputs {
entry.ir.Input().Stop()
}
}()
started.Wait()
c.Specify("loads scheduled jobs", func() {
pathIndex := func(name string) (i int) {
var p string
for i, p = range paths {
if name == p {
return
}
}
return -1
//.........這裏部分代碼省略.........
示例7: InputSpec
func InputSpec(c gs.Context) {
t := new(pipeline_ts.SimpleT)
ctrl := gomock.NewController(t)
var wg sync.WaitGroup
errChan := make(chan error, 1)
tickChan := make(chan time.Time)
defer func() {
close(tickChan)
close(errChan)
ctrl.Finish()
}()
pConfig := NewPipelineConfig(nil)
c.Specify("A SandboxInput", func() {
input := new(SandboxInput)
input.SetPipelineConfig(pConfig)
ith := new(plugins_ts.InputTestHelper)
ith.MockHelper = pipelinemock.NewMockPluginHelper(ctrl)
ith.MockInputRunner = pipelinemock.NewMockInputRunner(ctrl)
ith.PackSupply = make(chan *PipelinePack, 1)
ith.Pack = NewPipelinePack(ith.PackSupply)
ith.PackSupply <- ith.Pack
startInput := func() {
wg.Add(1)
go func() {
errChan <- input.Run(ith.MockInputRunner, ith.MockHelper)
wg.Done()
}()
}
c.Specify("test a polling input", func() {
tickChan := time.Tick(10 * time.Millisecond)
ith.MockInputRunner.EXPECT().Ticker().Return(tickChan)
ith.MockInputRunner.EXPECT().InChan().Return(ith.PackSupply).Times(2)
ith.MockInputRunner.EXPECT().LogError(fmt.Errorf("failure message"))
var cnt int
ith.MockInputRunner.EXPECT().Inject(gomock.Any()).Do(
func(pack *PipelinePack) {
switch cnt {
case 0:
c.Expect(pack.Message.GetPayload(), gs.Equals, "line 1")
case 1:
c.Expect(pack.Message.GetPayload(), gs.Equals, "line 3")
input.Stop()
}
cnt++
ith.PackSupply <- pack
}).Times(2)
config := input.ConfigStruct().(*sandbox.SandboxConfig)
config.ScriptFilename = "../lua/testsupport/input.lua"
err := input.Init(config)
c.Assume(err, gs.IsNil)
startInput()
wg.Wait()
c.Expect(<-errChan, gs.IsNil)
c.Expect(input.processMessageCount, gs.Equals, int64(2))
c.Expect(input.processMessageFailures, gs.Equals, int64(1))
c.Expect(input.processMessageBytes, gs.Equals, int64(72))
})
c.Specify("run once input", func() {
var tickChan <-chan time.Time
ith.MockInputRunner.EXPECT().Ticker().Return(tickChan)
ith.MockInputRunner.EXPECT().InChan().Return(ith.PackSupply).Times(1)
ith.MockInputRunner.EXPECT().LogMessage("single run completed")
ith.MockInputRunner.EXPECT().Inject(gomock.Any()).Do(
func(pack *PipelinePack) {
c.Expect(pack.Message.GetPayload(), gs.Equals, "line 1")
ith.PackSupply <- pack
}).Times(1)
config := input.ConfigStruct().(*sandbox.SandboxConfig)
config.ScriptFilename = "../lua/testsupport/input.lua"
err := input.Init(config)
c.Assume(err, gs.IsNil)
startInput()
wg.Wait()
c.Expect(<-errChan, gs.IsNil)
c.Expect(input.processMessageCount, gs.Equals, int64(1))
c.Expect(input.processMessageBytes, gs.Equals, int64(36))
})
c.Specify("exit with error", func() {
tickChan := make(chan time.Time)
defer close(tickChan)
ith.MockInputRunner.EXPECT().Ticker().Return(tickChan)
ith.MockInputRunner.EXPECT().LogError(fmt.Errorf("process_message() ../lua/testsupport/input_error.lua:2: boom"))
config := input.ConfigStruct().(*sandbox.SandboxConfig)
//.........這裏部分代碼省略.........
示例8: HttpListenInputSpec
func HttpListenInputSpec(c gs.Context) {
t := &pipeline_ts.SimpleT{}
ctrl := gomock.NewController(t)
defer ctrl.Finish()
pConfig := NewPipelineConfig(nil)
ith := new(plugins_ts.InputTestHelper)
ith.Pack = NewPipelinePack(pConfig.InputRecycleChan())
httpListenInput := HttpListenInput{}
ith.MockHelper = pipelinemock.NewMockPluginHelper(ctrl)
ith.MockInputRunner = pipelinemock.NewMockInputRunner(ctrl)
ith.MockSplitterRunner = pipelinemock.NewMockSplitterRunner(ctrl)
splitter := &TokenSplitter{} // Not actually used.
errChan := make(chan error, 1)
startInput := func() {
go func() {
err := httpListenInput.Run(ith.MockInputRunner, ith.MockHelper)
errChan <- err
}()
}
config := httpListenInput.ConfigStruct().(*HttpListenInputConfig)
config.Address = "127.0.0.1:58325"
c.Specify("A HttpListenInput", func() {
startedChan := make(chan bool, 1)
defer close(startedChan)
ts := httptest.NewUnstartedServer(nil)
httpListenInput.starterFunc = func(hli *HttpListenInput) error {
ts.Start()
startedChan <- true
return nil
}
// These EXPECTs imply that every spec below will send exactly one
// HTTP request to the input.
ith.MockInputRunner.EXPECT().NewSplitterRunner(gomock.Any()).Return(
ith.MockSplitterRunner)
ith.MockSplitterRunner.EXPECT().UseMsgBytes().Return(false)
ith.MockSplitterRunner.EXPECT().Splitter().Return(splitter)
decChan := make(chan func(*PipelinePack), 1)
feedDecorator := func(decorator func(*PipelinePack)) {
decChan <- decorator
}
setDecCall := ith.MockSplitterRunner.EXPECT().SetPackDecorator(gomock.Any())
setDecCall.Do(feedDecorator)
streamChan := make(chan io.Reader, 1)
feedStream := func(r io.Reader) {
streamChan <- r
}
getRecCall := ith.MockSplitterRunner.EXPECT().GetRecordFromStream(
gomock.Any()).Do(feedStream)
bytesChan := make(chan []byte, 1)
deliver := func(msgBytes []byte, del Deliverer) {
bytesChan <- msgBytes
}
ith.MockSplitterRunner.EXPECT().IncompleteFinal().Return(false).AnyTimes()
c.Specify("Adds query parameters to the message pack as fields", func() {
err := httpListenInput.Init(config)
c.Assume(err, gs.IsNil)
ts.Config = httpListenInput.server
getRecCall.Return(0, make([]byte, 0), io.EOF)
startInput()
<-startedChan
resp, err := http.Get(ts.URL + "/?test=Hello%20World")
resp.Body.Close()
c.Assume(err, gs.IsNil)
c.Assume(resp.StatusCode, gs.Equals, 200)
packDec := <-decChan
packDec(ith.Pack)
fieldValue, ok := ith.Pack.Message.GetFieldValue("test")
c.Assume(ok, gs.IsTrue)
c.Expect(fieldValue, gs.Equals, "Hello World")
})
c.Specify("Add custom headers", func() {
config.Headers = http.Header{
"One": []string{"two", "three"},
"Four": []string{"five", "six", "seven"},
}
err := httpListenInput.Init(config)
c.Assume(err, gs.IsNil)
ts.Config = httpListenInput.server
getRecCall.Return(0, make([]byte, 0), io.EOF)
startInput()
<-startedChan
resp, err := http.Get(ts.URL)
c.Assume(err, gs.IsNil)
resp.Body.Close()
c.Assume(resp.StatusCode, gs.Equals, 200)
//.........這裏部分代碼省略.........
示例9: LogfileInputSpec0
func LogfileInputSpec0(c gs.Context) {
t := &pipeline_ts.SimpleT{}
ctrl := gomock.NewController(t)
defer ctrl.Finish()
config := NewPipelineConfig(nil)
ith := new(plugins_ts.InputTestHelper)
ith.Msg = pipeline_ts.GetTestMessage()
ith.Pack = NewPipelinePack(config.InputRecycleChan())
// Specify localhost, but we're not really going to use the network
ith.AddrStr = "localhost:55565"
ith.ResolvedAddrStr = "127.0.0.1:55565"
// set up mock helper, decoder set, and packSupply channel
ith.MockHelper = pipelinemock.NewMockPluginHelper(ctrl)
ith.MockInputRunner = pipelinemock.NewMockInputRunner(ctrl)
ith.Decoder = pipelinemock.NewMockDecoderRunner(ctrl)
ith.PackSupply = make(chan *PipelinePack, 1)
ith.DecodeChan = make(chan *PipelinePack)
c.Specify("A LogFileInput", func() {
tmpDir, tmpErr := ioutil.TempDir("", "hekad-tests-")
c.Expect(tmpErr, gs.Equals, nil)
origBaseDir := Globals().BaseDir
Globals().BaseDir = tmpDir
defer func() {
Globals().BaseDir = origBaseDir
tmpErr = os.RemoveAll(tmpDir)
c.Expect(tmpErr, gs.IsNil)
}()
lfInput := new(LogfileInput)
lfiConfig := lfInput.ConfigStruct().(*LogfileInputConfig)
lfiConfig.SeekJournalName = "test-seekjournal"
lfiConfig.LogFile = "../testsupport/test-zeus.log"
lfiConfig.Logger = "zeus"
lfiConfig.UseSeekJournal = true
lfiConfig.Decoder = "decoder-name"
lfiConfig.DiscoverInterval = 1
lfiConfig.StatInterval = 1
err := lfInput.Init(lfiConfig)
c.Expect(err, gs.IsNil)
mockDecoderRunner := pipelinemock.NewMockDecoderRunner(ctrl)
// Create pool of packs.
numLines := 95 // # of lines in the log file we're parsing.
packs := make([]*PipelinePack, numLines)
ith.PackSupply = make(chan *PipelinePack, numLines)
for i := 0; i < numLines; i++ {
packs[i] = NewPipelinePack(ith.PackSupply)
ith.PackSupply <- packs[i]
}
c.Specify("reads a log file", func() {
// Expect InputRunner calls to get InChan and inject outgoing msgs
ith.MockInputRunner.EXPECT().LogError(gomock.Any()).AnyTimes()
ith.MockInputRunner.EXPECT().LogMessage(gomock.Any()).AnyTimes()
ith.MockInputRunner.EXPECT().InChan().Return(ith.PackSupply).Times(numLines)
// Expect calls to get decoder and decode each message. Since the
// decoding is a no-op, the message payload will be the log file
// line, unchanged.
ith.MockInputRunner.EXPECT().Name().Return("LogfileInput")
pbcall := ith.MockHelper.EXPECT().DecoderRunner(lfiConfig.Decoder, "LogfileInput-"+lfiConfig.Decoder)
pbcall.Return(mockDecoderRunner, true)
decodeCall := mockDecoderRunner.EXPECT().InChan().Times(numLines)
decodeCall.Return(ith.DecodeChan)
go func() {
err = lfInput.Run(ith.MockInputRunner, ith.MockHelper)
c.Expect(err, gs.IsNil)
}()
for x := 0; x < numLines; x++ {
_ = <-ith.DecodeChan
// Free up the scheduler while we wait for the log file lines
// to be processed.
runtime.Gosched()
}
lfInput.Stop()
fileBytes, err := ioutil.ReadFile(lfiConfig.LogFile)
c.Expect(err, gs.IsNil)
fileStr := string(fileBytes)
lines := strings.Split(fileStr, "\n")
for i, line := range lines {
if line == "" {
continue
}
c.Expect(packs[i].Message.GetPayload(), gs.Equals, line+"\n")
c.Expect(packs[i].Message.GetLogger(), gs.Equals, "zeus")
}
// Wait for the file update to hit the disk; better suggestions are welcome
runtime.Gosched()
time.Sleep(time.Millisecond * 250)
journalData := []byte(`{"last_hash":"f0b60af7f2cb35c3724151422e2f999af6e21fc0","last_len":300,"last_start":28650,"seek":28950}`)
journalFile, err := ioutil.ReadFile(filepath.Join(tmpDir, "seekjournals", lfiConfig.SeekJournalName))
c.Expect(err, gs.IsNil)
c.Expect(bytes.Compare(journalData, journalFile), gs.Equals, 0)
})
c.Specify("uses the filename as the default logger name", func() {
//.........這裏部分代碼省略.........
示例10: TestReceiveProtobufMessage
func TestReceiveProtobufMessage(t *testing.T) {
broker := sarama.NewMockBroker(t, 2)
ctrl := gomock.NewController(t)
tmpDir, tmpErr := ioutil.TempDir("", "kafkainput-tests")
if tmpErr != nil {
t.Errorf("Unable to create a temporary directory: %s", tmpErr)
}
defer func() {
if err := os.RemoveAll(tmpDir); err != nil {
t.Errorf("Cleanup failed: %s", err)
}
ctrl.Finish()
}()
topic := "test"
mockFetchResponse := sarama.NewMockFetchResponse(t, 1)
mockFetchResponse.SetMessage(topic, 0, 0, sarama.ByteEncoder([]byte{0x41, 0x42}))
broker.SetHandlerByMap(map[string]sarama.MockResponse{
"MetadataRequest": sarama.NewMockMetadataResponse(t).
SetBroker(broker.Addr(), broker.BrokerID()).
SetLeader(topic, 0, broker.BrokerID()),
"OffsetRequest": sarama.NewMockOffsetResponse(t).
SetOffset(topic, 0, sarama.OffsetOldest, 0).
SetOffset(topic, 0, sarama.OffsetNewest, 2),
"FetchRequest": mockFetchResponse,
})
pConfig := NewPipelineConfig(nil)
pConfig.Globals.BaseDir = tmpDir
ki := new(KafkaInput)
ki.SetName(topic)
ki.SetPipelineConfig(pConfig)
config := ki.ConfigStruct().(*KafkaInputConfig)
config.Addrs = append(config.Addrs, broker.Addr())
config.Topic = topic
ith := new(plugins_ts.InputTestHelper)
ith.Pack = NewPipelinePack(pConfig.InputRecycleChan())
ith.MockHelper = pipelinemock.NewMockPluginHelper(ctrl)
ith.MockInputRunner = pipelinemock.NewMockInputRunner(ctrl)
ith.MockSplitterRunner = pipelinemock.NewMockSplitterRunner(ctrl)
err := ki.Init(config)
if err != nil {
t.Fatalf("%s", err)
}
ith.MockInputRunner.EXPECT().NewSplitterRunner("").Return(ith.MockSplitterRunner)
ith.MockSplitterRunner.EXPECT().UseMsgBytes().Return(true)
ith.MockSplitterRunner.EXPECT().Done()
bytesChan := make(chan []byte, 1)
splitCall := ith.MockSplitterRunner.EXPECT().SplitBytes(gomock.Any(), nil)
splitCall.Do(func(recd []byte, del Deliverer) {
bytesChan <- recd
})
errChan := make(chan error)
go func() {
errChan <- ki.Run(ith.MockInputRunner, ith.MockHelper)
}()
recd := <-bytesChan
if string(recd) != "AB" {
t.Errorf("Invalid MsgBytes Expected: AB received: %s", string(recd))
}
// There is a hang on the consumer close with the mock broker
// closing the brokers before the consumer works around the issue
// and is good enough for this test.
broker.Close()
ki.Stop()
err = <-errChan
if err != nil {
t.Fatal(err)
}
}
示例11: LogfileInputSpec1
func LogfileInputSpec1(c gs.Context) {
t := &pipeline_ts.SimpleT{}
ctrl := gomock.NewController(t)
defer ctrl.Finish()
config := NewPipelineConfig(nil)
tmpDir, tmpErr := ioutil.TempDir("", "hekad-tests-")
c.Expect(tmpErr, gs.Equals, nil)
origBaseDir := Globals().BaseDir
Globals().BaseDir = tmpDir
defer func() {
Globals().BaseDir = origBaseDir
tmpErr = os.RemoveAll(tmpDir)
c.Expect(tmpErr, gs.Equals, nil)
}()
journalName := "test-seekjournal"
journalDir := filepath.Join(tmpDir, "seekjournal")
tmpErr = os.MkdirAll(journalDir, 0770)
c.Expect(tmpErr, gs.Equals, nil)
ith := new(plugins_ts.InputTestHelper)
ith.Msg = pipeline_ts.GetTestMessage()
ith.Pack = NewPipelinePack(config.InputRecycleChan())
// Specify localhost, but we're not really going to use the network
ith.AddrStr = "localhost:55565"
ith.ResolvedAddrStr = "127.0.0.1:55565"
// set up mock helper, decoder set, and packSupply channel
ith.MockHelper = pipelinemock.NewMockPluginHelper(ctrl)
ith.MockInputRunner = pipelinemock.NewMockInputRunner(ctrl)
ith.PackSupply = make(chan *PipelinePack, 1)
ith.DecodeChan = make(chan *PipelinePack)
c.Specify("A LogfileInput", func() {
c.Specify("save the seek position of the last complete logline", func() {
lfInput, lfiConfig := createIncompleteLogfileInput(journalName)
// Initialize the input test helper
err := lfInput.Init(lfiConfig)
c.Expect(err, gs.IsNil)
dName := "decoder-name"
lfInput.decoderName = dName
mockDecoderRunner := pipelinemock.NewMockDecoderRunner(ctrl)
// Create pool of packs.
numLines := 4 // # of lines in the log file we're parsing.
packs := make([]*PipelinePack, numLines)
ith.PackSupply = make(chan *PipelinePack, numLines)
for i := 0; i < numLines; i++ {
packs[i] = NewPipelinePack(ith.PackSupply)
ith.PackSupply <- packs[i]
}
// Expect InputRunner calls to get InChan and inject outgoing msgs
ith.MockInputRunner.EXPECT().InChan().Return(ith.PackSupply).Times(numLines)
// Expect calls to get decoder and decode each message. Since the
// decoding is a no-op, the message payload will be the log file
// line, unchanged.
ith.MockInputRunner.EXPECT().Name().Return("LogfileInput")
pbcall := ith.MockHelper.EXPECT().DecoderRunner(dName, "LogfileInput-"+dName)
pbcall.Return(mockDecoderRunner, true)
decodeCall := mockDecoderRunner.EXPECT().InChan().Times(numLines)
decodeCall.Return(ith.DecodeChan)
go func() {
err = lfInput.Run(ith.MockInputRunner, ith.MockHelper)
c.Expect(err, gs.IsNil)
}()
for x := 0; x < numLines; x++ {
_ = <-ith.DecodeChan
// Free up the scheduler while we wait for the log file lines
// to be processed.
runtime.Gosched()
}
newFM := new(FileMonitor)
newFM.Init(lfiConfig)
c.Expect(err, gs.Equals, nil)
fbytes, _ := json.Marshal(lfInput.Monitor)
// Check that the persisted hashcode is from the last
// complete log line
expected_lastline := `10.1.1.4 plinko-565.byzantium.mozilla.com user3 [15/Mar/2013:12:20:27 -0700] "GET /1.1/user3/storage/passwords?newer=1356237662.44&full=1 HTTP/1.1" 200 1396 "-" "Firefox/20.0.1 FxSync/1.22.0.201304.desktop" "-" "ssl: SSL_RSA_WITH_RC4_128_SHA, version=TLSv1, bits=128" node_s:0.047167 req_s:0.047167 retries:0 req_b:446 "c_l:-"` + "\n"
c.Expect((strings.IndexAny(string(fbytes),
sha1_hexdigest(expected_lastline)) > -1), gs.IsTrue)
json.Unmarshal(fbytes, &newFM)
if runtime.GOOS == "windows" {
c.Expect(newFM.seek, gs.Equals, int64(1253))
} else {
c.Expect(newFM.seek, gs.Equals, int64(1249))
}
lfInput.Stop()
//.........這裏部分代碼省略.........
示例12: NsqInputSpec
func NsqInputSpec(c gs.Context) {
t := new(pipeline_ts.SimpleT)
ctrl := gomock.NewController(t)
defer ctrl.Finish()
pConfig := pipeline.NewPipelineConfig(nil)
var wg sync.WaitGroup
errChan := make(chan error, 1)
retPackChan := make(chan *pipeline.PipelinePack, 1)
defer close(errChan)
defer close(retPackChan)
c.Specify("A nsq input", func() {
input := new(NsqInput)
ith := new(plugins_ts.InputTestHelper)
ith.MockHelper = pipelinemock.NewMockPluginHelper(ctrl)
ith.MockInputRunner = pipelinemock.NewMockInputRunner(ctrl)
config := input.ConfigStruct().(*NsqInputConfig)
config.Topic = "test_topic"
config.Channel = "test_channel"
startInput := func() {
wg.Add(1)
go func() {
errChan <- input.Run(ith.MockInputRunner, ith.MockHelper)
wg.Done()
}()
}
var mockConsumer *MockConsumer
input.newConsumer = func(topic, channel string, config *nsq.Config) (Consumer, error) {
mockConsumer, _ = NewMockConsumer(topic, channel, config)
return mockConsumer, nil
}
ith.Pack = pipeline.NewPipelinePack(pConfig.InputRecycleChan())
ith.PackSupply = make(chan *pipeline.PipelinePack, 1)
ith.PackSupply <- ith.Pack
inputName := "NsqInput"
ith.MockInputRunner.EXPECT().Name().Return(inputName).AnyTimes()
ith.MockInputRunner.EXPECT().InChan().Return(ith.PackSupply)
c.Specify("that is started", func() {
input.SetPipelineConfig(pConfig)
c.Specify("gets messages its subscribed to", func() {
c.Specify("injects messages into the pipeline when not configured with a decoder", func() {
ith.MockInputRunner.EXPECT().Inject(ith.Pack).Do(func(p *pipeline.PipelinePack) {
retPackChan <- p
}).AnyTimes()
err := input.Init(config)
c.Expect(err, gs.IsNil)
c.Expect(input.DecoderName, gs.Equals, "")
})
c.Specify("injects messages into the decoder when configured", func() {
decoderName := "ScribbleDecoder"
config.DecoderName = decoderName
decoder := new(plugins.ScribbleDecoder)
decoder.Init(&plugins.ScribbleDecoderConfig{})
mockDecoderRunner := pipelinemock.NewMockDecoderRunner(ctrl)
mockDecoderRunner.EXPECT().InChan().Return(retPackChan)
ith.MockHelper.EXPECT().DecoderRunner(decoderName,
fmt.Sprintf("%s-%s", inputName, decoderName),
).Return(mockDecoderRunner, true)
err := input.Init(config)
c.Expect(err, gs.IsNil)
c.Expect(input.DecoderName, gs.Equals, decoderName)
})
startInput()
// Should get two finished conn calls since we connect
// to lookupds and nsqds
c.Expect(<-mockConsumer.finishedConn, gs.IsTrue)
c.Expect(<-mockConsumer.finishedConn, gs.IsTrue)
id := nsq.MessageID{}
body := []byte("test")
msg := nsq.NewMessage(id, body)
for _, handler := range mockConsumer.handlers {
handler.HandleMessage(msg)
}
p := <-retPackChan
c.Expect(p.Message.GetPayload(), gs.Equals, "test")
})
input.Stop()
wg.Wait()
c.Expect(<-errChan, gs.IsNil)
//.........這裏部分代碼省略.........
示例13: FileMonitorSpec
func FileMonitorSpec(c gs.Context) {
config := NewPipelineConfig(nil)
tmpDir, tmpErr := ioutil.TempDir("", "hekad-tests-")
c.Expect(tmpErr, gs.Equals, nil)
origBaseDir := Globals().BaseDir
Globals().BaseDir = tmpDir
defer func() {
Globals().BaseDir = origBaseDir
tmpErr = os.RemoveAll(tmpDir)
c.Expect(tmpErr, gs.Equals, nil)
}()
journalName := "test-seekjournal"
journalDir := filepath.Join(tmpDir, "seekjournals")
tmpErr = os.MkdirAll(journalDir, 0770)
c.Expect(tmpErr, gs.Equals, nil)
journalPath := filepath.Join(journalDir, journalName)
t := &pipeline_ts.SimpleT{}
ctrl := gomock.NewController(t)
defer ctrl.Finish()
ith := new(plugins_ts.InputTestHelper)
ith.Msg = pipeline_ts.GetTestMessage()
ith.Pack = NewPipelinePack(config.InputRecycleChan())
// Specify localhost, but we're not really going to use the network
ith.AddrStr = "localhost:55565"
ith.ResolvedAddrStr = "127.0.0.1:55565"
// set up mock helper, decoder set, and packSupply channel
ith.MockHelper = pipelinemock.NewMockPluginHelper(ctrl)
ith.MockInputRunner = pipelinemock.NewMockInputRunner(ctrl)
ith.Decoder = pipelinemock.NewMockDecoderRunner(ctrl)
ith.PackSupply = make(chan *PipelinePack, 1)
ith.DecodeChan = make(chan *PipelinePack)
c.Specify("saved last read position", func() {
c.Specify("without a previous journal", func() {
ith.MockInputRunner.EXPECT().LogError(gomock.Any()).AnyTimes()
lfInput, lfiConfig := createLogfileInput(journalName)
// Initialize the input test helper
err := lfInput.Init(lfiConfig)
c.Expect(err, gs.IsNil)
dName := "decoder-name"
lfInput.decoderName = dName
mockDecoderRunner := pipelinemock.NewMockDecoderRunner(ctrl)
// Create pool of packs.
numLines := 95 // # of lines in the log file we're parsing.
packs := make([]*PipelinePack, numLines)
ith.PackSupply = make(chan *PipelinePack, numLines)
for i := 0; i < numLines; i++ {
packs[i] = NewPipelinePack(ith.PackSupply)
ith.PackSupply <- packs[i]
}
// Expect InputRunner calls to get InChan and inject outgoing msgs
ith.MockInputRunner.EXPECT().InChan().Return(ith.PackSupply).Times(numLines)
// Expect calls to get decoder and decode each message. Since the
// decoding is a no-op, the message payload will be the log file
// line, unchanged.
ith.MockInputRunner.EXPECT().Name().Return("FileMonitor")
ith.MockHelper.EXPECT().DecoderRunner(dName, "FileMonitor-"+dName).Return(mockDecoderRunner, true)
decodeCall := mockDecoderRunner.EXPECT().InChan().Times(numLines)
decodeCall.Return(ith.DecodeChan)
go func() {
err = lfInput.Run(ith.MockInputRunner, ith.MockHelper)
c.Expect(err, gs.IsNil)
}()
for x := 0; x < numLines; x++ {
_ = <-ith.DecodeChan
// Free up the scheduler while we wait for the log file lines
// to be processed.
runtime.Gosched()
}
newFM := new(FileMonitor)
newFM.Init(lfiConfig)
c.Expect(err, gs.Equals, nil)
fbytes, _ := json.Marshal(lfInput.Monitor)
json.Unmarshal(fbytes, &newFM)
c.Expect(newFM.seek, gs.Equals, int64(28950))
lfInput.Stop()
})
c.Specify("with a previous journal initializes with a seek value", func() {
lfInput, lfiConfig := createLogfileInput(journalName)
journalData := `{"last_hash":"f0b60af7f2cb35c3724151422e2f999af6e21fc0","last_start":28650,"last_len":300,"seek":28950}`
journal, journalErr := os.OpenFile(journalPath, os.O_CREATE|os.O_RDWR, 0660)
c.Expect(journalErr, gs.Equals, nil)
journal.WriteString(journalData)
journal.Close()
//.........這裏部分代碼省略.........
示例14: ProcessInputSpec
func ProcessInputSpec(c gs.Context) {
t := &pipeline_ts.SimpleT{}
ctrl := gomock.NewController(t)
defer ctrl.Finish()
pConfig := NewPipelineConfig(nil)
ith := new(plugins_ts.InputTestHelper)
ith.Msg = pipeline_ts.GetTestMessage()
ith.MockHelper = pipelinemock.NewMockPluginHelper(ctrl)
ith.MockInputRunner = pipelinemock.NewMockInputRunner(ctrl)
ith.MockDeliverer = pipelinemock.NewMockDeliverer(ctrl)
ith.MockSplitterRunner = pipelinemock.NewMockSplitterRunner(ctrl)
ith.Pack = NewPipelinePack(pConfig.InputRecycleChan())
c.Specify("A ProcessInput", func() {
pInput := ProcessInput{}
config := pInput.ConfigStruct().(*ProcessInputConfig)
config.Command = make(map[string]cmdConfig)
ith.MockHelper.EXPECT().Hostname().Return(pConfig.Hostname())
tickChan := make(chan time.Time)
ith.MockInputRunner.EXPECT().Ticker().Return(tickChan)
errChan := make(chan error)
ith.MockSplitterRunner.EXPECT().UseMsgBytes().Return(false)
decChan := make(chan func(*PipelinePack), 1)
setDecCall := ith.MockSplitterRunner.EXPECT().SetPackDecorator(gomock.Any())
setDecCall.Do(func(dec func(*PipelinePack)) {
decChan <- dec
})
bytesChan := make(chan []byte, 1)
splitCall := ith.MockSplitterRunner.EXPECT().SplitStream(gomock.Any(),
ith.MockDeliverer).Return(nil)
splitCall.Do(func(r io.Reader, del Deliverer) {
bytes, err := ioutil.ReadAll(r)
c.Assume(err, gs.IsNil)
bytesChan <- bytes
})
ith.MockDeliverer.EXPECT().Done()
c.Specify("using stdout", func() {
ith.MockInputRunner.EXPECT().NewDeliverer("stdout").Return(ith.MockDeliverer)
ith.MockInputRunner.EXPECT().NewSplitterRunner("stdout").Return(
ith.MockSplitterRunner)
c.Specify("reads a message from ProcessInput", func() {
pInput.SetName("SimpleTest")
// Note that no working directory is explicitly specified.
config.Command["0"] = cmdConfig{
Bin: PROCESSINPUT_TEST1_CMD,
Args: PROCESSINPUT_TEST1_CMD_ARGS,
}
err := pInput.Init(config)
c.Assume(err, gs.IsNil)
go func() {
errChan <- pInput.Run(ith.MockInputRunner, ith.MockHelper)
}()
tickChan <- time.Now()
actual := <-bytesChan
c.Expect(string(actual), gs.Equals, PROCESSINPUT_TEST1_OUTPUT+"\n")
dec := <-decChan
dec(ith.Pack)
fPInputName := ith.Pack.Message.FindFirstField("ProcessInputName")
c.Expect(fPInputName.ValueString[0], gs.Equals, "SimpleTest.stdout")
pInput.Stop()
err = <-errChan
c.Expect(err, gs.IsNil)
})
c.Specify("can pipe multiple commands together", func() {
pInput.SetName("PipedCmd")
// Note that no working directory is explicitly specified.
config.Command["0"] = cmdConfig{
Bin: PROCESSINPUT_PIPE_CMD1,
Args: PROCESSINPUT_PIPE_CMD1_ARGS,
}
config.Command["1"] = cmdConfig{
Bin: PROCESSINPUT_PIPE_CMD2,
Args: PROCESSINPUT_PIPE_CMD2_ARGS,
}
err := pInput.Init(config)
c.Assume(err, gs.IsNil)
go func() {
errChan <- pInput.Run(ith.MockInputRunner, ith.MockHelper)
}()
tickChan <- time.Now()
//.........這裏部分代碼省略.........
示例15: HttpInputSpec
func HttpInputSpec(c gs.Context) {
t := &pipeline_ts.SimpleT{}
ctrl := gomock.NewController(t)
defer ctrl.Finish()
pConfig := NewPipelineConfig(nil)
json_post := `{"uuid": "xxBI3zyeXU+spG8Uiveumw==", "timestamp": 1372966886023588, "hostname": "Victors-MacBook-Air.local", "pid": 40183, "fields": [{"representation": "", "value_type": "STRING", "name": "cef_meta.syslog_priority", "value_string": [""]}, {"representation": "", "value_type": "STRING", "name": "cef_meta.syslog_ident", "value_string": [""]}, {"representation": "", "value_type": "STRING", "name": "cef_meta.syslog_facility", "value_string": [""]}, {"representation": "", "value_type": "STRING", "name": "cef_meta.syslog_options", "value_string": [""]}], "logger": "", "env_version": "0.8", "type": "cef", "payload": "Jul 04 15:41:26 Victors-MacBook-Air.local CEF:0|mozilla|weave|3|xx\\\\|x|xx\\\\|x|5|cs1Label=requestClientApplication cs1=MySuperBrowser requestMethod=GET request=/ src=127.0.0.1 dest=127.0.0.1 suser=none", "severity": 6}'`
c.Specify("A HttpInput", func() {
httpInput := HttpInput{}
ith := new(plugins_ts.InputTestHelper)
ith.MockHelper = pipelinemock.NewMockPluginHelper(ctrl)
ith.MockInputRunner = pipelinemock.NewMockInputRunner(ctrl)
ith.MockSplitterRunner = pipelinemock.NewMockSplitterRunner(ctrl)
runOutputChan := make(chan error, 1)
startInput := func() {
go func() {
runOutputChan <- httpInput.Run(ith.MockInputRunner, ith.MockHelper)
}()
}
ith.Pack = NewPipelinePack(pConfig.InputRecycleChan())
// These assume that every sub-spec starts the input.
config := httpInput.ConfigStruct().(*HttpInputConfig)
tickChan := make(chan time.Time)
ith.MockInputRunner.EXPECT().Ticker().Return(tickChan)
ith.MockHelper.EXPECT().Hostname().Return("hekatests.example.com")
// These assume that every sub-spec makes exactly one HTTP request.
ith.MockInputRunner.EXPECT().NewSplitterRunner("0").Return(ith.MockSplitterRunner)
getRecCall := ith.MockSplitterRunner.EXPECT().GetRecordFromStream(gomock.Any())
getRecCall.Return(len(json_post), []byte(json_post), io.EOF)
ith.MockSplitterRunner.EXPECT().UseMsgBytes().Return(false)
decChan := make(chan func(*PipelinePack), 1)
packDecCall := ith.MockSplitterRunner.EXPECT().SetPackDecorator(gomock.Any())
packDecCall.Do(func(dec func(*PipelinePack)) {
decChan <- dec
})
ith.MockSplitterRunner.EXPECT().DeliverRecord([]byte(json_post), nil)
ith.MockSplitterRunner.EXPECT().IncompleteFinal().Return(false).AnyTimes()
splitter := &TokenSplitter{} // not actually used
ith.MockSplitterRunner.EXPECT().Splitter().Return(splitter)
c.Specify("honors time ticker to flush", func() {
// Spin up a http server.
server, err := plugins_ts.NewOneHttpServer(json_post, "localhost", 9876)
c.Expect(err, gs.IsNil)
go server.Start("/")
time.Sleep(10 * time.Millisecond)
config.Url = "http://localhost:9876/"
err = httpInput.Init(config)
c.Assume(err, gs.IsNil)
startInput()
tickChan <- time.Now()
// Getting the decorator means we've made our HTTP request.
<-decChan
})
c.Specify("supports configuring HTTP Basic Authentication", func() {
// Spin up a http server which expects username "user" and password "password"
server, err := plugins_ts.NewHttpBasicAuthServer("user", "password", "localhost", 9875)
c.Expect(err, gs.IsNil)
go server.Start("/BasicAuthTest")
time.Sleep(10 * time.Millisecond)
config.Url = "http://localhost:9875/BasicAuthTest"
config.User = "user"
config.Password = "password"
err = httpInput.Init(config)
c.Assume(err, gs.IsNil)
startInput()
tickChan <- time.Now()
dec := <-decChan
dec(ith.Pack)
// we expect a statuscode 200 (i.e. success)
statusCode, ok := ith.Pack.Message.GetFieldValue("StatusCode")
c.Assume(ok, gs.IsTrue)
c.Expect(statusCode, gs.Equals, int64(200))
})
c.Specify("supports configuring a different HTTP method", func() {
// Spin up a http server which expects requests with method "POST"
server, err := plugins_ts.NewHttpMethodServer("POST", "localhost", 9874)
c.Expect(err, gs.IsNil)
go server.Start("/PostTest")
time.Sleep(10 * time.Millisecond)
config.Url = "http://localhost:9874/PostTest"
config.Method = "POST"
//.........這裏部分代碼省略.........