diff --git a/backup_test.go b/backup_test.go index fc86d72..1d9401c 100644 --- a/backup_test.go +++ b/backup_test.go @@ -92,6 +92,10 @@ func TestCanRun(t *testing.T) { t.Log("Frequency zero can be executed anytime.") t.Fail() } + if !bkpFrequencyZero.ShouldRun() { + t.Log("Frequency zero can be executed anytime, should run does not work.") + t.Fail() + } runs.RegisterRun(&bkpFrequencySeven) err = bkpFrequencySeven.CanRun() diff --git a/events.go b/events.go index 3cd9152..e15eafa 100644 --- a/events.go +++ b/events.go @@ -9,37 +9,29 @@ import ( "path" ) +var mockAccept = func(eh *EventHandler) (net.Conn, error) { + log.Println("Calling eh.ls.Accept()") + return eh.ls.Accept() +} + // EventHandler holds the necessary elements to get an eventhandler setup and working. type EventHandler struct { - ls net.Listener - //done <-chan struct{} + ls net.Listener callbacks []func(map[string]string) - stop chan bool } // Init initializes the unix socket. -func (eh *EventHandler) Init(socketPath string) { - eh.stop = make(chan bool) +func (eh *EventHandler) Init(socketPath string) error { log.Println("Initializing EventHandler...") var err error dir, _ := path.Split(socketPath) CreateDirectoryIfNotExists(dir) eh.ls, err = net.Listen("unix", socketPath) if err != nil { - panic(err) + return err } eh.callbacks = make([]func(map[string]string), 3) -} - -// Stop stops the Eventhandler -func (eh *EventHandler) Stop() { - log.Println("Closing EventHandler") - eh.stop <- true - err := eh.ls.Close() - if err != nil { - log.Println("Error closing the listener") - } - log.Println("Closed EventHandler") + return nil } // Listen starts the event loop. @@ -47,12 +39,7 @@ func (eh *EventHandler) Listen() { log.Println("Running eventloop") func() { for { - select { - case <-eh.stop: - return - default: - eh.process() - } + eh.process() } }() } @@ -64,23 +51,21 @@ func (eh *EventHandler) RegisterCallback(cb func(map[string]string)) { // process processes each and every unix socket event, Unmarshals the json data and calls the list of callbacks. func (eh *EventHandler) process() { - client, err := eh.ls.Accept() + client, err := mockAccept(eh) log.Println("Accepted client") if err != nil { - select { - case <-eh.stop: - return - default: - log.Fatal(err) - } + log.Println(err) + return } defer client.Close() data := make([]byte, 2048) for { buf := make([]byte, 512) nr, err := client.Read(buf) + log.Printf("Read %d bytes...", nr) if err != nil && err != io.EOF { - log.Fatal(err) + log.Println(err) + return } data = append(data, buf[0:nr]...) if err == io.EOF { @@ -88,12 +73,14 @@ func (eh *EventHandler) process() { } } sdata := string(bytes.Trim(data, "\x00")) - //log.Println(sdata) var message map[string]interface{} + log.Printf("Reading JSON: %s", sdata) errjson := json.Unmarshal([]byte(sdata), &message) if errjson != nil { - log.Fatal(errjson) + log.Println(errjson) + return } + log.Println("Calling callbacks") var env = map[string]string{} if message["request"] == "udev" { for k, v := range message["data"].(map[string]interface{}) { @@ -102,6 +89,7 @@ func (eh *EventHandler) process() { } for _, v := range eh.callbacks { if v != nil { + log.Println("Calling callback") v(env) } } diff --git a/events_test.go b/events_test.go index 35d8b17..5ebd759 100644 --- a/events_test.go +++ b/events_test.go @@ -2,6 +2,8 @@ package backive import ( "encoding/json" + "fmt" + "io" "log" "net" "os" @@ -9,73 +11,89 @@ import ( "time" ) +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 + func TestEventhandler(t *testing.T) { - t.Skip("Do not get it to work...") eh := new(EventHandler) - eh.Init("./backive.socket") + err := eh.Init("./backive.socket") + if err != nil { + t.Fail() + } defer func() { - eh.Stop() err := os.Remove("./backive.socket") if err != nil { t.Log(err) } }() t.Log("Initialized test") - go eh.Listen() - t.Log("eh is listening") - var hasBeenCalled = make(chan bool) + //var hasBeenCalled = make(chan bool) eh.RegisterCallback( func(m map[string]string) { - hasBeenCalled <- true + t.Log("Callback got called") + hasBeenCalled = true }, ) t.Log("registered callback") - beenCalled := false - var counter = 0 - env := map[string]string{} - env["test"] = "test" - message := map[string]interface{}{} - message["request"] = "udev" - message["data"] = env - for { - select { - case data := <-hasBeenCalled: - t.Log("receiving message") - beenCalled = data - if !beenCalled { - t.Fail() - } - t.Log("received message") - eh.Stop() - return - default: - t.Logf("Waiting for callback %d", counter) - time.Sleep(time.Millisecond) - if counter == 2 { - sendDataToSocket("./backive.socket", message) - t.Log("sent message") - } - if counter < 10 { - counter++ - } else { - t.Log("Stopping with Fail") - eh.Stop() - t.Fail() - break - } - } - } -} -func sendDataToSocket(socket string, message map[string]interface{}) { - c, err := net.Dial("unix", socket) - if err != nil { - log.Fatalln("Could not instantiate unix socket. Aborting") + mockAccept = func(eh *EventHandler) (net.Conn, error) { + t.Log("Mocked Accept() has been called.") + mycon := ConnStub{} + return mycon, nil } - jsonstr, err := json.Marshal(message) - if err != nil { - log.Fatalln("Could not convert to json. Aborting") + eh.process() + //beenCalled := <-hasBeenCalled + if !hasBeenCalled { + t.Log("Got false, need true.") + t.Fail() } - c.Write(jsonstr) - defer c.Close() } diff --git a/utils.go b/utils.go index 8bea892..cd626e9 100644 --- a/utils.go +++ b/utils.go @@ -1,20 +1,21 @@ package backive import ( - "log" "os" ) var mockOsStat = os.Stat var mockOsMkdirAll = os.MkdirAll +var mockOsIsNotExist = os.IsNotExist // CreateDirectoryIfNotExists Checks for a directory string and creates the directory if it does not exist, must be a absolute path. -func CreateDirectoryIfNotExists(dir string) { +func CreateDirectoryIfNotExists(dir string) error { if _, err := mockOsStat(dir); err == nil { //ignore - } else if os.IsNotExist(err) { - mockOsMkdirAll(dir, 0755) + } else if mockOsIsNotExist(err) { + return mockOsMkdirAll(dir, 0755) } else { - log.Fatal(err) + return err } + return nil } diff --git a/utils_test.go b/utils_test.go new file mode 100644 index 0000000..94d2371 --- /dev/null +++ b/utils_test.go @@ -0,0 +1,32 @@ +package backive + +import ( + "fmt" + "io/fs" + "os" + "testing" +) + +var creatingDir = false + +func TestCreateDirectoryIfNotExists(t *testing.T) { + mockOsMkdirAll = func(dir string, mode os.FileMode) error { + t.Log("Creating directories") + creatingDir = true + return nil + } + mockOsStat = os.Stat + CreateDirectoryIfNotExists("/somewhere/which.does/not/exist") + if !creatingDir { + t.Log("Should have called MkdirAll") + t.Fail() + } + mockOsStat = func(dir string) (fs.FileInfo, error) { + return nil, fmt.Errorf("Just some error for testing") + } + err := CreateDirectoryIfNotExists("asdfasdfasdf") + if err == nil { + t.Log("Should have an error here") + t.Fail() + } +}