diff --git a/adb_test.go b/adb_test.go index 1d2c446..9167f09 100644 --- a/adb_test.go +++ b/adb_test.go @@ -1,6 +1,8 @@ package adb import ( + "context" + "errors" "net" "reflect" "testing" @@ -238,6 +240,27 @@ func TestTapSequence_GetLength(t *testing.T) { } } +func TestSequenceSleep_PlayHonorsContextCancellation(t *testing.T) { + ctx, cancel := context.WithCancel(context.Background()) + cancel() + + start := time.Now() + err := (SequenceSleep{Duration: time.Second, Type: SeqSleep}).Play(Device{}, ctx) + if !errors.Is(err, context.Canceled) { + t.Fatalf("SequenceSleep.Play() error = %v, want context.Canceled", err) + } + if elapsed := time.Since(start); elapsed > 100*time.Millisecond { + t.Fatalf("SequenceSleep.Play() took %v after cancellation", elapsed) + } +} + +func TestSequenceSleep_PlayCompletesAfterDuration(t *testing.T) { + err := (SequenceSleep{Duration: time.Millisecond, Type: SeqSleep}).Play(Device{}, context.Background()) + if err != nil { + t.Fatalf("SequenceSleep.Play() error = %v, want nil", err) + } +} + func TestTapSequence_JSONRoundTrip(t *testing.T) { now := time.UnixMilli(1700000000000) original := TapSequence{ diff --git a/capture.go b/capture.go index cf773d8..3a14dc1 100644 --- a/capture.go +++ b/capture.go @@ -71,9 +71,15 @@ type SequenceSleep struct { } func (s SequenceSleep) Play(d Device, ctx context.Context) error { - // TODO check if context is expired - time.Sleep(s.Duration) - return nil + timer := time.NewTimer(s.Duration) + defer timer.Stop() + + select { + case <-ctx.Done(): + return ctx.Err() + case <-timer.C: + return nil + } } func (s SequenceSleep) Length() time.Duration {