Skip to content

Commit

Permalink
Add more test cases (megaease#197)
Browse files Browse the repository at this point in the history
* add more test cases for channel, conf and report package

* add more test cases for probe.client.conf and daemon package

* add more test cases for probe package

* fix dry run bug

* add comment for package

* add init() for Channel to initialize the dryNotify

* go fmt

* upgrade the lint version and add the comment for all packages

* add more test cases for ssh & http prober

* rename GetDryNotify() to IsDryNotify()
  • Loading branch information
haoel authored Aug 19, 2022
1 parent f4fab9a commit b4a691d
Show file tree
Hide file tree
Showing 64 changed files with 736 additions and 97 deletions.
4 changes: 2 additions & 2 deletions .github/workflows/code.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ on:
- ".github/workflows/code.yml"

env:
GO_VERSION: 1.18
GO_VERSION: 1.19

jobs:

Expand All @@ -34,7 +34,7 @@ jobs:
- name: Spelling Check
uses: reviewdog/[email protected]
- name: Revive Action
uses: morphy2k/revive-action@v2.3.1
uses: morphy2k/revive-action@v2
- name: "Restore Permissions"
run: |
sudo chown -R $(id -u) $GITHUB_WORKSPACE
Expand Down
3 changes: 2 additions & 1 deletion channel/channel.go
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@
* limitations under the License.
*/

// Package channel implements the channel interface
package channel

import (
Expand Down Expand Up @@ -159,7 +160,7 @@ func (c *Channel) WatchEvent(wg *sync.WaitGroup) {
log.Infof("[%s / %s]: %s (%s) - Status changed [%s] ==> [%s]",
kind, c.Name, result.Name, result.Endpoint, result.PreStatus, result.Status)
for _, n := range c.Notifiers {
if dryNotify {
if IsDryNotify() == true {
n.DryNotify(result)
} else {
go n.Notify(result)
Expand Down
14 changes: 12 additions & 2 deletions channel/manager.go
Original file line number Diff line number Diff line change
Expand Up @@ -19,18 +19,28 @@ package channel

import (
"sync"
"sync/atomic"

"github.com/megaease/easeprobe/notify"
"github.com/megaease/easeprobe/probe"
)

var channel = make(map[string]*Channel)
var wg sync.WaitGroup
var dryNotify bool
var dryNotify atomic.Value

func init() {
SetDryNotify(false)
}

// SetDryNotify sets the global dry run flag
func SetDryNotify(dry bool) {
dryNotify = dry
dryNotify.Store(dry)
}

// IsDryNotify returns the dry run flag
func IsDryNotify() bool {
return dryNotify.Load().(bool)
}

// GetAllChannels returns all channels
Expand Down
11 changes: 11 additions & 0 deletions channel/manager_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -186,5 +186,16 @@ func TestManager(t *testing.T) {
time.Sleep(200 * time.Millisecond)
assert.Equal(t, nGoroutine, runtime.NumGoroutine())

// test the dry notification
SetDryNotify(true)
assert.True(t, IsDryNotify())
for _, ch := range chs {
for _, p := range ch.Probers {
res := p.Probe()
assert.NotNil(t, res)
ch.Send(res)
}
}

AllDone()
}
6 changes: 2 additions & 4 deletions cmd/easeprobe/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@
* limitations under the License.
*/

// Package main is the entry point for the easeprobe command.
package main

import (
Expand Down Expand Up @@ -107,14 +108,11 @@ func main() {
// if dry notification mode is specified in command line, overwrite the configuration
if *dryNotify {
c.Settings.Notify.Dry = *dryNotify
log.Infoln("Dry Notification Mode...")
}
// set the dry notify flag to channel
channel.SetDryNotify(c.Settings.Notify.Dry)

if c.Settings.Notify.Dry {
log.Infoln("Dry Notification Mode...")
}

////////////////////////////////////////////////////////////////////////////
// Start the HTTP Server //
////////////////////////////////////////////////////////////////////////////
Expand Down
38 changes: 25 additions & 13 deletions conf/conf.go
Original file line number Diff line number Diff line change
Expand Up @@ -15,9 +15,11 @@
* limitations under the License.
*/

// Package conf is the configuration of the application
package conf

import (
"fmt"
"io/ioutil"
httpClient "net/http"
netUrl "net/url"
Expand Down Expand Up @@ -56,30 +58,40 @@ type Schedule int

// Schedule enum
const (
Hourly Schedule = iota
None Schedule = iota
Hourly
Daily
Weekly
Monthly
None
)

var scheduleToString = map[Schedule]string{
Hourly: "hourly",
Daily: "daily",
Weekly: "weekly",
Monthly: "monthly",
None: "none",
}

var stringToSchedule = global.ReverseMap(scheduleToString)

// MarshalYAML marshal the configuration to yaml
func (s Schedule) MarshalYAML() (interface{}, error) {
if s, ok := scheduleToString[s]; ok {
return s, nil
}
return nil, fmt.Errorf("unknown schedule %d", s)
}

// UnmarshalYAML is unmarshal the debug level
func (s *Schedule) UnmarshalYAML(unmarshal func(interface{}) error) error {
var level string
if err := unmarshal(&level); err != nil {
return err
}
switch strings.ToLower(level) {
case "hourly":
*s = Hourly
case "daily":
*s = Daily
case "weekly":
*s = Weekly
case "monthly":
*s = Monthly
default:
*s = None
var ok bool
if *s, ok = stringToSchedule[strings.ToLower(level)]; !ok {
return fmt.Errorf("unknown schedule %s", level)
}
return nil
}
Expand Down
67 changes: 64 additions & 3 deletions conf/conf_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -18,9 +18,12 @@
package conf

import (
"errors"
"fmt"
"io"
"io/ioutil"
"net/http"
httpClient "net/http"
"os"
"testing"
"time"
Expand All @@ -41,6 +44,7 @@ import (
"github.com/megaease/easeprobe/probe/tcp"
log "github.com/sirupsen/logrus"
"github.com/stretchr/testify/assert"
"gopkg.in/yaml.v3"
)

func testisExternalURL(url string, expects bool, t *testing.T) {
Expand All @@ -64,6 +68,34 @@ func TestPathAndURL(t *testing.T) {
testisExternalURL("ftp://127.0.0.1", false, t)
}

func testScheduleYaml(t *testing.T, name string, sch Schedule, good bool) {
var s Schedule
err := yaml.Unmarshal([]byte(name), &s)
if good {
assert.Nil(t, err)
assert.Equal(t, sch, s)
} else {
assert.NotNil(t, err)
}

buf, err := yaml.Marshal(sch)
if good {
assert.Nil(t, err)
assert.Equal(t, name+"\n", string(buf))
} else {
assert.NotNil(t, err)
}
}
func TestScheduleYaml(t *testing.T) {
testScheduleYaml(t, "hourly", Hourly, true)
testScheduleYaml(t, "daily", Daily, true)
testScheduleYaml(t, "weekly", Weekly, true)
testScheduleYaml(t, "monthly", Monthly, true)
testScheduleYaml(t, "none", None, true)
testScheduleYaml(t, "yearly", 100, false)
testScheduleYaml(t, "- bad", 100, false)
}

func TestGetYamlFileFromFile(t *testing.T) {
if _, err := getYamlFileFromFile("/tmp/nonexistent"); err == nil {
t.Errorf("getYamlFileFromFile(\"/tmp/nonexistent\") = nil, expected error")
Expand Down Expand Up @@ -107,6 +139,8 @@ http:
interval: 30s
channels:
- "telegram#Dev"
- name: Env Variables
url: $WEB_SITE
`

func checkHTTPProbe(t *testing.T, probe httpProbe.HTTP) {
Expand All @@ -124,6 +158,8 @@ func checkHTTPProbe(t *testing.T, probe httpProbe.HTTP) {
assert.Equal(t, probe.ProbeTimeout, 2*time.Minute)
assert.Equal(t, probe.ProbeTimeInterval, 30*time.Second)
assert.Equal(t, probe.Channels(), []string{"telegram#Dev"})
case "Env Variables":
assert.Equal(t, probe.URL, os.Getenv("WEB_SITE"))
default:
t.Errorf("unexpected probe name %s", probe.ProbeName)
}
Expand Down Expand Up @@ -557,8 +593,15 @@ func TestConfig(t *testing.T) {
err := writeConfig(file, confYAML)
assert.Nil(t, err)

conf, err := New(&file)
// bad config
os.Setenv("WEB_SITE", "\n - x::")
_, err = New(&file)
assert.NotNil(t, err)

os.Setenv("WEB_SITE", "https://easeprobe.com")
_, err = New(&file)
assert.Nil(t, err)
conf := Get()

assert.Equal(t, "EaseProbeBot", conf.Settings.Name)
assert.Equal(t, "0.1.0", conf.Version)
Expand All @@ -583,7 +626,7 @@ func TestConfig(t *testing.T) {

conf.InitAllLogs()
probers := conf.AllProbers()
assert.Equal(t, 8, len(probers))
assert.Equal(t, 9, len(probers))
notifiers := conf.AllNotifiers()
assert.Equal(t, 6, len(notifiers))

Expand All @@ -597,12 +640,30 @@ func TestConfig(t *testing.T) {
assert.Equal(t, "0.1.0", httpConf.Version)

probers = conf.AllProbers()
assert.Equal(t, 8, len(probers))
assert.Equal(t, 9, len(probers))
notifiers = conf.AllNotifiers()
assert.Equal(t, 6, len(notifiers))

os.RemoveAll(file)
os.RemoveAll("data")

// error test
url = "http://localhost:65534"
_, err = New(&url)
assert.NotNil(t, err)

os.Setenv("HTTP_TIMEOUT", "invalid")
_, err = New(&url)
assert.NotNil(t, err)

monkey.Patch(httpClient.NewRequest, func(method, url string, body io.Reader) (*http.Request, error) {
return nil, errors.New("error")
})
url = "http://localhost"
_, err = New(&url)
assert.NotNil(t, err)

monkey.UnpatchAll()
}

func TestInitData(t *testing.T) {
Expand Down
21 changes: 10 additions & 11 deletions conf/log.go
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@
package conf

import (
"fmt"
"io"
"os"
"strings"
Expand All @@ -40,18 +41,14 @@ var levelToString = map[LogLevel]string{
LogLevel(log.PanicLevel): "panic",
}

var stringToLevel = map[string]LogLevel{
"debug": LogLevel(log.DebugLevel),
"info": LogLevel(log.InfoLevel),
"warn": LogLevel(log.WarnLevel),
"error": LogLevel(log.ErrorLevel),
"fatal": LogLevel(log.FatalLevel),
"panic": LogLevel(log.PanicLevel),
}
var stringToLevel = global.ReverseMap(levelToString)

// MarshalYAML is marshal the format
func (l LogLevel) MarshalYAML() (interface{}, error) {
return levelToString[l], nil
if s, ok := levelToString[l]; ok {
return s, nil
}
return nil, fmt.Errorf("invalid log level: %d", l)
}

// UnmarshalYAML is unmarshal the debug level
Expand All @@ -60,7 +57,10 @@ func (l *LogLevel) UnmarshalYAML(unmarshal func(interface{}) error) error {
if err := unmarshal(&level); err != nil {
return err
}
*l = stringToLevel[strings.ToLower(level)]
var ok bool
if *l, ok = stringToLevel[strings.ToLower(level)]; !ok {
return fmt.Errorf("invalid log level: %s", level)
}
return nil
}

Expand Down Expand Up @@ -197,7 +197,6 @@ func (l *Log) Rotate() {
l.Open() // open another writer
l.ConfigureLogger() // set the new logger writer.
}

}

// ConfigureLogger configure the logger
Expand Down
Loading

0 comments on commit b4a691d

Please sign in to comment.