@@ -23,7 +23,7 @@ type ExpensiveView struct {
2323 Err chan error
2424}
2525
26- func NewExpensiveView (shouldErr bool ) * ExpensiveView {
26+ func NewExpensiveView (shouldErr bool , sleepFor time. Duration ) * ExpensiveView {
2727 errCh := make (chan error )
2828 dataCh := make (chan ExpensiveViewData )
2929
@@ -35,7 +35,7 @@ func NewExpensiveView(shouldErr bool) *ExpensiveView {
3535
3636 // do data fetching and either write to
3737 // one thing or the other
38- time .Sleep (1 * time . Millisecond )
38+ time .Sleep (sleepFor )
3939 if shouldErr {
4040 errCh <- fmt .Errorf ("fetch failed" )
4141 } else {
@@ -46,8 +46,10 @@ func NewExpensiveView(shouldErr bool) *ExpensiveView {
4646 return & ExpensiveView {Data : dataCh , Err : errCh }
4747}
4848
49- func (v * ExpensiveView ) Renderable (_ context.Context ) (Renderable , error ) {
49+ func (v * ExpensiveView ) Renderable (ctx context.Context ) (Renderable , error ) {
5050 select {
51+ case <- ctx .Done ():
52+ return nil , ctx .Err ()
5153 case err := <- v .Err :
5254 return nil , err
5355 case data := <- v .Data :
@@ -57,13 +59,25 @@ func (v *ExpensiveView) Renderable(_ context.Context) (Renderable, error) {
5759
5860func TestViewWithChannels (t * testing.T ) {
5961 t .Run ("successful" , func (t * testing.T ) {
60- html , err := Render (context .Background (), NewExpensiveView (false ))
62+ html , err := Render (context .Background (), NewExpensiveView (false , 1 * time . Millisecond ))
6163 assert .NoError (t , err )
6264 assert .Equal (t , template .HTML (`hi success` ), html )
6365 })
6466
6567 t .Run ("failed" , func (t * testing.T ) {
66- _ , err := Render (context .Background (), NewExpensiveView (true ))
68+ _ , err := Render (context .Background (), NewExpensiveView (true , 1 * time . Millisecond ))
6769 assert .Error (t , err )
6870 })
71+
72+ t .Run ("context timed out" , func (t * testing.T ) {
73+ ctx , _ := context .WithTimeout (context .Background (), 1 * time .Millisecond )
74+ _ , err := Render (ctx , NewExpensiveView (false , 2 * time .Millisecond ))
75+ assert .Error (t , err )
76+ })
77+
78+ t .Run ("context timeout not reached" , func (t * testing.T ) {
79+ ctx , _ := context .WithTimeout (context .Background (), 5 * time .Millisecond )
80+ _ , err := Render (ctx , NewExpensiveView (false , 2 * time .Millisecond ))
81+ assert .NoError (t , err )
82+ })
6983}
0 commit comments