From 9ac7d8640c1e14c750ad4284f4a2751a3b2966cd Mon Sep 17 00:00:00 2001 From: David Gageot Date: Tue, 20 Jan 2026 10:17:26 +0100 Subject: [PATCH 1/4] test: modernize benchmark to use b.Loop() and t.Setenv() - Replace for i := 0; i < b.N; i++ with for b.Loop() (Go 1.24) - Replace os.Setenv/defer os.Unsetenv with t.Setenv() (Go 1.18) Assisted-By: cagent --- main_test.go | 5 +---- pkg/responses/handler_test.go | 3 +-- 2 files changed, 2 insertions(+), 6 deletions(-) diff --git a/main_test.go b/main_test.go index cca7c75e..75f89e58 100644 --- a/main_test.go +++ b/main_test.go @@ -1,7 +1,6 @@ package main import ( - "os" "testing" "github.com/docker/model-runner/pkg/inference/backends/llamacpp" @@ -58,10 +57,8 @@ func TestCreateLlamaCppConfigFromEnv(t *testing.T) { for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { - // Set up environment if tt.llamaArgs != "" { - os.Setenv("LLAMA_ARGS", tt.llamaArgs) - defer os.Unsetenv("LLAMA_ARGS") + t.Setenv("LLAMA_ARGS", tt.llamaArgs) } // Create a test logger that captures fatal errors diff --git a/pkg/responses/handler_test.go b/pkg/responses/handler_test.go index 9a2444fe..0968b3ac 100644 --- a/pkg/responses/handler_test.go +++ b/pkg/responses/handler_test.go @@ -697,8 +697,7 @@ func BenchmarkHandler_CreateResponse(b *testing.B) { handler := newTestHandler(mock) reqBody := []byte(`{"model": "gpt-4", "input": "Hello"}`) - b.ResetTimer() - for i := 0; i < b.N; i++ { + for b.Loop() { req := httptest.NewRequest(http.MethodPost, "/v1/responses", bytes.NewReader(reqBody)) req.Header.Set("Content-Type", "application/json") w := httptest.NewRecorder() From 57f43a5e8900aca78d3e9e726d59a979dd7d0e0c Mon Sep 17 00:00:00 2001 From: David Gageot Date: Tue, 20 Jan 2026 10:22:24 +0100 Subject: [PATCH 2/4] test: replace os.MkdirTemp with t.TempDir() Use t.TempDir() instead of manual os.MkdirTemp/defer os.RemoveAll patterns. This is cleaner, automatically handles cleanup on test failure, and is the recommended approach since Go 1.14. Assisted-By: cagent --- pkg/distribution/distribution/client_test.go | 155 +++--------------- pkg/distribution/distribution/delete_test.go | 7 +- pkg/distribution/distribution/load_test.go | 8 +- pkg/distribution/internal/store/blobs_test.go | 6 +- pkg/distribution/internal/store/store_test.go | 66 ++------ pkg/distribution/packaging/dirtar_test.go | 73 ++------- pkg/inference/models/handler_test.go | 22 +-- 7 files changed, 52 insertions(+), 285 deletions(-) diff --git a/pkg/distribution/distribution/client_test.go b/pkg/distribution/distribution/client_test.go index 77613e72..c46c514a 100644 --- a/pkg/distribution/distribution/client_test.go +++ b/pkg/distribution/distribution/client_test.go @@ -50,12 +50,7 @@ func TestClientPullModel(t *testing.T) { } registryHost := registryURL.Host - // Create temp directory for store - tempDir, err := os.MkdirTemp("", "model-distribution-test-*") - if err != nil { - t.Fatalf("Failed to create temp directory: %v", err) - } - defer os.RemoveAll(tempDir) + tempDir := t.TempDir() // Create client with plainHTTP for test registry client, err := newTestClient(tempDir) @@ -152,12 +147,7 @@ func TestClientPullModel(t *testing.T) { }) t.Run("pull non-existent model", func(t *testing.T) { - // Create temp directory for store - tempDir, err := os.MkdirTemp("", "model-distribution-test-*") - if err != nil { - t.Fatalf("Failed to create temp directory: %v", err) - } - defer os.RemoveAll(tempDir) + tempDir := t.TempDir() // Create client with plainHTTP for test registry testClient, err := newTestClient(tempDir) @@ -205,12 +195,7 @@ func TestClientPullModel(t *testing.T) { }) t.Run("pull with incomplete files", func(t *testing.T) { - // Create temp directory for store - tempDir, err := os.MkdirTemp("", "model-distribution-incomplete-test-*") - if err != nil { - t.Fatalf("Failed to create temp directory: %v", err) - } - defer os.RemoveAll(tempDir) + tempDir := t.TempDir() // Create client with plainHTTP for test registry testClient, err := newTestClient(tempDir) @@ -309,12 +294,7 @@ func TestClientPullModel(t *testing.T) { }) t.Run("pull updated model with same tag", func(t *testing.T) { - // Create temp directory for store - tempDir, err := os.MkdirTemp("", "model-distribution-update-test-*") - if err != nil { - t.Fatalf("Failed to create temp directory: %v", err) - } - defer os.RemoveAll(tempDir) + tempDir := t.TempDir() // Create client with plainHTTP for test registry testClient, err := newTestClient(tempDir) @@ -431,15 +411,10 @@ func TestClientPullModel(t *testing.T) { }) t.Run("pull safetensors model returns error on unsupported platforms", func(t *testing.T) { - // Create temp directory for the safetensors file - tempDir, err := os.MkdirTemp("", "safetensors-test-*") - if err != nil { - t.Fatalf("Failed to create temp directory: %v", err) - } - defer os.RemoveAll(tempDir) + safetensorsTempDir := t.TempDir() // Create a minimal safetensors file (just needs to exist for this test) - safetensorsPath := filepath.Join(tempDir, "model.safetensors") + safetensorsPath := filepath.Join(safetensorsTempDir, "model.safetensors") safetensorsContent := []byte("fake safetensors content for testing") if err := os.WriteFile(safetensorsPath, safetensorsContent, 0644); err != nil { t.Fatalf("Failed to create safetensors file: %v", err) @@ -462,11 +437,7 @@ func TestClientPullModel(t *testing.T) { } // Create a new client with a separate temp store - clientTempDir, err := os.MkdirTemp("", "client-safetensors-test-*") - if err != nil { - t.Fatalf("Failed to create client temp directory: %v", err) - } - defer os.RemoveAll(clientTempDir) + clientTempDir := t.TempDir() testClient, err := newTestClient(clientTempDir) if err != nil { @@ -495,12 +466,7 @@ func TestClientPullModel(t *testing.T) { }) t.Run("pull with JSON progress messages", func(t *testing.T) { - // Create temp directory for store - tempDir, err := os.MkdirTemp("", "model-distribution-json-test-*") - if err != nil { - t.Fatalf("Failed to create temp directory: %v", err) - } - defer os.RemoveAll(tempDir) + tempDir := t.TempDir() // Create client with plainHTTP for test registry testClient, err := newTestClient(tempDir) @@ -569,12 +535,7 @@ func TestClientPullModel(t *testing.T) { }) t.Run("pull with error and JSON progress messages", func(t *testing.T) { - // Create temp directory for store - tempDir, err := os.MkdirTemp("", "model-distribution-json-error-test-*") - if err != nil { - t.Fatalf("Failed to create temp directory: %v", err) - } - defer os.RemoveAll(tempDir) + tempDir := t.TempDir() // Create client with plainHTTP for test registry testClient, err := newTestClient(tempDir) @@ -605,12 +566,7 @@ func TestClientPullModel(t *testing.T) { } func TestClientGetModel(t *testing.T) { - // Create temp directory for store - tempDir, err := os.MkdirTemp("", "model-distribution-test-*") - if err != nil { - t.Fatalf("Failed to create temp directory: %v", err) - } - defer os.RemoveAll(tempDir) + tempDir := t.TempDir() // Create client with plainHTTP for test registry client, err := newTestClient(tempDir) @@ -644,12 +600,7 @@ func TestClientGetModel(t *testing.T) { } func TestClientGetModelNotFound(t *testing.T) { - // Create temp directory for store - tempDir, err := os.MkdirTemp("", "model-distribution-test-*") - if err != nil { - t.Fatalf("Failed to create temp directory: %v", err) - } - defer os.RemoveAll(tempDir) + tempDir := t.TempDir() // Create client with plainHTTP for test registry client, err := newTestClient(tempDir) @@ -665,12 +616,7 @@ func TestClientGetModelNotFound(t *testing.T) { } func TestClientListModels(t *testing.T) { - // Create temp directory for store - tempDir, err := os.MkdirTemp("", "model-distribution-test-*") - if err != nil { - t.Fatalf("Failed to create temp directory: %v", err) - } - defer os.RemoveAll(tempDir) + tempDir := t.TempDir() // Create client with plainHTTP for test registry client, err := newTestClient(tempDir) @@ -746,12 +692,7 @@ func TestClientListModels(t *testing.T) { } func TestClientGetStorePath(t *testing.T) { - // Create temp directory for store - tempDir, err := os.MkdirTemp("", "model-distribution-test-*") - if err != nil { - t.Fatalf("Failed to create temp directory: %v", err) - } - defer os.RemoveAll(tempDir) + tempDir := t.TempDir() // Create client with plainHTTP for test registry client, err := newTestClient(tempDir) @@ -774,12 +715,7 @@ func TestClientGetStorePath(t *testing.T) { } func TestClientDefaultLogger(t *testing.T) { - // Create temp directory for store - tempDir, err := os.MkdirTemp("", "model-distribution-test-*") - if err != nil { - t.Fatalf("Failed to create temp directory: %v", err) - } - defer os.RemoveAll(tempDir) + tempDir := t.TempDir() // Create client without specifying logger client, err := NewClient(WithStoreRootPath(tempDir)) @@ -809,12 +745,7 @@ func TestClientDefaultLogger(t *testing.T) { } func TestWithFunctionsNilChecks(t *testing.T) { - // Create temp directory for store - tempDir, err := os.MkdirTemp("", "model-distribution-test-*") - if err != nil { - t.Fatalf("Failed to create temp directory: %v", err) - } - defer os.RemoveAll(tempDir) + tempDir := t.TempDir() // Test WithStoreRootPath with empty string t.Run("WithStoreRootPath empty string", func(t *testing.T) { @@ -865,12 +796,7 @@ func TestWithFunctionsNilChecks(t *testing.T) { } func TestNewReferenceError(t *testing.T) { - // Create temp directory for store - tempDir, err := os.MkdirTemp("", "model-distribution-test-*") - if err != nil { - t.Fatalf("Failed to create temp directory: %v", err) - } - defer os.RemoveAll(tempDir) + tempDir := t.TempDir() // Create client with plainHTTP for test registry client, err := newTestClient(tempDir) @@ -891,12 +817,7 @@ func TestNewReferenceError(t *testing.T) { } func TestPush(t *testing.T) { - // Create temp directory for store - tempDir, err := os.MkdirTemp("", "model-distribution-test-*") - if err != nil { - t.Fatalf("Failed to create temp directory: %v", err) - } - defer os.RemoveAll(tempDir) + tempDir := t.TempDir() // Create client with plainHTTP for test registry client, err := newTestClient(tempDir) @@ -959,12 +880,7 @@ func TestPush(t *testing.T) { } func TestPushProgress(t *testing.T) { - // Create temp directory for store - tempDir, err := os.MkdirTemp("", "model-distribution-test-*") - if err != nil { - t.Fatalf("Failed to create temp directory: %v", err) - } - defer os.RemoveAll(tempDir) + tempDir := t.TempDir() // Create client with plainHTTP for test registry client, err := newTestClient(tempDir) @@ -1049,12 +965,7 @@ func TestPushProgress(t *testing.T) { } func TestTag(t *testing.T) { - // Create temp directory for store - tempDir, err := os.MkdirTemp("", "model-distribution-test-*") - if err != nil { - t.Fatalf("Failed to create temp directory: %v", err) - } - defer os.RemoveAll(tempDir) + tempDir := t.TempDir() // Create client with plainHTTP for test registry client, err := newTestClient(tempDir) @@ -1110,12 +1021,7 @@ func TestTag(t *testing.T) { } func TestTagNotFound(t *testing.T) { - // Create temp directory for store - tempDir, err := os.MkdirTemp("", "model-distribution-test-*") - if err != nil { - t.Fatalf("Failed to create temp directory: %v", err) - } - defer os.RemoveAll(tempDir) + tempDir := t.TempDir() // Create client with plainHTTP for test registry client, err := newTestClient(tempDir) @@ -1130,12 +1036,7 @@ func TestTagNotFound(t *testing.T) { } func TestClientPushModelNotFound(t *testing.T) { - // Create temp directory for store - tempDir, err := os.MkdirTemp("", "model-distribution-test-*") - if err != nil { - t.Fatalf("Failed to create temp directory: %v", err) - } - defer os.RemoveAll(tempDir) + tempDir := t.TempDir() // Create client with plainHTTP for test registry client, err := newTestClient(tempDir) @@ -1149,12 +1050,7 @@ func TestClientPushModelNotFound(t *testing.T) { } func TestIsModelInStoreNotFound(t *testing.T) { - // Create temp directory for store - tempDir, err := os.MkdirTemp("", "model-distribution-test-*") - if err != nil { - t.Fatalf("Failed to create temp directory: %v", err) - } - defer os.RemoveAll(tempDir) + tempDir := t.TempDir() // Create client with plainHTTP for test registry client, err := newTestClient(tempDir) @@ -1170,12 +1066,7 @@ func TestIsModelInStoreNotFound(t *testing.T) { } func TestIsModelInStoreFound(t *testing.T) { - // Create temp directory for store - tempDir, err := os.MkdirTemp("", "model-distribution-test-*") - if err != nil { - t.Fatalf("Failed to create temp directory: %v", err) - } - defer os.RemoveAll(tempDir) + tempDir := t.TempDir() // Create client with plainHTTP for test registry client, err := newTestClient(tempDir) diff --git a/pkg/distribution/distribution/delete_test.go b/pkg/distribution/distribution/delete_test.go index 1585409b..45ef6b51 100644 --- a/pkg/distribution/distribution/delete_test.go +++ b/pkg/distribution/distribution/delete_test.go @@ -9,12 +9,7 @@ import ( ) func TestDeleteModel(t *testing.T) { - // Create temp directory for store - tempDir, err := os.MkdirTemp("", "model-distribution-test-*") - if err != nil { - t.Fatalf("Failed to create temp directory: %v", err) - } - defer os.RemoveAll(tempDir) + tempDir := t.TempDir() // Create client client, err := NewClient(WithStoreRootPath(tempDir)) diff --git a/pkg/distribution/distribution/load_test.go b/pkg/distribution/distribution/load_test.go index 6c22fb92..b7b21ded 100644 --- a/pkg/distribution/distribution/load_test.go +++ b/pkg/distribution/distribution/load_test.go @@ -2,7 +2,6 @@ package distribution import ( "io" - "os" "testing" "github.com/docker/model-runner/pkg/distribution/builder" @@ -10,12 +9,7 @@ import ( ) func TestLoadModel(t *testing.T) { - // Create temp directory for store - tempDir, err := os.MkdirTemp("", "model-distribution-test-*") - if err != nil { - t.Fatalf("Failed to create temp directory: %v", err) - } - defer os.RemoveAll(tempDir) + tempDir := t.TempDir() // Create client client, err := NewClient(WithStoreRootPath(tempDir)) diff --git a/pkg/distribution/internal/store/blobs_test.go b/pkg/distribution/internal/store/blobs_test.go index 56084c72..bb3ea69d 100644 --- a/pkg/distribution/internal/store/blobs_test.go +++ b/pkg/distribution/internal/store/blobs_test.go @@ -12,11 +12,7 @@ import ( ) func TestBlobs(t *testing.T) { - tmpDir, err := os.MkdirTemp("", "blob-test") - if err != nil { - t.Fatalf("error creating temp dir: %v", err) - } - rootDir := filepath.Join(tmpDir, "store") + rootDir := filepath.Join(t.TempDir(), "store") store, err := New(Options{RootPath: rootDir}) if err != nil { t.Fatalf("error creating store: %v", err) diff --git a/pkg/distribution/internal/store/store_test.go b/pkg/distribution/internal/store/store_test.go index 6a3efc78..e3a82066 100644 --- a/pkg/distribution/internal/store/store_test.go +++ b/pkg/distribution/internal/store/store_test.go @@ -23,12 +23,7 @@ import ( // TestStoreAPI tests the store API directly func TestStoreAPI(t *testing.T) { - // Create a temporary directory for the test store - tempDir, err := os.MkdirTemp("", "store-api-test") - if err != nil { - t.Fatalf("Failed to create temp directory: %v", err) - } - defer os.RemoveAll(tempDir) + tempDir := t.TempDir() // Create store storePath := filepath.Join(tempDir, "api-model-store") @@ -388,11 +383,7 @@ func TestStoreAPI(t *testing.T) { } func TestWriteRollsBackOnTagFailure(t *testing.T) { - tempDir, err := os.MkdirTemp("", "store-rollback-test") - if err != nil { - t.Fatalf("Failed to create temp directory: %v", err) - } - defer os.RemoveAll(tempDir) + tempDir := t.TempDir() storePath := filepath.Join(tempDir, "rollback-store") s, err := store.New(store.Options{ @@ -470,11 +461,7 @@ func TestWriteRollsBackOnTagFailure(t *testing.T) { } func TestWriteRollsBackOnConfigFailure(t *testing.T) { - tempDir, err := os.MkdirTemp("", "store-config-failure") - if err != nil { - t.Fatalf("Failed to create temp directory: %v", err) - } - defer os.RemoveAll(tempDir) + tempDir := t.TempDir() storePath := filepath.Join(tempDir, "config-failure-store") s, err := store.New(store.Options{RootPath: storePath}) @@ -493,11 +480,7 @@ func TestWriteRollsBackOnConfigFailure(t *testing.T) { } func TestWriteRollsBackOnLayerFailure(t *testing.T) { - tempDir, err := os.MkdirTemp("", "store-layer-failure") - if err != nil { - t.Fatalf("Failed to create temp directory: %v", err) - } - defer os.RemoveAll(tempDir) + tempDir := t.TempDir() storePath := filepath.Join(tempDir, "layer-failure-store") s, err := store.New(store.Options{RootPath: storePath}) @@ -581,12 +564,7 @@ func (f failingLayer) Uncompressed() (io.ReadCloser, error) { // TestIncompleteFileHandling tests that files are created with .incomplete suffix and renamed on success func TestIncompleteFileHandling(t *testing.T) { - // Create a temporary directory for the test store - tempDir, err := os.MkdirTemp("", "incomplete-file-test") - if err != nil { - t.Fatalf("Failed to create temp directory: %v", err) - } - defer os.RemoveAll(tempDir) + tempDir := t.TempDir() // Create a temporary model file with known content modelContent := []byte("test model content for incomplete file test") @@ -686,11 +664,7 @@ func containsTag(tags []string, tag string) bool { } func TestWriteHandlesExistingBlobsGracefully(t *testing.T) { - tempDir, err := os.MkdirTemp("", "store-existing-blob") - if err != nil { - t.Fatalf("Failed to create temp directory: %v", err) - } - defer os.RemoveAll(tempDir) + tempDir := t.TempDir() storePath := filepath.Join(tempDir, "existing-blob-store") s, err := store.New(store.Options{RootPath: storePath}) @@ -722,12 +696,7 @@ func TestWriteHandlesExistingBlobsGracefully(t *testing.T) { // TestStoreWithMultimodalProjector tests storing and retrieving models with multimodal projector files func TestStoreWithMultimodalProjector(t *testing.T) { - // Create a temporary directory for the test store - tempDir, err := os.MkdirTemp("", "store-mmproj-test") - if err != nil { - t.Fatalf("Failed to create temp directory: %v", err) - } - defer os.RemoveAll(tempDir) + tempDir := t.TempDir() // Create store storePath := filepath.Join(tempDir, "mmproj-model-store") @@ -833,12 +802,7 @@ func newTestModelWithMultimodalProjector(t *testing.T) types.ModelArtifact { } // Create dummy multimodal projector file for testing - tempDir, err := os.MkdirTemp("", "mmproj-test") - if err != nil { - t.Fatalf("failed to create temp directory: %v", err) - } - - mmprojPath := filepath.Join(tempDir, "dummy.mmproj") + mmprojPath := filepath.Join(t.TempDir(), "dummy.mmproj") mmprojContent := []byte("dummy multimodal projector content for testing") if err := os.WriteFile(mmprojPath, mmprojContent, 0644); err != nil { t.Fatalf("failed to create dummy multimodal projector file: %v", err) @@ -871,12 +835,7 @@ func TestResetStore(t *testing.T) { for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { - // Create a temporary directory for the test store - tempDir, err := os.MkdirTemp("", "reset-store-test") - if err != nil { - t.Fatalf("Failed to create temp directory: %v", err) - } - defer os.RemoveAll(tempDir) + tempDir := t.TempDir() // Create store storePath := filepath.Join(tempDir, "reset-model-store") @@ -1033,12 +992,7 @@ func TestResetStore(t *testing.T) { } func TestWriteLightweight(t *testing.T) { - // Create a temporary directory for the test store - tempDir, err := os.MkdirTemp("", "lightweight-write-test") - if err != nil { - t.Fatalf("Failed to create temp directory: %v", err) - } - defer os.RemoveAll(tempDir) + tempDir := t.TempDir() // Create store storePath := filepath.Join(tempDir, "lightweight-model-store") diff --git a/pkg/distribution/packaging/dirtar_test.go b/pkg/distribution/packaging/dirtar_test.go index 4d91c414..ea764f59 100644 --- a/pkg/distribution/packaging/dirtar_test.go +++ b/pkg/distribution/packaging/dirtar_test.go @@ -10,12 +10,7 @@ import ( ) func TestCreateDirTarArchive(t *testing.T) { - // Create a temporary directory with some test files - tempDir, err := os.MkdirTemp("", "dirtar-test-*") - if err != nil { - t.Fatalf("Failed to create temp dir: %v", err) - } - defer os.RemoveAll(tempDir) + tempDir := t.TempDir() // Create test directory structure testDir := filepath.Join(tempDir, "test_directory") @@ -125,12 +120,7 @@ func TestCreateDirTarArchive_NotADirectory(t *testing.T) { } func TestDirTarProcessor_ValidRelativePaths(t *testing.T) { - // Create a temporary base directory with subdirectories - tempDir, err := os.MkdirTemp("", "dirtar-processor-test-*") - if err != nil { - t.Fatalf("Failed to create temp dir: %v", err) - } - defer os.RemoveAll(tempDir) + tempDir := t.TempDir() // Create test subdirectories subDir1 := filepath.Join(tempDir, "config") @@ -180,11 +170,7 @@ func TestDirTarProcessor_ValidRelativePaths(t *testing.T) { } func TestDirTarProcessor_DirectoryTraversal_DoubleDot(t *testing.T) { - tempDir, err := os.MkdirTemp("", "dirtar-security-test-*") - if err != nil { - t.Fatalf("Failed to create temp dir: %v", err) - } - defer os.RemoveAll(tempDir) + tempDir := t.TempDir() // Test various directory traversal attempts using OS-specific path separator sep := string(os.PathSeparator) @@ -213,11 +199,7 @@ func TestDirTarProcessor_DirectoryTraversal_DoubleDot(t *testing.T) { } func TestDirTarProcessor_AbsolutePathRejection(t *testing.T) { - tempDir, err := os.MkdirTemp("", "dirtar-absolute-test-*") - if err != nil { - t.Fatalf("Failed to create temp dir: %v", err) - } - defer os.RemoveAll(tempDir) + tempDir := t.TempDir() // Test absolute path rejection absolutePaths := []string{ @@ -241,14 +223,8 @@ func TestDirTarProcessor_AbsolutePathRejection(t *testing.T) { } func TestDirTarProcessor_NonExistentDirectory(t *testing.T) { - tempDir, err := os.MkdirTemp("", "dirtar-nonexistent-test-*") - if err != nil { - t.Fatalf("Failed to create temp dir: %v", err) - } - defer os.RemoveAll(tempDir) - - processor := NewDirTarProcessor([]string{"nonexistent"}, tempDir) - _, _, err = processor.Process() + processor := NewDirTarProcessor([]string{"nonexistent"}, t.TempDir()) + _, _, err := processor.Process() if err == nil { t.Error("Expected error for non-existent directory, got nil") } @@ -258,11 +234,7 @@ func TestDirTarProcessor_NonExistentDirectory(t *testing.T) { } func TestDirTarProcessor_FileInsteadOfDirectory(t *testing.T) { - tempDir, err := os.MkdirTemp("", "dirtar-file-test-*") - if err != nil { - t.Fatalf("Failed to create temp dir: %v", err) - } - defer os.RemoveAll(tempDir) + tempDir := t.TempDir() // Create a file instead of directory filePath := filepath.Join(tempDir, "not-a-dir.txt") @@ -271,7 +243,7 @@ func TestDirTarProcessor_FileInsteadOfDirectory(t *testing.T) { } processor := NewDirTarProcessor([]string{"not-a-dir.txt"}, tempDir) - _, _, err = processor.Process() + _, _, err := processor.Process() if err == nil { t.Error("Expected error for file instead of directory, got nil") } @@ -281,11 +253,7 @@ func TestDirTarProcessor_FileInsteadOfDirectory(t *testing.T) { } func TestDirTarProcessor_BaseDirItself(t *testing.T) { - tempDir, err := os.MkdirTemp("", "dirtar-basedir-test-*") - if err != nil { - t.Fatalf("Failed to create temp dir: %v", err) - } - defer os.RemoveAll(tempDir) + tempDir := t.TempDir() // Create a file in the base directory if err := os.WriteFile(filepath.Join(tempDir, "file.txt"), []byte("content"), 0644); err != nil { @@ -306,13 +274,7 @@ func TestDirTarProcessor_BaseDirItself(t *testing.T) { } func TestDirTarProcessor_EmptyList(t *testing.T) { - tempDir, err := os.MkdirTemp("", "dirtar-empty-test-*") - if err != nil { - t.Fatalf("Failed to create temp dir: %v", err) - } - defer os.RemoveAll(tempDir) - - processor := NewDirTarProcessor([]string{}, tempDir) + processor := NewDirTarProcessor([]string{}, t.TempDir()) tarPaths, cleanup, err := processor.Process() if err != nil { t.Fatalf("Process failed for empty list: %v", err) @@ -325,12 +287,7 @@ func TestDirTarProcessor_EmptyList(t *testing.T) { } func TestDirTarProcessor_DoubleDotPrefixedDirectories(t *testing.T) { - // Test that legitimate directories with names starting with ".." are accepted - tempDir, err := os.MkdirTemp("", "dirtar-doubledot-test-*") - if err != nil { - t.Fatalf("Failed to create temp dir: %v", err) - } - defer os.RemoveAll(tempDir) + tempDir := t.TempDir() // Create directories with names that start with ".." but are not traversal attempts doubleDotDirs := []string{ @@ -376,11 +333,7 @@ func TestDirTarProcessor_DoubleDotPrefixedDirectories(t *testing.T) { } func TestDirTarProcessor_SymlinkedDirectory(t *testing.T) { - tempDir, err := os.MkdirTemp("", "dirtar-symlink-test-*") - if err != nil { - t.Fatalf("Failed to create temp dir: %v", err) - } - defer os.RemoveAll(tempDir) + tempDir := t.TempDir() // Create a real directory realDir := filepath.Join(tempDir, "realdir") @@ -399,7 +352,7 @@ func TestDirTarProcessor_SymlinkedDirectory(t *testing.T) { // Test that the symlink is rejected processor := NewDirTarProcessor([]string{"symlink"}, tempDir) - _, _, err = processor.Process() + _, _, err := processor.Process() if err == nil { t.Error("Expected error for symlinked directory, got nil") } diff --git a/pkg/inference/models/handler_test.go b/pkg/inference/models/handler_test.go index 0f520a6f..a78e4f01 100644 --- a/pkg/inference/models/handler_test.go +++ b/pkg/inference/models/handler_test.go @@ -41,12 +41,7 @@ func getProjectRoot(t *testing.T) string { } func TestPullModel(t *testing.T) { - // Create temp directory for store - tempDir, err := os.MkdirTemp("", "model-distribution-test-*") - if err != nil { - t.Fatalf("Failed to create temp directory: %v", err) - } - defer os.RemoveAll(tempDir) + tempDir := t.TempDir() // Create a test registry server := httptest.NewServer(testregistry.New()) @@ -141,12 +136,7 @@ func TestPullModel(t *testing.T) { } func TestHandleGetModel(t *testing.T) { - // Create temp directory for store - tempDir, err := os.MkdirTemp("", "model-distribution-test-*") - if err != nil { - t.Fatalf("Failed to create temp directory: %v", err) - } - defer os.RemoveAll(tempDir) + tempDir := t.TempDir() // Create a test registry server := httptest.NewServer(testregistry.New()) @@ -287,15 +277,9 @@ func TestHandleGetModel(t *testing.T) { } func TestCors(t *testing.T) { - // Verify that preflight requests work against non-existing handlers or - // method-specific handlers that do not support OPTIONS t.Parallel() - tempDir, err := os.MkdirTemp("", "model-distribution-test-*") - if err != nil { - t.Fatalf("Failed to create temp directory: %v", err) - } - defer os.RemoveAll(tempDir) + tempDir := t.TempDir() tests := []struct { name string From 9640cdad5c0b0aaf7e2f0b878133290a608b8eeb Mon Sep 17 00:00:00 2001 From: David Gageot Date: Tue, 20 Jan 2026 10:43:00 +0100 Subject: [PATCH 3/4] test: replace context.Background() with t.Context() Use t.Context() instead of context.Background() in tests. This is cleaner and ensures the context is properly tied to the test's lifecycle. Available since Go 1.24. Assisted-By: cagent --- cmd/cli/commands/integration_test.go | 8 ++--- pkg/distribution/distribution/client_test.go | 29 +++++++++---------- pkg/distribution/distribution/ecr_test.go | 12 ++------ pkg/distribution/distribution/gar_test.go | 12 ++------ .../distribution/normalize_test.go | 4 +-- pkg/distribution/huggingface/client_test.go | 13 ++++----- pkg/inference/models/handler_test.go | 5 ++-- pkg/inference/scheduling/loader_test.go | 24 +++++++-------- 8 files changed, 45 insertions(+), 62 deletions(-) diff --git a/cmd/cli/commands/integration_test.go b/cmd/cli/commands/integration_test.go index 85d37efc..0bda8109 100644 --- a/cmd/cli/commands/integration_test.go +++ b/cmd/cli/commands/integration_test.go @@ -109,7 +109,7 @@ func generateReferenceTestCases(info modelInfo) []referenceTestCase { // setupTestEnv creates the complete test environment with registry and DMR func setupTestEnv(t *testing.T) *testEnv { - ctx := context.Background() + ctx := t.Context() // Set environment variables for the test process to match the DMR container. // This ensures CLI functions use the same default registry when parsing references. @@ -142,7 +142,7 @@ func setupTestEnv(t *testing.T) *testEnv { func ociRegistry(t *testing.T, ctx context.Context, net *testcontainers.DockerNetwork) string { t.Log("Starting OCI registry container...") - ctr, err := tc.Run(context.Background(), "registry:3", + ctr, err := tc.Run(t.Context(), "registry:3", network.WithNetwork([]string{"registry.local"}, net), ) require.NoError(t, err) @@ -251,7 +251,7 @@ func verifyModelInspect(t *testing.T, client *desktop.Client, ref, expectedID, e // createAndPushTestModel creates a minimal test model and pushes it to the local registry. // Returns the model ID, FQDNs for host and network access, and the manifest digest. func createAndPushTestModel(t *testing.T, registryURL, modelRef string, contextSize *int32) (modelID, hostFQDN, networkFQDN, digest string) { - ctx := context.Background() + ctx := t.Context() // Use the dummy GGUF file from assets dummyGGUFPath := filepath.Join("../../../assets/dummy.gguf") @@ -1157,7 +1157,7 @@ func int32ptr(n int32) *int32 { // the real Docker Hub (index.docker.io) as the default registry. // This is used to test that pulling from Docker Hub works correctly. func setupDockerHubTestEnv(t *testing.T) *testEnv { - ctx := context.Background() + ctx := t.Context() // Create a custom network for container communication net, err := network.New(ctx) diff --git a/pkg/distribution/distribution/client_test.go b/pkg/distribution/distribution/client_test.go index c46c514a..e3177c04 100644 --- a/pkg/distribution/distribution/client_test.go +++ b/pkg/distribution/distribution/client_test.go @@ -3,7 +3,6 @@ package distribution import ( "bufio" "bytes" - "context" "crypto/rand" "encoding/json" "errors" @@ -79,7 +78,7 @@ func TestClientPullModel(t *testing.T) { t.Run("pull without progress writer", func(t *testing.T) { // Pull model from registry without progress writer - err := client.PullModel(context.Background(), tag, nil) + err := client.PullModel(t.Context(), tag, nil) if err != nil { t.Fatalf("Failed to pull model: %v", err) } @@ -112,7 +111,7 @@ func TestClientPullModel(t *testing.T) { var progressBuffer bytes.Buffer // Pull model from registry with progress writer - if err := client.PullModel(context.Background(), tag, &progressBuffer); err != nil { + if err := client.PullModel(t.Context(), tag, &progressBuffer); err != nil { t.Fatalf("Failed to pull model: %v", err) } @@ -160,7 +159,7 @@ func TestClientPullModel(t *testing.T) { // Test with non-existent repository nonExistentRef := registryHost + "/nonexistent/model:v1.0.0" - err = testClient.PullModel(context.Background(), nonExistentRef, &progressBuffer) + err = testClient.PullModel(t.Context(), nonExistentRef, &progressBuffer) if err == nil { t.Fatal("Expected error for non-existent model, got nil") } @@ -216,7 +215,7 @@ func TestClientPullModel(t *testing.T) { } // Push model to registry - if err := testClient.PushModel(context.Background(), testTag, nil); err != nil { + if err := testClient.PushModel(t.Context(), testTag, nil); err != nil { t.Fatalf("Failed to pull model: %v", err) } @@ -262,7 +261,7 @@ func TestClientPullModel(t *testing.T) { var progressBuffer bytes.Buffer // Pull the model again - this should detect the incomplete file and pull again - if err := testClient.PullModel(context.Background(), testTag, &progressBuffer); err != nil { + if err := testClient.PullModel(t.Context(), testTag, &progressBuffer); err != nil { t.Fatalf("Failed to pull model: %v", err) } @@ -315,7 +314,7 @@ func TestClientPullModel(t *testing.T) { } // Pull first version of model - if err := testClient.PullModel(context.Background(), testTag, nil); err != nil { + if err := testClient.PullModel(t.Context(), testTag, nil); err != nil { t.Fatalf("Failed to pull first version of model: %v", err) } @@ -359,7 +358,7 @@ func TestClientPullModel(t *testing.T) { var progressBuffer bytes.Buffer // Pull model again - should get the updated version - if err := testClient.PullModel(context.Background(), testTag, &progressBuffer); err != nil { + if err := testClient.PullModel(t.Context(), testTag, &progressBuffer); err != nil { t.Fatalf("Failed to pull updated model: %v", err) } @@ -405,7 +404,7 @@ func TestClientPullModel(t *testing.T) { if err := remote.Write(ref, newMdl, remote.WithPlainHTTP(true)); err != nil { t.Fatalf("Failed to push model: %v", err) } - if err := client.PullModel(context.Background(), testTag, nil); err == nil || !errors.Is(err, ErrUnsupportedMediaType) { + if err := client.PullModel(t.Context(), testTag, nil); err == nil || !errors.Is(err, ErrUnsupportedMediaType) { t.Fatalf("Expected artifact version error, got %v", err) } }) @@ -446,7 +445,7 @@ func TestClientPullModel(t *testing.T) { // Try to pull the safetensors model with a progress writer to capture warnings var progressBuf bytes.Buffer - err = testClient.PullModel(context.Background(), testTag, &progressBuf) + err = testClient.PullModel(t.Context(), testTag, &progressBuf) // Pull should succeed on all platforms now (with a warning on non-Linux) if err != nil { @@ -478,7 +477,7 @@ func TestClientPullModel(t *testing.T) { var progressBuffer bytes.Buffer // Pull model from registry with progress writer - if err := testClient.PullModel(context.Background(), tag, &progressBuffer); err != nil { + if err := testClient.PullModel(t.Context(), tag, &progressBuffer); err != nil { t.Fatalf("Failed to pull model: %v", err) } @@ -548,7 +547,7 @@ func TestClientPullModel(t *testing.T) { // Test with non-existent model nonExistentRef := registryHost + "/nonexistent/model:v1.0.0" - err = testClient.PullModel(context.Background(), nonExistentRef, &progressBuffer) + err = testClient.PullModel(t.Context(), nonExistentRef, &progressBuffer) // Expect an error if err == nil { @@ -806,7 +805,7 @@ func TestNewReferenceError(t *testing.T) { // Test with invalid reference invalidRef := "invalid:reference:format" - err = client.PullModel(context.Background(), invalidRef, nil) + err = client.PullModel(t.Context(), invalidRef, nil) if err == nil { t.Fatal("Expected error for invalid reference, got nil") } @@ -851,7 +850,7 @@ func TestPush(t *testing.T) { } // Push the model to the registry - if err := client.PushModel(context.Background(), tag, nil); err != nil { + if err := client.PushModel(t.Context(), tag, nil); err != nil { t.Fatalf("Failed to push model: %v", err) } @@ -861,7 +860,7 @@ func TestPush(t *testing.T) { } // Test that model can be pulled successfully - if err := client.PullModel(context.Background(), tag, nil); err != nil { + if err := client.PullModel(t.Context(), tag, nil); err != nil { t.Fatalf("Failed to pull model: %v", err) } diff --git a/pkg/distribution/distribution/ecr_test.go b/pkg/distribution/distribution/ecr_test.go index 30d68639..699b8dbb 100644 --- a/pkg/distribution/distribution/ecr_test.go +++ b/pkg/distribution/distribution/ecr_test.go @@ -1,7 +1,6 @@ package distribution import ( - "context" "os" "testing" @@ -20,12 +19,7 @@ func TestECRIntegration(t *testing.T) { t.Fatal("TEST_ECR_TAG environment variable is required") } - // Create temp directory for store - tempDir, err := os.MkdirTemp("", "model-distribution-ecr-test-*") - if err != nil { - t.Fatalf("Failed to create temp directory: %v", err) - } - defer os.RemoveAll(tempDir) + tempDir := t.TempDir() // Create client client, err := NewClient(WithStoreRootPath(tempDir)) @@ -49,7 +43,7 @@ func TestECRIntegration(t *testing.T) { if err := client.store.Write(mdl, []string{ecrTag}, nil); err != nil { t.Fatalf("Failed to write model to store: %v", err) } - if err := client.PushModel(context.Background(), ecrTag, nil); err != nil { + if err := client.PushModel(t.Context(), ecrTag, nil); err != nil { t.Fatalf("Failed to push model to ECR: %v", err) } if _, err := client.DeleteModel(ecrTag, false); err != nil { // cleanup @@ -59,7 +53,7 @@ func TestECRIntegration(t *testing.T) { // Test pull from ECR t.Run("Pull without progress", func(t *testing.T) { - err := client.PullModel(context.Background(), ecrTag, nil) + err := client.PullModel(t.Context(), ecrTag, nil) if err != nil { t.Fatalf("Failed to pull model from ECR: %v", err) } diff --git a/pkg/distribution/distribution/gar_test.go b/pkg/distribution/distribution/gar_test.go index 05f36482..669e10c1 100644 --- a/pkg/distribution/distribution/gar_test.go +++ b/pkg/distribution/distribution/gar_test.go @@ -1,7 +1,6 @@ package distribution import ( - "context" "os" "testing" @@ -20,12 +19,7 @@ func TestGARIntegration(t *testing.T) { t.Fatal("TEST_GAR_TAG environment variable is required") } - // Create temp directory for store - tempDir, err := os.MkdirTemp("", "model-distribution-gar-test-*") - if err != nil { - t.Fatalf("Failed to create temp directory: %v", err) - } - defer os.RemoveAll(tempDir) + tempDir := t.TempDir() // Create client client, err := NewClient(WithStoreRootPath(tempDir)) @@ -50,7 +44,7 @@ func TestGARIntegration(t *testing.T) { if err := client.store.Write(mdl, []string{garTag}, nil); err != nil { t.Fatalf("Failed to write model to store: %v", err) } - if err := client.PushModel(context.Background(), garTag, nil); err != nil { + if err := client.PushModel(t.Context(), garTag, nil); err != nil { t.Fatalf("Failed to push model to ECR: %v", err) } if _, err := client.DeleteModel(garTag, false); err != nil { // cleanup @@ -60,7 +54,7 @@ func TestGARIntegration(t *testing.T) { // Test pull from GAR t.Run("Pull without progress", func(t *testing.T) { - err := client.PullModel(context.Background(), garTag, nil) + err := client.PullModel(t.Context(), garTag, nil) if err != nil { t.Fatalf("Failed to pull model from GAR: %v", err) } diff --git a/pkg/distribution/distribution/normalize_test.go b/pkg/distribution/distribution/normalize_test.go index 11754708..eff18597 100644 --- a/pkg/distribution/distribution/normalize_test.go +++ b/pkg/distribution/distribution/normalize_test.go @@ -1,7 +1,6 @@ package distribution import ( - "context" "io" "path/filepath" "strings" @@ -450,8 +449,7 @@ func loadTestModel(t *testing.T, client *Client, ggufPath string) string { t.Fatalf("Failed to create builder from GGUF: %v", err) } - ctx := context.Background() - if err := bldr.Build(ctx, target, nil); err != nil { + if err := bldr.Build(t.Context(), target, nil); err != nil { t.Fatalf("Failed to build model: %v", err) } diff --git a/pkg/distribution/huggingface/client_test.go b/pkg/distribution/huggingface/client_test.go index e33dff7a..f02a9343 100644 --- a/pkg/distribution/huggingface/client_test.go +++ b/pkg/distribution/huggingface/client_test.go @@ -1,7 +1,6 @@ package huggingface import ( - "context" "encoding/json" "errors" "io" @@ -30,7 +29,7 @@ func TestClientListFiles(t *testing.T) { client := NewClient(WithBaseURL(server.URL)) - files, err := client.ListFiles(context.Background(), "test-org/test-model", "main") + files, err := client.ListFiles(t.Context(), "test-org/test-model", "main") if err != nil { t.Fatalf("ListFiles failed: %v", err) } @@ -52,7 +51,7 @@ func TestClientListFilesDefaultRevision(t *testing.T) { defer server.Close() client := NewClient(WithBaseURL(server.URL)) - _, err := client.ListFiles(context.Background(), "test/model", "") + _, err := client.ListFiles(t.Context(), "test/model", "") if err != nil { t.Fatalf("ListFiles failed: %v", err) } @@ -73,7 +72,7 @@ func TestClientDownloadFile(t *testing.T) { client := NewClient(WithBaseURL(server.URL)) - reader, size, err := client.DownloadFile(context.Background(), "test-org/test-model", "main", "test.txt") + reader, size, err := client.DownloadFile(t.Context(), "test-org/test-model", "main", "test.txt") if err != nil { t.Fatalf("DownloadFile failed: %v", err) } @@ -101,7 +100,7 @@ func TestClientAuthError(t *testing.T) { client := NewClient(WithBaseURL(server.URL)) - _, err := client.ListFiles(context.Background(), "private/model", "main") + _, err := client.ListFiles(t.Context(), "private/model", "main") if err == nil { t.Fatal("Expected error, got nil") } @@ -120,7 +119,7 @@ func TestClientNotFoundError(t *testing.T) { client := NewClient(WithBaseURL(server.URL)) - _, err := client.ListFiles(context.Background(), "nonexistent/model", "main") + _, err := client.ListFiles(t.Context(), "nonexistent/model", "main") if err == nil { t.Fatal("Expected error, got nil") } @@ -146,7 +145,7 @@ func TestClientWithToken(t *testing.T) { WithToken("test-token"), ) - _, err := client.ListFiles(context.Background(), "test/model", "main") + _, err := client.ListFiles(t.Context(), "test/model", "main") if err != nil { t.Fatalf("ListFiles failed: %v", err) } diff --git a/pkg/inference/models/handler_test.go b/pkg/inference/models/handler_test.go index a78e4f01..d8c0d580 100644 --- a/pkg/inference/models/handler_test.go +++ b/pkg/inference/models/handler_test.go @@ -1,7 +1,6 @@ package models import ( - "context" "encoding/json" "io" "net/http" @@ -72,7 +71,7 @@ func TestPullModel(t *testing.T) { if err != nil { t.Fatalf("Failed to create model target: %v", err) } - err = license.Build(context.Background(), target, os.Stdout) + err = license.Build(t.Context(), target, os.Stdout) if err != nil { t.Fatalf("Failed to build model: %v", err) } @@ -166,7 +165,7 @@ func TestHandleGetModel(t *testing.T) { if err != nil { t.Fatalf("Failed to create model target: %v", err) } - err = license.Build(context.Background(), target, os.Stdout) + err = license.Build(t.Context(), target, os.Stdout) if err != nil { t.Fatalf("Failed to build model: %v", err) } diff --git a/pkg/inference/scheduling/loader_test.go b/pkg/inference/scheduling/loader_test.go index d9cf28ca..5d7d9d26 100644 --- a/pkg/inference/scheduling/loader_test.go +++ b/pkg/inference/scheduling/loader_test.go @@ -68,9 +68,9 @@ const ( // createDefunctMockRunner creates a mock runner with a closed done channel, // simulating a defunct (crashed/terminated) runner for testing -func createDefunctMockRunner(log *logrus.Entry, backend inference.Backend) *runner { +func createDefunctMockRunner(ctx context.Context, log *logrus.Entry, backend inference.Backend) *runner { defunctRunnerDone := make(chan struct{}) - _, defunctRunnerCancel := context.WithCancel(context.Background()) + _, defunctRunnerCancel := context.WithCancel(ctx) // Create minimal HTTP client and transport to avoid nil pointer errors transport := &http.Transport{} @@ -97,8 +97,8 @@ func createDefunctMockRunner(log *logrus.Entry, backend inference.Backend) *runn // createAliveTerminableMockRunner creates a mock runner with an open done channel // (i.e., not defunct) that will close when cancel is invoked, so terminate() returns. -func createAliveTerminableMockRunner(log *logrus.Entry, backend inference.Backend) *runner { - runCtx, cancel := context.WithCancel(context.Background()) +func createAliveTerminableMockRunner(ctx context.Context, log *logrus.Entry, backend inference.Backend) *runner { + runCtx, cancel := context.WithCancel(ctx) done := make(chan struct{}) // Create minimal HTTP client and transport to avoid nil pointer errors @@ -233,18 +233,18 @@ func TestDefunctRunnerEvictionTriggersRetry(t *testing.T) { loader := newLoader(log, backends, nil, nil) // Enable loads directly under the lock (no background run loop needed) - if !loader.lock(context.Background()) { + if !loader.lock(t.Context()) { t.Fatal("Failed to acquire loader lock to enable loads") } loader.loadsEnabled = true loader.unlock() // Set up a defunct runner in the loader's state to simulate an existing crashed runner - if !loader.lock(context.Background()) { + if !loader.lock(t.Context()) { t.Fatal("Failed to acquire loader lock") } - defunctRunner := createDefunctMockRunner(log, backend) + defunctRunner := createDefunctMockRunner(t.Context(), log, backend) // Register the defunct runner in slot 0 slot := 0 @@ -259,7 +259,7 @@ func TestDefunctRunnerEvictionTriggersRetry(t *testing.T) { loader.unlock() // Attempt to load - with fastFail backend, this should return quickly after eviction+retry - _, err := loader.load(context.Background(), "test-backend", "model1", "model1:latest", inference.BackendModeCompletion) + _, err := loader.load(t.Context(), "test-backend", "model1", "model1:latest", inference.BackendModeCompletion) // We expect an error (backend fails fast), but not a timeout/hang if errors.Is(err, context.DeadlineExceeded) { @@ -289,18 +289,18 @@ func TestUnusedRunnerEvictionTriggersRetry(t *testing.T) { loader := newLoader(log, backends, nil, nil) // Enable loads directly - if !loader.lock(context.Background()) { + if !loader.lock(t.Context()) { t.Fatal("Failed to acquire loader lock to enable loads") } loader.loadsEnabled = true loader.unlock() // Install an unused, alive runner under a different model key occupying all memory - if !loader.lock(context.Background()) { + if !loader.lock(t.Context()) { t.Fatal("Failed to acquire loader lock") } - aliveRunner := createAliveTerminableMockRunner(log, backend) + aliveRunner := createAliveTerminableMockRunner(t.Context(), log, backend) slot := 0 loader.slots[slot] = aliveRunner loader.runners[makeRunnerKey("test-backend", "modelX", "", inference.BackendModeCompletion)] = runnerInfo{ @@ -313,7 +313,7 @@ func TestUnusedRunnerEvictionTriggersRetry(t *testing.T) { loader.unlock() // Attempt to load a different model; eviction should occur and loop should retry immediately - _, err := loader.load(context.Background(), "test-backend", "model1", "model1:latest", inference.BackendModeCompletion) + _, err := loader.load(t.Context(), "test-backend", "model1", "model1:latest", inference.BackendModeCompletion) if errors.Is(err, context.DeadlineExceeded) { t.Error("load() timed out - eviction of unused runner did not trigger retry") From 0ad19e29de31c4f921d6e853096edf658059f821 Mon Sep 17 00:00:00 2001 From: David Gageot Date: Tue, 20 Jan 2026 10:52:49 +0100 Subject: [PATCH 4/4] lint: add forbidigo rules for modern test patterns Add lint rules to enforce modern Go test patterns: - t.TempDir() instead of os.MkdirTemp() in tests - t.Setenv() instead of os.Setenv() in tests - t.Context() instead of context.Background()/context.TODO() in tests The rules use forbidigo with proper pattern syntax (matching identifier names without parentheses) and are scoped to test files only via an exclusion rule with 'path-except: _test\.go$'. Assisted-By: cagent --- .golangci.yml | 15 ++++++++++++++- 1 file changed, 14 insertions(+), 1 deletion(-) diff --git a/.golangci.yml b/.golangci.yml index 060891ae..50844ccc 100644 --- a/.golangci.yml +++ b/.golangci.yml @@ -75,8 +75,16 @@ linters: forbidigo: forbid: + # General rule - applies everywhere (pkg: all preserves original behavior) - pkg: all - pattern: ^(fmt\.Print(|f|ln)|print|println)$ + pattern: '^(fmt\.Print(|f|ln)|print|println)$' + # Test-specific rules (scoped to test files via exclusions below) + - pattern: '^os\.MkdirTemp$' + msg: "use t.TempDir() instead of os.MkdirTemp() in tests" + - pattern: '^os\.Setenv$' + msg: "use t.Setenv() instead of os.Setenv() in tests" + - pattern: '^context\.(Background|TODO)$' + msg: "use t.Context() instead of context.Background()/context.TODO() in tests" analyze-types: true gocritic: @@ -221,6 +229,11 @@ linters: linters: - staticcheck text: "SA5011" + # Exclude test-specific forbidigo rules from non-test files + - path-except: '_test\.go$' + linters: + - forbidigo + text: 'use t\.' issues: # Maximum issues count per one linter. Set to 0 to disable. Default is 50.