backive/events_test.go

100 lines
1.8 KiB
Go
Raw Normal View History

2022-01-30 00:16:59 +01:00
package backive
import (
"encoding/json"
2022-01-31 22:18:21 +01:00
"fmt"
"io"
2022-01-30 00:16:59 +01:00
"log"
"net"
"os"
"testing"
"time"
)
2022-01-31 22:18:21 +01:00
type ConnStub struct {
}
var counter int
func (c ConnStub) Read(b []byte) (int, error) {
switch {
case counter == 0:
counter++
env := map[string]string{}
env["test"] = "test"
message := map[string]interface{}{}
message["request"] = "udev"
message["data"] = env
data, err := json.Marshal(message)
copy(b, data)
log.Println(string(b))
return len(data), err
case counter == 1:
counter++
return 0, io.EOF
case counter == 2:
counter++
return 0, fmt.Errorf("Some Error for testing")
default:
return 0, io.EOF
}
}
func (c ConnStub) Close() error {
return nil
}
func (c ConnStub) LocalAddr() net.Addr {
return nil
}
func (c ConnStub) RemoteAddr() net.Addr {
return nil
}
func (c ConnStub) SetDeadline(t time.Time) error {
return nil
}
func (c ConnStub) SetReadDeadline(t time.Time) error {
return nil
}
func (c ConnStub) SetWriteDeadline(t time.Time) error {
return nil
}
func (c ConnStub) Write(b []byte) (int, error) {
return 0, nil
}
var hasBeenCalled = false
2022-01-30 00:16:59 +01:00
func TestEventhandler(t *testing.T) {
eh := new(EventHandler)
2022-01-31 22:18:21 +01:00
err := eh.Init("./backive.socket")
if err != nil {
t.Fail()
}
2022-01-30 00:16:59 +01:00
defer func() {
err := os.Remove("./backive.socket")
if err != nil {
t.Log(err)
}
}()
t.Log("Initialized test")
2022-01-31 22:18:21 +01:00
//var hasBeenCalled = make(chan bool)
2022-01-30 00:16:59 +01:00
eh.RegisterCallback(
func(m map[string]string) {
2022-01-31 22:18:21 +01:00
t.Log("Callback got called")
hasBeenCalled = true
2022-01-30 00:16:59 +01:00
},
)
t.Log("registered callback")
2022-01-31 22:18:21 +01:00
mockAccept = func(eh *EventHandler) (net.Conn, error) {
t.Log("Mocked Accept() has been called.")
mycon := ConnStub{}
return mycon, nil
2022-01-30 00:16:59 +01:00
}
2022-01-31 22:18:21 +01:00
eh.process()
//beenCalled := <-hasBeenCalled
if !hasBeenCalled {
t.Log("Got false, need true.")
t.Fail()
2022-01-30 00:16:59 +01:00
}
}