@@ -2,8 +2,11 @@ package parallelisation
22
33import (
44 "context"
5+ "errors"
56 "testing"
7+ "time"
68
9+ "github.com/stretchr/testify/assert"
710 "github.com/stretchr/testify/require"
811
912 "github.com/ARM-software/golang-utils/utils/commonerrors"
@@ -49,3 +52,37 @@ func TestForEach(t *testing.T) {
4952 require .NoError (t , ForEach (context .Background (), WithOptions (Workers (5 ), JoinErrors ), WrapCancelToContextualFunc (cancelFunc ), WrapCancelToContextualFunc (cancelFunc ), WrapCancelToContextualFunc (cancelFunc )))
5053 })
5154}
55+
56+ func TestDetermineContextError (t * testing.T ) {
57+ t .Run ("normal" , func (t * testing.T ) {
58+ require .NoError (t , DetermineContextError (context .Background ()))
59+ })
60+ t .Run ("cancellation" , func (t * testing.T ) {
61+ ctx , cancel := context .WithTimeout (context .Background (), 5 * time .Second )
62+ defer cancel ()
63+ require .NoError (t , DetermineContextError (ctx ))
64+ cancel ()
65+ err := DetermineContextError (ctx )
66+ errortest .AssertError (t , err , commonerrors .ErrTimeout , commonerrors .ErrCancelled )
67+ })
68+ t .Run ("cancellation with cause" , func (t * testing.T ) {
69+ cause := errors .New ("a cause" )
70+ ctx , cancel := context .WithCancelCause (context .Background ())
71+ defer cancel (cause )
72+ require .NoError (t , DetermineContextError (ctx ))
73+ cancel (cause )
74+ err := DetermineContextError (ctx )
75+ errortest .AssertError (t , err , commonerrors .ErrTimeout , commonerrors .ErrCancelled )
76+ errortest .AssertErrorDescription (t , err , cause .Error ())
77+ })
78+ t .Run ("cancellation with timeout cause" , func (t * testing.T ) {
79+ cause := errors .New ("a cause" )
80+ ctx , cancel := context .WithTimeoutCause (context .Background (), 5 * time .Second , cause )
81+ defer cancel ()
82+ require .NoError (t , DetermineContextError (ctx ))
83+ cancel ()
84+ err := DetermineContextError (ctx )
85+ errortest .RequireError (t , err , commonerrors .ErrTimeout , commonerrors .ErrCancelled )
86+ assert .NotContains (t , err .Error (), cause .Error ()) // the timeout did not take effect and a cancellation was performed instead so the cause is not passed through
87+ })
88+ }
0 commit comments