Skip to content
Permalink
Browse files

http server refactor - tests

  • Loading branch information...
hunterlong committed Mar 5, 2019
1 parent 22dc195 commit 1402e3b17b90aae9eb457fed9784001bbc24da8b
@@ -33,13 +33,14 @@ var (

func init() {
dir = utils.Directory
core.SampleHits = 480
}

func TestStartServerCommand(t *testing.T) {
os.Setenv("DB_CONN", "sqlite")
cmd := helperCommand(nil, "")
var got = make(chan string)
commandAndSleep(cmd, time.Duration(360*time.Second), got)
commandAndSleep(cmd, time.Duration(60*time.Second), got)
os.Unsetenv("DB_CONN")
gg, _ := <-got
assert.Contains(t, gg, "DB_CONN environment variable was found")
@@ -33,6 +33,7 @@ func init() {
utils.InitLogs()
source.Assets()
skipNewDb = false
SampleHits = 480
}

func TestNewCore(t *testing.T) {
@@ -101,20 +101,20 @@ func (n *ExampleNotifier) Select() *Notification {
// OnSave is a required basic event for the Notifier interface
func (n *ExampleNotifier) OnSave() error {
msg := fmt.Sprintf("received on save trigger")
n.AddQueue(0, msg)
n.AddQueue("onsave", msg)
return errors.New("onsave triggered")
}

// OnSuccess is a required basic event for the Notifier interface
func (n *ExampleNotifier) OnSuccess(s *types.Service) {
msg := fmt.Sprintf("received a count trigger for service: %v\n", s.Name)
n.AddQueue(s.Id, msg)
n.AddQueue(fmt.Sprintf("service_%v", s.Id), msg)
}

// OnFailure is a required basic event for the Notifier interface
func (n *ExampleNotifier) OnFailure(s *types.Service, f *types.Failure) {
msg := fmt.Sprintf("received a failure trigger for service: %v\n", s.Name)
n.AddQueue(s.Id, msg)
n.AddQueue(fmt.Sprintf("service_%v", s.Id), msg)
}

// OnTest is a option testing event for the Notifier interface
@@ -126,61 +126,61 @@ func (n *ExampleNotifier) OnTest() error {
// OnNewService is a option event for new services
func (n *ExampleNotifier) OnNewService(s *types.Service) {
msg := fmt.Sprintf("received a new service trigger for service: %v\n", s.Name)
n.AddQueue(s.Id, msg)
n.AddQueue(fmt.Sprintf("service_%v", s.Id), msg)
}

// OnUpdatedService is a option event for updated services
func (n *ExampleNotifier) OnUpdatedService(s *types.Service) {
msg := fmt.Sprintf("received a update service trigger for service: %v\n", s.Name)
n.AddQueue(s.Id, msg)
n.AddQueue(fmt.Sprintf("service_%v", s.Id), msg)
}

// OnDeletedService is a option event for deleted services
func (n *ExampleNotifier) OnDeletedService(s *types.Service) {
msg := fmt.Sprintf("received a delete service trigger for service: %v\n", s.Name)
n.AddQueue(s.Id, msg)
n.AddQueue(fmt.Sprintf("service_%v", s.Id), msg)
}

// OnNewUser is a option event for new users
func (n *ExampleNotifier) OnNewUser(s *types.User) {
msg := fmt.Sprintf("received a new user trigger for user: %v\n", s.Username)
n.AddQueue(s.Id, msg)
n.AddQueue(fmt.Sprintf("service_%v", s.Id), msg)
}

// OnUpdatedUser is a option event for updated users
func (n *ExampleNotifier) OnUpdatedUser(s *types.User) {
msg := fmt.Sprintf("received a updated user trigger for user: %v\n", s.Username)
n.AddQueue(s.Id, msg)
n.AddQueue(fmt.Sprintf("service_%v", s.Id), msg)
}

// OnDeletedUser is a option event for deleted users
func (n *ExampleNotifier) OnDeletedUser(s *types.User) {
msg := fmt.Sprintf("received a deleted user trigger for user: %v\n", s.Username)
n.AddQueue(s.Id, msg)
n.AddQueue(fmt.Sprintf("service_%v", s.Id), msg)
}

// OnUpdatedCore is a option event when the settings are updated
func (n *ExampleNotifier) OnUpdatedCore(s *types.Core) {
msg := fmt.Sprintf("received a updated core trigger for core: %v\n", s.Name)
n.AddQueue(0, msg)
n.AddQueue("core", msg)
}

// OnStart is triggered when statup has been started
func (n *ExampleNotifier) OnStart(s *types.Core) {
msg := fmt.Sprintf("received a trigger on Statping boot: %v\n", s.Name)
n.AddQueue(0, msg)
n.AddQueue(fmt.Sprintf("core"), msg)
}

// OnNewNotifier is triggered when a new notifier has initialized
func (n *ExampleNotifier) OnNewNotifier(s *Notification) {
msg := fmt.Sprintf("received a new notifier trigger for notifier: %v\n", s.Method)
n.AddQueue(s.Id, msg)
n.AddQueue(fmt.Sprintf("notifier_%v", s.Id), msg)
}

// OnUpdatedNotifier is triggered when a notifier has been updated
func (n *ExampleNotifier) OnUpdatedNotifier(s *Notification) {
msg := fmt.Sprintf("received a update notifier trigger for notifier: %v\n", s.Method)
n.AddQueue(s.Id, msg)
n.AddQueue(fmt.Sprintf("notifier_%v", s.Id), msg)
}

// Create a new notifier that includes a form for the end user to insert their own values
@@ -224,21 +224,21 @@ func ExampleAddNotifier() {
// OnSuccess will be triggered everytime a service is online
func ExampleNotification_OnSuccess() {
msg := fmt.Sprintf("this is a successful message as a string passing into AddQueue function")
example.AddQueue(0, msg)
example.AddQueue("example", msg)
fmt.Println(len(example.Queue))
// Output: 1
}

// Add a new message into the queue OnSuccess
func ExampleOnSuccess() {
msg := fmt.Sprintf("received a count trigger for service: %v\n", service.Name)
example.AddQueue(0, msg)
example.AddQueue("example", msg)
}

// Add a new message into the queue OnFailure
func ExampleOnFailure() {
msg := fmt.Sprintf("received a failing service: %v\n", service.Name)
example.AddQueue(0, msg)
example.AddQueue("example", msg)
}

// OnTest allows your notifier to be testable
@@ -258,7 +258,7 @@ func ExampleNotification_CanTest() {
// Add any type of interface to the AddQueue function to be ran in the queue
func ExampleNotification_AddQueue() {
msg := fmt.Sprintf("this is a failing message as a string passing into AddQueue function")
example.AddQueue(0, msg)
example.AddQueue("example", msg)
queue := example.Queue
fmt.Printf("Example has %v items in the queue", len(queue))
// Output: Example has 2 items in the queue
@@ -100,7 +100,7 @@ func TestSelectNotification(t *testing.T) {
func TestAddQueue(t *testing.T) {
msg := "this is a test in the queue!"
example.AddQueue(fmt.Sprintf("service_%v", 0), msg)
assert.Equal(t, fmt.Sprintf("service_%v", 1), len(example.Queue))
assert.Equal(t, 1, len(example.Queue))
example.AddQueue(fmt.Sprintf("service_%v", 0), msg)
assert.Equal(t, 2, len(example.Queue))
example.AddQueue(fmt.Sprintf("service_%v", 0), msg)
@@ -24,7 +24,7 @@ import (

var (
sampleStart = time.Now().Add((-24 * 7) * time.Hour).UTC()
sampleHits = 9900.
SampleHits = 9900.
)

// InsertSampleData will create the example/dummy services for a brand new Statping installation
@@ -173,12 +173,12 @@ func InsertSampleHits() error {
service := SelectService(i)
seed := time.Now().UnixNano()

utils.Log(1, fmt.Sprintf("Adding %v sample hit records to service %v", sampleHits, service.Name))
utils.Log(1, fmt.Sprintf("Adding %v sample hit records to service %v", SampleHits, service.Name))
createdAt := sampleStart

p := utils.NewPerlin(2., 2., 10, seed)

for hi := 0.; hi <= float64(sampleHits); hi++ {
for hi := 0.; hi <= float64(SampleHits); hi++ {

latency := p.Noise1D(hi / 500)
createdAt = createdAt.Add(60 * time.Second)
@@ -440,17 +440,9 @@ func insertHitRecords(since time.Time, amount int64) {
service := SelectService(i)
utils.Log(1, fmt.Sprintf("Adding %v hit records to service %v", amount, service.Name))
createdAt := since

p := utils.NewPerlin(2, 2, 5, time.Now().UnixNano())

utils.Log(1, fmt.Sprint(p))

for hi := int64(1); hi <= amount; hi++ {

latency := p.Noise1D(float64(hi / 10))

fmt.Printf("%0.0f\t%0.4f\n", hi, latency)

createdAt = createdAt.Add(1 * time.Minute)
hit := &types.Hit{
Service: service.Id,
@@ -35,20 +35,12 @@ type apiResponse struct {
}

func apiIndexHandler(w http.ResponseWriter, r *http.Request) {
if !IsFullAuthenticated(r) {
sendUnauthorizedJson(w, r)
return
}
coreClone := *core.CoreApp
coreClone.Started = utils.Timezoner(core.CoreApp.Started, core.CoreApp.Timezone)
returnJson(coreClone, w, r)
}

func apiRenewHandler(w http.ResponseWriter, r *http.Request) {
if !IsFullAuthenticated(r) {
sendUnauthorizedJson(w, r)
return
}
var err error
core.CoreApp.ApiKey = utils.NewSHA1Hash(40)
core.CoreApp.ApiSecret = utils.NewSHA1Hash(40)
@@ -61,10 +53,6 @@ func apiRenewHandler(w http.ResponseWriter, r *http.Request) {
}

func apiClearCacheHandler(w http.ResponseWriter, r *http.Request) {
if !IsFullAuthenticated(r) {
sendUnauthorizedJson(w, r)
return
}
CacheStorage = NewStorage()
http.Redirect(w, r, "/", http.StatusSeeOther)
}
@@ -102,6 +102,12 @@ func TestMainApiRoutes(t *testing.T) {
URL: "/api/clear_cache",
Method: "POST",
ExpectedStatus: 303,
},
{
Name: "404 Error Page",
URL: "/api/missing_404_page",
Method: "GET",
ExpectedStatus: 404,
}}

for _, v := range tests {
@@ -1,9 +1,6 @@
package handlers

import (
"github.com/hunterlong/statping/core"
"net/http"
"net/http/httptest"
"sync"
"time"
)
@@ -74,31 +71,3 @@ func (s Storage) Set(key string, content []byte, duration time.Duration) {
Expiration: time.Now().Add(duration).UnixNano(),
}
}

func cached(duration, contentType string, handler func(w http.ResponseWriter, r *http.Request)) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
content := CacheStorage.Get(r.RequestURI)
w.Header().Set("Content-Type", contentType)
if core.Configs == nil {
handler(w, r)
return
}
if content != nil {
w.Write(content)
} else {
c := httptest.NewRecorder()
handler(c, r)
content := c.Body.Bytes()
result := c.Result()
if result.StatusCode != 200 {
w.WriteHeader(result.StatusCode)
w.Write(content)
return
}
w.Write(content)
if d, err := time.ParseDuration(duration); err == nil {
go CacheStorage.Set(r.RequestURI, content, d)
}
}
})
}
@@ -28,10 +28,6 @@ import (
)

func apiAllCheckinsHandler(w http.ResponseWriter, r *http.Request) {
if !IsFullAuthenticated(r) {
sendUnauthorizedJson(w, r)
return
}
checkins := core.AllCheckins()
for _, c := range checkins {
c.Hits = c.AllHits()
@@ -41,10 +37,6 @@ func apiAllCheckinsHandler(w http.ResponseWriter, r *http.Request) {
}

func apiCheckinHandler(w http.ResponseWriter, r *http.Request) {
if !IsFullAuthenticated(r) {
sendUnauthorizedJson(w, r)
return
}
vars := mux.Vars(r)
checkin := core.SelectCheckin(vars["api"])
if checkin == nil {
@@ -57,10 +49,6 @@ func apiCheckinHandler(w http.ResponseWriter, r *http.Request) {
}

func checkinCreateHandler(w http.ResponseWriter, r *http.Request) {
if !IsFullAuthenticated(r) {
http.Redirect(w, r, "/", http.StatusSeeOther)
return
}
var checkin *core.Checkin
decoder := json.NewDecoder(r.Body)
err := decoder.Decode(&checkin)
@@ -108,15 +96,10 @@ func checkinHitHandler(w http.ResponseWriter, r *http.Request) {
}
checkin.Failing = false
checkin.LastHit = utils.Timezoner(time.Now().UTC(), core.CoreApp.Timezone)
w.Header().Set("Content-Type", "application/json")
sendJsonAction(checkinHit, "update", w, r)
}

func checkinDeleteHandler(w http.ResponseWriter, r *http.Request) {
if !IsFullAuthenticated(r) {
http.Redirect(w, r, "/", http.StatusSeeOther)
return
}
vars := mux.Vars(r)
checkin := core.SelectCheckin(vars["api"])
if checkin == nil {
@@ -41,9 +41,9 @@ func loginHandler(w http.ResponseWriter, r *http.Request) {
resetCookies()
}
session, _ := sessionStore.Get(r, cookieKey)
r.ParseForm()
username := r.PostForm.Get("username")
password := r.PostForm.Get("password")
form := parseForm(r)
username := form.Get("username")
password := form.Get("password")
user, auth := core.AuthUser(username, password)
if auth {
session.Values["authenticated"] = true
@@ -77,10 +77,6 @@ func helpHandler(w http.ResponseWriter, r *http.Request) {
}

func logsHandler(w http.ResponseWriter, r *http.Request) {
if !IsFullAuthenticated(r) {
http.Redirect(w, r, "/", http.StatusSeeOther)
return
}
utils.LockLines.Lock()
logs := make([]string, 0)
length := len(utils.LastLines)
@@ -93,10 +89,6 @@ func logsHandler(w http.ResponseWriter, r *http.Request) {
}

func logsLineHandler(w http.ResponseWriter, r *http.Request) {
if !IsReadAuthenticated(r) {
w.WriteHeader(http.StatusInternalServerError)
return
}
if lastLine := utils.GetLastLine(); lastLine != nil {
w.Header().Set("Content-Type", "text/plain")
w.WriteHeader(http.StatusOK)
@@ -105,11 +97,6 @@ func logsLineHandler(w http.ResponseWriter, r *http.Request) {
}

func exportHandler(w http.ResponseWriter, r *http.Request) {
if !IsFullAuthenticated(r) {
w.WriteHeader(http.StatusInternalServerError)
return
}

var notifiers []*notifier.Notification
for _, v := range core.CoreApp.Notifications {
notifier := v.(notifier.Notifier)
Oops, something went wrong.

0 comments on commit 1402e3b

Please sign in to comment.
You can’t perform that action at this time.