diff --git a/.golangci.yml b/.golangci.yml index c51dd43a7d..e8a0311936 100644 --- a/.golangci.yml +++ b/.golangci.yml @@ -41,6 +41,7 @@ linters: - staticcheck - unconvert - unused + - usetesting - wastedassign - whitespace settings: @@ -88,6 +89,9 @@ linters: require-explanation: true require-specific: true allow-unused: false + usetesting: + context-background: true + context-todo: true exclusions: generated: lax presets: diff --git a/cmd/buf/buf_test.go b/cmd/buf/buf_test.go index da53c74a00..3490dcc8a7 100644 --- a/cmd/buf/buf_test.go +++ b/cmd/buf/buf_test.go @@ -16,7 +16,6 @@ package main import ( "bytes" - "context" "encoding/json" "errors" "fmt" @@ -1356,7 +1355,7 @@ func TestCheckLsBreakingRulesFromConfigExceptDeprecated(t *testing.T) { // Do not need any custom lint/breaking plugins here. client, err := bufcheck.NewClient(slogtestext.NewLogger(t)) require.NoError(t, err) - allRules, err := client.AllRules(context.Background(), check.RuleTypeBreaking, version) + allRules, err := client.AllRules(t.Context(), check.RuleTypeBreaking, version) require.NoError(t, err) allPackageIDs := make([]string, 0, len(allRules)) for _, rule := range allRules { diff --git a/cmd/buf/internal/command/alpha/protoc/protoc_test.go b/cmd/buf/internal/command/alpha/protoc/protoc_test.go index 246556a0c5..44e4ea4f28 100644 --- a/cmd/buf/internal/command/alpha/protoc/protoc_test.go +++ b/cmd/buf/internal/command/alpha/protoc/protoc_test.go @@ -16,7 +16,6 @@ package protoc import ( "bytes" - "context" "fmt" "os" "path/filepath" @@ -222,7 +221,7 @@ func testInsertionPointMixedPathsSuccess(t *testing.T, receiverOut string, write fmt.Sprintf("--%s_out=%s", "insertion-point-writer", writerOut), } err := prototesting.RunProtoc( - context.Background(), + t.Context(), []string{dirPath}, filePaths, false, @@ -338,7 +337,7 @@ func testCompareGeneratedStubs( ) require.NoError(t, err) diff, err := storage.DiffBytes( - context.Background(), + t.Context(), actualReadWriteBucket, bufReadWriteBucket, ) @@ -418,7 +417,7 @@ func testCompareGeneratedStubsArchive( require.NoError(t, err) actualReadWriteBucket := storagemem.NewReadWriteBucket() err = storagearchive.Unzip( - context.Background(), + t.Context(), bytes.NewReader(actualData), int64(len(actualData)), actualReadWriteBucket, @@ -428,14 +427,14 @@ func testCompareGeneratedStubsArchive( require.NoError(t, err) bufReadWriteBucket := storagemem.NewReadWriteBucket() err = storagearchive.Unzip( - context.Background(), + t.Context(), bytes.NewReader(bufData), int64(len(bufData)), bufReadWriteBucket, ) require.NoError(t, err) diff, err := storage.DiffBytes( - context.Background(), + t.Context(), actualReadWriteBucket, bufReadWriteBucket, ) diff --git a/cmd/buf/internal/command/config/configmigrate/configmigrate_test.go b/cmd/buf/internal/command/config/configmigrate/configmigrate_test.go index a50ee33289..247730b160 100644 --- a/cmd/buf/internal/command/config/configmigrate/configmigrate_test.go +++ b/cmd/buf/internal/command/config/configmigrate/configmigrate_test.go @@ -16,7 +16,6 @@ package configmigrate import ( "bytes" - "context" "path/filepath" "testing" @@ -54,7 +53,7 @@ func testCompareConfigMigrate(t *testing.T, dir string, expectCode int, expectSt tempDir := t.TempDir() tempBucket, err := storageosProvider.NewReadWriteBucket(tempDir) require.NoError(t, err) - ctx := context.Background() + ctx := t.Context() _, err = storage.Copy(ctx, inputBucket, tempBucket) require.NoError(t, err) var outputBucket storage.ReadWriteBucket diff --git a/cmd/buf/internal/command/generate/generate_test.go b/cmd/buf/internal/command/generate/generate_test.go index 98f0cdcf21..3e5a5e85a5 100644 --- a/cmd/buf/internal/command/generate/generate_test.go +++ b/cmd/buf/internal/command/generate/generate_test.go @@ -165,7 +165,7 @@ func TestGenerateV2LocalPluginBasic(t *testing.T) { actual, err := storageos.NewProvider().NewReadWriteBucket(tempDirPath) require.NoError(t, err) - diff, err := storage.DiffBytes(context.Background(), expected, actual) + diff, err := storage.DiffBytes(t.Context(), expected, actual) require.NoError(t, err) require.Empty(t, string(diff)) } @@ -188,7 +188,7 @@ func TestGenerateV2LocalPluginTypes(t *testing.T) { actual, err := storageos.NewProvider().NewReadWriteBucket(tempDirPath) require.NoError(t, err) - diff, err := storage.DiffBytes(context.Background(), expected, actual) + diff, err := storage.DiffBytes(t.Context(), expected, actual) require.NoError(t, err) require.Empty(t, string(diff)) } @@ -657,7 +657,7 @@ func testGenerateInsertionPoint( ) { storageosProvider := storageos.NewProvider() tempDir, readWriteBucket := internaltesting.CopyReadBucketToTempDir( - context.Background(), + t.Context(), t, storageosProvider, storagemem.NewReadWriteBucket(), @@ -672,7 +672,7 @@ func testGenerateInsertionPoint( ) expectedOutput, err := storageosProvider.NewReadWriteBucket(expectedOutputPath) require.NoError(t, err) - diff, err := storage.DiffBytes(context.Background(), expectedOutput, readWriteBucket) + diff, err := storage.DiffBytes(t.Context(), expectedOutput, readWriteBucket) require.NoError(t, err) require.Empty(t, string(diff)) } @@ -802,7 +802,7 @@ func testCompareGeneratedStubs( ) require.NoError(t, err) diff, err := storage.DiffBytes( - context.Background(), + t.Context(), actualReadWriteBucket, bufReadWriteBucket, transformGolangProtocVersionToUnknown(t), @@ -864,7 +864,7 @@ func testCompareGeneratedStubsArchive( require.NoError(t, err) actualReadWriteBucket := storagemem.NewReadWriteBucket() err = storagearchive.Unzip( - context.Background(), + t.Context(), bytes.NewReader(actualData), int64(len(actualData)), actualReadWriteBucket, @@ -874,14 +874,14 @@ func testCompareGeneratedStubsArchive( require.NoError(t, err) bufReadWriteBucket := storagemem.NewReadWriteBucket() err = storagearchive.Unzip( - context.Background(), + t.Context(), bytes.NewReader(bufData), int64(len(bufData)), bufReadWriteBucket, ) require.NoError(t, err) diff, err := storage.DiffBytes( - context.Background(), + t.Context(), actualReadWriteBucket, bufReadWriteBucket, transformGolangProtocVersionToUnknown(t), @@ -938,7 +938,7 @@ func testGenerateDeleteOutsWithArgAndConfig( }, ) } - ctx := context.Background() + ctx := t.Context() tmpDirPath := t.TempDir() storageBucket, err := storageos.NewProvider().NewReadWriteBucket(tmpDirPath) require.NoError(t, err) diff --git a/cmd/buf/workspace_test.go b/cmd/buf/workspace_test.go index de08aed89c..044e55f258 100644 --- a/cmd/buf/workspace_test.go +++ b/cmd/buf/workspace_test.go @@ -16,7 +16,6 @@ package main import ( "bytes" - "context" "fmt" "os" "path/filepath" @@ -1716,7 +1715,7 @@ func createZipFromDir(t *testing.T, rootPath string, archiveName string) string buffer := bytes.NewBuffer(nil) require.NoError(t, storagearchive.Zip( - context.Background(), + t.Context(), testdataBucket, buffer, true, @@ -1728,7 +1727,7 @@ func createZipFromDir(t *testing.T, rootPath string, archiveName string) string ) require.NoError(t, err) require.NoError(t, storage.PutPath( - context.Background(), + t.Context(), zipBucket, archiveName, buffer.Bytes(), diff --git a/cmd/protoc-gen-buf-lint/lint_test.go b/cmd/protoc-gen-buf-lint/lint_test.go index 7a59d8b0de..a09028c8d3 100644 --- a/cmd/protoc-gen-buf-lint/lint_test.go +++ b/cmd/protoc-gen-buf-lint/lint_test.go @@ -301,7 +301,7 @@ func testRunHandlerFunc( exitCode := app.GetExitCode( protoplugin.Run( - context.Background(), + t.Context(), protoplugin.Env{ Args: nil, Stdin: stdin, @@ -331,7 +331,7 @@ func testBuildRequest( fileToGenerate []string, ) protoplugin.Request { fileDescriptorSet, err := prototesting.GetProtocFileDescriptorSet( - context.Background(), + t.Context(), []string{root}, realFilePaths, true, diff --git a/private/buf/bufcurl/invoker_test.go b/private/buf/bufcurl/invoker_test.go index 63f44a9230..c0de6032f5 100644 --- a/private/buf/bufcurl/invoker_test.go +++ b/private/buf/bufcurl/invoker_test.go @@ -15,7 +15,6 @@ package bufcurl import ( - "context" "os" "testing" @@ -32,7 +31,7 @@ func TestCountUnrecognized(t *testing.T) { Resolver: &protocompile.SourceResolver{ ImportPaths: []string{"./testdata"}, }, - }).Compile(context.Background(), "test.proto") + }).Compile(t.Context(), "test.proto") require.NoError(t, err) msgType, err := descriptors.AsResolver().FindMessageByName("foo.bar.Message") require.NoError(t, err) diff --git a/private/buf/buffetch/buffetch_test.go b/private/buf/buffetch/buffetch_test.go index b5ad996c0d..4dbd7c29d9 100644 --- a/private/buf/buffetch/buffetch_test.go +++ b/private/buf/buffetch/buffetch_test.go @@ -15,7 +15,6 @@ package buffetch import ( - "context" "io" "log/slog" "path/filepath" @@ -106,7 +105,7 @@ func testRoundTripLocalFile( reader := testNewFetchReader(logger) writer := testNewFetchWriter(logger) - ctx := context.Background() + ctx := t.Context() container := app.NewContainer(nil, nil, nil, nil) tmpDir := t.TempDir() diff --git a/private/buf/buffetch/internal/reader_test.go b/private/buf/buffetch/internal/reader_test.go index abce1e7ecf..fe88f4f405 100644 --- a/private/buf/buffetch/internal/reader_test.go +++ b/private/buf/buffetch/internal/reader_test.go @@ -31,7 +31,7 @@ import ( func TestGetReadBucketCloserForBucketNoTerminateFileName(t *testing.T) { t.Parallel() - ctx := context.Background() + ctx := t.Context() inputBucket, err := storageos.NewProvider().NewReadWriteBucket("testdata/bufyaml/one/two") require.NoError(t, err) readBucketCloser, bucketTargeting, err := getReadBucketCloserForBucket( @@ -50,7 +50,7 @@ func TestGetReadBucketCloserForBucketNoTerminateFileName(t *testing.T) { func TestGetReadBucketCloserTerminateFileName(t *testing.T) { t.Parallel() - ctx := context.Background() + ctx := t.Context() inputBucket, err := storageos.NewProvider().NewReadWriteBucket("testdata/bufyaml/one/two") require.NoError(t, err) readBucketCloser, bucketTargeting, err := getReadBucketCloserForBucket( @@ -72,7 +72,7 @@ func TestGetReadBucketCloserTerminateFileName(t *testing.T) { func TestGetReadBucketCloserForBucketNoSubDirPath(t *testing.T) { t.Parallel() - ctx := context.Background() + ctx := t.Context() inputBucket, err := storageos.NewProvider().NewReadWriteBucket("testdata/bufyaml/one/two/three/four/five") require.NoError(t, err) readBucketCloser, bucketTargeting, err := getReadBucketCloserForBucket( @@ -94,7 +94,7 @@ func TestGetReadBucketCloserForBucketNoSubDirPath(t *testing.T) { func TestGetReadBucketCloserForBucketAbs(t *testing.T) { t.Parallel() - ctx := context.Background() + ctx := t.Context() absDirPath, err := filepath.Abs(".") require.NoError(t, err) inputBucket, err := storageos.NewProvider().NewReadWriteBucket(normalpath.Join(absDirPath, "testdata/bufyaml/one/two")) @@ -118,7 +118,7 @@ func TestGetReadBucketCloserForBucketAbs(t *testing.T) { func TestGetReadWriteBucketForOSNoTerminateFileName(t *testing.T) { t.Parallel() - ctx := context.Background() + ctx := t.Context() readWriteBucket, bucketTargeting, err := getReadWriteBucketForOS( ctx, slogtestext.NewLogger(t), @@ -138,7 +138,7 @@ func TestGetReadWriteBucketForOSNoTerminateFileName(t *testing.T) { func TestGetReadWriteBucketForOSTerminateFileName(t *testing.T) { t.Parallel() - ctx := context.Background() + ctx := t.Context() readWriteBucket, bucketTargeting, err := getReadWriteBucketForOS( ctx, slogtestext.NewLogger(t), @@ -162,7 +162,7 @@ func TestGetReadWriteBucketForOSTerminateFileName(t *testing.T) { func TestGetReadWriteBucketForOSParentPwd(t *testing.T) { // Cannot be parallel since we chdir. - ctx := context.Background() + ctx := t.Context() pwd, err := osext.Getwd() require.NoError(t, err) require.NoError(t, osext.Chdir(normalpath.Unnormalize(normalpath.Join(pwd, "testdata/bufyaml/one/two/three/four")))) @@ -196,7 +196,7 @@ func TestGetReadWriteBucketForOSParentPwd(t *testing.T) { func TestGetReadWriteBucketForOSAbsPwd(t *testing.T) { // Cannot be parallel since we chdir. - ctx := context.Background() + ctx := t.Context() absDirPath, err := filepath.Abs(".") require.NoError(t, err) pwd, err := osext.Getwd() @@ -231,7 +231,7 @@ func TestGetReadWriteBucketForOSAbsPwd(t *testing.T) { func TestGetReadBucketCloserForOSProtoFileNoWorkspaceTerminateFileName(t *testing.T) { t.Parallel() - ctx := context.Background() + ctx := t.Context() readBucketCloser, bucketTargeting, err := getReadBucketCloserForOSProtoFile( ctx, slogtestext.NewLogger(t), @@ -252,7 +252,7 @@ func TestGetReadBucketCloserForOSProtoFileNoWorkspaceTerminateFileName(t *testin func TestGetReadBucketCloserForOSProtoFileTerminateFileName(t *testing.T) { t.Parallel() - ctx := context.Background() + ctx := t.Context() readBucketCloser, bucketTargeting, err := getReadBucketCloserForOSProtoFile( ctx, slogtestext.NewLogger(t), @@ -277,7 +277,7 @@ func TestGetReadBucketCloserForOSProtoFileTerminateFileName(t *testing.T) { func TestGetReadBucketCloserForOSProtoFileParentPwd(t *testing.T) { // Cannot be parallel since we chdir. - ctx := context.Background() + ctx := t.Context() pwd, err := osext.Getwd() require.NoError(t, err) require.NoError(t, osext.Chdir(normalpath.Unnormalize(normalpath.Join(pwd, "testdata/bufyaml/one/two/three/four")))) @@ -312,7 +312,7 @@ func TestGetReadBucketCloserForOSProtoFileParentPwd(t *testing.T) { func TestGetReadBucketCloserForOSProtoFileAbsPwd(t *testing.T) { // Cannot be parallel since we chdir. - ctx := context.Background() + ctx := t.Context() absDirPath, err := filepath.Abs(".") require.NoError(t, err) pwd, err := osext.Getwd() @@ -348,7 +348,7 @@ func TestGetReadBucketCloserForOSProtoFileAbsPwd(t *testing.T) { func TestGetReadBucketCloserForOSProtoFileNoBufYAMLTerminateFileName(t *testing.T) { t.Parallel() - ctx := context.Background() + ctx := t.Context() readBucketCloser, bucketTargeting, err := getReadBucketCloserForOSProtoFile( ctx, slogtestext.NewLogger(t), @@ -370,7 +370,7 @@ func TestGetReadBucketCloserForOSProtoFileNoBufYAMLTerminateFileName(t *testing. func TestGetReadBucketCloserForOSProtoFileNoBufYAMLParentPwd(t *testing.T) { // Cannot be parallel since we chdir. - ctx := context.Background() + ctx := t.Context() pwd, err := osext.Getwd() require.NoError(t, err) require.NoError(t, osext.Chdir(normalpath.Unnormalize(normalpath.Join(pwd, "testdata/nobufyaml/one/two/three/four")))) @@ -406,7 +406,7 @@ func TestGetReadBucketCloserForOSProtoFileNoBufYAMLAbsPwd(t *testing.T) { // Cannot be parallel since we chdir. t.Skip() - ctx := context.Background() + ctx := t.Context() absDirPath, err := filepath.Abs(".") require.NoError(t, err) pwd, err := osext.Getwd() diff --git a/private/buf/buffetch/ref_parser_test.go b/private/buf/buffetch/ref_parser_test.go index 5ec8bd2bf5..efa5c8bfdb 100644 --- a/private/buf/buffetch/ref_parser_test.go +++ b/private/buf/buffetch/ref_parser_test.go @@ -15,7 +15,6 @@ package buffetch import ( - "context" "fmt" "path/filepath" "testing" @@ -1432,7 +1431,7 @@ func testGetParsedRef( value string, ) { parsedRef, err := newRefParser(slogtestext.NewLogger(t)).getParsedRef( - context.Background(), + t.Context(), value, allFormats, ) @@ -1457,7 +1456,7 @@ func testGetParsedDirOrProtoFileRef( value string, ) { parsedRef, err := newDirOrProtoFileRefParser(slogtestext.NewLogger(t)).getParsedRef( - context.Background(), + t.Context(), value, dirOrProtoFileFormats, ) diff --git a/private/buf/bufformat/formatter_test.go b/private/buf/bufformat/formatter_test.go index f65ef860cb..dea35ce915 100644 --- a/private/buf/bufformat/formatter_test.go +++ b/private/buf/bufformat/formatter_test.go @@ -15,7 +15,6 @@ package bufformat import ( - "context" "io" "strings" "testing" @@ -76,7 +75,7 @@ func testFormatHeader(t *testing.T) { func testFormatNoDiff(t *testing.T, path string) { t.Run(path, func(t *testing.T) { - ctx := context.Background() + ctx := t.Context() bucket, err := storageos.NewProvider().NewReadWriteBucket(path) require.NoError(t, err) @@ -119,7 +118,7 @@ func testFormatNoDiff(t *testing.T, path string) { func testFormatError(t *testing.T, path string, errContains string) { t.Run(path, func(t *testing.T) { - ctx := context.Background() + ctx := t.Context() bucket, err := storageos.NewProvider().NewReadWriteBucket(path) require.NoError(t, err) moduleSetBuilder := bufmodule.NewModuleSetBuilder(ctx, slogtestext.NewLogger(t), bufmodule.NopModuleDataProvider, bufmodule.NopCommitProvider) @@ -150,7 +149,7 @@ func TestFormatterWithDeprecation(t *testing.T) { func testDeprecateNoDiff(t *testing.T, name string, path string, deprecatePrefixes []string, files []string) { t.Run(name, func(t *testing.T) { - ctx := context.Background() + ctx := t.Context() bucket, err := storageos.NewProvider().NewReadWriteBucket(path) require.NoError(t, err) var opts []FormatOption @@ -194,7 +193,7 @@ func testDeprecateNoDiff(t *testing.T, name string, path string, deprecatePrefix func TestFormatBucketNoTypesMatchedError(t *testing.T) { t.Parallel() - ctx := context.Background() + ctx := t.Context() bucket, err := storageos.NewProvider().NewReadWriteBucket("testdata/deprecate") require.NoError(t, err) // Use a prefix that won't match anything in the deprecate testdata diff --git a/private/buf/bufprotoc/bufprotoc_test.go b/private/buf/bufprotoc/bufprotoc_test.go index 730d3751de..0a9c79165e 100644 --- a/private/buf/bufprotoc/bufprotoc_test.go +++ b/private/buf/bufprotoc/bufprotoc_test.go @@ -15,7 +15,6 @@ package bufprotoc import ( - "context" "testing" "github.com/bufbuild/buf/private/pkg/slogtestext" @@ -26,7 +25,7 @@ import ( func TestNewModuleSetForProtoc(t *testing.T) { t.Parallel() - ctx := context.Background() + ctx := t.Context() moduleSet, err := NewModuleSetForProtoc( ctx, diff --git a/private/buf/buftesting/buftesting.go b/private/buf/buftesting/buftesting.go index 759c5e380b..8736cfbc6d 100644 --- a/private/buf/buftesting/buftesting.go +++ b/private/buf/buftesting/buftesting.go @@ -64,7 +64,7 @@ func GetActualProtocFileDescriptorSet( filePaths []string, ) *descriptorpb.FileDescriptorSet { fileDescriptorSet, err := prototesting.GetProtocFileDescriptorSet( - context.Background(), + t.Context(), []string{dirPath}, filePaths, includeImports, @@ -86,7 +86,7 @@ func RunActualProtoc( extraFlags ...string, ) { err := prototesting.RunProtoc( - context.Background(), + t.Context(), []string{dirPath}, filePaths, includeImports, @@ -104,7 +104,7 @@ func GetGoogleapisDirPath(t *testing.T, buftestingDirPath string) string { require.NoError( t, testArchiveReader.GetArchive( - context.Background(), + t.Context(), googleapisDirPath, "googleapis", "googleapis", @@ -119,7 +119,7 @@ func GetGoogleapisDirPath(t *testing.T, buftestingDirPath string) string { // Limit limits the number of files returned if > 0. // protoc has a fixed size for number of characters to argument list. func GetProtocFilePaths(t *testing.T, dirPath string, limit int) []string { - realFilePaths, err := GetProtocFilePathsErr(context.Background(), dirPath, limit) + realFilePaths, err := GetProtocFilePathsErr(t.Context(), dirPath, limit) require.NoError(t, err) return realFilePaths } diff --git a/private/buf/bufworkspace/workspace_test.go b/private/buf/bufworkspace/workspace_test.go index 44c945f8f7..257c2bc8ff 100644 --- a/private/buf/bufworkspace/workspace_test.go +++ b/private/buf/bufworkspace/workspace_test.go @@ -46,7 +46,7 @@ func TestBasicV2(t *testing.T) { } func testBasic(t *testing.T, subDirPath string, isV2 bool) { - ctx := context.Background() + ctx := t.Context() // This represents some external dependencies from the BSR. workspaceProvider := testNewWorkspaceProvider( @@ -199,7 +199,7 @@ func testBasic(t *testing.T, subDirPath string, isV2 bool) { func TestUnusedDep(t *testing.T) { t.Parallel() - ctx := context.Background() + ctx := t.Context() // This represents some external dependencies from the BSR. workspaceProvider := testNewWorkspaceProvider( @@ -249,7 +249,7 @@ func TestUnusedDep(t *testing.T) { func TestDuplicatePath(t *testing.T) { t.Parallel() - ctx := context.Background() + ctx := t.Context() // This represents some external dependencies from the BSR. workspaceProvider := testNewWorkspaceProvider( @@ -329,7 +329,7 @@ func testNewWorkspaceProvider(t *testing.T, testModuleDatas ...bufmoduletesting. func requireModuleContainFileNames(t *testing.T, module bufmodule.Module, expectedFileNames ...string) { fileNamesToBeSeen := xslices.ToStructMap(expectedFileNames) - require.NoError(t, module.WalkFileInfos(context.Background(), func(fi bufmodule.FileInfo) error { + require.NoError(t, module.WalkFileInfos(t.Context(), func(fi bufmodule.FileInfo) error { path := fi.Path() if _, ok := fileNamesToBeSeen[path]; !ok { return fmt.Errorf("module has unexpected file: %s", path) diff --git a/private/bufpkg/bufcheck/breaking_test.go b/private/bufpkg/bufcheck/breaking_test.go index 80b04e8cca..a4ff6a622c 100644 --- a/private/bufpkg/bufcheck/breaking_test.go +++ b/private/bufpkg/bufcheck/breaking_test.go @@ -1313,7 +1313,7 @@ func testBreaking( relDirPath string, expectedFileAnnotations ...bufanalysis.FileAnnotation, ) { - ctx, cancel := context.WithTimeout(context.Background(), 60*time.Second) // Increased timeout for Wasm runtime + ctx, cancel := context.WithTimeout(t.Context(), 60*time.Second) // Increased timeout for Wasm runtime defer cancel() logger := slogtestext.NewLogger(t) diff --git a/private/bufpkg/bufcheck/bufcheckserver/internal/bufcheckserverhandle/field_default_test.go b/private/bufpkg/bufcheck/bufcheckserver/internal/bufcheckserverhandle/field_default_test.go index c89194a402..cb21bea072 100644 --- a/private/bufpkg/bufcheck/bufcheckserver/internal/bufcheckserverhandle/field_default_test.go +++ b/private/bufpkg/bufcheck/bufcheckserver/internal/bufcheckserverhandle/field_default_test.go @@ -15,7 +15,6 @@ package bufcheckserverhandle import ( - "context" "math" "testing" @@ -119,7 +118,7 @@ func TestGetDefault(t *testing.T) { }), }, } - results, err := compiler.Compile(context.Background(), "test.proto") + results, err := compiler.Compile(t.Context(), "test.proto") require.NoError(t, err) msg := results[0].Messages().ByName("A") diff --git a/private/bufpkg/bufcheck/lint_test.go b/private/bufpkg/bufcheck/lint_test.go index ff6ec37dff..5d5e28b6ad 100644 --- a/private/bufpkg/bufcheck/lint_test.go +++ b/private/bufpkg/bufcheck/lint_test.go @@ -1526,7 +1526,7 @@ func testLintWithOptions( imageModifier func(bufimage.Image) bufimage.Image, expectedFileAnnotations ...bufanalysis.FileAnnotation, ) { - ctx, cancel := context.WithTimeout(context.Background(), 60*time.Second) // Increased timeout for Wasm runtime + ctx, cancel := context.WithTimeout(t.Context(), 60*time.Second) // Increased timeout for Wasm runtime defer cancel() baseDirPath := filepath.Join("testdata", "lint") diff --git a/private/bufpkg/bufcheck/multi_client_test.go b/private/bufpkg/bufcheck/multi_client_test.go index d6d850b648..34ef9bebbf 100644 --- a/private/bufpkg/bufcheck/multi_client_test.go +++ b/private/bufpkg/bufcheck/multi_client_test.go @@ -82,7 +82,7 @@ func TestMultiClientSimpleCacheRules(t *testing.T) { } func testMultiClientSimple(t *testing.T, cacheRules bool) { - ctx := context.Background() + ctx := t.Context() requestSpec := &checktest.RequestSpec{ Files: &checktest.ProtoFileSpec{ @@ -171,7 +171,7 @@ func TestMultiClientCannotHaveOverlappingRules(t *testing.T) { }, ) - _, _, err = multiClient.ListRulesAndCategories(context.Background()) + _, _, err = multiClient.ListRulesAndCategories(t.Context()) duplicateRuleOrCategoryError := &duplicateRuleOrCategoryError{} require.ErrorAs(t, err, &duplicateRuleOrCategoryError) require.Equal(t, []string{fieldLowerSnakeCaseRuleID}, duplicateRuleOrCategoryError.duplicateIDs()) @@ -195,7 +195,7 @@ func TestMultiClientCannotHaveOverlappingRulesWithBuiltIn(t *testing.T) { require.NoError(t, err) multiClient, err := client.getMultiClient( - context.Background(), + t.Context(), bufconfig.FileVersionV2, []bufconfig.PluginConfig{ duplicateBuiltInRulePluginConfig, @@ -206,7 +206,7 @@ func TestMultiClientCannotHaveOverlappingRulesWithBuiltIn(t *testing.T) { ) require.NoError(t, err) - _, _, err = multiClient.ListRulesAndCategories(context.Background()) + _, _, err = multiClient.ListRulesAndCategories(t.Context()) duplicateRuleOrCategoryError := &duplicateRuleOrCategoryError{} require.ErrorAs(t, err, &duplicateRuleOrCategoryError) require.Equal(t, []string{"ENUM_NO_DELETE", "PACKAGE_DIRECTORY_MATCH"}, duplicateRuleOrCategoryError.duplicateIDs()) @@ -266,7 +266,7 @@ func TestMultiClientCannotHaveOverlappingCategories(t *testing.T) { }, ) - _, _, err = multiClient.ListRulesAndCategories(context.Background()) + _, _, err = multiClient.ListRulesAndCategories(t.Context()) duplicateRuleOrCategoryError := &duplicateRuleOrCategoryError{} require.ErrorAs(t, err, &duplicateRuleOrCategoryError) require.Equal(t, []string{"FOO"}, duplicateRuleOrCategoryError.duplicateIDs()) @@ -290,7 +290,7 @@ func TestMultiClientCannotHaveOverlappingCategoriesWithBuiltIn(t *testing.T) { require.NoError(t, err) multiClient, err := client.getMultiClient( - context.Background(), + t.Context(), bufconfig.FileVersionV2, []bufconfig.PluginConfig{ duplicateBuiltInRulePluginConfig, @@ -301,7 +301,7 @@ func TestMultiClientCannotHaveOverlappingCategoriesWithBuiltIn(t *testing.T) { ) require.NoError(t, err) - _, _, err = multiClient.ListRulesAndCategories(context.Background()) + _, _, err = multiClient.ListRulesAndCategories(t.Context()) duplicateRuleOrCategoryError := &duplicateRuleOrCategoryError{} require.ErrorAs(t, err, &duplicateRuleOrCategoryError) require.Equal(t, []string{"STANDARD"}, duplicateRuleOrCategoryError.duplicateIDs()) diff --git a/private/bufpkg/bufconfig/buf_lock_file_test.go b/private/bufpkg/bufconfig/buf_lock_file_test.go index 9d6a6cec25..2daa968234 100644 --- a/private/bufpkg/bufconfig/buf_lock_file_test.go +++ b/private/bufpkg/bufconfig/buf_lock_file_test.go @@ -16,7 +16,6 @@ package bufconfig import ( "bytes" - "context" "strings" "testing" @@ -128,7 +127,7 @@ func testReadBufLockFile( inputBufLockFileData string, ) BufLockFile { bufLockFile, err := ReadBufLockFile( - context.Background(), + t.Context(), strings.NewReader(testCleanYAMLData(inputBufLockFileData)), DefaultBufLockFileName, ) diff --git a/private/bufpkg/bufconfig/buf_work_yaml_file_test.go b/private/bufpkg/bufconfig/buf_work_yaml_file_test.go index 2f944b6a5c..7ec141e5cd 100644 --- a/private/bufpkg/bufconfig/buf_work_yaml_file_test.go +++ b/private/bufpkg/bufconfig/buf_work_yaml_file_test.go @@ -15,7 +15,6 @@ package bufconfig import ( - "context" "path/filepath" "testing" @@ -25,7 +24,7 @@ import ( func TestPutAndGetBufWorkYAMLFileForPrefix(t *testing.T) { t.Parallel() - ctx := context.Background() + ctx := t.Context() bufWorkYAMLFile, err := NewBufWorkYAMLFile(FileVersionV1, []string{"foo", "bar"}) require.NoError(t, err) readWriteBucket := storagemem.NewReadWriteBucket() @@ -44,7 +43,7 @@ func TestPutAndGetBufWorkYAMLFileForPrefix(t *testing.T) { func TestReadBufWorkYAMLFileValidateVersion(t *testing.T) { t.Parallel() - ctx := context.Background() + ctx := t.Context() testcases := []struct { description string prefix string diff --git a/private/bufpkg/bufconnect/interceptors_test.go b/private/bufpkg/bufconnect/interceptors_test.go index 5a7df2017f..96b9e591c1 100644 --- a/private/bufpkg/bufconnect/interceptors_test.go +++ b/private/bufpkg/bufconnect/interceptors_test.go @@ -54,7 +54,7 @@ func TestNewAuthorizationInterceptorProvider(t *testing.T) { return nil, errors.New("error auth token") } return nil, nil - })(context.Background(), connect.NewRequest(&bytes.Buffer{})) + })(t.Context(), connect.NewRequest(&bytes.Buffer{})) assert.NoError(t, err) getMachineForName := func(app.EnvContainer, string) (netrc.Machine, error) { @@ -67,7 +67,7 @@ func TestNewAuthorizationInterceptorProvider(t *testing.T) { return nil, errors.New("error auth token") } return nil, nil - })(context.Background(), connect.NewRequest(&bytes.Buffer{})) + })(t.Context(), connect.NewRequest(&bytes.Buffer{})) assert.NoError(t, err) // testing using tokenSet over netrc tokenToAuthKey @@ -76,7 +76,7 @@ func TestNewAuthorizationInterceptorProvider(t *testing.T) { return nil, errors.New("error auth token") } return nil, nil - })(context.Background(), connect.NewRequest(&bytes.Buffer{})) + })(t.Context(), connect.NewRequest(&bytes.Buffer{})) assert.NoError(t, err) // testing using netrc tokenToAuthKey over tokenSet @@ -85,7 +85,7 @@ func TestNewAuthorizationInterceptorProvider(t *testing.T) { return nil, errors.New("error auth token") } return nil, nil - })(context.Background(), connect.NewRequest(&bytes.Buffer{})) + })(t.Context(), connect.NewRequest(&bytes.Buffer{})) assert.NoError(t, err) _, err = NewAuthorizationInterceptorProvider()("default")(func(ctx context.Context, req connect.AnyRequest) (connect.AnyResponse, error) { @@ -93,7 +93,7 @@ func TestNewAuthorizationInterceptorProvider(t *testing.T) { return nil, errors.New("error auth token") } return nil, nil - })(context.Background(), connect.NewRequest(&bytes.Buffer{})) + })(t.Context(), connect.NewRequest(&bytes.Buffer{})) assert.NoError(t, err) tokenSet, err = NewTokenProviderFromContainer(app.NewEnvContainer(map[string]string{ @@ -102,7 +102,7 @@ func TestNewAuthorizationInterceptorProvider(t *testing.T) { assert.NoError(t, err) _, err = NewAuthorizationInterceptorProvider(tokenSet)("default")(func(ctx context.Context, req connect.AnyRequest) (connect.AnyResponse, error) { return nil, errors.New("underlying cause") - })(context.Background(), connect.NewRequest(&bytes.Buffer{})) + })(t.Context(), connect.NewRequest(&bytes.Buffer{})) authErr, ok := AsAuthError(err) assert.True(t, ok) assert.Equal(t, TokenEnvKey, authErr.tokenEnvKey) @@ -119,7 +119,7 @@ func TestCLIWarningInterceptor(t *testing.T) { resp := connect.NewResponse(&bytes.Buffer{}) resp.Header().Set(CLIWarningHeaderName, base64.StdEncoding.EncodeToString([]byte(warningMessage))) return resp, nil - })(context.Background(), connect.NewRequest(&bytes.Buffer{})) + })(t.Context(), connect.NewRequest(&bytes.Buffer{})) assert.NoError(t, err) assert.Equal(t, fmt.Sprintf("WARN\t%s\n", warningMessage), buf.String()) @@ -127,7 +127,7 @@ func TestCLIWarningInterceptor(t *testing.T) { buf.Reset() _, err = NewCLIWarningInterceptor(appext.NewLoggerContainer(logger))(func(ctx context.Context, req connect.AnyRequest) (connect.AnyResponse, error) { return connect.NewResponse(&bytes.Buffer{}), nil - })(context.Background(), connect.NewRequest(&bytes.Buffer{})) + })(t.Context(), connect.NewRequest(&bytes.Buffer{})) assert.NoError(t, err) assert.Equal(t, "", buf.String()) } @@ -143,7 +143,7 @@ func TestCLIWarningInterceptorFromError(t *testing.T) { err := connect.NewError(connect.CodeInternal, errors.New("error")) err.Meta().Set(CLIWarningHeaderName, base64.StdEncoding.EncodeToString([]byte(warningMessage))) return nil, err - })(context.Background(), connect.NewRequest(&bytes.Buffer{})) + })(t.Context(), connect.NewRequest(&bytes.Buffer{})) assert.Error(t, err) assert.Equal(t, fmt.Sprintf("WARN\t%s\n", warningMessage), buf.String()) } @@ -168,7 +168,7 @@ func TestNewAugmentedConnectErrorInterceptor(t *testing.T) { _, err := NewAugmentedConnectErrorInterceptor()(func(ctx context.Context, req connect.AnyRequest) (connect.AnyResponse, error) { err := connect.NewError(connect.CodeUnknown, errors.New("405 Method Not Allowed")) return nil, err - })(context.Background(), testRequest[bytes.Buffer]{Request: connect.NewRequest(&bytes.Buffer{})}) + })(t.Context(), testRequest[bytes.Buffer]{Request: connect.NewRequest(&bytes.Buffer{})}) assert.Error(t, err) var augmentedConnectError *AugmentedConnectError assert.ErrorAs(t, err, &augmentedConnectError) diff --git a/private/bufpkg/bufimage/bufimagefuzz/bufimagefuzz_unix_test.go b/private/bufpkg/bufimage/bufimagefuzz/bufimagefuzz_unix_test.go index 45472deed7..d68c24f982 100644 --- a/private/bufpkg/bufimage/bufimagefuzz/bufimagefuzz_unix_test.go +++ b/private/bufpkg/bufimage/bufimagefuzz/bufimagefuzz_unix_test.go @@ -42,7 +42,7 @@ func TestCorpus(t *testing.T) { t.Parallel() // To focus on just one test in the corpus, put its file name here. Don't forget to revert before committing. focus := "" - ctx := context.Background() + ctx := t.Context() require.NoError(t, filepath.Walk("corpus", func(path string, info fs.FileInfo, err error) error { if err != nil { return err diff --git a/private/bufpkg/bufimage/bufimagemodify/bufimagemodify_test.go b/private/bufpkg/bufimage/bufimagemodify/bufimagemodify_test.go index 939f71c1f2..32b9568160 100644 --- a/private/bufpkg/bufimage/bufimagemodify/bufimagemodify_test.go +++ b/private/bufpkg/bufimage/bufimagemodify/bufimagemodify_test.go @@ -15,7 +15,6 @@ package bufimagemodify import ( - "context" "path/filepath" "testing" @@ -865,7 +864,7 @@ func testGetImageFromDirs( options = []bufimage.BuildImageOption{bufimage.WithExcludeSourceCodeInfo()} } image, err := bufimage.BuildImage( - context.Background(), + t.Context(), slogtestext.NewLogger(t), bufmodule.ModuleSetToModuleReadBucketWithOnlyProtoFiles(moduleSet), options..., diff --git a/private/bufpkg/bufimage/bufimagetesting/bufimagetesting_test.go b/private/bufpkg/bufimage/bufimagetesting/bufimagetesting_test.go index 7587217d53..957b05e765 100644 --- a/private/bufpkg/bufimage/bufimagetesting/bufimagetesting_test.go +++ b/private/bufpkg/bufimage/bufimagetesting/bufimagetesting_test.go @@ -15,7 +15,6 @@ package bufimagetesting import ( - "context" "fmt" "testing" @@ -864,7 +863,7 @@ func TestImageFileInfosWithOnlyTargetsAndTargetImports(t *testing.T) { fileB, } resultImageFileInfos, err := bufimage.ImageFileInfosWithOnlyTargetsAndTargetImports( - context.Background(), + t.Context(), datawkt.ReadBucket, imageFileInfos, ) diff --git a/private/bufpkg/bufimage/bufimageutil/bufimageutil_test.go b/private/bufpkg/bufimage/bufimageutil/bufimageutil_test.go index cd8127852b..3176b7e626 100644 --- a/private/bufpkg/bufimage/bufimageutil/bufimageutil_test.go +++ b/private/bufpkg/bufimage/bufimageutil/bufimageutil_test.go @@ -119,7 +119,7 @@ func TestTypes(t *testing.T) { }) t.Run("include-method-exclude-method-types", func(t *testing.T) { t.Parallel() - _, image, err := getImage(context.Background(), slogtestext.NewLogger(t), "testdata/options", bufimage.WithExcludeSourceCodeInfo()) + _, image, err := getImage(t.Context(), slogtestext.NewLogger(t), "testdata/options", bufimage.WithExcludeSourceCodeInfo()) require.NoError(t, err) _, err = FilterImage(image, WithIncludeTypes("pkg.FooService", "pkg.FooService.Do"), WithExcludeTypes("pkg.Empty")) require.Error(t, err) @@ -128,7 +128,7 @@ func TestTypes(t *testing.T) { t.Run("include-extension-exclude-extendee", func(t *testing.T) { t.Parallel() - _, image, err := getImage(context.Background(), slogtestext.NewLogger(t), "testdata/options", bufimage.WithExcludeSourceCodeInfo()) + _, image, err := getImage(t.Context(), slogtestext.NewLogger(t), "testdata/options", bufimage.WithExcludeSourceCodeInfo()) require.NoError(t, err) _, err = FilterImage(image, WithIncludeTypes("pkg.extension"), WithExcludeTypes("pkg.Foo")) require.Error(t, err) @@ -179,7 +179,7 @@ func TestNesting(t *testing.T) { t.Run("include-excluded", func(t *testing.T) { t.Parallel() - ctx := context.Background() + ctx := t.Context() _, image, err := getImage(ctx, slogtestext.NewLogger(t), "testdata/nesting", bufimage.WithExcludeSourceCodeInfo()) require.NoError(t, err) _, err = FilterImage(image, WithIncludeTypes("pkg.Foo.NestedFoo"), WithExcludeTypes("pkg.Foo")) @@ -265,7 +265,7 @@ func TestOptionImports(t *testing.T) { // Safe to filter the image concurrently as its not being modified. image, err := bufimage.BuildImage( - context.Background(), + t.Context(), slogtestext.NewLogger(t), bufmodule.ModuleSetToModuleReadBucketWithOnlyProtoFiles(moduleSet), bufimage.WithExcludeSourceCodeInfo(), @@ -275,17 +275,17 @@ func TestOptionImports(t *testing.T) { t.Run("exclude_foo", func(t *testing.T) { t.Parallel() generated, _ := runFilterImage(t, image, WithExcludeTypes("message_foo")) - checkExpectation(t, context.Background(), generated, bucket, "foo.txtar") + checkExpectation(t, t.Context(), generated, bucket, "foo.txtar") }) t.Run("exclude_foo_bar", func(t *testing.T) { t.Parallel() generated, _ := runFilterImage(t, image, WithExcludeTypes("message_foo", "message_bar")) - checkExpectation(t, context.Background(), generated, bucket, "foo_bar.txtar") + checkExpectation(t, t.Context(), generated, bucket, "foo_bar.txtar") }) t.Run("exclude_bar", func(t *testing.T) { t.Parallel() generated, _ := runFilterImage(t, image, WithIncludeTypes("pkg.Foo"), WithExcludeTypes("message_bar")) - checkExpectation(t, context.Background(), generated, bucket, "bar.txtar") + checkExpectation(t, t.Context(), generated, bucket, "bar.txtar") }) } @@ -355,7 +355,7 @@ func TestUnusedDeps(t *testing.T) { func TestTransitivePublic(t *testing.T) { t.Parallel() - ctx := context.Background() + ctx := t.Context() moduleSet, err := bufmoduletesting.NewModuleSetForPathToData( map[string][]byte{ "a.proto": []byte(`syntax = "proto3";package a;message Foo{}`), @@ -382,7 +382,7 @@ func TestTransitivePublic(t *testing.T) { func TestTypesFromMainModule(t *testing.T) { t.Parallel() - ctx := context.Background() + ctx := t.Context() moduleSet, err := bufmoduletesting.NewOmniProvider( bufmoduletesting.ModuleData{ Name: "buf.build/repo/main", @@ -427,7 +427,7 @@ func TestTypesFromMainModule(t *testing.T) { func TestMutateInPlace(t *testing.T) { t.Parallel() - ctx := context.Background() + ctx := t.Context() _, image, err := getImage(ctx, slogtestext.NewLogger(t), "testdata/options") require.NoError(t, err) @@ -469,7 +469,7 @@ func TestMutateInPlace(t *testing.T) { func TestConsecutiveFilters(t *testing.T) { t.Parallel() - ctx := context.Background() + ctx := t.Context() _, image, err := getImage(ctx, slogtestext.NewLogger(t), "testdata/options") require.NoError(t, err) @@ -538,7 +538,7 @@ func getImage(ctx context.Context, logger *slog.Logger, testdataDir string, opti } func runDiffTest(t *testing.T, testdataDir string, expectedFile string, opts ...ImageFilterOption) { - ctx := context.Background() + ctx := t.Context() bucket, image, err := getImage(ctx, slogtestext.NewLogger(t), testdataDir, bufimage.WithExcludeSourceCodeInfo()) require.NoError(t, err) generated, _ := runFilterImage(t, image, opts...) @@ -615,7 +615,7 @@ func checkExpectation(t *testing.T, ctx context.Context, actual []byte, bucket s } func runSourceCodeInfoTest(t *testing.T, typename string, expectedFile string, opts ...ImageFilterOption) { - ctx := context.Background() + ctx := t.Context() bucket, image, err := getImage(ctx, slogtestext.NewLogger(t), "testdata/sourcecodeinfo") require.NoError(t, err) @@ -751,7 +751,7 @@ func benchmarkFilterImage(b *testing.B, opts ...bufimage.BuildImageOption) { types: []string{"pkg.Foo", "pkg.FooEnum", "pkg.FooService", "pkg.FooService.Do"}, }, } - ctx := context.Background() + ctx := b.Context() for _, benchmarkCase := range benchmarkCases { _, image, err := getImage(ctx, slogtestext.NewLogger(b, slogtestext.WithLogLevel(appext.LogLevelError)), benchmarkCase.folder, opts...) require.NoError(b, err) diff --git a/private/bufpkg/bufimage/build_image_test.go b/private/bufpkg/bufimage/build_image_test.go index 0fa85f4d68..664575b955 100644 --- a/private/bufpkg/bufimage/build_image_test.go +++ b/private/bufpkg/bufimage/build_image_test.go @@ -15,7 +15,6 @@ package bufimage_test import ( - "context" "errors" "fmt" "path/filepath" @@ -212,7 +211,7 @@ func TestGoogleapis(t *testing.T) { assert.Equal(t, buftesting.NumGoogleapisFilesWithImports, len(image.Files())) // basic check to make sure there is no error at this scale - _, err = bufprotosource.NewFiles(context.Background(), image.Files(), image.Resolver()) + _, err = bufprotosource.NewFiles(t.Context(), image.Files(), image.Resolver()) assert.NoError(t, err) } @@ -300,7 +299,7 @@ func TestOptionPanic(t *testing.T) { moduleSet, err := bufmoduletesting.NewModuleSetForDirPath(filepath.Join("testdata", "optionpanic")) require.NoError(t, err) _, err = bufimage.BuildImage( - context.Background(), + t.Context(), slogtestext.NewLogger(t), bufmodule.ModuleSetToModuleReadBucketWithOnlyProtoFiles(moduleSet), ) @@ -350,7 +349,7 @@ func TestModuleTargetFiles(t *testing.T) { require.NoError(t, err) } image, err := bufimage.BuildImage( - context.Background(), + t.Context(), slogtestext.NewLogger(t), bufmodule.ModuleSetToModuleReadBucketWithOnlyProtoFiles(targetModuleSet), ) @@ -393,7 +392,7 @@ func testBuild(t *testing.T, includeSourceInfo bool, dirPath string, parallelism options = append(options, bufimage.WithNoParallelism()) } image, err := bufimage.BuildImage( - context.Background(), + t.Context(), slogtestext.NewLogger(t), bufmodule.ModuleSetToModuleReadBucketWithOnlyProtoFiles(moduleSet), options..., diff --git a/private/bufpkg/bufmodule/bufmodule_test.go b/private/bufpkg/bufmodule/bufmodule_test.go index 5a7104a565..64f564b6a4 100644 --- a/private/bufpkg/bufmodule/bufmodule_test.go +++ b/private/bufpkg/bufmodule/bufmodule_test.go @@ -15,7 +15,6 @@ package bufmodule_test import ( - "context" "errors" "testing" @@ -33,7 +32,7 @@ import ( func TestBasic(t *testing.T) { t.Parallel() - ctx := context.Background() + ctx := t.Context() // This represents some external dependencies from the BSR. bsrProvider, err := bufmoduletesting.NewOmniProvider( @@ -448,7 +447,7 @@ func TestModuleCycleError(t *testing.T) { func TestDuplicateProtoPathError(t *testing.T) { t.Parallel() - ctx := context.Background() + ctx := t.Context() moduleSet, err := bufmoduletesting.NewOmniProvider( bufmoduletesting.ModuleData{ @@ -506,7 +505,7 @@ func TestDuplicateProtoPathError(t *testing.T) { func TestNoProtoFilesError(t *testing.T) { t.Parallel() - ctx := context.Background() + ctx := t.Context() moduleSet, err := bufmoduletesting.NewOmniProvider( bufmoduletesting.ModuleData{ @@ -549,7 +548,7 @@ func TestNoProtoFilesError(t *testing.T) { func TestProtoFileTargetPath(t *testing.T) { t.Parallel() - ctx := context.Background() + ctx := t.Context() bucket := testNewBucketForPathToData( t, map[string][]byte{ @@ -676,7 +675,7 @@ func testGetDepOpaqueIDToDirect(t *testing.T, module bufmodule.Module) map[strin } func testFilePaths(t *testing.T, module bufmodule.Module, expectedFilePaths ...string) { - ctx := context.Background() + ctx := t.Context() fileInfos, err := bufmodule.GetFileInfos(ctx, module) require.NoError(t, err) require.Equal( @@ -687,7 +686,7 @@ func testFilePaths(t *testing.T, module bufmodule.Module, expectedFilePaths ...s } func testTargetFilePaths(t *testing.T, module bufmodule.Module, expectedFilePaths ...string) { - ctx := context.Background() + ctx := t.Context() fileInfos, err := bufmodule.GetTargetFileInfos(ctx, module) require.NoError(t, err) require.Equal( diff --git a/private/bufpkg/bufmodule/bufmodulecache/bufmodulecache_test.go b/private/bufpkg/bufmodule/bufmodulecache/bufmodulecache_test.go index c368dcdcae..17f3b061df 100644 --- a/private/bufpkg/bufmodule/bufmodulecache/bufmodulecache_test.go +++ b/private/bufpkg/bufmodule/bufmodulecache/bufmodulecache_test.go @@ -37,7 +37,7 @@ import ( func TestCommitProviderForModuleKeyBasic(t *testing.T) { t.Parallel() - ctx := context.Background() + ctx := t.Context() bsrProvider, moduleKeys := testGetBSRProviderAndModuleKeys(t, ctx) logger := slogtestext.NewLogger(t) @@ -100,7 +100,7 @@ func TestCommitProviderForModuleKeyBasic(t *testing.T) { func TestCommitProviderForCommitKeyBasic(t *testing.T) { t.Parallel() - ctx := context.Background() + ctx := t.Context() bsrProvider, moduleKeys := testGetBSRProviderAndModuleKeys(t, ctx) logger := slogtestext.NewLogger(t) @@ -164,7 +164,7 @@ func TestCommitProviderForCommitKeyBasic(t *testing.T) { func TestModuleDataProviderBasic(t *testing.T) { t.Parallel() - ctx := context.Background() + ctx := t.Context() bsrProvider, moduleKeys := testGetBSRProviderAndModuleKeys(t, ctx) logger := slogtestext.NewLogger(t) @@ -228,7 +228,7 @@ func TestModuleDataProviderBasic(t *testing.T) { func TestConcurrentCacheReadWrite(t *testing.T) { t.Parallel() - bsrProvider, moduleKeys := testGetBSRProviderAndModuleKeys(t, context.Background()) + bsrProvider, moduleKeys := testGetBSRProviderAndModuleKeys(t, t.Context()) tempDir := t.TempDir() cacheDir := filepath.Join(tempDir, "cache") logger := slogtestext.NewLogger(t) @@ -277,7 +277,7 @@ func TestConcurrentCacheReadWrite(t *testing.T) { }, ) require.NoError(t, err) - require.NoError(t, thread.Parallelize(context.Background(), jobs)) + require.NoError(t, thread.Parallelize(t.Context(), jobs)) require.NoError(t, os.RemoveAll(cacheDir)) } } diff --git a/private/bufpkg/bufmodule/bufmodulestore/module_data_store_test.go b/private/bufpkg/bufmodule/bufmodulestore/module_data_store_test.go index a6b3daee72..64995db420 100644 --- a/private/bufpkg/bufmodule/bufmodulestore/module_data_store_test.go +++ b/private/bufpkg/bufmodule/bufmodulestore/module_data_store_test.go @@ -72,7 +72,7 @@ func testModuleDataStore( moduleDataStoreOptions []ModuleDataStoreOption, tar bool, ) { - ctx := context.Background() + ctx := t.Context() logger := slogtestext.NewLogger(t) moduleDataStore := NewModuleDataStore(logger, bucket, filelocker, moduleDataStoreOptions...) moduleKeys, moduleDatas := testGetModuleKeysAndModuleDatas(t, ctx) diff --git a/private/bufpkg/bufprotoplugin/bufprotoplugin_test.go b/private/bufpkg/bufprotoplugin/bufprotoplugin_test.go index 026722538a..c335032d1d 100644 --- a/private/bufpkg/bufprotoplugin/bufprotoplugin_test.go +++ b/private/bufpkg/bufprotoplugin/bufprotoplugin_test.go @@ -15,7 +15,6 @@ package bufprotoplugin import ( - "context" "strings" "testing" @@ -49,7 +48,7 @@ at varied indentation levels } postInsertionContent, err := writeInsertionPoint( - context.Background(), + t.Context(), insertionPointConsumer, strings.NewReader(targetFileContent), ) @@ -76,7 +75,7 @@ at varied indentation levels } postInsertionContent, err := writeInsertionPoint( - context.Background(), + t.Context(), insertionPointConsumer, strings.NewReader(targetFileContent), ) @@ -103,7 +102,7 @@ at varied indentation levels } postInsertionContent, err := writeInsertionPoint( - context.Background(), + t.Context(), insertionPointConsumer, strings.NewReader(targetFileContent), ) @@ -133,7 +132,7 @@ at varied indentation levels Content: &insertionPointContent, } _, err := writeInsertionPoint( - context.Background(), + t.Context(), insertionPointConsumer, strings.NewReader(targetFileContent), ) @@ -148,7 +147,7 @@ at varied indentation levels Content: &insertionPointContent, } _, err := writeInsertionPoint( - context.Background(), + t.Context(), insertionPointConsumer, strings.NewReader(targetFileContent), ) @@ -200,7 +199,7 @@ at varied indentation levels` + whitespacePrefix + "// @@protoc_insertion_point( b.ReportAllocs() postInsertionContent, _ = writeInsertionPoint( - context.Background(), + b.Context(), insertionPointConsumer, strings.NewReader(targetFileContent), ) @@ -234,7 +233,7 @@ at varied indentation levels` + whitespacePrefix + "// @@protoc_insertion_point( b.ReportAllocs() postInsertionContent, _ = writeInsertionPoint( - context.Background(), + b.Context(), insertionPointConsumer, strings.NewReader(inflatedTargetFileContent.String()), ) diff --git a/private/bufpkg/bufprotosource/bufprotosource_test.go b/private/bufpkg/bufprotosource/bufprotosource_test.go index 6cc6e1dcda..9d3d36d530 100644 --- a/private/bufpkg/bufprotosource/bufprotosource_test.go +++ b/private/bufpkg/bufprotosource/bufprotosource_test.go @@ -15,7 +15,6 @@ package bufprotosource import ( - "context" "testing" "github.com/bufbuild/buf/private/bufpkg/bufimage" @@ -30,12 +29,12 @@ func TestNewFiles(t *testing.T) { moduleSet, err := bufmoduletesting.NewModuleSetForDirPath("testdata/nested") require.NoError(t, err) image, err := bufimage.BuildImage( - context.Background(), + t.Context(), slogtestext.NewLogger(t), bufmodule.ModuleSetToModuleReadBucketWithOnlyProtoFiles(moduleSet), ) require.NoError(t, err) - files, err := NewFiles(context.Background(), image.Files(), image.Resolver()) + files, err := NewFiles(t.Context(), image.Files(), image.Resolver()) require.NoError(t, err) require.Len(t, files, 1) file := files[0] diff --git a/private/bufpkg/bufremoteplugin/bufremotepluginconfig/bufremotepluginconfig_test.go b/private/bufpkg/bufremoteplugin/bufremotepluginconfig/bufremotepluginconfig_test.go index 51e353a121..734b917e02 100644 --- a/private/bufpkg/bufremoteplugin/bufremotepluginconfig/bufremotepluginconfig_test.go +++ b/private/bufpkg/bufremoteplugin/bufremotepluginconfig/bufremotepluginconfig_test.go @@ -15,7 +15,6 @@ package bufremotepluginconfig import ( - "context" "math" "os" "path/filepath" @@ -35,7 +34,7 @@ func TestGetConfigForBucket(t *testing.T) { storageosProvider := storageos.NewProvider() readWriteBucket, err := storageosProvider.NewReadWriteBucket(filepath.Join("testdata", "success", "go")) require.NoError(t, err) - pluginConfig, err := GetConfigForBucket(context.Background(), readWriteBucket) + pluginConfig, err := GetConfigForBucket(t.Context(), readWriteBucket) require.NoError(t, err) pluginIdentity, err := bufremotepluginref.PluginIdentityForString("buf.build/library/go-grpc") require.NoError(t, err) @@ -524,7 +523,7 @@ func verifyDependencies(t testing.TB, validConfigBytes []byte, fail bool, invali cloned.Deps = slices.Clone(invalidDependencies) yamlBytes, err := yaml.Marshal(cloned) require.NoError(t, err) - _, err = GetConfigForData(context.Background(), yamlBytes) + _, err = GetConfigForData(t.Context(), yamlBytes) if fail { assert.Error(t, err) } else { diff --git a/private/bufpkg/bufremoteplugin/bufremoteplugindocker/docker_test.go b/private/bufpkg/bufremoteplugin/bufremoteplugindocker/docker_test.go index ffc6c04e01..2972a2e5b1 100644 --- a/private/bufpkg/bufremoteplugin/bufremoteplugindocker/docker_test.go +++ b/private/bufpkg/bufremoteplugin/bufremoteplugindocker/docker_test.go @@ -61,7 +61,7 @@ func TestPushSuccess(t *testing.T) { image, err := buildDockerPlugin(t, "testdata/success/Dockerfile", listenerAddr+"/library/go") require.Nilf(t, err, "failed to build docker plugin") require.NotEmpty(t, image) - pushResponse, err := dockerClient.Push(context.Background(), image, &RegistryAuthConfig{}) + pushResponse, err := dockerClient.Push(t.Context(), image, &RegistryAuthConfig{}) require.Nilf(t, err, "failed to push docker plugin") require.NotNil(t, pushResponse) assert.NotEmpty(t, pushResponse.Digest) @@ -77,7 +77,7 @@ func TestPushError(t *testing.T) { image, err := buildDockerPlugin(t, "testdata/success/Dockerfile", listenerAddr+"/library/go") require.Nilf(t, err, "failed to build docker plugin") require.NotEmpty(t, image) - _, err = dockerClient.Push(context.Background(), image, &RegistryAuthConfig{}) + _, err = dockerClient.Push(t.Context(), image, &RegistryAuthConfig{}) require.NotNil(t, err, "expected error") assert.Equal(t, server.pushErr.Error(), err.Error()) } @@ -150,7 +150,7 @@ func buildDockerPlugin(t testing.TB, dockerfilePath string, pluginIdentity strin envContainer, err := app.NewEnvContainerForOS() require.NoError(t, err) if err := xexec.Run( - context.Background(), + t.Context(), docker, xexec.WithArgs("build", "-t", imageName, "."), xexec.WithDir(filepath.Dir(dockerfilePath)), @@ -163,7 +163,7 @@ func buildDockerPlugin(t testing.TB, dockerfilePath string, pluginIdentity strin t.Logf("created image: %s", imageName) t.Cleanup(func() { if err := xexec.Run( - context.Background(), + t.Context(), docker, xexec.WithArgs("rmi", "--force", imageName), xexec.WithDir(filepath.Dir(dockerfilePath)), diff --git a/private/bufpkg/bufremoteplugin/dotnet_target_platform_test.go b/private/bufpkg/bufremoteplugin/dotnet_target_platform_test.go index da5b4afbd7..8964a13a43 100644 --- a/private/bufpkg/bufremoteplugin/dotnet_target_platform_test.go +++ b/private/bufpkg/bufremoteplugin/dotnet_target_platform_test.go @@ -15,7 +15,6 @@ package bufremoteplugin import ( - "context" "fmt" "testing" @@ -46,7 +45,7 @@ func TestDotnetTargetPlatformExternalConfigMapping(t *testing.T) { // We validate the string values for target frameworks in bufremoteconfig. // This test will fail if we add a new target framework to the proto and didn't update the validation. t.Parallel() - ctx := context.Background() + ctx := t.Context() for targetFrameworkStr := range stringToDotnetTargetFramework { externalCfg := fmt.Sprintf( `version: v1 diff --git a/private/pkg/filelock/filelock_test.go b/private/pkg/filelock/filelock_test.go index 39c5d0e619..1b16e463a0 100644 --- a/private/pkg/filelock/filelock_test.go +++ b/private/pkg/filelock/filelock_test.go @@ -15,7 +15,6 @@ package filelock import ( - "context" "path/filepath" "runtime" "testing" @@ -26,7 +25,7 @@ import ( func TestGlobalBasic(t *testing.T) { t.Parallel() - ctx := context.Background() + ctx := t.Context() tempDirPath := t.TempDir() filePath := filepath.Join(tempDirPath, "path/to/lock") unlocker, err := Lock(ctx, filePath) @@ -49,7 +48,7 @@ func TestGlobalBasic(t *testing.T) { func TestLockerBasic(t *testing.T) { t.Parallel() - ctx := context.Background() + ctx := t.Context() tempDirPath := t.TempDir() filePath := "path/to/lock" locker, err := NewLocker(tempDirPath) diff --git a/private/pkg/oauth2/client_test.go b/private/pkg/oauth2/client_test.go index d8205918dd..b8a2f3715b 100644 --- a/private/pkg/oauth2/client_test.go +++ b/private/pkg/oauth2/client_test.go @@ -15,7 +15,6 @@ package oauth2 import ( - "context" "errors" "fmt" "io" @@ -93,7 +92,7 @@ func TestRegisterDevice(t *testing.T) { for _, test := range tests { t.Run(test.name, func(t *testing.T) { t.Parallel() - ctx := context.Background() + ctx := t.Context() c := NewClient("https://buf.build", &http.Client{ Transport: testRoundTripFunc(func(r *http.Request) (*http.Response, error) { assert.Equal(t, r.Method, http.MethodPost) @@ -205,7 +204,7 @@ func TestAuthorizeDevice(t *testing.T) { for _, test := range tests { t.Run(test.name, func(t *testing.T) { t.Parallel() - ctx := context.Background() + ctx := t.Context() c := NewClient("https://buf.build", &http.Client{ Transport: testRoundTripFunc(func(r *http.Request) (*http.Response, error) { assert.Equal(t, r.Method, http.MethodPost) @@ -311,7 +310,7 @@ func TestAccessDeviceToken(t *testing.T) { for _, test := range tests { t.Run(test.name, func(t *testing.T) { t.Parallel() - ctx := context.Background() + ctx := t.Context() c := NewClient("https://buf.build", &http.Client{ Transport: testRoundTripFunc(func(r *http.Request) (*http.Response, error) { assert.Equal(t, r.Method, http.MethodPost) diff --git a/private/pkg/protosourcepath/protosourcepath_test.go b/private/pkg/protosourcepath/protosourcepath_test.go index 4daab88f57..bcd3563ac1 100644 --- a/private/pkg/protosourcepath/protosourcepath_test.go +++ b/private/pkg/protosourcepath/protosourcepath_test.go @@ -15,7 +15,6 @@ package protosourcepath import ( - "context" "testing" "github.com/bufbuild/protocompile" @@ -381,7 +380,7 @@ func testGetAssociatedSourcePaths( Resolver: &protocompile.SourceResolver{}, SourceInfoMode: protocompile.SourceInfoStandard, } - files, err := compiler.Compile(context.Background(), testFilePath) + files, err := compiler.Compile(t.Context(), testFilePath) require.NoError(t, err) require.Len(t, files, 1, "expect only one test file") sourceLocations := files[0].SourceLocations() diff --git a/private/pkg/protostat/protostat_test.go b/private/pkg/protostat/protostat_test.go index c69ddc87fe..46b3afc152 100644 --- a/private/pkg/protostat/protostat_test.go +++ b/private/pkg/protostat/protostat_test.go @@ -215,7 +215,7 @@ func TestGetStatsDeprecatedTypes(t *testing.T) { t.Run(tc.name, func(t *testing.T) { t.Parallel() walker := &testFileWalker{contents: []string{tc.content}} - stats, err := GetStats(context.Background(), walker) + stats, err := GetStats(t.Context(), walker) require.NoError(t, err) assert.Equal(t, tc.expectedTypes, stats.Types, "Types count mismatch") assert.Equal(t, tc.expectedDeprecatedMessages, stats.DeprecatedMessages, "DeprecatedMessages count mismatch") @@ -245,7 +245,7 @@ func TestGetStatsMultipleFiles(t *testing.T) { ` walker := &testFileWalker{contents: []string{file1, file2}} - stats, err := GetStats(context.Background(), walker) + stats, err := GetStats(t.Context(), walker) require.NoError(t, err) assert.Equal(t, 2, stats.Files) diff --git a/private/pkg/prototesting/prototesting.go b/private/pkg/prototesting/prototesting.go index 60f17bfbe1..3e3832d7c6 100644 --- a/private/pkg/prototesting/prototesting.go +++ b/private/pkg/prototesting/prototesting.go @@ -228,7 +228,7 @@ func AssertFileDescriptorSetsEqual( one *descriptorpb.FileDescriptorSet, two *descriptorpb.FileDescriptorSet, ) { - diff, err := DiffFileDescriptorSetsJSON(context.Background(), one, two, "buf", "protoc") + diff, err := DiffFileDescriptorSetsJSON(t.Context(), one, two, "buf", "protoc") assert.NoError(t, err) assert.Empty(t, diff) diff = DiffFileDescriptorSetsCompare(one, two) diff --git a/private/pkg/storage/storagemem/storagemem_test.go b/private/pkg/storage/storagemem/storagemem_test.go index 4bcda2a08e..c4087264c0 100644 --- a/private/pkg/storage/storagemem/storagemem_test.go +++ b/private/pkg/storage/storagemem/storagemem_test.go @@ -15,7 +15,6 @@ package storagemem_test import ( - "context" "path/filepath" "testing" @@ -49,7 +48,7 @@ func testNewReadBucket(t *testing.T, dirPath string, storageosProvider storageos require.NoError(t, err) readWriteBucket := storagemem.NewReadWriteBucket() _, err = storage.Copy( - context.Background(), + t.Context(), osBucket, readWriteBucket, storage.CopyWithExternalAndLocalPaths(), diff --git a/private/pkg/storage/storageos/storageos_test.go b/private/pkg/storage/storageos/storageos_test.go index 5c07e32814..2a76ee8b74 100644 --- a/private/pkg/storage/storageos/storageos_test.go +++ b/private/pkg/storage/storageos/storageos_test.go @@ -15,7 +15,6 @@ package storageos_test import ( - "context" "io/fs" "os" "path/filepath" @@ -43,7 +42,7 @@ func TestOS(t *testing.T) { t.Run("get_non_existent_file", func(t *testing.T) { t.Parallel() - ctx := context.Background() + ctx := t.Context() // Create a bucket at an absolute path. tempDir := t.TempDir() tempDir, err := filepath.Abs(tempDir) @@ -72,7 +71,7 @@ func TestOS(t *testing.T) { t.Run("get_non_existent_file_symlink", func(t *testing.T) { t.Parallel() - ctx := context.Background() + ctx := t.Context() // Create a bucket at an absolute path. actualTempDir := t.TempDir() actualTempDir, err := filepath.Abs(actualTempDir) diff --git a/private/pkg/storage/storagetesting/storagetesting.go b/private/pkg/storage/storagetesting/storagetesting.go index 28b6086554..c5e373135b 100644 --- a/private/pkg/storage/storagetesting/storagetesting.go +++ b/private/pkg/storage/storagetesting/storagetesting.go @@ -17,7 +17,6 @@ package storagetesting import ( "bytes" - "context" "errors" "fmt" "io" @@ -60,7 +59,7 @@ func AssertNotExist( readBucket storage.ReadBucket, path string, ) { - _, err := readBucket.Stat(context.Background(), path) + _, err := readBucket.Stat(t.Context(), path) assert.Error(t, err) assert.True(t, errors.Is(err, fs.ErrNotExist)) } @@ -77,7 +76,7 @@ func AssertObjectInfo( if externalPathShouldEqualLocalPath { localPath = externalPath } - objectInfo, err := readBucket.Stat(context.Background(), path) + objectInfo, err := readBucket.Stat(t.Context(), path) require.NoError(t, err) AssertObjectInfoEqual( t, @@ -109,7 +108,7 @@ func AssertPathToContent( ) { var paths []string require.NoError(t, readBucket.Walk( - context.Background(), + t.Context(), walkPrefix, func(objectInfo storage.ObjectInfo) error { paths = append(paths, objectInfo.Path()) @@ -121,9 +120,9 @@ func AssertPathToContent( for _, path := range paths { expectedContent, ok := expectedPathToContent[path] assert.True(t, ok, path) - _, err := readBucket.Stat(context.Background(), path) + _, err := readBucket.Stat(t.Context(), path) require.NoError(t, err, path) - readObjectCloser, err := readBucket.Get(context.Background(), path) + readObjectCloser, err := readBucket.Get(t.Context(), path) require.NoError(t, err, path) data, err := io.ReadAll(readObjectCloser) assert.NoError(t, err, path) @@ -141,7 +140,7 @@ func AssertPaths( ) { var paths []string require.NoError(t, readBucket.Walk( - context.Background(), + t.Context(), walkPrefix, func(objectInfo storage.ObjectInfo) error { paths = append(paths, objectInfo.Path()) @@ -397,19 +396,19 @@ func RunTestSuite( ), ) _, err := readBucketMulti.Get( - context.Background(), + t.Context(), "a/b/1.proto", ) assert.Error(t, err) assert.True(t, storage.IsExistsMultipleLocations(err)) _, err = readBucketMulti.Stat( - context.Background(), + t.Context(), "a/b/1.proto", ) assert.Error(t, err) assert.True(t, storage.IsExistsMultipleLocations(err)) err = readBucketMulti.Walk( - context.Background(), + t.Context(), "", func(storage.ObjectInfo) error { return nil @@ -912,7 +911,7 @@ func RunTestSuite( readBucket = storage.FilterReadBucket(readBucket, testCase.matchers...) writeBucket := newWriteBucket(t, defaultProvider) _, err := storage.Copy( - context.Background(), + t.Context(), readBucket, writeBucket, ) @@ -928,12 +927,12 @@ func RunTestSuite( writeBucket := newWriteBucket(t, defaultProvider) buffer := bytes.NewBuffer(nil) require.NoError(t, storagearchive.Tar( - context.Background(), + t.Context(), readBucket, buffer, )) require.NoError(t, storagearchive.Untar( - context.Background(), + t.Context(), buffer, writeBucket, storagearchive.UntarWithStripComponentCount( @@ -951,14 +950,14 @@ func RunTestSuite( writeBucket := newWriteBucket(t, defaultProvider) buffer := bytes.NewBuffer(nil) require.NoError(t, storagearchive.Zip( - context.Background(), + t.Context(), readBucket, buffer, true, )) data := buffer.Bytes() require.NoError(t, storagearchive.Unzip( - context.Background(), + t.Context(), bytes.NewReader(data), int64(len(data)), writeBucket, @@ -976,12 +975,12 @@ func RunTestSuite( writeBucket := newWriteBucket(t, defaultProvider) buffer := bytes.NewBuffer(nil) require.NoError(t, storagearchive.Tar( - context.Background(), + t.Context(), readBucket, buffer, )) require.NoError(t, storagearchive.Untar( - context.Background(), + t.Context(), buffer, writeBucket, storagearchive.UntarWithStripComponentCount( @@ -999,14 +998,14 @@ func RunTestSuite( writeBucket := newWriteBucket(t, defaultProvider) buffer := bytes.NewBuffer(nil) require.NoError(t, storagearchive.Zip( - context.Background(), + t.Context(), readBucket, buffer, true, )) data := buffer.Bytes() require.NoError(t, storagearchive.Unzip( - context.Background(), + t.Context(), bytes.NewReader(data), int64(len(data)), writeBucket, @@ -1037,7 +1036,7 @@ func RunTestSuite( b2TxtPath := filepath.ToSlash(externalPathPrefixB + "2.txt") diff, err := storage.DiffBytes( - context.Background(), + t.Context(), readBucketA, readBucketB, storage.DiffWithSuppressTimestamps(), @@ -1102,7 +1101,7 @@ func RunTestSuite( ), ) allPaths, err := storage.AllPaths( - context.Background(), + t.Context(), readBucket, "", ) @@ -1137,7 +1136,7 @@ func RunTestSuite( storage.MatchPathExt(".proto"), ) _, err := storage.AllPaths( - context.Background(), + t.Context(), readBucket, "", ) @@ -1152,7 +1151,7 @@ func RunTestSuite( storage.MapOnPrefix("a/b/c"), ) writeObjectCloser, err := mapWriteBucket.Put( - context.Background(), + t.Context(), "hello", ) require.NoError(t, err) @@ -1161,7 +1160,7 @@ func RunTestSuite( require.NoError(t, writeObjectCloser.Close()) readBucket := writeBucketToReadBucket(t, writeBucket) data, err := storage.ReadPath( - context.Background(), + t.Context(), readBucket, "a/b/c/hello", ) @@ -1179,11 +1178,11 @@ func RunTestSuite( expectErr := fmt.Sprintf("%s: expected to be relative", absolutePath) readBucket, _ := newReadBucket(t, oneDirPath, defaultProvider) - _, err := readBucket.Get(context.Background(), absolutePath) + _, err := readBucket.Get(t.Context(), absolutePath) require.EqualError(t, err, expectErr, "should be using storageutil.ValidatePath on Get") - _, err = readBucket.Stat(context.Background(), absolutePath) + _, err = readBucket.Stat(t.Context(), absolutePath) require.EqualError(t, err, expectErr, "should be using storageutil.ValidatePath on Stat") - err = readBucket.Walk(context.Background(), absolutePath, nil) + err = readBucket.Walk(t.Context(), absolutePath, nil) require.EqualError(t, err, expectErr, "should be using storageutil.ValidatePrefix on Walk") }) @@ -1197,55 +1196,55 @@ func RunTestSuite( expectErr := fmt.Sprintf("%s: expected to be relative", absolutePath) writeBucket := newWriteBucket(t, defaultProvider) - _, err := writeBucket.Put(context.Background(), absolutePath) + _, err := writeBucket.Put(t.Context(), absolutePath) require.EqualError(t, err, expectErr, "should be using normalize.NormalizeAndValidate on Put") - err = writeBucket.Delete(context.Background(), absolutePath) + err = writeBucket.Delete(t.Context(), absolutePath) require.EqualError(t, err, expectErr, "should be using normalize.NormalizeAndValidate on Delete") }) t.Run("root-path-error", func(t *testing.T) { t.Parallel() readBucket, _ := newReadBucket(t, oneDirPath, defaultProvider) - _, err := readBucket.Get(context.Background(), ".") + _, err := readBucket.Get(t.Context(), ".") require.EqualError(t, err, "cannot use root", "should be using storageutil.ValidatePath on Get") - _, err = readBucket.Stat(context.Background(), ".") + _, err = readBucket.Stat(t.Context(), ".") require.EqualError(t, err, "cannot use root", "should be using storageutil.ValidatePath on Stat") }) t.Run("write-bucket-put-delete", func(t *testing.T) { t.Parallel() writeBucket := newWriteBucket(t, defaultProvider) - err := writeBucket.Delete(context.Background(), "hello") + err := writeBucket.Delete(t.Context(), "hello") require.True(t, errors.Is(err, fs.ErrNotExist)) writeObjectCloser, err := writeBucket.Put( - context.Background(), + t.Context(), "hello", ) require.NoError(t, err) _, err = writeObjectCloser.Write([]byte("abcd")) require.NoError(t, err) require.NoError(t, writeObjectCloser.Close()) - err = writeBucket.Delete(context.Background(), "hello") + err = writeBucket.Delete(t.Context(), "hello") require.NoError(t, err) - err = writeBucket.Delete(context.Background(), "hello") + err = writeBucket.Delete(t.Context(), "hello") require.True(t, errors.Is(err, fs.ErrNotExist)) writeObjectCloser, err = writeBucket.Put( - context.Background(), + t.Context(), "hello", ) require.NoError(t, err) _, err = writeObjectCloser.Write([]byte("abcd")) require.NoError(t, err) require.NoError(t, writeObjectCloser.Close()) - err = writeBucket.Delete(context.Background(), "hello") + err = writeBucket.Delete(t.Context(), "hello") require.NoError(t, err) - err = writeBucket.Delete(context.Background(), "hello") + err = writeBucket.Delete(t.Context(), "hello") require.True(t, errors.Is(err, fs.ErrNotExist)) }) t.Run("write-bucket-put-delete-all", func(t *testing.T) { t.Parallel() - ctx := context.Background() + ctx := t.Context() writeBucket := newWriteBucket(t, defaultProvider) // this test starts with this data in the bucket, and then // deletes it over time in different ways @@ -1354,7 +1353,7 @@ func RunTestSuite( writeBucket := newWriteBucket(t, defaultProvider) readBucket := writeBucketToReadBucket(t, writeBucket) mappedReadBucket := storage.MapReadBucket(readBucket, storage.MapOnPrefix("prefix")) - err := mappedReadBucket.Walk(context.Background(), "", func(_ storage.ObjectInfo) error { + err := mappedReadBucket.Walk(t.Context(), "", func(_ storage.ObjectInfo) error { return nil }) require.NoError(t, err) @@ -1431,7 +1430,7 @@ func RunTestSuite( }) t.Run("is_empty", func(t *testing.T) { t.Parallel() - ctx := context.Background() + ctx := t.Context() readBucket, _ := newReadBucket(t, oneDirPath, defaultProvider) isEmpty, err := storage.IsEmpty(ctx, readBucket, "") @@ -1482,12 +1481,12 @@ func RunTestSuite( data := bytes.Repeat([]byte("b"), i*100) path := strconv.Itoa(i) triedBytes.Add(int64(len(data))) - err := storage.PutPath(context.Background(), limitedWriteBucket, path, data) + err := storage.PutPath(t.Context(), limitedWriteBucket, path, data) if err != nil { assert.True(t, storage.IsWriteLimitReached(err)) return } - readData, err := storage.ReadPath(context.Background(), readBucket, path) + readData, err := storage.ReadPath(t.Context(), readBucket, path) assert.NoError(t, err) assert.Equal(t, readData, data) writtenBytes.Add(int64(len(data))) @@ -1508,26 +1507,26 @@ func RunTestSuite( "match-file": bytes.Repeat([]byte{0}, limit-1), } for path, data := range files { - err := storage.PutPath(context.Background(), writeBucket, path, data) + err := storage.PutPath(t.Context(), writeBucket, path, data) require.NoError(t, err) } var buffer bytes.Buffer - err := storagearchive.Tar(context.Background(), writeBucketToReadBucket(t, writeBucket), &buffer) + err := storagearchive.Tar(t.Context(), writeBucketToReadBucket(t, writeBucket), &buffer) require.NoError(t, err) writeBucket = newWriteBucket(t, defaultProvider) tarball := bytes.NewReader(buffer.Bytes()) - err = storagearchive.Untar(context.Background(), tarball, writeBucket, storagearchive.UntarWithMaxFileSize(limit)) + err = storagearchive.Untar(t.Context(), tarball, writeBucket, storagearchive.UntarWithMaxFileSize(limit)) assert.ErrorIs(t, err, storagearchive.ErrFileSizeLimit) _, err = tarball.Seek(0, io.SeekStart) require.NoError(t, err) - err = storagearchive.Untar(context.Background(), tarball, writeBucket) + err = storagearchive.Untar(t.Context(), tarball, writeBucket) assert.NoError(t, err) _, err = tarball.Seek(0, io.SeekStart) require.NoError(t, err) - err = storagearchive.Untar(context.Background(), tarball, writeBucket, storagearchive.UntarWithMaxFileSize(limit+1)) + err = storagearchive.Untar(t.Context(), tarball, writeBucket, storagearchive.UntarWithMaxFileSize(limit+1)) assert.NoError(t, err) err = storagearchive.Untar( - context.Background(), + t.Context(), tarball, writeBucket, storagearchive.UntarWithFilePathMatcher( diff --git a/private/pkg/thread/thread_test.go b/private/pkg/thread/thread_test.go index 31993ce258..f60d4d0b32 100644 --- a/private/pkg/thread/thread_test.go +++ b/private/pkg/thread/thread_test.go @@ -39,7 +39,7 @@ func TestParallelizeWithImmediateCancellation(t *testing.T) { return nil }) } - err := Parallelize(context.Background(), jobs) + err := Parallelize(t.Context(), jobs) assert.NoError(t, err) assert.Equal(t, int64(jobsToExecute), executed.Load(), "jobs executed") }) @@ -53,7 +53,7 @@ func TestParallelizeWithImmediateCancellation(t *testing.T) { return nil }) } - ctx, cancel := context.WithCancel(context.Background()) + ctx, cancel := context.WithCancel(t.Context()) cancel() err := Parallelize(ctx, jobs) assert.Error(t, err) diff --git a/private/pkg/tmp/tmp_test.go b/private/pkg/tmp/tmp_test.go index 4f709f4e16..c0526a0a47 100644 --- a/private/pkg/tmp/tmp_test.go +++ b/private/pkg/tmp/tmp_test.go @@ -28,7 +28,7 @@ import ( func TestFile(t *testing.T) { t.Parallel() - ctx := context.Background() + ctx := t.Context() tmpFile, err := NewFile(ctx, strings.NewReader("foo")) require.NoError(t, err) assert.True(t, filepath.IsAbs(tmpFile.Path())) @@ -42,7 +42,7 @@ func TestFile(t *testing.T) { func TestFileCancel(t *testing.T) { t.Parallel() - ctx, cancel := context.WithCancel(context.Background()) + ctx, cancel := context.WithCancel(t.Context()) tmpFile, err := NewFile(ctx, strings.NewReader("foo")) require.NoError(t, err) _, err = os.ReadFile(tmpFile.Path()) @@ -55,7 +55,7 @@ func TestFileCancel(t *testing.T) { func TestDir(t *testing.T) { t.Parallel() - ctx := context.Background() + ctx := t.Context() tmpDir, err := NewDir(ctx) require.NoError(t, err) assert.True(t, filepath.IsAbs(tmpDir.Path())) @@ -69,7 +69,7 @@ func TestDir(t *testing.T) { func TestDirCancel(t *testing.T) { t.Parallel() - ctx, cancel := context.WithCancel(context.Background()) + ctx, cancel := context.WithCancel(t.Context()) tmpDir, err := NewDir(ctx) require.NoError(t, err) _, err = os.Lstat(tmpDir.Path())