Add some more tests for coverage

This commit is contained in:
Marcel Otte 2022-01-31 22:18:21 +01:00
parent 87109b6bf0
commit e102e976ab
5 changed files with 133 additions and 90 deletions

View File

@ -92,6 +92,10 @@ func TestCanRun(t *testing.T) {
t.Log("Frequency zero can be executed anytime.") t.Log("Frequency zero can be executed anytime.")
t.Fail() t.Fail()
} }
if !bkpFrequencyZero.ShouldRun() {
t.Log("Frequency zero can be executed anytime, should run does not work.")
t.Fail()
}
runs.RegisterRun(&bkpFrequencySeven) runs.RegisterRun(&bkpFrequencySeven)
err = bkpFrequencySeven.CanRun() err = bkpFrequencySeven.CanRun()

View File

@ -9,37 +9,29 @@ import (
"path" "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. // EventHandler holds the necessary elements to get an eventhandler setup and working.
type EventHandler struct { type EventHandler struct {
ls net.Listener ls net.Listener
//done <-chan struct{}
callbacks []func(map[string]string) callbacks []func(map[string]string)
stop chan bool
} }
// Init initializes the unix socket. // Init initializes the unix socket.
func (eh *EventHandler) Init(socketPath string) { func (eh *EventHandler) Init(socketPath string) error {
eh.stop = make(chan bool)
log.Println("Initializing EventHandler...") log.Println("Initializing EventHandler...")
var err error var err error
dir, _ := path.Split(socketPath) dir, _ := path.Split(socketPath)
CreateDirectoryIfNotExists(dir) CreateDirectoryIfNotExists(dir)
eh.ls, err = net.Listen("unix", socketPath) eh.ls, err = net.Listen("unix", socketPath)
if err != nil { if err != nil {
panic(err) return err
} }
eh.callbacks = make([]func(map[string]string), 3) eh.callbacks = make([]func(map[string]string), 3)
} return nil
// 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")
} }
// Listen starts the event loop. // Listen starts the event loop.
@ -47,12 +39,7 @@ func (eh *EventHandler) Listen() {
log.Println("Running eventloop") log.Println("Running eventloop")
func() { func() {
for { for {
select { eh.process()
case <-eh.stop:
return
default:
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. // process processes each and every unix socket event, Unmarshals the json data and calls the list of callbacks.
func (eh *EventHandler) process() { func (eh *EventHandler) process() {
client, err := eh.ls.Accept() client, err := mockAccept(eh)
log.Println("Accepted client") log.Println("Accepted client")
if err != nil { if err != nil {
select { log.Println(err)
case <-eh.stop: return
return
default:
log.Fatal(err)
}
} }
defer client.Close() defer client.Close()
data := make([]byte, 2048) data := make([]byte, 2048)
for { for {
buf := make([]byte, 512) buf := make([]byte, 512)
nr, err := client.Read(buf) nr, err := client.Read(buf)
log.Printf("Read %d bytes...", nr)
if err != nil && err != io.EOF { if err != nil && err != io.EOF {
log.Fatal(err) log.Println(err)
return
} }
data = append(data, buf[0:nr]...) data = append(data, buf[0:nr]...)
if err == io.EOF { if err == io.EOF {
@ -88,12 +73,14 @@ func (eh *EventHandler) process() {
} }
} }
sdata := string(bytes.Trim(data, "\x00")) sdata := string(bytes.Trim(data, "\x00"))
//log.Println(sdata)
var message map[string]interface{} var message map[string]interface{}
log.Printf("Reading JSON: %s", sdata)
errjson := json.Unmarshal([]byte(sdata), &message) errjson := json.Unmarshal([]byte(sdata), &message)
if errjson != nil { if errjson != nil {
log.Fatal(errjson) log.Println(errjson)
return
} }
log.Println("Calling callbacks")
var env = map[string]string{} var env = map[string]string{}
if message["request"] == "udev" { if message["request"] == "udev" {
for k, v := range message["data"].(map[string]interface{}) { for k, v := range message["data"].(map[string]interface{}) {
@ -102,6 +89,7 @@ func (eh *EventHandler) process() {
} }
for _, v := range eh.callbacks { for _, v := range eh.callbacks {
if v != nil { if v != nil {
log.Println("Calling callback")
v(env) v(env)
} }
} }

View File

@ -2,6 +2,8 @@ package backive
import ( import (
"encoding/json" "encoding/json"
"fmt"
"io"
"log" "log"
"net" "net"
"os" "os"
@ -9,73 +11,89 @@ import (
"time" "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) { func TestEventhandler(t *testing.T) {
t.Skip("Do not get it to work...")
eh := new(EventHandler) eh := new(EventHandler)
eh.Init("./backive.socket") err := eh.Init("./backive.socket")
if err != nil {
t.Fail()
}
defer func() { defer func() {
eh.Stop()
err := os.Remove("./backive.socket") err := os.Remove("./backive.socket")
if err != nil { if err != nil {
t.Log(err) t.Log(err)
} }
}() }()
t.Log("Initialized test") t.Log("Initialized test")
go eh.Listen() //var hasBeenCalled = make(chan bool)
t.Log("eh is listening")
var hasBeenCalled = make(chan bool)
eh.RegisterCallback( eh.RegisterCallback(
func(m map[string]string) { func(m map[string]string) {
hasBeenCalled <- true t.Log("Callback got called")
hasBeenCalled = true
}, },
) )
t.Log("registered callback") 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{}) { mockAccept = func(eh *EventHandler) (net.Conn, error) {
c, err := net.Dial("unix", socket) t.Log("Mocked Accept() has been called.")
if err != nil { mycon := ConnStub{}
log.Fatalln("Could not instantiate unix socket. Aborting") return mycon, nil
} }
jsonstr, err := json.Marshal(message) eh.process()
if err != nil { //beenCalled := <-hasBeenCalled
log.Fatalln("Could not convert to json. Aborting") if !hasBeenCalled {
t.Log("Got false, need true.")
t.Fail()
} }
c.Write(jsonstr)
defer c.Close()
} }

View File

@ -1,20 +1,21 @@
package backive package backive
import ( import (
"log"
"os" "os"
) )
var mockOsStat = os.Stat var mockOsStat = os.Stat
var mockOsMkdirAll = os.MkdirAll 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. // 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 { if _, err := mockOsStat(dir); err == nil {
//ignore //ignore
} else if os.IsNotExist(err) { } else if mockOsIsNotExist(err) {
mockOsMkdirAll(dir, 0755) return mockOsMkdirAll(dir, 0755)
} else { } else {
log.Fatal(err) return err
} }
return nil
} }

32
utils_test.go Normal file
View File

@ -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()
}
}