notifier testing - JS updates

pull/78/head
hunterlong 2018-09-26 17:41:51 -07:00
parent 0f208c979f
commit 2385cf88e1
9 changed files with 71 additions and 20 deletions

View File

@ -103,13 +103,6 @@ func (n *Example) OnSave() error {
return errors.New("onsave triggered") return errors.New("onsave triggered")
} }
// REQUIRED
func (n *Example) Test() error {
msg := fmt.Sprintf("received a test trigger\n")
n.AddQueue(msg)
return errors.New("test triggered")
}
// REQUIRED - BASIC EVENT // REQUIRED - BASIC EVENT
func (n *Example) OnSuccess(s *types.Service) { func (n *Example) OnSuccess(s *types.Service) {
msg := fmt.Sprintf("received a count trigger for service: %v\n", s.Name) msg := fmt.Sprintf("received a count trigger for service: %v\n", s.Name)
@ -123,9 +116,9 @@ func (n *Example) OnFailure(s *types.Service, f *types.Failure) {
} }
// OPTIONAL Test function before user saves // OPTIONAL Test function before user saves
func (n *Example) OnTest(s Notification) (bool, error) { func (n *Example) OnTest() error {
fmt.Printf("received a test trigger with form data: %v\n", s.Host) fmt.Printf("received a test trigger with form data: %v\n", n.Host)
return true, nil return nil
} }
// OPTIONAL // OPTIONAL

View File

@ -57,8 +57,8 @@ type Notification struct {
Delay time.Duration `gorm:"-" json:"-"` Delay time.Duration `gorm:"-" json:"-"`
Queue []interface{} `gorm:"-" json:"-"` Queue []interface{} `gorm:"-" json:"-"`
Running chan bool `gorm:"-" json:"-"` Running chan bool `gorm:"-" json:"-"`
CanTest bool `gorm:"-" json:"-"`
Online bool `gorm:"-" json:"-"` Online bool `gorm:"-" json:"-"`
testable bool
} }
type NotificationForm struct { type NotificationForm struct {
@ -80,6 +80,10 @@ func (n *Notification) AddQueue(msg interface{}) {
n.Queue = append(n.Queue, msg) n.Queue = append(n.Queue, msg)
} }
func (n *Notification) CanTest() bool {
return n.testable
}
// db will return the notifier database column/record // db will return the notifier database column/record
func modelDb(n *Notification) *gorm.DB { func modelDb(n *Notification) *gorm.DB {
return db.Model(&Notification{}).Where("method = ?", n.Method).Find(n) return db.Model(&Notification{}).Where("method = ?", n.Method).Find(n)
@ -233,6 +237,7 @@ func Init(n Notifier) (*Notification, error) {
var notify *Notification var notify *Notification
if err == nil { if err == nil {
notify, _ = SelectNotification(n) notify, _ = SelectNotification(n)
notify.testable = isType(n, new(Tester))
notify.Form = n.Select().Form notify.Form = n.Select().Form
} }
return notify, err return notify, err

View File

@ -217,13 +217,15 @@ func testNotificationHandler(w http.ResponseWriter, r *http.Request) {
apiSecret := form.Get("api_secret") apiSecret := form.Get("api_secret")
limits := int(utils.StringInt(form.Get("limits"))) limits := int(utils.StringInt(form.Get("limits")))
notifer, notif, err := notifier.SelectNotifier(method) fakeNotifer, notif, err := notifier.SelectNotifier(method)
if err != nil { if err != nil {
utils.Log(3, fmt.Sprintf("issue saving notifier %v: %v", method, err)) utils.Log(3, fmt.Sprintf("issue saving notifier %v: %v", method, err))
executeResponse(w, r, "settings.html", core.CoreApp, "/settings") executeResponse(w, r, "settings.html", core.CoreApp, "/settings")
return return
} }
notifer := *fakeNotifer
if host != "" { if host != "" {
notifer.Host = host notifer.Host = host
} }
@ -254,7 +256,6 @@ func testNotificationHandler(w http.ResponseWriter, r *http.Request) {
notifer.Enabled = enabled == "on" notifer.Enabled = enabled == "on"
err = notif.(notifier.Tester).OnTest() err = notif.(notifier.Tester).OnTest()
if err == nil { if err == nil {
w.Write([]byte("ok")) w.Write([]byte("ok"))
} else { } else {

View File

@ -17,9 +17,12 @@ package notifiers
import ( import (
"bytes" "bytes"
"encoding/json"
"errors"
"fmt" "fmt"
"github.com/hunterlong/statup/core/notifier" "github.com/hunterlong/statup/core/notifier"
"github.com/hunterlong/statup/types" "github.com/hunterlong/statup/types"
"io/ioutil"
"net/http" "net/http"
"time" "time"
) )
@ -91,3 +94,36 @@ func (u *Discord) OnSave() error {
u.AddQueue(msg) u.AddQueue(msg)
return nil return nil
} }
// OnSave triggers when this notifier has been saved
func (u *Discord) OnTest() error {
outError := errors.New("Incorrect Discord URL, please confirm URL is correct")
message := `{"content": "Testing the Discord notifier"}`
req, _ := http.NewRequest("POST", discorder.Host, bytes.NewBuffer([]byte(message)))
req.Header.Set("Content-Type", "application/json")
client := &http.Client{}
resp, err := client.Do(req)
if err != nil {
return err
}
defer resp.Body.Close()
contents, _ := ioutil.ReadAll(resp.Body)
if string(contents) == "" {
return nil
}
var d discordTestJson
err = json.Unmarshal(contents, &d)
if err != nil {
return outError
}
if d.Code == 0 {
return outError
}
fmt.Println("discord: ", string(contents))
return nil
}
type discordTestJson struct {
Code int `json:"code"`
Message string `json:"message"`
}

View File

@ -54,6 +54,10 @@ func TestDiscordNotifier(t *testing.T) {
notifier.Load() notifier.Load()
}) })
t.Run("Discord Notifier Tester", func(t *testing.T) {
assert.True(t, discorder.CanTest())
})
t.Run("Discord Within Limits", func(t *testing.T) { t.Run("Discord Within Limits", func(t *testing.T) {
ok, err := discorder.WithinLimits() ok, err := discorder.WithinLimits()
assert.Nil(t, err) assert.Nil(t, err)

View File

@ -46,7 +46,6 @@ var slacker = &Slack{&notifier.Notification{
AuthorUrl: "https://github.com/hunterlong", AuthorUrl: "https://github.com/hunterlong",
Delay: time.Duration(10 * time.Second), Delay: time.Duration(10 * time.Second),
Host: "https://webhooksurl.slack.com/***", Host: "https://webhooksurl.slack.com/***",
CanTest: true,
Form: []notifier.NotificationForm{{ Form: []notifier.NotificationForm{{
Type: "text", Type: "text",
Title: "Incoming Webhook Url", Title: "Incoming Webhook Url",
@ -107,7 +106,7 @@ func (u *Slack) OnTest() error {
defer res.Body.Close() defer res.Body.Close()
contents, _ := ioutil.ReadAll(res.Body) contents, _ := ioutil.ReadAll(res.Body)
if string(contents) != "ok" { if string(contents) != "ok" {
return errors.New("incorrect url") return errors.New("The Slack response was incorrect, check the URL")
} }
return err return err
} }

View File

@ -61,6 +61,10 @@ func TestSlackNotifier(t *testing.T) {
notifier.Load() notifier.Load()
}) })
t.Run("Slack Notifier Tester", func(t *testing.T) {
assert.True(t, slacker.CanTest())
})
t.Run("Slack parse message", func(t *testing.T) { t.Run("Slack parse message", func(t *testing.T) {
err := parseSlackMessage(SLACK_TEXT, "this is a test!") err := parseSlackMessage(SLACK_TEXT, "this is a test!")
assert.Nil(t, err) assert.Nil(t, err)

View File

@ -24,20 +24,31 @@ $('.service_li').on('click', function() {
}); });
$('.test_notifier').on('click', function(e) { $('.test_notifier').on('click', function(e) {
var btn = $(this);
var form = $(this).parents('form:first'); var form = $(this).parents('form:first');
var values = form.serialize(); var values = form.serialize();
var notifier = form.find('input[name=notifier]').val(); var notifier = form.find('input[name=notifier]').val();
var success = $('#'+notifier+'-success');
var error = $('#'+notifier+'-error');
btn.prop("disabled", true);
$.ajax({ $.ajax({
url: form.attr("action")+"/test", url: form.attr("action")+"/test",
type: 'POST', type: 'POST',
data: values, data: values,
success: function(data) { success: function(data) {
if (data === 'ok') { if (data === 'ok') {
$('#'+notifier+'-success').removeClass('d-none'); success.removeClass('d-none');
setTimeout(function() {
success.addClass('d-none');
}, 5000)
} else { } else {
$('#'+notifier+'-error').removeClass('d-none'); error.removeClass('d-none');
$('#'+notifier+'-error').html(data); error.html(data);
setTimeout(function() {
error.addClass('d-none');
}, 8000)
} }
btn.prop("disabled", false);
} }
}); });
e.preventDefault(); e.preventDefault();

View File

@ -233,8 +233,6 @@
The {{$n.Method}} notifier is working correctly! The {{$n.Method}} notifier is working correctly!
</div> </div>
</div> </div>
</div>
{{end}} {{end}}
</div> </div>