git-webhook-ci/internal/watcher/watcher_test.go

137 lines
2.6 KiB
Go

package watcher
import (
"context"
"errors"
"testing"
"time"
"gitea.urkob.com/urko/git-webhook-ci/cfg"
pkgwatcher "gitea.urkob.com/urko/git-webhook-ci/pkg/watcher"
"github.com/fsnotify/fsnotify"
"github.com/stretchr/testify/require"
)
var (
mockDeploy pkgwatcher.DeployFunc
mockErrorDeploy pkgwatcher.DeployFunc
errIntentional = errors.New("intentional error")
binaryPath = ""
scriptPath = ""
executionMaxTimeout = time.Second * 2
config *cfg.Config
events = []fsnotify.Event{
{
Name: "test event",
Op: fsnotify.Create,
},
{
Name: "Write",
Op: fsnotify.Write,
},
}
)
func init() {
mockDeploy = func(binaryPath, scriptPath string) error {
return nil
}
mockErrorDeploy = func(binaryPath, scriptPath string) error {
return errIntentional
}
config = cfg.NewConfig(false)
}
func sendTestEvents(w *watcher) {
for _, event := range events {
w.fswatcher.Events <- event
}
}
func getNewWatcher() *watcher {
return NewWatcher(mockDeploy)
}
func getNewWatcherWithError() *watcher {
return NewWatcher(mockErrorDeploy)
}
func Test_NewWatcher(t *testing.T) {
w := getNewWatcher()
require.NotNil(t, w)
}
func Test_Close(t *testing.T) {
w := getNewWatcher()
err := w.Close()
require.NoError(t, err)
}
func Test_Monitor(t *testing.T) {
w := getNewWatcher()
err := w.Monitor(config.TestFileToWatchPath)
require.NoError(t, err)
}
func Test_ListenSuccess(t *testing.T) {
w := getNewWatcher()
ctx, errors := listenWithSendEvents(w)
for {
select {
case <-ctx.Done():
return
case err := <-errors:
require.NoError(t, err)
return
}
}
}
func Test_ListenError(t *testing.T) {
w := getNewWatcherWithError()
ctx, errors := listenWithSendEvents(w)
for {
select {
case <-ctx.Done():
return
case err := <-errors:
require.Error(t, err)
require.EqualError(t, err, errIntentional.Error())
return
}
}
}
func Test_ListenErrorChanClose(t *testing.T) {
w := getNewWatcher()
ctx, errors := listenWithSendEvents(w)
close(w.fswatcher.Events)
for {
select {
case <-ctx.Done():
return
case err := <-errors:
require.Error(t, err)
require.EqualError(t, err, errEventsClosedChan.Error())
return
}
}
}
func listenWithSendEvents(w *watcher) (context.Context, chan error) {
ctx, cancel := context.WithTimeout(context.Background(), executionMaxTimeout)
errors := make(chan error)
w.Listen(binaryPath, scriptPath, errors)
go func(cancel context.CancelFunc) {
time.Sleep(executionMaxTimeout)
cancel()
}(cancel)
sendTestEvents(w)
return ctx, errors
}