tests: add wait function in place of sleep

Add a function to wait for a specific condition instead of sleeping for a fixed
number of seconds.
This commit is contained in:
Simone Gotti 2019-08-30 10:03:22 +02:00
parent 409033c9a8
commit 6d1f159500
2 changed files with 68 additions and 5 deletions

View File

@ -526,6 +526,23 @@ func NewTestGitea(t *testing.T, logger *zap.Logger, dir, dockerBridgeAddress str
return tgitea, nil
}
type CheckFunc func() (bool, error)
func Wait(timeout time.Duration, f CheckFunc) error {
start := time.Now()
for time.Now().Add(-timeout).Before(start) {
ok, err := f()
if err != nil {
return err
}
if ok {
return nil
}
time.Sleep(sleepInterval)
}
return fmt.Errorf("timeout")
}
func testFreeTCPPort(port int) error {
ln, err := net.Listen("tcp", fmt.Sprintf("localhost:%d", port))
if err != nil {

View File

@ -606,8 +606,22 @@ func TestPush(t *testing.T) {
push(t, tt.config, giteaRepo.CloneURL, giteaToken)
// TODO(sgotti) add an util to wait for a run phase
time.Sleep(10 * time.Second)
_ = testutil.Wait(30*time.Second, func() (bool, error) {
runs, _, err := gwClient.GetRuns(ctx, nil, nil, []string{path.Join("/project", project.ID)}, nil, "", 0, false)
if err != nil {
return false, nil
}
if len(runs) == 0 {
return false, nil
}
run := runs[0]
if run.Phase != rstypes.RunPhaseFinished {
return false, nil
}
return true, nil
})
runs, _, err := gwClient.GetRuns(ctx, nil, nil, []string{path.Join("/project", project.ID)}, nil, "", 0, false)
if err != nil {
@ -634,6 +648,7 @@ func TestPush(t *testing.T) {
}
}
}
})
}
}
@ -777,8 +792,23 @@ func TestDirectRun(t *testing.T) {
directRun(t, dir, config, c.Gateway.APIExposedURL, token, tt.args...)
// TODO(sgotti) add an util to wait for a run phase
time.Sleep(10 * time.Second)
_ = testutil.Wait(30*time.Second, func() (bool, error) {
runs, _, err := gwClient.GetRuns(ctx, nil, nil, []string{path.Join("/user", user.ID)}, nil, "", 0, false)
if err != nil {
return false, nil
}
if len(runs) != 1 {
return false, nil
}
run := runs[0]
if run.Phase != rstypes.RunPhaseFinished {
return false, nil
}
return true, nil
})
runs, _, err := gwClient.GetRuns(ctx, nil, nil, []string{path.Join("/user", user.ID)}, nil, "", 0, false)
if err != nil {
@ -916,7 +946,23 @@ func TestDirectRunVariables(t *testing.T) {
directRun(t, dir, config, c.Gateway.APIExposedURL, token, tt.args...)
// TODO(sgotti) add an util to wait for a run phase
time.Sleep(10 * time.Second)
_ = testutil.Wait(30*time.Second, func() (bool, error) {
runs, _, err := gwClient.GetRuns(ctx, nil, nil, []string{path.Join("/user", user.ID)}, nil, "", 0, false)
if err != nil {
return false, nil
}
if len(runs) != 1 {
return false, nil
}
run := runs[0]
if run.Phase != rstypes.RunPhaseFinished {
return false, nil
}
return true, nil
})
runs, _, err := gwClient.GetRuns(ctx, nil, nil, []string{path.Join("/user", user.ID)}, nil, "", 0, false)
if err != nil {