mirror of
https://github.com/bettercap/bettercap
synced 2025-08-19 21:13:18 -07:00
wrote unit tests for session.Environment
This commit is contained in:
parent
64f3a79be3
commit
4cd86f3fd0
5 changed files with 303 additions and 18 deletions
|
@ -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
|
||||
}
|
||||
|
||||
|
|
Loading…
Add table
Add a link
Reference in a new issue