Skip to content

Commit

Permalink
Improve tests
Browse files Browse the repository at this point in the history
Signed-off-by: Tim Vaillancourt <[email protected]>
  • Loading branch information
timvaillancourt committed Dec 23, 2023
1 parent 86efc84 commit cd194e9
Show file tree
Hide file tree
Showing 2 changed files with 22 additions and 13 deletions.
22 changes: 13 additions & 9 deletions go/logic/server.go
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,8 @@ import (
"github.com/github/gh-ost/go/base"
)

const defaultCPUProfileDuration = time.Second * 30

var ErrCPUProfilingInProgress = errors.New("cpu profiling already in progress")

type printStatusFunc func(PrintStatusRule, io.Writer)
Expand All @@ -45,16 +47,24 @@ func NewServer(migrationContext *base.MigrationContext, hooksExecutor *HooksExec
}
}

func (this *Server) runCPUProfile(duration time.Duration) (string, error) {
func (this *Server) runCPUProfile(arg string) (string, error) {
if atomic.LoadInt64(&this.isCPUProfiling) > 0 {
return "", ErrCPUProfilingInProgress
}

var err error
duration := defaultCPUProfileDuration
if arg != "" {
if duration, err = time.ParseDuration(arg); err != nil {
return "", err
}
}

atomic.StoreInt64(&this.isCPUProfiling, 1)
defer atomic.StoreInt64(&this.isCPUProfiling, 0)

var buf bytes.Buffer
if err := pprof.StartCPUProfile(&buf); err != nil {
if err = pprof.StartCPUProfile(&buf); err != nil {
return "", err
}

Expand Down Expand Up @@ -198,13 +208,7 @@ help # This message
case "info", "status":
return ForcePrintStatusAndHintRule, nil
case "cpu-profile":
profileDuration := time.Second * 30
if arg != "" {
if profileDuration, err = time.ParseDuration(arg); err != nil {
return NoPrintStatusRule, err
}
}
profile, err := this.runCPUProfile(profileDuration)
profile, err := this.runCPUProfile(arg)
if err == nil {
fmt.Fprintln(writer, profile)
}
Expand Down
13 changes: 9 additions & 4 deletions go/logic/server_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,15 +3,20 @@ package logic
import (
"encoding/base64"
"testing"
"time"

"github.com/openark/golib/tests"
)

func TestRunCPUProfile(t *testing.T) {
{
s := &Server{isCPUProfiling: 0}
profile, err := s.runCPUProfile(time.Millisecond * 10)
profile, err := s.runCPUProfile("should-fail")
tests.S(t).ExpectNotNil(err)
tests.S(t).ExpectEquals(profile, "")
}
{
s := &Server{isCPUProfiling: 0}
profile, err := s.runCPUProfile("10ms")
tests.S(t).ExpectNil(err)
tests.S(t).ExpectNotEquals(profile, "")

Expand All @@ -21,8 +26,8 @@ func TestRunCPUProfile(t *testing.T) {
}
{
s := &Server{isCPUProfiling: 1}
profile, err := s.runCPUProfile(time.Millisecond * 10)
tests.S(t).ExpectNotNil(err)
profile, err := s.runCPUProfile("15ms")
tests.S(t).ExpectEquals(err, ErrCPUProfilingInProgress)
tests.S(t).ExpectEquals(profile, "")
}
}

0 comments on commit cd194e9

Please sign in to comment.