| // Copyright 2015 The Vanadium Authors. All rights reserved. |
| // Use of this source code is governed by a BSD-style |
| // license that can be found in the LICENSE file. |
| |
| package util_test |
| |
| import ( |
| "errors" |
| "testing" |
| "time" |
| |
| "v.io/v23/context" |
| "v.io/v23/verror" |
| "v.io/x/sensorlog/internal/util" |
| ) |
| |
| var ( |
| errFoo = errors.New("errFoo") |
| errBar = errors.New("errBar") |
| ) |
| |
| func TestAsyncRun(t *testing.T) { |
| wait1 := util.AsyncRun(func() error { |
| time.Sleep(200 * time.Microsecond) |
| return nil |
| }, func(err error) { |
| t.Errorf("unexpected callback with error: %v", err) |
| }) |
| |
| var ecb2 error |
| wait2 := util.AsyncRun(func() error { |
| time.Sleep(100 * time.Microsecond) |
| return errFoo |
| }, func(err error) { |
| ecb2 = err |
| }) |
| |
| if wgot, want := wait1(), error(nil); wgot != want { |
| t.Errorf("wait1 unexpected error: got %v, want %v", wgot, want) |
| } |
| if wgot, cbgot, want := wait2(), ecb2, errFoo; wgot != want || cbgot != want { |
| t.Errorf("wait2 unexpected error: wait got %v, cb got %v, want %v", wgot, cbgot, want) |
| } |
| } |
| |
| func TestAsyncRunNoCallback(t *testing.T) { |
| wait1 := util.AsyncRun(func() error { |
| time.Sleep(200 * time.Microsecond) |
| return nil |
| }, nil) |
| |
| wait2 := util.AsyncRun(func() error { |
| time.Sleep(100 * time.Microsecond) |
| return errBar |
| }, nil) |
| |
| if wgot, want := wait1(), error(nil); wgot != want { |
| t.Errorf("wait1 unexpected error: got %v, want %v", wgot, want) |
| } |
| if wgot, want := wait2(), errBar; wgot != want { |
| t.Errorf("wait2 unexpected error: got %v, want %v", wgot, want) |
| } |
| } |
| |
| func TestAsyncRunIgnoreErrCancelled(t *testing.T) { |
| ctx, cancel := context.RootContext() |
| |
| wait1 := util.AsyncRun(func() error { |
| <-ctx.Done() |
| return verror.New(verror.ErrCanceled, ctx) |
| }, func(err error) { |
| t.Errorf("unexpected callback with error: %v", err) |
| }) |
| |
| cancel() |
| |
| if wgot, want := wait1(), error(nil); wgot != want { |
| t.Errorf("wait1 unexpected error: got %v, want %v", wgot, want) |
| } |
| } |