@@ -2121,6 +2121,59 @@ func testReturnErrorForUnexpectedDirectoryLayout(t *testing.T, exporter packages
21212121}
21222122}
21232123
2124+ func TestReturnErrorForContextCanceled (t * testing.T ) {
2125+ packagestest .TestAll (t , testReturnErrorForContextCanceled )
2126+ }
2127+
2128+ type slowContext struct {
2129+ context.Context
2130+ delay time.Duration
2131+ }
2132+
2133+ func (ctx slowContext ) Err () error {
2134+ time .Sleep (ctx .delay )
2135+ return ctx .Context .Err ()
2136+ }
2137+
2138+ func testReturnErrorForContextCanceled (t * testing.T , exporter packagestest.Exporter ) {
2139+ exported := packagestest .Export (t , exporter , []packagestest.Module {{
2140+ Name : "golang.org/fake" ,
2141+ Files : map [string ]interface {}{
2142+ "a/a.go" : `package a; const A = "a" ` ,
2143+ }}})
2144+ defer exported .Cleanup ()
2145+
2146+ ctx , cancel := context .WithCancel (context .Background ())
2147+ // we need to slow a Load function to be able to test ctx cancellation
2148+ // in the middle of loading packages
2149+ slowCtx := slowContext {ctx , 10 * time .Millisecond }
2150+
2151+ go func () {
2152+ // should have delay before canceling
2153+ // otherwise returns early with 'signal killed'
2154+ time .Sleep (8 * time .Millisecond )
2155+ cancel ()
2156+ }()
2157+
2158+ exported .Config .Mode = packages .LoadAllSyntax
2159+ exported .Config .Context = slowCtx
2160+ pkgs , err := packages .Load (exported .Config , "golang.org/fake/a" )
2161+ if err != nil {
2162+ t .Fatal (err )
2163+ }
2164+ // flaky test, because of timings
2165+ // sometimes Load returns early with err "signal: killed" when tested under Module
2166+ want := packages .ContextCancelError
2167+ if len (pkgs ) > 0 {
2168+ errKind := pkgs [0 ].Errors [0 ].Kind
2169+ if want != errKind {
2170+ t .Fatalf ("want error kind: %v, got: %v" , want , errKind )
2171+ }
2172+ } else {
2173+ t .Fatal ("unexpected no packages returned" )
2174+ }
2175+ }
2176+
21242177func TestMissingDependency (t * testing.T ) { packagestest .TestAll (t , testMissingDependency ) }
21252178func testMissingDependency (t * testing.T , exporter packagestest.Exporter ) {
21262179exported := packagestest .Export (t , exporter , []packagestest.Module {{
0 commit comments