wrote unit tests for session.Environment

This commit is contained in:
evilsocket 2018-04-30 14:20:34 +02:00
commit 4cd86f3fd0
No known key found for this signature in database
GPG key ID: 1564D7F30393A456
5 changed files with 303 additions and 18 deletions

View file

@ -11,32 +11,30 @@ import (
"github.com/bettercap/bettercap/core"
)
type SetCallback func(newValue string)
type EnvironmentChangedCallback func(newValue string)
type Environment struct {
sync.Mutex
Data map[string]string `json:"data"`
cbs map[string]SetCallback
sess *Session
cbs map[string]EnvironmentChangedCallback
}
func NewEnvironment(s *Session, envFile string) *Environment {
func NewEnvironment(envFile string) (*Environment, error) {
env := &Environment{
Data: make(map[string]string),
sess: s,
cbs: make(map[string]SetCallback),
cbs: make(map[string]EnvironmentChangedCallback),
}
if envFile != "" {
envFile, _ := core.ExpandPath(envFile)
if core.Exists(envFile) {
if err := env.Load(envFile); err != nil {
fmt.Printf("Error while loading %s: %s\n", envFile, err)
return nil, err
}
}
}
return env
return env, nil
}
func (env *Environment) Load(fileName string) error {
@ -48,7 +46,10 @@ func (env *Environment) Load(fileName string) error {
return err
}
return json.Unmarshal(raw, &env.Data)
if len(raw) > 0 {
return json.Unmarshal(raw, &env.Data)
}
return nil
}
func (env *Environment) Save(fileName string) error {
@ -72,15 +73,15 @@ func (env *Environment) Has(name string) bool {
return found
}
func (env *Environment) SetCallback(name string, cb SetCallback) {
func (env *Environment) addCb(name string, cb EnvironmentChangedCallback) {
env.Lock()
defer env.Unlock()
env.cbs[name] = cb
}
func (env *Environment) WithCallback(name, value string, cb SetCallback) string {
func (env *Environment) WithCallback(name, value string, cb EnvironmentChangedCallback) string {
env.addCb(name, cb)
ret := env.Set(name, value)
env.SetCallback(name, cb)
return ret
}
@ -95,8 +96,6 @@ func (env *Environment) Set(name, value string) string {
cb(value)
}
env.sess.Events.Log(core.DEBUG, "env.change: %s -> '%s'", name, value)
return old
}