Skip to content

Commit

Permalink
Added tests for the Timer
Browse files Browse the repository at this point in the history
  • Loading branch information
thibauult committed Jan 12, 2024
1 parent 545ecff commit 3598023
Show file tree
Hide file tree
Showing 3 changed files with 38 additions and 16 deletions.
28 changes: 12 additions & 16 deletions cmd/root.go
Original file line number Diff line number Diff line change
Expand Up @@ -36,6 +36,16 @@ openhue controls your Philips Hue lighting system
},
}

cmd.AddGroup(&cobra.Group{
ID: string(OpenHueCmdGroupConfig),
Title: "Configuration",
})

cmd.AddGroup(&cobra.Group{
ID: string(OpenHueCmdGroupHue),
Title: "Philips Hue",
})

return cmd
}

Expand Down Expand Up @@ -66,9 +76,6 @@ func Execute(buildInfo *openhue.BuildInfo) {
// create the root command
root := NewCmdOpenHue(ctx)

// init groups
initGroups(root)

// add sub commands
root.AddCommand(version.NewCmdVersion(ctx))
root.AddCommand(setup.NewCmdAuth(ctx.Io))
Expand All @@ -83,19 +90,8 @@ func Execute(buildInfo *openhue.BuildInfo) {
cobra.CheckErr(err)
}

func initGroups(rootCmd *cobra.Command) {
rootCmd.AddGroup(&cobra.Group{
ID: string(OpenHueCmdGroupConfig),
Title: "Configuration",
})

rootCmd.AddGroup(&cobra.Group{
ID: string(OpenHueCmdGroupHue),
Title: "Philips Hue",
})
}

// isCmdInGroup verifies if a given cobra.Command belongs to a certain OpenHueCmdGroup
// isCmdInGroup verifies if a given cobra.Command belongs to a certain OpenHueCmdGroup.
// This function will recursively command parents until the root one (e.g. parent is nil)
func isCmdInGroup(cmd *cobra.Command, id OpenHueCmdGroup) bool {

if cmd.GroupID == string(id) {
Expand Down
9 changes: 9 additions & 0 deletions util/metrics.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,10 +2,12 @@ package util

import "time"

// NewTimer creates a new started Timer
func NewTimer() *Timer {
return new(Timer).start()
}

// Timer can be used to monitor the execution time of a given method
type Timer struct {
t0 time.Time
}
Expand All @@ -15,6 +17,13 @@ func (t *Timer) start() *Timer {
return t
}

// Reset sets the Timer initial time to time.Now()
func (t *Timer) Reset() *Timer {
t.t0 = time.Now()
return t
}

// SinceInMillis returns the elapsed time in milliseconds since the Timer was started or Reset
func (t *Timer) SinceInMillis() int64 {
return time.Since(t.t0).Milliseconds()
}
17 changes: 17 additions & 0 deletions util/metrics_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
package util

import (
"github.com/stretchr/testify/assert"
"testing"
"time"
)

func TestNewTimer(t *testing.T) {
timer := NewTimer()
assert.NotNil(t, timer)
time.Sleep(1 * time.Millisecond)
assert.True(t, timer.SinceInMillis() >= 1, "we slept for 1 millis")
timer.Reset()
time.Sleep(2 * time.Millisecond)
assert.True(t, timer.SinceInMillis() >= 2, "we slept for 2 millis")
}

0 comments on commit 3598023

Please sign in to comment.