From 349f50af9c9daf99e1ca4c478773629c4cc0f2c1 Mon Sep 17 00:00:00 2001 From: Hunter Long Date: Wed, 4 Mar 2020 21:38:56 -0800 Subject: [PATCH] vue --- cmd/cli.go | 4 +- database/database_test.go | 44 ------ database/hits.go | 1 - database/incident.go | 1 - database/integration.go | 1 - database/message.go | 1 - database/setup.go | 15 -- database/user.go | 1 - frontend/public/base.gohtml | 2 +- .../src/components/Service/ServiceBlock.vue | 6 +- frontend/src/pages/Help.vue | 9 -- frontend/src/routes.js | 3 +- handlers/api_test.go | 4 +- handlers/messages_test.go | 2 +- handlers/users_test.go | 20 ++- .../testdata/bulk_import.csv | 0 notifiers/discord_test.go | 3 +- notifiers/notifiers_test.go | 5 - notifiers/slack_test.go | 1 - types/configs/configs_test.go | 23 ++- types/configs/connection.go | 15 +- types/configs/database.go | 14 -- types/core/core_test.go | 21 --- types/groups/groups_test.go | 29 ++++ types/messages/database.go | 6 +- types/notifications/audit.go | 16 -- types/notifications/example_test.go | 147 ------------------ types/notifications/notifications_test.go | 14 -- types/notifications/struct_test.go | 17 +- types/services/services_checkin_test.go | 49 +++--- types/services/services_test.go | 143 ++++++++--------- types/users/database.go | 18 ++- types/users/struct.go | 3 + types/users/users_test.go | 34 ++-- 34 files changed, 219 insertions(+), 453 deletions(-) delete mode 100644 database/database_test.go delete mode 100644 database/hits.go delete mode 100644 database/incident.go delete mode 100644 database/integration.go delete mode 100644 database/message.go delete mode 100644 database/setup.go delete mode 100644 database/user.go delete mode 100644 frontend/src/pages/Help.vue rename {core/integrations => integrators}/testdata/bulk_import.csv (100%) delete mode 100644 types/core/core_test.go create mode 100644 types/groups/groups_test.go delete mode 100644 types/notifications/audit.go delete mode 100644 types/notifications/notifications_test.go diff --git a/cmd/cli.go b/cmd/cli.go index 0fb3015a..afd8cc04 100644 --- a/cmd/cli.go +++ b/cmd/cli.go @@ -106,7 +106,7 @@ func catchCLI(args []string) error { if err != nil { return err } - if err = config.Connect(); err != nil { + if err = configs.ConnectConfigs(config); err != nil { return err } if data, err = handlers.ExportSettings(); err != nil { @@ -206,7 +206,7 @@ func runOnce() error { if err != nil { return errors.Wrap(err, "config.yml file not found") } - err = config.Connect() + err = configs.ConnectConfigs(config) if err != nil { return errors.Wrap(err, "issue connecting to database") } diff --git a/database/database_test.go b/database/database_test.go deleted file mode 100644 index 80083a55..00000000 --- a/database/database_test.go +++ /dev/null @@ -1,44 +0,0 @@ -package database - -import ( - "github.com/stretchr/testify/assert" - "testing" -) - -func TestDbConnection(t *testing.T) { - err := CoreApp.Connect(configs, false, dir) - assert.Nil(t, err) -} - -func TestDropDatabase(t *testing.T) { - if skipNewDb { - t.SkipNow() - } - err := CoreApp.DropDatabase() - assert.Nil(t, err) -} - -func TestSeedSchemaDatabase(t *testing.T) { - if skipNewDb { - t.SkipNow() - } - err := CoreApp.CreateDatabase() - assert.Nil(t, err) -} - -func TestMigrateDatabase(t *testing.T) { - t.SkipNow() - err := CoreApp.MigrateDatabase() - assert.Nil(t, err) -} - -func TestSeedDatabase(t *testing.T) { - err := InsertLargeSampleData() - assert.Nil(t, err) -} - -func TestReLoadDbConfig(t *testing.T) { - err := CoreApp.Connect(configs, false, dir) - assert.Nil(t, err) - assert.Equal(t, "sqlite", CoreApp.config.DbConn) -} diff --git a/database/hits.go b/database/hits.go deleted file mode 100644 index 636bab89..00000000 --- a/database/hits.go +++ /dev/null @@ -1 +0,0 @@ -package database diff --git a/database/incident.go b/database/incident.go deleted file mode 100644 index 636bab89..00000000 --- a/database/incident.go +++ /dev/null @@ -1 +0,0 @@ -package database diff --git a/database/integration.go b/database/integration.go deleted file mode 100644 index 636bab89..00000000 --- a/database/integration.go +++ /dev/null @@ -1 +0,0 @@ -package database diff --git a/database/message.go b/database/message.go deleted file mode 100644 index 636bab89..00000000 --- a/database/message.go +++ /dev/null @@ -1 +0,0 @@ -package database diff --git a/database/setup.go b/database/setup.go deleted file mode 100644 index e64cffd3..00000000 --- a/database/setup.go +++ /dev/null @@ -1,15 +0,0 @@ -package database - -//// SampleData runs all the sample data for a new Statping installation -//func SampleData() error { -// if err := InsertSampleData(); err != nil { -// return errors.Wrap(err, "sample data") -// } -// if err := InsertSampleHits(); err != nil { -// return errors.Wrap(err, "sample service hits") -// } -// if err := insertSampleCheckins(); err != nil { -// return errors.Wrap(err, "sample checkin examples") -// } -// return nil -//} diff --git a/database/user.go b/database/user.go deleted file mode 100644 index 636bab89..00000000 --- a/database/user.go +++ /dev/null @@ -1 +0,0 @@ -package database diff --git a/frontend/public/base.gohtml b/frontend/public/base.gohtml index 22eb22d9..e74795c4 100644 --- a/frontend/public/base.gohtml +++ b/frontend/public/base.gohtml @@ -5,7 +5,7 @@ {{CoreApp.Name}} - + {{if USE_CDN}} diff --git a/frontend/src/components/Service/ServiceBlock.vue b/frontend/src/components/Service/ServiceBlock.vue index b034fe36..faf1d278 100644 --- a/frontend/src/components/Service/ServiceBlock.vue +++ b/frontend/src/components/Service/ServiceBlock.vue @@ -56,7 +56,11 @@ export default { if (s.online) { return `Online, last checked ${this.ago(this.parseTime(s.last_success))}` } else { - return `Offline, last error: ${s.last_failure.issue} ${this.ago(this.parseTime(s.last_failure.created_at))}` + const last = s.last_failure + if (last) { + return `Offline, last error: ${last} ${this.ago(this.parseTime(last.created_at))}` + } + return `Offline` } }, visibleChart(isVisible, entry) { diff --git a/frontend/src/pages/Help.vue b/frontend/src/pages/Help.vue deleted file mode 100644 index c45547aa..00000000 --- a/frontend/src/pages/Help.vue +++ /dev/null @@ -1,9 +0,0 @@ - - - \ No newline at end of file diff --git a/frontend/src/routes.js b/frontend/src/routes.js index dacca2b4..df31db98 100644 --- a/frontend/src/routes.js +++ b/frontend/src/routes.js @@ -1,4 +1,3 @@ -import Help from './pages/Help'; import Index from "./pages/Index"; import Dashboard from "./pages/Dashboard"; import DashboardIndex from "./components/Dashboard/DashboardIndex"; @@ -59,7 +58,7 @@ const routes = [ component: Logs },{ path: 'help', - component: Help + component: Logs }] }, { diff --git a/handlers/api_test.go b/handlers/api_test.go index ed6c1ee8..0c739572 100644 --- a/handlers/api_test.go +++ b/handlers/api_test.go @@ -80,7 +80,7 @@ func TestSetupRoutes(t *testing.T) { Body: form.Encode(), ExpectedStatus: 200, HttpHeaders: []string{"Content-Type=application/x-www-form-urlencoded"}, - ExpectedFiles: []string{dir + "/config.yml", dir + "/handlers/" + "statping.db"}, + ExpectedFiles: []string{dir + "/config.yml", dir + "/" + "statping.db"}, FuncTest: func() error { if !core.App.Setup { return errors.New("core has not been setup") @@ -107,7 +107,7 @@ func TestMainApiRoutes(t *testing.T) { URL: "/api", Method: "GET", ExpectedStatus: 200, - ExpectedContains: []string{`"description":"This is an awesome test"`}, + ExpectedContains: []string{`"description":"This data is only used to testing"`}, FuncTest: func() error { if !core.App.Setup { return errors.New("database is not setup") diff --git a/handlers/messages_test.go b/handlers/messages_test.go index b68b48c2..748c27d8 100644 --- a/handlers/messages_test.go +++ b/handlers/messages_test.go @@ -29,7 +29,7 @@ func TestMessagesApiRoutes(t *testing.T) { "notify_before_scale": "hour" }`, ExpectedStatus: 200, - ExpectedContains: []string{`"status":"success"`, `"type":"message"`, `"method":"create"`, `"title": "API Message"`}, + ExpectedContains: []string{`"status":"success"`, `"type":"message"`, `"method":"create"`, `"title":"API Message"`}, }, { Name: "Statping View Message", diff --git a/handlers/users_test.go b/handlers/users_test.go index a9e82ed8..7b31ee7e 100644 --- a/handlers/users_test.go +++ b/handlers/users_test.go @@ -12,7 +12,7 @@ func TestApiUsersRoutes(t *testing.T) { URL: "/api/users", Method: "GET", ExpectedStatus: 200, - ResponseLen: 1, + ResponseLen: 4, }, { Name: "Statping Create User", URL: "/api/users", @@ -46,6 +46,24 @@ func TestApiUsersRoutes(t *testing.T) { URL: "/api/users/1", Method: "DELETE", ExpectedStatus: 200, + }, { + Name: "Statping Login User", + URL: "/api/login", + Method: "POST", + Body: `{ + "username": "admin", + "password": "admin" +}`, ExpectedContains: []string{`"token"`}, + ExpectedStatus: 200, + }, { + Name: "Statping Bad Login User", + URL: "/api/login", + Method: "POST", + Body: `{ + "username": "admin", + "password": "wrongpassword" +}`, ExpectedContains: []string{`"token"`}, + ExpectedStatus: 200, }} for _, v := range tests { diff --git a/core/integrations/testdata/bulk_import.csv b/integrators/testdata/bulk_import.csv similarity index 100% rename from core/integrations/testdata/bulk_import.csv rename to integrators/testdata/bulk_import.csv diff --git a/notifiers/discord_test.go b/notifiers/discord_test.go index ecd1ac23..839e2359 100644 --- a/notifiers/discord_test.go +++ b/notifiers/discord_test.go @@ -16,6 +16,7 @@ package notifiers import ( + "github.com/hunterlong/statping/types/notifications" "github.com/stretchr/testify/assert" "os" "testing" @@ -89,7 +90,7 @@ func TestDiscordNotifier(t *testing.T) { }) t.Run("discord Queue", func(t *testing.T) { - go notifier.Queue(Discorder) + go notifications.Queue(Discorder) time.Sleep(1 * time.Second) assert.Equal(t, DISCORD_URL, Discorder.Host) assert.Equal(t, 0, len(Discorder.Queue)) diff --git a/notifiers/notifiers_test.go b/notifiers/notifiers_test.go index b74d6f5d..2ab71d08 100644 --- a/notifiers/notifiers_test.go +++ b/notifiers/notifiers_test.go @@ -18,7 +18,6 @@ package notifiers import ( "github.com/hunterlong/statping/database" "github.com/hunterlong/statping/source" - "github.com/hunterlong/statping/types/core" "github.com/hunterlong/statping/types/failures" "github.com/hunterlong/statping/types/notifications" "github.com/hunterlong/statping/types/null" @@ -63,10 +62,6 @@ var TestUser = &users.User{ Email: "info@email.com", } -var TestCore = &core.Core{ - Name: "testing notifiers", -} - func CountNotifiers() int { return len(notifications.AllCommunications) } diff --git a/notifiers/slack_test.go b/notifiers/slack_test.go index 48e4d535..dd8e31be 100644 --- a/notifiers/slack_test.go +++ b/notifiers/slack_test.go @@ -16,7 +16,6 @@ package notifiers import ( - "github.com/hunterlong/statping/notifiers" "github.com/hunterlong/statping/types/notifications" "github.com/stretchr/testify/assert" "os" diff --git a/types/configs/configs_test.go b/types/configs/configs_test.go index 85bedd48..b19bf6e1 100644 --- a/types/configs/configs_test.go +++ b/types/configs/configs_test.go @@ -1,30 +1,39 @@ package configs import ( + "github.com/hunterlong/statping/utils" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" "os" "testing" ) +var ( + configs *DbConfig +) + func TestDbConfig_Save(t *testing.T) { - config := &types.DbConfig{ + config := &DbConfig{ DbConn: "sqlite", Project: "Tester", - Location: dir, + Location: utils.Directory, } - err := SaveConfig(config) + err := ConnectConfigs(config) require.Nil(t, err) - assert.Equal(t, "sqlite", config.DbConn) + + err = config.Save(utils.Directory) + require.Nil(t, err) + + assert.Equal(t, "sqlite3", config.DbConn) assert.NotEmpty(t, config.ApiKey) assert.NotEmpty(t, config.ApiSecret) } func TestLoadDbConfig(t *testing.T) { - Configs, err := LoadConfigFile(dir) + Configs, err := LoadConfigFile(utils.Directory) assert.Nil(t, err) - assert.Equal(t, "sqlite", Configs.DbConn) + assert.Equal(t, "sqlite3", Configs.DbConn) configs = Configs } @@ -40,7 +49,7 @@ func TestEnvToConfig(t *testing.T) { os.Setenv("ADMIN_USER", "admin") os.Setenv("ADMIN_PASS", "admin123") os.Setenv("VERBOSE", "1") - config, err := EnvToConfig() + config, err := loadConfigEnvs() assert.Nil(t, err) assert.Equal(t, config.DbConn, "sqlite") assert.Equal(t, config.Domain, "http://localhost:8080") diff --git a/types/configs/connection.go b/types/configs/connection.go index f113bf19..6fc49b1d 100644 --- a/types/configs/connection.go +++ b/types/configs/connection.go @@ -52,11 +52,18 @@ func Connect(configs *DbConfig, retry bool) error { log.Debugln(fmt.Sprintf("Database connection error %s", err)) if retry { log.Errorln(fmt.Sprintf("Database %s connection to '%s' is not available, trying again in 5 seconds...", configs.DbConn, configs.DbHost)) - return configs.waitForDb(configs) + time.Sleep(5 * time.Second) + return Connect(configs, retry) } else { return err } } + + apiKey := utils.Getenv("API_KEY", utils.RandomString(16)).(string) + apiSecret := utils.Getenv("API_SECRET", utils.RandomString(16)).(string) + configs.ApiKey = apiKey + configs.ApiSecret = apiSecret + log.WithFields(utils.ToFields(dbSession)).Debugln("connected to database") maxOpenConn := utils.Getenv("MAX_OPEN_CONN", 5) @@ -77,12 +84,6 @@ func Connect(configs *DbConfig, retry bool) error { return err } -// waitForDb will sleep for 5 seconds and try to connect to the database again -func (c *DbConfig) waitForDb(configs *DbConfig) error { - time.Sleep(5 * time.Second) - return c.Connect() -} - func InitialSetup(configs *DbConfig) error { log.Infoln(fmt.Sprintf("Core database does not exist, creating now!")) diff --git a/types/configs/database.go b/types/configs/database.go index 47e6157c..8160af66 100644 --- a/types/configs/database.go +++ b/types/configs/database.go @@ -47,16 +47,6 @@ func createSamples(sm ...SamplerFunc) error { return nil } -func (d *DbConfig) Connect() error { - - return nil -} - -func (d *DbConfig) Create() error { - - return nil -} - // Migrate function func (d *DbConfig) Update() error { var err error @@ -103,14 +93,10 @@ func CreateDatabase() error { for _, table := range DbModels { if err := database.DB().CreateTable(table); err.Error() != nil { return err.Error() - } else { - log.Infof("Database table: '%T' was created", table) } } if err := database.DB().Table("core").CreateTable(&core.Core{}); err.Error() != nil { return err.Error() - } else { - log.Infof("Database table: '%s' was created", "core") } log.Infoln("Statping Database Created") diff --git a/types/core/core_test.go b/types/core/core_test.go deleted file mode 100644 index 462a7690..00000000 --- a/types/core/core_test.go +++ /dev/null @@ -1,21 +0,0 @@ -package core - -import ( - "github.com/stretchr/testify/assert" - "testing" - "time" -) - -// NewCore return a new *core.Core struct -func NewCore() *Core { - core := &Core{ - Started: time.Now().UTC(), - } - return core -} - -func TestSelectCore(t *testing.T) { - core, err := Select() - assert.Nil(t, err) - assert.Equal(t, "Statping Sample Data", core.Name) -} diff --git a/types/groups/groups_test.go b/types/groups/groups_test.go new file mode 100644 index 00000000..858084a0 --- /dev/null +++ b/types/groups/groups_test.go @@ -0,0 +1,29 @@ +package groups + +import ( + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + "testing" +) + +func TestGroup_Create(t *testing.T) { + group := &Group{ + Name: "Testing", + } + err := group.Create() + assert.Nil(t, err) + assert.NotZero(t, group.Id) +} + +func TestGroup_Services(t *testing.T) { + group, err := Find(1) + require.Nil(t, err) + assert.NotEmpty(t, group.Services()) +} + +func TestSelectGroups(t *testing.T) { + grs := SelectGroups(true, false) + assert.Equal(t, int(3), len(grs)) + grs = SelectGroups(true, true) + assert.Equal(t, int(5), len(grs)) +} diff --git a/types/messages/database.go b/types/messages/database.go index 8085c213..870f4a01 100644 --- a/types/messages/database.go +++ b/types/messages/database.go @@ -7,9 +7,9 @@ func DB() database.Database { } func Find(id int64) (*Message, error) { - var user *Message - db := DB().Where("id = ?", id).Find(&user) - return user, db.Error() + var message Message + db := DB().Where("id = ?", id).Find(&message) + return &message, db.Error() } func All() []*Message { diff --git a/types/notifications/audit.go b/types/notifications/audit.go deleted file mode 100644 index 3adf508b..00000000 --- a/types/notifications/audit.go +++ /dev/null @@ -1,16 +0,0 @@ -// Statping -// Copyright (C) 2018. Hunter Long and the project contributors -// Written by Hunter Long and the project contributors -// -// https://github.com/hunterlong/statping -// -// The licenses for most software and other practical works are designed -// to take away your freedom to share and change the works. By contrast, -// the GNU General Public License is intended to guarantee your freedom to -// share and change all versions of a program--to make sure it remains free -// software for all its users. -// -// You should have received a copy of the GNU General Public License -// along with this program. If not, see . - -package notifications diff --git a/types/notifications/example_test.go b/types/notifications/example_test.go index 5215a0a7..39782fa5 100644 --- a/types/notifications/example_test.go +++ b/types/notifications/example_test.go @@ -91,7 +91,6 @@ func init() { source.Assets() utils.InitLogs() injectDatabase() - AddNotifiers(example) } // Send is the main function to hold your notifier functionality @@ -167,18 +166,6 @@ func (n *ExampleNotifier) OnDeletedUser(s *users.User) { n.AddQueue(fmt.Sprintf("service_%v", s.Id), msg) } -//// OnUpdatedCore is a option event when the settings are updated -//func (n *ExampleNotifier) OnUpdatedCore(c *core.Core) { -// msg := fmt.Sprintf("received a updated core trigger for core: %v\n", c.Name) -// n.AddQueue("core", msg) -//} -// -//// OnStart is triggered when statup has been started -//func (n *ExampleNotifier) OnStart(c *core.Core) { -// msg := fmt.Sprintf("received a trigger on Statping boot: %v\n", c.Name) -// 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) @@ -190,137 +177,3 @@ func (n *ExampleNotifier) OnUpdatedNotifier(s *Notification) { msg := fmt.Sprintf("received a update notifier trigger for notifier: %v\n", s.Method) 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 -func ExampleNotification() { - // Create a new variable for your Notifier - example = &ExampleNotifier{&Notification{ - Method: "Example", - Title: "Example Notifier", - Description: "Example Notifier can hold many different types of fields for a customized look.", - Author: "Hunter Long", - AuthorUrl: "https://github.com/hunterlong", - Delay: time.Duration(1500 * time.Millisecond), - Limits: 7, - Form: []NotificationForm{{ - Type: "text", - Title: "Host", - Placeholder: "Insert your Host here.", - DbField: "host", - SmallText: "you can also use SmallText to insert some helpful hints under this input", - }, { - Type: "text", - Title: "API Key", - Placeholder: "Include some type of API key here", - DbField: "api_key", - }}, - }} - - // AddNotifier accepts a Notifier to load into the Statping Notification system - err := AddNotifiers(example) - fmt.Println(err) - // Output: -} - -// Add a Notifier to the AddQueue function to insert it into the system -func ExampleAddNotifier() { - err := AddNotifiers(example) - fmt.Println(err) - // Output: -} - -// 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("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("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("example", msg) -} - -// OnTest allows your notifier to be testable -func ExampleOnTest() { - err := example.OnTest() - fmt.Print(err) - // Output -} - -// Implement the Test interface to give your notifier testing abilities -func ExampleNotification_CanTest() { - testable := example.CanTest() - fmt.Print(testable) - // Output: true -} - -// 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("example", msg) - queue := example.Queue - fmt.Printf("Example has %v items in the queue", len(queue)) - // Output: - // Example has 2 items in the queue -} - -// The Send method will run the main functionality of your notifier -func ExampleNotification_Send() { - msg := "this can be any type of interface" - example.Send(msg) - queue := example.Queue - fmt.Printf("Example has %v items in the queue", len(queue)) - // Output: - // i received this string: this can be any type of interface - // Example has 2 items in the queue -} - -// LastSent will return the time.Duration of the last sent message -func ExampleNotification_LastSent() { - last := example.LastSent() - fmt.Printf("Last message was sent %v seconds ago", last.Seconds()) - // Output: Last message was sent 0 seconds ago -} - -// Logs will return a slice of previously sent items from your notifier -func ExampleNotification_Logs() { - logs := example.Logs() - fmt.Printf("Example has %v items in the log", len(logs)) - // Output: Example has 0 items in the log -} - -// SentLastMinute will return he amount of notifications sent in last 1 minute -func ExampleNotification_SentLastMinute() { - lastMinute := example.SentLastMinute() - fmt.Printf("%v notifications sent in the last minute", lastMinute) - // Output: 0 notifications sent in the last minute -} - -// SentLastHour will return he amount of notifications sent in last 1 hour -func ExampleNotification_SentLastHour() { - lastHour := example.SentLastHour() - fmt.Printf("%v notifications sent in the last hour", lastHour) - // Output: 0 notifications sent in the last hour -} - -// SentLastHour will return he amount of notifications sent in last 1 hour -func ExampleNotification_WithinLimits() { - ok, err := example.WithinLimits() - if err != nil { - panic(err) - } - if ok { - fmt.Printf("Example notifier is still within its sending limits") - } - // Output: Example notifier is still within its sending limits -} diff --git a/types/notifications/notifications_test.go b/types/notifications/notifications_test.go deleted file mode 100644 index 9965610b..00000000 --- a/types/notifications/notifications_test.go +++ /dev/null @@ -1,14 +0,0 @@ -package notifications - -import ( - "github.com/stretchr/testify/assert" - "testing" -) - -func TestInsertNotifierDB(t *testing.T) { - if skipNewDb { - t.SkipNow() - } - err := InsertNotifierDB() - assert.Nil(t, err) -} diff --git a/types/notifications/struct_test.go b/types/notifications/struct_test.go index d9762905..1c2a7ed9 100644 --- a/types/notifications/struct_test.go +++ b/types/notifications/struct_test.go @@ -18,7 +18,6 @@ package notifications import ( "fmt" "github.com/hunterlong/statping/database" - "github.com/hunterlong/statping/types/core" "github.com/hunterlong/statping/types/failures" "github.com/hunterlong/statping/types/null" "github.com/hunterlong/statping/types/services" @@ -55,10 +54,6 @@ var user = &users.User{ Email: "info@email.com", } -var testCore = &core.Core{ - Name: "testing notifiers", -} - func injectDatabase() { sqlPath := dir + "/notifier.db" utils.DeleteFile(sqlPath) @@ -71,14 +66,15 @@ func TestIsBasicType(t *testing.T) { assert.True(t, utils.IsType(example, new(BasicEvents))) assert.True(t, utils.IsType(example, new(ServiceEvents))) assert.True(t, utils.IsType(example, new(UserEvents))) - assert.True(t, utils.IsType(example, new(CoreEvents))) assert.True(t, utils.IsType(example, new(NotifierEvents))) assert.True(t, utils.IsType(example, new(Tester))) } func TestSelectNotification(t *testing.T) { - notifier, err := SelectNotification(example) + notifier, notif, err := SelectNotifier(example.Method) assert.Nil(t, err) + assert.NotNil(t, notifier) + assert.NotNil(t, notif) assert.Equal(t, "example", notifier.Method) assert.False(t, notifier.Enabled.Bool) assert.False(t, notifier.IsRunning()) @@ -199,11 +195,6 @@ func TestOnDeletedUser(t *testing.T) { assert.Equal(t, 9, len(example.Queue)) } -func TestOnUpdatedCore(t *testing.T) { - OnUpdatedCore(testCore) - assert.Equal(t, 10, len(example.Queue)) -} - func TestOnUpdatedNotifier(t *testing.T) { OnUpdatedNotifier(example.Select()) assert.Equal(t, 11, len(example.Queue)) @@ -215,7 +206,7 @@ func TestRunAllQueueAndStop(t *testing.T) { go Queue(example) time.Sleep(13 * time.Second) assert.NotZero(t, len(example.Queue)) - example.close() + example.Close() assert.False(t, example.IsRunning()) assert.NotZero(t, len(example.Queue)) } diff --git a/types/services/services_checkin_test.go b/types/services/services_checkin_test.go index df9c6410..078c53ca 100644 --- a/types/services/services_checkin_test.go +++ b/types/services/services_checkin_test.go @@ -16,8 +16,7 @@ package services import ( - "github.com/hunterlong/statping/database" - "github.com/hunterlong/statping/types" + "github.com/hunterlong/statping/types/checkins" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" "testing" @@ -25,19 +24,20 @@ import ( ) var ( - testCheckin *Checkin + testCheckin *checkins.Checkin ) func TestCreateCheckin(t *testing.T) { - service := SelectService(1) - checkin := &types.Checkin{ + service, err := Find(2) + require.Nil(t, err) + checkin := &checkins.Checkin{ ServiceId: service.Id, Interval: 10, GracePeriod: 5, } - id, err := database.Create(checkin) - assert.Nil(t, err) - assert.NotZero(t, id) + err = checkin.Create() + require.Nil(t, err) + assert.NotZero(t, checkin.Id) assert.NotEmpty(t, testCheckin.ApiKey) assert.Equal(t, int64(10), testCheckin.Interval) assert.Equal(t, int64(5), testCheckin.GracePeriod) @@ -45,11 +45,12 @@ func TestCreateCheckin(t *testing.T) { } func TestSelectCheckin(t *testing.T) { - service := SelectService(1) - checkins := service.Checkins() - assert.NotNil(t, checkins) - assert.Equal(t, 1, len(checkins)) - c := checkins[0] + service, err := Find(2) + require.Nil(t, err) + chks := service.Checkins() + assert.NotNil(t, chks) + assert.Equal(t, 1, len(chks)) + c := chks[0] assert.Equal(t, int64(10), c.Interval) assert.Equal(t, int64(5), c.GracePeriod) assert.Equal(t, 7, len(c.ApiKey)) @@ -58,11 +59,13 @@ func TestSelectCheckin(t *testing.T) { func TestUpdateCheckin(t *testing.T) { testCheckin.Interval = 60 testCheckin.GracePeriod = 15 - err := database.Update(testCheckin) - assert.Nil(t, err) + err := testCheckin.Update() + require.Nil(t, err) assert.NotZero(t, testCheckin.Id) assert.NotEmpty(t, testCheckin.ApiKey) - service := SelectService(1) + + service, err := Find(1) + require.Nil(t, err) checkin := service.Checkins()[0] assert.Equal(t, int64(60), checkin.Interval) assert.Equal(t, int64(15), checkin.GracePeriod) @@ -71,16 +74,17 @@ func TestUpdateCheckin(t *testing.T) { } func TestCreateCheckinHits(t *testing.T) { - service := SelectService(1) - checkins := service.Checkins() - assert.Equal(t, 1, len(checkins)) + service, err := Find(1) + require.Nil(t, err) + check := service.Checkins() + assert.Equal(t, 1, len(check)) created := time.Now().UTC().Add(-60 * time.Second) - hit := &types.CheckinHit{ + hit := &checkins.CheckinHit{ Checkin: testCheckin.Id, From: "192.168.1.1", CreatedAt: created, } - _, err := database.Create(hit) + err = hit.Create() require.Nil(t, err) checks := service.Checkins() @@ -89,7 +93,8 @@ func TestCreateCheckinHits(t *testing.T) { func TestSelectCheckinMethods(t *testing.T) { time.Sleep(5 * time.Second) - service := SelectService(1) + service, err := Find(1) + require.Nil(t, err) checkins := service.Checkins() assert.NotNil(t, checkins) assert.Equal(t, float64(60), testCheckin.Period().Seconds()) diff --git a/types/services/services_test.go b/types/services/services_test.go index 0502cef1..89875b05 100644 --- a/types/services/services_test.go +++ b/types/services/services_test.go @@ -16,8 +16,7 @@ package services import ( - "github.com/hunterlong/statping/database" - "github.com/hunterlong/statping/types" + "github.com/hunterlong/statping/types/failures" "github.com/hunterlong/statping/utils" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" @@ -38,9 +37,9 @@ func TestSelectHTTPService(t *testing.T) { } func TestSelectAllServices(t *testing.T) { - services := CoreApp.services + services := All() for _, s := range services { - CheckService(s, false) + s.CheckService(false) assert.False(t, s.IsRunning()) t.Logf("ID: %v %v\n", s.Id, s.Name) } @@ -48,32 +47,35 @@ func TestSelectAllServices(t *testing.T) { } func TestServiceDowntime(t *testing.T) { - t.SkipNow() - service := SelectService(15) + service, err := Find(15) + require.Nil(t, err) downtime := service.Downtime() assert.True(t, downtime.Seconds() > 0) } func TestSelectTCPService(t *testing.T) { - services := CoreApp.services + services := All() assert.Equal(t, 15, len(services)) - service := SelectService(5) + service, err := Find(5) + require.Nil(t, err) assert.NotNil(t, service) assert.Equal(t, "Google DNS", service.Name) assert.Equal(t, "tcp", service.Type) } func TestUpdateService(t *testing.T) { - service := SelectService(1) + service, err := Find(1) + require.Nil(t, err) assert.Equal(t, "Google", service.Name) service.Name = "Updated Google" service.Interval = 5 - err := database.Update(service) + err = service.Update() require.Nil(t, err) // check if updating pointer array shutdown any other service - service = SelectService(1) + service, err = Find(1) + require.Nil(t, err) assert.Equal(t, "Updated Google", service.Name) assert.Equal(t, 5, service.Interval) } @@ -86,21 +88,23 @@ func TestUpdateAllServices(t *testing.T) { srv.Name = "Changed " + srv.Name srv.Interval = i + 3 - err := database.Update(srv) + err := srv.Update() require.Nil(t, err) i++ } } func TestServiceHTTPCheck(t *testing.T) { - service := SelectService(1) - CheckService(service, true) + service, err := Find(1) + require.Nil(t, err) + service.CheckService(true) assert.Equal(t, "Changed Updated Google", service.Name) assert.True(t, service.Online) } func TestCheckHTTPService(t *testing.T) { - service := SelectService(1) + service, err := Find(1) + require.Nil(t, err) assert.Equal(t, "Changed Updated Google", service.Name) assert.True(t, service.Online) assert.Equal(t, 200, service.LastStatusCode) @@ -109,14 +113,16 @@ func TestCheckHTTPService(t *testing.T) { } func TestServiceTCPCheck(t *testing.T) { - service := SelectService(5) - CheckService(service, true) + service, err := Find(5) + require.Nil(t, err) + service.CheckService(false) assert.Equal(t, "Changed Google DNS", service.Name) assert.True(t, service.Online) } func TestCheckTCPService(t *testing.T) { - service := SelectService(5) + service, err := Find(5) + require.Nil(t, err) assert.Equal(t, "Changed Google DNS", service.Name) assert.True(t, service.Online) assert.NotZero(t, service.Latency) @@ -125,28 +131,32 @@ func TestCheckTCPService(t *testing.T) { func TestServiceOnline24Hours(t *testing.T) { since := utils.Now().Add(-24 * time.Hour).Add(-10 * time.Minute) - service := SelectService(1) + service, err := Find(1) + require.Nil(t, err) assert.Equal(t, float32(100), service.OnlineSince(since)) - service2 := SelectService(5) + service2, err := Find(5) + require.Nil(t, err) assert.Equal(t, float32(100), service2.OnlineSince(since)) - service3 := SelectService(14) + service3, err := Find(14) + require.Nil(t, err) assert.True(t, service3.OnlineSince(since) > float32(49)) } func TestServiceAvgUptime(t *testing.T) { since := utils.Now().Add(-24 * time.Hour).Add(-10 * time.Minute) - service := SelectService(1) + service, err := Find(1) + require.Nil(t, err) assert.NotEqual(t, "0.00", service.AvgTime()) - service2 := SelectService(5) + service2, err := Find(5) assert.Equal(t, "100", service2.AvgTime()) - service3 := SelectService(13) + service3, err := Find(13) assert.NotEqual(t, "0", service3.AvgUptime(since)) - service4 := SelectService(15) + service4, err := Find(15) assert.NotEqual(t, "0", service4.AvgUptime(since)) } func TestCreateService(t *testing.T) { - s := &services.Service{ + s := &Service{ Name: "That'll do 🐢", Domain: "https://www.youtube.com/watch?v=rjQtzV9IZ0Q", ExpectedStatus: 200, @@ -156,20 +166,21 @@ func TestCreateService(t *testing.T) { Timeout: 20, GroupId: 1, } - obj, err := database.Create(s) + err := s.Create() require.Nil(t, err) - assert.NotZero(t, obj.Id) - newService := SelectService(obj.Id) + assert.NotZero(t, s.Id) + newService, err := Find(s.Id) assert.Equal(t, "That'll do 🐢", newService.Name) } func TestViewNewService(t *testing.T) { - newService := SelectService(newServiceId) + newService, err := Find(newServiceId) + require.Nil(t, err) assert.Equal(t, "That'll do 🐢", newService.Name) } func TestCreateFailingHTTPService(t *testing.T) { - s := &services.Service{ + s := &Service{ Name: "Bad URL", Domain: "http://localhost/iamnothere", ExpectedStatus: 200, @@ -179,24 +190,26 @@ func TestCreateFailingHTTPService(t *testing.T) { Timeout: 5, GroupId: 1, } - obj, err := database.Create(s) + err := s.Create() + require.Nil(t, err) + assert.NotZero(t, s.Id) + newService, err := Find(s.Id) require.Nil(t, err) - assert.NotZero(t, obj.Id) - newService := SelectService(obj.Id) assert.Equal(t, "Bad URL", newService.Name) t.Log("new service ID: ", newServiceId) } func TestServiceFailedCheck(t *testing.T) { - service := SelectService(17) + service, err := Find(17) + require.Nil(t, err) assert.Equal(t, "Bad URL", service.Name) - CheckService(service, false) + service.CheckService(false) assert.Equal(t, "Bad URL", service.Name) assert.False(t, service.Online) } func TestCreateFailingTCPService(t *testing.T) { - s := &services.Service{ + s := &Service{ Name: "Bad TCP", Domain: "localhost", Port: 5050, @@ -205,36 +218,37 @@ func TestCreateFailingTCPService(t *testing.T) { Timeout: 5, GroupId: 1, } - var err error - obj, err := database.Create(s) + err := s.Create() assert.Nil(t, err) - assert.NotZero(t, obj.Id) - newService := SelectService(obj.Id) + assert.NotZero(t, s.Id) + newService, err := Find(s.Id) + require.Nil(t, err) assert.Equal(t, "Bad TCP", newService.Name) t.Log("new failing tcp service ID: ", newServiceId) } func TestServiceFailedTCPCheck(t *testing.T) { - service := SelectService(newServiceId) - CheckService(service, false) - assert.Equal(t, "Bad TCP", service.Name) - assert.False(t, service.Online) + srv, err := Find(newServiceId) + require.Nil(t, err) + srv.CheckService(false) + assert.Equal(t, "Bad TCP", srv.Name) + assert.False(t, srv.Online) } func TestCreateServiceFailure(t *testing.T) { - service := SelectService(8) - fail := &types.Failure{ + service, err := Find(8) + fail := &failures.Failure{ Issue: "This is not an issue, but it would container HTTP response errors.", Method: "http", Service: service.Id, } - obj, err := database.Create(fail) + err = fail.Create() assert.Nil(t, err) - assert.NotZero(t, obj.Id) + assert.NotZero(t, fail.Id) } func TestDeleteService(t *testing.T) { - service := SelectService(newServiceId) + service, err := Find(newServiceId) count, err := SelectAllServices(false) assert.Nil(t, err) @@ -243,7 +257,7 @@ func TestDeleteService(t *testing.T) { err = service.Delete() assert.Nil(t, err) - services := CoreApp.services + services := All() assert.Equal(t, 17, len(services)) } @@ -311,29 +325,8 @@ func TestDNScheckService(t *testing.T) { assert.NotZero(t, amount) } -func TestSelectServiceLink(t *testing.T) { - service := SelectService(1) +func TestFindLink(t *testing.T) { + service, err := Find(1) + require.Nil(t, err) assert.Equal(t, "google", service.Permalink.String) } - -func TestGroup_Create(t *testing.T) { - group := &types.Group{ - Name: "Testing", - } - obj, err := database.Create(group) - assert.Nil(t, err) - assert.NotZero(t, obj.Id) -} - -func TestGroup_Services(t *testing.T) { - t.SkipNow() - //group := SelectGroup(1) - //assert.NotEmpty(t, group.Services()) -} - -func TestSelectGroups(t *testing.T) { - groups := SelectGroups(true, false) - assert.Equal(t, int(3), len(groups)) - groups = SelectGroups(true, true) - assert.Equal(t, int(5), len(groups)) -} diff --git a/types/users/database.go b/types/users/database.go index de6b21d4..1be201cd 100644 --- a/types/users/database.go +++ b/types/users/database.go @@ -1,6 +1,7 @@ package users import ( + "errors" "github.com/hunterlong/statping/database" "github.com/hunterlong/statping/utils" "time" @@ -12,14 +13,14 @@ func DB() database.Database { func Find(id int64) (*User, error) { var user *User - db := DB().Where("id = ?", id).Find(&user) + db := DB().Where("id = ?", id).Find(user) return user, db.Error() } func FindByUsername(username string) (*User, error) { - var user User - db := DB().Where("username = ?", username).Find(&user) - return &user, db.Error() + var user *User + db := DB().Where("username = ?", username).Find(user) + return user, db.Error() } func All() []*User { @@ -30,22 +31,25 @@ func All() []*User { func (u *User) Create() error { u.CreatedAt = time.Now().UTC() + if u.Password == "" { + return errors.New("did not supply user password") + } u.Password = utils.HashPassword(u.Password) u.ApiKey = utils.NewSHA1Hash(5) u.ApiSecret = utils.NewSHA1Hash(10) - db := DB().Create(&u) + db := DB().Create(u) return db.Error() } func (u *User) Update() error { u.ApiKey = utils.NewSHA1Hash(5) u.ApiSecret = utils.NewSHA1Hash(10) - db := DB().Update(&u) + db := DB().Update(u) return db.Error() } func (u *User) Delete() error { - db := DB().Delete(&u) + db := DB().Delete(u) return db.Error() } diff --git a/types/users/struct.go b/types/users/struct.go index 50e97b3c..aae4878a 100644 --- a/types/users/struct.go +++ b/types/users/struct.go @@ -2,6 +2,7 @@ package users import ( "github.com/hunterlong/statping/types/null" + "github.com/hunterlong/statping/utils" "time" ) @@ -20,6 +21,8 @@ type User struct { // BeforeCreate for User will set CreatedAt to UTC func (u *User) BeforeCreate() (err error) { + u.ApiKey = utils.RandomString(16) + u.ApiSecret = utils.RandomString(16) if u.CreatedAt.IsZero() { u.CreatedAt = time.Now().UTC() u.UpdatedAt = time.Now().UTC() diff --git a/types/users/users_test.go b/types/users/users_test.go index 06010c51..7a107bd8 100644 --- a/types/users/users_test.go +++ b/types/users/users_test.go @@ -17,37 +17,37 @@ package users import ( "github.com/hunterlong/statping/database" - "github.com/hunterlong/statping/types" + "github.com/hunterlong/statping/types/null" "github.com/stretchr/testify/assert" "testing" ) func TestCreateUser(t *testing.T) { - user := &types.User{ + user := &User{ Username: "hunter", Password: "password123", Email: "test@email.com", - Admin: types.NewNullBool(true), + Admin: null.NewNullBool(true), } - obj, err := database.Create(user) + err := user.Create() assert.Nil(t, err) - assert.NotZero(t, obj.Id) + assert.NotZero(t, user.Id) } func TestSelectAllUsers(t *testing.T) { - users := SelectAllUsers() + users := All() assert.Equal(t, 3, len(users)) } func TestSelectUser(t *testing.T) { - user, err := SelectUser(1) + user, err := Find(1) assert.Nil(t, err) assert.Equal(t, "info@betatude.com", user.Email) assert.True(t, user.Admin.Bool) } func TestSelectUsername(t *testing.T) { - user, err := SelectUsername("hunter") + user, err := FindByUsername("hunter") assert.Nil(t, err) assert.Equal(t, "test@email.com", user.Email) assert.Equal(t, int64(3), user.Id) @@ -55,30 +55,30 @@ func TestSelectUsername(t *testing.T) { } func TestUpdateUser(t *testing.T) { - user, err := SelectUser(1) + user, err := Find(1) assert.Nil(t, err) user.Username = "updated" err = user.Update() assert.Nil(t, err) - updatedUser, err := SelectUser(1) + updatedUser, err := Find(1) assert.Nil(t, err) assert.Equal(t, "updated", updatedUser.Username) } func TestCreateUser2(t *testing.T) { - user := &types.User{ + user := &User{ Username: "hunterlong", Password: "password123", Email: "User@email.com", - Admin: types.NewNullBool(true), + Admin: null.NewNullBool(true), } - obj, err := database.Create(user) + err := user.Create() assert.Nil(t, err) - assert.NotZero(t, obj.Id) + assert.NotZero(t, user.Id) } func TestSelectAllUsersAgain(t *testing.T) { - users := SelectAllUsers() + users := All() assert.Equal(t, 4, len(users)) } @@ -98,14 +98,14 @@ func TestFailedAuthUser(t *testing.T) { } func TestCheckPassword(t *testing.T) { - user, err := SelectUser(2) + user, err := Find(2) assert.Nil(t, err) pass := CheckHash("password123", user.Password) assert.True(t, pass) } func TestDeleteUser(t *testing.T) { - user, err := SelectUser(2) + user, err := Find(2) assert.Nil(t, err) err = user.Delete() assert.Nil(t, err)