Skip to content

Modern Docker Management, Designed for Everyone

chore: refactor tests in the backend

Kyle Mendellde735b05ce3e
diff --git a/backend/api/api_test.go b/backend/api/api_test.go
index 5d017ade6..5bf22f7a4 100644
--- a/backend/api/api_test.go
+++ b/backend/api/api_test.go
@@ -29,76 +29,77 @@ func TestCustomSchemaNamer_PrefixesArcaneTypesByPackage(t *testing.T) {
imageName := customSchemaNamer(reflect.TypeFor[imagetypes.Summary](), "")
envName := customSchemaNamer(reflect.TypeFor[envtypes.Summary](), "")
- if imageName != "ImageSummary" {
- t.Fatalf("expected ImageSummary, got %q", imageName)
- }
- if envName != "EnvSummary" {
- t.Fatalf("expected EnvSummary, got %q", envName)
- }
+ require.Equal(t, "ImageSummary", imageName,
+ "expected ImageSummary, got %q", imageName)
+
+ require.Equal(t, "EnvSummary", envName,
+ "expected EnvSummary, got %q", envName)
+
}
func TestCustomSchemaNamer_PointerMatchesValue(t *testing.T) {
valueName := customSchemaNamer(reflect.TypeFor[imagetypes.Summary](), "")
pointerName := customSchemaNamer(reflect.TypeFor[*imagetypes.Summary](), "")
- if valueName != pointerName {
- t.Fatalf("expected pointer and value names to match, got %q and %q", valueName, pointerName)
- }
+ require.Equal(t, pointerName, valueName,
+ "expected pointer and value names to match, got %q and %q", valueName, pointerName)
genericValueName := customSchemaNamer(reflect.TypeFor[basetypes.ApiResponse[containertypes.StatusCounts]](), "")
genericPointerName := customSchemaNamer(reflect.TypeFor[*basetypes.ApiResponse[containertypes.StatusCounts]](), "")
- if genericValueName != genericPointerName {
- t.Fatalf("expected generic pointer and value names to match, got %q and %q", genericValueName, genericPointerName)
- }
+
+ require.Equal(t, genericPointerName, genericValueName,
+ "expected generic pointer and value names to match, got %q and %q", genericValueName, genericPointerName)
+
}
func TestCustomSchemaNamer_PrefixesDockerTypes(t *testing.T) {
name := customSchemaNamer(reflect.TypeFor[dockernetwork.Inspect](), "")
- if !strings.HasPrefix(name, "DockerNetwork") {
- t.Fatalf("expected DockerNetwork prefix, got %q", name)
- }
+
+ require.True(t, strings.HasPrefix(name, "DockerNetwork"),
+ "expected DockerNetwork prefix, got %q", name)
+
}
func TestCustomSchemaNamer_DisambiguatesGenericDomainTypes(t *testing.T) {
volumeResp := customSchemaNamer(reflect.TypeFor[basetypes.ApiResponse[volumetypes.UsageCounts]](), "")
imageResp := customSchemaNamer(reflect.TypeFor[basetypes.ApiResponse[imagetypes.UsageCounts]](), "")
- if !strings.Contains(volumeResp, "VolumeUsageCounts") {
- t.Fatalf("expected VolumeUsageCounts in name, got %q", volumeResp)
- }
- if !strings.Contains(imageResp, "ImageUsageCounts") {
- t.Fatalf("expected ImageUsageCounts in name, got %q", imageResp)
- }
- if volumeResp == imageResp {
- t.Fatalf("expected unique generic schema names, got %q", volumeResp)
- }
+ require.Contains(t, volumeResp, "VolumeUsageCounts",
+ "expected VolumeUsageCounts in name, got %q", volumeResp)
+
+ require.Contains(t, imageResp, "ImageUsageCounts",
+ "expected ImageUsageCounts in name, got %q", imageResp)
+
+ require.NotEqual(t, imageResp, volumeResp,
+ "expected unique generic schema names, got %q", volumeResp)
containerResp := customSchemaNamer(reflect.TypeFor[basetypes.ApiResponse[containertypes.StatusCounts]](), "")
projectResp := customSchemaNamer(reflect.TypeFor[basetypes.ApiResponse[projecttypes.StatusCounts]](), "")
- if !strings.Contains(containerResp, "ContainerStatusCounts") {
- t.Fatalf("expected ContainerStatusCounts in name, got %q", containerResp)
- }
- if !strings.Contains(projectResp, "ProjectStatusCounts") {
- t.Fatalf("expected ProjectStatusCounts in name, got %q", projectResp)
- }
- if containerResp == projectResp {
- t.Fatalf("expected unique generic schema names, got %q", containerResp)
- }
+
+ require.Contains(t, containerResp, "ContainerStatusCounts",
+ "expected ContainerStatusCounts in name, got %q", containerResp)
+
+ require.Contains(t, projectResp, "ProjectStatusCounts",
+ "expected ProjectStatusCounts in name, got %q", projectResp)
+
+ require.NotEqual(t, projectResp, containerResp,
+ "expected unique generic schema names, got %q", containerResp)
baseResp := customSchemaNamer(reflect.TypeFor[basetypes.ApiResponse[basetypes.MessageResponse]](), "")
- if strings.Contains(baseResp, "BaseApiResponseBase") {
- t.Fatalf("expected base generic argument without redundant package prefix, got %q", baseResp)
- }
+
+ require.NotContains(t, baseResp, "BaseApiResponseBase",
+ "expected base generic argument without redundant package prefix, got %q", baseResp)
multiArgument := customSchemaNamer(reflect.TypeFor[basetypes.PaginatedWithCounts[networktypes.Summary, networktypes.UsageCounts]](), "")
- if multiArgument != "BasePaginatedWithCountsNetworkSummaryNetworkUsageCounts" {
- t.Fatalf("expected both generic arguments to be package-qualified in order, got %q", multiArgument)
- }
+
+ require.Equal(t, "BasePaginatedWithCountsNetworkSummaryNetworkUsageCounts", multiArgument,
+ "expected both generic arguments to be package-qualified in order, got %q", multiArgument)
mixedPackages := customSchemaNamer(reflect.TypeFor[basetypes.PaginatedWithCounts[dockercontainer.Summary, imagetypes.Summary]](), "")
- if mixedPackages != "BasePaginatedWithCountsSummaryImageSummary" {
- t.Fatalf("expected only the Arcane argument to be qualified in place, got %q", mixedPackages)
- }
+
+ require.Equal(t, "BasePaginatedWithCountsSummaryImageSummary", mixedPackages,
+ "expected only the Arcane argument to be qualified in place, got %q", mixedPackages)
+
}
func TestHandlerDeps_ZeroValue(t *testing.T) {
@@ -116,9 +117,9 @@ func TestSetupAPIForSpec_DefaultSecurity(t *testing.T) {
{"ApiKeyAuth": {}},
}
- if !reflect.DeepEqual(api.OpenAPI().Security, expectedSecurity) {
- t.Fatalf("expected default API security %v, got %v", expectedSecurity, api.OpenAPI().Security)
- }
+ require.True(t, reflect.DeepEqual(api.OpenAPI().Security, expectedSecurity),
+ "expected default API security %v, got %v", expectedSecurity, api.OpenAPI().Security)
+
}
func TestSetupAPIForSpecUsesV2JSONFormats(t *testing.T) {
@@ -131,12 +132,18 @@ func TestSetupAPIForSpecUsesV2JSONFormats(t *testing.T) {
for _, contentType := range []string{"application/json", "application/problem+json"} {
t.Run(contentType, func(t *testing.T) {
var body bytes.Buffer
- if err := api.Marshal(&body, contentType, response{}); err != nil {
- t.Fatalf("marshal %s: %v", contentType, err)
+ {
+ err := api.Marshal(&body, contentType, response{})
+ require.NoError(t, err,
+ "marshal %s: %v", contentType, err)
}
- if got, want := body.String(), `{"items":[],"count":0}`; got != want {
- t.Fatalf("marshal %s = %s, want %s", contentType, got, want)
+ {
+
+ got, want := body.String(), `{"items":[],"count":0}`
+ require.Equal(t, want, got,
+ "marshal %s = %s, want %s", contentType, got, want)
}
+
})
}
}
@@ -148,12 +155,18 @@ func TestSetupAPIForSpecPreservesDurationNanoseconds(t *testing.T) {
api := SetupAPIForSpec()
var body bytes.Buffer
- if err := api.Marshal(&body, "application/json", response{HeartbeatPeriod: 5 * time.Second}); err != nil {
- t.Fatalf("marshal duration: %v", err)
+ {
+ err := api.Marshal(&body, "application/json", response{HeartbeatPeriod: 5 * time.Second})
+ require.NoError(t, err,
+ "marshal duration: %v", err)
}
- if got, want := body.String(), `{"heartbeatPeriod":5000000000}`; got != want {
- t.Fatalf("marshal duration = %s, want %s", got, want)
+ {
+
+ got, want := body.String(), `{"heartbeatPeriod":5000000000}`
+ require.Equal(t, want, got,
+ "marshal duration = %s, want %s", got, want)
}
+
}
func TestSetupAPIForSpec_PublicRoutesOverrideSecurity(t *testing.T) {
@@ -161,9 +174,9 @@ func TestSetupAPIForSpec_PublicRoutesOverrideSecurity(t *testing.T) {
getOperation := func(path, method string) *humav2.Operation {
pathItem := api.OpenAPI().Paths[path]
- if pathItem == nil {
- t.Fatalf("expected path %q to be registered", path)
- }
+
+ require.NotNil(t, pathItem,
+ "expected path %q to be registered", path)
switch method {
case "GET":
@@ -173,7 +186,7 @@ func TestSetupAPIForSpec_PublicRoutesOverrideSecurity(t *testing.T) {
case "HEAD":
return pathItem.Head
default:
- t.Fatalf("unsupported method %q", method)
+ require.FailNowf(t, "unexpected failure", "unsupported method %q", method)
return nil
}
}
@@ -207,15 +220,16 @@ func TestSetupAPIForSpec_PublicRoutesOverrideSecurity(t *testing.T) {
for _, testCase := range testCases {
t.Run(testCase.method+" "+testCase.path, func(t *testing.T) {
operation := getOperation(testCase.path, testCase.method)
- if operation == nil {
- t.Fatalf("expected operation %s %s to be registered", testCase.method, testCase.path)
- }
- if operation.Security == nil {
- t.Fatalf("expected operation %s %s to explicitly override security", testCase.method, testCase.path)
- }
- if len(operation.Security) != 0 {
- t.Fatalf("expected operation %s %s to be public, got security %v", testCase.method, testCase.path, operation.Security)
- }
+
+ require.NotNil(t, operation,
+ "expected operation %s %s to be registered", testCase.method, testCase.path)
+
+ require.NotNil(t, operation.Security,
+ "expected operation %s %s to explicitly override security", testCase.method, testCase.path)
+
+ require.Empty(t, operation.Security,
+ "expected operation %s %s to be public, got security %v", testCase.method, testCase.path, operation.Security)
+
})
}
}
@@ -240,15 +254,16 @@ func TestSetupAPIForSpec_TemplateReadRoutesProtected(t *testing.T) {
for _, testCase := range testCases {
t.Run(testCase.path, func(t *testing.T) {
pathItem := api.OpenAPI().Paths[testCase.path]
- if pathItem == nil || pathItem.Get == nil {
- t.Fatalf("expected GET %s to be registered", testCase.path)
- }
- if pathItem.Get.Security != nil {
- t.Fatalf("expected GET %s to inherit API security, got explicit security %v", testCase.path, pathItem.Get.Security)
- }
- if !reflect.DeepEqual(api.OpenAPI().Security, expectedSecurity) {
- t.Fatalf("expected API security %v, got %v", expectedSecurity, api.OpenAPI().Security)
- }
+
+ require.False(t, pathItem == nil || pathItem.Get == nil,
+ "expected GET %s to be registered", testCase.path)
+
+ require.Nil(t, pathItem.Get.Security,
+ "expected GET %s to inherit API security, got explicit security %v", testCase.path, pathItem.Get.Security)
+
+ require.True(t, reflect.DeepEqual(api.OpenAPI().Security, expectedSecurity),
+ "expected API security %v, got %v", expectedSecurity, api.OpenAPI().Security)
+
})
}
}
@@ -257,12 +272,13 @@ func TestSetupAPIForSpec_DoesNotRegisterPublicCreateEvent(t *testing.T) {
api := SetupAPIForSpec()
pathItem := api.OpenAPI().Paths["/events"]
- if pathItem == nil {
- t.Fatal("expected /events path to be registered for list events")
- }
- if pathItem.Post != nil {
- t.Fatal("expected POST /events to be absent from the public API")
- }
+
+ require.NotNil(t, pathItem,
+ "expected /events path to be registered for list events")
+
+ require.Nil(t, pathItem.Post,
+ "expected POST /events to be absent from the public API")
+
}
func TestVariableMaterializationRoutesAreAgentOnly(t *testing.T) {
diff --git a/backend/api/env_scoped_permission_test.go b/backend/api/env_scoped_permission_test.go
index df8df69c0..157f13a7a 100644
--- a/backend/api/env_scoped_permission_test.go
+++ b/backend/api/env_scoped_permission_test.go
@@ -9,6 +9,8 @@ import (
"github.com/danielgtaylor/huma/v2"
"github.com/getarcaneapp/arcane/backend/v2/pkg/authz"
+ "github.com/stretchr/testify/assert"
+ "github.com/stretchr/testify/require"
)
// TestEnvScopedOperationsDeclarePermission guards the remote-environment proxy
@@ -19,12 +21,13 @@ import (
// to an agent. An operation missing this metadata would be denied by the proxy
// (default-deny), so this test fails loudly if any env-scoped operation is
// registered with a bare huma.Register instead of RegisterWithPermission.
+
func TestEnvScopedOperationsDeclarePermission(t *testing.T) {
api := SetupAPIForSpec()
oapi := api.OpenAPI()
- if oapi == nil || oapi.Paths == nil {
- t.Fatal("expected an OpenAPI document with paths")
- }
+
+ require.False(t, oapi == nil || oapi.Paths == nil,
+ "expected an OpenAPI document with paths")
var missing []string
for path, item := range oapi.Paths {
@@ -50,7 +53,7 @@ func TestEnvScopedOperationsDeclarePermission(t *testing.T) {
if len(missing) > 0 {
sort.Strings(missing)
- t.Errorf("%d env-scoped operation(s) missing required-permission metadata; register them with middleware.RegisterWithPermission:\n %s",
+ assert.Failf(t, "unexpected failure", "%d env-scoped operation(s) missing required-permission metadata; register them with middleware.RegisterWithPermission:\n %s",
len(missing), strings.Join(missing, "\n "))
}
}
diff --git a/backend/api/handlers/activities_test.go b/backend/api/handlers/activities_test.go
index 8111fb1ab..7e5434cd1 100644
--- a/backend/api/handlers/activities_test.go
+++ b/backend/api/handlers/activities_test.go
@@ -22,6 +22,7 @@ import (
"github.com/getarcaneapp/arcane/backend/v2/pkg/authz"
"github.com/getarcaneapp/arcane/types/v2/activity"
streamtypes "github.com/getarcaneapp/arcane/types/v2/stream"
+ "github.com/stretchr/testify/assert"
)
func setupActivityHandlerTestDBInternal(t *testing.T) *database.DB {
@@ -88,10 +89,18 @@ func TestActivityHandlerClearHistoryProxiesRemoteEnvironmentInternal(t *testing.
token := "remote-token"
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
- require.Equal(t, http.MethodDelete, r.Method)
- require.Equal(t, "/api/environments/0/activities/history", r.URL.Path)
- require.Equal(t, token, r.Header.Get("X-API-Key"))
- require.Equal(t, token, r.Header.Get("X-Arcane-Agent-Token"))
+ if !assert.Equal(t, http.MethodDelete, r.Method) {
+ return
+ }
+ if !assert.Equal(t, "/api/environments/0/activities/history", r.URL.Path) {
+ return
+ }
+ if !assert.Equal(t, token, r.Header.Get("X-API-Key")) {
+ return
+ }
+ if !assert.Equal(t, token, r.Header.Get("X-Arcane-Agent-Token")) {
+ return
+ }
w.Header().Set("Content-Type", "application/json")
_, _ = w.Write([]byte(`{"success":true,"data":{"deleted":7}}`))
}))
@@ -180,7 +189,7 @@ func runActivityClientStreamInternal(t *testing.T, ctx context.Context, cancel c
select {
case <-done:
case <-time.After(5 * time.Second):
- t.Fatal("stream did not terminate after cancel")
+ require.FailNow(t, "stream did not terminate after cancel")
}
}
diff --git a/backend/api/handlers/dashboard_test.go b/backend/api/handlers/dashboard_test.go
index 6212340d7..f0fb1e81f 100644
--- a/backend/api/handlers/dashboard_test.go
+++ b/backend/api/handlers/dashboard_test.go
@@ -22,6 +22,7 @@ import (
"github.com/libtnb/sqlite"
dockercontainer "github.com/moby/moby/api/types/container"
dockerimage "github.com/moby/moby/api/types/image"
+ "github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
"gorm.io/gorm"
)
@@ -56,9 +57,13 @@ func newDashboardHandlerTestDockerService(
w.Header().Set("API-Version", "1.41")
w.WriteHeader(http.StatusOK)
case strings.HasSuffix(r.URL.Path, "/containers/json"):
- require.NoError(t, json.NewEncoder(w).Encode(containers))
+ if !assert.NoError(t, json.NewEncoder(w).Encode(containers)) {
+ return
+ }
case strings.HasSuffix(r.URL.Path, "/images/json"):
- require.NoError(t, json.NewEncoder(w).Encode(images))
+ if !assert.NoError(t, json.NewEncoder(w).Encode(images)) {
+ return
+ }
default:
http.NotFound(w, r)
}
@@ -177,7 +182,7 @@ func runDashboardStreamAllInternal(t *testing.T, ctx context.Context, cancel con
select {
case <-done:
case <-time.After(5 * time.Second):
- t.Fatal("stream did not terminate after cancel")
+ require.FailNow(t, "stream did not terminate after cancel")
}
}
@@ -192,7 +197,9 @@ func TestDashboardHandlerStreamAllEmitsRemoteSnapshotInternal(t *testing.T) {
token := "remote-token"
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
- require.Equal(t, "/api/environments/0/dashboard", r.URL.Path)
+ if !assert.Equal(t, "/api/environments/0/dashboard", r.URL.Path) {
+ return
+ }
w.Header().Set("Content-Type", "application/json")
_, _ = w.Write([]byte(`{"success":true,"data":{
"containers":{"data":[{"id":"c1"}],"counts":{"runningContainers":2,"stoppedContainers":1,"totalContainers":3},"pagination":{"totalPages":1,"totalItems":1,"currentPage":1,"itemsPerPage":20}},
diff --git a/backend/api/handlers/edge_mtls_ca_test.go b/backend/api/handlers/edge_mtls_ca_test.go
index 9ffcabbf6..49d9e0f90 100644
--- a/backend/api/handlers/edge_mtls_ca_test.go
+++ b/backend/api/handlers/edge_mtls_ca_test.go
@@ -102,7 +102,7 @@ func TestReadGeneratedEdgeMTLSCertificateInfo(t *testing.T) {
require.NotNil(t, info.ExpiresAt)
require.True(t, info.ExpiresAt.After(time.Now().UTC()))
require.NotNil(t, info.DaysRemaining)
- require.True(t, *info.DaysRemaining > 0)
+ require.Positive(t, *info.DaysRemaining)
require.False(t, info.Expired)
require.False(t, info.ExpiringSoon)
}
diff --git a/backend/api/handlers/environments_test.go b/backend/api/handlers/environments_test.go
index 32303023c..1176fb86b 100644
--- a/backend/api/handlers/environments_test.go
+++ b/backend/api/handlers/environments_test.go
@@ -285,6 +285,5 @@ func TestFingerprintEnvironmentsDetectsFieldChange(t *testing.T) {
base := []envtypes.Environment{{ID: "1", Name: "prod", Status: "online", Enabled: true}}
renamed := []envtypes.Environment{{ID: "1", Name: "production", Status: "online", Enabled: true}}
- assert.Equal(t, fingerprintEnvironmentsInternal(base), fingerprintEnvironmentsInternal(base))
assert.NotEqual(t, fingerprintEnvironmentsInternal(base), fingerprintEnvironmentsInternal(renamed))
}
diff --git a/backend/api/handlers/git_repositories_test.go b/backend/api/handlers/git_repositories_test.go
index ffcbfd967..f9b1b4155 100644
--- a/backend/api/handlers/git_repositories_test.go
+++ b/backend/api/handlers/git_repositories_test.go
@@ -39,7 +39,7 @@ func TestGitRepositoryHandlers_PermissionGating(t *testing.T) {
Path: "/customize/git-repositories",
Middlewares: humamw.RequirePermission(api, authz.PermGitReposCreate),
}, func(_ context.Context, _ *struct{}) (*struct{}, error) {
- t.Fatal("handler must not run when permission is missing")
+ require.FailNow(t, "handler must not run when permission is missing")
return nil, nil
})
},
@@ -57,7 +57,7 @@ func TestGitRepositoryHandlers_PermissionGating(t *testing.T) {
}, func(_ context.Context, _ *struct {
ID string `path:"id"`
}) (*struct{}, error) {
- t.Fatal("handler must not run when permission is missing")
+ require.FailNow(t, "handler must not run when permission is missing")
return nil, nil
})
},
@@ -75,7 +75,7 @@ func TestGitRepositoryHandlers_PermissionGating(t *testing.T) {
}, func(_ context.Context, _ *struct {
ID string `path:"id"`
}) (*struct{}, error) {
- t.Fatal("handler must not run when permission is missing")
+ require.FailNow(t, "handler must not run when permission is missing")
return nil, nil
})
},
@@ -93,7 +93,7 @@ func TestGitRepositoryHandlers_PermissionGating(t *testing.T) {
}, func(_ context.Context, _ *struct {
ID string `path:"id"`
}) (*struct{}, error) {
- t.Fatal("handler must not run when permission is missing")
+ require.FailNow(t, "handler must not run when permission is missing")
return nil, nil
})
},
diff --git a/backend/api/handlers/remenv_handlers_test.go b/backend/api/handlers/remenv_handlers_test.go
index 526d13d57..4bd379191 100644
--- a/backend/api/handlers/remenv_handlers_test.go
+++ b/backend/api/handlers/remenv_handlers_test.go
@@ -19,12 +19,14 @@ import (
"github.com/getarcaneapp/arcane/types/v2/jobschedule"
settingstypes "github.com/getarcaneapp/arcane/types/v2/settings"
"github.com/libtnb/sqlite"
+ "github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
"gorm.io/gorm"
)
// adminTestContextInternal returns a context with a sudo PermissionSet attached,
// suitable for unit-testing handlers that gate via RequirePermission middleware.
+
func adminTestContextInternal() context.Context {
return context.WithValue(context.Background(), humamiddleware.ContextKeyUserPermissions, authz.SudoPermissionSet())
}
@@ -91,10 +93,14 @@ func TestProxyRemoteJSONInternal_MapsDecodeError(t *testing.T) {
func TestJobSchedulesHandler_ListJobs_RemoteSuccess(t *testing.T) {
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
- require.Equal(t, "/api/environments/0/jobs", r.URL.Path)
- require.NoError(t, json.NewEncoder(w).Encode(jobschedule.JobListResponse{
+ if !assert.Equal(t, "/api/environments/0/jobs", r.URL.Path) {
+ return
+ }
+ if !assert.NoError(t, json.NewEncoder(w).Encode(jobschedule.JobListResponse{
Jobs: []jobschedule.JobStatus{{ID: "job-1", Name: "Test Job"}},
- }))
+ })) {
+ return
+ }
}))
defer server.Close()
@@ -112,8 +118,12 @@ func TestJobSchedulesHandler_ListJobs_RemoteSuccess(t *testing.T) {
func TestSettingsHandler_GetPublicSettings_RemoteSuccess(t *testing.T) {
expected := []settingstypes.PublicSetting{{Key: "theme", Type: "string", Value: "dark"}}
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
- require.Equal(t, "/api/environments/0/settings/public", r.URL.Path)
- require.NoError(t, json.NewEncoder(w).Encode(expected))
+ if !assert.Equal(t, "/api/environments/0/settings/public", r.URL.Path) {
+ return
+ }
+ if !assert.NoError(t, json.NewEncoder(w).Encode(expected)) {
+ return
+ }
}))
defer server.Close()
@@ -135,8 +145,12 @@ func TestSettingsHandler_GetSettings_RemoteFiltersNonAdminVisibility(t *testing.
{Key: "futureAdminSetting", Type: "string", Value: "hidden"},
}
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
- require.Equal(t, "/api/environments/0/settings", r.URL.Path)
- require.NoError(t, json.NewEncoder(w).Encode(remoteSettings))
+ if !assert.Equal(t, "/api/environments/0/settings", r.URL.Path) {
+ return
+ }
+ if !assert.NoError(t, json.NewEncoder(w).Encode(remoteSettings)) {
+ return
+ }
}))
defer server.Close()
@@ -162,7 +176,9 @@ func TestSettingsHandler_GetSettings_RemotePreservesAdminResponse(t *testing.T)
{Key: "futureAdminSetting", Type: "string", Value: "visible-to-admin"},
}
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
- require.NoError(t, json.NewEncoder(w).Encode(remoteSettings))
+ if !assert.NoError(t, json.NewEncoder(w).Encode(remoteSettings)) {
+ return
+ }
}))
defer server.Close()
@@ -185,8 +201,12 @@ func TestVariableHandler_GetMaterializedVariables_RemoteSuccess(t *testing.T) {
Data: []env.Variable{{Key: "FOO", Value: "bar"}},
}
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
- require.Equal(t, "/api/environments/0/templates/variables", r.URL.Path)
- require.NoError(t, json.NewEncoder(w).Encode(expected))
+ if !assert.Equal(t, "/api/environments/0/templates/variables", r.URL.Path) {
+ return
+ }
+ if !assert.NoError(t, json.NewEncoder(w).Encode(expected)) {
+ return
+ }
}))
defer server.Close()
diff --git a/backend/api/handlers/roles_access_policy_test.go b/backend/api/handlers/roles_access_policy_test.go
index 91913d3c4..be2b6b3d2 100644
--- a/backend/api/handlers/roles_access_policy_test.go
+++ b/backend/api/handlers/roles_access_policy_test.go
@@ -45,10 +45,9 @@ func TestBuildPermissionsManifestIncludesEventsDelete(t *testing.T) {
return
}
}
- t.Fatalf("events resource did not include %s", authz.PermEventsDelete)
+ require.FailNowf(t, "unexpected failure", "events resource did not include %s", authz.PermEventsDelete)
}
-
- t.Fatal("events resource not found")
+ require.FailNow(t, "events resource not found")
}
func TestBuildPermissionsManifestKeepsVariablesSeparateFromTemplates(t *testing.T) {
diff --git a/backend/api/handlers/settings_test.go b/backend/api/handlers/settings_test.go
index c4b4ca100..d1ace33ae 100644
--- a/backend/api/handlers/settings_test.go
+++ b/backend/api/handlers/settings_test.go
@@ -5,7 +5,6 @@ import (
"os"
"path/filepath"
"runtime"
- "strings"
"testing"
"github.com/danielgtaylor/huma/v2"
@@ -92,7 +91,7 @@ func TestSettingsHandler_UpdateLocalEnvironment_RejectsUnreadableProjectsDirecto
var statusErr huma.StatusError
require.ErrorAs(t, err, &statusErr, "expected a huma status error")
require.Equal(t, 400, statusErr.GetStatus())
- require.True(t, strings.Contains(err.Error(), "cannot read projects directory"), "error message should explain the failure: %s", err.Error())
+ require.Contains(t, err.Error(), "cannot read projects directory", "error message should explain the failure: %s", err.Error())
require.Equal(t, originalDir, settingsSvc.GetSettingsConfig().ProjectsDirectory.Value, "projectsDirectory must not be persisted on validation failure")
}
diff --git a/backend/api/handlers/stream_test.go b/backend/api/handlers/stream_test.go
index c9a87ba2a..4e87ef0a4 100644
--- a/backend/api/handlers/stream_test.go
+++ b/backend/api/handlers/stream_test.go
@@ -65,7 +65,7 @@ func TestStreamHandlerEnvironmentsChannelEmitsUnreachableEnvironmentInternal(t *
select {
case <-done:
case <-time.After(5 * time.Second):
- t.Fatal("stream did not terminate after cancel")
+ require.FailNow(t, "stream did not terminate after cancel")
}
require.NotNil(t, seen, "expected an environments snapshot for an unreachable environment")
diff --git a/backend/api/json_serializer_benchmark_test.go b/backend/api/json_serializer_benchmark_test.go
index 9b6112238..f707f8c40 100644
--- a/backend/api/json_serializer_benchmark_test.go
+++ b/backend/api/json_serializer_benchmark_test.go
@@ -6,6 +6,8 @@ import (
jsonv2 "encoding/json/v2"
"io"
"testing"
+
+ "github.com/stretchr/testify/require"
)
type jsonBenchmarkItem struct {
@@ -43,7 +45,7 @@ func BenchmarkJSONResponseEncoding(b *testing.B) {
b.ReportAllocs()
for b.Loop() {
if err := jsonv1.NewEncoder(io.Discard).Encode(jsonBenchmarkPayload); err != nil {
- b.Fatal(err)
+ require.FailNowf(b, "benchmark JSON encoding failed", "%v", err)
}
}
})
@@ -52,7 +54,7 @@ func BenchmarkJSONResponseEncoding(b *testing.B) {
b.ReportAllocs()
for b.Loop() {
if err := jsonv2.MarshalWrite(io.Discard, jsonBenchmarkPayload, jsonV2APIOptions); err != nil {
- b.Fatal(err)
+ require.FailNowf(b, "benchmark JSON encoding failed", "%v", err)
}
}
})
@@ -61,7 +63,7 @@ func BenchmarkJSONResponseEncoding(b *testing.B) {
func BenchmarkJSONRequestDecoding(b *testing.B) {
data, err := jsonv2.Marshal(jsonBenchmarkPayload)
if err != nil {
- b.Fatal(err)
+ require.FailNowf(b, "benchmark JSON setup failed", "%v", err)
}
b.SetBytes(int64(len(data)))
@@ -71,7 +73,7 @@ func BenchmarkJSONRequestDecoding(b *testing.B) {
for b.Loop() {
var output jsonBenchmarkResponse
if err := jsonv1.NewDecoder(bytes.NewReader(data)).Decode(&output); err != nil {
- b.Fatal(err)
+ require.FailNowf(b, "benchmark JSON decoding failed", "%v", err)
}
}
})
@@ -81,7 +83,7 @@ func BenchmarkJSONRequestDecoding(b *testing.B) {
for b.Loop() {
var output jsonBenchmarkResponse
if err := jsonv2.UnmarshalRead(bytes.NewReader(data), &output, jsonV2APIOptions); err != nil {
- b.Fatal(err)
+ require.FailNowf(b, "benchmark JSON decoding failed", "%v", err)
}
}
})
diff --git a/backend/api/json_serializer_test.go b/backend/api/json_serializer_test.go
index bfd2a824e..cb3237c08 100644
--- a/backend/api/json_serializer_test.go
+++ b/backend/api/json_serializer_test.go
@@ -9,6 +9,7 @@ import (
"time"
"github.com/labstack/echo/v5"
+ "github.com/stretchr/testify/require"
)
func TestJSONV2SerializerUsesV2ResponseSemantics(t *testing.T) {
@@ -22,12 +23,16 @@ func TestJSONV2SerializerUsesV2ResponseSemantics(t *testing.T) {
context := e.NewContext(httptest.NewRequest("GET", "/", nil), recorder)
err := (jsonV2Serializer{}).Serialize(context, response{}, "")
- if err != nil {
- t.Fatalf("serialize response: %v", err)
- }
- if got, want := recorder.Body.String(), `{"items":[],"count":0}`; got != want {
- t.Fatalf("serialized response = %s, want %s", got, want)
+
+ require.NoError(t, err,
+ "serialize response: %v", err)
+ {
+
+ got, want := recorder.Body.String(), `{"items":[],"count":0}`
+ require.Equal(t, want, got,
+ "serialized response = %s, want %s", got, want)
}
+
}
func TestJSONV2SerializerPreservesDurationNanoseconds(t *testing.T) {
@@ -40,12 +45,16 @@ func TestJSONV2SerializerPreservesDurationNanoseconds(t *testing.T) {
context := e.NewContext(httptest.NewRequest("GET", "/", nil), recorder)
err := (jsonV2Serializer{}).Serialize(context, response{HeartbeatPeriod: 5 * time.Second}, "")
- if err != nil {
- t.Fatalf("serialize duration: %v", err)
- }
- if got, want := recorder.Body.String(), `{"heartbeatPeriod":5000000000}`; got != want {
- t.Fatalf("serialized response = %s, want %s", got, want)
+
+ require.NoError(t, err,
+ "serialize duration: %v", err)
+ {
+
+ got, want := recorder.Body.String(), `{"heartbeatPeriod":5000000000}`
+ require.Equal(t, want, got,
+ "serialized response = %s, want %s", got, want)
}
+
}
func TestJSONV2SerializerUsesStrictV2Decoding(t *testing.T) {
@@ -59,12 +68,13 @@ func TestJSONV2SerializerUsesStrictV2Decoding(t *testing.T) {
var body requestBody
err := (jsonV2Serializer{}).Deserialize(context, &body)
- if err != nil {
- t.Fatalf("deserialize case-variant field: %v", err)
- }
- if body.Name != "" {
- t.Fatalf("case-variant field populated Name with %q", body.Name)
- }
+
+ require.NoError(t, err,
+ "deserialize case-variant field: %v", err)
+
+ require.Empty(t, body.Name,
+ "case-variant field populated Name with %q", body.Name)
+
})
for _, test := range []struct {
@@ -82,11 +92,13 @@ func TestJSONV2SerializerUsesStrictV2Decoding(t *testing.T) {
err := (jsonV2Serializer{}).Deserialize(context, &body)
var httpErr *echo.HTTPError
if !errors.As(err, &httpErr) {
- t.Fatalf("deserialize error = %T %v, want *echo.HTTPError", err, err)
- }
- if httpErr.StatusCode() != http.StatusBadRequest {
- t.Fatalf("HTTP status = %d, want %d", httpErr.StatusCode(), http.StatusBadRequest)
+ require.ErrorAs(t, err, &httpErr,
+ "deserialize error = %T %v, want *echo.HTTPError", err, err)
}
+
+ require.Equal(t, http.StatusBadRequest, httpErr.StatusCode(),
+ "HTTP status = %d, want %d", httpErr.StatusCode(), http.StatusBadRequest)
+
})
}
}
diff --git a/backend/api/middleware/auth_test.go b/backend/api/middleware/auth_test.go
index 4647ae70b..365351903 100644
--- a/backend/api/middleware/auth_test.go
+++ b/backend/api/middleware/auth_test.go
@@ -223,7 +223,7 @@ func TestNewAuthBridge_RejectsApiKeyOnBearerOnlyOperation(t *testing.T) {
Path: "/bearer-only",
Security: []map[string][]string{{"BearerAuth": {}}},
}, func(ctx context.Context, _ *secureInput) (*secureOutput, error) {
- t.Fatal("handler must not be reached with API key auth")
+ require.FailNow(t, "handler must not be reached with API key auth")
return &secureOutput{}, nil
})
@@ -384,7 +384,7 @@ func TestNewAuthBridge_OpportunisticAuthOnPublicRoute(t *testing.T) {
rec := httptest.NewRecorder()
router.ServeHTTP(rec, req)
require.Equal(t, http.StatusOK, rec.Code)
- require.Equal(t, "", sawSessionID)
+ require.Empty(t, sawSessionID)
})
t.Run("succeeds with invalid token (does not block)", func(t *testing.T) {
@@ -394,7 +394,7 @@ func TestNewAuthBridge_OpportunisticAuthOnPublicRoute(t *testing.T) {
rec := httptest.NewRecorder()
router.ServeHTTP(rec, req)
require.Equal(t, http.StatusOK, rec.Code)
- require.Equal(t, "", sawSessionID)
+ require.Empty(t, sawSessionID)
})
}
diff --git a/backend/api/middleware/role_test.go b/backend/api/middleware/role_test.go
index d9b1980cd..9be799dc4 100644
--- a/backend/api/middleware/role_test.go
+++ b/backend/api/middleware/role_test.go
@@ -34,7 +34,7 @@ func TestRequirePermission_RejectsCallerMissingPermission(t *testing.T) {
ID string `path:"id"`
CID string `path:"cid"`
}) (*struct{}, error) {
- t.Fatal("handler must not run when permission is missing")
+ require.FailNow(t, "handler must not run when permission is missing")
return nil, nil
})
@@ -105,7 +105,7 @@ func TestRequirePermission_EnvScopedDoesNotLeakAcrossEnvs(t *testing.T) {
ID string `path:"id"`
CID string `path:"cid"`
}) (*struct{}, error) {
- t.Fatal("handler must not run when permission is scoped to a different env")
+ require.FailNow(t, "handler must not run when permission is scoped to a different env")
return nil, nil
})
@@ -134,7 +134,7 @@ func TestRequirePermissionEnvironmentGrantCannotManageGlobalNotificationsInterna
}, func(_ context.Context, _ *struct {
ID string `path:"id"`
}) (*struct{}, error) {
- t.Fatal("handler must not run for an environment-scoped grant on global notification settings")
+ require.FailNow(t, "handler must not run for an environment-scoped grant on global notification settings")
return nil, nil
})
diff --git a/backend/api/ws/handler_test.go b/backend/api/ws/handler_test.go
index 1ceec8462..32fe7f6e0 100644
--- a/backend/api/ws/handler_test.go
+++ b/backend/api/ws/handler_test.go
@@ -239,7 +239,7 @@ func TestWebSocketHandler_ProjectLogs_CompletedSourceStartsFreshStream(t *testin
select {
case <-firstDone:
case <-time.After(2 * time.Second):
- t.Fatal("first finite log stream did not complete")
+ require.FailNow(t, "first finite log stream did not complete")
}
conn2 := dialWebSocket(t, server.URL, path)
@@ -432,17 +432,17 @@ func TestWebSocketHandler_AcquireSystemStatsSampler_WaitsForInitialSnapshot(t *t
select {
case <-firstDone:
case <-time.After(2 * time.Second):
- t.Fatal("first sampler acquisition did not finish")
+ require.FailNow(t, "first sampler acquisition did not finish")
}
select {
case <-secondDone:
case <-time.After(2 * time.Second):
- t.Fatal("second sampler acquisition did not wait for readiness")
+ require.FailNow(t, "second sampler acquisition did not wait for readiness")
}
stats := handler.latestSystemStatsSnapshotInternal()
- require.Equal(t, 42.0, stats.CPUUsage)
+ require.InDelta(t, 42.0, stats.CPUUsage, 0.000001)
handler.releaseSystemStatsSamplerInternal()
handler.releaseSystemStatsSamplerInternal()
@@ -477,7 +477,7 @@ func TestWebSocketHandler_AcquireSystemStatsSampler_StopsWaitingWhenCallerCancel
select {
case <-readyToCancel:
case <-time.After(time.Second):
- t.Fatal("sampler did not start CPU initialization")
+ require.FailNow(t, "sampler did not start CPU initialization")
}
cancel()
@@ -486,7 +486,7 @@ func TestWebSocketHandler_AcquireSystemStatsSampler_StopsWaitingWhenCallerCancel
case ok := <-done:
require.False(t, ok)
case <-time.After(100 * time.Millisecond):
- t.Fatal("sampler acquisition did not stop waiting after cancellation")
+ require.FailNow(t, "sampler acquisition did not stop waiting after cancellation")
}
handler.releaseSystemStatsSamplerInternal()
@@ -607,7 +607,7 @@ func TestWebSocketHandler_GetCachedCgroupLimitsInternal_DeduplicatesRefresh(t *t
select {
case <-start:
case <-time.After(2 * time.Second):
- t.Fatal("detector was not called")
+ require.FailNow(t, "detector was not called")
}
require.Equal(t, int32(1), calls.Load())
diff --git a/backend/cli/generate/api_key_test.go b/backend/cli/generate/api_key_test.go
index 85473c890..cf7e533e0 100644
--- a/backend/cli/generate/api_key_test.go
+++ b/backend/cli/generate/api_key_test.go
@@ -3,6 +3,8 @@ package generate
import (
"strings"
"testing"
+
+ "github.com/stretchr/testify/require"
)
func TestAPIKeyCommandAvailableInBackendCLI(t *testing.T) {
@@ -13,17 +15,17 @@ func TestAPIKeyCommandAvailableInBackendCLI(t *testing.T) {
_, err := cmd.ExecuteC()
return err
})
- if err != nil {
- t.Fatalf("command failed: %v", err)
- }
-
- if strings.TrimSpace(out) == "" {
- t.Fatalf("expected raw arc_ key in output, got: %q", out)
- }
- if !strings.HasPrefix(strings.TrimSpace(out), "arc_") {
- t.Fatalf("expected raw arc_ key in output, got: %q", out)
- }
- if strings.Contains(out, "ADMIN_STATIC_API_KEY") {
- t.Fatalf("expected raw arc_ key in output, got: %q", out)
- }
+
+ require.NoError(t, err,
+ "command failed: %v", err)
+
+ require.NotEmpty(t, strings.TrimSpace(out),
+ "expected raw arc_ key in output, got: %q", out)
+
+ require.True(t, strings.HasPrefix(strings.TrimSpace(out), "arc_"),
+ "expected raw arc_ key in output, got: %q", out)
+
+ require.NotContains(t, out, "ADMIN_STATIC_API_KEY",
+ "expected raw arc_ key in output, got: %q", out)
+
}
diff --git a/backend/cli/generate/secret_test.go b/backend/cli/generate/secret_test.go
index a00e57d76..89075cb7a 100644
--- a/backend/cli/generate/secret_test.go
+++ b/backend/cli/generate/secret_test.go
@@ -8,9 +8,12 @@ import (
"os"
"strings"
"testing"
+
+ "github.com/stretchr/testify/require"
)
// captureOutput captures stdout produced by fn and returns it as a string.
+
func captureOutput(fn func() error) (string, error) {
// Save original
oldOut := os.Stdout
@@ -41,18 +44,17 @@ func TestSecretDefaultBase64(t *testing.T) {
_, err := cmd.ExecuteC()
return err
})
- if err != nil {
- t.Fatalf("command failed: %v", err)
- }
+
+ require.NoError(t, err,
+ "command failed: %v", err)
// should not include emoji characters used previously
- if strings.Contains(out, "πŸ“‹") || strings.Contains(out, "🐳") || strings.Contains(out, "πŸ”’") || strings.Contains(out, "⚠️") {
- t.Fatalf("output contains emoji/box characters: %q", out)
- }
- if !strings.Contains(out, "BASE64") {
- t.Fatalf("expected BASE64 header in output, got: %q", out)
- }
+ require.False(t, strings.Contains(out, "πŸ“‹") || strings.Contains(out, "🐳") || strings.Contains(out, "πŸ”’") || strings.Contains(out, "⚠️"),
+ "output contains emoji/box characters: %q", out)
+
+ require.Contains(t, out, "BASE64",
+ "expected BASE64 header in output, got: %q", out)
// find ENCRYPTION_KEY= and JWT_SECRET= lines and ensure they are valid base64
var encVal, jwtVal string
@@ -64,19 +66,21 @@ func TestSecretDefaultBase64(t *testing.T) {
jwtVal = after
}
}
- if encVal == "" || jwtVal == "" {
- t.Fatalf("missing keys in output: enc=%q jwt=%q out=%q", encVal, jwtVal, out)
- }
+
+ require.False(t, encVal == "" || jwtVal == "",
+ "missing keys in output: enc=%q jwt=%q out=%q", encVal, jwtVal, out)
if b, err := base64.StdEncoding.DecodeString(encVal); err != nil {
- t.Fatalf("ENCRYPTION_KEY is not valid base64: %v (value=%q)", err, encVal)
+ require.FailNowf(t, "unexpected failure", "ENCRYPTION_KEY is not valid base64: %v (value=%q)", err, encVal)
} else if len(b) != 32 {
- t.Fatalf("ENCRYPTION_KEY decoded length != 32 bytes: %d", len(b))
+ require.Len(t, b, 32,
+ "ENCRYPTION_KEY decoded length != 32 bytes: %d", len(b))
}
if b, err := base64.StdEncoding.DecodeString(jwtVal); err != nil {
- t.Fatalf("JWT_SECRET is not valid base64: %v (value=%q)", err, jwtVal)
+ require.FailNowf(t, "unexpected failure", "JWT_SECRET is not valid base64: %v (value=%q)", err, jwtVal)
} else if len(b) != 32 {
- t.Fatalf("JWT_SECRET decoded length != 32 bytes: %d", len(b))
+ require.Len(t, b, 32,
+ "JWT_SECRET decoded length != 32 bytes: %d", len(b))
}
}
@@ -88,13 +92,12 @@ func TestSecretAllFormatContainsSections(t *testing.T) {
_, err := cmd.ExecuteC()
return err
})
- if err != nil {
- t.Fatalf("command failed: %v", err)
- }
- if strings.Contains(out, "πŸ“‹") || strings.Contains(out, "🐳") || strings.Contains(out, "πŸ”’") || strings.Contains(out, "⚠️") {
- t.Fatalf("output contains emoji/box characters: %q", out)
- }
+ require.NoError(t, err,
+ "command failed: %v", err)
+
+ require.False(t, strings.Contains(out, "πŸ“‹") || strings.Contains(out, "🐳") || strings.Contains(out, "πŸ”’") || strings.Contains(out, "⚠️"),
+ "output contains emoji/box characters: %q", out)
// verify presence of expected section headers
mustContain := []string{
@@ -103,9 +106,10 @@ func TestSecretAllFormatContainsSections(t *testing.T) {
"HEX",
}
for _, s := range mustContain {
- if !strings.Contains(out, s) {
- t.Fatalf("expected section %q not found in output:\n%s", s, out)
- }
+
+ require.Contains(t, out, s,
+ "expected section %q not found in output:\n%s", s, out)
+
}
// verify hex values decode to 32 bytes
@@ -127,17 +131,20 @@ func TestSecretAllFormatContainsSections(t *testing.T) {
}
}
}
- if hexEnc == "" || hexJwt == "" {
- t.Fatalf("hex values not found in output (enc=%q jwt=%q) output:\n%s", hexEnc, hexJwt, out)
- }
+
+ require.False(t, hexEnc == "" || hexJwt == "",
+ "hex values not found in output (enc=%q jwt=%q) output:\n%s", hexEnc, hexJwt, out)
+
if b, err := hex.DecodeString(strings.TrimSpace(hexEnc)); err != nil {
- t.Fatalf("ENCRYPTION_KEY hex decode failed: %v", err)
+ require.FailNowf(t, "unexpected failure", "ENCRYPTION_KEY hex decode failed: %v", err)
} else if len(b) != 32 {
- t.Fatalf("ENCRYPTION_KEY hex decoded length != 32: %d", len(b))
+ require.Len(t, b, 32,
+ "ENCRYPTION_KEY hex decoded length != 32: %d", len(b))
}
if b, err := hex.DecodeString(strings.TrimSpace(hexJwt)); err != nil {
- t.Fatalf("JWT_SECRET hex decode failed: %v", err)
+ require.FailNowf(t, "unexpected failure", "JWT_SECRET hex decode failed: %v", err)
} else if len(b) != 32 {
- t.Fatalf("JWT_SECRET hex decoded length != 32: %d", len(b))
+ require.Len(t, b, 32,
+ "JWT_SECRET hex decoded length != 32: %d", len(b))
}
}
diff --git a/backend/cli/health_test.go b/backend/cli/health_test.go
index 24ddbd95b..87c1661ea 100644
--- a/backend/cli/health_test.go
+++ b/backend/cli/health_test.go
@@ -11,71 +11,84 @@ import (
"time"
"github.com/getarcaneapp/arcane/backend/v2/internal/config"
+ "github.com/stretchr/testify/assert"
+ "github.com/stretchr/testify/require"
)
func TestBuildHealthURLInternalDefaults(t *testing.T) {
t.Run("default_port", func(t *testing.T) {
cfg := &config.Config{}
healthURL, err := buildHealthURLInternal(cfg)
- if err != nil {
- t.Fatalf("build health URL failed: %v", err)
- }
- if !strings.HasPrefix(healthURL, "http://127.0.0.1:3552") {
- t.Fatalf("unexpected health URL: %s", healthURL)
- }
- if !strings.HasSuffix(healthURL, "/api/health") {
- t.Fatalf("expected health URL path /api/health, got: %s", healthURL)
- }
+ require.NoError(t, err,
+ "build health URL failed: %v", err)
+
+ require.True(t, strings.HasPrefix(healthURL, "http://127.0.0.1:3552"),
+ "unexpected health URL: %s", healthURL)
+
+ require.True(t, strings.HasSuffix(healthURL, "/api/health"),
+ "expected health URL path /api/health, got: %s", healthURL)
+
})
t.Run("explicit_port", func(t *testing.T) {
cfg := &config.Config{Port: "8443"}
healthURL, err := buildHealthURLInternal(cfg)
- if err != nil {
- t.Fatalf("build health URL failed: %v", err)
- }
- if !strings.HasPrefix(healthURL, "http://127.0.0.1:8443") {
- t.Fatalf("unexpected health URL: %s", healthURL)
- }
+
+ require.NoError(t, err,
+ "build health URL failed: %v", err)
+
+ require.True(t, strings.HasPrefix(healthURL, "http://127.0.0.1:8443"),
+ "unexpected health URL: %s", healthURL)
+
})
}
func TestBuildHealthURLInternalInvalidPort(t *testing.T) {
cfg := &config.Config{Port: "invalid-port"}
_, err := buildHealthURLInternal(cfg)
- if err == nil {
- t.Fatal("expected invalid health URL port to fail")
- }
+
+ require.Error(t, err,
+ "expected invalid health URL port to fail")
+
}
func TestRunHealthCommandInternal(t *testing.T) {
s := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
- if r.Method != http.MethodHead {
- t.Fatalf("expected HEAD request, got: %s", r.Method)
+ if !assert.Equal(t, http.MethodHead, r.Method,
+ "expected HEAD request, got: %s", r.Method) {
+ return
}
- if r.URL.Path != "/api/health" {
- t.Fatalf("unexpected path: %s", r.URL.Path)
+ if !assert.Equal(t, "/api/health", r.URL.Path,
+ "unexpected path: %s", r.URL.Path) {
+ return
}
+
w.WriteHeader(http.StatusOK)
}))
defer s.Close()
_, port, ok := strings.Cut(strings.TrimPrefix(s.URL, "http://"), ":")
- if !ok {
- t.Fatalf("failed to parse port from %s", s.URL)
- }
+
+ require.True(t, ok,
+ "failed to parse port from %s", s.URL)
+
if strings.Contains(port, "/") {
port = strings.SplitN(port, "/", 2)[0]
}
- if _, err := strconv.Atoi(port); err != nil {
- t.Fatalf("invalid port in test server URL %q: %v", s.URL, err)
+ {
+ _, err := strconv.Atoi(port)
+ require.NoError(t, err,
+ "invalid port in test server URL %q: %v", s.URL, err)
}
cfg := &config.Config{Port: port}
- if err := runHealthCommandInternal(context.Background(), cfg, 2*time.Second); err != nil {
- t.Fatalf("health command failed: %v", err)
+ {
+ err := runHealthCommandInternal(context.Background(), cfg, 2*time.Second)
+ require.NoError(t, err,
+ "health command failed: %v", err)
}
+
}
func TestRunHealthCommandInternalNon2xx(t *testing.T) {
@@ -85,41 +98,45 @@ func TestRunHealthCommandInternalNon2xx(t *testing.T) {
defer s.Close()
_, port, ok := strings.Cut(strings.TrimPrefix(s.URL, "http://"), ":")
- if !ok {
- t.Fatalf("failed to parse port from %s", s.URL)
- }
+
+ require.True(t, ok,
+ "failed to parse port from %s", s.URL)
+
if strings.Contains(port, "/") {
port = strings.SplitN(port, "/", 2)[0]
}
cfg := &config.Config{Port: port}
err := runHealthCommandInternal(context.Background(), cfg, 2*time.Second)
- if err == nil {
- t.Fatal("expected non-2xx response to fail")
- }
- if !strings.Contains(err.Error(), "health check failed with status") {
- t.Fatalf("unexpected error: %v", err)
- }
+
+ require.Error(t, err,
+ "expected non-2xx response to fail")
+
+ require.Contains(t, err.Error(), "health check failed with status",
+ "unexpected error: %v", err)
+
}
func TestRunHealthCommandInternalConnectionFailure(t *testing.T) {
err := runHealthCommandInternal(context.Background(), &config.Config{Port: "1"}, 200*time.Millisecond)
- if err == nil {
- t.Fatal("expected connection failure")
- }
+
+ require.Error(t, err,
+ "expected connection failure")
+
}
func TestRunHealthCommandInternalDefaultTimeoutFallback(t *testing.T) {
err := runHealthCommandInternal(context.Background(), &config.Config{Port: "1"}, 0)
- if err == nil {
- t.Fatal("expected connection failure")
- }
- if !strings.Contains(err.Error(), "health check request failed") {
- t.Fatalf("unexpected error: %v", err)
- }
+
+ require.Error(t, err,
+ "expected connection failure")
+
+ require.Contains(t, err.Error(), "health check request failed",
+ "unexpected error: %v", err)
// Ensure timeout path is exercised by checking the string formatting path.
- if !strings.Contains(fmt.Sprint(defaultHealthTimeout), "5s") {
- t.Fatalf("unexpected default timeout: %s", defaultHealthTimeout)
- }
+
+ require.Contains(t, fmt.Sprint(defaultHealthTimeout), "5s",
+ "unexpected default timeout: %s", defaultHealthTimeout)
+
}
diff --git a/backend/cli/upgrade/logfile_test.go b/backend/cli/upgrade/logfile_test.go
index 9c98a7cd2..a33b19be8 100644
--- a/backend/cli/upgrade/logfile_test.go
+++ b/backend/cli/upgrade/logfile_test.go
@@ -5,6 +5,8 @@ import (
"os"
"strings"
"testing"
+
+ "github.com/stretchr/testify/require"
)
func TestSetupMessageOnlyLogFile(t *testing.T) {
@@ -14,20 +16,22 @@ func TestSetupMessageOnlyLogFile(t *testing.T) {
})
logFile, err := SetupMessageOnlyLogFile(t.TempDir(), "upgrade-test", slog.LevelInfo)
- if err != nil {
- t.Fatalf("SetupMessageOnlyLogFile() error = %v", err)
- }
+
+ require.NoError(t, err,
+ "SetupMessageOnlyLogFile() error = %v", err)
// Each entry is written atomically as it is logged, so the file is readable
// in full without any flush or close.
slog.Info("container updated", "container", "web")
content, err := os.ReadFile(logFile.Name())
- if err != nil {
- t.Fatalf("read log file: %v", err)
- }
+
+ require.NoError(t, err,
+ "read log file: %v", err)
+
got := string(content)
- if !strings.Contains(got, "container updated") || !strings.Contains(got, `container="web"`) {
- t.Fatalf("log file content = %q, want message-only entry with attrs", got)
- }
+
+ require.False(t, !strings.Contains(got, "container updated") || !strings.Contains(got, `container="web"`),
+ "log file content = %q, want message-only entry with attrs", got)
+
}
diff --git a/backend/cli/upgrade/upgrade_test.go b/backend/cli/upgrade/upgrade_test.go
index 229fef940..1832cd55e 100644
--- a/backend/cli/upgrade/upgrade_test.go
+++ b/backend/cli/upgrade/upgrade_test.go
@@ -8,6 +8,7 @@ import (
"testing"
"github.com/moby/moby/client"
+ "github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
"go.getarcane.app/updater/labels"
)
@@ -131,9 +132,10 @@ func TestRefreshRecreatedImageLabelsInternalKeepsNilWhenNoLabelsExist(t *testing
func TestRefreshRecreatedContainerLabelsInternalPreservesLabelsWhenTargetInspectFails(t *testing.T) {
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
- if !strings.Contains(r.URL.Path, "/images/target:latest/json") {
- t.Errorf("unexpected Docker API request: %s %s", r.Method, r.URL.Path)
- }
+
+ assert.Contains(t, r.URL.Path, "/images/target:latest/json",
+ "unexpected Docker API request: %s %s", r.Method, r.URL.Path)
+
http.Error(w, "target inspect failed", http.StatusInternalServerError)
}))
t.Cleanup(server.Close)
@@ -173,7 +175,7 @@ func TestRefreshRecreatedContainerLabelsInternalPreservesOverridesWhenPreviousIn
case strings.Contains(r.URL.Path, "/images/sha256:old-image/json"):
http.Error(w, "previous inspect failed", http.StatusInternalServerError)
default:
- t.Errorf("unexpected Docker API request: %s %s", r.Method, r.URL.Path)
+ assert.Failf(t, "unexpected failure", "unexpected Docker API request: %s %s", r.Method, r.URL.Path)
http.NotFound(w, r)
}
}))
diff --git a/backend/internal/actors/resource_test.go b/backend/internal/actors/resource_test.go
index 081ba426e..c86f84db5 100644
--- a/backend/internal/actors/resource_test.go
+++ b/backend/internal/actors/resource_test.go
@@ -88,7 +88,7 @@ func TestResourceCanceledStopStillCleansAndFencesInternal(t *testing.T) {
select {
case <-stopped:
case <-time.After(time.Second):
- t.Fatal("resource cleanup was abandoned after stop wait cancellation")
+ require.FailNow(t, "resource cleanup was abandoned after stop wait cancellation")
}
require.ErrorIs(t, resource.Restart(t.Context(), "restart", func(context.Context) (int, error) { return 2, nil }), ErrResourceStopped)
diff --git a/backend/internal/actors/runner_test.go b/backend/internal/actors/runner_test.go
index 9da4cab18..28624b154 100644
--- a/backend/internal/actors/runner_test.go
+++ b/backend/internal/actors/runner_test.go
@@ -26,7 +26,7 @@ func TestRunnerCancelsAndJoinsBackgroundFunctionInternal(t *testing.T) {
select {
case <-started:
case <-time.After(time.Second):
- t.Fatal("runner did not start")
+ require.FailNow(t, "runner did not start")
}
stopCtx, cancel := context.WithTimeout(context.Background(), time.Second)
@@ -35,7 +35,7 @@ func TestRunnerCancelsAndJoinsBackgroundFunctionInternal(t *testing.T) {
select {
case <-exited:
default:
- t.Fatal("runner stop returned before background function exited")
+ require.FailNow(t, "runner stop returned before background function exited")
}
require.NoError(t, lifecycle.Stop(stopCtx))
}
diff --git a/backend/internal/bootstrap/bootstrap_test.go b/backend/internal/bootstrap/bootstrap_test.go
index 928dd3d10..191c3f2ab 100644
--- a/backend/internal/bootstrap/bootstrap_test.go
+++ b/backend/internal/bootstrap/bootstrap_test.go
@@ -331,13 +331,13 @@ func TestJobSchedulerStopCancelsItsPrivateContextInternal(t *testing.T) {
select {
case <-watcher.started:
case <-time.After(time.Second):
- t.Fatal("watcher did not start")
+ require.FailNow(t, "watcher did not start")
}
lifecycle.RequireStop()
select {
case <-watcher.stopped:
case <-time.After(time.Second):
- t.Fatal("watcher did not stop")
+ require.FailNow(t, "watcher did not stop")
}
require.NoError(t, appCtx.Err())
}
diff --git a/backend/internal/bootstrap/jobs_bootstrap_test.go b/backend/internal/bootstrap/jobs_bootstrap_test.go
index 5466912e7..ee6234094 100644
--- a/backend/internal/bootstrap/jobs_bootstrap_test.go
+++ b/backend/internal/bootstrap/jobs_bootstrap_test.go
@@ -91,19 +91,19 @@ func TestSettingsTimeoutSyncDoesNotBlockOtherEffectsInternal(t *testing.T) {
select {
case <-environment.started:
case <-time.After(time.Second):
- t.Fatal("timeout sync did not start")
+ require.FailNow(t, "timeout sync did not start")
}
select {
case <-timeoutCallbackDone:
case <-time.After(time.Second):
- t.Fatal("timeout settings callback remained blocked by remote sync")
+ require.FailNow(t, "timeout settings callback remained blocked by remote sync")
}
settings.pollingCallback([]libarcane.SettingUpdate{{Key: "pollingEnabled", Value: "true"}})
select {
case <-scheduler.rescheduled:
case <-time.After(time.Second):
- t.Fatal("local settings effect was blocked by remote timeout sync")
+ require.FailNow(t, "local settings effect was blocked by remote timeout sync")
}
stopCtx, cancel := context.WithTimeout(context.Background(), time.Second)
diff --git a/backend/internal/bootstrap/router_bootstrap_test.go b/backend/internal/bootstrap/router_bootstrap_test.go
index 624d1699f..d55d1d4ea 100644
--- a/backend/internal/bootstrap/router_bootstrap_test.go
+++ b/backend/internal/bootstrap/router_bootstrap_test.go
@@ -8,13 +8,15 @@ import (
"github.com/getarcaneapp/arcane/backend/v2/pkg/utils/cookie"
"github.com/labstack/echo/v5"
"github.com/stretchr/testify/assert"
+ "github.com/stretchr/testify/require"
)
func TestSecureCookieContextMiddleware_TrustGating(t *testing.T) {
_, loopback, err := net.ParseCIDR("127.0.0.0/8")
- if err != nil {
- t.Fatalf("parse cidr: %v", err)
- }
+
+ require.NoError(t, err,
+ "parse cidr: %v", err)
+
trusted := []*net.IPNet{loopback}
runRequest := func(t *testing.T, nets []*net.IPNet, remoteAddr, forwardedProto string) bool {
@@ -33,9 +35,12 @@ func TestSecureCookieContextMiddleware_TrustGating(t *testing.T) {
observed = cookie.SecureCookieFromContext(c.Request().Context())
return nil
})
- if err := handler(c); err != nil {
- t.Fatalf("handler: %v", err)
+ {
+ err := handler(c)
+ require.NoError(t, err,
+ "handler: %v", err)
}
+
return observed
}
diff --git a/backend/internal/config/config_test.go b/backend/internal/config/config_test.go
index 7acdbb4be..412e1557f 100644
--- a/backend/internal/config/config_test.go
+++ b/backend/internal/config/config_test.go
@@ -383,8 +383,8 @@ func TestConfig_TLSSettings(t *testing.T) {
cfg := Load()
assert.False(t, cfg.TLSEnabled)
- assert.Equal(t, "", cfg.TLSCertFile)
- assert.Equal(t, "", cfg.TLSKeyFile)
+ assert.Empty(t, cfg.TLSCertFile)
+ assert.Empty(t, cfg.TLSKeyFile)
})
t.Run("loads tls settings from env", func(t *testing.T) {
@@ -439,7 +439,7 @@ func TestConfig_GetManagerGRPCAddr(t *testing.T) {
cfg := &Config{
ManagerApiUrl: "://bad-url",
}
- assert.Equal(t, "", cfg.GetManagerGRPCAddr())
+ assert.Empty(t, cfg.GetManagerGRPCAddr())
})
}
@@ -544,13 +544,13 @@ func TestConfig_ApplyProxyDefaults(t *testing.T) {
t.Run("empty listen is no-op", func(t *testing.T) {
cfg := &Config{Listen: ""}
applyProxyDefaults(cfg)
- assert.Equal(t, "", cfg.TrustedProxies)
+ assert.Empty(t, cfg.TrustedProxies)
})
t.Run("public bind is no-op", func(t *testing.T) {
cfg := &Config{Listen: "0.0.0.0"}
applyProxyDefaults(cfg)
- assert.Equal(t, "", cfg.TrustedProxies)
+ assert.Empty(t, cfg.TrustedProxies)
})
}
@@ -561,7 +561,7 @@ func TestConfig_TrustedProxies(t *testing.T) {
t.Run("Default empty", func(t *testing.T) {
unsetEnv(t, "TRUSTED_PROXIES")
cfg := Load()
- assert.Equal(t, "", cfg.TrustedProxies)
+ assert.Empty(t, cfg.TrustedProxies)
})
t.Run("Single CIDR", func(t *testing.T) {
diff --git a/backend/internal/database/database_test.go b/backend/internal/database/database_test.go
index 514729886..b853d5634 100644
--- a/backend/internal/database/database_test.go
+++ b/backend/internal/database/database_test.go
@@ -45,8 +45,8 @@ func TestMigrateDatabase_BlocksDowngradeWithoutFlag(t *testing.T) {
err := migrateDatabaseToVersionInternal(ctx, rawDB, dbProviderSQLite, MigrationOptions{}, targetVersion)
require.Error(t, err)
- assert.ErrorContains(t, err, "ALLOW_DOWNGRADE=true")
- assert.ErrorContains(t, err, "newer than this Arcane binary supports")
+ require.ErrorContains(t, err, "ALLOW_DOWNGRADE=true")
+ require.ErrorContains(t, err, "newer than this Arcane binary supports")
highestVersion, err := getHighestEmbeddedMigrationVersionInternal("sqlite")
require.NoError(t, err)
@@ -183,7 +183,7 @@ func TestMigrateDatabase_BlocksFutureGooseVersionWithoutFlag(t *testing.T) {
err = migrateDatabaseInternal(ctx, rawDB, dbProviderSQLite, MigrationOptions{})
require.Error(t, err)
- assert.ErrorContains(t, err, "newer than this Arcane binary supports")
+ require.ErrorContains(t, err, "newer than this Arcane binary supports")
assert.Equal(t, highestVersion+1, readGooseSQLiteVersionInternal(t, dsn))
}
@@ -198,9 +198,9 @@ func TestMigrateDatabase_BlocksDowngradeWhenEmbeddedMigrationMissing(t *testing.
err = migrateDatabaseInternal(ctx, rawDB, dbProviderSQLite, MigrationOptions{AllowDowngrade: true})
require.Error(t, err)
- assert.ErrorContains(t, err, "ALLOW_DOWNGRADE=true is not sufficient")
- assert.ErrorContains(t, err, "restore the database from a backup")
- assert.ErrorContains(t, err, strconv.FormatInt(highestVersion+1, 10))
+ require.ErrorContains(t, err, "ALLOW_DOWNGRADE=true is not sufficient")
+ require.ErrorContains(t, err, "restore the database from a backup")
+ require.ErrorContains(t, err, strconv.FormatInt(highestVersion+1, 10))
assert.Equal(t, highestVersion+1, readGooseSQLiteVersionInternal(t, dsn))
}
@@ -213,8 +213,8 @@ func TestMigrateDatabase_BlocksDirtyLegacyCurrentVersion(t *testing.T) {
err = migrateDatabaseInternal(ctx, rawDB, dbProviderSQLite, MigrationOptions{})
require.Error(t, err)
- assert.ErrorContains(t, err, "is dirty")
- assert.ErrorContains(t, err, "ALLOW_DOWNGRADE=true")
+ require.ErrorContains(t, err, "is dirty")
+ require.ErrorContains(t, err, "ALLOW_DOWNGRADE=true")
require.NoError(t, migrateDatabaseInternal(ctx, rawDB, dbProviderSQLite, MigrationOptions{AllowDowngrade: true}))
assert.Equal(t, highestVersion, readGooseSQLiteVersionInternal(t, dsn))
@@ -232,8 +232,8 @@ func TestMigrateDatabase_BlocksDirtyLegacyOlderVersion(t *testing.T) {
err := migrateDatabaseInternal(ctx, rawDB, dbProviderSQLite, MigrationOptions{})
require.Error(t, err)
- assert.ErrorContains(t, err, "is dirty")
- assert.ErrorContains(t, err, "ALLOW_DOWNGRADE=true")
+ require.ErrorContains(t, err, "is dirty")
+ require.ErrorContains(t, err, "ALLOW_DOWNGRADE=true")
require.NoError(t, migrateDatabaseInternal(ctx, rawDB, dbProviderSQLite, MigrationOptions{AllowDowngrade: true}))
highestVersion, err := getHighestEmbeddedMigrationVersionInternal("sqlite")
@@ -333,7 +333,7 @@ CREATE TABLE goose_db_version (
err = adoptLegacyMigrationStateInternal(ctx, rawDB, dbProviderSQLite, MigrationOptions{})
require.Error(t, err)
- assert.ErrorContains(t, err, "failed to insert Goose migration version")
+ require.ErrorContains(t, err, "failed to insert Goose migration version")
var rowCount int
err = rawDB.QueryRowContext(ctx, `SELECT COUNT(*) FROM goose_db_version WHERE version_id = 0 AND is_applied = 0`).Scan(&rowCount)
@@ -351,7 +351,7 @@ func TestInitialize_BlocksDirtyLegacyMigrationState(t *testing.T) {
db, err := Initialize(ctx, dsn, MigrationOptions{})
require.Error(t, err)
require.Nil(t, db)
- assert.ErrorContains(t, err, "dirty")
+ require.ErrorContains(t, err, "dirty")
assert.ErrorContains(t, err, "ALLOW_DOWNGRADE=true")
}
diff --git a/backend/internal/middleware/environment_middleware_authz_test.go b/backend/internal/middleware/environment_middleware_authz_test.go
index a584e0572..9127ef584 100644
--- a/backend/internal/middleware/environment_middleware_authz_test.go
+++ b/backend/internal/middleware/environment_middleware_authz_test.go
@@ -8,6 +8,7 @@ import (
"github.com/labstack/echo/v5"
"github.com/getarcaneapp/arcane/backend/v2/pkg/authz"
+ "github.com/stretchr/testify/require"
)
const proxyTestEnvID = "remote-1"
@@ -36,9 +37,10 @@ func TestProxyPermissionDeniedBlocksWriteForReadOnlyUser(t *testing.T) {
ps.AddEnv(proxyTestEnvID, authz.PermContainersList, authz.PermContainersRead)
c := newProxyRequestContext(http.MethodPost, "/api/environments/"+proxyTestEnvID+"/containers/abc/restart")
- if !m.proxyPermissionDenied(c, ps, proxyTestEnvID) {
- t.Fatal("expected restart to be denied for a read-only user")
- }
+
+ require.True(t, m.proxyPermissionDenied(c, ps, proxyTestEnvID),
+ "expected restart to be denied for a read-only user")
+
}
func TestProxyPermissionDeniedAllowsWriteForPermittedUser(t *testing.T) {
@@ -47,9 +49,10 @@ func TestProxyPermissionDeniedAllowsWriteForPermittedUser(t *testing.T) {
ps.AddEnv(proxyTestEnvID, authz.PermContainersRestart)
c := newProxyRequestContext(http.MethodPost, "/api/environments/"+proxyTestEnvID+"/containers/abc/restart")
- if m.proxyPermissionDenied(c, ps, proxyTestEnvID) {
- t.Fatal("expected restart to be allowed for a user with containers:restart")
- }
+
+ require.False(t, m.proxyPermissionDenied(c, ps, proxyTestEnvID),
+ "expected restart to be allowed for a user with containers:restart")
+
}
func TestProxyPermissionDeniedAllowsRead(t *testing.T) {
@@ -58,9 +61,10 @@ func TestProxyPermissionDeniedAllowsRead(t *testing.T) {
ps.AddEnv(proxyTestEnvID, authz.PermContainersList)
c := newProxyRequestContext(http.MethodGet, "/api/environments/"+proxyTestEnvID+"/containers")
- if m.proxyPermissionDenied(c, ps, proxyTestEnvID) {
- t.Fatal("expected list to be allowed for a user with containers:list")
- }
+
+ require.False(t, m.proxyPermissionDenied(c, ps, proxyTestEnvID),
+ "expected list to be allowed for a user with containers:list")
+
}
func TestProxyPermissionDeniedDeniesPermissionFromDifferentEnv(t *testing.T) {
@@ -70,17 +74,19 @@ func TestProxyPermissionDeniedDeniesPermissionFromDifferentEnv(t *testing.T) {
ps.AddEnv("other-env", authz.PermContainersRestart)
c := newProxyRequestContext(http.MethodPost, "/api/environments/"+proxyTestEnvID+"/containers/abc/restart")
- if !m.proxyPermissionDenied(c, ps, proxyTestEnvID) {
- t.Fatal("expected denial: permission is scoped to a different environment")
- }
+
+ require.True(t, m.proxyPermissionDenied(c, ps, proxyTestEnvID),
+ "expected denial: permission is scoped to a different environment")
+
}
func TestProxyPermissionDeniedSudoBypasses(t *testing.T) {
m := newProxyAuthzMiddleware(containerMatcher())
c := newProxyRequestContext(http.MethodPost, "/api/environments/"+proxyTestEnvID+"/containers/abc/restart")
- if m.proxyPermissionDenied(c, authz.SudoPermissionSet(), proxyTestEnvID) {
- t.Fatal("expected sudo permission set to bypass the permission check")
- }
+
+ require.False(t, m.proxyPermissionDenied(c, authz.SudoPermissionSet(), proxyTestEnvID),
+ "expected sudo permission set to bypass the permission check")
+
}
func TestProxyPermissionDeniedDefaultDeniesUnmappedRoute(t *testing.T) {
@@ -89,9 +95,10 @@ func TestProxyPermissionDeniedDefaultDeniesUnmappedRoute(t *testing.T) {
ps.AddEnv(proxyTestEnvID, authz.PermContainersRestart, authz.PermContainersList)
c := newProxyRequestContext(http.MethodPost, "/api/environments/"+proxyTestEnvID+"/unknown/resource")
- if !m.proxyPermissionDenied(c, ps, proxyTestEnvID) {
- t.Fatal("expected an unmapped proxied route to be denied by default")
- }
+
+ require.True(t, m.proxyPermissionDenied(c, ps, proxyTestEnvID),
+ "expected an unmapped proxied route to be denied by default")
+
}
func TestProxyPermissionDeniedAllowsPublicRoute(t *testing.T) {
@@ -99,9 +106,10 @@ func TestProxyPermissionDeniedAllowsPublicRoute(t *testing.T) {
ps := authz.NewPermissionSet() // no permissions at all
c := newProxyRequestContext(http.MethodGet, "/api/environments/"+proxyTestEnvID+"/settings/public")
- if m.proxyPermissionDenied(c, ps, proxyTestEnvID) {
- t.Fatal("expected an explicitly public route to be allowed for any authenticated caller")
- }
+
+ require.False(t, m.proxyPermissionDenied(c, ps, proxyTestEnvID),
+ "expected an explicitly public route to be allowed for any authenticated caller")
+
}
// wsTerminalMatcher mirrors ws.AddProxiedPermissions for the container terminal
@@ -122,13 +130,14 @@ func TestProxyPermissionDeniedWSTerminalRequiresExec(t *testing.T) {
ps.AddEnv(proxyTestEnvID, authz.PermContainersRead, authz.PermContainersList)
c := newProxyRequestContext(http.MethodGet, "/api/environments/"+proxyTestEnvID+"/ws/containers/abc/terminal")
- if !m.proxyPermissionDenied(c, ps, proxyTestEnvID) {
- t.Fatal("expected WS terminal to be denied without containers:exec")
- }
+
+ require.True(t, m.proxyPermissionDenied(c, ps, proxyTestEnvID),
+ "expected WS terminal to be denied without containers:exec")
// Granting containers:exec allows the same stream.
ps.AddEnv(proxyTestEnvID, authz.PermContainersExec)
- if m.proxyPermissionDenied(c, ps, proxyTestEnvID) {
- t.Fatal("expected WS terminal to be allowed with containers:exec")
- }
+
+ require.False(t, m.proxyPermissionDenied(c, ps, proxyTestEnvID),
+ "expected WS terminal to be allowed with containers:exec")
+
}
diff --git a/backend/internal/middleware/environment_middleware_test.go b/backend/internal/middleware/environment_middleware_test.go
index 9d418e584..67fcc2f4d 100644
--- a/backend/internal/middleware/environment_middleware_test.go
+++ b/backend/internal/middleware/environment_middleware_test.go
@@ -10,6 +10,7 @@ import (
"github.com/getarcaneapp/arcane/backend/v2/pkg/libarcane/edge"
"github.com/labstack/echo/v5"
"github.com/stretchr/testify/assert"
+ "github.com/stretchr/testify/require"
)
func newTestEnvironmentMiddleware() *EnvironmentMiddleware {
@@ -303,7 +304,7 @@ func TestEnvironmentMiddleware_CreateProxyRequest_RejectsInvalidProxyTarget(t *t
c := e.NewContext(req, recorder)
_, err := middleware.createProxyRequest(c, "ftp://example.com/containers", nil)
- assert.Error(t, err)
+ require.Error(t, err)
assert.Contains(t, err.Error(), "Invalid proxy target URL")
}
diff --git a/backend/internal/services/activity_service_test.go b/backend/internal/services/activity_service_test.go
index 322c026b2..eec93654c 100644
--- a/backend/internal/services/activity_service_test.go
+++ b/backend/internal/services/activity_service_test.go
@@ -315,7 +315,7 @@ func TestActivitySubscriberCoalescesProgressEventsInternal(t *testing.T) {
return
}
case <-deadline:
- t.Fatal("did not receive final coalesced progress event")
+ require.FailNow(t, "did not receive final coalesced progress event")
}
}
}
@@ -395,7 +395,7 @@ func TestActivityServiceQueuedActivityFlipsToRunningWhenSlotFreesInternal(t *tes
select {
case awaitErr := <-awaitDone:
- t.Fatalf("await returned before the slot freed: %v", awaitErr)
+ require.FailNowf(t, "unexpected failure", "await returned before the slot freed: %v", awaitErr)
case <-time.After(100 * time.Millisecond):
}
@@ -406,7 +406,7 @@ func TestActivityServiceQueuedActivityFlipsToRunningWhenSlotFreesInternal(t *tes
case awaitErr := <-awaitDone:
require.NoError(t, awaitErr)
case <-time.After(5 * time.Second):
- t.Fatal("await did not acquire the freed slot")
+ require.FailNow(t, "await did not acquire the freed slot")
}
var model models.Activity
@@ -435,7 +435,7 @@ func TestActivityServiceLimitIncreaseKeepsCountingActiveSlotsInternal(t *testing
case awaitErr := <-awaitDone:
require.NoError(t, awaitErr)
case <-time.After(2 * slotWaitRecheckInterval):
- t.Fatal("waiter was not admitted after the limit increase")
+ require.FailNow(t, "waiter was not admitted after the limit increase")
}
third, err := service.StartActivity(ctx, StartActivityRequest{EnvironmentID: "0", Type: models.ActivityTypeImagePull, Queue: true})
@@ -462,7 +462,7 @@ func TestActivityServiceCancelWhileQueuedUnblocksAwaitInternal(t *testing.T) {
case awaitErr := <-awaitDone:
require.ErrorIs(t, awaitErr, activitylib.ErrCanceled)
case <-time.After(5 * time.Second):
- t.Fatal("cancel did not unblock the queued slot wait")
+ require.FailNow(t, "cancel did not unblock the queued slot wait")
}
}
@@ -706,7 +706,7 @@ func receiveActivityEventInternal(t *testing.T, events <-chan activitytypes.Stre
case event := <-events:
return event
case <-time.After(time.Second):
- t.Fatal("timed out waiting for activity event")
+ require.FailNow(t, "timed out waiting for activity event")
return activitytypes.StreamEvent{}
}
}
diff --git a/backend/internal/services/api_key_service_test.go b/backend/internal/services/api_key_service_test.go
index 7157f26e6..f6a62489c 100644
--- a/backend/internal/services/api_key_service_test.go
+++ b/backend/internal/services/api_key_service_test.go
@@ -519,14 +519,14 @@ func TestValidateAPIKeyLastUsedUpdateIsRequestScoped(t *testing.T) {
case <-updateStarted:
case <-time.After(time.Second):
close(releaseUpdate)
- t.Fatal("last-used update did not start")
+ require.FailNow(t, "last-used update did not start")
}
select {
case err := <-validationDone:
close(releaseUpdate)
require.NoError(t, err)
- t.Fatal("validation returned before its last-used update completed")
+ require.FailNow(t, "validation returned before its last-used update completed")
case <-time.After(50 * time.Millisecond):
}
@@ -703,7 +703,7 @@ func TestBackfillApiKeyPermissionsRepairsExistingBootstrapKey(t *testing.T) {
require.NoError(t, err)
envPerms, ok := ps.PerEnv[envID]
require.True(t, ok)
- require.Equal(t, len(authz.AllPermissions()), len(envPerms))
+ require.Len(t, envPerms, len(authz.AllPermissions()))
}
func TestGetEnvironmentByAPIKeyRecentLastUsedAtDoesNotRewriteImmediately(t *testing.T) {
diff --git a/backend/internal/services/auth_service_test.go b/backend/internal/services/auth_service_test.go
index 8073a0744..68ab32fd2 100644
--- a/backend/internal/services/auth_service_test.go
+++ b/backend/internal/services/auth_service_test.go
@@ -3,7 +3,6 @@ package services
import (
"context"
"crypto/rand"
- "errors"
"testing"
"time"
@@ -18,6 +17,7 @@ import (
"github.com/getarcaneapp/arcane/types/v2/auth"
"github.com/golang-jwt/jwt/v5"
"github.com/samber/hot"
+ "github.com/stretchr/testify/assert"
)
func setupAuthServiceTestDB(t *testing.T) *database.DB {
@@ -87,9 +87,10 @@ func makeAccessToken(t *testing.T, secret []byte, subject string, id string, use
}
tok := jwt.NewWithClaims(jwt.SigningMethodHS256, claims)
signed, err := tok.SignedString(secret)
- if err != nil {
- t.Fatalf("sign: %v", err)
- }
+
+ require.NoError(t, err,
+ "sign: %v", err)
+
return signed
}
@@ -116,9 +117,10 @@ func makeRefreshToken(t *testing.T, secret []byte, subject string, id string, ex
}
tok := jwt.NewWithClaims(jwt.SigningMethodHS256, claims)
signed, err := tok.SignedString(secret)
- if err != nil {
- t.Fatalf("sign: %v", err)
- }
+
+ require.NoError(t, err,
+ "sign: %v", err)
+
return signed
}
@@ -137,9 +139,10 @@ func makeUnsignedToken(t *testing.T, claims jwt.Claims) string {
t.Helper()
tok := jwt.NewWithClaims(jwt.SigningMethodNone, claims)
signed, err := tok.SignedString(jwt.UnsafeAllowNoneSignatureType)
- if err != nil {
- t.Fatalf("sign none: %v", err)
- }
+
+ require.NoError(t, err,
+ "sign none: %v", err)
+
return signed
}
@@ -165,21 +168,22 @@ func TestVerifyToken_ValidClaims(t *testing.T) {
token := makeAccessToken(t, s.jwtSecret, "access", "u123", "alice", []string{"user", "admin"}, "[email protected]", "Alice", exp, session.ID)
verifiedUser, _, err := s.VerifyToken(context.Background(), token)
- if err != nil {
- t.Fatalf("VerifyToken error: %v", err)
- }
- if verifiedUser.ID != "u123" {
- t.Errorf("id %q", verifiedUser.ID)
- }
- if verifiedUser.Username != "alice" {
- t.Errorf("username %q", verifiedUser.Username)
- }
- if verifiedUser.Email == nil || *verifiedUser.Email != "[email protected]" {
- t.Errorf("email %v", verifiedUser.Email)
- }
- if verifiedUser.DisplayName == nil || *verifiedUser.DisplayName != "Alice" {
- t.Errorf("displayName %v", verifiedUser.DisplayName)
- }
+
+ require.NoError(t, err,
+ "VerifyToken error: %v", err)
+
+ assert.Equal(t, "u123", verifiedUser.ID,
+ "id %q", verifiedUser.ID)
+
+ assert.Equal(t, "alice", verifiedUser.Username,
+ "username %q", verifiedUser.Username)
+
+ assert.False(t, verifiedUser.Email == nil || *verifiedUser.Email != "[email protected]",
+ "email %v", verifiedUser.Email)
+
+ assert.False(t, verifiedUser.DisplayName == nil || *verifiedUser.DisplayName != "Alice",
+ "displayName %v", verifiedUser.DisplayName)
+
}
func TestVerifyToken_RejectsNonHMACAlg(t *testing.T) {
@@ -198,9 +202,10 @@ func TestVerifyToken_RejectsNonHMACAlg(t *testing.T) {
})
_, _, err := s.VerifyToken(context.Background(), token)
- if !errors.Is(err, ErrInvalidToken) {
- t.Errorf("want ErrInvalidToken, got %v", err)
- }
+
+ assert.ErrorIs(t, err, ErrInvalidToken,
+ "want ErrInvalidToken, got %v", err)
+
}
func TestVerifyToken_Expired(t *testing.T) {
@@ -222,9 +227,10 @@ func TestVerifyToken_Expired(t *testing.T) {
token := makeAccessToken(t, s.jwtSecret, "access", "u1", "bob", []string{"user"}, "", "", exp)
_, _, err = s.VerifyToken(context.Background(), token)
- if !errors.Is(err, ErrExpiredToken) {
- t.Errorf("want ErrExpiredToken, got %v", err)
- }
+
+ assert.ErrorIs(t, err, ErrExpiredToken,
+ "want ErrExpiredToken, got %v", err)
+
}
func TestVerifyToken_InvalidSubject(t *testing.T) {
@@ -240,15 +246,19 @@ func TestVerifyToken_InvalidSignature(t *testing.T) {
s := newTestAuthService("")
exp := time.Now().Add(5 * time.Minute)
otherSecret := make([]byte, 32)
- if _, err := rand.Read(otherSecret); err != nil {
- t.Fatalf("rand.Read: %v", err)
+ {
+ _, err := rand.Read(otherSecret)
+ require.NoError(t, err,
+ "rand.Read: %v", err)
}
+
token := makeAccessToken(t, otherSecret, "access", "u1", "bob", []string{"user"}, "", "", exp)
_, _, err := s.VerifyToken(context.Background(), token)
- if !errors.Is(err, ErrInvalidToken) {
- t.Errorf("want ErrInvalidToken, got %v", err)
- }
+
+ assert.ErrorIs(t, err, ErrInvalidToken,
+ "want ErrInvalidToken, got %v", err)
+
}
func TestVerifyToken_MissingUserID(t *testing.T) {
@@ -262,17 +272,20 @@ func TestVerifyToken_MissingUserID(t *testing.T) {
func TestGenerateUsernameFromEmail(t *testing.T) {
u := generateUsernameFromEmail("[email protected]", "sub-abcdef01")
- if u != "john.doe" {
- t.Errorf("username %q", u)
- }
+
+ assert.Equal(t, "john.doe", u,
+ "username %q", u)
+
u2 := generateUsernameFromEmail("", "1234567890abcdef")
- if u2 != "user_90abcdef" {
- t.Errorf("fallback username %q", u2)
- }
+
+ assert.Equal(t, "user_90abcdef", u2,
+ "fallback username %q", u2)
+
u3 := generateUsernameFromEmail("", "short")
- if u3 != "user_short" {
- t.Errorf("short subject username %q", u3)
- }
+
+ assert.Equal(t, "user_short", u3,
+ "short subject username %q", u3)
+
}
func TestPersistOidcTokens_SetsFields(t *testing.T) {
@@ -287,21 +300,22 @@ func TestPersistOidcTokens_SetsFields(t *testing.T) {
}
s.persistOidcTokens(user, resp)
- if user.OidcAccessToken == nil || *user.OidcAccessToken != "at-123" {
- t.Errorf("access token %v", user.OidcAccessToken)
- }
- if user.OidcRefreshToken == nil || *user.OidcRefreshToken != "rt-456" {
- t.Errorf("refresh token %v", user.OidcRefreshToken)
- }
- if user.OidcAccessTokenExpiresAt == nil {
- t.Errorf("expiresAt nil")
- }
+ assert.False(t, user.OidcAccessToken == nil || *user.OidcAccessToken != "at-123",
+ "access token %v", user.OidcAccessToken)
+
+ assert.False(t, user.OidcRefreshToken == nil || *user.OidcRefreshToken != "rt-456",
+ "refresh token %v", user.OidcRefreshToken)
+
+ assert.NotNil(t, user.OidcAccessTokenExpiresAt,
+ "expiresAt nil")
+
// Check approx expiry within [start+7s, start+12s] to allow CI slop
earliest := start.Add(7 * time.Second)
latest := start.Add(12 * time.Second)
- if user.OidcAccessTokenExpiresAt.Before(earliest) || user.OidcAccessTokenExpiresAt.After(latest) {
- t.Errorf("expiresAt %v not in [%v,%v]", user.OidcAccessTokenExpiresAt, earliest, latest)
- }
+
+ assert.False(t, user.OidcAccessTokenExpiresAt.Before(earliest) || user.OidcAccessTokenExpiresAt.After(latest),
+ "expiresAt %v not in [%v,%v]", user.OidcAccessTokenExpiresAt, earliest, latest)
+
}
func TestVerifyToken_VersionMismatch(t *testing.T) {
@@ -314,9 +328,9 @@ func TestVerifyToken_VersionMismatch(t *testing.T) {
config.Version = "2.0.0"
_, _, err := s.VerifyToken(context.Background(), token)
- if !errors.Is(err, ErrTokenVersionMismatch) {
- t.Errorf("want ErrTokenVersionMismatch, got %v", err)
- }
+
+ assert.ErrorIs(t, err, ErrTokenVersionMismatch,
+ "want ErrTokenVersionMismatch, got %v", err)
config.Version = oldVersion
}
@@ -421,7 +435,7 @@ func TestVerifyToken_RejectsRevokedSession(t *testing.T) {
token := makeAccessToken(t, s.jwtSecret, "access", user.ID, user.Username, []string{"user"}, "", "", exp, session.ID)
_, _, err = s.VerifyToken(context.Background(), token)
- require.True(t, errors.Is(err, common.ErrSessionRevoked))
+ require.ErrorIs(t, err, common.ErrSessionRevoked)
}
func TestVerifyToken_RejectsMissingSessionID(t *testing.T) {
@@ -464,7 +478,7 @@ func TestRevokeSessionThenVerifyTokenFails(t *testing.T) {
require.NoError(t, s.RevokeSession(context.Background(), session.ID))
_, _, err = s.VerifyToken(context.Background(), token)
- require.True(t, errors.Is(err, common.ErrSessionRevoked))
+ require.ErrorIs(t, err, common.ErrSessionRevoked)
}
func TestVerifyToken_RejectsRevokedCachedSession(t *testing.T) {
@@ -490,7 +504,7 @@ func TestVerifyToken_RejectsRevokedCachedSession(t *testing.T) {
require.NoError(t, NewSessionService(db).RevokeSession(context.Background(), session.ID))
_, _, err = s.VerifyToken(context.Background(), token)
- require.True(t, errors.Is(err, common.ErrSessionRevoked), "expected cached access token to be rejected after cross-process revocation, got %v", err)
+ require.ErrorIs(t, err, common.ErrSessionRevoked, "expected cached access token to be rejected after cross-process revocation, got %v", err)
}
func TestRefreshToken_RotatesJTI(t *testing.T) {
@@ -545,7 +559,7 @@ func TestRefreshToken_RejectsRevokedSession(t *testing.T) {
token := makeRefreshToken(t, s.jwtSecret, "refresh", refreshJTI, exp, user.ID, session.ID)
_, err = s.RefreshToken(context.Background(), token, auth.SessionMeta{})
- require.True(t, errors.Is(err, common.ErrSessionRevoked))
+ require.ErrorIs(t, err, common.ErrSessionRevoked)
}
func TestChangePassword_RevokesAllSessions(t *testing.T) {
@@ -619,9 +633,10 @@ func TestRefreshToken_RejectsNonHMACAlg(t *testing.T) {
})
_, err := s.RefreshToken(context.Background(), token, auth.SessionMeta{})
- if !errors.Is(err, ErrInvalidToken) {
- t.Errorf("want ErrInvalidToken, got %v", err)
- }
+
+ assert.ErrorIs(t, err, ErrInvalidToken,
+ "want ErrInvalidToken, got %v", err)
+
}
func TestGetOidcConfigurationStatus(t *testing.T) {
@@ -633,51 +648,53 @@ func TestGetOidcConfigurationStatus(t *testing.T) {
s.settingsService = &SettingsService{}
status, err := s.GetOidcConfigurationStatus(context.Background())
- if err != nil {
- t.Fatalf("GetOidcConfigurationStatus error: %v", err)
- }
- if status.EnvForced || status.EnvConfigured {
- t.Errorf("expected disabled, got forced=%v configured=%v", status.EnvForced, status.EnvConfigured)
- }
+
+ require.NoError(t, err,
+ "GetOidcConfigurationStatus error: %v", err)
+
+ assert.False(t, status.EnvForced || status.EnvConfigured,
+ "expected disabled, got forced=%v configured=%v", status.EnvForced, status.EnvConfigured)
+
// MergeAccounts will be false since GetSettings will fail
- if status.MergeAccounts {
- t.Errorf("expected mergeAccounts=false, got true")
- }
+
+ assert.False(t, status.MergeAccounts,
+ "expected mergeAccounts=false, got true")
// Explicit env override to false should still be treated as forced
t.Setenv("OIDC_ENABLED", "false")
s.settingsService.envOverrides = resolveSettingsEnvOverridesInternal()
s.config.OidcEnabled = false
status, err = s.GetOidcConfigurationStatus(context.Background())
- if err != nil {
- t.Fatalf("GetOidcConfigurationStatus error: %v", err)
- }
- if !status.EnvForced || status.EnvConfigured {
- t.Errorf("expected forced=false-override and not configured, got forced=%v configured=%v", status.EnvForced, status.EnvConfigured)
- }
+
+ require.NoError(t, err,
+ "GetOidcConfigurationStatus error: %v", err)
+
+ assert.False(t, !status.EnvForced || status.EnvConfigured,
+ "expected forced=false-override and not configured, got forced=%v configured=%v", status.EnvForced, status.EnvConfigured)
// Enabled but missing fields
t.Setenv("OIDC_ENABLED", "true")
s.settingsService.envOverrides = resolveSettingsEnvOverridesInternal()
s.config.OidcEnabled = true
status, err = s.GetOidcConfigurationStatus(context.Background())
- if err != nil {
- t.Fatalf("GetOidcConfigurationStatus error: %v", err)
- }
- if !status.EnvForced || status.EnvConfigured {
- t.Errorf("expected enabled but not configured, got forced=%v configured=%v", status.EnvForced, status.EnvConfigured)
- }
+
+ require.NoError(t, err,
+ "GetOidcConfigurationStatus error: %v", err)
+
+ assert.False(t, !status.EnvForced || status.EnvConfigured,
+ "expected enabled but not configured, got forced=%v configured=%v", status.EnvForced, status.EnvConfigured)
// Enabled and configured
s.config.OidcClientID = "client-id"
s.config.OidcIssuerURL = "https://example.com"
status, err = s.GetOidcConfigurationStatus(context.Background())
- if err != nil {
- t.Fatalf("GetOidcConfigurationStatus error: %v", err)
- }
- if !status.EnvForced || !status.EnvConfigured {
- t.Errorf("expected enabled and configured, got forced=%v configured=%v", status.EnvForced, status.EnvConfigured)
- }
+
+ require.NoError(t, err,
+ "GetOidcConfigurationStatus error: %v", err)
+
+ assert.False(t, !status.EnvForced || !status.EnvConfigured,
+ "expected enabled and configured, got forced=%v configured=%v", status.EnvForced, status.EnvConfigured)
+
}
func TestFindOrCreateOidcUser_MergeEnabled_EmailNotVerified_NoExistingUser_CreatesNewUser(t *testing.T) {
diff --git a/backend/internal/services/build_service_test.go b/backend/internal/services/build_service_test.go
index 5ed1b5f41..e4ff84bf5 100644
--- a/backend/internal/services/build_service_test.go
+++ b/backend/internal/services/build_service_test.go
@@ -27,7 +27,7 @@ func TestBuildService_ResolveBuildRequest_PassesThroughLocalContext(t *testing.T
contextDir := t.TempDir()
svc := &BuildService{
gitCloneFn: func(context.Context, string, string, buildgit.AuthConfig) (string, error) {
- t.Fatal("git clone should not run for local contexts")
+ require.FailNow(t, "git clone should not run for local contexts")
return "", nil
},
}
@@ -63,7 +63,7 @@ func TestBuildService_ResolveBuildRequest_ClonesRemoteGitContext(t *testing.T) {
cleanupCalled := false
svc := &BuildService{
gitProbeFn: func(context.Context, string, buildgit.AuthConfig) error {
- t.Fatal("git remote probe should not run for .git URLs")
+ require.FailNow(t, "git remote probe should not run for .git URLs")
return nil
},
gitCloneFn: func(_ context.Context, repositoryURL, ref string, auth buildgit.AuthConfig) (string, error) {
@@ -150,7 +150,7 @@ func TestBuildService_ResolveBuildRequest_RejectsNonGitHTTPContextViaProbeFailur
return assert.AnError
},
gitCloneFn: func(context.Context, string, string, buildgit.AuthConfig) (string, error) {
- t.Fatal("git clone should not run when remote probe fails")
+ require.FailNow(t, "git clone should not run when remote probe fails")
return "", nil
},
}
@@ -225,7 +225,7 @@ func TestBuildService_ResolveBuildRequest_UsesSavedGitCredentials(t *testing.T)
svc := &BuildService{
gitRepository: repoService,
gitProbeFn: func(context.Context, string, buildgit.AuthConfig) error {
- t.Fatal("git remote probe should not run for ssh URLs")
+ require.FailNow(t, "git remote probe should not run for ssh URLs")
return nil
},
gitCloneFn: func(_ context.Context, _ string, _ string, auth buildgit.AuthConfig) (string, error) {
diff --git a/backend/internal/services/container_registry_service_test.go b/backend/internal/services/container_registry_service_test.go
index 9345875e5..c07282b8b 100644
--- a/backend/internal/services/container_registry_service_test.go
+++ b/backend/internal/services/container_registry_service_test.go
@@ -218,7 +218,9 @@ func TestContainerRegistryService_GetRegistryPullUsage_AnonymousDockerHubLimit(t
w.Header().Set("RateLimit-Remaining", "90;w=21600")
w.WriteHeader(http.StatusOK)
default:
- t.Fatalf("unexpected request %s %s", r.Method, r.URL.Path)
+ if !assert.Failf(t, "unexpected failure", "unexpected request %s %s", r.Method, r.URL.Path) {
+ return
+ }
}
})
@@ -268,7 +270,9 @@ func TestContainerRegistryService_GetRegistryPullUsage_UsesDockerHubCredential(t
w.Header().Set("RateLimit-Remaining", "199;w=21600")
w.WriteHeader(http.StatusOK)
default:
- t.Fatalf("unexpected request %s %s", r.Method, r.URL.Path)
+ if !assert.Failf(t, "unexpected failure", "unexpected request %s %s", r.Method, r.URL.Path) {
+ return
+ }
}
})
@@ -300,7 +304,9 @@ func TestContainerRegistryService_GetRegistryPullUsage_CredentialErrorIsNonFatal
w.Header().Set("WWW-Authenticate", `Bearer realm="https://auth.docker.io/token",service="registry.docker.io"`)
w.WriteHeader(http.StatusUnauthorized)
default:
- t.Fatalf("unexpected request %s %s", r.Method, r.URL.Path)
+ if !assert.Failf(t, "unexpected failure", "unexpected request %s %s", r.Method, r.URL.Path) {
+ return
+ }
}
})
@@ -661,7 +667,7 @@ func TestContainerRegistryService_TestRegistry_SkipsLoginForEmptyCredentials(t *
svc := NewContainerRegistryService(nil, func(context.Context) (RegistryDaemonClient, error) {
return &fakeRegistryDaemonClient{
registryLoginFn: func(ctx context.Context, options client.RegistryLoginOptions) (client.RegistryLoginResult, error) {
- t.Fatal("RegistryLogin should not be called with empty credentials")
+ require.FailNow(t, "RegistryLogin should not be called with empty credentials")
return client.RegistryLoginResult{}, nil
},
}, nil
@@ -727,7 +733,7 @@ func TestContainerRegistryService_GetImageDigest_HonorsCallerCancellation(t *tes
select {
case <-started:
case <-time.After(time.Second):
- t.Fatal("registry lookup did not start")
+ require.FailNow(t, "registry lookup did not start")
}
cancel()
@@ -735,7 +741,7 @@ func TestContainerRegistryService_GetImageDigest_HonorsCallerCancellation(t *tes
case err := <-result:
require.ErrorIs(t, err, context.Canceled)
case <-time.After(time.Second):
- t.Fatal("registry lookup did not honor caller cancellation")
+ require.FailNow(t, "registry lookup did not honor caller cancellation")
}
}
@@ -907,23 +913,34 @@ func TestContainerRegistryService_InspectImageDigest_RetriesStoredCredentialsAft
w.Header().Set("Docker-Content-Digest", wantDigest)
w.WriteHeader(http.StatusOK)
default:
- t.Fatalf("unexpected manifest call %d", len(authHeaders))
+ if !assert.Failf(t, "unexpected failure", "unexpected manifest call %d", len(authHeaders)) {
+ return
+ }
}
case "/token":
username, password, ok := r.BasicAuth()
if !ok {
- require.Equal(t, "", r.Header.Get("Authorization"))
- require.NoError(t, json.NewEncoder(w).Encode(map[string]string{
+ if !assert.Empty(t, r.Header.Get("Authorization")) {
+ return
+ }
+ if !assert.NoError(t, json.NewEncoder(w).Encode(map[string]string{
"token": "anonymous-token",
- }))
+ })) {
+ return
+ }
return
}
-
- require.Equal(t, "stored-user", username)
- require.Equal(t, "stored-token", password)
- require.NoError(t, json.NewEncoder(w).Encode(map[string]string{
+ if !assert.Equal(t, "stored-user", username) {
+ return
+ }
+ if !assert.Equal(t, "stored-token", password) {
+ return
+ }
+ if !assert.NoError(t, json.NewEncoder(w).Encode(map[string]string{
"token": "credential-token",
- }))
+ })) {
+ return
+ }
default:
http.NotFound(w, r)
}
@@ -952,7 +969,7 @@ func TestContainerRegistryService_InspectImageDigest_RetriesStoredCredentialsAft
assert.Equal(t, "stored-user", result.AuthUsername)
assert.True(t, result.UsedCredential)
require.Len(t, authHeaders, 3)
- assert.Equal(t, "", authHeaders[0])
+ assert.Empty(t, authHeaders[0])
assert.Equal(t, "Bearer anonymous-token", authHeaders[1])
assert.Equal(t, "Basic c3RvcmVkLXVzZXI6c3RvcmVkLXRva2Vu", authHeaders[2])
}
@@ -997,7 +1014,7 @@ func TestContainerRegistryService_InspectImageDigest_PreservesDaemonAndFallbackE
result, err := svc.inspectImageDigestInternal(context.Background(), "registry.example.com/team/app:1.2.3", nil)
require.Error(t, err)
require.NotNil(t, result)
- assert.ErrorIs(t, err, daemonErr)
+ require.ErrorIs(t, err, daemonErr)
assert.ErrorIs(t, err, fallbackErr)
}
@@ -1014,9 +1031,11 @@ func TestContainerRegistryService_InspectImageDigest_PreservesAnonymousUnauthori
w.Header().Set("WWW-Authenticate", `Bearer realm="`+tokenURL+`",service="registry.example.com"`)
w.WriteHeader(http.StatusUnauthorized)
case "/token":
- require.NoError(t, json.NewEncoder(w).Encode(map[string]string{
+ if !assert.NoError(t, json.NewEncoder(w).Encode(map[string]string{
"token": "anonymous-token",
- }))
+ })) {
+ return
+ }
default:
http.NotFound(w, r)
}
diff --git a/backend/internal/services/dashboard_service_test.go b/backend/internal/services/dashboard_service_test.go
index 727a09439..604b89c65 100644
--- a/backend/internal/services/dashboard_service_test.go
+++ b/backend/internal/services/dashboard_service_test.go
@@ -22,6 +22,7 @@ import (
dockermount "github.com/moby/moby/api/types/mount"
dockervolume "github.com/moby/moby/api/types/volume"
"github.com/moby/moby/client"
+ "github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
"gorm.io/gorm"
)
@@ -64,11 +65,17 @@ func newDashboardTestDockerService(
switch {
case strings.HasSuffix(r.URL.Path, "/containers/json"):
- require.NoError(t, json.NewEncoder(w).Encode(containers))
+ if !assert.NoError(t, json.NewEncoder(w).Encode(containers)) {
+ return
+ }
case strings.HasSuffix(r.URL.Path, "/images/json"):
- require.NoError(t, json.NewEncoder(w).Encode(images))
+ if !assert.NoError(t, json.NewEncoder(w).Encode(images)) {
+ return
+ }
case strings.HasSuffix(r.URL.Path, "/volumes"):
- require.NoError(t, json.NewEncoder(w).Encode(map[string]any{"Volumes": volumes, "Warnings": []string{}}))
+ if !assert.NoError(t, json.NewEncoder(w).Encode(map[string]any{"Volumes": volumes, "Warnings": []string{}})) {
+ return
+ }
default:
http.NotFound(w, r)
}
diff --git a/backend/internal/services/diagnostics_service_test.go b/backend/internal/services/diagnostics_service_test.go
index 370870209..b43d07293 100644
--- a/backend/internal/services/diagnostics_service_test.go
+++ b/backend/internal/services/diagnostics_service_test.go
@@ -1,6 +1,10 @@
package services
-import "testing"
+import (
+ "testing"
+
+ "github.com/stretchr/testify/assert"
+)
func TestDiagnosticsServiceCollect(t *testing.T) {
s := NewDiagnosticsService()
@@ -8,15 +12,19 @@ func TestDiagnosticsServiceCollect(t *testing.T) {
rt, mem, _ := s.Collect()
if rt.Goroutines <= 0 {
- t.Errorf("expected a positive goroutine count, got %d", rt.Goroutines)
- }
- if rt.GoVersion == "" {
- t.Error("expected a non-empty Go version")
+ assert.Positive(t, rt.Goroutines,
+ "expected a positive goroutine count, got %d", rt.Goroutines)
}
+
+ assert.NotEmpty(t, rt.GoVersion,
+ "expected a non-empty Go version")
+
if rt.NumCPU <= 0 {
- t.Errorf("expected a positive CPU count, got %d", rt.NumCPU)
- }
- if mem.Sys == 0 {
- t.Error("expected non-zero Sys memory")
+ assert.Positive(t, rt.NumCPU,
+ "expected a positive CPU count, got %d", rt.NumCPU)
}
+
+ assert.NotEqual(t, 0, mem.Sys,
+ "expected non-zero Sys memory")
+
}
diff --git a/backend/internal/services/docker_client_service_test.go b/backend/internal/services/docker_client_service_test.go
index e73d9b990..ccb369692 100644
--- a/backend/internal/services/docker_client_service_test.go
+++ b/backend/internal/services/docker_client_service_test.go
@@ -188,7 +188,7 @@ func TestDockerClientService_PublishImageStateResyncNotifiesSubscribers(t *testi
require.Equal(t, events.ImageEventType, message.Type)
require.Equal(t, docker.ImageStateResyncAction, message.Action)
case <-time.After(time.Second):
- t.Fatal("timed out waiting for image state resync event")
+ require.FailNow(t, "timed out waiting for image state resync event")
}
}
@@ -231,13 +231,13 @@ func TestDockerClientService_EventActorStopCancelsAndJoinsStreamInternal(t *test
select {
case <-streamStarted:
case <-time.After(time.Second):
- t.Fatal("Docker event stream did not start")
+ require.FailNow(t, "Docker event stream did not start")
}
select {
case message := <-eventsCh:
require.Equal(t, docker.ImageStateResyncAction, message.Action)
case <-time.After(time.Second):
- t.Fatal("Docker event stream did not publish reconnect resync")
+ require.FailNow(t, "Docker event stream did not publish reconnect resync")
}
stopCtx, cancel := context.WithTimeout(context.Background(), time.Second)
diff --git a/backend/internal/services/environment_runtime_notify_test.go b/backend/internal/services/environment_runtime_notify_test.go
index f34cdd260..2288a4ec7 100644
--- a/backend/internal/services/environment_runtime_notify_test.go
+++ b/backend/internal/services/environment_runtime_notify_test.go
@@ -23,12 +23,12 @@ func TestEnvironmentServiceRuntimeChangeSignalCoalescesInternal(t *testing.T) {
select {
case <-changes:
default:
- t.Fatal("expected a pending runtime change signal")
+ require.FailNow(t, "expected a pending runtime change signal")
}
select {
case <-changes:
- t.Fatal("expected coalesced signals, got a second wake-up")
+ require.FailNow(t, "expected coalesced signals, got a second wake-up")
default:
}
@@ -37,7 +37,7 @@ func TestEnvironmentServiceRuntimeChangeSignalCoalescesInternal(t *testing.T) {
s.NotifyRuntimeStateChanged()
select {
case <-changes:
- t.Fatal("expected no signal after unsubscribe")
+ require.FailNow(t, "expected no signal after unsubscribe")
default:
}
diff --git a/backend/internal/services/environment_service_test.go b/backend/internal/services/environment_service_test.go
index b441f2ec7..9f5b07bd1 100644
--- a/backend/internal/services/environment_service_test.go
+++ b/backend/internal/services/environment_service_test.go
@@ -28,6 +28,7 @@ import (
"github.com/getarcaneapp/arcane/types/v2/containerregistry"
"github.com/getarcaneapp/arcane/types/v2/environment"
"github.com/getarcaneapp/arcane/types/v2/gitops"
+ "github.com/stretchr/testify/assert"
"go.getarcane.app/sys/crypto"
"go.uber.org/fx/fxtest"
)
@@ -249,14 +250,26 @@ func TestEnvironmentService_SyncRegistriesToRemoteEnvironments_SyncsEligibleRemo
var env1Calls atomic.Int32
env1Token := "token-1"
env1Server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
- require.Equal(t, http.MethodPost, r.Method)
- require.Equal(t, "/api/container-registries/sync", r.URL.Path)
- require.Equal(t, env1Token, r.Header.Get("X-API-Key"))
- require.Equal(t, env1Token, r.Header.Get("X-Arcane-Agent-Token"))
+ if !assert.Equal(t, http.MethodPost, r.Method) {
+ return
+ }
+ if !assert.Equal(t, "/api/container-registries/sync", r.URL.Path) {
+ return
+ }
+ if !assert.Equal(t, env1Token, r.Header.Get("X-API-Key")) {
+ return
+ }
+ if !assert.Equal(t, env1Token, r.Header.Get("X-Arcane-Agent-Token")) {
+ return
+ }
var syncReq containerregistry.SyncRequest
- require.NoError(t, json.NewDecoder(r.Body).Decode(&syncReq))
- require.Len(t, syncReq.Registries, 1)
+ if !assert.NoError(t, json.NewDecoder(r.Body).Decode(&syncReq)) {
+ return
+ }
+ if !assert.Len(t, syncReq.Registries, 1) {
+ return
+ }
env1Calls.Add(1)
w.Header().Set("Content-Type", "application/json")
@@ -267,14 +280,26 @@ func TestEnvironmentService_SyncRegistriesToRemoteEnvironments_SyncsEligibleRemo
var env2Calls atomic.Int32
env2Token := "token-2"
env2Server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
- require.Equal(t, http.MethodPost, r.Method)
- require.Equal(t, "/api/container-registries/sync", r.URL.Path)
- require.Equal(t, env2Token, r.Header.Get("X-API-Key"))
- require.Equal(t, env2Token, r.Header.Get("X-Arcane-Agent-Token"))
+ if !assert.Equal(t, http.MethodPost, r.Method) {
+ return
+ }
+ if !assert.Equal(t, "/api/container-registries/sync", r.URL.Path) {
+ return
+ }
+ if !assert.Equal(t, env2Token, r.Header.Get("X-API-Key")) {
+ return
+ }
+ if !assert.Equal(t, env2Token, r.Header.Get("X-Arcane-Agent-Token")) {
+ return
+ }
var syncReq containerregistry.SyncRequest
- require.NoError(t, json.NewDecoder(r.Body).Decode(&syncReq))
- require.Len(t, syncReq.Registries, 1)
+ if !assert.NoError(t, json.NewDecoder(r.Body).Decode(&syncReq)) {
+ return
+ }
+ if !assert.Len(t, syncReq.Registries, 1) {
+ return
+ }
env2Calls.Add(1)
w.Header().Set("Content-Type", "application/json")
@@ -300,21 +325,43 @@ func TestEnvironmentService_SyncRegistriesToEnvironment_IncludesECRFields(t *tes
createTestECRRegistry(t, db, "reg-ecr")
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
- require.Equal(t, http.MethodPost, r.Method)
- require.Equal(t, "/api/container-registries/sync", r.URL.Path)
+ if !assert.Equal(t, http.MethodPost, r.Method) {
+ return
+ }
+ if !assert.Equal(t, "/api/container-registries/sync", r.URL.Path) {
+ return
+ }
var syncReq containerregistry.SyncRequest
- require.NoError(t, json.NewDecoder(r.Body).Decode(&syncReq))
- require.Len(t, syncReq.Registries, 1)
+ if !assert.NoError(t, json.NewDecoder(r.Body).Decode(&syncReq)) {
+ return
+ }
+ if !assert.Len(t, syncReq.Registries, 1) {
+ return
+ }
registry := syncReq.Registries[0]
- require.Equal(t, registryTypeECR, registry.RegistryType)
- require.Equal(t, "123456789012.dkr.ecr.us-east-1.amazonaws.com", registry.URL)
- require.Equal(t, "AKIA1234567890EXAMPLE", registry.AWSAccessKeyID)
- require.Equal(t, "aws-secret", registry.AWSSecretAccessKey)
- require.Equal(t, "us-east-1", registry.AWSRegion)
- require.Empty(t, registry.Username)
- require.Empty(t, registry.Token)
+ if !assert.Equal(t, registryTypeECR, registry.RegistryType) {
+ return
+ }
+ if !assert.Equal(t, "123456789012.dkr.ecr.us-east-1.amazonaws.com", registry.URL) {
+ return
+ }
+ if !assert.Equal(t, "AKIA1234567890EXAMPLE", registry.AWSAccessKeyID) {
+ return
+ }
+ if !assert.Equal(t, "aws-secret", registry.AWSSecretAccessKey) {
+ return
+ }
+ if !assert.Equal(t, "us-east-1", registry.AWSRegion) {
+ return
+ }
+ if !assert.Empty(t, registry.Username) {
+ return
+ }
+ if !assert.Empty(t, registry.Token) {
+ return
+ }
w.Header().Set("Content-Type", "application/json")
_, _ = w.Write([]byte(`{"success":true,"data":{"message":"ok"}}`))
@@ -346,16 +393,32 @@ func TestEnvironmentService_SyncRepositoriesToEnvironment_UsesAgentHeaders(t *te
accessToken := "token-1"
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
- require.Equal(t, http.MethodPost, r.Method)
- require.Equal(t, "/api/git-repositories/sync", r.URL.Path)
- require.Equal(t, accessToken, r.Header.Get("X-API-Key"))
- require.Equal(t, accessToken, r.Header.Get("X-Arcane-Agent-Token"))
+ if !assert.Equal(t, http.MethodPost, r.Method) {
+ return
+ }
+ if !assert.Equal(t, "/api/git-repositories/sync", r.URL.Path) {
+ return
+ }
+ if !assert.Equal(t, accessToken, r.Header.Get("X-API-Key")) {
+ return
+ }
+ if !assert.Equal(t, accessToken, r.Header.Get("X-Arcane-Agent-Token")) {
+ return
+ }
var syncReq gitops.RepositorySyncRequest
- require.NoError(t, json.NewDecoder(r.Body).Decode(&syncReq))
- require.Len(t, syncReq.Repositories, 1)
- require.Equal(t, "repo-token", syncReq.Repositories[0].Token)
- require.Equal(t, "arcane", syncReq.Repositories[0].Username)
+ if !assert.NoError(t, json.NewDecoder(r.Body).Decode(&syncReq)) {
+ return
+ }
+ if !assert.Len(t, syncReq.Repositories, 1) {
+ return
+ }
+ if !assert.Equal(t, "repo-token", syncReq.Repositories[0].Token) {
+ return
+ }
+ if !assert.Equal(t, "arcane", syncReq.Repositories[0].Username) {
+ return
+ }
w.Header().Set("Content-Type", "application/json")
_, _ = w.Write([]byte(`{"success":true,"data":{"message":"ok"}}`))
@@ -670,7 +733,7 @@ func TestEnvironmentService_GenerateDeploymentSnippets_ExplicitlyUsePollTranspor
require.NotContains(t, standard.DockerCompose, "EDGE_TRANSPORT=websocket")
require.Contains(t, standard.DockerRun, "EDGE_TRANSPORT=poll")
require.Contains(t, standard.DockerCompose, "EDGE_TRANSPORT=poll")
- require.True(t, strings.Contains(standard.DockerRun, "AGENT_TOKEN=token-123"))
+ require.Contains(t, standard.DockerRun, "AGENT_TOKEN=token-123")
require.Contains(t, standard.DockerRun, "-v arcane-data:/app/data")
require.Contains(t, standard.DockerCompose, "- arcane-data:/app/data")
require.NotContains(t, standard.DockerRun, "-v arcane-data:/data")
@@ -682,7 +745,7 @@ func TestEnvironmentService_GenerateDeploymentSnippets_ExplicitlyUsePollTranspor
require.NotContains(t, edgeSnippets.DockerCompose, "EDGE_TRANSPORT=websocket")
require.Contains(t, edgeSnippets.DockerRun, "EDGE_TRANSPORT=poll")
require.Contains(t, edgeSnippets.DockerCompose, "EDGE_TRANSPORT=poll")
- require.True(t, strings.Contains(edgeSnippets.DockerRun, "AGENT_TOKEN=token-456"))
+ require.Contains(t, edgeSnippets.DockerRun, "AGENT_TOKEN=token-456")
require.Contains(t, edgeSnippets.DockerRun, "-v arcane-data:/app/data")
require.Contains(t, edgeSnippets.DockerCompose, "- arcane-data:/app/data")
require.NotContains(t, edgeSnippets.DockerRun, "-v arcane-data:/data")
@@ -779,8 +842,10 @@ func TestEnvironmentService_EnsureSwarmNodeAgentEnvironment_ReusesLegacyHiddenRe
ParentEnvironmentID: &parentEnvironmentID,
SwarmNodeID: &nodeID,
}
- if err := db.WithContext(ctx).Create(legacy).Error; err != nil {
- t.Fatalf("create legacy environment: %v", err)
+ {
+ err := db.WithContext(ctx).Create(legacy).Error
+ require.NoError(t, err,
+ "create legacy environment: %v", err)
}
reused, reusedToken, err := svc.EnsureSwarmNodeAgentEnvironment(
@@ -792,28 +857,31 @@ func TestEnvironmentService_EnsureSwarmNodeAgentEnvironment_ReusesLegacyHiddenRe
"username",
false,
)
- if err != nil {
- t.Fatalf("EnsureSwarmNodeAgentEnvironment() error = %v", err)
- }
- if reused.ID != legacy.ID {
- t.Fatalf("environment ID = %q, want %q", reused.ID, legacy.ID)
- }
- if !reused.Hidden {
- t.Fatal("legacy environment was unexpectedly converted to visible")
- }
- if reusedToken != token {
- t.Fatalf("token = %q, want existing token", reusedToken)
- }
+
+ require.NoError(t, err,
+ "EnsureSwarmNodeAgentEnvironment() error = %v", err)
+
+ require.Equal(t, legacy.ID, reused.ID,
+ "environment ID = %q, want %q", reused.ID, legacy.ID)
+
+ require.True(t, reused.Hidden,
+ "legacy environment was unexpectedly converted to visible")
+
+ require.Equal(t, token, reusedToken,
+ "token = %q, want existing token", reusedToken)
var environments []models.Environment
- if err := db.WithContext(ctx).
- Where("parent_environment_id = ? AND swarm_node_id = ?", parentEnvironmentID, nodeID).
- Find(&environments).Error; err != nil {
- t.Fatalf("list node environments: %v", err)
- }
- if len(environments) != 1 {
- t.Fatalf("environment count = %d, want 1", len(environments))
+ {
+ err := db.WithContext(ctx).
+ Where("parent_environment_id = ? AND swarm_node_id = ?", parentEnvironmentID, nodeID).
+ Find(&environments).Error
+ require.NoError(t, err,
+ "list node environments: %v", err)
}
+
+ require.Len(t, environments, 1,
+ "environment count = %d, want 1", len(environments))
+
}
// TestEnvironmentService_EnsureSwarmNodeAgentEnvironment_TokenResolvesEndToEnd
@@ -1112,7 +1180,9 @@ func newTestWebSocketTunnelInternal(t *testing.T, envID string) (*edge.AgentTunn
connCh := make(chan *websocket.Conn, 1)
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
conn, err := websocket.Accept(w, r, nil)
- require.NoError(t, err)
+ if !assert.NoError(t, err) {
+ return
+ }
connCh <- conn
}))
diff --git a/backend/internal/services/event_service_test.go b/backend/internal/services/event_service_test.go
index 8ba2e47ab..fa7b46d68 100644
--- a/backend/internal/services/event_service_test.go
+++ b/backend/internal/services/event_service_test.go
@@ -15,6 +15,7 @@ import (
"github.com/getarcaneapp/arcane/backend/v2/pkg/pagination"
pkgutils "github.com/getarcaneapp/arcane/backend/v2/pkg/utils"
"github.com/libtnb/sqlite"
+ "github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
"gorm.io/gorm"
)
@@ -185,13 +186,21 @@ func TestEventService_CreateEvent_ForwardsToManagerAPIInAgentMode(t *testing.T)
requests := make(chan CreateEventRequest, 1)
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
- require.Equal(t, http.MethodPost, r.Method)
- require.Equal(t, "/api/events", r.URL.Path)
- require.Equal(t, "test-agent-token", r.Header.Get(pkgutils.HeaderAgentToken))
+ if !assert.Equal(t, http.MethodPost, r.Method) {
+ return
+ }
+ if !assert.Equal(t, "/api/events", r.URL.Path) {
+ return
+ }
+ if !assert.Equal(t, "test-agent-token", r.Header.Get(pkgutils.HeaderAgentToken)) {
+ return
+ }
defer func() { _ = r.Body.Close() }()
var payload CreateEventRequest
- require.NoError(t, json.NewDecoder(r.Body).Decode(&payload))
+ if !assert.NoError(t, json.NewDecoder(r.Body).Decode(&payload)) {
+ return
+ }
select {
case requests <- payload:
@@ -228,7 +237,7 @@ func TestEventService_CreateEvent_ForwardsToManagerAPIInAgentMode(t *testing.T)
require.Equal(t, "0", *payload.EnvironmentID)
require.Equal(t, "test", payload.Metadata["source"])
case <-time.After(2 * time.Second):
- t.Fatal("timed out waiting for manager event sync request")
+ require.FailNow(t, "timed out waiting for manager event sync request")
}
}
diff --git a/backend/internal/services/federated_credential_service_test.go b/backend/internal/services/federated_credential_service_test.go
index a73644279..2df7f09cf 100644
--- a/backend/internal/services/federated_credential_service_test.go
+++ b/backend/internal/services/federated_credential_service_test.go
@@ -26,6 +26,7 @@ import (
"github.com/getarcaneapp/arcane/backend/v2/internal/models"
"github.com/getarcaneapp/arcane/backend/v2/pkg/authz"
federatedtypes "github.com/getarcaneapp/arcane/types/v2/federated"
+ "github.com/stretchr/testify/assert"
)
type federatedTestIssuerInternal struct {
@@ -48,18 +49,20 @@ func newFederatedTestIssuerInternal(t *testing.T) *federatedTestIssuerInternal {
mux := http.NewServeMux()
mux.HandleFunc("/.well-known/openid-configuration", func(w http.ResponseWriter, _ *http.Request) {
- require.NoError(t, json.NewEncoder(w).Encode(map[string]any{
+ if !assert.NoError(t, json.NewEncoder(w).Encode(map[string]any{
"issuer": issuer.IssuerURL,
"jwks_uri": issuer.IssuerURL + "/jwks",
"authorization_endpoint": issuer.IssuerURL + "/authorize",
"token_endpoint": issuer.IssuerURL + "/token",
"subject_types_supported": []string{"public"},
"id_token_signing_alg_values_supported": []string{"RS256"},
- }))
+ })) {
+ return
+ }
})
mux.HandleFunc("/jwks", func(w http.ResponseWriter, _ *http.Request) {
pub := privateKey.PublicKey
- require.NoError(t, json.NewEncoder(w).Encode(map[string]any{
+ if !assert.NoError(t, json.NewEncoder(w).Encode(map[string]any{
"keys": []map[string]any{
{
"kty": "RSA",
@@ -70,7 +73,9 @@ func newFederatedTestIssuerInternal(t *testing.T) *federatedTestIssuerInternal {
"e": base64.RawURLEncoding.EncodeToString(big.NewInt(int64(pub.E)).Bytes()),
},
},
- }))
+ })) {
+ return
+ }
})
issuer.server = httptest.NewServer(mux)
diff --git a/backend/internal/services/gitops_sync_service_test.go b/backend/internal/services/gitops_sync_service_test.go
index af547f27d..13550699c 100644
--- a/backend/internal/services/gitops_sync_service_test.go
+++ b/backend/internal/services/gitops_sync_service_test.go
@@ -331,7 +331,7 @@ func TestGitOpsSyncService_CleanupLeakedScratchDirsOnStartup_RemovesOrphans(t *t
for _, p := range scratch {
_, err := os.Stat(p)
- assert.ErrorIs(t, err, os.ErrNotExist, "scratch dir should be removed: %s", p)
+ require.ErrorIs(t, err, os.ErrNotExist, "scratch dir should be removed: %s", p)
}
_, err := os.Stat(realProject)
assert.NoError(t, err, "real project dir must be kept")
@@ -369,7 +369,7 @@ func TestGitOpsSyncService_SyncProjectDirectory_RefusesDuplicateOnNameCollision(
require.ErrorIs(t, err, common.ErrGitOpsSyncProjectBindingBroken)
_, statErr := os.Stat(filepath.Join(projectsDir, "Dozzle-1"))
- assert.ErrorIs(t, statErr, os.ErrNotExist, "must not mint a -N duplicate")
+ require.ErrorIs(t, statErr, os.ErrNotExist, "must not mint a -N duplicate")
var got models.GitOpsSync
require.NoError(t, db.Where("id = ?", sync.ID).First(&got).Error)
@@ -402,7 +402,7 @@ func TestGitOpsSyncService_GetOrCreateProject_RefusesDuplicateOnNameCollision(t
require.ErrorIs(t, err, common.ErrGitOpsSyncProjectBindingBroken)
_, statErr := os.Stat(filepath.Join(projectsDir, "Dozzle-1"))
- assert.ErrorIs(t, statErr, os.ErrNotExist, "must not mint a -N duplicate")
+ require.ErrorIs(t, statErr, os.ErrNotExist, "must not mint a -N duplicate")
var got models.GitOpsSync
require.NoError(t, db.Where("id = ?", sync.ID).First(&got).Error)
@@ -564,10 +564,10 @@ services:
assert.Equal(t, filepath.Join(updatedProject.Path, "docker-compose.yaml"), composePath)
_, statErr := os.Stat(filepath.Join(updatedProject.Path, "old.txt"))
- assert.ErrorIs(t, statErr, os.ErrNotExist)
+ require.ErrorIs(t, statErr, os.ErrNotExist)
_, statErr = os.Stat(filepath.Join(updatedProject.Path, "compose.yaml"))
- assert.ErrorIs(t, statErr, os.ErrNotExist)
+ require.ErrorIs(t, statErr, os.ErrNotExist)
keepBytes, err := os.ReadFile(filepath.Join(updatedProject.Path, "keep.txt"))
require.NoError(t, err)
@@ -1014,7 +1014,7 @@ func TestProjectsRemoveStaleComposeFiles_RemovesStaleCustomComposeFiles(t *testi
require.NoError(t, err)
_, statErr := os.Stat(filepath.Join(projectPath, "radarr.yaml"))
- assert.ErrorIs(t, statErr, os.ErrNotExist)
+ require.ErrorIs(t, statErr, os.ErrNotExist)
_, statErr = os.Stat(filepath.Join(projectPath, "sonarr.yaml"))
require.NoError(t, statErr)
@@ -1183,7 +1183,7 @@ func TestGitOpsSyncService_SyncProjectDirectory_FailsWhenBoundProjectMissing(t *
assert.Zero(t, projectCount)
_, statErr := os.Stat(filepath.Join(projectsDir, "demo-project"))
- assert.ErrorIs(t, statErr, os.ErrNotExist)
+ require.ErrorIs(t, statErr, os.ErrNotExist)
var storedSync models.GitOpsSync
require.NoError(t, db.First(&storedSync, "id = ?", sync.ID).Error)
@@ -1280,9 +1280,9 @@ func TestGitOpsSyncService_GetOrCreateProjectInternal_FailsWhenBoundProjectMissi
assert.Zero(t, projectCount)
_, statErr := os.Stat(filepath.Join(projectsDir, "demo-project"))
- assert.ErrorIs(t, statErr, os.ErrNotExist)
+ require.ErrorIs(t, statErr, os.ErrNotExist)
_, statErr = os.Stat(filepath.Join(projectsDir, "demo-project-1"))
- assert.ErrorIs(t, statErr, os.ErrNotExist)
+ require.ErrorIs(t, statErr, os.ErrNotExist)
var storedSync models.GitOpsSync
require.NoError(t, db.First(&storedSync, "id = ?", sync.ID).Error)
diff --git a/backend/internal/services/image_attestations_service_test.go b/backend/internal/services/image_attestations_service_test.go
index 50b9c81c3..609207ca5 100644
--- a/backend/internal/services/image_attestations_service_test.go
+++ b/backend/internal/services/image_attestations_service_test.go
@@ -7,6 +7,7 @@ import (
"github.com/google/go-containerregistry/pkg/v1/static"
"github.com/klauspost/compress/zstd"
+ "github.com/stretchr/testify/require"
)
func TestReadAttestationLayerBytesInternalDecompressesGzip(t *testing.T) {
@@ -14,21 +15,27 @@ func TestReadAttestationLayerBytesInternalDecompressesGzip(t *testing.T) {
var buf bytes.Buffer
gz := gzip.NewWriter(&buf)
- if _, err := gz.Write(statement); err != nil {
- t.Fatalf("gzip write: %v", err)
+ {
+ _, err := gz.Write(statement)
+ require.NoError(t, err,
+ "gzip write: %v", err)
}
- if err := gz.Close(); err != nil {
- t.Fatalf("gzip close: %v", err)
+ {
+
+ err := gz.Close()
+ require.NoError(t, err,
+ "gzip close: %v", err)
}
layer := static.NewLayer(buf.Bytes(), inTotoLayerMediaTypeInternal)
got, err := readAttestationLayerBytesInternal(layer, "sha256:test")
- if err != nil {
- t.Fatalf("unexpected error: %v", err)
- }
- if !bytes.Equal(got, statement) {
- t.Fatalf("expected decompressed statement %q, got %q", statement, got)
- }
+
+ require.NoError(t, err,
+ "unexpected error: %v", err)
+
+ require.True(t, bytes.Equal(got, statement),
+ "expected decompressed statement %q, got %q", statement, got)
+
}
func TestReadAttestationLayerBytesInternalPassesThroughRawJSON(t *testing.T) {
@@ -36,32 +43,37 @@ func TestReadAttestationLayerBytesInternalPassesThroughRawJSON(t *testing.T) {
layer := static.NewLayer(statement, inTotoLayerMediaTypeInternal)
got, err := readAttestationLayerBytesInternal(layer, "sha256:test")
- if err != nil {
- t.Fatalf("unexpected error: %v", err)
- }
- if !bytes.Equal(got, statement) {
- t.Fatalf("expected raw statement unchanged %q, got %q", statement, got)
- }
+
+ require.NoError(t, err,
+ "unexpected error: %v", err)
+
+ require.True(t, bytes.Equal(got, statement),
+ "expected raw statement unchanged %q, got %q", statement, got)
+
}
func TestReadAttestationLayerBytesInternalDecompressesZstd(t *testing.T) {
statement := []byte(`{"predicateType":"https://slsa.dev/provenance/v1"}`)
encoder, err := zstd.NewWriter(nil)
- if err != nil {
- t.Fatalf("zstd writer: %v", err)
- }
+
+ require.NoError(t, err,
+ "zstd writer: %v", err)
+
compressed := encoder.EncodeAll(statement, nil)
- if err := encoder.Close(); err != nil {
- t.Fatalf("zstd close: %v", err)
+ {
+ err := encoder.Close()
+ require.NoError(t, err,
+ "zstd close: %v", err)
}
layer := static.NewLayer(compressed, inTotoLayerMediaTypeInternal)
got, err := readAttestationLayerBytesInternal(layer, "sha256:test")
- if err != nil {
- t.Fatalf("unexpected error: %v", err)
- }
- if !bytes.Equal(got, statement) {
- t.Fatalf("expected decompressed statement %q, got %q", statement, got)
- }
+
+ require.NoError(t, err,
+ "unexpected error: %v", err)
+
+ require.True(t, bytes.Equal(got, statement),
+ "expected decompressed statement %q, got %q", statement, got)
+
}
diff --git a/backend/internal/services/image_service_test.go b/backend/internal/services/image_service_test.go
index 70f270885..4e1ff8e5c 100644
--- a/backend/internal/services/image_service_test.go
+++ b/backend/internal/services/image_service_test.go
@@ -290,7 +290,9 @@ func TestImageServiceExportImageReturnsTarStreamInternal(t *testing.T) {
return
}
names := r.URL.Query()["names"]
- require.Equal(t, []string{"source:latest"}, names)
+ if !assert.Equal(t, []string{"source:latest"}, names) {
+ return
+ }
_, _ = w.Write([]byte("tar-bytes"))
}))
t.Cleanup(server.Close)
diff --git a/backend/internal/services/image_update_service_test.go b/backend/internal/services/image_update_service_test.go
index 8112f5a06..5bea9da0f 100644
--- a/backend/internal/services/image_update_service_test.go
+++ b/backend/internal/services/image_update_service_test.go
@@ -417,10 +417,12 @@ func TestImageUpdateService_InspectLocalImageSnapshot_NoRepoDigestsRemainsLocal(
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if strings.Contains(r.URL.Path, "/images/") && strings.HasSuffix(r.URL.Path, "/json") {
w.Header().Set("Content-Type", "application/json")
- require.NoError(t, json.NewEncoder(w).Encode(dockertypesimage.InspectResponse{
+ if !assert.NoError(t, json.NewEncoder(w).Encode(dockertypesimage.InspectResponse{
ID: "sha256:local-only-image",
RepoTags: []string{"local-only:latest"},
- }))
+ })) {
+ return
+ }
return
}
http.NotFound(w, r)
@@ -455,11 +457,13 @@ func newImageUpdateFallbackServer(t *testing.T, repositoryTag, localDigest, remo
}
w.Header().Set("Content-Type", "application/json")
- require.NoError(t, json.NewEncoder(w).Encode(dockertypesimage.InspectResponse{
+ if !assert.NoError(t, json.NewEncoder(w).Encode(dockertypesimage.InspectResponse{
ID: "sha256:local-image-id",
RepoTags: []string{imageRef},
RepoDigests: []string{repositoryRef + "@" + localDigest},
- }))
+ })) {
+ return
+ }
return
case r.URL.Path == manifestPath:
w.Header().Set("Docker-Content-Digest", remoteDigest)
@@ -507,7 +511,9 @@ func newImageRefResolutionServer(t *testing.T, containers []dockertypescontainer
return
case strings.HasSuffix(r.URL.Path, "/containers/json"):
w.Header().Set("Content-Type", "application/json")
- require.NoError(t, json.NewEncoder(w).Encode(containers))
+ if !assert.NoError(t, json.NewEncoder(w).Encode(containers)) {
+ return
+ }
return
default:
http.NotFound(w, r)
@@ -554,7 +560,7 @@ func TestImageUpdateService_GetImageRefByIDInternal_UsesContainerFallback(t *tes
imageRef, err := svc.getImageRefByIDInternal(context.Background(), imageID)
if tt.wantErr != "" {
require.Error(t, err)
- assert.ErrorContains(t, err, tt.wantErr)
+ require.ErrorContains(t, err, tt.wantErr)
assert.Empty(t, imageRef)
return
}
@@ -669,11 +675,13 @@ func newImageUpdateNoRepoTagsServer(t *testing.T, imageID, localDigest string) *
return httptest.NewTLSServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if strings.Contains(r.URL.Path, "/images/") && strings.HasSuffix(r.URL.Path, "/json") {
w.Header().Set("Content-Type", "application/json")
- require.NoError(t, json.NewEncoder(w).Encode(dockertypesimage.InspectResponse{
+ if !assert.NoError(t, json.NewEncoder(w).Encode(dockertypesimage.InspectResponse{
ID: imageID,
RepoTags: []string{},
RepoDigests: []string{r.Host + "/valkey/valkey@" + localDigest},
- }))
+ })) {
+ return
+ }
return
}
http.NotFound(w, r)
@@ -796,7 +804,7 @@ func TestImageUpdateService_CheckMultipleImagesCompletesActivityWhenRequestConte
case err := <-errCh:
require.ErrorIs(t, err, context.Canceled)
case <-time.After(time.Second):
- t.Fatal("timed out waiting for image update check to return")
+ require.FailNow(t, "timed out waiting for image update check to return")
}
require.Eventually(t, func() bool {
@@ -1767,10 +1775,14 @@ func newImageUpdateDiscoveryServerInternal(
switch {
case strings.HasSuffix(r.URL.Path, "/images/json"):
w.Header().Set("Content-Type", "application/json")
- require.NoError(t, json.NewEncoder(w).Encode(images))
+ if !assert.NoError(t, json.NewEncoder(w).Encode(images)) {
+ return
+ }
case strings.HasSuffix(r.URL.Path, "/containers/json"):
w.Header().Set("Content-Type", "application/json")
- require.NoError(t, json.NewEncoder(w).Encode(containers))
+ if !assert.NoError(t, json.NewEncoder(w).Encode(containers)) {
+ return
+ }
default:
http.NotFound(w, r)
}
@@ -2069,10 +2081,12 @@ func TestImageUpdateService_GetAllImageRefsFallsBackWhenContainerDiscoveryFailsI
switch {
case strings.HasSuffix(r.URL.Path, "/images/json"):
w.Header().Set("Content-Type", "application/json")
- require.NoError(t, json.NewEncoder(w).Encode([]dockertypesimage.Summary{
+ if !assert.NoError(t, json.NewEncoder(w).Encode([]dockertypesimage.Summary{
{ID: "sha256:first", RepoTags: []string{firstRef}},
{ID: "sha256:second", RepoTags: []string{secondRef}},
- }))
+ })) {
+ return
+ }
case strings.HasSuffix(r.URL.Path, "/containers/json"):
http.Error(w, "container listing denied", http.StatusForbidden)
default:
diff --git a/backend/internal/services/job_service_test.go b/backend/internal/services/job_service_test.go
index 589706064..75e432420 100644
--- a/backend/internal/services/job_service_test.go
+++ b/backend/internal/services/job_service_test.go
@@ -319,8 +319,7 @@ func findJobStatusByIDInternal(t *testing.T, jobs []jobschedule.JobStatus, id st
return job
}
}
-
- t.Fatalf("job %q not found", id)
+ require.FailNowf(t, "unexpected failure", "job %q not found", id)
return jobschedule.JobStatus{}
}
diff --git a/backend/internal/services/lifecycle_path_diagnostics_unix_test.go b/backend/internal/services/lifecycle_path_diagnostics_unix_test.go
index 804924a91..c2b753a34 100644
--- a/backend/internal/services/lifecycle_path_diagnostics_unix_test.go
+++ b/backend/internal/services/lifecycle_path_diagnostics_unix_test.go
@@ -88,7 +88,7 @@ func TestValidateScriptPath_PermissionDeniedIncludesDiagnostics(t *testing.T) {
err := validateScriptPathInternal(dir, "blocked/pre-deploy.sh")
require.Error(t, err)
- assert.ErrorIs(t, err, os.ErrPermission)
+ require.ErrorIs(t, err, os.ErrPermission)
assert.Contains(t, err.Error(), "Arcane pre-deploy validation")
assert.Contains(t, err.Error(), "Arcane process identity: uid=")
assert.Contains(t, err.Error(), blockedDir)
diff --git a/backend/internal/services/lifecycle_service_test.go b/backend/internal/services/lifecycle_service_test.go
index aaa10fffe..1de4a7137 100644
--- a/backend/internal/services/lifecycle_service_test.go
+++ b/backend/internal/services/lifecycle_service_test.go
@@ -182,7 +182,7 @@ func TestDescribeScriptStatError_PermissionDeniedIsActionable(t *testing.T) {
)
require.Error(t, err)
- assert.ErrorIs(t, err, os.ErrPermission)
+ require.ErrorIs(t, err, os.ErrPermission)
assert.Contains(t, err.Error(), "Arcane pre-deploy validation")
assert.Contains(t, err.Error(), "permission denied")
assert.Contains(t, err.Error(), "scripts/pre-deploy.sh")
@@ -197,7 +197,7 @@ func TestDescribeScriptStatError_PreservesGenericStatFailure(t *testing.T) {
)
require.Error(t, err)
- assert.ErrorIs(t, err, os.ErrNotExist)
+ require.ErrorIs(t, err, os.ErrNotExist)
assert.Contains(t, err.Error(), `stat script "missing.sh"`)
assert.NotContains(t, err.Error(), "Arcane pre-deploy validation could not inspect")
}
diff --git a/backend/internal/services/notification_service_test.go b/backend/internal/services/notification_service_test.go
index ae3c31e09..2ca2ae0a2 100644
--- a/backend/internal/services/notification_service_test.go
+++ b/backend/internal/services/notification_service_test.go
@@ -26,6 +26,7 @@ import (
"github.com/getarcaneapp/arcane/types/v2/imageupdate"
notificationdto "github.com/getarcaneapp/arcane/types/v2/notification"
"github.com/getarcaneapp/arcane/types/v2/system"
+ "github.com/stretchr/testify/assert"
"go.getarcane.app/sys/crypto"
)
@@ -169,7 +170,7 @@ func TestNotificationService_DispatchNotification_UnsupportedKindReturnsSentinel
require.Error(t, err)
require.ErrorIs(t, err, ErrUnsupportedDispatchKind)
var unsupportedErr = ErrUnsupportedDispatchKind
- require.True(t, errors.Is(err, unsupportedErr))
+ require.ErrorIs(t, err, unsupportedErr)
require.Contains(t, err.Error(), "bogus_kind")
}
@@ -215,18 +216,28 @@ func TestNotificationService_SendImageUpdateNotification_AgentModeDispatchesToMa
var calls atomic.Int32
var dispatched notificationdto.DispatchRequest
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
- require.Equal(t, http.MethodPost, r.Method)
- require.Equal(t, "/api/notifications/dispatch", r.URL.Path)
- require.Equal(t, "agent-token", r.Header.Get("X-API-Key"))
- require.NoError(t, json.NewDecoder(r.Body).Decode(&dispatched))
+ if !assert.Equal(t, http.MethodPost, r.Method) {
+ return
+ }
+ if !assert.Equal(t, "/api/notifications/dispatch", r.URL.Path) {
+ return
+ }
+ if !assert.Equal(t, "agent-token", r.Header.Get("X-API-Key")) {
+ return
+ }
+ if !assert.NoError(t, json.NewDecoder(r.Body).Decode(&dispatched)) {
+ return
+ }
calls.Add(1)
- require.NoError(t, json.NewEncoder(w).Encode(map[string]any{
+ if !assert.NoError(t, json.NewEncoder(w).Encode(map[string]any{
"success": true,
"data": notificationdto.DispatchResponse{
Message: "Notification dispatched successfully",
Delivered: 2,
},
- }))
+ })) {
+ return
+ }
}))
defer server.Close()
@@ -239,7 +250,7 @@ func TestNotificationService_SendImageUpdateNotification_AgentModeDispatchesToMa
delivered, err := svc.SendImageUpdateNotification(ctx, "nginx:latest", newNotificationTestUpdateInfoInternal(), models.NotificationEventImageUpdate)
require.NoError(t, err)
- require.EqualValues(t, 2, delivered)
+ require.Equal(t, 2, delivered)
require.EqualValues(t, 1, calls.Load())
require.Equal(t, notificationdto.DispatchKindImageUpdate, dispatched.Kind)
require.NotNil(t, dispatched.ImageUpdate)
@@ -253,17 +264,27 @@ func TestNotificationService_SendBatchImageUpdateNotification_AgentModeUsesManag
var dispatched notificationdto.DispatchRequest
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
- require.Equal(t, http.MethodPost, r.Method)
- require.Equal(t, "/api/notifications/dispatch", r.URL.Path)
- require.Equal(t, "agent-token", r.Header.Get("X-API-Key"))
- require.NoError(t, json.NewDecoder(r.Body).Decode(&dispatched))
- require.NoError(t, json.NewEncoder(w).Encode(map[string]any{
+ if !assert.Equal(t, http.MethodPost, r.Method) {
+ return
+ }
+ if !assert.Equal(t, "/api/notifications/dispatch", r.URL.Path) {
+ return
+ }
+ if !assert.Equal(t, "agent-token", r.Header.Get("X-API-Key")) {
+ return
+ }
+ if !assert.NoError(t, json.NewDecoder(r.Body).Decode(&dispatched)) {
+ return
+ }
+ if !assert.NoError(t, json.NewEncoder(w).Encode(map[string]any{
"success": true,
"data": notificationdto.DispatchResponse{
Message: "Notification dispatched successfully",
Delivered: 0,
},
- }))
+ })) {
+ return
+ }
}))
defer server.Close()
@@ -278,7 +299,7 @@ func TestNotificationService_SendBatchImageUpdateNotification_AgentModeUsesManag
"nginx:latest": newNotificationTestUpdateInfoInternal(),
})
require.NoError(t, err)
- require.EqualValues(t, 0, delivered)
+ require.Equal(t, 0, delivered)
require.Equal(t, notificationdto.DispatchKindBatchImageUpdate, dispatched.Kind)
require.NotNil(t, dispatched.BatchImageUpdate)
require.Contains(t, dispatched.BatchImageUpdate.Updates, "nginx:latest")
@@ -321,7 +342,7 @@ func TestNotificationService_SendBatchImageUpdateNotification_AgentModeSkipsNoOp
t.Run("empty updates", func(t *testing.T) {
delivered, err := svc.SendBatchImageUpdateNotification(ctx, map[string]*imageupdate.Response{})
require.NoError(t, err)
- require.EqualValues(t, 0, delivered)
+ require.Equal(t, 0, delivered)
require.EqualValues(t, 0, calls.Load())
})
@@ -335,7 +356,7 @@ func TestNotificationService_SendBatchImageUpdateNotification_AgentModeSkipsNoOp
"redis:latest": nil,
})
require.NoError(t, err)
- require.EqualValues(t, 0, delivered)
+ require.Equal(t, 0, delivered)
require.EqualValues(t, 0, calls.Load())
})
}
@@ -765,6 +786,6 @@ func TestSupportedNotificationTestTypes_IncludesAutoHeal(t *testing.T) {
require.True(t, ok, "expected %q to be in supportedNotificationTestTypes", tt)
}
- require.Equal(t, len(expected), len(supportedNotificationTestTypes),
+ require.Len(t, supportedNotificationTestTypes, len(expected),
"supportedNotificationTestTypes has unexpected entries")
}
diff --git a/backend/internal/services/oidc_service_test.go b/backend/internal/services/oidc_service_test.go
index 277140c64..4fb21ced6 100644
--- a/backend/internal/services/oidc_service_test.go
+++ b/backend/internal/services/oidc_service_test.go
@@ -5,6 +5,7 @@ import (
"testing"
"github.com/getarcaneapp/arcane/backend/v2/internal/config"
+ "github.com/stretchr/testify/require"
)
func TestValidateMobileRedirectURI(t *testing.T) {
@@ -31,9 +32,10 @@ func TestValidateMobileRedirectURI(t *testing.T) {
for _, tc := range cases {
t.Run(tc.name, func(t *testing.T) {
err := s.ValidateMobileRedirectURI(ctx, tc.uri)
- if (err != nil) != tc.wantErr {
- t.Fatalf("ValidateMobileRedirectURI(%q): wantErr=%v got err=%v", tc.uri, tc.wantErr, err)
- }
+
+ require.Equal(t, tc.wantErr, (err != nil),
+ "ValidateMobileRedirectURI(%q): wantErr=%v got err=%v", tc.uri, tc.wantErr, err)
+
})
}
}
@@ -49,12 +51,14 @@ func TestGetMobileRedirectAllowlistTrimsWhitespace(t *testing.T) {
got := s.GetMobileRedirectAllowlist(ctx)
want := []string{"arcane-mobile://a", "arcane-mobile://b", "arcane-mobile://c"}
if len(got) != len(want) {
- t.Fatalf("got %d entries (%v), want %d (%v)", len(got), got, len(want), want)
+ require.Len(t, got, len(want),
+ "got %d entries (%v), want %d (%v)", len(got), got, len(want), want)
}
for i, w := range want {
- if got[i] != w {
- t.Fatalf("entry %d: got %q, want %q", i, got[i], w)
- }
+
+ require.Equal(t, w, got[i],
+ "entry %d: got %q, want %q", i, got[i], w)
+
}
}
@@ -62,11 +66,14 @@ func TestGetMobileRedirectAllowlistUsesSettings(t *testing.T) {
ctx := context.Background()
db := setupSettingsTestDB(t)
settingsService, err := newSettingsServiceForTestInternal(t, ctx, db)
- if err != nil {
- t.Fatalf("NewSettingsService: %v", err)
- }
- if err := settingsService.UpdateSetting(ctx, "oidcMobileRedirectUris", "arcane-mobile://db-callback"); err != nil {
- t.Fatalf("UpdateSetting: %v", err)
+
+ require.NoError(t, err,
+ "NewSettingsService: %v", err)
+ {
+
+ err := settingsService.UpdateSetting(ctx, "oidcMobileRedirectUris", "arcane-mobile://db-callback")
+ require.NoError(t, err,
+ "UpdateSetting: %v", err)
}
s := &OidcService{
@@ -75,11 +82,17 @@ func TestGetMobileRedirectAllowlistUsesSettings(t *testing.T) {
OidcMobileRedirectUris: "arcane-mobile://config-callback",
},
}
+ {
- if err := s.ValidateMobileRedirectURI(ctx, "arcane-mobile://db-callback"); err != nil {
- t.Fatalf("ValidateMobileRedirectURI db value: %v", err)
+ err := s.ValidateMobileRedirectURI(ctx, "arcane-mobile://db-callback")
+ require.NoError(t, err,
+ "ValidateMobileRedirectURI db value: %v", err)
}
- if err := s.ValidateMobileRedirectURI(ctx, "arcane-mobile://config-callback"); err == nil {
- t.Fatal("ValidateMobileRedirectURI config fallback should fail when DB setting is configured")
+ {
+
+ err := s.ValidateMobileRedirectURI(ctx, "arcane-mobile://config-callback")
+ require.Error(t, err,
+ "ValidateMobileRedirectURI config fallback should fail when DB setting is configured")
}
+
}
diff --git a/backend/internal/services/port_service_test.go b/backend/internal/services/port_service_test.go
index 65c960c32..f31aac8d9 100644
--- a/backend/internal/services/port_service_test.go
+++ b/backend/internal/services/port_service_test.go
@@ -23,7 +23,9 @@ func newPortServiceTestDockerService(t *testing.T, containers []dockercontainer.
switch {
case strings.HasSuffix(r.URL.Path, "/containers/json"):
- require.NoError(t, json.NewEncoder(w).Encode(containers))
+ if !assert.NoError(t, json.NewEncoder(w).Encode(containers)) {
+ return
+ }
default:
http.NotFound(w, r)
}
diff --git a/backend/internal/services/project_service_test.go b/backend/internal/services/project_service_test.go
index b179c6d4a..3d11c3b98 100644
--- a/backend/internal/services/project_service_test.go
+++ b/backend/internal/services/project_service_test.go
@@ -262,10 +262,14 @@ func newProjectImagePullServerWithObserverInternal(t *testing.T, inspectByRef ma
case strings.Contains(r.URL.Path, "/images/") && strings.HasSuffix(r.URL.Path, "/json"):
path := r.URL.Path
imagePathIndex := strings.Index(path, "/images/")
- require.NotEqual(t, -1, imagePathIndex)
+ if !assert.NotEqual(t, -1, imagePathIndex) {
+ return
+ }
encodedRef := strings.TrimSuffix(path[imagePathIndex+len("/images/"):], "/json")
imageRef, err := url.PathUnescape(encodedRef)
- require.NoError(t, err)
+ if !assert.NoError(t, err) {
+ return
+ }
inspect, ok := inspectByRef[imageRef]
if !ok {
@@ -274,7 +278,9 @@ func newProjectImagePullServerWithObserverInternal(t *testing.T, inspectByRef ma
}
w.Header().Set("Content-Type", "application/json")
- require.NoError(t, json.NewEncoder(w).Encode(inspect))
+ if !assert.NoError(t, json.NewEncoder(w).Encode(inspect)) {
+ return
+ }
return
default:
http.NotFound(w, r)
@@ -428,7 +434,7 @@ func TestProjectService_UpdateProjectStatusInternal(t *testing.T) {
if updated.UpdatedAt != nil {
assert.WithinDuration(t, time.Now(), *updated.UpdatedAt, time.Second)
} else {
- t.Error("UpdatedAt should not be nil")
+ assert.Fail(t, "UpdatedAt should not be nil")
}
}
@@ -974,7 +980,7 @@ func TestProjectService_ComposePullSelectedServicesInternal_LeavesRecordsWhenPul
err = svc.composePullSelectedServicesInternal(ctx, projectDef, []string{"app"}, systemUser, nil)
require.Error(t, err)
- assert.ErrorContains(t, err, "failed to pull image")
+ require.ErrorContains(t, err, "failed to pull image")
var selectedRecord models.ImageUpdateRecord
require.NoError(t, db.WithContext(ctx).Where("id = ?", "sha256:selected-old").First(&selectedRecord).Error)
@@ -1043,7 +1049,7 @@ func TestProjectService_UpdateProjectServicesHardFailsWhenPullFailsInternal(t *t
svc := NewProjectService(db, settingsService, nil, imageService, dockerService, nil, nil, nil, config.Load())
err = svc.UpdateProjectServices(ctx, projectRecord.ID, []string{"app"}, systemUser)
require.Error(t, err)
- assert.ErrorContains(t, err, "pull updated service images")
+ require.ErrorContains(t, err, "pull updated service images")
assert.False(t, upCalled, "compose up must not run after a pull failure")
var persistedProject models.Project
@@ -1162,19 +1168,25 @@ func TestProjectService_UpdateProject_RenameFailsWhenVolumeMigrationPreparationF
_, _ = io.WriteString(w, "OK")
case strings.HasSuffix(r.URL.Path, "/version"):
w.Header().Set("Content-Type", "application/json")
- require.NoError(t, json.NewEncoder(w).Encode(map[string]string{
+ if !assert.NoError(t, json.NewEncoder(w).Encode(map[string]string{
"ApiVersion": "1.41",
"MinAPIVersion": "1.24",
"Version": "24.0.0",
- }))
+ })) {
+ return
+ }
case strings.HasSuffix(r.URL.Path, "/containers/json"):
w.Header().Set("Content-Type", "application/json")
- require.NoError(t, json.NewEncoder(w).Encode([]container.Summary{}))
+ if !assert.NoError(t, json.NewEncoder(w).Encode([]container.Summary{})) {
+ return
+ }
case r.Method == http.MethodGet && strings.HasSuffix(r.URL.Path, "/volumes/bar_data"):
w.Header().Set("Content-Type", "application/json")
- require.NoError(t, json.NewEncoder(w).Encode(map[string]any{
+ if !assert.NoError(t, json.NewEncoder(w).Encode(map[string]any{
"Name": "bar_data",
- }))
+ })) {
+ return
+ }
default:
http.NotFound(w, r)
}
@@ -1278,17 +1290,21 @@ func TestProjectService_PrepareProjectRenameVolumeMigrationForUpdate_UsesCompose
http.NotFound(w, r)
case strings.HasSuffix(r.URL.Path, "/volumes/nginx_data"):
w.Header().Set("Content-Type", "application/json")
- require.NoError(t, json.NewEncoder(w).Encode(map[string]any{
+ if !assert.NoError(t, json.NewEncoder(w).Encode(map[string]any{
"Name": "nginx_data",
"Driver": "local",
"Labels": map[string]string{
composeapi.ProjectLabel: "nginx",
composeapi.VolumeLabel: "data",
},
- }))
+ })) {
+ return
+ }
case strings.HasSuffix(r.URL.Path, "/containers/json"):
w.Header().Set("Content-Type", "application/json")
- require.NoError(t, json.NewEncoder(w).Encode([]container.Summary{}))
+ if !assert.NoError(t, json.NewEncoder(w).Encode([]container.Summary{})) {
+ return
+ }
default:
http.NotFound(w, r)
}
@@ -2367,7 +2383,7 @@ func TestProjectService_UpdateProject_RejectsStaleProjectFileRevision(t *testing
})
require.Error(t, err)
- assert.ErrorIs(t, err, common.ErrProjectFileConflict)
+ require.ErrorIs(t, err, common.ErrProjectFileConflict)
assert.NoFileExists(t, filepath.Join(project.Path, "notes.txt"))
}
@@ -2408,7 +2424,7 @@ func TestProjectService_UpdateProject_RejectsStaleDeepProjectFileRevision(t *tes
})
require.Error(t, err)
- assert.ErrorIs(t, err, common.ErrProjectFileConflict)
+ require.ErrorIs(t, err, common.ErrProjectFileConflict)
assert.NoFileExists(t, filepath.Join(project.Path, "notes.txt"))
}
@@ -3223,7 +3239,7 @@ func TestProjectService_ApplyGitSyncProjectFiles_PreservesGitEnvSyntax(t *testin
assert.Equal(t, gitEnv, string(gitBytes))
_, statErr := os.Stat(filepath.Join(projectPath, "project.env"))
- assert.ErrorIs(t, statErr, os.ErrNotExist)
+ require.ErrorIs(t, statErr, os.ErrNotExist)
}
effectiveEnv, err := projects.ParseProjectEnvFile(filepath.Join(projectPath, ".env"), nil)
@@ -4160,7 +4176,7 @@ func TestProjectService_ArchiveProject_RequiresStoppedProject(t *testing.T) {
svc := NewProjectService(db, settingsService, nil, nil, nil, nil, nil, nil, config.Load())
err = svc.ArchiveProject(ctx, "project-running", models.User{BaseModel: models.BaseModel{ID: "user-1"}, Username: "tester"})
require.Error(t, err)
- assert.ErrorIs(t, err, common.ErrProjectMustBeStopped)
+ require.ErrorIs(t, err, common.ErrProjectMustBeStopped)
var stored models.Project
require.NoError(t, db.First(&stored, "id = ?", "project-running").Error)
@@ -5407,7 +5423,7 @@ func TestProjectService_GetProjectDetails_UsesGitOpsCustomComposeFilename(t *tes
assert.Equal(t, "radarr.yaml", details.ComposeFileName)
assert.Equal(t, composeContent, details.ComposeContent)
assert.Equal(t, "TZ=UTC\n", details.EnvContent)
- assert.Equal(t, 1, len(details.Services))
+ assert.Len(t, details.Services, 1)
}
func TestProjectService_UpdateProject_WritesThroughSymlinkedProjectPath(t *testing.T) {
@@ -5989,7 +6005,9 @@ func TestProjectService_RecoverProjectRenameJournals_ClearsPreservedTargetJourna
http.NotFound(w, r)
case r.Method == http.MethodGet && strings.HasSuffix(r.URL.Path, "/volumes/web_data"):
w.Header().Set("Content-Type", "application/json")
- require.NoError(t, json.NewEncoder(w).Encode(map[string]any{"Name": "web_data"}))
+ if !assert.NoError(t, json.NewEncoder(w).Encode(map[string]any{"Name": "web_data"})) {
+ return
+ }
case r.Method == http.MethodDelete && strings.HasSuffix(r.URL.Path, "/volumes/web_data"):
targetRemoved = true
w.WriteHeader(http.StatusNoContent)
@@ -6183,17 +6201,23 @@ func TestProjectService_RecoverProjectRenameJournals_KeepsJournalWhenDirectoryRo
switch {
case r.Method == http.MethodGet && strings.HasSuffix(r.URL.Path, "/volumes/nginx_data"):
w.Header().Set("Content-Type", "application/json")
- require.NoError(t, json.NewEncoder(w).Encode(volume.Volume{Name: "nginx_data"}))
+ if !assert.NoError(t, json.NewEncoder(w).Encode(volume.Volume{Name: "nginx_data"})) {
+ return
+ }
case r.Method == http.MethodGet && strings.HasSuffix(r.URL.Path, "/volumes/web_data"):
if targetRemoved.Load() {
http.NotFound(w, r)
return
}
w.Header().Set("Content-Type", "application/json")
- require.NoError(t, json.NewEncoder(w).Encode(volume.Volume{Name: "web_data"}))
+ if !assert.NoError(t, json.NewEncoder(w).Encode(volume.Volume{Name: "web_data"})) {
+ return
+ }
case r.Method == http.MethodGet && strings.HasSuffix(r.URL.Path, "/containers/json"):
w.Header().Set("Content-Type", "application/json")
- require.NoError(t, json.NewEncoder(w).Encode([]container.Summary{}))
+ if !assert.NoError(t, json.NewEncoder(w).Encode([]container.Summary{})) {
+ return
+ }
case r.Method == http.MethodDelete && strings.HasSuffix(r.URL.Path, "/volumes/web_data"):
targetRemoved.Store(true)
w.WriteHeader(http.StatusNoContent)
@@ -6283,7 +6307,9 @@ func TestProjectService_RecoverProjectRenameJournals_CompletesCommittedVolumeJou
switch {
case r.Method == http.MethodGet && strings.HasSuffix(r.URL.Path, "/volumes/web_data"):
w.Header().Set("Content-Type", "application/json")
- require.NoError(t, json.NewEncoder(w).Encode(volume.Volume{Name: "web_data"}))
+ if !assert.NoError(t, json.NewEncoder(w).Encode(volume.Volume{Name: "web_data"})) {
+ return
+ }
case r.Method == http.MethodDelete && strings.HasSuffix(r.URL.Path, "/volumes/nginx_data"):
oldVolumeRemoved.Store(true)
w.WriteHeader(http.StatusNoContent)
@@ -6357,7 +6383,9 @@ func TestProjectService_RecoverProjectRenameJournals_RollsBackCommittedJournalWh
http.NotFound(w, r)
case r.Method == http.MethodGet && strings.HasSuffix(r.URL.Path, "/volumes/nginx_data"):
w.Header().Set("Content-Type", "application/json")
- require.NoError(t, json.NewEncoder(w).Encode(volume.Volume{Name: "nginx_data"}))
+ if !assert.NoError(t, json.NewEncoder(w).Encode(volume.Volume{Name: "nginx_data"})) {
+ return
+ }
case r.Method == http.MethodDelete && strings.HasSuffix(r.URL.Path, "/volumes/nginx_data"):
oldVolumeRemoved.Store(true)
w.WriteHeader(http.StatusNoContent)
@@ -6440,20 +6468,28 @@ func TestProjectService_RecoverProjectRenameJournals_ClearsJournalAfterDBRestore
http.NotFound(w, r)
case r.Method == http.MethodGet && strings.HasSuffix(r.URL.Path, "/volumes/nginx_data"):
w.Header().Set("Content-Type", "application/json")
- require.NoError(t, json.NewEncoder(w).Encode(volume.Volume{Name: "nginx_data"}))
+ if !assert.NoError(t, json.NewEncoder(w).Encode(volume.Volume{Name: "nginx_data"})) {
+ return
+ }
case r.Method == http.MethodGet && strings.HasSuffix(r.URL.Path, "/volumes/web_cache"):
if !targetExists.Load() {
http.NotFound(w, r)
return
}
w.Header().Set("Content-Type", "application/json")
- require.NoError(t, json.NewEncoder(w).Encode(volume.Volume{Name: "web_cache"}))
+ if !assert.NoError(t, json.NewEncoder(w).Encode(volume.Volume{Name: "web_cache"})) {
+ return
+ }
case r.Method == http.MethodGet && strings.HasSuffix(r.URL.Path, "/volumes/nginx_cache"):
w.Header().Set("Content-Type", "application/json")
- require.NoError(t, json.NewEncoder(w).Encode(volume.Volume{Name: "nginx_cache"}))
+ if !assert.NoError(t, json.NewEncoder(w).Encode(volume.Volume{Name: "nginx_cache"})) {
+ return
+ }
case r.Method == http.MethodGet && strings.HasSuffix(r.URL.Path, "/containers/json"):
w.Header().Set("Content-Type", "application/json")
- require.NoError(t, json.NewEncoder(w).Encode([]container.Summary{}))
+ if !assert.NoError(t, json.NewEncoder(w).Encode([]container.Summary{})) {
+ return
+ }
case r.Method == http.MethodDelete && strings.HasSuffix(r.URL.Path, "/volumes/web_cache"):
targetRemoveAttempts.Add(1)
if allowTargetRemove.Load() {
@@ -6678,10 +6714,14 @@ func TestProjectService_RecoverProjectRenameJournals_ClearsCommittedJournalAndCl
http.NotFound(w, r)
case r.Method == http.MethodGet && strings.HasSuffix(r.URL.Path, "/volumes/web_cache"):
w.Header().Set("Content-Type", "application/json")
- require.NoError(t, json.NewEncoder(w).Encode(volume.Volume{Name: "web_cache"}))
+ if !assert.NoError(t, json.NewEncoder(w).Encode(volume.Volume{Name: "web_cache"})) {
+ return
+ }
case r.Method == http.MethodGet && strings.HasSuffix(r.URL.Path, "/volumes/nginx_cache"):
w.Header().Set("Content-Type", "application/json")
- require.NoError(t, json.NewEncoder(w).Encode(volume.Volume{Name: "nginx_cache"}))
+ if !assert.NoError(t, json.NewEncoder(w).Encode(volume.Volume{Name: "nginx_cache"})) {
+ return
+ }
case r.Method == http.MethodDelete && strings.HasSuffix(r.URL.Path, "/volumes/nginx_cache"):
cacheSourceRemoved.Store(true)
w.WriteHeader(http.StatusNoContent)
@@ -6762,7 +6802,9 @@ func TestProjectService_RecoverProjectRenameJournals_MarksSourceCleanupPendingWh
switch {
case r.Method == http.MethodGet && strings.HasSuffix(r.URL.Path, "/volumes/web_data"):
w.Header().Set("Content-Type", "application/json")
- require.NoError(t, json.NewEncoder(w).Encode(volume.Volume{Name: "web_data"}))
+ if !assert.NoError(t, json.NewEncoder(w).Encode(volume.Volume{Name: "web_data"})) {
+ return
+ }
case r.Method == http.MethodDelete && strings.HasSuffix(r.URL.Path, "/volumes/nginx_data"):
sourceRemoveAttempts.Add(1)
http.Error(w, "volume busy", http.StatusInternalServerError)
@@ -6845,7 +6887,9 @@ func TestProjectService_RecoverProjectRenameJournals_ClearsSourceCleanupPendingJ
switch {
case r.Method == http.MethodGet && strings.HasSuffix(r.URL.Path, "/volumes/web_data"):
w.Header().Set("Content-Type", "application/json")
- require.NoError(t, json.NewEncoder(w).Encode(volume.Volume{Name: "web_data"}))
+ if !assert.NoError(t, json.NewEncoder(w).Encode(volume.Volume{Name: "web_data"})) {
+ return
+ }
case r.Method == http.MethodDelete && strings.HasSuffix(r.URL.Path, "/volumes/nginx_data"):
sourceRemoved.Store(true)
w.WriteHeader(http.StatusNoContent)
@@ -6920,16 +6964,24 @@ func TestProjectService_RecoverProjectRenameJournals_RollsBackSourceCleanupPendi
http.NotFound(w, r)
case r.Method == http.MethodGet && strings.HasSuffix(r.URL.Path, "/volumes/nginx_data"):
w.Header().Set("Content-Type", "application/json")
- require.NoError(t, json.NewEncoder(w).Encode(volume.Volume{Name: "nginx_data"}))
+ if !assert.NoError(t, json.NewEncoder(w).Encode(volume.Volume{Name: "nginx_data"})) {
+ return
+ }
case r.Method == http.MethodGet && strings.HasSuffix(r.URL.Path, "/volumes/web_cache"):
w.Header().Set("Content-Type", "application/json")
- require.NoError(t, json.NewEncoder(w).Encode(volume.Volume{Name: "web_cache"}))
+ if !assert.NoError(t, json.NewEncoder(w).Encode(volume.Volume{Name: "web_cache"})) {
+ return
+ }
case r.Method == http.MethodGet && strings.HasSuffix(r.URL.Path, "/volumes/nginx_cache"):
w.Header().Set("Content-Type", "application/json")
- require.NoError(t, json.NewEncoder(w).Encode(volume.Volume{Name: "nginx_cache"}))
+ if !assert.NoError(t, json.NewEncoder(w).Encode(volume.Volume{Name: "nginx_cache"})) {
+ return
+ }
case r.Method == http.MethodGet && strings.HasSuffix(r.URL.Path, "/containers/json"):
w.Header().Set("Content-Type", "application/json")
- require.NoError(t, json.NewEncoder(w).Encode([]container.Summary{}))
+ if !assert.NoError(t, json.NewEncoder(w).Encode([]container.Summary{})) {
+ return
+ }
case r.Method == http.MethodDelete && strings.HasSuffix(r.URL.Path, "/volumes/nginx_data"):
dataSourceRemoved.Store(true)
w.WriteHeader(http.StatusNoContent)
@@ -7024,7 +7076,9 @@ func TestProjectService_RecoverProjectRenameJournals_KeepsSourceCleanupPendingJo
switch {
case r.Method == http.MethodGet && strings.HasSuffix(r.URL.Path, "/volumes/web_data"):
w.Header().Set("Content-Type", "application/json")
- require.NoError(t, json.NewEncoder(w).Encode(volume.Volume{Name: "web_data"}))
+ if !assert.NoError(t, json.NewEncoder(w).Encode(volume.Volume{Name: "web_data"})) {
+ return
+ }
case r.Method == http.MethodDelete && strings.HasSuffix(r.URL.Path, "/volumes/nginx_data"):
sourceRemoveAttempts.Add(1)
http.Error(w, "volume busy", http.StatusInternalServerError)
@@ -7152,12 +7206,16 @@ func TestProjectService_RecoverProjectRenameJournals_ClearsMissingPathJournalWhe
switch {
case r.Method == http.MethodGet && strings.HasSuffix(r.URL.Path, "/volumes/web_data"):
w.Header().Set("Content-Type", "application/json")
- require.NoError(t, json.NewEncoder(w).Encode(volume.Volume{Name: "web_data"}))
+ if !assert.NoError(t, json.NewEncoder(w).Encode(volume.Volume{Name: "web_data"})) {
+ return
+ }
case r.Method == http.MethodGet && strings.HasSuffix(r.URL.Path, "/volumes/nginx_data"):
http.NotFound(w, r)
case r.Method == http.MethodGet && strings.HasSuffix(r.URL.Path, "/containers/json"):
w.Header().Set("Content-Type", "application/json")
- require.NoError(t, json.NewEncoder(w).Encode([]container.Summary{}))
+ if !assert.NoError(t, json.NewEncoder(w).Encode([]container.Summary{})) {
+ return
+ }
case r.Method == http.MethodDelete && strings.HasSuffix(r.URL.Path, "/volumes/web_data"):
targetRemoved.Store(true)
w.WriteHeader(http.StatusNoContent)
@@ -7305,7 +7363,9 @@ func TestProjectService_RecoverProjectRenameJournals_ClearsJournalWhenRollbackTa
switch {
case r.Method == http.MethodGet && strings.HasSuffix(r.URL.Path, "/volumes/nginx_data"):
w.Header().Set("Content-Type", "application/json")
- require.NoError(t, json.NewEncoder(w).Encode(volume.Volume{Name: "nginx_data"}))
+ if !assert.NoError(t, json.NewEncoder(w).Encode(volume.Volume{Name: "nginx_data"})) {
+ return
+ }
case r.Method == http.MethodGet && strings.HasSuffix(r.URL.Path, "/volumes/web_data"):
http.Error(w, "temporary docker error", http.StatusInternalServerError)
case r.Method == http.MethodDelete && strings.HasSuffix(r.URL.Path, "/volumes/web_data"):
@@ -7382,12 +7442,16 @@ func TestProjectService_RecoverProjectRenameJournals_ClearsJournalWhenTargetPres
switch {
case r.Method == http.MethodGet && strings.HasSuffix(r.URL.Path, "/volumes/web_data"):
w.Header().Set("Content-Type", "application/json")
- require.NoError(t, json.NewEncoder(w).Encode(volume.Volume{Name: "web_data"}))
+ if !assert.NoError(t, json.NewEncoder(w).Encode(volume.Volume{Name: "web_data"})) {
+ return
+ }
case r.Method == http.MethodGet && strings.HasSuffix(r.URL.Path, "/volumes/nginx_data"):
http.NotFound(w, r)
case r.Method == http.MethodGet && strings.HasSuffix(r.URL.Path, "/containers/json"):
w.Header().Set("Content-Type", "application/json")
- require.NoError(t, json.NewEncoder(w).Encode([]container.Summary{}))
+ if !assert.NoError(t, json.NewEncoder(w).Encode([]container.Summary{})) {
+ return
+ }
case r.Method == http.MethodDelete && strings.HasSuffix(r.URL.Path, "/volumes/web_data"):
targetRemoved.Store(true)
w.WriteHeader(http.StatusNoContent)
diff --git a/backend/internal/services/settings_service_test.go b/backend/internal/services/settings_service_test.go
index 2f17fc181..094b92265 100644
--- a/backend/internal/services/settings_service_test.go
+++ b/backend/internal/services/settings_service_test.go
@@ -105,7 +105,7 @@ func TestSettingsService_EnsureDefaultSettings_Idempotent(t *testing.T) {
case "followProjectSymlinks":
require.Equal(t, "false", sv.Value)
case "autoUpdateExcludedContainers":
- require.Equal(t, "", sv.Value)
+ require.Empty(t, sv.Value)
case "imageEventWatcherEnabled":
require.Equal(t, "false", sv.Value)
case "vulnerabilityScanEnabled":
@@ -117,9 +117,9 @@ func TestSettingsService_EnsureDefaultSettings_Idempotent(t *testing.T) {
case "lifecycleDefaultRunnerImage":
require.Equal(t, "alpine:latest", sv.Value)
case "trivyNetwork":
- require.Equal(t, "", sv.Value)
+ require.Empty(t, sv.Value)
case "trivySecurityOpts":
- require.Equal(t, "", sv.Value)
+ require.Empty(t, sv.Value)
case "trivyPrivileged":
require.Equal(t, "false", sv.Value)
case "trivyPreserveCacheOnVolumePrune":
@@ -642,7 +642,7 @@ func TestSettingsServiceActorPublishesSnapshotBeforeAsynchronousNotificationInte
case err := <-updateResult:
require.NoError(t, err)
case <-time.After(time.Second):
- t.Fatal("settings update waited for notification callback")
+ require.FailNow(t, "settings update waited for notification callback")
}
secondUpdate := make(chan error, 1)
@@ -654,7 +654,7 @@ func TestSettingsServiceActorPublishesSnapshotBeforeAsynchronousNotificationInte
case err := <-secondUpdate:
require.NoError(t, err)
case <-time.After(time.Second):
- t.Fatal("settings subscriber blocked the next settings writer")
+ require.FailNow(t, "settings subscriber blocked the next settings writer")
}
close(releaseCallback)
}
@@ -725,15 +725,15 @@ func BenchmarkSettingsService_GetSettings(b *testing.B) {
ctx := context.Background()
db, err := gorm.Open(sqlite.Open(":memory:"), &gorm.Config{})
if err != nil {
- b.Fatal(err)
+ require.FailNowf(b, "benchmark database setup failed", "%v", err)
}
if err := db.AutoMigrate(&models.SettingVariable{}); err != nil {
- b.Fatal(err)
+ require.FailNowf(b, "benchmark database migration failed", "%v", err)
}
settingsDB := &database.DB{DB: db}
svc, err := newSettingsServiceForTestInternal(b, ctx, settingsDB)
if err != nil {
- b.Fatal(err)
+ require.FailNowf(b, "benchmark service setup failed", "%v", err)
}
b.ReportAllocs()
@@ -742,10 +742,10 @@ func BenchmarkSettingsService_GetSettings(b *testing.B) {
for b.Loop() {
settingsCfg, err := svc.GetSettings(ctx)
if err != nil {
- b.Fatal(err)
+ require.FailNowf(b, "benchmark GetSettings failed", "%v", err)
}
if settingsCfg == nil {
- b.Fatal("settings should not be nil")
+ require.FailNow(b, "GetSettings returned nil settings")
}
}
}
diff --git a/backend/internal/services/swarm_service_test.go b/backend/internal/services/swarm_service_test.go
index 8efc7b53c..35cff7558 100644
--- a/backend/internal/services/swarm_service_test.go
+++ b/backend/internal/services/swarm_service_test.go
@@ -14,6 +14,7 @@ import (
swarmtypes "github.com/getarcaneapp/arcane/types/v2/swarm"
"github.com/moby/moby/api/types/swarm"
"github.com/moby/moby/api/types/system"
+ "github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
@@ -44,10 +45,18 @@ func TestSwarmService_FetchSwarmNodeIdentityViaEdgeInternal_UsesEnvironmentAcces
accessToken := "token-123"
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
- require.Equal(t, http.MethodGet, r.Method)
- require.Equal(t, "/api/swarm/node-identity", r.URL.Path)
- require.Equal(t, accessToken, r.Header.Get("X-API-Key"))
- require.Equal(t, accessToken, r.Header.Get("X-Arcane-Agent-Token"))
+ if !assert.Equal(t, http.MethodGet, r.Method) {
+ return
+ }
+ if !assert.Equal(t, "/api/swarm/node-identity", r.URL.Path) {
+ return
+ }
+ if !assert.Equal(t, accessToken, r.Header.Get("X-API-Key")) {
+ return
+ }
+ if !assert.Equal(t, accessToken, r.Header.Get("X-Arcane-Agent-Token")) {
+ return
+ }
w.Header().Set("Content-Type", "application/json")
_, _ = w.Write([]byte(`{"success":true,"data":{"swarmNodeId":"node-1","hostname":"worker-1","role":"worker","engineVersion":"29.3.1","swarmActive":true}}`))
@@ -230,14 +239,16 @@ func TestSwarmService_ScaleService_HandlesServiceModesInternal(t *testing.T) {
switch {
case r.Method == http.MethodGet && r.URL.Path == "/v1.41/info":
- require.NoError(t, json.NewEncoder(w).Encode(system.Info{
+ if !assert.NoError(t, json.NewEncoder(w).Encode(system.Info{
Swarm: swarm.Info{
LocalNodeState: swarm.LocalNodeStateActive,
ControlAvailable: true,
},
- }))
+ })) {
+ return
+ }
case r.Method == http.MethodGet && r.URL.Path == "/v1.41/services/service-1":
- require.NoError(t, json.NewEncoder(w).Encode(swarm.Service{
+ if !assert.NoError(t, json.NewEncoder(w).Encode(swarm.Service{
ID: "service-1",
Meta: swarm.Meta{
Version: swarm.Version{Index: 7},
@@ -246,12 +257,20 @@ func TestSwarmService_ScaleService_HandlesServiceModesInternal(t *testing.T) {
Annotations: swarm.Annotations{Name: "service-1"},
Mode: tt.mode,
},
- }))
+ })) {
+ return
+ }
case r.Method == http.MethodPost && r.URL.Path == "/v1.41/services/service-1/update":
updateCalls++
- require.Equal(t, "7", r.URL.Query().Get("version"))
- require.NoError(t, json.NewDecoder(r.Body).Decode(&updatedSpec))
- require.NoError(t, json.NewEncoder(w).Encode(map[string]any{"Warnings": []string{"updated"}}))
+ if !assert.Equal(t, "7", r.URL.Query().Get("version")) {
+ return
+ }
+ if !assert.NoError(t, json.NewDecoder(r.Body).Decode(&updatedSpec)) {
+ return
+ }
+ if !assert.NoError(t, json.NewEncoder(w).Encode(map[string]any{"Warnings": []string{"updated"}})) {
+ return
+ }
default:
http.NotFound(w, r)
}
diff --git a/backend/internal/services/system_upgrade_update_all_test.go b/backend/internal/services/system_upgrade_update_all_test.go
index fc3c19f5b..5be06144b 100644
--- a/backend/internal/services/system_upgrade_update_all_test.go
+++ b/backend/internal/services/system_upgrade_update_all_test.go
@@ -77,12 +77,13 @@ func TestUpdateAllResolveResumeAction(t *testing.T) {
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
got := resolveResumeActionInternal(tt.job, tt.currentVersion, tt.currentDigest, now)
- if got.markStale != tt.wantStale {
- t.Fatalf("markStale = %v, want %v", got.markStale, tt.wantStale)
- }
- if !tt.wantStale && got.managerSucceeded != tt.wantManagerOK {
- t.Fatalf("managerSucceeded = %v, want %v", got.managerSucceeded, tt.wantManagerOK)
- }
+
+ require.Equal(t, tt.wantStale, got.markStale,
+ "markStale = %v, want %v", got.markStale, tt.wantStale)
+
+ require.False(t, !tt.wantStale && got.managerSucceeded != tt.wantManagerOK,
+ "managerSucceeded = %v, want %v", got.managerSucceeded, tt.wantManagerOK)
+
})
}
}
@@ -103,31 +104,35 @@ func TestUpsertPendingResult(t *testing.T) {
{EnvironmentID: "abc", EnvironmentName: "palladium", Status: models.EnvironmentUpdateResultStatusPending},
},
}
+ {
- // A seeded environment resolves to its existing row without appending.
- if idx := upsertPendingResultInternal(job, "abc", "palladium"); idx != 1 {
- t.Fatalf("existing env index = %d, want 1", idx)
- }
- if len(job.Results) != 2 {
- t.Fatalf("results grew to %d, want 2", len(job.Results))
+ // A seeded environment resolves to its existing row without appending.
+ idx := upsertPendingResultInternal(job, "abc", "palladium")
+ require.Equal(t, 1, idx,
+ "existing env index = %d, want 1", idx)
}
+ require.Len(t, job.Results, 2,
+ "results grew to %d, want 2", len(job.Results))
+
// A missing environment (seeding raced or a new env was registered) appends a
// fresh pending row and returns the new index.
idx := upsertPendingResultInternal(job, "xyz", "oracle-cloud")
- if idx != 2 {
- t.Fatalf("new env index = %d, want 2", idx)
- }
- if len(job.Results) != 3 {
- t.Fatalf("results = %d, want 3", len(job.Results))
- }
+
+ require.Equal(t, 2, idx,
+ "new env index = %d, want 2", idx)
+
+ require.Len(t, job.Results, 3,
+ "results = %d, want 3", len(job.Results))
+
got := job.Results[2]
- if got.EnvironmentID != "xyz" || got.EnvironmentName != "oracle-cloud" {
- t.Fatalf("appended row = %+v, want id=xyz name=oracle-cloud", got)
- }
- if got.Status != models.EnvironmentUpdateResultStatusPending {
- t.Fatalf("appended row status = %q, want pending", got.Status)
- }
+
+ require.False(t, got.EnvironmentID != "xyz" || got.EnvironmentName != "oracle-cloud",
+ "appended row = %+v, want id=xyz name=oracle-cloud", got)
+
+ require.Equal(t, models.EnvironmentUpdateResultStatusPending, got.Status,
+ "appended row status = %q, want pending", got.Status)
+
}
func TestUpdateAllFailedJobMarksUpdatingResultsFailed(t *testing.T) {
diff --git a/backend/internal/services/updater_service_test.go b/backend/internal/services/updater_service_test.go
index 67d4f50eb..0501f2c25 100644
--- a/backend/internal/services/updater_service_test.go
+++ b/backend/internal/services/updater_service_test.go
@@ -123,7 +123,9 @@ func newUpdaterApplyPendingDockerServerInternal(
case strings.Contains(r.URL.Path, "/images/") && strings.HasSuffix(r.URL.Path, "/json"):
encodedRef := strings.TrimSuffix(r.URL.Path[strings.LastIndex(r.URL.Path, "/images/")+len("/images/"):], "/json")
imageRef, err := url.PathUnescape(encodedRef)
- require.NoError(t, err)
+ if !assert.NoError(t, err) {
+ return
+ }
inspect, ok := imageInspectByRef[imageRef]
if !ok {
http.NotFound(w, r)
@@ -135,7 +137,9 @@ func newUpdaterApplyPendingDockerServerInternal(
response := containers
if filters := strings.TrimSpace(r.URL.Query().Get("filters")); filters != "" {
var raw map[string]map[string]bool
- require.NoError(t, json.Unmarshal([]byte(filters), &raw))
+ if !assert.NoError(t, json.Unmarshal([]byte(filters), &raw)) {
+ return
+ }
projectName := ""
serviceName := ""
for value := range raw["label"] {
diff --git a/backend/internal/services/variable_service_test.go b/backend/internal/services/variable_service_test.go
index 7500345bb..c2dd1986a 100644
--- a/backend/internal/services/variable_service_test.go
+++ b/backend/internal/services/variable_service_test.go
@@ -20,6 +20,7 @@ import (
"github.com/getarcaneapp/arcane/backend/v2/pkg/remenv"
envtypes "github.com/getarcaneapp/arcane/types/v2/env"
"github.com/libtnb/sqlite"
+ "github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
"go.getarcane.app/sys/crypto"
"gorm.io/gorm"
@@ -230,7 +231,9 @@ func TestSyncEnvironment_DirectMaterializesSecretsThroughAgentRoute(t *testing.T
requests := make([]capturedVariableSyncRequestInternal, 0, 2)
server := httptest.NewServer(http.HandlerFunc(func(writer http.ResponseWriter, request *http.Request) {
body, err := io.ReadAll(request.Body)
- require.NoError(t, err)
+ if !assert.NoError(t, err) {
+ return
+ }
requestMu.Lock()
requests = append(requests, capturedVariableSyncRequestInternal{
Method: request.Method,
diff --git a/backend/internal/services/version_service_test.go b/backend/internal/services/version_service_test.go
index 5f48902d8..703eb2a32 100644
--- a/backend/internal/services/version_service_test.go
+++ b/backend/internal/services/version_service_test.go
@@ -36,7 +36,7 @@ func TestVersionService_GetAppVersionInfoDoesNotUseStoredDigestUpdateForSemverBu
switch {
case strings.HasSuffix(r.URL.Path, "/containers/json"):
w.Header().Set("Content-Type", "application/json")
- require.NoError(t, json.NewEncoder(w).Encode([]container.Summary{
+ if !assert.NoError(t, json.NewEncoder(w).Encode([]container.Summary{
{
ID: containerID,
State: container.StateRunning,
@@ -44,10 +44,12 @@ func TestVersionService_GetAppVersionInfoDoesNotUseStoredDigestUpdateForSemverBu
labels.LabelArcane: "true",
},
},
- }))
+ })) {
+ return
+ }
case strings.Contains(r.URL.Path, "/containers/") && strings.HasSuffix(r.URL.Path, "/json"):
w.Header().Set("Content-Type", "application/json")
- require.NoError(t, json.NewEncoder(w).Encode(container.InspectResponse{
+ if !assert.NoError(t, json.NewEncoder(w).Encode(container.InspectResponse{
ID: containerID,
Image: imageID,
Config: &container.Config{
@@ -56,18 +58,24 @@ func TestVersionService_GetAppVersionInfoDoesNotUseStoredDigestUpdateForSemverBu
labels.LabelArcane: "true",
},
},
- }))
+ })) {
+ return
+ }
case strings.Contains(r.URL.Path, "/images/") && strings.HasSuffix(r.URL.Path, "/json"):
encodedRef := strings.TrimSuffix(r.URL.Path[strings.LastIndex(r.URL.Path, "/images/")+len("/images/"):], "/json")
_, err := url.PathUnescape(encodedRef)
- require.NoError(t, err)
+ if !assert.NoError(t, err) {
+ return
+ }
w.Header().Set("Content-Type", "application/json")
- require.NoError(t, json.NewEncoder(w).Encode(dockertypesimage.InspectResponse{
+ if !assert.NoError(t, json.NewEncoder(w).Encode(dockertypesimage.InspectResponse{
ID: imageID,
RepoTags: []string{imageRef},
RepoDigests: []string{"ghcr.io/getarcaneapp/arcane@" + currentDigest},
- }))
+ })) {
+ return
+ }
default:
http.NotFound(w, r)
}
diff --git a/backend/internal/services/volume_service_test.go b/backend/internal/services/volume_service_test.go
index c77311f6d..a63caac58 100644
--- a/backend/internal/services/volume_service_test.go
+++ b/backend/internal/services/volume_service_test.go
@@ -474,8 +474,8 @@ func TestTakeHelperIDInternal(t *testing.T) {
require.NotContains(t, s.helperByVolume, "vol-a")
// Absent (idempotent): returns "" without panicking.
- require.Equal(t, "", s.takeHelperIDInternal("vol-a"))
- require.Equal(t, "", s.takeHelperIDInternal("never-existed"))
+ require.Empty(t, s.takeHelperIDInternal("vol-a"))
+ require.Empty(t, s.takeHelperIDInternal("never-existed"))
}
func TestTouchHelperInternal(t *testing.T) {
diff --git a/backend/internal/services/vulnerability_service_test.go b/backend/internal/services/vulnerability_service_test.go
index bdef3dbb0..11f692a64 100644
--- a/backend/internal/services/vulnerability_service_test.go
+++ b/backend/internal/services/vulnerability_service_test.go
@@ -595,7 +595,7 @@ func TestIsSynologyDockerHostInternal(t *testing.T) {
}
func TestBuildTrivyCPUSetInternal(t *testing.T) {
- require.Equal(t, "", buildTrivyCPUSetInternal(0, 4))
+ require.Empty(t, buildTrivyCPUSetInternal(0, 4))
require.Equal(t, "0", buildTrivyCPUSetInternal(1_000_000_000, 4))
require.Equal(t, "0-1", buildTrivyCPUSetInternal(2_500_000_000, 4))
require.Equal(t, "0-1", buildTrivyCPUSetInternal(3_000_000_000, 2))
@@ -617,7 +617,7 @@ func TestGetTrivyScanSlotChannelInternal_PrefillsSlots(t *testing.T) {
slotCh := svc.getTrivyScanSlotChannelInternal(3)
require.NotNil(t, slotCh)
require.Equal(t, 3, cap(slotCh))
- require.Equal(t, 3, len(slotCh))
+ require.Len(t, slotCh, 3)
seen := map[int]bool{}
for range 3 {
@@ -628,7 +628,7 @@ func TestGetTrivyScanSlotChannelInternal_PrefillsSlots(t *testing.T) {
require.True(t, seen[0])
require.True(t, seen[1])
require.True(t, seen[2])
- require.Equal(t, 0, len(slotCh))
+ require.Empty(t, slotCh)
}
func TestTrivyMountSummariesInternal(t *testing.T) {
@@ -664,7 +664,7 @@ func TestTrivyMountSummariesInternal(t *testing.T) {
}
func TestTruncateTrivyLogOutputInternal(t *testing.T) {
- require.Equal(t, "", truncateTrivyLogOutputInternal("", 32))
+ require.Empty(t, truncateTrivyLogOutputInternal("", 32))
require.Equal(t, "keep me", truncateTrivyLogOutputInternal(" keep me ", 32))
longOutput := strings.Repeat("x", 80)
diff --git a/backend/internal/services/webhook_service_test.go b/backend/internal/services/webhook_service_test.go
index 4d5021b68..2fe522c49 100644
--- a/backend/internal/services/webhook_service_test.go
+++ b/backend/internal/services/webhook_service_test.go
@@ -213,7 +213,7 @@ func TestCreateWebhook_EmptyTargetIDAcceptedForUpdaterType(t *testing.T) {
wh, _, err := svc.CreateWebhook(ctx, "updater-hook", models.WebhookTargetTypeUpdater, models.WebhookActionTypeRun, "", "env-1", models.User{})
require.NoError(t, err)
- assert.Equal(t, "", wh.TargetID)
+ assert.Empty(t, wh.TargetID)
}
func TestCreateWebhook_ContainerTypeAccepted(t *testing.T) {
@@ -427,7 +427,7 @@ func TestDeleteWebhook_NotFoundForWrongEnvironment(t *testing.T) {
require.NoError(t, err)
err = svc.DeleteWebhook(ctx, created.ID, "env-2", models.User{})
- assert.ErrorIs(t, err, ErrWebhookNotFound)
+ require.ErrorIs(t, err, ErrWebhookNotFound)
// Webhook must still exist in the correct environment
_, err = svc.GetWebhookByID(ctx, created.ID, "env-1")
diff --git a/backend/pkg/authz/permission_matcher_test.go b/backend/pkg/authz/permission_matcher_test.go
index 89b8dddc9..1c3be20aa 100644
--- a/backend/pkg/authz/permission_matcher_test.go
+++ b/backend/pkg/authz/permission_matcher_test.go
@@ -1,18 +1,28 @@
package authz
-import "testing"
+import (
+ "testing"
+
+ "github.com/stretchr/testify/require"
+)
func TestPermissionMatcherLookupExactAndWildcard(t *testing.T) {
m := NewPermissionMatcher()
m.Add("POST", "/containers/{containerId}/start", "containers:start")
m.Add("GET", "/containers/{containerId}", "containers:read")
+ {
- if perm, ok := m.Lookup("POST", "/containers/abc123/start").Get(); !ok || perm != "containers:start" {
- t.Fatalf("expected containers:start, got %q ok=%v", perm, ok)
+ perm, ok := m.Lookup("POST", "/containers/abc123/start").Get()
+ require.False(t, !ok || perm != "containers:start",
+ "expected containers:start, got %q ok=%v", perm, ok)
}
- if perm, ok := m.Lookup("GET", "/containers/abc123").Get(); !ok || perm != "containers:read" {
- t.Fatalf("expected containers:read, got %q ok=%v", perm, ok)
+ {
+
+ perm, ok := m.Lookup("GET", "/containers/abc123").Get()
+ require.False(t, !ok || perm != "containers:read",
+ "expected containers:read, got %q ok=%v", perm, ok)
}
+
}
func TestPermissionMatcherStaticBeatsWildcard(t *testing.T) {
@@ -21,37 +31,55 @@ func TestPermissionMatcherStaticBeatsWildcard(t *testing.T) {
// not registration order, decides the winner.
m.Add("GET", "/containers/{containerId}", "containers:read")
m.Add("GET", "/containers/counts", "containers:list")
+ {
- if perm, ok := m.Lookup("GET", "/containers/counts").Get(); !ok || perm != "containers:list" {
- t.Fatalf("expected static route to win with containers:list, got %q ok=%v", perm, ok)
+ perm, ok := m.Lookup("GET", "/containers/counts").Get()
+ require.False(t, !ok || perm != "containers:list",
+ "expected static route to win with containers:list, got %q ok=%v", perm, ok)
}
- if perm, ok := m.Lookup("GET", "/containers/xyz").Get(); !ok || perm != "containers:read" {
- t.Fatalf("expected wildcard route containers:read, got %q ok=%v", perm, ok)
+ {
+
+ perm, ok := m.Lookup("GET", "/containers/xyz").Get()
+ require.False(t, !ok || perm != "containers:read",
+ "expected wildcard route containers:read, got %q ok=%v", perm, ok)
}
+
}
func TestPermissionMatcherMethodAndLengthMismatch(t *testing.T) {
m := NewPermissionMatcher()
m.Add("POST", "/containers/{containerId}/start", "containers:start")
+ {
- if _, ok := m.Lookup("DELETE", "/containers/abc/start").Get(); ok {
- t.Fatal("expected no match for wrong method")
+ _, ok := m.Lookup("DELETE", "/containers/abc/start").Get()
+ require.False(t, ok,
+ "expected no match for wrong method")
}
- if _, ok := m.Lookup("POST", "/containers/abc/start/extra").Get(); ok {
- t.Fatal("expected no match for longer path")
+ {
+
+ _, ok := m.Lookup("POST", "/containers/abc/start/extra").Get()
+ require.False(t, ok,
+ "expected no match for longer path")
}
- if _, ok := m.Lookup("POST", "/containers/abc").Get(); ok {
- t.Fatal("expected no match for shorter path")
+ {
+
+ _, ok := m.Lookup("POST", "/containers/abc").Get()
+ require.False(t, ok,
+ "expected no match for shorter path")
}
+
}
func TestPermissionMatcherNormalizesEchoParamsAndStripsQuery(t *testing.T) {
m := NewPermissionMatcher()
m.Add("GET", "/volumes/:volumeName/browse", "volumes:browse")
+ {
- if perm, ok := m.Lookup("GET", "/volumes/data/browse?path=/etc").Get(); !ok || perm != "volumes:browse" {
- t.Fatalf("expected volumes:browse with echo param + query string, got %q ok=%v", perm, ok)
+ perm, ok := m.Lookup("GET", "/volumes/data/browse?path=/etc").Get()
+ require.False(t, !ok || perm != "volumes:browse",
+ "expected volumes:browse with echo param + query string, got %q ok=%v", perm, ok)
}
+
}
func TestPermissionMatcherPublicRoute(t *testing.T) {
@@ -59,19 +87,23 @@ func TestPermissionMatcherPublicRoute(t *testing.T) {
m.AddPublic("GET", "/settings/public")
perm, ok := m.Lookup("GET", "/settings/public").Get()
- if !ok {
- t.Fatal("expected public route to be found")
- }
- if perm != "" {
- t.Fatalf("expected empty permission for public route, got %q", perm)
- }
+
+ require.True(t, ok,
+ "expected public route to be found")
+
+ require.Empty(t, perm,
+ "expected empty permission for public route, got %q", perm)
+
}
func TestPermissionMatcherUnmappedReturnsNotFound(t *testing.T) {
m := NewPermissionMatcher()
m.Add("GET", "/containers", "containers:list")
+ {
- if _, ok := m.Lookup("GET", "/images").Get(); ok {
- t.Fatal("expected unmapped path to return not found")
+ _, ok := m.Lookup("GET", "/images").Get()
+ require.False(t, ok,
+ "expected unmapped path to return not found")
}
+
}
diff --git a/backend/pkg/authz/permission_set_test.go b/backend/pkg/authz/permission_set_test.go
index cda86f047..19adff6b6 100644
--- a/backend/pkg/authz/permission_set_test.go
+++ b/backend/pkg/authz/permission_set_test.go
@@ -1,38 +1,40 @@
package authz
import (
- "slices"
"testing"
+
+ "github.com/stretchr/testify/assert"
+ "github.com/stretchr/testify/require"
)
func TestPermissionSetAllowsGlobal(t *testing.T) {
ps := NewPermissionSet()
ps.AddGlobal(PermContainersList)
- if !ps.Allows(PermContainersList, "env-1") {
- t.Fatal("global perm should apply to any env")
- }
- if !ps.Allows(PermContainersList, "") {
- t.Fatal("global perm should apply org-level too")
- }
- if ps.Allows(PermContainersStart, "env-1") {
- t.Fatal("unrelated perm should be denied")
- }
+ require.True(t, ps.Allows(PermContainersList, "env-1"),
+ "global perm should apply to any env")
+
+ require.True(t, ps.Allows(PermContainersList, ""),
+ "global perm should apply org-level too")
+
+ require.False(t, ps.Allows(PermContainersStart, "env-1"),
+ "unrelated perm should be denied")
+
}
func TestPermissionSetEnvScopedDoesNotLeak(t *testing.T) {
ps := NewPermissionSet()
ps.AddEnv("env-1", PermContainersStart)
- if !ps.Allows(PermContainersStart, "env-1") {
- t.Fatal("env perm should apply to its own env")
- }
- if ps.Allows(PermContainersStart, "env-2") {
- t.Fatal("env perm must not leak to another env")
- }
- if ps.Allows(PermContainersStart, "") {
- t.Fatal("env perm must not satisfy an org-level check")
- }
+ require.True(t, ps.Allows(PermContainersStart, "env-1"),
+ "env perm should apply to its own env")
+
+ require.False(t, ps.Allows(PermContainersStart, "env-2"),
+ "env perm must not leak to another env")
+
+ require.False(t, ps.Allows(PermContainersStart, ""),
+ "env perm must not satisfy an org-level check")
+
}
func TestPermissionSetAllowsAnyEffectiveScope(t *testing.T) {
@@ -63,9 +65,12 @@ func TestPermissionSetAllowsAnyEffectiveScope(t *testing.T) {
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
- if got := tt.ps.AllowsAny(PermActivitiesRead); got != tt.want {
- t.Fatalf("AllowsAny() = %v, want %v", got, tt.want)
+ {
+ got := tt.ps.AllowsAny(PermActivitiesRead)
+ require.Equal(t, tt.want, got,
+ "AllowsAny() = %v, want %v", got, tt.want)
}
+
})
}
}
@@ -81,9 +86,9 @@ func TestPermissionSetIsGlobalAdminRejectsUnknownPermissions(t *testing.T) {
}
ps.AddGlobal("projects:made-up")
- if ps.IsGlobalAdmin() {
- t.Fatal("global admin should reject injected unknown permissions")
- }
+ require.False(t, ps.IsGlobalAdmin(),
+ "global admin should reject injected unknown permissions")
+
}
func TestPermissionSetIsGlobalAdminRequiresExactKnownSet(t *testing.T) {
@@ -94,9 +99,9 @@ func TestPermissionSetIsGlobalAdminRequiresExactKnownSet(t *testing.T) {
}
ps.AddGlobal("containers:does-not-exist")
- if ps.IsGlobalAdmin() {
- t.Fatal("global admin should require the complete known permission set")
- }
+ require.False(t, ps.IsGlobalAdmin(),
+ "global admin should require the complete known permission set")
+
}
func TestPermissionSetIsGlobalAdmin(t *testing.T) {
@@ -105,44 +110,45 @@ func TestPermissionSetIsGlobalAdmin(t *testing.T) {
ps.AddGlobal(perm)
}
- if !ps.IsGlobalAdmin() {
- t.Fatal("complete known permission set should be global admin")
- }
+ require.True(t, ps.IsGlobalAdmin(),
+ "complete known permission set should be global admin")
+
}
func TestSudoAllowsEverything(t *testing.T) {
ps := SudoPermissionSet()
- if !ps.Allows(PermContainersDelete, "any-env") {
- t.Fatal("sudo should allow any perm on any env")
- }
- if !ps.Allows(PermUsersDelete, "") {
- t.Fatal("sudo should allow org-level perms")
- }
- if !ps.IsGlobalAdmin() {
- t.Fatal("sudo should report as global admin")
- }
+
+ require.True(t, ps.Allows(PermContainersDelete, "any-env"),
+ "sudo should allow any perm on any env")
+
+ require.True(t, ps.Allows(PermUsersDelete, ""),
+ "sudo should allow org-level perms")
+
+ require.True(t, ps.IsGlobalAdmin(),
+ "sudo should report as global admin")
+
}
func TestEnvironmentPermissionSetScopesToOwnEnvironment(t *testing.T) {
ps := EnvironmentPermissionSet("env-A")
- if !ps.Allows(PermContainersStart, "env-A") {
- t.Fatal("environment token should allow env-scoped permissions for its own env")
- }
- if ps.Allows(PermContainersStart, "env-B") {
- t.Fatal("environment token must not allow env-scoped permissions for another env")
- }
- if ps.Allows(PermUsersList, "") {
- t.Fatal("environment token must not allow org-level permissions")
- }
- if ps.IsGlobalAdmin() {
- t.Fatal("environment token must not be global admin")
- }
+ require.True(t, ps.Allows(PermContainersStart, "env-A"),
+ "environment token should allow env-scoped permissions for its own env")
+
+ require.False(t, ps.Allows(PermContainersStart, "env-B"),
+ "environment token must not allow env-scoped permissions for another env")
+
+ require.False(t, ps.Allows(PermUsersList, ""),
+ "environment token must not allow org-level permissions")
+
+ require.False(t, ps.IsGlobalAdmin(),
+ "environment token must not be global admin")
empty := EnvironmentPermissionSet("")
- if empty.Allows(PermContainersStart, "env-A") {
- t.Fatal("environment token with empty env id must deny env-scoped permissions")
- }
+
+ require.False(t, empty.Allows(PermContainersStart, "env-A"),
+ "environment token with empty env id must deny env-scoped permissions")
+
}
func TestEnvIDFromPath(t *testing.T) {
@@ -155,25 +161,29 @@ func TestEnvIDFromPath(t *testing.T) {
"": "",
}
for input, want := range cases {
- if got := EnvIDFromPath(input); got != want {
- t.Errorf("EnvIDFromPath(%q) = %q, want %q", input, got, want)
+ {
+ got := EnvIDFromPath(input)
+ assert.Equal(t, want, got,
+ "EnvIDFromPath(%q) = %q, want %q", input, got, want)
}
+
}
}
func TestIsOrgLevelAndEnvScoped(t *testing.T) {
- if !IsOrgLevel(PermUsersList) {
- t.Fatal("users:list should be org-level")
- }
- if IsEnvScoped(PermUsersList) {
- t.Fatal("users:list should not be env-scoped")
- }
- if IsOrgLevel(PermContainersStart) {
- t.Fatal("containers:start should not be org-level")
- }
- if !IsEnvScoped(PermContainersStart) {
- t.Fatal("containers:start should be env-scoped")
- }
+
+ require.True(t, IsOrgLevel(PermUsersList),
+ "users:list should be org-level")
+
+ require.False(t, IsEnvScoped(PermUsersList),
+ "users:list should not be env-scoped")
+
+ require.False(t, IsOrgLevel(PermContainersStart),
+ "containers:start should not be org-level")
+
+ require.True(t, IsEnvScoped(PermContainersStart),
+ "containers:start should be env-scoped")
+
}
func TestIsKnownPermissionRejectsSyntheticPrefixMatches(t *testing.T) {
@@ -181,30 +191,34 @@ func TestIsKnownPermissionRejectsSyntheticPrefixMatches(t *testing.T) {
// must not be accepted β€” otherwise an admin could inflate ps.Global past
// TotalPermissionsCount() with bogus entries and trip IsGlobalAdmin().
for _, p := range []string{"containers:fake1", "projects:bogus", "images:made-up"} {
- if IsKnownPermission(p) {
- t.Errorf("IsKnownPermission(%q) = true, want false", p)
- }
- if IsEnvScoped(p) {
- t.Errorf("IsEnvScoped(%q) = true, want false", p)
- }
+
+ assert.False(t, IsKnownPermission(p),
+ "IsKnownPermission(%q) = true, want false", p)
+
+ assert.False(t, IsEnvScoped(p),
+ "IsEnvScoped(%q) = true, want false", p)
+
}
}
func TestBuiltInRolesOnlyReferenceKnownPermissions(t *testing.T) {
for _, p := range BuiltInEditorPermissions() {
- if !IsKnownPermission(p) {
- t.Errorf("editor references unknown perm %q", p)
- }
+
+ assert.True(t, IsKnownPermission(p),
+ "editor references unknown perm %q", p)
+
}
for _, p := range BuiltInDeployerPermissions() {
- if !IsKnownPermission(p) {
- t.Errorf("deployer references unknown perm %q", p)
- }
+
+ assert.True(t, IsKnownPermission(p),
+ "deployer references unknown perm %q", p)
+
}
for _, p := range BuiltInViewerPermissions() {
- if !IsKnownPermission(p) {
- t.Errorf("viewer references unknown perm %q", p)
- }
+
+ assert.True(t, IsKnownPermission(p),
+ "viewer references unknown perm %q", p)
+
}
}
@@ -218,15 +232,16 @@ func TestVariablePermissionsAreSeparateGlobalGrantsWithBuiltInAccess(t *testing.
}
for _, permission := range variablePermissions {
- if !IsKnownPermission(permission) {
- t.Fatalf("variable permission %q must be known", permission)
- }
- if !IsOrgLevel(permission) {
- t.Fatalf("variable permission %q must be global", permission)
- }
- if slices.Contains(BuiltInMonitorPermissions(), permission) {
- t.Fatalf("Monitor must not receive %q", permission)
- }
+
+ require.True(t, IsKnownPermission(permission),
+ "variable permission %q must be known", permission)
+
+ require.True(t, IsOrgLevel(permission),
+ "variable permission %q must be global", permission)
+
+ require.NotContains(t, BuiltInMonitorPermissions(), permission,
+ "Monitor must not receive %q", permission)
+
}
for name, permissions := range map[string][]string{
@@ -235,9 +250,10 @@ func TestVariablePermissionsAreSeparateGlobalGrantsWithBuiltInAccess(t *testing.
"No-Shell Editor": BuiltInNoShellEditorPermissions(),
} {
for _, permission := range variablePermissions {
- if !slices.Contains(permissions, permission) {
- t.Fatalf("%s must receive %q", name, permission)
- }
+
+ require.Contains(t, permissions, permission,
+ "%s must receive %q", name, permission)
+
}
}
@@ -245,89 +261,103 @@ func TestVariablePermissionsAreSeparateGlobalGrantsWithBuiltInAccess(t *testing.
"Viewer": BuiltInViewerPermissions(),
"Deployer": BuiltInDeployerPermissions(),
} {
- if !slices.Contains(permissions, PermVariablesRead) {
- t.Fatalf("%s must receive %q", name, PermVariablesRead)
- }
+
+ require.Contains(t, permissions, PermVariablesRead,
+ "%s must receive %q", name, PermVariablesRead)
+
for _, permission := range variablePermissions[1:] {
- if slices.Contains(permissions, permission) {
- t.Fatalf("%s must not receive %q", name, permission)
- }
+
+ require.NotContains(t, permissions, permission,
+ "%s must not receive %q", name, permission)
+
}
}
templatesOnly := NewPermissionSet()
templatesOnly.AddGlobal(PermTemplatesRead, PermTemplatesCreate, PermTemplatesUpdate, PermTemplatesDelete)
for _, permission := range variablePermissions {
- if templatesOnly.Allows(permission, "") {
- t.Fatalf("template grants must not satisfy %q", permission)
- }
+
+ require.False(t, templatesOnly.Allows(permission, ""),
+ "template grants must not satisfy %q", permission)
+
}
}
func TestPermissionCatalogDerivesKnownPermissionsAndScopes(t *testing.T) {
catalog := PermissionCatalog()
- if len(catalog) == 0 {
- t.Fatal("permission catalog must not be empty")
- }
+
+ require.NotEmpty(t, catalog,
+ "permission catalog must not be empty")
all := AllPermissions()
if len(all) != TotalPermissionsCount() {
- t.Fatalf("AllPermissions length = %d, TotalPermissionsCount = %d", len(all), TotalPermissionsCount())
+ require.Len(t, all, TotalPermissionsCount(),
+ "AllPermissions length = %d, TotalPermissionsCount = %d", len(all), TotalPermissionsCount())
}
seen := make(map[string]struct{}, len(all))
var catalogCount int
for _, resource := range catalog {
- if resource.Scope != PermissionScopeGlobal && resource.Scope != PermissionScopeEnv {
- t.Fatalf("resource %q has invalid scope %q", resource.Key, resource.Scope)
- }
+
+ require.False(t, resource.Scope != PermissionScopeGlobal && resource.Scope != PermissionScopeEnv,
+ "resource %q has invalid scope %q", resource.Key, resource.Scope)
+
for _, action := range resource.Actions {
catalogCount++
- if action.Permission == "" {
- t.Fatalf("resource %q action %q has empty permission", resource.Key, action.Key)
- }
- if _, exists := seen[action.Permission]; exists {
- t.Fatalf("duplicate permission %q in catalog", action.Permission)
+
+ require.NotEmpty(t, action.Permission,
+ "resource %q action %q has empty permission", resource.Key, action.Key)
+ {
+
+ _, exists := seen[action.Permission]
+ require.False(t, exists,
+ "duplicate permission %q in catalog", action.Permission)
}
+
seen[action.Permission] = struct{}{}
- if !IsKnownPermission(action.Permission) {
- t.Fatalf("catalog permission %q is not known", action.Permission)
- }
- if resource.Scope == PermissionScopeGlobal && !IsOrgLevel(action.Permission) {
- t.Fatalf("catalog permission %q should be org-level", action.Permission)
- }
- if resource.Scope == PermissionScopeEnv && !IsEnvScoped(action.Permission) {
- t.Fatalf("catalog permission %q should be env-scoped", action.Permission)
- }
+
+ require.True(t, IsKnownPermission(action.Permission),
+ "catalog permission %q is not known", action.Permission)
+
+ require.False(t, resource.Scope == PermissionScopeGlobal && !IsOrgLevel(action.Permission),
+ "catalog permission %q should be org-level", action.Permission)
+
+ require.False(t, resource.Scope == PermissionScopeEnv && !IsEnvScoped(action.Permission),
+ "catalog permission %q should be env-scoped", action.Permission)
+
}
}
- if catalogCount != len(all) {
- t.Fatalf("catalog permission count = %d, AllPermissions count = %d", catalogCount, len(all))
- }
+ require.Equal(t, len(all), catalogCount,
+ "catalog permission count = %d, AllPermissions count = %d", catalogCount, len(all))
+
for _, permission := range all {
- if _, exists := seen[permission]; !exists {
- t.Fatalf("AllPermissions includes %q outside catalog", permission)
+ {
+ _, exists := seen[permission]
+ require.True(t, exists,
+ "AllPermissions includes %q outside catalog", permission)
}
+
}
}
func TestNotificationsManageRequiresGlobalScope(t *testing.T) {
- if !IsOrgLevel(PermNotificationsManage) {
- t.Fatal("notifications:manage must be org-level for manager-global notification settings")
- }
- if IsEnvScoped(PermNotificationsManage) {
- t.Fatal("notifications:manage must not be environment-scoped")
- }
+
+ require.True(t, IsOrgLevel(PermNotificationsManage),
+ "notifications:manage must be org-level for manager-global notification settings")
+
+ require.False(t, IsEnvScoped(PermNotificationsManage),
+ "notifications:manage must not be environment-scoped")
ps := NewPermissionSet()
ps.AddEnv("env-1", PermNotificationsManage)
- if ps.Allows(PermNotificationsManage, "") {
- t.Fatal("an environment-scoped notification grant must not authorize the global resource")
- }
+
+ require.False(t, ps.Allows(PermNotificationsManage, ""),
+ "an environment-scoped notification grant must not authorize the global resource")
ps.AddGlobal(PermNotificationsManage)
- if !ps.Allows(PermNotificationsManage, "") {
- t.Fatal("a global notification grant must authorize the global resource")
- }
+
+ require.True(t, ps.Allows(PermNotificationsManage, ""),
+ "a global notification grant must authorize the global resource")
+
}
diff --git a/backend/pkg/dockerutil/compose_labels_test.go b/backend/pkg/dockerutil/compose_labels_test.go
index f96d42539..f8da048a7 100644
--- a/backend/pkg/dockerutil/compose_labels_test.go
+++ b/backend/pkg/dockerutil/compose_labels_test.go
@@ -1,24 +1,39 @@
package docker
-import "testing"
+import (
+ "testing"
+
+ "github.com/stretchr/testify/assert"
+)
func TestComposeLabels(t *testing.T) {
labels := map[string]string{
ComposeProjectLabelKey: " myproj ",
ComposeServiceLabelKey: "web",
}
+ {
- if got := ComposeProjectLabel(labels); got != "myproj" {
- t.Errorf("ComposeProjectLabel() = %q, want %q", got, "myproj")
+ got := ComposeProjectLabel(labels)
+ assert.Equal(t, "myproj", got,
+ "ComposeProjectLabel() = %q, want %q", got, "myproj")
}
- if got := ComposeServiceLabel(labels); got != "web" {
- t.Errorf("ComposeServiceLabel() = %q, want %q", got, "web")
+ {
+
+ got := ComposeServiceLabel(labels)
+ assert.Equal(t, "web", got,
+ "ComposeServiceLabel() = %q, want %q", got, "web")
}
+ {
- if got := ComposeProjectLabel(nil); got != "" {
- t.Errorf("ComposeProjectLabel(nil) = %q, want %q", got, "")
+ got := ComposeProjectLabel(nil)
+ assert.Empty(t, got,
+ "ComposeProjectLabel(nil) = %q, want %q", got, "")
}
- if got := ComposeServiceLabel(map[string]string{}); got != "" {
- t.Errorf("ComposeServiceLabel(empty) = %q, want %q", got, "")
+ {
+
+ got := ComposeServiceLabel(map[string]string{})
+ assert.Empty(t, got,
+ "ComposeServiceLabel(empty) = %q, want %q", got, "")
}
+
}
diff --git a/backend/pkg/dockerutil/container_names_test.go b/backend/pkg/dockerutil/container_names_test.go
index b6e854c75..2806ae641 100644
--- a/backend/pkg/dockerutil/container_names_test.go
+++ b/backend/pkg/dockerutil/container_names_test.go
@@ -1,6 +1,10 @@
package docker
-import "testing"
+import (
+ "testing"
+
+ "github.com/stretchr/testify/assert"
+)
func TestContainerNameFromNames(t *testing.T) {
tests := []struct {
@@ -32,9 +36,12 @@ func TestContainerNameFromNames(t *testing.T) {
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
- if got := ContainerNameFromNames(tt.names); got != tt.want {
- t.Errorf("ContainerNameFromNames() = %v, want %v", got, tt.want)
+ {
+ got := ContainerNameFromNames(tt.names)
+ assert.Equal(t, tt.want, got,
+ "ContainerNameFromNames() = %v, want %v", got, tt.want)
}
+
})
}
}
diff --git a/backend/pkg/dockerutil/log_stream_test.go b/backend/pkg/dockerutil/log_stream_test.go
index bd373c229..e1deaa6c6 100644
--- a/backend/pkg/dockerutil/log_stream_test.go
+++ b/backend/pkg/dockerutil/log_stream_test.go
@@ -111,7 +111,7 @@ func TestStreamMultiplexedLogsContextCancelDoesNotDeadlock(t *testing.T) {
case err := <-done:
require.ErrorIs(t, err, context.Canceled)
case <-time.After(time.Second):
- t.Fatal("StreamMultiplexedLogs did not exit after cancellation")
+ require.FailNow(t, "StreamMultiplexedLogs did not exit after cancellation")
}
}
@@ -129,7 +129,7 @@ func TestReadAllLogsContextCancelClosesReader(t *testing.T) {
select {
case <-reader.readStarted:
case <-time.After(time.Second):
- t.Fatal("ReadAllLogs did not start reading")
+ require.FailNow(t, "ReadAllLogs did not start reading")
}
cancel()
@@ -138,13 +138,13 @@ func TestReadAllLogsContextCancelClosesReader(t *testing.T) {
case err := <-done:
require.ErrorIs(t, err, context.Canceled)
case <-time.After(time.Second):
- t.Fatal("ReadAllLogs did not exit after cancellation")
+ require.FailNow(t, "ReadAllLogs did not exit after cancellation")
}
select {
case <-reader.closeCalled:
case <-time.After(time.Second):
- t.Fatal("ReadAllLogs did not close the reader on cancellation")
+ require.FailNow(t, "ReadAllLogs did not close the reader on cancellation")
}
}
diff --git a/backend/pkg/dockerutil/mount_utils_test.go b/backend/pkg/dockerutil/mount_utils_test.go
index fabe4e7ca..f75e9c7e3 100644
--- a/backend/pkg/dockerutil/mount_utils_test.go
+++ b/backend/pkg/dockerutil/mount_utils_test.go
@@ -48,7 +48,7 @@ func TestCurrentContainerInspectTarget(t *testing.T) {
require.Error(t, err)
require.Contains(t, err.Error(), "hostname unavailable")
- require.Equal(t, "", target)
+ require.Empty(t, target)
})
}
diff --git a/backend/pkg/dockerutil/render_test.go b/backend/pkg/dockerutil/render_test.go
index bb41dcbe0..87aea8114 100644
--- a/backend/pkg/dockerutil/render_test.go
+++ b/backend/pkg/dockerutil/render_test.go
@@ -4,6 +4,8 @@ import (
"strings"
"sync"
"testing"
+
+ "github.com/stretchr/testify/require"
)
func TestRenderJSONMessageStream(t *testing.T) {
@@ -13,24 +15,29 @@ func TestRenderJSONMessageStream(t *testing.T) {
`{"status":"Pull complete","id":"abc123"}` + "\n" +
`{"status":"Status: Downloaded newer image for nginx:stable-alpine"}` + "\n")
var out strings.Builder
+ {
- if err := RenderJSONMessageStream(stream, &out); err != nil {
- t.Fatalf("expected nil error, got %v", err)
+ err := RenderJSONMessageStream(stream, &out)
+ require.NoError(t, err,
+ "expected nil error, got %v", err)
}
+
want := "stable-alpine: Pulling from library/nginx\n" +
"abc123: Pull complete\n" +
"Status: Downloaded newer image for nginx:stable-alpine\n"
- if out.String() != want {
- t.Fatalf("expected CLI-parity output %q, got %q", want, out.String())
- }
+
+ require.Equal(t, want, out.String(),
+ "expected CLI-parity output %q, got %q", want, out.String())
+
})
t.Run("returns daemon errorDetail verbatim", func(t *testing.T) {
stream := strings.NewReader(`{"errorDetail":{"code":401,"message":"unauthorized"}}` + "\n")
err := RenderJSONMessageStream(stream, nil)
- if err == nil || !strings.Contains(err.Error(), "unauthorized") {
- t.Fatalf("expected unauthorized error, got %v", err)
- }
+
+ require.False(t, err == nil || !strings.Contains(err.Error(), "unauthorized"),
+ "expected unauthorized error, got %v", err)
+
})
}
@@ -53,7 +60,8 @@ func TestLogLineWriterConcurrentWrites(t *testing.T) {
lines := strings.Split(strings.TrimSpace(out.String()), "\n")
if len(lines) != 8*200 {
- t.Fatalf("expected %d frames, got %d", 8*200, len(lines))
+ require.Len(t, lines, 8*200,
+ "expected %d frames, got %d", 8*200, len(lines))
}
}
@@ -85,7 +93,8 @@ func TestLogLineWriter(t *testing.T) {
want := `{"log":"Container arcane-test Creating"}` + "\n" +
`{"log":"Container arcane-test Created"}` + "\n" +
`{"log":"partial"}` + "\n"
- if out.String() != want {
- t.Fatalf("expected framed lines %q, got %q", want, out.String())
- }
+
+ require.Equal(t, want, out.String(),
+ "expected framed lines %q, got %q", want, out.String())
+
}
diff --git a/backend/pkg/dockerutil/volume_utils_test.go b/backend/pkg/dockerutil/volume_utils_test.go
index e820df9d8..6294bf967 100644
--- a/backend/pkg/dockerutil/volume_utils_test.go
+++ b/backend/pkg/dockerutil/volume_utils_test.go
@@ -43,7 +43,7 @@ func TestVolumeUsageCacheBehaviorInternal(t *testing.T) {
select {
case <-started:
case <-time.After(time.Second):
- t.Fatal("volume usage refresh did not start")
+ require.FailNow(t, "volume usage refresh did not start")
}
waiterCtx, waiterCancel := context.WithTimeout(context.Background(), 20*time.Millisecond)
@@ -101,7 +101,7 @@ func TestVolumeUsageCacheBehaviorInternal(t *testing.T) {
select {
case <-secondStarted:
case <-time.After(time.Second):
- t.Fatal("background volume usage refresh did not start")
+ require.FailNow(t, "background volume usage refresh did not start")
}
_, _ = GetVolumeUsageDataStaleWhileRevalidate(ctx, dockerClient).Get()
require.Equal(t, int32(2), requests.Load())
diff --git a/backend/pkg/fswatch/watcher_test.go b/backend/pkg/fswatch/watcher_test.go
index df921a1ce..4fe973667 100644
--- a/backend/pkg/fswatch/watcher_test.go
+++ b/backend/pkg/fswatch/watcher_test.go
@@ -44,7 +44,7 @@ func TestWatcher_StartWatchesExistingSymlinkDirectoriesWhenEnabled(t *testing.T)
select {
case <-changeCh:
case <-time.After(2 * time.Second):
- t.Fatal("expected symlinked directory change to trigger watcher callback")
+ require.FailNow(t, "expected symlinked directory change to trigger watcher callback")
}
}
@@ -86,7 +86,7 @@ func TestWatcher_StartWatchesNewDirectoriesInsideSymlinkDirectoriesWhenEnabled(t
select {
case <-changeCh:
case <-time.After(2 * time.Second):
- t.Fatal("expected compose file in new symlinked directory to trigger watcher callback")
+ require.FailNow(t, "expected compose file in new symlinked directory to trigger watcher callback")
}
}
@@ -127,7 +127,7 @@ func TestWatcher_StartIgnoresNonProjectFileWritesInsideProjectDir(t *testing.T)
select {
case <-changeCh:
- t.Fatal("did not expect non-project file writes to trigger watcher callback")
+ require.FailNow(t, "did not expect non-project file writes to trigger watcher callback")
case <-time.After(500 * time.Millisecond):
}
}
@@ -164,7 +164,7 @@ func TestWatcher_StartIgnoresChmodOnNonProjectFiles(t *testing.T) {
// Chmod on a non-project file is exactly the noise we're filtering.
select {
case <-changeCh:
- t.Fatal("did not expect chmod on a non-project file to trigger watcher callback")
+ require.FailNow(t, "did not expect chmod on a non-project file to trigger watcher callback")
case <-time.After(500 * time.Millisecond):
}
}
@@ -197,7 +197,7 @@ func TestWatcher_StartFiresOnComposeFileDroppedIntoNewlyCreatedDirectory(t *test
select {
case <-changeCh:
- t.Fatal("did not expect plain directory create to trigger watcher callback")
+ require.FailNow(t, "did not expect plain directory create to trigger watcher callback")
case <-time.After(500 * time.Millisecond):
}
@@ -209,7 +209,7 @@ func TestWatcher_StartFiresOnComposeFileDroppedIntoNewlyCreatedDirectory(t *test
select {
case <-changeCh:
case <-time.After(2 * time.Second):
- t.Fatal("expected compose file inside newly-created directory to trigger watcher callback")
+ require.FailNow(t, "expected compose file inside newly-created directory to trigger watcher callback")
}
}
@@ -245,7 +245,7 @@ func TestWatcher_StartSkipsExistingSymlinkDirectoriesWhenDisabled(t *testing.T)
select {
case <-changeCh:
- t.Fatal("did not expect symlinked directory change to trigger watcher callback when disabled")
+ require.FailNow(t, "did not expect symlinked directory change to trigger watcher callback when disabled")
case <-time.After(300 * time.Millisecond):
}
}
@@ -279,7 +279,7 @@ func TestWatcher_StartTriggersOnNestedProjectFileBeyondDepthOne(t *testing.T) {
select {
case <-changeCh:
case <-time.After(2 * time.Second):
- t.Fatal("expected nested compose file change to trigger watcher callback")
+ require.FailNow(t, "expected nested compose file change to trigger watcher callback")
}
}
@@ -311,7 +311,7 @@ func TestWatcher_StartDoesNotTriggerOnNestedProjectFileBeyondConfiguredDepth(t *
select {
case <-changeCh:
- t.Fatal("did not expect nested compose file beyond max depth to trigger watcher callback")
+ require.FailNow(t, "did not expect nested compose file beyond max depth to trigger watcher callback")
case <-time.After(500 * time.Millisecond):
}
}
@@ -345,7 +345,7 @@ func TestWatcher_StartTriggersOnDirectChildProjectFileAtConfiguredDepth(t *testi
select {
case <-changeCh:
case <-time.After(2 * time.Second):
- t.Fatal("expected direct child compose file at max depth to trigger watcher callback")
+ require.FailNow(t, "expected direct child compose file at max depth to trigger watcher callback")
}
}
@@ -380,7 +380,7 @@ func TestWatcher_StartIgnoresBareNestedDirectoryCreateAndRemove(t *testing.T) {
select {
case <-changeCh:
- t.Fatal("did not expect plain nested directory create to trigger watcher callback")
+ require.FailNow(t, "did not expect plain nested directory create to trigger watcher callback")
case <-time.After(500 * time.Millisecond):
}
@@ -388,7 +388,7 @@ func TestWatcher_StartIgnoresBareNestedDirectoryCreateAndRemove(t *testing.T) {
select {
case <-changeCh:
- t.Fatal("did not expect plain nested directory removal to trigger watcher callback")
+ require.FailNow(t, "did not expect plain nested directory removal to trigger watcher callback")
case <-time.After(500 * time.Millisecond):
}
}
@@ -427,6 +427,6 @@ func stopWatcherWithinTimeoutInternal(t *testing.T, watcher *Watcher) {
case err := <-done:
require.NoError(t, err)
case <-time.After(2 * time.Second):
- t.Fatal("timed out waiting for watcher to stop")
+ require.FailNow(t, "timed out waiting for watcher to stop")
}
}
diff --git a/backend/pkg/gitutil/git_test.go b/backend/pkg/gitutil/git_test.go
index d6867b7d2..da2489cdc 100644
--- a/backend/pkg/gitutil/git_test.go
+++ b/backend/pkg/gitutil/git_test.go
@@ -14,16 +14,20 @@ import (
"github.com/go-git/go-git/v5/plumbing/protocol/packp/capability"
"github.com/go-git/go-git/v5/plumbing/transport"
+ "github.com/stretchr/testify/assert"
+ "github.com/stretchr/testify/require"
gossh "golang.org/x/crypto/ssh"
)
// Azure DevOps requires multi_ack/multi_ack_detailed in pack negotiation;
// go-git's default UnsupportedCapabilities strips them and clones fail with
// "invalid reset option: object not found" (#3168).
+
func TestInitAllowsMultiAckCapabilities(t *testing.T) {
- if len(transport.UnsupportedCapabilities) != 1 || transport.UnsupportedCapabilities[0] != capability.ThinPack {
- t.Errorf("expected UnsupportedCapabilities to contain only thin-pack, got %v", transport.UnsupportedCapabilities)
- }
+
+ assert.False(t, len(transport.UnsupportedCapabilities) != 1 || transport.UnsupportedCapabilities[0] != capability.ThinPack,
+ "expected UnsupportedCapabilities to contain only thin-pack, got %v", transport.UnsupportedCapabilities)
+
}
func TestGetKnownHostsPath(t *testing.T) {
@@ -35,9 +39,10 @@ func TestGetKnownHostsPath(t *testing.T) {
os.Stat,
os.UserHomeDir,
)
- if result != customPath {
- t.Errorf("expected %s, got %s", customPath, result)
- }
+
+ assert.Equal(t, customPath, result,
+ "expected %s, got %s", customPath, result)
+
})
t.Run("returns Arcane data path when data directory exists", func(t *testing.T) {
@@ -54,9 +59,9 @@ func TestGetKnownHostsPath(t *testing.T) {
expected := defaultKnownHostsPath
- if result != expected {
- t.Errorf("expected %s, got %s", expected, result)
- }
+ assert.Equal(t, expected, result,
+ "expected %s, got %s", expected, result)
+
})
t.Run("falls back to home directory when Arcane data directory is unavailable", func(t *testing.T) {
@@ -68,9 +73,10 @@ func TestGetKnownHostsPath(t *testing.T) {
)
expected := filepath.Join(homeDir, ".ssh", "known_hosts")
- if result != expected {
- t.Errorf("expected %s, got %s", expected, result)
- }
+
+ assert.Equal(t, expected, result,
+ "expected %s, got %s", expected, result)
+
})
t.Run("falls back to temp dir when data directory and home are unavailable", func(t *testing.T) {
@@ -81,9 +87,10 @@ func TestGetKnownHostsPath(t *testing.T) {
)
expected := filepath.Join(os.TempDir(), ".ssh", "known_hosts")
- if result != expected {
- t.Errorf("expected %s, got %s", expected, result)
- }
+
+ assert.Equal(t, expected, result,
+ "expected %s, got %s", expected, result)
+
})
}
@@ -103,17 +110,19 @@ func TestGetSSHHostKeyCallback(t *testing.T) {
t.Run("skip mode returns InsecureIgnoreHostKey", func(t *testing.T) {
callback, err := client.getSSHHostKeyCallback(SSHHostKeyVerificationSkip)
- if err != nil {
- t.Fatalf("unexpected error: %v", err)
- }
- if callback == nil {
- t.Fatal("expected non-nil callback")
- }
+
+ require.NoError(t, err,
+ "unexpected error: %v", err)
+
+ require.NotNil(t, callback,
+ "expected non-nil callback")
+
// InsecureIgnoreHostKey always returns nil
err = callback("example.com:22", &net.TCPAddr{}, nil)
- if err != nil {
- t.Errorf("skip mode should not return error, got: %v", err)
- }
+
+ assert.NoError(t, err,
+ "skip mode should not return error, got: %v", err)
+
})
t.Run("empty mode defaults to accept_new", func(t *testing.T) {
@@ -122,12 +131,13 @@ func TestGetSSHHostKeyCallback(t *testing.T) {
t.Setenv("SSH_KNOWN_HOSTS", knownHostsPath)
callback, err := client.getSSHHostKeyCallback("")
- if err != nil {
- t.Fatalf("unexpected error: %v", err)
- }
- if callback == nil {
- t.Fatal("expected non-nil callback")
- }
+
+ require.NoError(t, err,
+ "unexpected error: %v", err)
+
+ require.NotNil(t, callback,
+ "expected non-nil callback")
+
})
t.Run("accept_new mode creates callback", func(t *testing.T) {
@@ -136,12 +146,13 @@ func TestGetSSHHostKeyCallback(t *testing.T) {
t.Setenv("SSH_KNOWN_HOSTS", knownHostsPath)
callback, err := client.getSSHHostKeyCallback(SSHHostKeyVerificationAcceptNew)
- if err != nil {
- t.Fatalf("unexpected error: %v", err)
- }
- if callback == nil {
- t.Fatal("expected non-nil callback")
- }
+
+ require.NoError(t, err,
+ "unexpected error: %v", err)
+
+ require.NotNil(t, callback,
+ "expected non-nil callback")
+
})
}
@@ -154,18 +165,19 @@ func TestAddHostKey(t *testing.T) {
key := generateTestPublicKey(t)
err := addHostKey(knownHostsPath, "example.com:22", key)
- if err != nil {
- t.Fatalf("unexpected error: %v", err)
- }
+
+ require.NoError(t, err,
+ "unexpected error: %v", err)
// Verify file was created and contains content
content, err := os.ReadFile(knownHostsPath)
- if err != nil {
- t.Fatalf("failed to read known_hosts: %v", err)
- }
- if len(content) == 0 {
- t.Error("expected non-empty known_hosts file")
- }
+
+ require.NoError(t, err,
+ "failed to read known_hosts: %v", err)
+
+ assert.NotEmpty(t, content,
+ "expected non-empty known_hosts file")
+
})
t.Run("concurrent writes don't corrupt file", func(t *testing.T) {
@@ -193,17 +205,18 @@ func TestAddHostKey(t *testing.T) {
close(errChan)
for err := range errChan {
- t.Errorf("concurrent write error: %v", err)
+ assert.Failf(t, "unexpected failure", "concurrent write error: %v", err)
}
// Verify file exists and has content
content, err := os.ReadFile(knownHostsPath)
- if err != nil {
- t.Fatalf("failed to read known_hosts: %v", err)
- }
- if len(content) == 0 {
- t.Error("expected non-empty known_hosts file after concurrent writes")
- }
+
+ require.NoError(t, err,
+ "failed to read known_hosts: %v", err)
+
+ assert.NotEmpty(t, content,
+ "expected non-empty known_hosts file after concurrent writes")
+
})
}
@@ -215,17 +228,20 @@ func TestCreateAcceptNewHostKeyCallback(t *testing.T) {
client := NewClient("")
callback, err := client.createAcceptNewHostKeyCallback()
- if err != nil {
- t.Fatalf("unexpected error: %v", err)
- }
- if callback == nil {
- t.Fatal("expected non-nil callback")
- }
- // Verify directory was created
- if _, err := os.Stat(filepath.Dir(knownHostsPath)); os.IsNotExist(err) {
- t.Error("expected known_hosts directory to be created")
+ require.NoError(t, err,
+ "unexpected error: %v", err)
+
+ require.NotNil(t, callback,
+ "expected non-nil callback")
+ {
+
+ // Verify directory was created
+ _, err := os.Stat(filepath.Dir(knownHostsPath))
+ assert.False(t, os.IsNotExist(err),
+ "expected known_hosts directory to be created")
}
+
})
t.Run("callback adds new host keys", func(t *testing.T) {
@@ -235,26 +251,27 @@ func TestCreateAcceptNewHostKeyCallback(t *testing.T) {
client := NewClient("")
callback, err := client.createAcceptNewHostKeyCallback()
- if err != nil {
- t.Fatalf("unexpected error: %v", err)
- }
+
+ require.NoError(t, err,
+ "unexpected error: %v", err)
key := generateTestPublicKey(t)
addr := &net.TCPAddr{IP: net.ParseIP("192.168.1.1"), Port: 22}
err = callback("192.168.1.1:22", addr, key)
- if err != nil {
- t.Errorf("callback returned error: %v", err)
- }
+
+ require.NoError(t, err,
+ "callback returned error: %v", err)
// Verify host was added to file
content, err := os.ReadFile(knownHostsPath)
- if err != nil {
- t.Fatalf("failed to read known_hosts: %v", err)
- }
- if len(content) == 0 {
- t.Error("expected host key to be added to known_hosts")
- }
+
+ require.NoError(t, err,
+ "failed to read known_hosts: %v", err)
+
+ assert.NotEmpty(t, content,
+ "expected host key to be added to known_hosts")
+
})
t.Run("callback accepts known host", func(t *testing.T) {
@@ -264,24 +281,25 @@ func TestCreateAcceptNewHostKeyCallback(t *testing.T) {
client := NewClient("")
callback, err := client.createAcceptNewHostKeyCallback()
- if err != nil {
- t.Fatalf("unexpected error: %v", err)
- }
+
+ require.NoError(t, err,
+ "unexpected error: %v", err)
key := generateTestPublicKey(t)
addr := &net.TCPAddr{IP: net.ParseIP("192.168.1.1"), Port: 22}
// First call adds the key
err = callback("192.168.1.1:22", addr, key)
- if err != nil {
- t.Fatalf("first callback returned error: %v", err)
- }
+
+ require.NoError(t, err,
+ "first callback returned error: %v", err)
// Second call should recognize the known host
err = callback("192.168.1.1:22", addr, key)
- if err != nil {
- t.Errorf("second callback returned error for known host: %v", err)
- }
+
+ assert.NoError(t, err,
+ "second callback returned error for known host: %v", err)
+
})
t.Run("callback detects host key mismatch", func(t *testing.T) {
@@ -291,9 +309,9 @@ func TestCreateAcceptNewHostKeyCallback(t *testing.T) {
client := NewClient("")
callback, err := client.createAcceptNewHostKeyCallback()
- if err != nil {
- t.Fatalf("unexpected error: %v", err)
- }
+
+ require.NoError(t, err,
+ "unexpected error: %v", err)
key1 := generateTestPublicKey(t)
key2 := generateTestPublicKeyVariant(t)
@@ -301,16 +319,17 @@ func TestCreateAcceptNewHostKeyCallback(t *testing.T) {
// First call adds key1
err = callback("192.168.1.1:22", addr, key1)
- if err != nil {
- t.Fatalf("first callback returned error: %v", err)
- }
+
+ require.NoError(t, err,
+ "first callback returned error: %v", err)
// Second call with different key for same host should fail
err = callback("192.168.1.1:22", addr, key2)
if err == nil {
- t.Error("expected error for host key mismatch, got nil")
+ assert.Fail(t, "expected error for host key mismatch, got nil")
} else if !strings.Contains(err.Error(), "host key mismatch") {
- t.Errorf("expected host key mismatch error, got: %v", err)
+ assert.Contains(t, err.Error(), "host key mismatch",
+ "expected host key mismatch error, got: %v", err)
}
})
}
@@ -319,53 +338,64 @@ func TestValidatePath(t *testing.T) {
t.Run("allows valid paths", func(t *testing.T) {
tmpDir := t.TempDir()
err := ValidatePath(tmpDir, "subdir/file.txt")
- if err != nil {
- t.Errorf("expected valid path to be allowed: %v", err)
- }
+
+ assert.NoError(t, err,
+ "expected valid path to be allowed: %v", err)
+
})
t.Run("rejects path traversal", func(t *testing.T) {
tmpDir := t.TempDir()
err := ValidatePath(tmpDir, "../../../etc/passwd")
- if err == nil {
- t.Error("expected path traversal to be rejected")
- }
+
+ assert.Error(t, err,
+ "expected path traversal to be rejected")
+
})
t.Run("rejects absolute path escape", func(t *testing.T) {
tmpDir := t.TempDir()
err := ValidatePath(tmpDir, "foo/../../..")
- if err == nil {
- t.Error("expected path escape to be rejected")
- }
+
+ assert.Error(t, err,
+ "expected path escape to be rejected")
+
})
}
func TestNewClient(t *testing.T) {
t.Run("creates client with work dir", func(t *testing.T) {
client := NewClient("/tmp/test")
- if client.workDir != "/tmp/test" {
- t.Errorf("expected workDir /tmp/test, got %s", client.workDir)
- }
+
+ assert.Equal(t, "/tmp/test", client.workDir,
+ "expected workDir /tmp/test, got %s", client.workDir)
+
})
t.Run("creates client with empty work dir", func(t *testing.T) {
client := NewClient("")
- if client.workDir != "" {
- t.Errorf("expected empty workDir, got %s", client.workDir)
- }
+
+ assert.Empty(t, client.workDir,
+ "expected empty workDir, got %s", client.workDir)
+
})
}
func writeFileInternal(t *testing.T, dir, name string, content []byte) {
t.Helper()
targetPath := filepath.Join(dir, name)
- if err := os.MkdirAll(filepath.Dir(targetPath), 0o755); err != nil {
- t.Fatalf("failed to create parent directories for %s: %v", name, err)
+ {
+ err := os.MkdirAll(filepath.Dir(targetPath), 0o755)
+ require.NoError(t, err,
+ "failed to create parent directories for %s: %v", name, err)
}
- if err := os.WriteFile(targetPath, content, 0644); err != nil {
- t.Fatalf("failed to write file %s: %v", name, err)
+ {
+
+ err := os.WriteFile(targetPath, content, 0644)
+ require.NoError(t, err,
+ "failed to write file %s: %v", name, err)
}
+
}
func minimalCompose() []byte {
@@ -380,15 +410,16 @@ func TestWalkDirectory_BasicWalk(t *testing.T) {
client := NewClient("")
result, err := client.WalkDirectory(context.Background(), tmpDir, "compose.yaml", 0, 0, 0)
- if err != nil {
- t.Fatalf("unexpected error: %v", err)
- }
- if result.TotalFiles != 3 {
- t.Errorf("expected 3 files, got %d", result.TotalFiles)
- }
- if len(result.Files) != 3 {
- t.Errorf("expected 3 entries in Files, got %d", len(result.Files))
- }
+
+ require.NoError(t, err,
+ "unexpected error: %v", err)
+
+ assert.Equal(t, 3, result.TotalFiles,
+ "expected 3 files, got %d", result.TotalFiles)
+
+ assert.Len(t, result.Files, 3,
+ "expected 3 entries in Files, got %d", len(result.Files))
+
}
func TestWalkDirectory_PreservesExecutableBit(t *testing.T) {
@@ -396,15 +427,17 @@ func TestWalkDirectory_PreservesExecutableBit(t *testing.T) {
writeFileInternal(t, tmpDir, "compose.yaml", minimalCompose())
writeFileInternal(t, tmpDir, "scripts/hook.sh", []byte("#!/bin/sh\necho hi\n"))
writeFileInternal(t, tmpDir, "README.md", []byte("readme"))
- if err := os.Chmod(filepath.Join(tmpDir, "scripts/hook.sh"), 0o755); err != nil {
- t.Fatalf("chmod: %v", err)
+ {
+ err := os.Chmod(filepath.Join(tmpDir, "scripts/hook.sh"), 0o755)
+ require.NoError(t, err,
+ "chmod: %v", err)
}
client := NewClient("")
result, err := client.WalkDirectory(context.Background(), tmpDir, "compose.yaml", 0, 0, 0)
- if err != nil {
- t.Fatalf("unexpected error: %v", err)
- }
+
+ require.NoError(t, err,
+ "unexpected error: %v", err)
byPath := map[string]SyncFileInfo{}
for _, f := range result.Files {
@@ -412,15 +445,19 @@ func TestWalkDirectory_PreservesExecutableBit(t *testing.T) {
}
hook, ok := byPath[filepath.ToSlash("scripts/hook.sh")]
- if !ok {
- t.Fatalf("expected scripts/hook.sh in walk result, got %v", byPath)
- }
- if !hook.Executable {
- t.Errorf("expected scripts/hook.sh to be reported Executable, got false")
- }
- if readme, ok := byPath["README.md"]; ok && readme.Executable {
- t.Errorf("expected README.md to not be Executable")
+
+ require.True(t, ok,
+ "expected scripts/hook.sh in walk result, got %v", byPath)
+
+ assert.True(t, hook.Executable,
+ "expected scripts/hook.sh to be reported Executable, got false")
+ {
+
+ readme, ok := byPath["README.md"]
+ assert.False(t, ok && readme.Executable,
+ "expected README.md to not be Executable")
}
+
}
func TestWalkDirectory_MaxFilesLimit(t *testing.T) {
@@ -433,12 +470,13 @@ func TestWalkDirectory_MaxFilesLimit(t *testing.T) {
client := NewClient("")
_, err := client.WalkDirectory(context.Background(), tmpDir, "compose.yaml", 3, 0, 0)
- if err == nil {
- t.Fatal("expected error for file count limit, got nil")
- }
- if !strings.Contains(err.Error(), "file count limit exceeded") {
- t.Errorf("expected 'file count limit exceeded' error, got: %v", err)
- }
+
+ require.Error(t, err,
+ "expected error for file count limit, got nil")
+
+ assert.Contains(t, err.Error(), "file count limit exceeded",
+ "expected 'file count limit exceeded' error, got: %v", err)
+
}
func TestWalkDirectory_MaxFilesUnlimited(t *testing.T) {
@@ -451,12 +489,13 @@ func TestWalkDirectory_MaxFilesUnlimited(t *testing.T) {
client := NewClient("")
result, err := client.WalkDirectory(context.Background(), tmpDir, "compose.yaml", 0, 0, 0)
- if err != nil {
- t.Fatalf("unexpected error: %v", err)
- }
- if result.TotalFiles != 5 {
- t.Errorf("expected 5 files, got %d", result.TotalFiles)
- }
+
+ require.NoError(t, err,
+ "unexpected error: %v", err)
+
+ assert.Equal(t, 5, result.TotalFiles,
+ "expected 5 files, got %d", result.TotalFiles)
+
}
func TestWalkDirectory_MaxTotalSizeLimit(t *testing.T) {
@@ -467,12 +506,13 @@ func TestWalkDirectory_MaxTotalSizeLimit(t *testing.T) {
client := NewClient("")
_, err := client.WalkDirectory(context.Background(), tmpDir, "compose.yaml", 0, 50, 0)
- if err == nil {
- t.Fatal("expected error for total size limit, got nil")
- }
- if !strings.Contains(err.Error(), "total size limit exceeded") {
- t.Errorf("expected 'total size limit exceeded' error, got: %v", err)
- }
+
+ require.Error(t, err,
+ "expected error for total size limit, got nil")
+
+ assert.Contains(t, err.Error(), "total size limit exceeded",
+ "expected 'total size limit exceeded' error, got: %v", err)
+
}
func TestWalkDirectory_MaxTotalSizeUnlimited(t *testing.T) {
@@ -483,12 +523,13 @@ func TestWalkDirectory_MaxTotalSizeUnlimited(t *testing.T) {
client := NewClient("")
result, err := client.WalkDirectory(context.Background(), tmpDir, "compose.yaml", 0, 0, 0)
- if err != nil {
- t.Fatalf("unexpected error: %v", err)
- }
- if result.TotalFiles != 3 {
- t.Errorf("expected 3 files, got %d", result.TotalFiles)
- }
+
+ require.NoError(t, err,
+ "unexpected error: %v", err)
+
+ assert.Equal(t, 3, result.TotalFiles,
+ "expected 3 files, got %d", result.TotalFiles)
+
}
func TestWalkDirectory_MaxBinarySizeSkips(t *testing.T) {
@@ -500,12 +541,13 @@ func TestWalkDirectory_MaxBinarySizeSkips(t *testing.T) {
client := NewClient("")
result, err := client.WalkDirectory(context.Background(), tmpDir, "compose.yaml", 0, 0, 5)
- if err != nil {
- t.Fatalf("unexpected error: %v", err)
- }
- if result.SkippedBinaries == 0 {
- t.Error("expected at least one skipped binary file, got 0")
- }
+
+ require.NoError(t, err,
+ "unexpected error: %v", err)
+
+ assert.NotEqual(t, 0, result.SkippedBinaries,
+ "expected at least one skipped binary file, got 0")
+
}
func TestWalkDirectory_MaxBinarySizeUnlimited(t *testing.T) {
@@ -516,15 +558,16 @@ func TestWalkDirectory_MaxBinarySizeUnlimited(t *testing.T) {
client := NewClient("")
result, err := client.WalkDirectory(context.Background(), tmpDir, "compose.yaml", 0, 0, 0)
- if err != nil {
- t.Fatalf("unexpected error: %v", err)
- }
- if result.SkippedBinaries != 0 {
- t.Errorf("expected no skipped binaries with unlimited size, got %d", result.SkippedBinaries)
- }
- if result.TotalFiles != 2 {
- t.Errorf("expected 2 files (compose + binary), got %d", result.TotalFiles)
- }
+
+ require.NoError(t, err,
+ "unexpected error: %v", err)
+
+ assert.Equal(t, 0, result.SkippedBinaries,
+ "expected no skipped binaries with unlimited size, got %d", result.SkippedBinaries)
+
+ assert.Equal(t, 2, result.TotalFiles,
+ "expected 2 files (compose + binary), got %d", result.TotalFiles)
+
}
func TestWalkDirectory_LargeTextFileNotSkippedByBinaryLimit(t *testing.T) {
@@ -534,15 +577,16 @@ func TestWalkDirectory_LargeTextFileNotSkippedByBinaryLimit(t *testing.T) {
client := NewClient("")
result, err := client.WalkDirectory(context.Background(), tmpDir, "compose.yaml", 0, 0, 16)
- if err != nil {
- t.Fatalf("unexpected error: %v", err)
- }
- if result.SkippedBinaries != 0 {
- t.Errorf("expected no skipped binaries for large text file, got %d", result.SkippedBinaries)
- }
- if result.TotalFiles != 2 {
- t.Errorf("expected 2 files (compose + text), got %d", result.TotalFiles)
- }
+
+ require.NoError(t, err,
+ "unexpected error: %v", err)
+
+ assert.Equal(t, 0, result.SkippedBinaries,
+ "expected no skipped binaries for large text file, got %d", result.SkippedBinaries)
+
+ assert.Equal(t, 2, result.TotalFiles,
+ "expected 2 files (compose + text), got %d", result.TotalFiles)
+
}
func TestWalkDirectory_ComposeInSubdirectory(t *testing.T) {
@@ -552,9 +596,9 @@ func TestWalkDirectory_ComposeInSubdirectory(t *testing.T) {
client := NewClient("")
result, err := client.WalkDirectory(context.Background(), tmpDir, "subdir/docker-compose.yml", 0, 0, 0)
- if err != nil {
- t.Fatalf("unexpected error: %v", err)
- }
+
+ require.NoError(t, err,
+ "unexpected error: %v", err)
paths := make([]string, 0, len(result.Files))
for _, file := range result.Files {
@@ -563,13 +607,15 @@ func TestWalkDirectory_ComposeInSubdirectory(t *testing.T) {
expected := []string{"docker-compose.yml", "dynamic_config.yml"}
if len(paths) != len(expected) {
- t.Fatalf("expected %d files, got %d (%v)", len(expected), len(paths), paths)
+ require.Len(t, paths, len(expected),
+ "expected %d files, got %d (%v)", len(expected), len(paths), paths)
}
for _, want := range expected {
found := slices.Contains(paths, want)
- if !found {
- t.Fatalf("expected walked paths to include %q, got %v", want, paths)
- }
+
+ require.True(t, found,
+ "expected walked paths to include %q, got %v", want, paths)
+
}
}
@@ -580,9 +626,9 @@ func TestWalkDirectory_NestedSiblingFile(t *testing.T) {
client := NewClient("")
result, err := client.WalkDirectory(context.Background(), tmpDir, "subdir/docker-compose.yml", 0, 0, 0)
- if err != nil {
- t.Fatalf("unexpected error: %v", err)
- }
+
+ require.NoError(t, err,
+ "unexpected error: %v", err)
paths := make([]string, 0, len(result.Files))
for _, file := range result.Files {
@@ -591,13 +637,15 @@ func TestWalkDirectory_NestedSiblingFile(t *testing.T) {
expected := []string{"docker-compose.yml", "config/dynamic_config.yml"}
if len(paths) != len(expected) {
- t.Fatalf("expected %d files, got %d (%v)", len(expected), len(paths), paths)
+ require.Len(t, paths, len(expected),
+ "expected %d files, got %d (%v)", len(expected), len(paths), paths)
}
for _, want := range expected {
found := slices.Contains(paths, want)
- if !found {
- t.Fatalf("expected walked paths to include %q, got %v", want, paths)
- }
+
+ require.True(t, found,
+ "expected walked paths to include %q, got %v", want, paths)
+
}
}
@@ -608,9 +656,9 @@ func TestWalkDirectory_SpecialCharsInPath(t *testing.T) {
client := NewClient("")
result, err := client.WalkDirectory(context.Background(), tmpDir, "traefik (nl10)/docker-compose.yml", 0, 0, 0)
- if err != nil {
- t.Fatalf("unexpected error: %v", err)
- }
+
+ require.NoError(t, err,
+ "unexpected error: %v", err)
paths := make([]string, 0, len(result.Files))
for _, file := range result.Files {
@@ -619,13 +667,15 @@ func TestWalkDirectory_SpecialCharsInPath(t *testing.T) {
expected := []string{"docker-compose.yml", "config/dynamic_config.yml"}
if len(paths) != len(expected) {
- t.Fatalf("expected %d files, got %d (%v)", len(expected), len(paths), paths)
+ require.Len(t, paths, len(expected),
+ "expected %d files, got %d (%v)", len(expected), len(paths), paths)
}
for _, want := range expected {
found := slices.Contains(paths, want)
- if !found {
- t.Fatalf("expected walked paths to include %q, got %v", want, paths)
- }
+
+ require.True(t, found,
+ "expected walked paths to include %q, got %v", want, paths)
+
}
}
@@ -647,9 +697,10 @@ func generateTestPublicKey(t *testing.T) gossh.PublicKey {
}
key, err := gossh.ParsePublicKey(pubKeyBytes)
- if err != nil {
- t.Fatalf("failed to parse test public key: %v", err)
- }
+
+ require.NoError(t, err,
+ "failed to parse test public key: %v", err)
+
return key
}
@@ -669,9 +720,10 @@ func generateTestPublicKeyVariant(t *testing.T) gossh.PublicKey {
}
key, err := gossh.ParsePublicKey(pubKeyBytes)
- if err != nil {
- t.Fatalf("failed to parse test public key variant: %v", err)
- }
+
+ require.NoError(t, err,
+ "failed to parse test public key variant: %v", err)
+
return key
}
@@ -699,17 +751,19 @@ func TestNormalizeURL(t *testing.T) {
t.Run(tc.name, func(t *testing.T) {
got, err := normalizeURL(tc.in)
if tc.wantErr {
- if err == nil {
- t.Fatalf("expected error, got %q", got)
- }
+
+ require.Error(t, err,
+ "expected error, got %q", got)
+
return
}
- if err != nil {
- t.Fatalf("unexpected error: %v", err)
- }
- if got != tc.want {
- t.Errorf("expected %q, got %q", tc.want, got)
- }
+
+ require.NoError(t, err,
+ "unexpected error: %v", err)
+
+ assert.Equal(t, tc.want, got,
+ "expected %q, got %q", tc.want, got)
+
})
}
}
diff --git a/backend/pkg/libarcane/edge/client_test.go b/backend/pkg/libarcane/edge/client_test.go
index 199c20264..bd73f8c44 100644
--- a/backend/pkg/libarcane/edge/client_test.go
+++ b/backend/pkg/libarcane/edge/client_test.go
@@ -294,7 +294,7 @@ func TestTunnelClient_WebSocket_ReconnectClosesStreams(t *testing.T) {
select {
case <-firstStreamLive:
case <-time.After(5 * time.Second):
- t.Fatal("timed out waiting for the first stream to come up")
+ require.FailNow(t, "timed out waiting for the first stream to come up")
}
assert.Equal(t, 1, countStreams(), "expected one active stream during the first connection")
@@ -600,8 +600,9 @@ func TestTunnelClient_DialLocalWebSocket_StripsForwardedBrowserHeaders(t *testin
return
}
defer func() { _ = conn.CloseNow() }()
-
- require.NoError(t, conn.Write(r.Context(), websocket.MessageText, []byte("ok")))
+ if !assert.NoError(t, conn.Write(r.Context(), websocket.MessageText, []byte("ok"))) {
+ return
+ }
}))
defer localServer.Close()
@@ -659,7 +660,9 @@ func TestTunnelClient_IsGRPCConnectionInternal(t *testing.T) {
func TestTunnelClient_HandleRequest_GRPCConfigWithWebSocketConnUsesNonStreamingResponse(t *testing.T) {
localHandler := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
- require.Equal(t, "/local/api", r.URL.Path)
+ if !assert.Equal(t, "/local/api", r.URL.Path) {
+ return
+ }
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(http.StatusOK)
_, _ = w.Write([]byte(`{"ok":true}`))
@@ -1107,7 +1110,7 @@ func TestTunnelClient_connectAndServeGRPC_TimesOutWithoutRegisterResponse(t *tes
err := client.connectAndServeGRPC(ctx)
require.Error(t, err)
- assert.ErrorIs(t, err, errTunnelRegistrationTimeout)
+ require.ErrorIs(t, err, errTunnelRegistrationTimeout)
assert.Contains(t, err.Error(), "timed out waiting for tunnel registration response")
assert.Contains(t, err.Error(), "not forwarding gRPC")
assert.EqualValues(t, 1, service.connectCount.Load())
@@ -1161,7 +1164,7 @@ func TestTunnelClient_awaitRegistrationInternal_ClosesAttemptConnWhenClientConnC
select {
case <-firstConn.receiveStarted:
case <-time.After(time.Second):
- t.Fatal("registration receive did not start")
+ require.FailNow(t, "registration receive did not start")
}
client.conn.Store(&connBox{conn: secondConn})
@@ -1172,7 +1175,7 @@ func TestTunnelClient_awaitRegistrationInternal_ClosesAttemptConnWhenClientConnC
require.Nil(t, result.msg)
require.ErrorIs(t, result.err, context.Canceled)
case <-time.After(time.Second):
- t.Fatal("registration did not exit after cancellation")
+ require.FailNow(t, "registration did not exit after cancellation")
}
assert.True(t, firstConn.IsClosed())
@@ -1295,7 +1298,7 @@ func TestTunnelClient_GRPC_WebSocketProxyEndToEnd(t *testing.T) {
msgType, payload, err := proxyConn.Read(ctx)
select {
case upgradeErr := <-upgradeErrCh:
- t.Fatalf("local websocket upgrade failed: %s", upgradeErr)
+ require.FailNowf(t, "unexpected failure", "local websocket upgrade failed: %s", upgradeErr)
default:
}
require.NoError(t, err)
@@ -1306,28 +1309,28 @@ func TestTunnelClient_GRPC_WebSocketProxyEndToEnd(t *testing.T) {
case got := <-pathCh:
assert.Equal(t, "/api/environments/0/ws/system/stats", got)
case <-time.After(2 * time.Second):
- t.Fatal("timeout waiting for forwarded websocket path")
+ require.FailNow(t, "timeout waiting for forwarded websocket path")
}
select {
case got := <-headerTokenCh:
assert.Equal(t, "valid-token", got)
case <-time.After(2 * time.Second):
- t.Fatal("timeout waiting for local websocket auth header")
+ require.FailNow(t, "timeout waiting for local websocket auth header")
}
select {
case got := <-queryCh:
assert.Equal(t, "tail=100", got)
case <-time.After(2 * time.Second):
- t.Fatal("timeout waiting for forwarded query")
+ require.FailNow(t, "timeout waiting for forwarded query")
}
select {
case got := <-receivedMsgCh:
assert.Equal(t, "hello-grpc-ws", got)
case <-time.After(2 * time.Second):
- t.Fatal("timeout waiting for forwarded websocket payload")
+ require.FailNow(t, "timeout waiting for forwarded websocket payload")
}
select {
@@ -1376,7 +1379,7 @@ func TestTunnelClient_connectAndServe_WebSocketConfigFallsBackToWebSocket(t *tes
select {
case <-wsConnectedCh:
case <-time.After(2 * time.Second):
- t.Fatal("expected websocket fallback connection to manager")
+ require.FailNow(t, "expected websocket fallback connection to manager")
}
}
@@ -1417,7 +1420,7 @@ func TestTunnelClient_connectAndServe_AutoFallsBackToWebSocketWhenGRPCUnavailabl
select {
case <-wsConnectedCh:
case <-time.After(2 * time.Second):
- t.Fatal("expected auto transport to fall back to websocket when gRPC is unavailable")
+ require.FailNow(t, "expected auto transport to fall back to websocket when gRPC is unavailable")
}
cancel()
@@ -1425,7 +1428,7 @@ func TestTunnelClient_connectAndServe_AutoFallsBackToWebSocketWhenGRPCUnavailabl
select {
case <-errCh:
case <-time.After(2 * time.Second):
- t.Fatal("timeout waiting for auto fallback tunnel shutdown")
+ require.FailNow(t, "timeout waiting for auto fallback tunnel shutdown")
}
}
@@ -1455,7 +1458,7 @@ func TestTunnelClient_connectAndServe_AutoFallsBackToWebSocketWhenGRPCSetupHangs
select {
case <-wsConnectedCh:
case <-time.After(2 * time.Second):
- t.Fatal("expected auto transport to fall back to websocket when gRPC setup hangs")
+ require.FailNow(t, "expected auto transport to fall back to websocket when gRPC setup hangs")
}
cancel()
@@ -1463,7 +1466,7 @@ func TestTunnelClient_connectAndServe_AutoFallsBackToWebSocketWhenGRPCSetupHangs
select {
case <-errCh:
case <-time.After(2 * time.Second):
- t.Fatal("timeout waiting for auto fallback tunnel shutdown")
+ require.FailNow(t, "timeout waiting for auto fallback tunnel shutdown")
}
}
@@ -1489,7 +1492,7 @@ func TestTunnelClient_connectAndServe_GRPCDoesNotFallbackToWebSocket(t *testing.
select {
case <-wsConnectedCh:
- t.Fatal("explicit gRPC transport should not fall back to websocket")
+ require.FailNow(t, "explicit gRPC transport should not fall back to websocket")
default:
}
}
@@ -1540,9 +1543,9 @@ func TestTunnelClient_connectAndServe_OpensGRPCWhenAvailable(t *testing.T) {
select {
case err := <-errCh:
- assert.ErrorIs(t, err, context.Canceled)
+ require.ErrorIs(t, err, context.Canceled)
case <-time.After(2 * time.Second):
- t.Fatal("timeout waiting for gRPC tunnel shutdown")
+ require.FailNow(t, "timeout waiting for gRPC tunnel shutdown")
}
}
@@ -1626,7 +1629,7 @@ func startHangingTCPServerInternal(t *testing.T, ctx context.Context) (string, f
select {
case <-done:
case <-time.After(2 * time.Second):
- t.Fatal("timeout waiting for hanging TCP server shutdown")
+ require.FailNow(t, "timeout waiting for hanging TCP server shutdown")
}
}
@@ -1761,10 +1764,12 @@ func TestTunnelClient_connectAndServePoll_OpensWebSocketWhenRequired(t *testing.
case "/api/tunnel/poll":
pollCount.Add(1)
w.Header().Set("Content-Type", "application/json")
- require.NoError(t, json.NewEncoder(w).Encode(TunnelPollResponse{
+ if !assert.NoError(t, json.NewEncoder(w).Encode(TunnelPollResponse{
Status: TunnelStatusRequired,
PollIntervalSeconds: 1,
- }))
+ })) {
+ return
+ }
case "/api/tunnel/connect":
conn, err := websocket.Accept(w, r, nil)
if err != nil {
@@ -1809,12 +1814,12 @@ func TestTunnelClient_connectAndServePoll_OpensWebSocketWhenRequired(t *testing.
err := client.connectAndServe(ctx)
require.Error(t, err)
- assert.ErrorIs(t, err, context.DeadlineExceeded)
+ require.ErrorIs(t, err, context.DeadlineExceeded)
select {
case <-wsConnectedCh:
case <-time.After(2 * time.Second):
- t.Fatal("expected poll transport to open websocket tunnel when required")
+ require.FailNow(t, "expected poll transport to open websocket tunnel when required")
}
assert.GreaterOrEqual(t, pollCount.Load(), int32(1))
@@ -1825,10 +1830,12 @@ func TestTunnelClient_pollTunnelControlInternal_UsesConfiguredHTTPClient(t *test
managerServer := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json")
- require.NoError(t, json.NewEncoder(w).Encode(TunnelPollResponse{
+ if !assert.NoError(t, json.NewEncoder(w).Encode(TunnelPollResponse{
Status: TunnelStatusIdle,
PollIntervalSeconds: 1,
- }))
+ })) {
+ return
+ }
}))
defer managerServer.Close()
@@ -1866,10 +1873,12 @@ func TestTunnelClient_connectAndServePoll_DoesNotOpenWebSocketWhenIdle(t *testin
switch r.URL.Path {
case "/api/tunnel/poll":
w.Header().Set("Content-Type", "application/json")
- require.NoError(t, json.NewEncoder(w).Encode(TunnelPollResponse{
+ if !assert.NoError(t, json.NewEncoder(w).Encode(TunnelPollResponse{
Status: TunnelStatusIdle,
PollIntervalSeconds: 1,
- }))
+ })) {
+ return
+ }
case "/api/tunnel/connect":
select {
case wsConnectedCh <- struct{}{}:
@@ -1890,11 +1899,11 @@ func TestTunnelClient_connectAndServePoll_DoesNotOpenWebSocketWhenIdle(t *testin
err := client.connectAndServe(ctx)
require.Error(t, err)
- assert.ErrorIs(t, err, context.DeadlineExceeded)
+ require.ErrorIs(t, err, context.DeadlineExceeded)
select {
case <-wsConnectedCh:
- t.Fatal("did not expect idle poll transport to open websocket tunnel")
+ require.FailNow(t, "did not expect idle poll transport to open websocket tunnel")
default:
}
}
@@ -1916,10 +1925,12 @@ func TestTunnelClient_connectAndServePoll_RetriesAfterTransientPollError(t *test
}
w.Header().Set("Content-Type", "application/json")
- require.NoError(t, json.NewEncoder(w).Encode(TunnelPollResponse{
+ if !assert.NoError(t, json.NewEncoder(w).Encode(TunnelPollResponse{
Status: TunnelStatusRequired,
PollIntervalSeconds: 1,
- }))
+ })) {
+ return
+ }
case "/api/tunnel/connect":
conn, err := websocket.Accept(w, r, nil)
if err != nil {
@@ -1964,12 +1975,12 @@ func TestTunnelClient_connectAndServePoll_RetriesAfterTransientPollError(t *test
err := client.connectAndServe(ctx)
require.Error(t, err)
- assert.ErrorIs(t, err, context.DeadlineExceeded)
+ require.ErrorIs(t, err, context.DeadlineExceeded)
select {
case <-wsConnectedCh:
case <-time.After(2 * time.Second):
- t.Fatal("expected poll transport to recover after transient poll error")
+ require.FailNow(t, "expected poll transport to recover after transient poll error")
}
assert.GreaterOrEqual(t, pollCount.Load(), int32(2))
@@ -2006,7 +2017,7 @@ func TestTunnelClient_syncPollManagedSessionInternal_IdleUsesBoundedStopTimeout(
nextSession, err := (&TunnelClient{}).syncPollManagedSessionInternal(context.Background(), session, TunnelStatusIdle)
require.Same(t, session, nextSession)
require.Error(t, err)
- assert.EqualError(t, err, "timed out waiting for poll-managed websocket session to stop")
+ require.EqualError(t, err, "timed out waiting for poll-managed websocket session to stop")
fencedSession, err := (&TunnelClient{}).syncPollManagedSessionInternal(context.Background(), nextSession, TunnelStatusRequired)
require.NoError(t, err)
@@ -2036,7 +2047,9 @@ func startTestPollAndGRPCManagerInternal(t *testing.T, ctx context.Context, serv
handler := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if r.URL.Path == "/api/tunnel/poll" {
w.Header().Set("Content-Type", "application/json")
- require.NoError(t, json.NewEncoder(w).Encode(pollResp))
+ if !assert.NoError(t, json.NewEncoder(w).Encode(pollResp)) {
+ return
+ }
return
}
@@ -2304,7 +2317,7 @@ func TestConnectAndServeWebSocket_CancelUnblocksMessageLoop(t *testing.T) {
select {
case <-registered:
case <-time.After(5 * time.Second):
- t.Fatal("timed out waiting for registration")
+ require.FailNow(t, "timed out waiting for registration")
}
cancel()
@@ -2313,6 +2326,6 @@ func TestConnectAndServeWebSocket_CancelUnblocksMessageLoop(t *testing.T) {
// Cancellation must close the socket and unblock the message loop well
// under the poll-managed teardown timeout.
case <-time.After(defaultPollManagedSessionStopTimeout):
- t.Fatal("messageLoop did not unblock after context cancellation")
+ require.FailNow(t, "messageLoop did not unblock after context cancellation")
}
}
diff --git a/backend/pkg/libarcane/edge/event_sync_test.go b/backend/pkg/libarcane/edge/event_sync_test.go
index 0114a5edf..f34f25f20 100644
--- a/backend/pkg/libarcane/edge/event_sync_test.go
+++ b/backend/pkg/libarcane/edge/event_sync_test.go
@@ -68,5 +68,5 @@ func TestPublishEventToManager_SendsEventMessage(t *testing.T) {
require.NotNil(t, conn.msgs[0].Event)
assert.Equal(t, "container.start", conn.msgs[0].Event.Type)
assert.Equal(t, "Container started", conn.msgs[0].Event.Title)
- assert.Equal(t, []byte(`{"source":"test"}`), conn.msgs[0].Event.MetadataJSON)
+ assert.JSONEq(t, `{"source":"test"}`, string(conn.msgs[0].Event.MetadataJSON))
}
diff --git a/backend/pkg/libarcane/edge/proxy_test.go b/backend/pkg/libarcane/edge/proxy_test.go
index 7d36511cb..95b55121e 100644
--- a/backend/pkg/libarcane/edge/proxy_test.go
+++ b/backend/pkg/libarcane/edge/proxy_test.go
@@ -294,7 +294,7 @@ func TestCommandRequestFailsWhenTunnelCloses(t *testing.T) {
case err := <-errCh:
require.ErrorContains(t, err, "edge tunnel closed while waiting for response")
case <-time.After(time.Second):
- t.Fatal("pending command did not fail after tunnel close")
+ require.FailNow(t, "pending command did not fail after tunnel close")
}
}
diff --git a/backend/pkg/libarcane/edge/registry_test.go b/backend/pkg/libarcane/edge/registry_test.go
index de442d8da..179c51791 100644
--- a/backend/pkg/libarcane/edge/registry_test.go
+++ b/backend/pkg/libarcane/edge/registry_test.go
@@ -131,7 +131,7 @@ func TestTunnelRegistry_RegisterSessionRejectsCompetingAgent(t *testing.T) {
require.NoError(t, err)
assert.True(t, accepted)
assert.False(t, drainPrevious)
- assert.Equal(t, "", reason)
+ assert.Empty(t, reason)
conn2 := createTestConn(t)
defer func() { _ = conn2.CloseNow() }()
@@ -164,7 +164,7 @@ func TestTunnelRegistry_RegisterSessionReplacesSameAgentInstance(t *testing.T) {
require.NoError(t, err)
assert.True(t, accepted)
assert.False(t, drainPrevious)
- assert.Equal(t, "", reason)
+ assert.Empty(t, reason)
conn2 := createTestConn(t)
defer func() { _ = conn2.CloseNow() }()
@@ -175,7 +175,7 @@ func TestTunnelRegistry_RegisterSessionReplacesSameAgentInstance(t *testing.T) {
require.NoError(t, err)
assert.True(t, accepted)
assert.True(t, drainPrevious)
- assert.Equal(t, "", reason)
+ assert.Empty(t, reason)
assert.True(t, tunnel1.Conn.IsClosed())
got, ok := r.Get(envID).Get()
@@ -212,14 +212,16 @@ func TestActorTunnelRegistryPublishesReplacementBeforeClosingPreviousInternal(t
registered := make(chan bool, 1)
go func() {
accepted, _, _, registerErr := registry.RegisterSession(t.Context(), replacement, TunnelStaleTimeout)
- require.NoError(t, registerErr)
+ if !assert.NoError(t, registerErr) {
+ return
+ }
registered <- accepted
}()
select {
case <-previousConn.closeStarted:
case <-time.After(time.Second):
- t.Fatal("replacement did not begin closing the previous tunnel")
+ require.FailNow(t, "replacement did not begin closing the previous tunnel")
}
active, ok := registry.Get("env-actor-registry").Get()
require.True(t, ok)
diff --git a/backend/pkg/libarcane/edge/server_test.go b/backend/pkg/libarcane/edge/server_test.go
index 93d629539..4e410751c 100644
--- a/backend/pkg/libarcane/edge/server_test.go
+++ b/backend/pkg/libarcane/edge/server_test.go
@@ -90,7 +90,7 @@ func TestTunnelServer_HandleConnect(t *testing.T) {
case <-statusCallbackCalled:
// callback observed
case <-time.After(1 * time.Second):
- t.Fatal("timeout waiting for status callback")
+ require.FailNow(t, "timeout waiting for status callback")
}
// Test Heartbeat
@@ -128,7 +128,7 @@ func TestTunnelServer_HandleConnect(t *testing.T) {
assert.Equal(t, "req-1", received.ID)
assert.Equal(t, []byte("response"), received.Body)
case <-time.After(1 * time.Second):
- t.Fatal("timeout waiting for response")
+ require.FailNow(t, "timeout waiting for response")
}
// Test Stream Delivery
@@ -150,7 +150,7 @@ func TestTunnelServer_HandleConnect(t *testing.T) {
case received := <-streamCh:
assert.Equal(t, "stream-1", received.ID)
case <-time.After(1 * time.Second):
- t.Fatal("timeout waiting for stream")
+ require.FailNow(t, "timeout waiting for stream")
}
// Test Ignored/Unknown Messages
@@ -515,7 +515,7 @@ func TestTokenFromMetadata(t *testing.T) {
})
t.Run("returns empty when metadata missing", func(t *testing.T) {
- assert.Equal(t, "", tokenFromMetadataInternal(context.Background()))
+ assert.Empty(t, tokenFromMetadataInternal(context.Background()))
})
}
@@ -581,7 +581,7 @@ func TestTunnelServer_HandleEventCallback(t *testing.T) {
select {
case <-called:
case <-time.After(2 * time.Second):
- t.Fatal("timeout waiting for event callback")
+ require.FailNow(t, "timeout waiting for event callback")
}
}
diff --git a/backend/pkg/libarcane/edge/tls_test.go b/backend/pkg/libarcane/edge/tls_test.go
index 163ebbfda..e822de6ae 100644
--- a/backend/pkg/libarcane/edge/tls_test.go
+++ b/backend/pkg/libarcane/edge/tls_test.go
@@ -136,7 +136,7 @@ func TestGeneratedClientCertificate_IncludesSANs(t *testing.T) {
require.True(t, cert.NotBefore.Before(cert.NotAfter))
skew := cert.NotAfter.Sub(cert.NotBefore)
- require.True(t, skew > 0)
+ require.Positive(t, skew)
}
func TestEnsureAgentMTLSAssets_RejectsPlainHTTPEnrollment(t *testing.T) {
@@ -507,7 +507,7 @@ func TestCAKey_EncryptedOnDiskWhenCryptoInitialized(t *testing.T) {
raw, err := os.ReadFile(caKeyPath)
require.NoError(t, err)
- require.False(t, strings.Contains(string(raw), "BEGIN EC PRIVATE KEY"),
+ require.NotContains(t, string(raw), "BEGIN EC PRIVATE KEY",
"encrypted CA key file must not contain plain PEM markers")
pemBytes, err := readCAKeyPEMInternal(caKeyPath)
diff --git a/backend/pkg/libarcane/edge/transport_test.go b/backend/pkg/libarcane/edge/transport_test.go
index 2c0fb48dd..53d8166ec 100644
--- a/backend/pkg/libarcane/edge/transport_test.go
+++ b/backend/pkg/libarcane/edge/transport_test.go
@@ -16,6 +16,7 @@ import (
"github.com/coder/websocket/wsjson"
tunnelpb "github.com/getarcaneapp/arcane/backend/v2/proto/tunnel/v1"
"github.com/stretchr/testify/assert"
+ "github.com/stretchr/testify/require"
"google.golang.org/grpc"
"google.golang.org/grpc/credentials/insecure"
)
@@ -67,7 +68,7 @@ func TestGetActiveTunnelTransport(t *testing.T) {
t.Run("returns false when tunnel is missing", func(t *testing.T) {
transport, ok := GetActiveTunnelTransport("env-missing").Get()
assert.False(t, ok)
- assert.Equal(t, "", transport)
+ assert.Empty(t, transport)
})
t.Run("detects grpc tunnel", func(t *testing.T) {
@@ -110,7 +111,7 @@ func TestGetActiveTunnelTransport(t *testing.T) {
transport, ok := GetActiveTunnelTransport(envID).Get()
assert.False(t, ok)
- assert.Equal(t, "", transport)
+ assert.Empty(t, transport)
})
t.Run("returns false for unknown transport implementation", func(t *testing.T) {
@@ -123,7 +124,7 @@ func TestGetActiveTunnelTransport(t *testing.T) {
transport, ok := GetActiveTunnelTransport(envID).Get()
assert.False(t, ok)
- assert.Equal(t, "", transport)
+ assert.Empty(t, transport)
})
}
@@ -226,14 +227,16 @@ func runProxyRequestBenchmark(b *testing.B, tunnel *AgentTunnel, payloadSize int
for b.Loop() {
statusCode, _, respBody, err := ProxyRequest(ctx, tunnel, http.MethodPost, "/api/environments/0/images/upload", "", headers, body)
- if err != nil {
- b.Fatalf("proxy request failed: %v", err)
- }
- if statusCode != http.StatusOK {
- b.Fatalf("unexpected status code: %d", statusCode)
- }
+
+ require.NoError(b, err,
+ "proxy request failed: %v", err)
+
+ require.Equal(b, http.StatusOK, statusCode,
+ "unexpected status code: %d", statusCode)
+
if len(respBody) != payloadSize {
- b.Fatalf("unexpected response length: got %d want %d", len(respBody), payloadSize)
+ require.Len(b, respBody, payloadSize,
+ "unexpected response length: got %d want %d", len(respBody), payloadSize)
}
}
}
@@ -259,7 +262,7 @@ func setupGRPCBenchmarkTunnel(b *testing.B, payloadSize int) (*AgentTunnel, func
if err != nil {
cancel()
tunnelServer.WaitForCleanupDone()
- b.Fatalf("failed to create gRPC client: %v", err)
+ require.FailNowf(b, "unexpected failure", "failed to create gRPC client: %v", err)
}
client := tunnelpb.NewTunnelServiceClient(conn)
@@ -268,7 +271,7 @@ func setupGRPCBenchmarkTunnel(b *testing.B, payloadSize int) (*AgentTunnel, func
_ = conn.Close()
cancel()
tunnelServer.WaitForCleanupDone()
- b.Fatalf("failed to open gRPC stream: %v", err)
+ require.FailNowf(b, "unexpected failure", "failed to open gRPC stream: %v", err)
}
if err := stream.Send(&tunnelpb.AgentMessage{
@@ -279,14 +282,14 @@ func setupGRPCBenchmarkTunnel(b *testing.B, payloadSize int) (*AgentTunnel, func
_ = conn.Close()
cancel()
tunnelServer.WaitForCleanupDone()
- b.Fatalf("failed to send register message: %v", err)
+ require.FailNowf(b, "unexpected failure", "failed to send register message: %v", err)
}
if _, err := stream.Recv(); err != nil {
_ = conn.Close()
cancel()
tunnelServer.WaitForCleanupDone()
- b.Fatalf("failed to receive register response: %v", err)
+ require.FailNowf(b, "unexpected failure", "failed to receive register response: %v", err)
}
responseBody := make([]byte, payloadSize)
@@ -368,7 +371,7 @@ func setupWebSocketBenchmarkTunnel(b *testing.B, payloadSize int) (*AgentTunnel,
conn, _, err := websocket.Dial(context.Background(), wsURL, nil)
if err != nil {
server.Close()
- b.Fatalf("failed to dial websocket server: %v", err)
+ require.FailNowf(b, "unexpected failure", "failed to dial websocket server: %v", err)
}
tunnel := NewAgentTunnelWithConn("bench-websocket", NewTunnelConn(conn))
@@ -405,7 +408,6 @@ func waitForBenchmarkTunnel(b *testing.B, envID string) *AgentTunnel {
}
time.Sleep(10 * time.Millisecond)
}
-
- b.Fatalf("timed out waiting for tunnel registration for env %s", envID)
+ require.FailNowf(b, "unexpected failure", "timed out waiting for tunnel registration for env %s", envID)
return nil
}
diff --git a/backend/pkg/libarcane/edge/tunnel_test.go b/backend/pkg/libarcane/edge/tunnel_test.go
index 727adea28..52223683b 100644
--- a/backend/pkg/libarcane/edge/tunnel_test.go
+++ b/backend/pkg/libarcane/edge/tunnel_test.go
@@ -114,7 +114,7 @@ func TestGRPCManagerTunnelConn_CloseCancelsReceive(t *testing.T) {
select {
case <-stream.recvStarted:
case <-time.After(time.Second):
- t.Fatal("timed out waiting for stream recv start")
+ require.FailNow(t, "timed out waiting for stream recv start")
}
require.NoError(t, conn.Close())
@@ -122,9 +122,9 @@ func TestGRPCManagerTunnelConn_CloseCancelsReceive(t *testing.T) {
select {
case err := <-errCh:
require.Error(t, err)
- assert.ErrorIs(t, err, context.Canceled)
+ require.ErrorIs(t, err, context.Canceled)
case <-time.After(time.Second):
- t.Fatal("timed out waiting for receive to unblock")
+ require.FailNow(t, "timed out waiting for receive to unblock")
}
}
@@ -171,7 +171,7 @@ func TestTunnelConn_CloseSendsCloseFrame(t *testing.T) {
assert.Equal(t, websocket.StatusNormalClosure, websocket.CloseStatus(err),
"peer should observe a normal closure, got: %v", err)
case <-time.After(5 * time.Second):
- t.Fatal("timed out waiting for peer read to return")
+ require.FailNow(t, "timed out waiting for peer read to return")
}
}
diff --git a/backend/pkg/libarcane/edge/ws_proxy_test.go b/backend/pkg/libarcane/edge/ws_proxy_test.go
index 29a0b1475..c8a90c899 100644
--- a/backend/pkg/libarcane/edge/ws_proxy_test.go
+++ b/backend/pkg/libarcane/edge/ws_proxy_test.go
@@ -261,7 +261,9 @@ func TestHandleAgentMessage_StreamDataPreservesTextFrame(t *testing.T) {
serverConnCh := make(chan *websocket.Conn, 1)
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
conn, err := websocket.Accept(w, r, nil)
- require.NoError(t, err)
+ if !assert.NoError(t, err) {
+ return
+ }
serverConnCh <- conn
}))
defer server.Close()
diff --git a/backend/pkg/libarcane/inspect_compat_test.go b/backend/pkg/libarcane/inspect_compat_test.go
index 38717bc15..0bce8d1db 100644
--- a/backend/pkg/libarcane/inspect_compat_test.go
+++ b/backend/pkg/libarcane/inspect_compat_test.go
@@ -94,10 +94,10 @@ func TestNormalizeContainerInspectRawJSONInternal_NormalizesTopLevelNetworkSetti
require.True(t, ok)
assert.Equal(t, "172.18.0.1", networkSettings["Gateway"])
assert.Equal(t, "172.18.0.20", networkSettings["IPAddress"])
- assert.Equal(t, float64(16), networkSettings["IPPrefixLen"])
+ assert.InDelta(t, float64(16), networkSettings["IPPrefixLen"], 0.000001)
assert.Equal(t, "fdd0:0:0:c::1", networkSettings["IPv6Gateway"])
assert.Equal(t, "fdd0:0:0:c::10", networkSettings["GlobalIPv6Address"])
- assert.Equal(t, float64(64), networkSettings["GlobalIPv6PrefixLen"])
+ assert.InDelta(t, float64(64), networkSettings["GlobalIPv6PrefixLen"], 0.000001)
}
func TestNormalizeNetworkInspectRawJSONInternal(t *testing.T) {
@@ -312,7 +312,7 @@ func TestNetworkListWithCompatibility(t *testing.T) {
dockerClient := newTestDockerClient(t, func(w http.ResponseWriter, r *http.Request) {
callCount++
assert.Equal(t, "/v1.41/networks", r.URL.Path)
- assert.Equal(t, `{"name":{"test-net":true}}`, r.URL.Query().Get("filters"))
+ assert.JSONEq(t, `{"name":{"test-net":true}}`, r.URL.Query().Get("filters"))
_, _ = w.Write([]byte(networkJSON))
})
@@ -413,7 +413,7 @@ func TestInspectCompatibilityLeavesInvalidValuesFailing(t *testing.T) {
_, err := NetworkInspectWithCompatibility(context.Background(), dockerClient, "test-net", client.NetworkInspectOptions{})
require.Error(t, err)
- assert.True(t, strings.Contains(err.Error(), `ParseAddr("definitely-not-an-ip")`))
+ assert.Contains(t, err.Error(), `ParseAddr("definitely-not-an-ip")`)
}
func TestNetworkListWithCompatibility_LeavesInvalidValuesFailing(t *testing.T) {
@@ -435,7 +435,7 @@ func TestNetworkListWithCompatibility_LeavesInvalidValuesFailing(t *testing.T) {
_, err := NetworkListWithCompatibility(context.Background(), dockerClient, client.NetworkListOptions{})
require.Error(t, err)
- assert.True(t, strings.Contains(err.Error(), `ParseAddr("definitely-not-an-ip")`))
+ assert.Contains(t, err.Error(), `ParseAddr("definitely-not-an-ip")`)
assert.Equal(t, 2, callCount)
}
@@ -497,8 +497,12 @@ func TestWrapDockerAPIClientForInspectCompatibility_ContainerCreateLegacyNetwork
switch {
case r.Method == http.MethodPost && strings.HasSuffix(r.URL.Path, "/containers/create"):
body, err := io.ReadAll(r.Body)
- require.NoError(t, err)
- require.NoError(t, json.Unmarshal(body, &createPayload))
+ if !assert.NoError(t, err) {
+ return
+ }
+ if !assert.NoError(t, json.Unmarshal(body, &createPayload)) {
+ return
+ }
w.Header().Set("Content-Type", "application/json")
_, _ = w.Write([]byte(`{"Id":"new-container-id","Warnings":[]}`))
case r.Method == http.MethodPost && strings.Contains(r.URL.Path, "/networks/") && strings.HasSuffix(r.URL.Path, "/connect"):
@@ -506,14 +510,20 @@ func TestWrapDockerAPIClientForInspectCompatibility_ContainerCreateLegacyNetwork
networkName = strings.TrimSuffix(networkName, "/connect")
networkName = networkName[strings.LastIndex(networkName, "/networks/")+len("/networks/"):]
body, err := io.ReadAll(r.Body)
- require.NoError(t, err)
+ if !assert.NoError(t, err) {
+ return
+ }
var payload connectRequest
- require.NoError(t, json.Unmarshal(body, &payload))
+ if !assert.NoError(t, json.Unmarshal(body, &payload)) {
+ return
+ }
connectPayloads[networkName] = payload
w.WriteHeader(http.StatusOK)
default:
- t.Fatalf("unexpected request: %s %s", r.Method, r.URL.Path)
+ if !assert.Failf(t, "unexpected failure", "unexpected request: %s %s", r.Method, r.URL.Path) {
+ return
+ }
}
})
diff --git a/backend/pkg/libarcane/startup/runtime_identity_test.go b/backend/pkg/libarcane/startup/runtime_identity_test.go
index 15f46a766..92b054978 100644
--- a/backend/pkg/libarcane/startup/runtime_identity_test.go
+++ b/backend/pkg/libarcane/startup/runtime_identity_test.go
@@ -277,7 +277,7 @@ func TestEnsureRuntimeDockerConfigCreatesCustomDirectory(t *testing.T) {
require.NoError(t, ensureRuntimeDockerConfigInternal(
cfg,
func(string, string) error {
- t.Fatal("setenv should not be called for explicit DOCKER_CONFIG")
+ require.FailNow(t, "setenv should not be called for explicit DOCKER_CONFIG")
return nil
},
1001,
diff --git a/backend/pkg/libarcane/volumehelper/helper_test.go b/backend/pkg/libarcane/volumehelper/helper_test.go
index c7a59acb3..79f973860 100644
--- a/backend/pkg/libarcane/volumehelper/helper_test.go
+++ b/backend/pkg/libarcane/volumehelper/helper_test.go
@@ -12,6 +12,7 @@ import (
"github.com/getarcaneapp/arcane/backend/v2/pkg/libarcane"
"github.com/moby/moby/api/types/container"
"github.com/moby/moby/client"
+ "github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
@@ -29,7 +30,9 @@ func TestResolveHelperImage_UsesLocalToolsImage(t *testing.T) {
switch {
case r.Method == http.MethodGet && strings.Contains(r.URL.Path, "/images/") && strings.HasSuffix(r.URL.Path, "/json"):
w.Header().Set("Content-Type", "application/json")
- require.NoError(t, json.NewEncoder(w).Encode(map[string]any{"Id": "tools-image"}))
+ if !assert.NoError(t, json.NewEncoder(w).Encode(map[string]any{"Id": "tools-image"})) {
+ return
+ }
case r.Method == http.MethodPost && strings.HasSuffix(r.URL.Path, "/images/create"):
pullCalls.Add(1)
http.Error(w, "unexpected pull", http.StatusInternalServerError)
@@ -54,11 +57,17 @@ func TestResolveHelperImage_PullsToolsImageWhenMissing(t *testing.T) {
http.NotFound(w, r)
case r.Method == http.MethodPost && strings.HasSuffix(r.URL.Path, "/images/create"):
pullCalls.Add(1)
- require.Equal(t, "ghcr.io/getarcaneapp/tools", r.URL.Query().Get("fromImage"))
- require.Equal(t, "latest", r.URL.Query().Get("tag"))
+ if !assert.Equal(t, "ghcr.io/getarcaneapp/tools", r.URL.Query().Get("fromImage")) {
+ return
+ }
+ if !assert.Equal(t, "latest", r.URL.Query().Get("tag")) {
+ return
+ }
w.Header().Set("Content-Type", "application/json")
_, err := w.Write([]byte(`{"status":"pulled"}` + "\n"))
- require.NoError(t, err)
+ if !assert.NoError(t, err) {
+ return
+ }
default:
http.NotFound(w, r)
}
@@ -81,17 +90,21 @@ func TestResolveHelperImage_FallsBackToArcaneRuntimeWhenToolsPullFails(t *testin
http.Error(w, "pull failed", http.StatusInternalServerError)
case r.Method == http.MethodGet && strings.HasSuffix(r.URL.Path, "/containers/json"):
w.Header().Set("Content-Type", "application/json")
- require.NoError(t, json.NewEncoder(w).Encode([]container.Summary{
+ if !assert.NoError(t, json.NewEncoder(w).Encode([]container.Summary{
{ID: "arcane-container", Image: "arcane:local", State: container.StateRunning},
- }))
+ })) {
+ return
+ }
case r.Method == http.MethodGet && strings.Contains(r.URL.Path, "/containers/arcane-container/") && strings.HasSuffix(r.URL.Path, "/json"):
w.Header().Set("Content-Type", "application/json")
- require.NoError(t, json.NewEncoder(w).Encode(container.InspectResponse{
+ if !assert.NoError(t, json.NewEncoder(w).Encode(container.InspectResponse{
ID: "arcane-container",
Config: &container.Config{
Image: "arcane:local",
},
- }))
+ })) {
+ return
+ }
default:
http.NotFound(w, r)
}
@@ -113,7 +126,9 @@ func TestResolveHelperImage_ReturnsPullErrorWhenNoFallbackExists(t *testing.T) {
http.Error(w, "pull failed", http.StatusInternalServerError)
case r.Method == http.MethodGet && strings.HasSuffix(r.URL.Path, "/containers/json"):
w.Header().Set("Content-Type", "application/json")
- require.NoError(t, json.NewEncoder(w).Encode([]container.Summary{}))
+ if !assert.NoError(t, json.NewEncoder(w).Encode([]container.Summary{})) {
+ return
+ }
default:
http.NotFound(w, r)
}
diff --git a/backend/pkg/libarcane/volumes/volume_rename_followup_test.go b/backend/pkg/libarcane/volumes/volume_rename_followup_test.go
index d37f2d8d1..7e2601c16 100644
--- a/backend/pkg/libarcane/volumes/volume_rename_followup_test.go
+++ b/backend/pkg/libarcane/volumes/volume_rename_followup_test.go
@@ -9,6 +9,7 @@ import (
"sync/atomic"
"testing"
+ "github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
@@ -21,7 +22,9 @@ func TestDockerProjectVolumeRenameMigrationInternal_RollbackExplainsPreservedTar
http.NotFound(w, r)
case r.Method == http.MethodGet && strings.HasSuffix(r.URL.Path, "/volumes/web_data"):
w.Header().Set("Content-Type", "application/json")
- require.NoError(t, json.NewEncoder(w).Encode(map[string]any{"Name": "web_data"}))
+ if !assert.NoError(t, json.NewEncoder(w).Encode(map[string]any{"Name": "web_data"})) {
+ return
+ }
case r.Method == http.MethodDelete && strings.HasSuffix(r.URL.Path, "/volumes/web_data"):
targetRemoved.Store(true)
w.WriteHeader(http.StatusNoContent)
@@ -55,7 +58,9 @@ func TestRollbackVolume_ExplainsPreservedTargetWhenSourceMissing(t *testing.T) {
http.NotFound(w, r)
case r.Method == http.MethodGet && strings.HasSuffix(r.URL.Path, "/volumes/web_data"):
w.Header().Set("Content-Type", "application/json")
- require.NoError(t, json.NewEncoder(w).Encode(map[string]any{"Name": "web_data"}))
+ if !assert.NoError(t, json.NewEncoder(w).Encode(map[string]any{"Name": "web_data"})) {
+ return
+ }
default:
http.NotFound(w, r)
}
diff --git a/backend/pkg/libarcane/volumes/volume_rename_runtime_test.go b/backend/pkg/libarcane/volumes/volume_rename_runtime_test.go
index 24c71644d..825f49075 100644
--- a/backend/pkg/libarcane/volumes/volume_rename_runtime_test.go
+++ b/backend/pkg/libarcane/volumes/volume_rename_runtime_test.go
@@ -9,6 +9,7 @@ import (
"testing"
"github.com/getarcaneapp/arcane/backend/v2/pkg/libarcane/volumehelper"
+ "github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
@@ -17,7 +18,9 @@ func TestGetProjectVolumeCopyRuntimeInternal_UsesToolsImageWhenAvailable(t *test
switch {
case r.Method == http.MethodGet && strings.Contains(r.URL.Path, "/images/") && strings.HasSuffix(r.URL.Path, "/json"):
w.Header().Set("Content-Type", "application/json")
- require.NoError(t, json.NewEncoder(w).Encode(map[string]any{"Id": "tools-image"}))
+ if !assert.NoError(t, json.NewEncoder(w).Encode(map[string]any{"Id": "tools-image"})) {
+ return
+ }
default:
http.NotFound(w, r)
}
@@ -35,12 +38,16 @@ func TestCreateProjectVolumeCopyHolderContainerInternal_UsesPassiveHolderCommand
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
switch {
case r.Method == http.MethodPost && strings.HasSuffix(r.URL.Path, "/containers/create"):
- require.NoError(t, json.NewDecoder(r.Body).Decode(&createBody))
+ if !assert.NoError(t, json.NewDecoder(r.Body).Decode(&createBody)) {
+ return
+ }
w.Header().Set("Content-Type", "application/json")
- require.NoError(t, json.NewEncoder(w).Encode(map[string]any{
+ if !assert.NoError(t, json.NewEncoder(w).Encode(map[string]any{
"Id": "helper-container",
"Warnings": []string{},
- }))
+ })) {
+ return
+ }
case r.Method == http.MethodDelete && strings.Contains(r.URL.Path, "/containers/helper-container"):
w.WriteHeader(http.StatusNoContent)
default:
diff --git a/backend/pkg/libarcane/volumes/volume_rename_safety_test.go b/backend/pkg/libarcane/volumes/volume_rename_safety_test.go
index 4266d8da5..08597701e 100644
--- a/backend/pkg/libarcane/volumes/volume_rename_safety_test.go
+++ b/backend/pkg/libarcane/volumes/volume_rename_safety_test.go
@@ -13,6 +13,7 @@ import (
"github.com/moby/moby/api/types/container"
"github.com/moby/moby/api/types/mount"
+ "github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
@@ -26,9 +27,11 @@ func TestEnsureProjectRenameTargetVolumeAbsentInternal_ReturnsConflictWhenTarget
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if strings.HasSuffix(r.URL.Path, "/volumes/web_data") {
w.Header().Set("Content-Type", "application/json")
- require.NoError(t, json.NewEncoder(w).Encode(map[string]any{
+ if !assert.NoError(t, json.NewEncoder(w).Encode(map[string]any{
"Name": "web_data",
- }))
+ })) {
+ return
+ }
return
}
http.NotFound(w, r)
@@ -48,14 +51,16 @@ func TestEnsureProjectRenameSourceVolumeDetachedInternal_ReturnsConflictWhenCont
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if strings.HasSuffix(r.URL.Path, "/containers/json") {
w.Header().Set("Content-Type", "application/json")
- require.NoError(t, json.NewEncoder(w).Encode([]container.Summary{
+ if !assert.NoError(t, json.NewEncoder(w).Encode([]container.Summary{
{
ID: "stopped-container",
Mounts: []container.MountPoint{
{Type: mount.TypeVolume, Name: "nginx_data"},
},
},
- }))
+ })) {
+ return
+ }
return
}
http.NotFound(w, r)
@@ -80,25 +85,31 @@ func TestGetProjectVolumeCopyRuntimeInternal_UsesArcaneAgentLabel(t *testing.T)
case strings.HasSuffix(r.URL.Path, "/containers/json"):
w.Header().Set("Content-Type", "application/json")
if listCalls.Add(1) == 1 {
- require.NoError(t, json.NewEncoder(w).Encode([]container.Summary{}))
+ if !assert.NoError(t, json.NewEncoder(w).Encode([]container.Summary{})) {
+ return
+ }
return
}
- require.NoError(t, json.NewEncoder(w).Encode([]container.Summary{
+ if !assert.NoError(t, json.NewEncoder(w).Encode([]container.Summary{
{
ID: "agent-container",
Image: "arcane-agent:local",
State: container.StateRunning,
},
- }))
+ })) {
+ return
+ }
case strings.Contains(r.URL.Path, "/containers/agent-container/") && strings.HasSuffix(r.URL.Path, "/json"):
w.Header().Set("Content-Type", "application/json")
- require.NoError(t, json.NewEncoder(w).Encode(container.InspectResponse{
+ if !assert.NoError(t, json.NewEncoder(w).Encode(container.InspectResponse{
ID: "agent-container",
Config: &container.Config{
Image: "arcane-agent:local",
Cmd: []string{"./arcane-agent"},
},
- }))
+ })) {
+ return
+ }
default:
http.NotFound(w, r)
}
@@ -120,7 +131,9 @@ func TestDockerProjectVolumeRenameMigrationInternal_RollbackPreservesTargetWhenS
http.NotFound(w, r)
case r.Method == http.MethodGet && strings.HasSuffix(r.URL.Path, "/volumes/web_data"):
w.Header().Set("Content-Type", "application/json")
- require.NoError(t, json.NewEncoder(w).Encode(map[string]any{"Name": "web_data"}))
+ if !assert.NoError(t, json.NewEncoder(w).Encode(map[string]any{"Name": "web_data"})) {
+ return
+ }
case r.Method == http.MethodDelete && strings.HasSuffix(r.URL.Path, "/volumes/web_data"):
targetRemoved.Store(true)
w.WriteHeader(http.StatusNoContent)
@@ -162,13 +175,19 @@ func TestDockerProjectVolumeRenameMigrationInternal_RollbackCleansSafeTargetsWhe
http.NotFound(w, r)
case r.Method == http.MethodGet && strings.HasSuffix(r.URL.Path, "/volumes/web_data"):
w.Header().Set("Content-Type", "application/json")
- require.NoError(t, json.NewEncoder(w).Encode(map[string]any{"Name": "web_data"}))
+ if !assert.NoError(t, json.NewEncoder(w).Encode(map[string]any{"Name": "web_data"})) {
+ return
+ }
case r.Method == http.MethodGet && strings.HasSuffix(r.URL.Path, "/volumes/nginx_cache"):
w.Header().Set("Content-Type", "application/json")
- require.NoError(t, json.NewEncoder(w).Encode(map[string]any{"Name": "nginx_cache"}))
+ if !assert.NoError(t, json.NewEncoder(w).Encode(map[string]any{"Name": "nginx_cache"})) {
+ return
+ }
case r.Method == http.MethodGet && strings.HasSuffix(r.URL.Path, "/containers/json"):
w.Header().Set("Content-Type", "application/json")
- require.NoError(t, json.NewEncoder(w).Encode([]container.Summary{}))
+ if !assert.NoError(t, json.NewEncoder(w).Encode([]container.Summary{})) {
+ return
+ }
case r.Method == http.MethodDelete && strings.HasSuffix(r.URL.Path, "/volumes/web_data"):
preservedTargetRemoved.Store(true)
w.WriteHeader(http.StatusNoContent)
@@ -215,10 +234,14 @@ func TestDockerProjectVolumeRenameMigrationInternal_RollbackPreservesTargetWhenS
http.Error(w, "temporary docker error", http.StatusInternalServerError)
case r.Method == http.MethodGet && strings.HasSuffix(r.URL.Path, "/volumes/nginx_cache"):
w.Header().Set("Content-Type", "application/json")
- require.NoError(t, json.NewEncoder(w).Encode(map[string]any{"Name": "nginx_cache"}))
+ if !assert.NoError(t, json.NewEncoder(w).Encode(map[string]any{"Name": "nginx_cache"})) {
+ return
+ }
case r.Method == http.MethodGet && strings.HasSuffix(r.URL.Path, "/containers/json"):
w.Header().Set("Content-Type", "application/json")
- require.NoError(t, json.NewEncoder(w).Encode([]container.Summary{}))
+ if !assert.NoError(t, json.NewEncoder(w).Encode([]container.Summary{})) {
+ return
+ }
case r.Method == http.MethodDelete && strings.HasSuffix(r.URL.Path, "/volumes/web_data"):
preservedTargetRemoved.Store(true)
w.WriteHeader(http.StatusNoContent)
@@ -261,10 +284,14 @@ func TestDockerProjectVolumeRenameMigrationInternal_RollbackPreservesTargetWhenT
http.Error(w, "temporary docker error", http.StatusInternalServerError)
case r.Method == http.MethodGet && strings.HasSuffix(r.URL.Path, "/volumes/nginx_cache"):
w.Header().Set("Content-Type", "application/json")
- require.NoError(t, json.NewEncoder(w).Encode(map[string]any{"Name": "nginx_cache"}))
+ if !assert.NoError(t, json.NewEncoder(w).Encode(map[string]any{"Name": "nginx_cache"})) {
+ return
+ }
case r.Method == http.MethodGet && strings.HasSuffix(r.URL.Path, "/containers/json"):
w.Header().Set("Content-Type", "application/json")
- require.NoError(t, json.NewEncoder(w).Encode([]container.Summary{}))
+ if !assert.NoError(t, json.NewEncoder(w).Encode([]container.Summary{})) {
+ return
+ }
case r.Method == http.MethodDelete && strings.HasSuffix(r.URL.Path, "/volumes/web_data"):
preservedTargetRemoved.Store(true)
w.WriteHeader(http.StatusNoContent)
@@ -302,10 +329,14 @@ func TestDockerProjectVolumeRenameMigrationInternal_RollbackRemovesTargetsWhenSo
switch {
case r.Method == http.MethodGet && strings.HasSuffix(r.URL.Path, "/volumes/nginx_data"):
w.Header().Set("Content-Type", "application/json")
- require.NoError(t, json.NewEncoder(w).Encode(map[string]any{"Name": "nginx_data"}))
+ if !assert.NoError(t, json.NewEncoder(w).Encode(map[string]any{"Name": "nginx_data"})) {
+ return
+ }
case r.Method == http.MethodGet && strings.HasSuffix(r.URL.Path, "/containers/json"):
w.Header().Set("Content-Type", "application/json")
- require.NoError(t, json.NewEncoder(w).Encode([]container.Summary{}))
+ if !assert.NoError(t, json.NewEncoder(w).Encode([]container.Summary{})) {
+ return
+ }
case r.Method == http.MethodDelete && strings.Contains(r.URL.Path, "/containers/copy-holder-"):
w.WriteHeader(http.StatusNoContent)
case r.Method == http.MethodDelete && strings.HasSuffix(r.URL.Path, "/volumes/web_data"):
@@ -381,16 +412,24 @@ func TestDockerProjectVolumeRenameMigrationInternal_RollbackAfterPartialCommitCl
switch {
case r.Method == http.MethodGet && strings.HasSuffix(r.URL.Path, "/volumes/web_data"):
w.Header().Set("Content-Type", "application/json")
- require.NoError(t, json.NewEncoder(w).Encode(map[string]any{"Name": "web_data"}))
+ if !assert.NoError(t, json.NewEncoder(w).Encode(map[string]any{"Name": "web_data"})) {
+ return
+ }
case r.Method == http.MethodGet && strings.HasSuffix(r.URL.Path, "/volumes/web_cache"):
w.Header().Set("Content-Type", "application/json")
- require.NoError(t, json.NewEncoder(w).Encode(map[string]any{"Name": "web_cache"}))
+ if !assert.NoError(t, json.NewEncoder(w).Encode(map[string]any{"Name": "web_cache"})) {
+ return
+ }
case r.Method == http.MethodGet && strings.HasSuffix(r.URL.Path, "/volumes/nginx_cache"):
w.Header().Set("Content-Type", "application/json")
- require.NoError(t, json.NewEncoder(w).Encode(map[string]any{"Name": "nginx_cache"}))
+ if !assert.NoError(t, json.NewEncoder(w).Encode(map[string]any{"Name": "nginx_cache"})) {
+ return
+ }
case r.Method == http.MethodGet && strings.HasSuffix(r.URL.Path, "/containers/json"):
w.Header().Set("Content-Type", "application/json")
- require.NoError(t, json.NewEncoder(w).Encode([]container.Summary{}))
+ if !assert.NoError(t, json.NewEncoder(w).Encode([]container.Summary{})) {
+ return
+ }
case r.Method == http.MethodDelete && strings.HasSuffix(r.URL.Path, "/volumes/nginx_data"):
firstSourceRemoved.Store(true)
w.WriteHeader(http.StatusNoContent)
@@ -446,12 +485,16 @@ func TestDockerProjectVolumeRenameMigrationInternal_CommitPreflightsAllTargetsBe
switch {
case r.Method == http.MethodGet && strings.HasSuffix(r.URL.Path, "/volumes/web_data"):
w.Header().Set("Content-Type", "application/json")
- require.NoError(t, json.NewEncoder(w).Encode(map[string]any{"Name": "web_data"}))
+ if !assert.NoError(t, json.NewEncoder(w).Encode(map[string]any{"Name": "web_data"})) {
+ return
+ }
case r.Method == http.MethodGet && strings.HasSuffix(r.URL.Path, "/volumes/web_cache"):
http.NotFound(w, r)
case r.Method == http.MethodGet && strings.HasSuffix(r.URL.Path, "/volumes/nginx_cache"):
w.Header().Set("Content-Type", "application/json")
- require.NoError(t, json.NewEncoder(w).Encode(map[string]any{"Name": "nginx_cache"}))
+ if !assert.NoError(t, json.NewEncoder(w).Encode(map[string]any{"Name": "nginx_cache"})) {
+ return
+ }
case r.Method == http.MethodDelete && strings.HasSuffix(r.URL.Path, "/volumes/nginx_data"):
firstSourceRemoved.Store(true)
w.WriteHeader(http.StatusNoContent)
diff --git a/backend/pkg/libarcane/volumes/volume_rename_test.go b/backend/pkg/libarcane/volumes/volume_rename_test.go
index 08f999e2c..e62507e34 100644
--- a/backend/pkg/libarcane/volumes/volume_rename_test.go
+++ b/backend/pkg/libarcane/volumes/volume_rename_test.go
@@ -13,6 +13,7 @@ import (
"github.com/getarcaneapp/arcane/backend/v2/pkg/libarcane"
"github.com/moby/moby/api/types/container"
"github.com/moby/moby/api/types/volume"
+ "github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
@@ -59,9 +60,13 @@ func TestCreateProjectRenamedVolumeInternal_UsesPendingComposeDriverOptions(t *t
var payload map[string]any
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if r.Method == http.MethodPost && strings.HasSuffix(r.URL.Path, "/volumes/create") {
- require.NoError(t, json.NewDecoder(r.Body).Decode(&payload))
+ if !assert.NoError(t, json.NewDecoder(r.Body).Decode(&payload)) {
+ return
+ }
w.Header().Set("Content-Type", "application/json")
- require.NoError(t, json.NewEncoder(w).Encode(volume.Volume{Name: "web_data"}))
+ if !assert.NoError(t, json.NewEncoder(w).Encode(volume.Volume{Name: "web_data"})) {
+ return
+ }
return
}
http.NotFound(w, r)
diff --git a/backend/pkg/libarcane/vuln/trivy_test.go b/backend/pkg/libarcane/vuln/trivy_test.go
index 871c8119a..782565398 100644
--- a/backend/pkg/libarcane/vuln/trivy_test.go
+++ b/backend/pkg/libarcane/vuln/trivy_test.go
@@ -10,7 +10,7 @@ import (
)
func TestParseVersion(t *testing.T) {
- require.Equal(t, "", ParseVersion(""))
+ require.Empty(t, ParseVersion(""))
require.Equal(t, "0.50.1", ParseVersion("Version: 0.50.1\nVulnerability DB:\n Version: 2"))
require.Equal(t, "raw-output", ParseVersion("raw-output"))
}
diff --git a/backend/pkg/libarcane/ws/benchmark_test.go b/backend/pkg/libarcane/ws/benchmark_test.go
index e25190788..949be08d9 100644
--- a/backend/pkg/libarcane/ws/benchmark_test.go
+++ b/backend/pkg/libarcane/ws/benchmark_test.go
@@ -11,10 +11,12 @@ import (
"time"
"github.com/coder/websocket"
+ "github.com/stretchr/testify/require"
)
// benchWSServer creates a test WebSocket server for benchmarks.
// The server keeps connections open until the returned cleanup is called.
+
func benchWSServer(b *testing.B) (url string, cleanup func()) {
b.Helper()
@@ -59,7 +61,7 @@ func benchHub(b *testing.B, numClients int, hubBuf int) (*Hub, context.CancelFun
for range numClients {
conn, _, err := websocket.Dial(ctx, wsURL, nil)
if err != nil {
- b.Fatal(err)
+ require.FailNowf(b, "benchmark websocket dial failed", "%v", err)
}
conns = append(conns, conn)
@@ -198,7 +200,7 @@ func BenchmarkLogMessage_Marshal(b *testing.B) {
for b.Loop() {
if _, err := json.Marshal(msg); err != nil {
- b.Fatal(err)
+ require.FailNowf(b, "benchmark JSON marshal failed", "%v", err)
}
}
}
@@ -223,7 +225,7 @@ func BenchmarkLogMessageBatch_Marshal(b *testing.B) {
for b.Loop() {
if _, err := json.Marshal(batch); err != nil {
- b.Fatal(err)
+ require.FailNowf(b, "benchmark JSON marshal failed", "%v", err)
}
}
})
@@ -301,7 +303,7 @@ func BenchmarkHub_MemoryPerClient(b *testing.B) {
for b.Loop() {
conn, _, err := websocket.Dial(ctx, wsURL, nil)
if err != nil {
- b.Fatal(err)
+ require.FailNowf(b, "benchmark websocket dial failed", "%v", err)
}
c := NewClient(conn, sendBuf)
h.register <- c
diff --git a/backend/pkg/libarcane/ws/bridge_test.go b/backend/pkg/libarcane/ws/bridge_test.go
index a325bbeaa..91ea5fa22 100644
--- a/backend/pkg/libarcane/ws/bridge_test.go
+++ b/backend/pkg/libarcane/ws/bridge_test.go
@@ -37,7 +37,7 @@ func drainClient(t *testing.T, c *Client, count int, timeout time.Duration) [][]
case msg := <-c.send:
msgs = append(msgs, msg)
case <-deadline:
- t.Fatalf("timed out waiting for messages, got %d/%d", len(msgs), count)
+ require.FailNowf(t, "unexpected failure", "timed out waiting for messages, got %d/%d", len(msgs), count)
}
}
return msgs
@@ -85,7 +85,7 @@ func TestForwardLines_ContextCancellation(t *testing.T) {
case <-done:
// ForwardLines exited as expected
case <-time.After(time.Second):
- t.Fatal("ForwardLines did not exit after context cancellation")
+ require.FailNow(t, "ForwardLines did not exit after context cancellation")
}
}
@@ -285,7 +285,7 @@ func TestForwardLogJSONBatched_FlushesOnContextCancel(t *testing.T) {
select {
case <-done:
case <-time.After(2 * time.Second):
- t.Fatal("ForwardLogJSONBatched did not exit after context cancellation")
+ require.FailNow(t, "ForwardLogJSONBatched did not exit after context cancellation")
}
// The buffered message should have been flushed
diff --git a/backend/pkg/libarcane/ws/client_test.go b/backend/pkg/libarcane/ws/client_test.go
index d98a1d5ca..a984a288a 100644
--- a/backend/pkg/libarcane/ws/client_test.go
+++ b/backend/pkg/libarcane/ws/client_test.go
@@ -271,7 +271,7 @@ func TestServeClient_StoppedHubDoesNotBlock(t *testing.T) {
case registered := <-done:
assert.False(t, registered, "registration against a stopped hub must fail")
case <-time.After(2 * time.Second):
- t.Fatal("ServeClientWithOnRemove blocked on a stopped hub")
+ require.FailNow(t, "ServeClientWithOnRemove blocked on a stopped hub")
}
// The caller owns the connection and its bookkeeping on failure, so it can
diff --git a/backend/pkg/libarcane/ws/cpu_regression_test.go b/backend/pkg/libarcane/ws/cpu_regression_test.go
index a407174b7..2e5186bce 100644
--- a/backend/pkg/libarcane/ws/cpu_regression_test.go
+++ b/backend/pkg/libarcane/ws/cpu_regression_test.go
@@ -113,7 +113,7 @@ func BenchmarkCPU_PageReloadSimulation(b *testing.B) {
for i := range b.N {
conn, _, err := websocket.Dial(b.Context(), url, nil)
if err != nil {
- b.Fatal(err)
+ require.FailNowf(b, "benchmark websocket dial failed", "%v", err)
}
// Read one message to exercise the pipeline
@@ -200,7 +200,7 @@ func BenchmarkCPU_ContainerLogReloadSimulation(b *testing.B) {
for i := range b.N {
conn, _, err := websocket.Dial(b.Context(), url, nil)
if err != nil {
- b.Fatal(err)
+ require.FailNowf(b, "benchmark websocket dial failed", "%v", err)
}
_ = readOneWithTimeout(conn, 2*time.Second)
@@ -253,7 +253,7 @@ func BenchmarkCPU_GoroutineScaling(b *testing.B) {
for j := range concurrency {
conn, _, err := websocket.Dial(b.Context(), url, nil)
if err != nil {
- b.Fatal(err)
+ require.FailNowf(b, "benchmark websocket dial failed", "%v", err)
}
conns[j] = conn
}
@@ -303,7 +303,7 @@ func BenchmarkCPU_SustainedStreaming(b *testing.B) {
for b.Loop() {
conn, _, err := websocket.Dial(b.Context(), url, nil)
if err != nil {
- b.Fatal(err)
+ require.FailNowf(b, "benchmark websocket dial failed", "%v", err)
}
for range 10 {
if err := readOneWithTimeout(conn, 2*time.Second); err != nil {
diff --git a/backend/pkg/libarcane/ws/hub_test.go b/backend/pkg/libarcane/ws/hub_test.go
index 1151169a6..d2907f5d2 100644
--- a/backend/pkg/libarcane/ws/hub_test.go
+++ b/backend/pkg/libarcane/ws/hub_test.go
@@ -113,7 +113,7 @@ func TestHub_Broadcast(t *testing.T) {
case received := <-c.send:
assert.Equal(t, msg, received)
case <-time.After(time.Second):
- t.Fatal("timed out waiting for broadcast message")
+ require.FailNow(t, "timed out waiting for broadcast message")
}
}
@@ -150,7 +150,7 @@ func TestHub_BroadcastToMultipleClients(t *testing.T) {
case received := <-c.send:
assert.Equal(t, msg, received, "client %d did not receive expected message", i)
case <-time.After(time.Second):
- t.Fatalf("client %d timed out waiting for broadcast message", i)
+ require.FailNowf(t, "unexpected failure", "client %d timed out waiting for broadcast message", i)
}
}
}
@@ -300,7 +300,7 @@ func TestHub_ContextCancellation(t *testing.T) {
case <-done:
// Hub exited as expected
case <-time.After(2 * time.Second):
- t.Fatal("Hub.Run did not exit after context cancellation")
+ require.FailNow(t, "Hub.Run did not exit after context cancellation")
}
// After closeAll, clients map should be empty
diff --git a/backend/pkg/libarcane/ws/proxy_test.go b/backend/pkg/libarcane/ws/proxy_test.go
index fa0310e59..5a36f1c85 100644
--- a/backend/pkg/libarcane/ws/proxy_test.go
+++ b/backend/pkg/libarcane/ws/proxy_test.go
@@ -108,7 +108,7 @@ func TestProxyHTTP_RemoteClose(t *testing.T) {
case <-proxyDone:
// OK
case <-time.After(5 * time.Second):
- t.Fatal("ProxyHTTP did not return after remote closed")
+ require.FailNow(t, "ProxyHTTP did not return after remote closed")
}
}
@@ -130,7 +130,7 @@ func TestProxyHTTP_InvalidRemoteURL(t *testing.T) {
case err := <-proxyDone:
require.Error(t, err, "ProxyHTTP should return error when remote is unreachable")
case <-time.After(50 * time.Second):
- t.Fatal("ProxyHTTP did not return after failed dial")
+ require.FailNow(t, "ProxyHTTP did not return after failed dial")
}
}
@@ -217,6 +217,6 @@ func TestProxyHTTP_HeadersForwarded(t *testing.T) {
assert.Equal(t, "test-value", receivedHeaders.Get("X-Custom-Header"))
assert.Equal(t, "Bearer token123", receivedHeaders.Get("Authorization"))
case <-time.After(2 * time.Second):
- t.Fatal("timed out waiting for headers")
+ require.FailNow(t, "timed out waiting for headers")
}
}
diff --git a/backend/pkg/projects/env_test.go b/backend/pkg/projects/env_test.go
index c069673fc..fad093b0a 100644
--- a/backend/pkg/projects/env_test.go
+++ b/backend/pkg/projects/env_test.go
@@ -202,7 +202,7 @@ func TestBuildOverrideEnvContent(t *testing.T) {
override, err := BuildOverrideEnvContent(gitContent, effectiveContent)
require.NoError(t, err)
- assert.Equal(t, "", override)
+ assert.Empty(t, override)
})
t.Run("drops empty overrides for git-backed keys during normalization", func(t *testing.T) {
diff --git a/backend/pkg/projects/fs_templates_test.go b/backend/pkg/projects/fs_templates_test.go
index 53efc4a16..f37d441cb 100644
--- a/backend/pkg/projects/fs_templates_test.go
+++ b/backend/pkg/projects/fs_templates_test.go
@@ -3,7 +3,6 @@ package projects
import (
"os"
"path/filepath"
- "strings"
"testing"
"github.com/stretchr/testify/assert"
@@ -39,7 +38,7 @@ func TestReadFolderComposeTemplate_DetectsAllVariants(t *testing.T) {
require.True(t, found, "expected template to be detected for %s", tc.fileName)
assert.Equal(t, composeContent, content)
assert.Nil(t, env)
- assert.True(t, strings.Contains(desc, tc.fileName), "description should reference detected filename, got %q", desc)
+ assert.Contains(t, desc, tc.fileName, "description should reference detected filename, got %q", desc)
})
}
}
diff --git a/backend/pkg/projects/includes_test.go b/backend/pkg/projects/includes_test.go
index d40c1a919..026853355 100644
--- a/backend/pkg/projects/includes_test.go
+++ b/backend/pkg/projects/includes_test.go
@@ -7,6 +7,8 @@ import (
"testing"
pkgutils "github.com/getarcaneapp/arcane/backend/v2/pkg/utils"
+ "github.com/stretchr/testify/assert"
+ "github.com/stretchr/testify/require"
)
func TestParseIncludes_NormalizesRelativePaths(t *testing.T) {
@@ -18,9 +20,10 @@ func TestParseIncludes_NormalizesRelativePaths(t *testing.T) {
requireNoError := func(err error) {
t.Helper()
- if err != nil {
- t.Fatalf("unexpected error: %v", err)
- }
+
+ require.NoError(t, err,
+ "unexpected error: %v", err)
+
}
requireNoError(os.MkdirAll(filepath.Dir(includePath), 0o755))
@@ -30,13 +33,12 @@ func TestParseIncludes_NormalizesRelativePaths(t *testing.T) {
includes, err := ParseIncludes(composePath, nil, false)
requireNoError(err)
- if len(includes) != 1 {
- t.Fatalf("expected 1 include, got %d", len(includes))
- }
+ require.Len(t, includes, 1,
+ "expected 1 include, got %d", len(includes))
+
+ require.Equal(t, "includes/config.yaml", includes[0].RelativePath,
+ "unexpected relative path: got %q, want %q", includes[0].RelativePath, "includes/config.yaml")
- if includes[0].RelativePath != "includes/config.yaml" {
- t.Fatalf("unexpected relative path: got %q, want %q", includes[0].RelativePath, "includes/config.yaml")
- }
}
func TestParseIncludes_ExpandsArrayPathForm(t *testing.T) {
@@ -47,9 +49,10 @@ func TestParseIncludes_ExpandsArrayPathForm(t *testing.T) {
requireNoError := func(err error) {
t.Helper()
- if err != nil {
- t.Fatalf("unexpected error: %v", err)
- }
+
+ require.NoError(t, err,
+ "unexpected error: %v", err)
+
}
requireNoError(os.WriteFile(composePath, []byte("include:\n - path:\n - ./base.yaml\n - ./override.yaml\n"), 0o600))
@@ -57,12 +60,12 @@ func TestParseIncludes_ExpandsArrayPathForm(t *testing.T) {
includes, err := ParseIncludes(composePath, nil, false)
requireNoError(err)
- if len(includes) != 2 {
- t.Fatalf("expected 2 includes, got %d", len(includes))
- }
- if includes[0].RelativePath != "base.yaml" || includes[1].RelativePath != "override.yaml" {
- t.Fatalf("unexpected relative paths: %q, %q", includes[0].RelativePath, includes[1].RelativePath)
- }
+ require.Len(t, includes, 2,
+ "expected 2 includes, got %d", len(includes))
+
+ require.False(t, includes[0].RelativePath != "base.yaml" || includes[1].RelativePath != "override.yaml",
+ "unexpected relative paths: %q, %q", includes[0].RelativePath, includes[1].RelativePath)
+
}
func TestWriteIncludeFilePermissions(t *testing.T) {
@@ -81,30 +84,33 @@ func TestWriteIncludeFilePermissions(t *testing.T) {
t.Run("Uses custom permissions", func(t *testing.T) {
pkgutils.FilePerm = 0o600
pkgutils.DirPerm = 0o700
+ {
- if err := WriteIncludeFile(projectDir, includePath, content); err != nil {
- t.Fatalf("WriteIncludeFile() returned error: %v", err)
+ err := WriteIncludeFile(projectDir, includePath, content)
+ require.NoError(t, err,
+ "WriteIncludeFile() returned error: %v", err)
}
targetPath := filepath.Join(projectDir, includePath)
info, err := os.Stat(targetPath)
- if err != nil {
- t.Fatalf("failed to stat include file: %v", err)
- }
+
+ require.NoError(t, err,
+ "failed to stat include file: %v", err)
// On Linux/macOS, we can check permissions. On Windows, it's more limited.
if runtime.GOOS != "windows" {
- if info.Mode().Perm() != 0o600 {
- t.Errorf("unexpected file permissions: got %o, want %o", info.Mode().Perm(), 0o600)
- }
+
+ assert.Equal(t, os.FileMode(0o600), info.Mode().Perm(),
+ "unexpected file permissions: got %o, want %o", info.Mode().Perm(), 0o600)
dirInfo, err := os.Stat(filepath.Dir(targetPath))
- if err != nil {
- t.Fatalf("failed to stat include directory: %v", err)
- }
- if dirInfo.Mode().Perm() != 0o700 {
- t.Errorf("unexpected directory permissions: got %o, want %o", dirInfo.Mode().Perm(), 0o700)
- }
+
+ require.NoError(t, err,
+ "failed to stat include directory: %v", err)
+
+ assert.Equal(t, os.FileMode(0o700), dirInfo.Mode().Perm(),
+ "unexpected directory permissions: got %o, want %o", dirInfo.Mode().Perm(), 0o700)
+
}
})
}
@@ -115,20 +121,22 @@ func TestWriteIncludeFileCreatesSafeDirectory(t *testing.T) {
projectDir := t.TempDir()
includePath := filepath.Join("includes", "config.yaml")
content := "services: {}\n"
+ {
- if err := WriteIncludeFile(projectDir, includePath, content); err != nil {
- t.Fatalf("WriteIncludeFile() returned error: %v", err)
+ err := WriteIncludeFile(projectDir, includePath, content)
+ require.NoError(t, err,
+ "WriteIncludeFile() returned error: %v", err)
}
targetPath := filepath.Join(projectDir, includePath)
data, err := os.ReadFile(targetPath)
- if err != nil {
- t.Fatalf("failed to read include file: %v", err)
- }
- if string(data) != content {
- t.Fatalf("unexpected file content: got %q, want %q", string(data), content)
- }
+ require.NoError(t, err,
+ "failed to read include file: %v", err)
+
+ require.Equal(t, content, string(data),
+ "unexpected file content: got %q, want %q", string(data), content)
+
}
func TestWriteIncludeFileRejectsSymlinkEscape(t *testing.T) {
@@ -141,13 +149,16 @@ func TestWriteIncludeFileRejectsSymlinkEscape(t *testing.T) {
outsideDir := t.TempDir()
linkPath := filepath.Join(projectDir, "link")
- if err := os.Symlink(outsideDir, linkPath); err != nil {
- t.Fatalf("failed to create symlink: %v", err)
+ {
+ err := os.Symlink(outsideDir, linkPath)
+ require.NoError(t, err,
+ "failed to create symlink: %v", err)
}
includePath := filepath.Join("link", "escape.yaml")
err := WriteIncludeFile(projectDir, includePath, "malicious: true\n")
- if err == nil {
- t.Fatalf("WriteIncludeFile() succeeded but expected rejection for symlink escape")
- }
+
+ require.Error(t, err,
+ "WriteIncludeFile() succeeded but expected rejection for symlink escape")
+
}
diff --git a/backend/pkg/projects/name_test.go b/backend/pkg/projects/name_test.go
index d791f48f7..426b5ccb9 100644
--- a/backend/pkg/projects/name_test.go
+++ b/backend/pkg/projects/name_test.go
@@ -1,6 +1,11 @@
package projects
-import "testing"
+import (
+ "testing"
+
+ "github.com/stretchr/testify/assert"
+ "github.com/stretchr/testify/require"
+)
func TestComposeContentProjectName(t *testing.T) {
tests := []struct {
@@ -16,9 +21,12 @@ func TestComposeContentProjectName(t *testing.T) {
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
- if got := ComposeContentProjectName(tt.content); got != tt.want {
- t.Errorf("ComposeContentProjectName() = %q, want %q", got, tt.want)
+ {
+ got := ComposeContentProjectName(tt.content)
+ assert.Equal(t, tt.want, got,
+ "ComposeContentProjectName() = %q, want %q", got, tt.want)
}
+
})
}
}
@@ -49,9 +57,10 @@ func TestNormalizeProjectName(t *testing.T) {
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
got := NormalizeProjectName(tt.input)
- if got != tt.expected {
- t.Fatalf("NormalizeProjectName() = %q, want %q", got, tt.expected)
- }
+
+ require.Equal(t, tt.expected, got,
+ "NormalizeProjectName() = %q, want %q", got, tt.expected)
+
})
}
}
diff --git a/backend/pkg/projects/project_files_test.go b/backend/pkg/projects/project_files_test.go
index 900b820ae..29064bcb8 100644
--- a/backend/pkg/projects/project_files_test.go
+++ b/backend/pkg/projects/project_files_test.go
@@ -1,7 +1,6 @@
package projects
import (
- "errors"
"fmt"
"os"
"path/filepath"
@@ -145,7 +144,7 @@ func TestApplyProjectFileChanges_WrapsForbiddenSentinelErrors(t *testing.T) {
{Operation: "delete", RelativePath: "compose.yaml"},
}, ProjectFileApplyOptions{ComposeFileName: "compose.yaml"})
require.Error(t, err)
- assert.ErrorIs(t, err, ErrProjectFileProtectedPath)
+ require.ErrorIs(t, err, ErrProjectFileProtectedPath)
targetPath := filepath.Join(projectDir, "target.txt")
linkPath := filepath.Join(projectDir, "link.txt")
@@ -159,7 +158,7 @@ func TestApplyProjectFileChanges_WrapsForbiddenSentinelErrors(t *testing.T) {
{Operation: "update_file", RelativePath: "link.txt", Content: &content},
}, ProjectFileApplyOptions{ComposeFileName: "compose.yaml"})
require.Error(t, err)
- assert.ErrorIs(t, err, ErrProjectFileSymlinkPath)
+ require.ErrorIs(t, err, ErrProjectFileSymlinkPath)
outsideDir := t.TempDir()
require.NoError(t, os.WriteFile(filepath.Join(outsideDir, "outside.txt"), []byte("outside\n"), 0o644))
@@ -194,7 +193,7 @@ func TestApplyProjectFileChanges_UsesRevisionConflictDetection(t *testing.T) {
})
require.Error(t, err)
- assert.True(t, errors.Is(err, ErrProjectFileRevisionConflict))
+ assert.ErrorIs(t, err, ErrProjectFileRevisionConflict)
}
func TestApplyProjectFileChanges_AppliesOrderedTextFileOperations(t *testing.T) {
diff --git a/backend/pkg/projects/pull_policy_test.go b/backend/pkg/projects/pull_policy_test.go
index 5b3fc53cf..d938a28f8 100644
--- a/backend/pkg/projects/pull_policy_test.go
+++ b/backend/pkg/projects/pull_policy_test.go
@@ -91,7 +91,7 @@ func TestBuildProjectImagePullPlan(t *testing.T) {
func TestNormalizePullPolicy(t *testing.T) {
assert.Equal(t, "missing", NormalizePullPolicy("if_not_present"))
assert.Equal(t, "build", NormalizePullPolicy(" BUILD "))
- assert.Equal(t, "", NormalizePullPolicy(""))
+ assert.Empty(t, NormalizePullPolicy(""))
}
func TestDecideDeployImageAction(t *testing.T) {
diff --git a/backend/pkg/remenv/client_test.go b/backend/pkg/remenv/client_test.go
index b7228d0f5..8e218ba7c 100644
--- a/backend/pkg/remenv/client_test.go
+++ b/backend/pkg/remenv/client_test.go
@@ -7,6 +7,7 @@ import (
"net/http/httptest"
"testing"
+ "github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
@@ -36,9 +37,15 @@ func TestRedactedTokenFingerprint(t *testing.T) {
func TestClientDo_DirectHTTPSuccess(t *testing.T) {
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
- require.Equal(t, http.MethodPost, r.Method)
- require.Equal(t, "/api/registries/sync", r.URL.Path)
- require.Equal(t, "application/json", r.Header.Get("Content-Type"))
+ if !assert.Equal(t, http.MethodPost, r.Method) {
+ return
+ }
+ if !assert.Equal(t, "/api/registries/sync", r.URL.Path) {
+ return
+ }
+ if !assert.Equal(t, "application/json", r.Header.Get("Content-Type")) {
+ return
+ }
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(http.StatusAccepted)
_, _ = w.Write([]byte(`{"ok":true}`))
diff --git a/backend/pkg/scheduler/analytics_job_test.go b/backend/pkg/scheduler/analytics_job_test.go
index 576f26ec4..46229dcb1 100644
--- a/backend/pkg/scheduler/analytics_job_test.go
+++ b/backend/pkg/scheduler/analytics_job_test.go
@@ -19,6 +19,7 @@ import (
"github.com/getarcaneapp/arcane/backend/v2/internal/database"
"github.com/getarcaneapp/arcane/backend/v2/internal/models"
"github.com/getarcaneapp/arcane/backend/v2/internal/services"
+ "github.com/stretchr/testify/assert"
)
func setupAnalyticsStateServicesInternal(t *testing.T) (*database.DB, *services.SettingsService, *services.KVService) {
@@ -45,9 +46,10 @@ func newHeartbeatServer(t *testing.T) (*httptest.Server, <-chan []byte, *atomic.
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
requestCount.Add(1)
body, err := io.ReadAll(r.Body)
- if err != nil {
- t.Errorf("failed to read heartbeat body: %v", err)
- }
+
+ assert.NoError(t, err,
+ "failed to read heartbeat body: %v", err)
+
bodyCh <- body
w.WriteHeader(http.StatusOK)
}))
@@ -71,7 +73,7 @@ func TestAnalyticsJob_Run_ManagerPayload(t *testing.T) {
select {
case body = <-bodyCh:
default:
- t.Fatal("expected heartbeat request")
+ require.FailNow(t, "expected heartbeat request")
}
var payload map[string]any
@@ -97,7 +99,7 @@ func TestAnalyticsJob_Run_AgentPayload(t *testing.T) {
select {
case body = <-bodyCh:
default:
- t.Fatal("expected heartbeat request")
+ require.FailNow(t, "expected heartbeat request")
}
var payload map[string]any
@@ -119,7 +121,7 @@ func TestAnalyticsJob_Run_SkipsWhenDisabled(t *testing.T) {
select {
case <-bodyCh:
- t.Fatal("unexpected heartbeat request")
+ require.FailNow(t, "unexpected heartbeat request")
default:
}
}
@@ -138,7 +140,7 @@ func TestAnalyticsJob_Run_SkipsWhenTestEnv(t *testing.T) {
select {
case <-bodyCh:
- t.Fatal("unexpected heartbeat request")
+ require.FailNow(t, "unexpected heartbeat request")
default:
}
}
diff --git a/backend/pkg/scheduler/auto_heal_job_test.go b/backend/pkg/scheduler/auto_heal_job_test.go
index dcd6e9766..925a6dee5 100644
--- a/backend/pkg/scheduler/auto_heal_job_test.go
+++ b/backend/pkg/scheduler/auto_heal_job_test.go
@@ -256,6 +256,6 @@ func TestAutoHealJob_OverlappingRunIsSkippedInternal(t *testing.T) {
select {
case <-firstDone:
case <-time.After(time.Second):
- t.Fatal("first auto-heal run did not finish")
+ require.FailNow(t, "first auto-heal run did not finish")
}
}
diff --git a/backend/pkg/scheduler/auto_update_job_test.go b/backend/pkg/scheduler/auto_update_job_test.go
index 11dc38a5c..2c57b2180 100644
--- a/backend/pkg/scheduler/auto_update_job_test.go
+++ b/backend/pkg/scheduler/auto_update_job_test.go
@@ -70,7 +70,7 @@ func TestAutoUpdateJob_OverlappingRunIsSkippedInternal(t *testing.T) {
select {
case <-firstDone:
case <-time.After(time.Second):
- t.Fatal("first auto-update run did not finish")
+ require.FailNow(t, "first auto-update run did not finish")
}
// The guard resets once the run finishes.
diff --git a/backend/pkg/scheduler/image_update_watcher_test.go b/backend/pkg/scheduler/image_update_watcher_test.go
index 896e0be83..df6c1d7e4 100644
--- a/backend/pkg/scheduler/image_update_watcher_test.go
+++ b/backend/pkg/scheduler/image_update_watcher_test.go
@@ -5,7 +5,6 @@ import (
"context"
"fmt"
"log/slog"
- "strings"
"sync"
"testing"
"time"
@@ -489,9 +488,9 @@ func TestImageUpdateWatcher_BackfillGatesFirstScanAndCoalescesEventBurst(t *test
require.Equal(t, 1, scanner.countInternal())
logs := logBuffer.stringInternal()
- require.True(t, strings.Contains(logs, "project image metadata backfill completed"), logs)
- require.True(t, strings.Contains(logs, "projects=2500"), logs)
- require.True(t, strings.Contains(logs, "duration="), logs)
+ require.Contains(t, logs, "project image metadata backfill completed", logs)
+ require.Contains(t, logs, "projects=2500", logs)
+ require.Contains(t, logs, "duration=", logs)
t.Logf("coalesced %d image events into one scan after backfilling %d projects in %s", eventCount, projectCount, time.Since(burstStartedAt))
}
@@ -538,7 +537,7 @@ func TestImageUpdateWatcher_BackfillFailureRetriesBeforeScanning(t *testing.T) {
select {
case <-secondAttemptStarted:
case <-time.After(time.Second):
- t.Fatal("backfill was not retried")
+ require.FailNow(t, "backfill was not retried")
}
require.Zero(t, scanner.countInternal())
close(releaseSecondAttempt)
@@ -569,7 +568,7 @@ func TestImageUpdateWatcher_CancellationStopsBackfillWithoutScanning(t *testing.
case err := <-errCh:
require.NoError(t, err)
case <-time.After(time.Second):
- t.Fatal("watcher did not stop after cancellation")
+ require.FailNow(t, "watcher did not stop after cancellation")
}
require.Zero(t, scanner.countInternal())
}
diff --git a/backend/pkg/scheduler/job_schedule_integration_test.go b/backend/pkg/scheduler/job_schedule_integration_test.go
index b4ccd5d1e..15e33253e 100644
--- a/backend/pkg/scheduler/job_schedule_integration_test.go
+++ b/backend/pkg/scheduler/job_schedule_integration_test.go
@@ -134,7 +134,6 @@ func findJobStatusInternal(t *testing.T, jobs *jobschedule.JobListResponse, jobI
return job
}
}
-
- t.Fatalf("job %q not found", jobID)
+ require.FailNowf(t, "unexpected failure", "job %q not found", jobID)
return jobschedule.JobStatus{}
}
diff --git a/backend/pkg/scheduler/scheduler_test.go b/backend/pkg/scheduler/scheduler_test.go
index e5716e65c..13fd2884f 100644
--- a/backend/pkg/scheduler/scheduler_test.go
+++ b/backend/pkg/scheduler/scheduler_test.go
@@ -148,7 +148,7 @@ func TestJobScheduler_StopWaitsForBusWatchers(t *testing.T) {
select {
case <-watcher.started:
case <-time.After(time.Second):
- t.Fatal("timed out waiting for bus watcher to start")
+ require.FailNow(t, "timed out waiting for bus watcher to start")
}
stopDone := make(chan error, 1)
@@ -158,13 +158,13 @@ func TestJobScheduler_StopWaitsForBusWatchers(t *testing.T) {
select {
case <-watcher.stopped:
case <-time.After(time.Second):
- t.Fatal("timed out waiting for bus watcher to stop")
+ require.FailNow(t, "timed out waiting for bus watcher to stop")
}
select {
case err := <-stopDone:
require.NoError(t, err)
case <-time.After(time.Second):
- t.Fatal("scheduler did not stop after bus watcher finished")
+ require.FailNow(t, "scheduler did not stop after bus watcher finished")
}
}
@@ -180,7 +180,7 @@ func TestJobScheduler_StopJoinsRunnerBeforeStoppingWatcher(t *testing.T) {
select {
case <-watcher.started:
case <-time.After(time.Second):
- t.Fatal("timed out waiting for bus watcher to start")
+ require.FailNow(t, "timed out waiting for bus watcher to start")
}
require.NoError(t, js.Stop(t.Context()))
}
@@ -303,7 +303,7 @@ func TestJobScheduler_RescheduleJob_UsesProvidedContext(t *testing.T) {
case err := <-runErrCh:
require.NoError(t, err)
case <-time.After(2500 * time.Millisecond):
- t.Fatal("timed out waiting for scheduled run")
+ require.FailNow(t, "timed out waiting for scheduled run")
}
}
@@ -336,7 +336,7 @@ func TestJobScheduler_RescheduleJob_UsesLifecycleContextForShutdown(t *testing.T
select {
case <-startedCh:
case <-time.After(2500 * time.Millisecond):
- t.Fatal("timed out waiting for scheduled run")
+ require.FailNow(t, "timed out waiting for scheduled run")
}
cancelLifecycle()
@@ -344,7 +344,7 @@ func TestJobScheduler_RescheduleJob_UsesLifecycleContextForShutdown(t *testing.T
select {
case <-stoppedCh:
case <-time.After(1500 * time.Millisecond):
- t.Fatal("scheduled job did not observe lifecycle cancellation")
+ require.FailNow(t, "scheduled job did not observe lifecycle cancellation")
}
}
@@ -456,14 +456,14 @@ func TestJobScheduler_StopWaitsForCanceledJobToFinish(t *testing.T) {
select {
case <-jobStarted:
case <-time.After(2500 * time.Millisecond):
- t.Fatal("timed out waiting for scheduled job to start")
+ require.FailNow(t, "timed out waiting for scheduled job to start")
}
cancelLifecycle()
select {
case <-cancellationObserved:
case <-time.After(time.Second):
- t.Fatal("scheduled job did not observe lifecycle cancellation")
+ require.FailNow(t, "scheduled job did not observe lifecycle cancellation")
}
stopDone := make(chan error, 1)
@@ -471,7 +471,7 @@ func TestJobScheduler_StopWaitsForCanceledJobToFinish(t *testing.T) {
select {
case err := <-stopDone:
- t.Fatalf("scheduler stopped before the running job finished: %v", err)
+ require.FailNowf(t, "unexpected failure", "scheduler stopped before the running job finished: %v", err)
case <-time.After(100 * time.Millisecond):
}
@@ -479,12 +479,12 @@ func TestJobScheduler_StopWaitsForCanceledJobToFinish(t *testing.T) {
select {
case <-jobFinished:
case <-time.After(time.Second):
- t.Fatal("scheduled job did not finish after release")
+ require.FailNow(t, "scheduled job did not finish after release")
}
select {
case err := <-stopDone:
require.NoError(t, err)
case <-time.After(time.Second):
- t.Fatal("scheduler did not stop after the running job finished")
+ require.FailNow(t, "scheduler did not stop after the running job finished")
}
}
diff --git a/backend/pkg/utils/httpx/request_test.go b/backend/pkg/utils/httpx/request_test.go
index e2a99d94e..bb0650267 100644
--- a/backend/pkg/utils/httpx/request_test.go
+++ b/backend/pkg/utils/httpx/request_test.go
@@ -3,6 +3,8 @@ package httpx
import (
"net/http/httptest"
"testing"
+
+ "github.com/stretchr/testify/assert"
)
func TestIsWebSocketUpgradeRequest(t *testing.T) {
@@ -29,9 +31,12 @@ func TestIsWebSocketUpgradeRequest(t *testing.T) {
if tt.upgrade != "" {
r.Header.Set("Upgrade", tt.upgrade)
}
- if got := IsWebSocketUpgradeRequest(r); got != tt.want {
- t.Errorf("IsWebSocketUpgradeRequest() = %v, want %v", got, tt.want)
+ {
+ got := IsWebSocketUpgradeRequest(r)
+ assert.Equal(t, tt.want, got,
+ "IsWebSocketUpgradeRequest() = %v, want %v", got, tt.want)
}
+
})
}
}
diff --git a/backend/pkg/utils/keyedmutex_test.go b/backend/pkg/utils/keyedmutex_test.go
index 843ffaa85..d2d4cc2da 100644
--- a/backend/pkg/utils/keyedmutex_test.go
+++ b/backend/pkg/utils/keyedmutex_test.go
@@ -44,8 +44,10 @@ func TestKeyedMutexTryLockDoesNotBlockOnHeldKey(t *testing.T) {
var locks KeyedMutex
unlock := locks.Lock("a")
- if _, ok := locks.TryLock("a"); ok {
- t.Fatal("TryLock acquired a key that is already held")
+ {
+ _, ok := locks.TryLock("a")
+ require.False(t, ok,
+ "TryLock acquired a key that is already held")
}
// A different key is unaffected.
diff --git a/backend/pkg/utils/validation/email_test.go b/backend/pkg/utils/validation/email_test.go
index 96228472e..ef78b7610 100644
--- a/backend/pkg/utils/validation/email_test.go
+++ b/backend/pkg/utils/validation/email_test.go
@@ -1,6 +1,10 @@
package validation
-import "testing"
+import (
+ "testing"
+
+ "github.com/stretchr/testify/require"
+)
func TestIsValidUserEmail_AllowsReportedFormats(t *testing.T) {
t.Parallel()
@@ -15,9 +19,10 @@ func TestIsValidUserEmail_AllowsReportedFormats(t *testing.T) {
for _, email := range validEmails {
t.Run(email, func(t *testing.T) {
t.Parallel()
- if !IsValidUserEmail(email) {
- t.Fatalf("expected %q to be valid", email)
- }
+
+ require.True(t, IsValidUserEmail(email),
+ "expected %q to be valid", email)
+
})
}
}
@@ -43,9 +48,10 @@ func TestIsValidUserEmail_RejectsMalformedAddresses(t *testing.T) {
for _, email := range invalidEmails {
t.Run(email, func(t *testing.T) {
t.Parallel()
- if IsValidUserEmail(email) {
- t.Fatalf("expected %q to be invalid", email)
- }
+
+ require.False(t, IsValidUserEmail(email),
+ "expected %q to be invalid", email)
+
})
}
}
diff --git a/cli/internal/benchmark/baseline_benchmark_test.go b/cli/internal/benchmark/baseline_benchmark_test.go
index 2e533cc03..be7d671f9 100644
--- a/cli/internal/benchmark/baseline_benchmark_test.go
+++ b/cli/internal/benchmark/baseline_benchmark_test.go
@@ -10,6 +10,7 @@ import (
"github.com/getarcaneapp/arcane/cli/v2/internal/client"
clitypes "github.com/getarcaneapp/arcane/cli/v2/internal/types"
+ "github.com/stretchr/testify/require"
)
func BenchmarkClientListMediumPayload(b *testing.B) {
@@ -41,14 +42,14 @@ func BenchmarkClientListMediumPayload(b *testing.B) {
cfg := &clitypes.Config{ServerURL: srv.URL, APIKey: "arc_test_key"}
c, err := client.New(cfg)
if err != nil {
- b.Fatalf("new client: %v", err)
+ require.FailNowf(b, "benchmark client setup failed", "new client: %v", err)
}
b.ResetTimer()
for i := 0; i < b.N; i++ {
resp, err := c.Get(context.Background(), "/api/environments/0/containers?limit=200")
if err != nil {
- b.Fatalf("request: %v", err)
+ require.FailNowf(b, "benchmark request failed", "request: %v", err)
}
_ = resp.Body.Close()
}
diff --git a/cli/internal/ci/ci_detect_test.go b/cli/internal/ci/ci_detect_test.go
index c33c08381..1b5f4d851 100644
--- a/cli/internal/ci/ci_detect_test.go
+++ b/cli/internal/ci/ci_detect_test.go
@@ -7,6 +7,7 @@ import (
"net/http/httptest"
"testing"
+ "github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
@@ -18,7 +19,7 @@ func TestDetectFederatedTokenFromGitHubActionsInternal(t *testing.T) {
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
gotAudience = r.URL.Query().Get("audience")
gotAuth = r.Header.Get("Authorization")
- require.NoError(t, json.NewEncoder(w).Encode(map[string]string{"value": "github.jwt"}))
+ assert.NoError(t, json.NewEncoder(w).Encode(map[string]string{"value": "github.jwt"}))
}))
t.Cleanup(server.Close)
diff --git a/cli/internal/client/client_test.go b/cli/internal/client/client_test.go
index 1710566a8..076ae010d 100644
--- a/cli/internal/client/client_test.go
+++ b/cli/internal/client/client_test.go
@@ -8,6 +8,7 @@ import (
"testing"
"github.com/getarcaneapp/arcane/cli/v2/internal/types"
+ "github.com/stretchr/testify/require"
)
func TestClient_UsesAPIKeyHeader(t *testing.T) {
@@ -28,18 +29,20 @@ func TestClient_UsesAPIKeyHeader(t *testing.T) {
cfg := &types.Config{ServerURL: srv.URL, APIKey: "arc_test_key"}
c, err := New(cfg)
- if err != nil {
- t.Fatalf("New() error: %v", err)
- }
+
+ require.NoError(t, err,
+ "New() error: %v", err)
resp, err := c.Get(context.Background(), "/api/version")
- if err != nil {
- t.Fatalf("Get() error: %v", err)
- }
+
+ require.NoError(t, err,
+ "Get() error: %v", err)
+
_ = resp.Body.Close()
- if resp.StatusCode != http.StatusOK {
- t.Fatalf("unexpected status: %d", resp.StatusCode)
- }
+
+ require.Equal(t, http.StatusOK, resp.StatusCode,
+ "unexpected status: %d", resp.StatusCode)
+
}
func TestClient_UsesBearerTokenHeader(t *testing.T) {
@@ -60,18 +63,20 @@ func TestClient_UsesBearerTokenHeader(t *testing.T) {
cfg := &types.Config{ServerURL: srv.URL, JWTToken: "header.payload.sig"}
c, err := New(cfg)
- if err != nil {
- t.Fatalf("New() error: %v", err)
- }
+
+ require.NoError(t, err,
+ "New() error: %v", err)
resp, err := c.Get(context.Background(), "/api/version")
- if err != nil {
- t.Fatalf("Get() error: %v", err)
- }
+
+ require.NoError(t, err,
+ "Get() error: %v", err)
+
_ = resp.Body.Close()
- if resp.StatusCode != http.StatusOK {
- t.Fatalf("unexpected status: %d", resp.StatusCode)
- }
+
+ require.Equal(t, http.StatusOK, resp.StatusCode,
+ "unexpected status: %d", resp.StatusCode)
+
}
func TestClient_NewUnauthenticated_DoesNotSendAuthHeaders(t *testing.T) {
@@ -88,18 +93,20 @@ func TestClient_NewUnauthenticated_DoesNotSendAuthHeaders(t *testing.T) {
cfg := &types.Config{ServerURL: srv.URL}
c, err := NewUnauthenticated(cfg)
- if err != nil {
- t.Fatalf("NewUnauthenticated() error: %v", err)
- }
+
+ require.NoError(t, err,
+ "NewUnauthenticated() error: %v", err)
resp, err := c.Get(context.Background(), "/api/auth/login")
- if err != nil {
- t.Fatalf("Get() error: %v", err)
- }
+
+ require.NoError(t, err,
+ "Get() error: %v", err)
+
_ = resp.Body.Close()
- if resp.StatusCode != http.StatusOK {
- t.Fatalf("unexpected status: %d", resp.StatusCode)
- }
+
+ require.Equal(t, http.StatusOK, resp.StatusCode,
+ "unexpected status: %d", resp.StatusCode)
+
}
func TestClient_Request_DoesNotDoubleMarshalBytes(t *testing.T) {
@@ -126,20 +133,23 @@ func TestClient_Request_DoesNotDoubleMarshalBytes(t *testing.T) {
cfg := &types.Config{ServerURL: srv.URL, JWTToken: "header.payload.sig"}
c, err := New(cfg)
- if err != nil {
- t.Fatalf("New() error: %v", err)
- }
+
+ require.NoError(t, err,
+ "New() error: %v", err)
raw, err := json.Marshal(payload{Username: "arcane", Password: "secret"})
- if err != nil {
- t.Fatalf("json.Marshal() error: %v", err)
- }
+
+ require.NoError(t, err,
+ "json.Marshal() error: %v", err)
+
resp, err := c.Post(context.Background(), "/api/auth/login", raw)
- if err != nil {
- t.Fatalf("Post() error: %v", err)
- }
+
+ require.NoError(t, err,
+ "Post() error: %v", err)
+
_ = resp.Body.Close()
- if resp.StatusCode != http.StatusOK {
- t.Fatalf("unexpected status: %d", resp.StatusCode)
- }
+
+ require.Equal(t, http.StatusOK, resp.StatusCode,
+ "unexpected status: %d", resp.StatusCode)
+
}
diff --git a/cli/internal/client/retry_test.go b/cli/internal/client/retry_test.go
index 317d1bc11..cc24b9a2e 100644
--- a/cli/internal/client/retry_test.go
+++ b/cli/internal/client/retry_test.go
@@ -10,6 +10,7 @@ import (
"time"
"github.com/getarcaneapp/arcane/cli/v2/internal/types"
+ "github.com/stretchr/testify/require"
)
func TestClient_RetriesIdempotentRequests(t *testing.T) {
@@ -30,19 +31,24 @@ func TestClient_RetriesIdempotentRequests(t *testing.T) {
cfg := &types.Config{ServerURL: srv.URL, APIKey: "arc_test_key"}
c, err := New(cfg)
- if err != nil {
- t.Fatalf("New() error: %v", err)
- }
+
+ require.NoError(t, err,
+ "New() error: %v", err)
+
c.SetRetryPolicy(3, 1*time.Millisecond, 2*time.Millisecond)
resp, err := c.Get(context.Background(), "/api/version")
- if err != nil {
- t.Fatalf("Get() error: %v", err)
- }
+
+ require.NoError(t, err,
+ "Get() error: %v", err)
+
_ = resp.Body.Close()
- if got := atomic.LoadInt32(&attempts); got != 2 {
- t.Fatalf("expected 2 attempts, got %d", got)
+ {
+ got := atomic.LoadInt32(&attempts)
+ require.Equal(t, int32(2), got,
+ "expected 2 attempts, got %d", got)
}
+
}
func TestClient_DoesNotRetryNonIdempotentRequests(t *testing.T) {
@@ -58,19 +64,24 @@ func TestClient_DoesNotRetryNonIdempotentRequests(t *testing.T) {
cfg := &types.Config{ServerURL: srv.URL, APIKey: "arc_test_key"}
c, err := New(cfg)
- if err != nil {
- t.Fatalf("New() error: %v", err)
- }
+
+ require.NoError(t, err,
+ "New() error: %v", err)
+
c.SetRetryPolicy(3, 1*time.Millisecond, 2*time.Millisecond)
resp, err := c.Post(context.Background(), "/api/version", map[string]any{"a": 1})
- if err != nil {
- t.Fatalf("Post() returned transport error: %v", err)
- }
+
+ require.NoError(t, err,
+ "Post() returned transport error: %v", err)
+
_ = resp.Body.Close()
- if got := atomic.LoadInt32(&attempts); got != 1 {
- t.Fatalf("expected 1 attempt, got %d", got)
+ {
+ got := atomic.LoadInt32(&attempts)
+ require.Equal(t, int32(1), got,
+ "expected 1 attempt, got %d", got)
}
+
}
func TestClient_DoJSON_StrictStatus(t *testing.T) {
@@ -84,14 +95,17 @@ func TestClient_DoJSON_StrictStatus(t *testing.T) {
cfg := &types.Config{ServerURL: srv.URL, APIKey: "arc_test_key"}
c, err := New(cfg)
- if err != nil {
- t.Fatalf("New() error: %v", err)
- }
+
+ require.NoError(t, err,
+ "New() error: %v", err)
var out map[string]any
- if err := c.DoJSON(context.Background(), http.MethodGet, "/api/version", nil, &out); err == nil {
- t.Fatal("expected strict status error")
+ {
+ err := c.DoJSON(context.Background(), http.MethodGet, "/api/version", nil, &out)
+ require.Error(t, err,
+ "expected strict status error")
}
+
}
func TestDecodeResponseStrict_RequiresSuccessEnvelope(t *testing.T) {
@@ -102,9 +116,12 @@ func TestDecodeResponseStrict_RequiresSuccessEnvelope(t *testing.T) {
rec.Body.WriteString(`{"success":false,"error":"not ok"}`)
resp := rec.Result()
- if _, err := DecodeResponseStrict[map[string]any](resp); err == nil {
- t.Fatal("expected envelope failure")
+ {
+ _, err := DecodeResponseStrict[map[string]any](resp)
+ require.Error(t, err,
+ "expected envelope failure")
}
+
}
func TestClient_DoRaw_Success(t *testing.T) {
@@ -118,15 +135,16 @@ func TestClient_DoRaw_Success(t *testing.T) {
cfg := &types.Config{ServerURL: srv.URL, APIKey: "arc_test_key"}
c, err := New(cfg)
- if err != nil {
- t.Fatalf("New() error: %v", err)
- }
+
+ require.NoError(t, err,
+ "New() error: %v", err)
b, err := c.DoRaw(context.Background(), http.MethodGet, "/api/version", nil)
- if err != nil {
- t.Fatalf("DoRaw() error: %v", err)
- }
- if len(b) == 0 {
- t.Fatal("expected response payload")
- }
+
+ require.NoError(t, err,
+ "DoRaw() error: %v", err)
+
+ require.NotEmpty(t, b,
+ "expected response payload")
+
}
diff --git a/cli/internal/config/config_test.go b/cli/internal/config/config_test.go
index 723ebec8a..d4edee338 100644
--- a/cli/internal/config/config_test.go
+++ b/cli/internal/config/config_test.go
@@ -3,54 +3,65 @@ package config
import (
"os"
"path/filepath"
- "strings"
"testing"
+
+ "github.com/stretchr/testify/assert"
+ "github.com/stretchr/testify/require"
)
func setTempConfigPath(t *testing.T) string {
t.Helper()
path := filepath.Join(t.TempDir(), "arcanecli.yml")
- if err := SetConfigPath(path); err != nil {
- t.Fatalf("SetConfigPath() failed: %v", err)
+ {
+ err := SetConfigPath(path)
+ require.NoError(t, err,
+ "SetConfigPath() failed: %v", err)
}
+
t.Cleanup(func() {
- if err := SetConfigPath(""); err != nil {
- t.Errorf("SetConfigPath(reset) failed: %v", err)
+ {
+ err := SetConfigPath("")
+ assert.NoError(t, err,
+ "SetConfigPath(reset) failed: %v", err)
}
+
})
return path
}
func TestLoadReturnsDefaultsWhenFileMissing(t *testing.T) {
path := setTempConfigPath(t)
- if _, err := os.Stat(path); !os.IsNotExist(err) {
- t.Fatalf("expected config file to be missing, got err=%v", err)
+ {
+ _, err := os.Stat(path)
+ require.True(t, os.IsNotExist(err),
+ "expected config file to be missing, got err=%v", err)
}
cfg, err := Load()
- if err != nil {
- t.Fatalf("Load() failed: %v", err)
- }
- if cfg.ServerURL != "http://localhost:3552" {
- t.Fatalf("ServerURL=%q, want %q", cfg.ServerURL, "http://localhost:3552")
- }
- if cfg.DefaultEnvironment != "0" {
- t.Fatalf("DefaultEnvironment=%q, want %q", cfg.DefaultEnvironment, "0")
- }
- if cfg.LogLevel != "info" {
- t.Fatalf("LogLevel=%q, want %q", cfg.LogLevel, "info")
- }
+
+ require.NoError(t, err,
+ "Load() failed: %v", err)
+
+ require.Equal(t, "http://localhost:3552", cfg.ServerURL,
+ "ServerURL=%q, want %q", cfg.ServerURL, "http://localhost:3552")
+
+ require.Equal(t, "0", cfg.DefaultEnvironment,
+ "DefaultEnvironment=%q, want %q", cfg.DefaultEnvironment, "0")
+
+ require.Equal(t, "info", cfg.LogLevel,
+ "LogLevel=%q, want %q", cfg.LogLevel, "info")
// Ensure callers cannot mutate cached config state.
cfg.ServerURL = "https://mutated.invalid"
cfg2, err := Load()
- if err != nil {
- t.Fatalf("Load() second call failed: %v", err)
- }
- if cfg2.ServerURL != "http://localhost:3552" {
- t.Fatalf("cached config was mutated, ServerURL=%q", cfg2.ServerURL)
- }
+
+ require.NoError(t, err,
+ "Load() second call failed: %v", err)
+
+ require.Equal(t, "http://localhost:3552", cfg2.ServerURL,
+ "cached config was mutated, ServerURL=%q", cfg2.ServerURL)
+
}
func TestSaveAndLoadRoundTripPagination(t *testing.T) {
@@ -62,47 +73,60 @@ func TestSaveAndLoadRoundTripPagination(t *testing.T) {
cfg.SetDefaultLimit(42)
cfg.SetResourceLimit("images", 17)
cfg.SetResourceLimit("Containers", 9)
+ {
- if err := Save(cfg); err != nil {
- t.Fatalf("Save() failed: %v", err)
+ err := Save(cfg)
+ require.NoError(t, err,
+ "Save() failed: %v", err)
}
raw, err := os.ReadFile(path)
- if err != nil {
- t.Fatalf("failed to read saved config: %v", err)
- }
+
+ require.NoError(t, err,
+ "failed to read saved config: %v", err)
+
text := string(raw)
- if !strings.Contains(text, "pagination:") {
- t.Fatalf("expected saved YAML to include pagination block:\n%s", text)
- }
- if !strings.Contains(text, "cli_update_channel: next") {
- t.Fatalf("expected saved YAML to include cli_update_channel key:\n%s", text)
- }
+
+ require.Contains(t, text, "pagination:",
+ "expected saved YAML to include pagination block:\n%s", text)
+
+ require.Contains(t, text, "cli_update_channel: next",
+ "expected saved YAML to include cli_update_channel key:\n%s", text)
info, err := os.Stat(path)
- if err != nil {
- t.Fatalf("failed to stat config file: %v", err)
- }
- if got := info.Mode().Perm(); got != 0o600 {
- t.Fatalf("config file permissions=%#o, want %#o", got, 0o600)
+
+ require.NoError(t, err,
+ "failed to stat config file: %v", err)
+ {
+
+ got := info.Mode().Perm()
+ require.Equal(t, os.FileMode(0o600), got,
+ "config file permissions=%#o, want %#o", got, 0o600)
}
loaded, err := Load()
- if err != nil {
- t.Fatalf("Load() failed: %v", err)
- }
- if loaded.Pagination.Default.Limit != 42 {
- t.Fatalf("default limit mismatch: pagination=%d, want 42", loaded.Pagination.Default.Limit)
- }
- if got := loaded.LimitFor("images"); got != 17 {
- t.Fatalf("images limit=%d, want 17", got)
- }
- if got := loaded.LimitFor("containers"); got != 9 {
- t.Fatalf("containers limit=%d, want 9", got)
+
+ require.NoError(t, err,
+ "Load() failed: %v", err)
+
+ require.Equal(t, 42, loaded.Pagination.Default.Limit,
+ "default limit mismatch: pagination=%d, want 42", loaded.Pagination.Default.Limit)
+ {
+
+ got := loaded.LimitFor("images")
+ require.Equal(t, 17, got,
+ "images limit=%d, want 17", got)
}
- if loaded.CLIUpdateChannel != "next" {
- t.Fatalf("CLIUpdateChannel=%q, want next", loaded.CLIUpdateChannel)
+ {
+
+ got := loaded.LimitFor("containers")
+ require.Equal(t, 9, got,
+ "containers limit=%d, want 9", got)
}
+
+ require.Equal(t, "next", loaded.CLIUpdateChannel,
+ "CLIUpdateChannel=%q, want next", loaded.CLIUpdateChannel)
+
}
func TestLoadCanonicalPaginationBlock(t *testing.T) {
@@ -121,46 +145,56 @@ pagination:
registries:
limit: 9
`
- if err := os.WriteFile(path, []byte(content), 0o600); err != nil {
- t.Fatalf("failed to write config fixture: %v", err)
+ {
+ err := os.WriteFile(path, []byte(content), 0o600)
+ require.NoError(t, err,
+ "failed to write config fixture: %v", err)
}
cfg, err := Load()
- if err != nil {
- t.Fatalf("Load() failed: %v", err)
- }
- if cfg.ServerURL != "https://api.arcane.test" {
- t.Fatalf("ServerURL=%q, want %q", cfg.ServerURL, "https://api.arcane.test")
- }
- if cfg.APIKey != "k_123" {
- t.Fatalf("APIKey=%q, want %q", cfg.APIKey, "k_123")
- }
- if cfg.Pagination.Default.Limit != 13 {
- t.Fatalf("Pagination.Default.Limit=%d, want 13", cfg.Pagination.Default.Limit)
- }
- if got := cfg.LimitFor("networks"); got != 4 {
- t.Fatalf("networks limit=%d, want 4", got)
+
+ require.NoError(t, err,
+ "Load() failed: %v", err)
+
+ require.Equal(t, "https://api.arcane.test", cfg.ServerURL,
+ "ServerURL=%q, want %q", cfg.ServerURL, "https://api.arcane.test")
+
+ require.Equal(t, "k_123", cfg.APIKey,
+ "APIKey=%q, want %q", cfg.APIKey, "k_123")
+
+ require.Equal(t, 13, cfg.Pagination.Default.Limit,
+ "Pagination.Default.Limit=%d, want 13", cfg.Pagination.Default.Limit)
+ {
+
+ got := cfg.LimitFor("networks")
+ require.Equal(t, 4, got,
+ "networks limit=%d, want 4", got)
}
- if got := cfg.LimitFor("registries"); got != 9 {
- t.Fatalf("registries limit=%d, want 9", got)
+ {
+
+ got := cfg.LimitFor("registries")
+ require.Equal(t, 9, got,
+ "registries limit=%d, want 9", got)
}
+
}
func TestInitDefaultFileCreatesTemplate(t *testing.T) {
path := setTempConfigPath(t)
created, err := InitDefaultFile()
- if err != nil {
- t.Fatalf("InitDefaultFile() failed: %v", err)
- }
- if !created {
- t.Fatal("InitDefaultFile() created = false, want true")
- }
+
+ require.NoError(t, err,
+ "InitDefaultFile() failed: %v", err)
+
+ require.True(t, created,
+ "InitDefaultFile() created = false, want true")
raw, err := os.ReadFile(path)
- if err != nil {
- t.Fatalf("failed to read config file: %v", err)
- }
+
+ require.NoError(t, err,
+ "failed to read config file: %v", err)
+
text := string(raw)
requiredKeys := []string{
@@ -173,138 +207,161 @@ func TestInitDefaultFileCreatesTemplate(t *testing.T) {
"pagination:",
}
for _, key := range requiredKeys {
- if !strings.Contains(text, key) {
- t.Fatalf("expected generated config to contain %q:\n%s", key, text)
- }
+
+ require.Contains(t, text, key,
+ "expected generated config to contain %q:\n%s", key, text)
+
}
for _, resource := range []string{"containers", "images", "volumes", "networks", "projects", "environments", "registries", "templates", "users", "events", "apikeys"} {
- if !strings.Contains(text, resource+":") {
- t.Fatalf("expected generated config to contain resource key %q:\n%s", resource, text)
- }
+
+ require.Contains(t, text, resource+":",
+ "expected generated config to contain resource key %q:\n%s", resource, text)
+
}
cfg, err := Load()
- if err != nil {
- t.Fatalf("Load() after init failed: %v", err)
- }
- if cfg.Pagination.Default.Limit != defaultPaginationInitLimit {
- t.Fatalf("Pagination.Default.Limit=%d, want %d", cfg.Pagination.Default.Limit, defaultPaginationInitLimit)
- }
+
+ require.NoError(t, err,
+ "Load() after init failed: %v", err)
+
+ require.Equal(t, defaultPaginationInitLimit, cfg.Pagination.Default.Limit,
+ "Pagination.Default.Limit=%d, want %d", cfg.Pagination.Default.Limit, defaultPaginationInitLimit)
+
for _, resource := range []string{"containers", "images", "volumes", "networks", "projects", "environments", "registries", "templates", "users", "events", "apikeys"} {
- if got := cfg.LimitFor(resource); got != defaultPaginationInitLimit {
- t.Fatalf("LimitFor(%s)=%d, want %d", resource, got, defaultPaginationInitLimit)
+ {
+ got := cfg.LimitFor(resource)
+ require.Equal(t, defaultPaginationInitLimit, got,
+ "LimitFor(%s)=%d, want %d", resource, got, defaultPaginationInitLimit)
}
+
}
}
func TestInitDefaultFileDoesNotOverwriteExistingFile(t *testing.T) {
path := setTempConfigPath(t)
original := "server_url: https://custom.arcane.example\napi_key: custom\n"
- if err := os.WriteFile(path, []byte(original), 0o600); err != nil {
- t.Fatalf("failed to write fixture file: %v", err)
+ {
+ err := os.WriteFile(path, []byte(original), 0o600)
+ require.NoError(t, err,
+ "failed to write fixture file: %v", err)
}
created, err := InitDefaultFile()
- if err != nil {
- t.Fatalf("InitDefaultFile() failed: %v", err)
- }
- if created {
- t.Fatal("InitDefaultFile() created = true, want false")
- }
+
+ require.NoError(t, err,
+ "InitDefaultFile() failed: %v", err)
+
+ require.False(t, created,
+ "InitDefaultFile() created = true, want false")
raw, err := os.ReadFile(path)
- if err != nil {
- t.Fatalf("failed to read config file: %v", err)
- }
- if string(raw) != original {
- t.Fatalf("existing file was modified:\nwant:\n%s\ngot:\n%s", original, string(raw))
- }
+
+ require.NoError(t, err,
+ "failed to read config file: %v", err)
+
+ require.Equal(t, original, string(raw),
+ "existing file was modified:\nwant:\n%s\ngot:\n%s", original, string(raw))
+
}
func TestBackupFileMovesConfig(t *testing.T) {
path := setTempConfigPath(t)
original := "server_url: https://backup.arcane.example\napi_key: abc123\n"
- if err := os.WriteFile(path, []byte(original), 0o600); err != nil {
- t.Fatalf("failed to write config fixture: %v", err)
+ {
+ err := os.WriteFile(path, []byte(original), 0o600)
+ require.NoError(t, err,
+ "failed to write config fixture: %v", err)
}
backupPath, moved, err := BackupFile()
- if err != nil {
- t.Fatalf("BackupFile() failed: %v", err)
- }
- if !moved {
- t.Fatal("BackupFile() moved = false, want true")
- }
- if backupPath != path+".bak" {
- t.Fatalf("backup path = %q, want %q", backupPath, path+".bak")
- }
- if _, err := os.Stat(path); !os.IsNotExist(err) {
- t.Fatalf("expected original config to be removed, stat err=%v", err)
+ require.NoError(t, err,
+ "BackupFile() failed: %v", err)
+
+ require.True(t, moved,
+ "BackupFile() moved = false, want true")
+
+ require.Equal(t, path+".bak", backupPath,
+ "backup path = %q, want %q", backupPath, path+".bak")
+ {
+
+ _, err := os.Stat(path)
+ require.True(t, os.IsNotExist(err),
+ "expected original config to be removed, stat err=%v", err)
}
raw, err := os.ReadFile(backupPath)
- if err != nil {
- t.Fatalf("failed to read backup file: %v", err)
- }
- if string(raw) != original {
- t.Fatalf("backup content mismatch:\nwant:\n%s\ngot:\n%s", original, string(raw))
- }
+
+ require.NoError(t, err,
+ "failed to read backup file: %v", err)
+
+ require.Equal(t, original, string(raw),
+ "backup content mismatch:\nwant:\n%s\ngot:\n%s", original, string(raw))
+
}
func TestBackupFileNoConfig(t *testing.T) {
path := setTempConfigPath(t)
- if _, err := os.Stat(path); !os.IsNotExist(err) {
- t.Fatalf("expected missing config before backup, stat err=%v", err)
+ {
+ _, err := os.Stat(path)
+ require.True(t, os.IsNotExist(err),
+ "expected missing config before backup, stat err=%v", err)
}
backupPath, moved, err := BackupFile()
- if err != nil {
- t.Fatalf("BackupFile() failed: %v", err)
- }
- if moved {
- t.Fatal("BackupFile() moved = true, want false")
- }
- if backupPath != path+".bak" {
- t.Fatalf("backup path = %q, want %q", backupPath, path+".bak")
- }
+
+ require.NoError(t, err,
+ "BackupFile() failed: %v", err)
+
+ require.False(t, moved,
+ "BackupFile() moved = true, want false")
+
+ require.Equal(t, path+".bak", backupPath,
+ "backup path = %q, want %q", backupPath, path+".bak")
+
}
func TestBackupFileRotatesExistingBak(t *testing.T) {
path := setTempConfigPath(t)
backupPath := path + ".bak"
+ {
- if err := os.WriteFile(path, []byte("server_url: https://new.example\n"), 0o600); err != nil {
- t.Fatalf("failed to write primary config: %v", err)
+ err := os.WriteFile(path, []byte("server_url: https://new.example\n"), 0o600)
+ require.NoError(t, err,
+ "failed to write primary config: %v", err)
}
- if err := os.WriteFile(backupPath, []byte("server_url: https://old.example\n"), 0o600); err != nil {
- t.Fatalf("failed to write existing backup: %v", err)
+ {
+
+ err := os.WriteFile(backupPath, []byte("server_url: https://old.example\n"), 0o600)
+ require.NoError(t, err,
+ "failed to write existing backup: %v", err)
}
newBackupPath, moved, err := BackupFile()
- if err != nil {
- t.Fatalf("BackupFile() failed: %v", err)
- }
- if !moved {
- t.Fatal("BackupFile() moved = false, want true")
- }
- if newBackupPath != backupPath {
- t.Fatalf("backup path = %q, want %q", newBackupPath, backupPath)
- }
+
+ require.NoError(t, err,
+ "BackupFile() failed: %v", err)
+
+ require.True(t, moved,
+ "BackupFile() moved = false, want true")
+
+ require.Equal(t, backupPath, newBackupPath,
+ "backup path = %q, want %q", newBackupPath, backupPath)
raw, err := os.ReadFile(backupPath)
- if err != nil {
- t.Fatalf("failed to read newest backup: %v", err)
- }
- if !strings.Contains(string(raw), "new.example") {
- t.Fatalf("expected newest backup to contain new config, got:\n%s", string(raw))
- }
+
+ require.NoError(t, err,
+ "failed to read newest backup: %v", err)
+
+ require.Contains(t, string(raw), "new.example",
+ "expected newest backup to contain new config, got:\n%s", string(raw))
rotated, err := filepath.Glob(backupPath + ".*")
- if err != nil {
- t.Fatalf("failed to glob rotated backups: %v", err)
- }
- if len(rotated) == 0 {
- t.Fatalf("expected rotated backup matching %q", backupPath+".*")
- }
+
+ require.NoError(t, err,
+ "failed to glob rotated backups: %v", err)
+
+ require.NotEmpty(t, rotated,
+ "expected rotated backup matching %q", backupPath+".*")
+
}
diff --git a/cli/internal/integrationtest/action_error_handling_test.go b/cli/internal/integrationtest/action_error_handling_test.go
index 4ec70cd80..30aedbd5b 100644
--- a/cli/internal/integrationtest/action_error_handling_test.go
+++ b/cli/internal/integrationtest/action_error_handling_test.go
@@ -3,8 +3,9 @@ package integrationtest
import (
"net/http"
"net/http/httptest"
- "strings"
"testing"
+
+ "github.com/stretchr/testify/require"
)
// TestContainerStartSurfacesServerError verifies that `containers start` reports
@@ -12,6 +13,7 @@ import (
// false success. This is a regression guard: the manager's remote-environment
// proxy returns 403 when the caller lacks the required per-environment
// permission, and the CLI must not swallow that and exit 0.
+
func TestContainerStartSurfacesServerError(t *testing.T) {
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
switch {
@@ -34,15 +36,16 @@ func TestContainerStartSurfacesServerError(t *testing.T) {
t,
[]string{"--config", configPath, "containers", "start", "abc123"},
)
- if err == nil {
- t.Fatalf("expected an error for a 403 start response, got success\nstdout=%s\nstderr=%s", outBuf, errOut)
- }
- if !strings.Contains(err.Error(), "403") {
- t.Fatalf("expected the error to mention status 403, got: %v", err)
- }
- if strings.Contains(outBuf, "successfully") {
- t.Fatalf("expected no success message on a denied start, got stdout=%s", outBuf)
- }
+
+ require.Error(t, err,
+ "expected an error for a 403 start response, got success\nstdout=%s\nstderr=%s", outBuf, errOut)
+
+ require.Contains(t, err.Error(), "403",
+ "expected the error to mention status 403, got: %v", err)
+
+ require.NotContains(t, outBuf, "successfully",
+ "expected no success message on a denied start, got stdout=%s", outBuf)
+
}
// TestSystemContainersStartAllSurfacesServerError verifies the same guard for a
@@ -65,13 +68,14 @@ func TestSystemContainersStartAllSurfacesServerError(t *testing.T) {
t,
[]string{"--config", configPath, "system", "containers-start-all"},
)
- if err == nil {
- t.Fatalf("expected an error for a 403 response, got success\nstdout=%s\nstderr=%s", outBuf, errOut)
- }
- if !strings.Contains(err.Error(), "403") {
- t.Fatalf("expected the error to mention status 403, got: %v", err)
- }
- if strings.Contains(outBuf, "Started all containers") {
- t.Fatalf("expected no success message on a denied start-all, got stdout=%s", outBuf)
- }
+
+ require.Error(t, err,
+ "expected an error for a 403 response, got success\nstdout=%s\nstderr=%s", outBuf, errOut)
+
+ require.Contains(t, err.Error(), "403",
+ "expected the error to mention status 403, got: %v", err)
+
+ require.NotContains(t, outBuf, "Started all containers",
+ "expected no success message on a denied start-all, got stdout=%s", outBuf)
+
}
diff --git a/cli/internal/integrationtest/command_helpers_test.go b/cli/internal/integrationtest/command_helpers_test.go
index 08b936d2b..0519b44c2 100644
--- a/cli/internal/integrationtest/command_helpers_test.go
+++ b/cli/internal/integrationtest/command_helpers_test.go
@@ -12,6 +12,7 @@ import (
clipkg "github.com/getarcaneapp/arcane/cli/v2/pkg"
"github.com/spf13/cobra"
"github.com/spf13/pflag"
+ "github.com/stretchr/testify/require"
)
var stdoutCaptureMuInternal sync.Mutex
@@ -28,8 +29,10 @@ func writeCLIIntegrationConfigInternal(t *testing.T, serverURL string) string {
"log_level: info",
"",
}, "\n")
- if err := os.WriteFile(configPath, []byte(configContent), 0o600); err != nil {
- t.Fatalf("write config: %v", err)
+ {
+ err := os.WriteFile(configPath, []byte(configContent), 0o600)
+ require.NoError(t, err,
+ "write config: %v", err)
}
return configPath
@@ -49,9 +52,10 @@ func executeCLIIntegrationCommandInternal(t *testing.T, args []string) (string,
stdout := os.Stdout
reader, writer, err := os.Pipe()
- if err != nil {
- t.Fatalf("pipe: %v", err)
- }
+
+ require.NoError(t, err,
+ "pipe: %v", err)
+
os.Stdout = writer
defer func() {
_ = writer.Close()
@@ -62,9 +66,9 @@ func executeCLIIntegrationCommandInternal(t *testing.T, args []string) (string,
_ = writer.Close()
stdoutBytes, readErr := io.ReadAll(reader)
- if readErr != nil {
- t.Fatalf("read stdout: %v", readErr)
- }
+
+ require.NoError(t, readErr,
+ "read stdout: %v", readErr)
outBuf := string(stdoutBytes)
if runtime.GOOS == "windows" {
@@ -103,10 +107,13 @@ func resetFlagSetInternal(t *testing.T, flagSet *pflag.FlagSet) {
defValue = ""
}
}
+ {
- if err := flag.Value.Set(defValue); err != nil {
- t.Fatalf("reset flag %s: %v", flag.Name, err)
+ err := flag.Value.Set(defValue)
+ require.NoError(t, err,
+ "reset flag %s: %v", flag.Name, err)
}
+
flag.Changed = false
})
}
diff --git a/cli/internal/integrationtest/json_contract_test.go b/cli/internal/integrationtest/json_contract_test.go
index 1601197e2..223327018 100644
--- a/cli/internal/integrationtest/json_contract_test.go
+++ b/cli/internal/integrationtest/json_contract_test.go
@@ -6,6 +6,8 @@ import (
"net/http/httptest"
"strings"
"testing"
+
+ "github.com/stretchr/testify/require"
)
func TestContainersListJSONContract(t *testing.T) {
@@ -32,17 +34,23 @@ func TestContainersListJSONContract(t *testing.T) {
t,
[]string{"--config", configPath, "containers", "list", "--json"},
)
- if err != nil {
- t.Fatalf("execute: %v (%s)", err, errOut)
- }
+
+ require.NoError(t, err,
+ "execute: %v (%s)", err, errOut)
var got map[string]any
- if err := json.Unmarshal([]byte(strings.TrimSpace(outBuf)), &got); err != nil {
- t.Fatalf("json parse failed: %v\noutput=%s", err, outBuf)
+ {
+ err := json.Unmarshal([]byte(strings.TrimSpace(outBuf)), &got)
+ require.NoError(t, err,
+ "json parse failed: %v\noutput=%s", err, outBuf)
}
+
for _, key := range []string{"success", "data", "pagination"} {
- if _, ok := got[key]; !ok {
- t.Fatalf("missing key %q in output: %v", key, got)
+ {
+ _, ok := got[key]
+ require.True(t, ok,
+ "missing key %q in output: %v", key, got)
}
+
}
}
diff --git a/cli/internal/integrationtest/pagination_test.go b/cli/internal/integrationtest/pagination_test.go
index 3146f43bb..b1ee60e86 100644
--- a/cli/internal/integrationtest/pagination_test.go
+++ b/cli/internal/integrationtest/pagination_test.go
@@ -7,6 +7,8 @@ import (
"strings"
"sync"
"testing"
+
+ "github.com/stretchr/testify/require"
)
func TestContainersListSendsLimitAndStart(t *testing.T) {
@@ -38,27 +40,32 @@ func TestContainersListSendsLimitAndStart(t *testing.T) {
t,
[]string{"--config", configPath, "containers", "list", "--json", "--limit", "5", "--start", "10"},
)
- if err != nil {
- t.Fatalf("execute: %v (%s)", err, errOut)
- }
+
+ require.NoError(t, err,
+ "execute: %v (%s)", err, errOut)
mu.Lock()
defer mu.Unlock()
- if gotPath != "/api/environments/0/containers" {
- t.Fatalf("path = %q, want %q", gotPath, "/api/environments/0/containers")
- }
- if !(strings.Contains(gotQuery, "limit=5") && strings.Contains(gotQuery, "start=10")) {
- t.Fatalf("query = %q, want limit=5 and start=10", gotQuery)
- }
+ require.Equal(t, "/api/environments/0/containers", gotPath,
+ "path = %q, want %q", gotPath, "/api/environments/0/containers")
+
+ require.True(t, (strings.Contains(gotQuery, "limit=5") && strings.Contains(gotQuery, "start=10")),
+ "query = %q, want limit=5 and start=10", gotQuery)
var got map[string]any
- if err := json.Unmarshal([]byte(strings.TrimSpace(outBuf)), &got); err != nil {
- t.Fatalf("json parse failed: %v\noutput=%s", err, outBuf)
+ {
+ err := json.Unmarshal([]byte(strings.TrimSpace(outBuf)), &got)
+ require.NoError(t, err,
+ "json parse failed: %v\noutput=%s", err, outBuf)
}
- if _, ok := got["pagination"]; !ok {
- t.Fatalf("expected pagination in output: %v", got)
+ {
+
+ _, ok := got["pagination"]
+ require.True(t, ok,
+ "expected pagination in output: %v", got)
}
+
}
func TestContainersListExplicitStartZeroSendsStartZero(t *testing.T) {
@@ -88,19 +95,19 @@ func TestContainersListExplicitStartZeroSendsStartZero(t *testing.T) {
t,
[]string{"--config", configPath, "containers", "list", "--json", "--start", "0"},
)
- if err != nil {
- t.Fatalf("execute: %v (%s)", err, errOut)
- }
+
+ require.NoError(t, err,
+ "execute: %v (%s)", err, errOut)
mu.Lock()
defer mu.Unlock()
- if gotPath != "/api/environments/0/containers" {
- t.Fatalf("path = %q, want %q", gotPath, "/api/environments/0/containers")
- }
- if !(strings.Contains(gotQuery, "start=0") && strings.Contains(gotQuery, "limit=20")) {
- t.Fatalf("query = %q, want start=0 and limit=20", gotQuery)
- }
+ require.Equal(t, "/api/environments/0/containers", gotPath,
+ "path = %q, want %q", gotPath, "/api/environments/0/containers")
+
+ require.True(t, (strings.Contains(gotQuery, "start=0") && strings.Contains(gotQuery, "limit=20")),
+ "query = %q, want start=0 and limit=20", gotQuery)
+
}
func TestContainersListTextShowsShowingSummary(t *testing.T) {
@@ -121,12 +128,13 @@ func TestContainersListTextShowsShowingSummary(t *testing.T) {
t,
[]string{"--config", configPath, "containers", "list", "--json=false"},
)
- if err != nil {
- t.Fatalf("execute: %v (%s)", err, errOut)
- }
- if !strings.Contains(outBuf, "Showing: 1/26 containers") {
- t.Fatalf("expected showing summary in output, got:\n%s", outBuf)
- }
+
+ require.NoError(t, err,
+ "execute: %v (%s)", err, errOut)
+
+ require.Contains(t, outBuf, "Showing: 1/26 containers",
+ "expected showing summary in output, got:\n%s", outBuf)
+
}
// TestContainersListAllRequestsEveryItem pins the wire form of --all. The API
@@ -160,19 +168,19 @@ func TestContainersListAllRequestsEveryItem(t *testing.T) {
t,
[]string{"--config", configPath, "containers", "list", "--json", "--all"},
)
- if err != nil {
- t.Fatalf("execute: %v (%s)", err, errOut)
- }
+
+ require.NoError(t, err,
+ "execute: %v (%s)", err, errOut)
mu.Lock()
defer mu.Unlock()
- if gotPath != "/api/environments/0/containers" {
- t.Fatalf("path = %q, want %q", gotPath, "/api/environments/0/containers")
- }
- if gotQuery != "limit=-1" {
- t.Fatalf("query = %q, want %q", gotQuery, "limit=-1")
- }
+ require.Equal(t, "/api/environments/0/containers", gotPath,
+ "path = %q, want %q", gotPath, "/api/environments/0/containers")
+
+ require.Equal(t, "limit=-1", gotQuery,
+ "query = %q, want %q", gotQuery, "limit=-1")
+
}
// TestProjectsListAllIncludesArchived covers the one resource where "everything"
@@ -203,16 +211,16 @@ func TestProjectsListAllIncludesArchived(t *testing.T) {
t,
[]string{"--config", configPath, "projects", "list", "--json", "--all"},
)
- if err != nil {
- t.Fatalf("execute: %v (%s)", err, errOut)
- }
+
+ require.NoError(t, err,
+ "execute: %v (%s)", err, errOut)
mu.Lock()
defer mu.Unlock()
- if gotQuery != "archived=all&limit=-1" {
- t.Fatalf("query = %q, want %q", gotQuery, "archived=all&limit=-1")
- }
+ require.Equal(t, "archived=all&limit=-1", gotQuery,
+ "query = %q, want %q", gotQuery, "archived=all&limit=-1")
+
}
func TestAdminEventsListEnvSendsLimitAndStart(t *testing.T) {
@@ -251,19 +259,19 @@ func TestAdminEventsListEnvSendsLimitAndStart(t *testing.T) {
t,
[]string{"--config", configPath, "admin", "events", "list-env", "--json", "--limit", "3", "--start", "6"},
)
- if err != nil {
- t.Fatalf("execute: %v (%s)", err, errOut)
- }
+
+ require.NoError(t, err,
+ "execute: %v (%s)", err, errOut)
mu.Lock()
defer mu.Unlock()
- if gotPath != "/api/events/environment/0" {
- t.Fatalf("path = %q, want %q", gotPath, "/api/events/environment/0")
- }
- if !(strings.Contains(gotQuery, "limit=3") && strings.Contains(gotQuery, "start=6")) {
- t.Fatalf("query = %q, want limit=3 and start=6", gotQuery)
- }
+ require.Equal(t, "/api/events/environment/0", gotPath,
+ "path = %q, want %q", gotPath, "/api/events/environment/0")
+
+ require.True(t, (strings.Contains(gotQuery, "limit=3") && strings.Contains(gotQuery, "start=6")),
+ "query = %q, want limit=3 and start=6", gotQuery)
+
}
func TestTemplatesListJSONIncludesPaginatedEnvelope(t *testing.T) {
@@ -295,34 +303,46 @@ func TestTemplatesListJSONIncludesPaginatedEnvelope(t *testing.T) {
t,
[]string{"--config", configPath, "templates", "list", "--json", "--limit", "7", "--start", "14"},
)
- if err != nil {
- t.Fatalf("execute: %v (%s)", err, errOut)
- }
+
+ require.NoError(t, err,
+ "execute: %v (%s)", err, errOut)
mu.Lock()
if gotPath != "/api/templates" {
mu.Unlock()
- t.Fatalf("path = %q, want %q", gotPath, "/api/templates")
+ require.FailNowf(t, "unexpected failure", "path = %q, want %q", gotPath, "/api/templates")
}
if !(strings.Contains(gotQuery, "limit=7") && strings.Contains(gotQuery, "start=14")) {
mu.Unlock()
- t.Fatalf("query = %q, want limit=7 and start=14", gotQuery)
+ require.FailNowf(t, "unexpected failure", "query = %q, want limit=7 and start=14", gotQuery)
}
mu.Unlock()
var got map[string]any
- if err := json.Unmarshal([]byte(strings.TrimSpace(outBuf)), &got); err != nil {
- t.Fatalf("json parse failed: %v\noutput=%s", err, outBuf)
+ {
+ err := json.Unmarshal([]byte(strings.TrimSpace(outBuf)), &got)
+ require.NoError(t, err,
+ "json parse failed: %v\noutput=%s", err, outBuf)
}
- if _, ok := got["success"]; !ok {
- t.Fatalf("expected success key in output: %v", got)
+ {
+
+ _, ok := got["success"]
+ require.True(t, ok,
+ "expected success key in output: %v", got)
}
- if _, ok := got["data"]; !ok {
- t.Fatalf("expected data key in output: %v", got)
+ {
+
+ _, ok := got["data"]
+ require.True(t, ok,
+ "expected data key in output: %v", got)
}
- if _, ok := got["pagination"]; !ok {
- t.Fatalf("expected pagination key in output: %v", got)
+ {
+
+ _, ok := got["pagination"]
+ require.True(t, ok,
+ "expected pagination key in output: %v", got)
}
+
}
func TestTemplatesListAllRejectsExplicitPaginationFlags(t *testing.T) {
@@ -345,18 +365,20 @@ func TestTemplatesListAllRejectsExplicitPaginationFlags(t *testing.T) {
t,
[]string{"--config", configPath, "templates", "list", "--all", "--limit", "50"},
)
- if err == nil {
- t.Fatal("expected command error, got nil")
- }
- if !strings.Contains(err.Error(), "--all cannot be combined with explicit pagination flags") {
- t.Fatalf("unexpected error: %v", err)
- }
- if !strings.Contains(errOut, "--all cannot be combined with explicit pagination flags") {
- t.Fatalf("unexpected stderr output: %s", errOut)
- }
+
+ require.Error(t, err,
+ "expected command error, got nil")
+
+ require.Contains(t, err.Error(), "--all cannot be combined with explicit pagination flags",
+ "unexpected error: %v", err)
+
+ require.Contains(t, errOut, "--all cannot be combined with explicit pagination flags",
+ "unexpected stderr output: %s", errOut)
+
mu.Lock()
defer mu.Unlock()
- if called {
- t.Fatal("expected command to fail before issuing HTTP request")
- }
+
+ require.False(t, called,
+ "expected command to fail before issuing HTTP request")
+
}
diff --git a/cli/internal/integrationtest/updates_commands_test.go b/cli/internal/integrationtest/updates_commands_test.go
index d63bb8c23..d8cb11567 100644
--- a/cli/internal/integrationtest/updates_commands_test.go
+++ b/cli/internal/integrationtest/updates_commands_test.go
@@ -8,6 +8,7 @@ import (
"testing"
"github.com/getarcaneapp/arcane/types/v2/imageupdate"
+ "github.com/stretchr/testify/require"
)
func TestContainersListUpdatesJSONContract(t *testing.T) {
@@ -44,21 +45,27 @@ func TestContainersListUpdatesJSONContract(t *testing.T) {
t,
[]string{"--config", configPath, "containers", "list", "--updates", "has_update", "--json"},
)
- if err != nil {
- t.Fatalf("execute: %v (%s)", err, errOut)
- }
- if seenUpdatesFilter != "has_update" {
- t.Fatalf("expected updates filter query param, got %q", seenUpdatesFilter)
- }
+
+ require.NoError(t, err,
+ "execute: %v (%s)", err, errOut)
+
+ require.Equal(t, "has_update", seenUpdatesFilter,
+ "expected updates filter query param, got %q", seenUpdatesFilter)
var got map[string]any
- if err := json.Unmarshal([]byte(strings.TrimSpace(outBuf)), &got); err != nil {
- t.Fatalf("json parse failed: %v\noutput=%s", err, outBuf)
+ {
+ err := json.Unmarshal([]byte(strings.TrimSpace(outBuf)), &got)
+ require.NoError(t, err,
+ "json parse failed: %v\noutput=%s", err, outBuf)
}
+
for _, key := range []string{"success", "data", "pagination"} {
- if _, ok := got[key]; !ok {
- t.Fatalf("missing key %q in output: %v", key, got)
+ {
+ _, ok := got[key]
+ require.True(t, ok,
+ "missing key %q in output: %v", key, got)
}
+
}
}
@@ -96,15 +103,16 @@ func TestContainersUpdatesCommandUsesHasUpdateFilter(t *testing.T) {
t,
[]string{"--config", configPath, "--output", "text", "containers", "updates"},
)
- if err != nil {
- t.Fatalf("execute: %v (%s)", err, errOut)
- }
- if seenUpdatesFilter != "has_update" {
- t.Fatalf("expected updates filter query param, got %q", seenUpdatesFilter)
- }
- if strings.TrimSpace(outBuf) == "" {
- t.Fatal("expected output from containers updates command")
- }
+
+ require.NoError(t, err,
+ "execute: %v (%s)", err, errOut)
+
+ require.Equal(t, "has_update", seenUpdatesFilter,
+ "expected updates filter query param, got %q", seenUpdatesFilter)
+
+ require.NotEmpty(t, strings.TrimSpace(outBuf),
+ "expected output from containers updates command")
+
}
func TestProjectsListUpdatesJSONContract(t *testing.T) {
@@ -144,21 +152,27 @@ func TestProjectsListUpdatesJSONContract(t *testing.T) {
t,
[]string{"--config", configPath, "projects", "list", "--updates", "has_update", "--json"},
)
- if err != nil {
- t.Fatalf("execute: %v (%s)", err, errOut)
- }
- if seenUpdatesFilter != "has_update" {
- t.Fatalf("expected updates filter query param, got %q", seenUpdatesFilter)
- }
+
+ require.NoError(t, err,
+ "execute: %v (%s)", err, errOut)
+
+ require.Equal(t, "has_update", seenUpdatesFilter,
+ "expected updates filter query param, got %q", seenUpdatesFilter)
var got map[string]any
- if err := json.Unmarshal([]byte(strings.TrimSpace(outBuf)), &got); err != nil {
- t.Fatalf("json parse failed: %v\noutput=%s", err, outBuf)
+ {
+ err := json.Unmarshal([]byte(strings.TrimSpace(outBuf)), &got)
+ require.NoError(t, err,
+ "json parse failed: %v\noutput=%s", err, outBuf)
}
+
for _, key := range []string{"success", "data", "pagination"} {
- if _, ok := got[key]; !ok {
- t.Fatalf("missing key %q in output: %v", key, got)
+ {
+ _, ok := got[key]
+ require.True(t, ok,
+ "missing key %q in output: %v", key, got)
}
+
}
}
@@ -199,15 +213,16 @@ func TestProjectsUpdatesCommandUsesHasUpdateFilter(t *testing.T) {
t,
[]string{"--config", configPath, "--output", "text", "projects", "updates"},
)
- if err != nil {
- t.Fatalf("execute: %v (%s)", err, errOut)
- }
- if seenUpdatesFilter != "has_update" {
- t.Fatalf("expected updates filter query param, got %q", seenUpdatesFilter)
- }
- if strings.TrimSpace(outBuf) == "" {
- t.Fatal("expected output from projects updates command")
- }
+
+ require.NoError(t, err,
+ "execute: %v (%s)", err, errOut)
+
+ require.Equal(t, "has_update", seenUpdatesFilter,
+ "expected updates filter query param, got %q", seenUpdatesFilter)
+
+ require.NotEmpty(t, strings.TrimSpace(outBuf),
+ "expected output from projects updates command")
+
}
func TestImagesUpdatesCheckEncodesImageRefAndDecodesSingleResponse(t *testing.T) {
@@ -244,36 +259,40 @@ func TestImagesUpdatesCheckEncodesImageRefAndDecodesSingleResponse(t *testing.T)
t,
[]string{"--config", configPath, "images", "updates", "check", imageRef, "--json"},
)
- if err != nil {
- t.Fatalf("execute: %v (%s)", err, errOut)
- }
- if receivedImageRef != imageRef {
- t.Fatalf("expected imageRef %q, got %q", imageRef, receivedImageRef)
- }
- if !strings.Contains(receivedRawQuery, "%26") || !strings.Contains(receivedRawQuery, "%3D") {
- t.Fatalf("expected reserved query characters to be encoded, got %q", receivedRawQuery)
- }
- if strings.Contains(receivedRawQuery, "&debug=") {
- t.Fatalf("imageRef escaped into a second query parameter: %q", receivedRawQuery)
- }
+
+ require.NoError(t, err,
+ "execute: %v (%s)", err, errOut)
+
+ require.Equal(t, imageRef, receivedImageRef,
+ "expected imageRef %q, got %q", imageRef, receivedImageRef)
+
+ require.False(t, !strings.Contains(receivedRawQuery, "%26") || !strings.Contains(receivedRawQuery, "%3D"),
+ "expected reserved query characters to be encoded, got %q", receivedRawQuery)
+
+ require.NotContains(t, receivedRawQuery, "&debug=",
+ "imageRef escaped into a second query parameter: %q", receivedRawQuery)
var result imageupdate.Response
- if err := json.Unmarshal([]byte(strings.TrimSpace(outBuf)), &result); err != nil {
- t.Fatalf("single response JSON parse failed: %v\noutput=%s", err, outBuf)
- }
- if !result.HasUpdate || result.CurrentVersion != "1.0.0" || result.LatestVersion != "1.1.0" {
- t.Fatalf("unexpected single image update response: %+v", result)
+ {
+ err := json.Unmarshal([]byte(strings.TrimSpace(outBuf)), &result)
+ require.NoError(t, err,
+ "single response JSON parse failed: %v\noutput=%s", err, outBuf)
}
+
+ require.False(t, !result.HasUpdate || result.CurrentVersion != "1.0.0" || result.LatestVersion != "1.1.0",
+ "unexpected single image update response: %+v", result)
+
}
func TestImagesUpdatesCheckRequiresImageRef(t *testing.T) {
outBuf, _, err := executeCLIIntegrationCommandInternal(t, []string{"images", "updates", "check"})
- if err == nil {
- t.Fatalf("expected missing image reference to fail, got output %q", outBuf)
- }
- if !strings.Contains(err.Error(), "1 arg") || !strings.Contains(err.Error(), "received 0") {
- t.Fatalf("unexpected argument error: %v", err)
- }
+
+ require.Error(t, err,
+ "expected missing image reference to fail, got output %q", outBuf)
+
+ require.False(t, !strings.Contains(err.Error(), "1 arg") || !strings.Contains(err.Error(), "received 0"),
+ "unexpected argument error: %v", err)
+
}
func TestImageUpdateCommandsDecodeExpectedResponseTypes(t *testing.T) {
@@ -327,46 +346,56 @@ func TestImageUpdateCommandsDecodeExpectedResponseTypes(t *testing.T) {
t,
[]string{"--config", configPath, "images", "updates", "check-all", "--json"},
)
- if err != nil {
- t.Fatalf("check-all: %v (%s)", err, errOut)
- }
+
+ require.NoError(t, err,
+ "check-all: %v (%s)", err, errOut)
+
var batch imageupdate.BatchResponse
- if err := json.Unmarshal([]byte(strings.TrimSpace(outBuf)), &batch); err != nil {
- t.Fatalf("batch response JSON parse failed: %v\noutput=%s", err, outBuf)
- }
- if batch["nginx:latest"] == nil || !batch["nginx:latest"].HasUpdate {
- t.Fatalf("unexpected batch response: %+v", batch)
+ {
+ err := json.Unmarshal([]byte(strings.TrimSpace(outBuf)), &batch)
+ require.NoError(t, err,
+ "batch response JSON parse failed: %v\noutput=%s", err, outBuf)
}
+ require.False(t, batch["nginx:latest"] == nil || !batch["nginx:latest"].HasUpdate,
+ "unexpected batch response: %+v", batch)
+
outBuf, errOut, err = executeCLIIntegrationCommandInternal(
t,
[]string{"--config", configPath, "images", "updates", "check-image", "image-123", "--json"},
)
- if err != nil {
- t.Fatalf("check-image: %v (%s)", err, errOut)
- }
+
+ require.NoError(t, err,
+ "check-image: %v (%s)", err, errOut)
+
var single imageupdate.Response
- if err := json.Unmarshal([]byte(strings.TrimSpace(outBuf)), &single); err != nil {
- t.Fatalf("single response JSON parse failed: %v\noutput=%s", err, outBuf)
- }
- if single.HasUpdate || single.CurrentVersion != "1.1.0" {
- t.Fatalf("unexpected image response: %+v", single)
+ {
+ err := json.Unmarshal([]byte(strings.TrimSpace(outBuf)), &single)
+ require.NoError(t, err,
+ "single response JSON parse failed: %v\noutput=%s", err, outBuf)
}
+ require.False(t, single.HasUpdate || single.CurrentVersion != "1.1.0",
+ "unexpected image response: %+v", single)
+
outBuf, errOut, err = executeCLIIntegrationCommandInternal(
t,
[]string{"--config", configPath, "images", "updates", "summary", "--json"},
)
- if err != nil {
- t.Fatalf("summary: %v (%s)", err, errOut)
- }
+
+ require.NoError(t, err,
+ "summary: %v (%s)", err, errOut)
+
var summary imageupdate.Summary
- if err := json.Unmarshal([]byte(strings.TrimSpace(outBuf)), &summary); err != nil {
- t.Fatalf("summary response JSON parse failed: %v\noutput=%s", err, outBuf)
- }
- if summary.TotalImages != 4 || summary.ImagesWithUpdates != 2 || summary.DigestUpdates != 1 {
- t.Fatalf("unexpected summary response: %+v", summary)
+ {
+ err := json.Unmarshal([]byte(strings.TrimSpace(outBuf)), &summary)
+ require.NoError(t, err,
+ "summary response JSON parse failed: %v\noutput=%s", err, outBuf)
}
+
+ require.False(t, summary.TotalImages != 4 || summary.ImagesWithUpdates != 2 || summary.DigestUpdates != 1,
+ "unexpected summary response: %+v", summary)
+
}
func TestImageUpdateCommandsRejectHTTPAndEnvelopeFailures(t *testing.T) {
@@ -413,15 +442,16 @@ func TestImageUpdateCommandsRejectHTTPAndEnvelopeFailures(t *testing.T) {
t.Run(command.name, func(t *testing.T) {
args := append([]string{"--config", configPath}, command.args...)
outBuf, _, err := executeCLIIntegrationCommandInternal(t, args)
- if err == nil {
- t.Fatalf("expected %s error, got success with output %q", failure.name, outBuf)
- }
- if !strings.Contains(err.Error(), failure.wantError) {
- t.Fatalf("expected error containing %q, got %v", failure.wantError, err)
- }
- if strings.TrimSpace(outBuf) != "" {
- t.Fatalf("failed response produced success output: %q", outBuf)
- }
+
+ require.Error(t, err,
+ "expected %s error, got success with output %q", failure.name, outBuf)
+
+ require.Contains(t, err.Error(), failure.wantError,
+ "expected error containing %q, got %v", failure.wantError, err)
+
+ require.Empty(t, strings.TrimSpace(outBuf),
+ "failed response produced success output: %q", outBuf)
+
})
}
})
diff --git a/cli/internal/types/config_test.go b/cli/internal/types/config_test.go
index a556ae258..0f7b21cc3 100644
--- a/cli/internal/types/config_test.go
+++ b/cli/internal/types/config_test.go
@@ -1,15 +1,22 @@
package types
-import "testing"
+import (
+ "testing"
+
+ "github.com/stretchr/testify/require"
+)
func TestConfigLimitForRepos(t *testing.T) {
cfg := &Config{}
cfg.SetResourceLimit("repos", 42)
for _, resource := range []string{"repos", "repo", "git-repositories", "git-repos"} {
- if got := cfg.LimitFor(resource); got != 42 {
- t.Fatalf("LimitFor(%q) = %d, want 42", resource, got)
+ {
+ got := cfg.LimitFor(resource)
+ require.Equal(t, 42, got,
+ "LimitFor(%q) = %d, want 42", resource, got)
}
+
}
}
@@ -21,8 +28,11 @@ func TestNormalizePaginatedResourceGitOpsSyncAliases(t *testing.T) {
"gitops",
"gitopssync",
} {
- if got := NormalizePaginatedResource(resource); got != "gitops-syncs" {
- t.Fatalf("NormalizePaginatedResource(%q) = %q, want %q", resource, got, "gitops-syncs")
+ {
+ got := NormalizePaginatedResource(resource)
+ require.Equal(t, "gitops-syncs", got,
+ "NormalizePaginatedResource(%q) = %q, want %q", resource, got, "gitops-syncs")
}
+
}
}
diff --git a/cli/pkg/config/cmd_test.go b/cli/pkg/config/cmd_test.go
index 211d0476c..b501b1c00 100644
--- a/cli/pkg/config/cmd_test.go
+++ b/cli/pkg/config/cmd_test.go
@@ -1,10 +1,10 @@
package config
import (
- "strings"
"testing"
clitypes "github.com/getarcaneapp/arcane/cli/v2/internal/types"
+ "github.com/stretchr/testify/require"
)
func TestApplyConfigSetArgs(t *testing.T) {
@@ -17,68 +17,80 @@ func TestApplyConfigSetArgs(t *testing.T) {
"pagination.resources.images.limit", "100",
"resource-limit.volumes", "40",
})
- if err != nil {
- t.Fatalf("applyConfigSetArgs() error = %v", err)
- }
- if !changed {
- t.Fatal("applyConfigSetArgs() changed = false, want true")
- }
- if cfg.ServerURL != "http://localhost:3552" {
- t.Fatalf("ServerURL = %q, want %q", cfg.ServerURL, "http://localhost:3552")
- }
- if cfg.APIKey != "arc_test_12345678" {
- t.Fatalf("APIKey = %q, want %q", cfg.APIKey, "arc_test_12345678")
- }
- if cfg.JWTToken != "" {
- t.Fatalf("JWTToken = %q, want empty", cfg.JWTToken)
- }
- if cfg.Pagination.Default.Limit != 25 {
- t.Fatalf("Pagination.Default.Limit = %d, want 25", cfg.Pagination.Default.Limit)
- }
- if got := cfg.LimitFor("images"); got != 100 {
- t.Fatalf("LimitFor(images) = %d, want 100", got)
+ require.NoError(t, err,
+ "applyConfigSetArgs() error = %v", err)
+
+ require.True(t, changed,
+ "applyConfigSetArgs() changed = false, want true")
+
+ require.Equal(t, "http://localhost:3552", cfg.ServerURL,
+ "ServerURL = %q, want %q", cfg.ServerURL, "http://localhost:3552")
+
+ require.Equal(t, "arc_test_12345678", cfg.APIKey,
+ "APIKey = %q, want %q", cfg.APIKey, "arc_test_12345678")
+
+ require.Empty(t, cfg.JWTToken,
+ "JWTToken = %q, want empty", cfg.JWTToken)
+
+ require.Equal(t, 25, cfg.Pagination.Default.Limit,
+ "Pagination.Default.Limit = %d, want 25", cfg.Pagination.Default.Limit)
+ {
+
+ got := cfg.LimitFor("images")
+ require.Equal(t, 100, got,
+ "LimitFor(images) = %d, want 100", got)
}
- if got := cfg.LimitFor("volumes"); got != 40 {
- t.Fatalf("LimitFor(volumes) = %d, want 40", got)
+ {
+
+ got := cfg.LimitFor("volumes")
+ require.Equal(t, 40, got,
+ "LimitFor(volumes) = %d, want 40", got)
}
+
}
func TestApplyConfigSetArgs_OddArgs(t *testing.T) {
cfg := &clitypes.Config{}
changed, err := applyConfigSetArgs(cfg, []string{"server-url", "http://localhost:3552", "api-key"})
- if err == nil {
- t.Fatal("expected error for odd key/value args, got nil")
- }
- if changed {
- t.Fatal("changed = true, want false")
- }
+
+ require.Error(t, err,
+ "expected error for odd key/value args, got nil")
+
+ require.False(t, changed,
+ "changed = true, want false")
+
}
func TestApplyConfigSetArg_UnknownKey(t *testing.T) {
cfg := &clitypes.Config{}
changed, err := applyConfigSetArg(cfg, "not-a-real-key", "value")
- if err == nil {
- t.Fatal("expected unknown key error, got nil")
- }
- if changed {
- t.Fatal("changed = true, want false")
- }
- if !strings.Contains(err.Error(), "unknown config key") {
- t.Fatalf("unexpected error: %v", err)
- }
+
+ require.Error(t, err,
+ "expected unknown key error, got nil")
+
+ require.False(t, changed,
+ "changed = true, want false")
+
+ require.Contains(t, err.Error(), "unknown config key",
+ "unexpected error: %v", err)
+
}
func TestApplyConfigSetArg_ResourceLimitPair(t *testing.T) {
cfg := &clitypes.Config{}
changed, err := applyConfigSetArg(cfg, "resource-limit", "containers=55")
- if err != nil {
- t.Fatalf("applyConfigSetArg() error = %v", err)
- }
- if !changed {
- t.Fatal("changed = false, want true")
- }
- if got := cfg.LimitFor("containers"); got != 55 {
- t.Fatalf("LimitFor(containers) = %d, want 55", got)
+
+ require.NoError(t, err,
+ "applyConfigSetArg() error = %v", err)
+
+ require.True(t, changed,
+ "changed = false, want true")
+ {
+
+ got := cfg.LimitFor("containers")
+ require.Equal(t, 55, got,
+ "LimitFor(containers) = %d, want 55", got)
}
+
}
diff --git a/cli/pkg/generate/api_key_test.go b/cli/pkg/generate/api_key_test.go
index e8d57f531..b5ea1ade0 100644
--- a/cli/pkg/generate/api_key_test.go
+++ b/cli/pkg/generate/api_key_test.go
@@ -5,6 +5,7 @@ import (
"testing"
gen "github.com/getarcaneapp/arcane/cli/v2/pkg/generate"
+ "github.com/stretchr/testify/require"
)
func TestAPIKeyDefaultOutput(t *testing.T) {
@@ -15,31 +16,31 @@ func TestAPIKeyDefaultOutput(t *testing.T) {
_, err := cmd.ExecuteC()
return err
})
- if err != nil {
- t.Fatalf("command failed: %v", err)
- }
-
- if strings.TrimSpace(out) == "" {
- t.Fatalf("expected raw arc_ key in output, got: %q", out)
- }
- if !strings.HasPrefix(strings.TrimSpace(out), "arc_") {
- t.Fatalf("expected raw arc_ key in output, got: %q", out)
- }
- if strings.Contains(out, "ADMIN_STATIC_API_KEY") {
- t.Fatalf("expected raw arc_ key in output, got: %q", out)
- }
+
+ require.NoError(t, err,
+ "command failed: %v", err)
+
+ require.NotEmpty(t, strings.TrimSpace(out),
+ "expected raw arc_ key in output, got: %q", out)
+
+ require.True(t, strings.HasPrefix(strings.TrimSpace(out), "arc_"),
+ "expected raw arc_ key in output, got: %q", out)
+
+ require.NotContains(t, out, "ADMIN_STATIC_API_KEY",
+ "expected raw arc_ key in output, got: %q", out)
+
}
func TestGenerateAPIKeyProducesArcanePrefix(t *testing.T) {
apiKey, err := gen.GenerateAPIKey()
- if err != nil {
- t.Fatalf("GenerateAPIKey failed: %v", err)
- }
-
- if !strings.HasPrefix(apiKey, "arc_") {
- t.Fatalf("expected arc_ prefix, got %q", apiKey)
- }
- if len(apiKey) != 68 {
- t.Fatalf("expected 68-character key, got %d (%q)", len(apiKey), apiKey)
- }
+
+ require.NoError(t, err,
+ "GenerateAPIKey failed: %v", err)
+
+ require.True(t, strings.HasPrefix(apiKey, "arc_"),
+ "expected arc_ prefix, got %q", apiKey)
+
+ require.Len(t, apiKey, 68,
+ "expected 68-character key, got %d (%q)", len(apiKey), apiKey)
+
}
diff --git a/cli/pkg/generate/certs_test.go b/cli/pkg/generate/certs_test.go
index b47e53e1c..7876d4ddf 100644
--- a/cli/pkg/generate/certs_test.go
+++ b/cli/pkg/generate/certs_test.go
@@ -11,6 +11,7 @@ import (
"testing"
gen "github.com/getarcaneapp/arcane/cli/v2/pkg/generate"
+ "github.com/stretchr/testify/require"
)
func TestGenerateMTLSCommandWritesECDSAP384Assets(t *testing.T) {
@@ -23,17 +24,18 @@ func TestGenerateMTLSCommandWritesECDSAP384Assets(t *testing.T) {
_, err := cmd.ExecuteC()
return err
})
- if err != nil {
- t.Fatalf("command failed: %v", err)
- }
+
+ require.NoError(t, err,
+ "command failed: %v", err)
assertECDSAP384PrivateKey(t, filepath.Join(outDir, "ca.key"))
assertECDSAP384PrivateKey(t, filepath.Join(outDir, "agent.key"))
assertECDSAP384Certificate(t, filepath.Join(outDir, "ca.crt"))
cert := assertECDSAP384Certificate(t, filepath.Join(outDir, "agent.crt"))
- if len(cert.URIs) == 0 || cert.URIs[0].String() != "spiffe://manager.example.com/edge/env-123" {
- t.Fatalf("expected edge SPIFFE URI SAN, got %v", cert.URIs)
- }
+
+ require.False(t, len(cert.URIs) == 0 || cert.URIs[0].String() != "spiffe://manager.example.com/edge/env-123",
+ "expected edge SPIFFE URI SAN, got %v", cert.URIs)
+
}
func TestGenerateTLSCommandWritesECDSAP384ServerCert(t *testing.T) {
@@ -46,19 +48,19 @@ func TestGenerateTLSCommandWritesECDSAP384ServerCert(t *testing.T) {
_, err := cmd.ExecuteC()
return err
})
- if err != nil {
- t.Fatalf("command failed: %v", err)
- }
+
+ require.NoError(t, err,
+ "command failed: %v", err)
assertECDSAP384PrivateKey(t, filepath.Join(outDir, "local-manager.key"))
cert := assertECDSAP384Certificate(t, filepath.Join(outDir, "local-manager.crt"))
- if len(cert.DNSNames) == 0 || cert.DNSNames[0] != "localhost" {
- t.Fatalf("expected localhost DNS SAN, got %v", cert.DNSNames)
- }
- if len(cert.IPAddresses) == 0 || !cert.IPAddresses[0].Equal(net.ParseIP("127.0.0.1")) {
- t.Fatalf("expected 127.0.0.1 IP SAN, got %v", cert.IPAddresses)
- }
+ require.False(t, len(cert.DNSNames) == 0 || cert.DNSNames[0] != "localhost",
+ "expected localhost DNS SAN, got %v", cert.DNSNames)
+
+ require.False(t, len(cert.IPAddresses) == 0 || !cert.IPAddresses[0].Equal(net.ParseIP("127.0.0.1")),
+ "expected 127.0.0.1 IP SAN, got %v", cert.IPAddresses)
+
}
func TestGenerateTLSCommandOverwritesCertificateAtomically(t *testing.T) {
@@ -70,91 +72,98 @@ func TestGenerateTLSCommandOverwritesCertificateAtomically(t *testing.T) {
_, err := cmd.ExecuteC()
return err
})
- if err != nil {
- t.Fatalf("command failed: %v", err)
- }
+
+ require.NoError(t, err,
+ "command failed: %v", err)
certPath := filepath.Join(outDir, "server.crt")
keyPath := filepath.Join(outDir, "server.key")
firstCert, err := os.ReadFile(certPath)
- if err != nil {
- t.Fatalf("failed to read first cert: %v", err)
- }
+
+ require.NoError(t, err,
+ "failed to read first cert: %v", err)
cmd.SetArgs([]string{"tls", "--out-dir", outDir, "--common-name", "localhost", "--host", "localhost", "--cert-name", "server.crt", "--key-name", "server.key"})
_, err = captureOutput(func() error {
_, err := cmd.ExecuteC()
return err
})
- if err != nil {
- t.Fatalf("command failed: %v", err)
- }
+
+ require.NoError(t, err,
+ "command failed: %v", err)
secondCert, err := os.ReadFile(certPath)
- if err != nil {
- t.Fatalf("failed to read second cert: %v", err)
- }
- if string(firstCert) == string(secondCert) {
- t.Fatalf("expected certificate to be replaced on second generation")
- }
+
+ require.NoError(t, err,
+ "failed to read second cert: %v", err)
+
+ require.NotEqual(t, string(secondCert), string(firstCert),
+ "expected certificate to be replaced on second generation")
+
assertECDSAP384Certificate(t, certPath)
assertECDSAP384PrivateKey(t, keyPath)
tmpFiles, err := filepath.Glob(filepath.Join(outDir, "*.tmp-*"))
- if err != nil {
- t.Fatalf("failed to glob temp files: %v", err)
- }
- if len(tmpFiles) != 0 {
- t.Fatalf("expected atomic write temp files to be cleaned up, got %v", tmpFiles)
- }
+
+ require.NoError(t, err,
+ "failed to glob temp files: %v", err)
+
+ require.Empty(t, tmpFiles,
+ "expected atomic write temp files to be cleaned up, got %v", tmpFiles)
+
}
func assertECDSAP384PrivateKey(t *testing.T, path string) {
t.Helper()
pemBytes, err := os.ReadFile(path)
- if err != nil {
- t.Fatalf("failed to read key %s: %v", path, err)
- }
+
+ require.NoError(t, err,
+ "failed to read key %s: %v", path, err)
+
block, _ := pem.Decode(pemBytes)
- if block == nil {
- t.Fatalf("failed to decode key PEM %s", path)
- }
- if block.Type != "EC PRIVATE KEY" {
- t.Fatalf("expected EC PRIVATE KEY for %s, got %s", path, block.Type)
- }
+
+ require.NotNil(t, block,
+ "failed to decode key PEM %s", path)
+
+ require.Equal(t, "EC PRIVATE KEY", block.Type,
+ "expected EC PRIVATE KEY for %s, got %s", path, block.Type)
key, err := x509.ParseECPrivateKey(block.Bytes)
- if err != nil {
- t.Fatalf("failed to parse EC private key %s: %v", path, err)
- }
- if key.Curve != elliptic.P384() {
- t.Fatalf("expected P-384 private key for %s", path)
- }
+
+ require.NoError(t, err,
+ "failed to parse EC private key %s: %v", path, err)
+
+ require.Equal(t, elliptic.P384(), key.Curve,
+ "expected P-384 private key for %s", path)
+
}
func assertECDSAP384Certificate(t *testing.T, path string) *x509.Certificate {
t.Helper()
pemBytes, err := os.ReadFile(path)
- if err != nil {
- t.Fatalf("failed to read certificate %s: %v", path, err)
- }
+
+ require.NoError(t, err,
+ "failed to read certificate %s: %v", path, err)
+
block, _ := pem.Decode(pemBytes)
- if block == nil {
- t.Fatalf("failed to decode certificate PEM %s", path)
- }
+
+ require.NotNil(t, block,
+ "failed to decode certificate PEM %s", path)
cert, err := x509.ParseCertificate(block.Bytes)
- if err != nil {
- t.Fatalf("failed to parse certificate %s: %v", path, err)
- }
+
+ require.NoError(t, err,
+ "failed to parse certificate %s: %v", path, err)
+
publicKey, ok := cert.PublicKey.(*ecdsa.PublicKey)
- if !ok {
- t.Fatalf("expected ECDSA public key for %s", path)
- }
- if publicKey.Curve != elliptic.P384() {
- t.Fatalf("expected P-384 certificate for %s", path)
- }
+
+ require.True(t, ok,
+ "expected ECDSA public key for %s", path)
+
+ require.Equal(t, elliptic.P384(), publicKey.Curve,
+ "expected P-384 certificate for %s", path)
+
return cert
}
diff --git a/cli/pkg/generate/secret_test.go b/cli/pkg/generate/secret_test.go
index 2eb5f245e..16d7e70d8 100644
--- a/cli/pkg/generate/secret_test.go
+++ b/cli/pkg/generate/secret_test.go
@@ -10,9 +10,11 @@ import (
"testing"
gen "github.com/getarcaneapp/arcane/cli/v2/pkg/generate"
+ "github.com/stretchr/testify/require"
)
// captureOutput captures stdout produced by fn and returns it as a string.
+
func captureOutput(fn func() error) (string, error) {
// Save original
oldOut := os.Stdout
@@ -43,18 +45,17 @@ func TestSecretDefaultBase64(t *testing.T) {
_, err := cmd.ExecuteC()
return err
})
- if err != nil {
- t.Fatalf("command failed: %v", err)
- }
+
+ require.NoError(t, err,
+ "command failed: %v", err)
// should not include emoji characters used previously
- if strings.Contains(out, "πŸ“‹") || strings.Contains(out, "🐳") || strings.Contains(out, "πŸ”’") || strings.Contains(out, "⚠️") {
- t.Fatalf("output contains emoji/box characters: %q", out)
- }
- if !strings.Contains(out, "BASE64") {
- t.Fatalf("expected BASE64 header in output, got: %q", out)
- }
+ require.False(t, strings.Contains(out, "πŸ“‹") || strings.Contains(out, "🐳") || strings.Contains(out, "πŸ”’") || strings.Contains(out, "⚠️"),
+ "output contains emoji/box characters: %q", out)
+
+ require.Contains(t, out, "BASE64",
+ "expected BASE64 header in output, got: %q", out)
// find ENCRYPTION_KEY= and JWT_SECRET= lines and ensure they are valid base64
var encVal, jwtVal string
@@ -66,19 +67,21 @@ func TestSecretDefaultBase64(t *testing.T) {
jwtVal = after
}
}
- if encVal == "" || jwtVal == "" {
- t.Fatalf("missing keys in output: enc=%q jwt=%q out=%q", encVal, jwtVal, out)
- }
+
+ require.False(t, encVal == "" || jwtVal == "",
+ "missing keys in output: enc=%q jwt=%q out=%q", encVal, jwtVal, out)
if b, err := base64.StdEncoding.DecodeString(encVal); err != nil {
- t.Fatalf("ENCRYPTION_KEY is not valid base64: %v (value=%q)", err, encVal)
+ require.FailNowf(t, "unexpected failure", "ENCRYPTION_KEY is not valid base64: %v (value=%q)", err, encVal)
} else if len(b) != 32 {
- t.Fatalf("ENCRYPTION_KEY decoded length != 32 bytes: %d", len(b))
+ require.Len(t, b, 32,
+ "ENCRYPTION_KEY decoded length != 32 bytes: %d", len(b))
}
if b, err := base64.StdEncoding.DecodeString(jwtVal); err != nil {
- t.Fatalf("JWT_SECRET is not valid base64: %v (value=%q)", err, jwtVal)
+ require.FailNowf(t, "unexpected failure", "JWT_SECRET is not valid base64: %v (value=%q)", err, jwtVal)
} else if len(b) != 32 {
- t.Fatalf("JWT_SECRET decoded length != 32 bytes: %d", len(b))
+ require.Len(t, b, 32,
+ "JWT_SECRET decoded length != 32 bytes: %d", len(b))
}
}
@@ -90,13 +93,12 @@ func TestSecretAllFormatContainsSections(t *testing.T) {
_, err := cmd.ExecuteC()
return err
})
- if err != nil {
- t.Fatalf("command failed: %v", err)
- }
- if strings.Contains(out, "πŸ“‹") || strings.Contains(out, "🐳") || strings.Contains(out, "πŸ”’") || strings.Contains(out, "⚠️") {
- t.Fatalf("output contains emoji/box characters: %q", out)
- }
+ require.NoError(t, err,
+ "command failed: %v", err)
+
+ require.False(t, strings.Contains(out, "πŸ“‹") || strings.Contains(out, "🐳") || strings.Contains(out, "πŸ”’") || strings.Contains(out, "⚠️"),
+ "output contains emoji/box characters: %q", out)
// verify presence of expected section headers
mustContain := []string{
@@ -105,9 +107,10 @@ func TestSecretAllFormatContainsSections(t *testing.T) {
"HEX",
}
for _, s := range mustContain {
- if !strings.Contains(out, s) {
- t.Fatalf("expected section %q not found in output:\n%s", s, out)
- }
+
+ require.Contains(t, out, s,
+ "expected section %q not found in output:\n%s", s, out)
+
}
// verify hex values decode to 32 bytes
@@ -129,17 +132,20 @@ func TestSecretAllFormatContainsSections(t *testing.T) {
}
}
}
- if hexEnc == "" || hexJwt == "" {
- t.Fatalf("hex values not found in output (enc=%q jwt=%q) output:\n%s", hexEnc, hexJwt, out)
- }
+
+ require.False(t, hexEnc == "" || hexJwt == "",
+ "hex values not found in output (enc=%q jwt=%q) output:\n%s", hexEnc, hexJwt, out)
+
if b, err := hex.DecodeString(strings.TrimSpace(hexEnc)); err != nil {
- t.Fatalf("ENCRYPTION_KEY hex decode failed: %v", err)
+ require.FailNowf(t, "unexpected failure", "ENCRYPTION_KEY hex decode failed: %v", err)
} else if len(b) != 32 {
- t.Fatalf("ENCRYPTION_KEY hex decoded length != 32: %d", len(b))
+ require.Len(t, b, 32,
+ "ENCRYPTION_KEY hex decoded length != 32: %d", len(b))
}
if b, err := hex.DecodeString(strings.TrimSpace(hexJwt)); err != nil {
- t.Fatalf("JWT_SECRET hex decode failed: %v", err)
+ require.FailNowf(t, "unexpected failure", "JWT_SECRET hex decode failed: %v", err)
} else if len(b) != 32 {
- t.Fatalf("JWT_SECRET hex decoded length != 32: %d", len(b))
+ require.Len(t, b, 32,
+ "JWT_SECRET hex decoded length != 32: %d", len(b))
}
}
diff --git a/cli/pkg/selfupdate/cmd_test.go b/cli/pkg/selfupdate/cmd_test.go
index 43ed44179..8f86cc3ca 100644
--- a/cli/pkg/selfupdate/cmd_test.go
+++ b/cli/pkg/selfupdate/cmd_test.go
@@ -3,30 +3,34 @@ package selfupdate
import (
"strings"
"testing"
+
+ "github.com/stretchr/testify/require"
)
func TestFindChecksumMatchesNextDistPath(t *testing.T) {
checksums := "abc123 dist/arcane-cli_darwin_arm64_v8.0/arcane-cli\n"
got, err := findChecksumInternal(checksums, "arcane-cli_darwin_arm64_v8.0/arcane-cli", "arcane-cli_darwin_arm64")
- if err != nil {
- t.Fatalf("findChecksum returned error: %v", err)
- }
- if got != "abc123" {
- t.Fatalf("findChecksum = %q, want abc123", got)
- }
+
+ require.NoError(t, err,
+ "findChecksum returned error: %v", err)
+
+ require.Equal(t, "abc123", got,
+ "findChecksum = %q, want abc123", got)
+
}
func TestFindChecksumMatchesArchiveBasename(t *testing.T) {
checksums := "def456 dist/arcane-cli_linux_amd64.tar.gz\n"
got, err := findChecksumInternal(checksums, "arcane-cli_linux_amd64.tar.gz")
- if err != nil {
- t.Fatalf("findChecksum returned error: %v", err)
- }
- if got != "def456" {
- t.Fatalf("findChecksum = %q, want def456", got)
- }
+
+ require.NoError(t, err,
+ "findChecksum returned error: %v", err)
+
+ require.Equal(t, "def456", got,
+ "findChecksum = %q, want def456", got)
+
}
func TestChecksumEntryNames(t *testing.T) {
@@ -35,29 +39,32 @@ func TestChecksumEntryNames(t *testing.T) {
got := checksumEntryNamesInternal(checksums)
want := []string{"arcane-cli_darwin_arm64", "dist/arcane-cli_linux_amd64.tar.gz"}
if len(got) != len(want) {
- t.Fatalf("checksumEntryNames length = %d, want %d (%v)", len(got), len(want), got)
+ require.Len(t, got, len(want),
+ "checksumEntryNames length = %d, want %d (%v)", len(got), len(want), got)
}
for i := range want {
- if got[i] != want[i] {
- t.Fatalf("checksumEntryNames[%d] = %q, want %q", i, got[i], want[i])
- }
+
+ require.Equal(t, want[i], got[i],
+ "checksumEntryNames[%d] = %q, want %q", i, got[i], want[i])
+
}
}
func TestCLIArtifactNamesUseFlatR2BinaryNames(t *testing.T) {
platformName, err := cliPlatformNameInternal()
- if err != nil {
- t.Fatalf("cliPlatformName returned error: %v", err)
- }
- if strings.HasPrefix(platformName, "arcane-cli_") || strings.Contains(platformName, "/") || strings.HasSuffix(platformName, ".tar.gz") {
- t.Fatalf("platformName = %q, want bare platform name", platformName)
- }
+
+ require.NoError(t, err,
+ "cliPlatformName returned error: %v", err)
+
+ require.False(t, strings.HasPrefix(platformName, "arcane-cli_") || strings.Contains(platformName, "/") || strings.HasSuffix(platformName, ".tar.gz"),
+ "platformName = %q, want bare platform name", platformName)
artifactName, err := cliRawArtifactNameInternal()
- if err != nil {
- t.Fatalf("cliRawArtifactName returned error: %v", err)
- }
- if artifactName != "arcane-cli_"+platformName {
- t.Fatalf("artifactName = %q, want %q", artifactName, "arcane-cli_"+platformName)
- }
+
+ require.NoError(t, err,
+ "cliRawArtifactName returned error: %v", err)
+
+ require.Equal(t, "arcane-cli_"+platformName, artifactName,
+ "artifactName = %q, want %q", artifactName, "arcane-cli_"+platformName)
+
}
diff --git a/types/dockerinfo/docker_info_test.go b/types/dockerinfo/docker_info_test.go
index 84a2992c0..5dc79877d 100644
--- a/types/dockerinfo/docker_info_test.go
+++ b/types/dockerinfo/docker_info_test.go
@@ -5,6 +5,7 @@ import (
"testing"
"github.com/moby/moby/api/types/system"
+ "github.com/stretchr/testify/require"
)
func TestInfoMarshalsEmbeddedDockerFieldsAtTopLevel(t *testing.T) {
@@ -18,13 +19,15 @@ func TestInfoMarshalsEmbeddedDockerFieldsAtTopLevel(t *testing.T) {
Success: true,
APIVersion: "1.55",
})
- if err != nil {
- t.Fatalf("marshal Docker info: %v", err)
- }
+
+ require.NoError(t, err,
+ "marshal Docker info: %v", err)
var payload map[string]any
- if err := json.Unmarshal(data, &payload); err != nil {
- t.Fatalf("unmarshal Docker info payload: %v", err)
+ {
+ err := json.Unmarshal(data, &payload)
+ require.NoError(t, err,
+ "unmarshal Docker info payload: %v", err)
}
for name, want := range map[string]any{
@@ -33,11 +36,17 @@ func TestInfoMarshalsEmbeddedDockerFieldsAtTopLevel(t *testing.T) {
"ContainersRunning": float64(3),
"apiVersion": "1.55",
} {
- if got := payload[name]; got != want {
- t.Fatalf("payload[%q] = %#v, want %#v; payload: %s", name, got, want, data)
+ {
+ got := payload[name]
+ require.Equal(t, want, got,
+ "payload[%q] = %#v, want %#v; payload: %s", name, got, want, data)
}
+
}
- if _, nested := payload["Info"]; nested {
- t.Fatalf("Docker fields were nested under Info: %s", data)
+ {
+ _, nested := payload["Info"]
+ require.False(t, nested,
+ "Docker fields were nested under Info: %s", data)
}
+
}
diff --git a/types/go.mod b/types/go.mod
index abddb0562..30d7bb21c 100644
--- a/types/go.mod
+++ b/types/go.mod
@@ -8,6 +8,7 @@ require (
github.com/docker/go-units v0.5.0
github.com/moby/moby/api v1.55.0
github.com/moby/moby/client v0.5.1
+ github.com/stretchr/testify v1.11.1
)
require (
@@ -39,4 +40,5 @@ require (
go.yaml.in/yaml/v4 v4.0.0-rc.6 // indirect
golang.org/x/sync v0.22.0 // indirect
golang.org/x/sys v0.47.0 // indirect
+ gopkg.in/yaml.v3 v3.0.1 // indirect
)
diff --git a/types/go.sum b/types/go.sum
index c8569d6db..d41da1e84 100644
--- a/types/go.sum
+++ b/types/go.sum
@@ -33,6 +33,10 @@ github.com/google/go-cmp v0.7.0 h1:wk8382ETsv4JYUZwIsn6YpYiWiBsYLSJiTsyBybVuN8=
github.com/google/go-cmp v0.7.0/go.mod h1:pXiqmnSA92OHEEa9HXL2W4E7lf9JzCmGVUdgjX3N/iU=
github.com/google/uuid v1.6.0 h1:NIvaJDMOsjHA8n1jAhLSgzrAzy1Hgr+hNrb57e+94F0=
github.com/google/uuid v1.6.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo=
+github.com/kr/pretty v0.3.1 h1:flRD4NNwYAUpkphVc1HcthR4KEIFJ65n8Mw5qdRn3LE=
+github.com/kr/pretty v0.3.1/go.mod h1:hoEshYVHaxMs3cyo3Yncou5ZscifuDolrwPKZanG3xk=
+github.com/kr/text v0.2.0 h1:5Nx0Ya0ZqY2ygV366QzturHI13Jq95ApcVaJBhpS+AY=
+github.com/kr/text v0.2.0/go.mod h1:eLer722TekiGuMkidMxC/pM04lWEeraHUUmBw8l2grE=
github.com/mattn/go-shellwords v1.0.13 h1:DC0OMEpGjm6LfNFU4ckYcvbQKyp2vE8atyFGXNtDcf4=
github.com/mattn/go-shellwords v1.0.13/go.mod h1:EZzvwXDESEeg03EKmM+RmDnNOPKG4lLtQsUlTZDWQ8Y=
github.com/moby/docker-image-spec v1.3.1 h1:jMKff3w6PgbfSa69GfNg+zN/XLhfXJGnEx3Nl2EsFP0=
@@ -50,6 +54,8 @@ github.com/pkg/errors v0.9.1/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINE
github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
github.com/pmezard/go-difflib v1.0.1-0.20181226105442-5d4384ee4fb2 h1:Jamvg5psRIccs7FGNTlIRMkT8wgtp5eCXdBlqhYGL6U=
github.com/pmezard/go-difflib v1.0.1-0.20181226105442-5d4384ee4fb2/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
+github.com/rogpeppe/go-internal v1.14.1 h1:UQB4HGPB6osV0SQTLymcB4TgvyWu6ZyliaW0tI/otEQ=
+github.com/rogpeppe/go-internal v1.14.1/go.mod h1:MaRKkUm5W0goXpeCfT7UZI6fk/L7L7so1lCWt35ZSgc=
github.com/sirupsen/logrus v1.9.4 h1:TsZE7l11zFCLZnZ+teH4Umoq5BhEIfIzfRDZ1Uzql2w=
github.com/sirupsen/logrus v1.9.4/go.mod h1:ftWc9WdOfJ0a92nsE2jF5u5ZwH8Bv2zdeOC42RjbV2g=
github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME=
@@ -82,6 +88,9 @@ golang.org/x/sync v0.22.0 h1:SZjpbeLmrCk4xhRSZFNZW5gFUeCeFgjekvI/+gfScek=
golang.org/x/sync v0.22.0/go.mod h1:9xrNwdLfx4jkKbNva9FpL6vEN7evnE43NNNJQ2LF3+0=
golang.org/x/sys v0.47.0 h1:o7XGOvZQCADBQQ4Y7VNq2dRWQR7JmOUW8Kxx4ZsNgWs=
golang.org/x/sys v0.47.0/go.mod h1:4GL1E5IUh+htKOUEOaiffhrAeqysfVGipDYzABqnCmw=
+gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
+gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c h1:Hei/4ADfdWqJk1ZMxUNpqntNwaWcugrBjAiHlqqRiVk=
+gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c/go.mod h1:JHkPIbrfpd72SG/EVd6muEfDQjcINNoR0C8j2r3qZ4Q=
gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA=
gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
gotest.tools/v3 v3.5.2 h1:7koQfIKdy+I8UTetycgUqXWSDwpgv193Ka+qRsmBY8Q=
diff --git a/types/project/marshal_utils_test.go b/types/project/marshal_utils_test.go
index 6a78640e6..c6a20765e 100644
--- a/types/project/marshal_utils_test.go
+++ b/types/project/marshal_utils_test.go
@@ -5,6 +5,7 @@ import (
"testing"
composetypes "github.com/compose-spec/compose-go/v2/types"
+ "github.com/stretchr/testify/require"
)
func TestDetailsUnmarshalJSONAcceptsUnitBytesStringsAndNumbers(t *testing.T) {
@@ -26,15 +27,19 @@ func TestDetailsUnmarshalJSONAcceptsUnitBytesStringsAndNumbers(t *testing.T) {
t.Run(test.name, func(t *testing.T) {
var details Details
err := json.Unmarshal([]byte(test.payload), &details)
- if err != nil {
- t.Fatalf("unmarshal Details: %v", err)
- }
- if len(details.Services) != 1 {
- t.Fatalf("decoded %d services, want 1", len(details.Services))
- }
- if got, want := details.Services[0].MemLimit, composetypes.UnitBytes(256*1024*1024); got != want {
- t.Fatalf("mem_limit = %d, want %d", got, want)
+
+ require.NoError(t, err,
+ "unmarshal Details: %v", err)
+
+ require.Len(t, details.Services, 1,
+ "decoded %d services, want 1", len(details.Services))
+ {
+
+ got, want := details.Services[0].MemLimit, composetypes.UnitBytes(256*1024*1024)
+ require.Equal(t, want, got,
+ "mem_limit = %d, want %d", got, want)
}
+
})
}
}
diff --git a/types/swarm/node_test.go b/types/swarm/node_test.go
index b32eb9d30..30a12d66e 100644
--- a/types/swarm/node_test.go
+++ b/types/swarm/node_test.go
@@ -5,25 +5,30 @@ import (
"reflect"
"strings"
"testing"
+
+ "github.com/stretchr/testify/require"
)
func TestNodeAgentStatusLegacyJSONCompatibility(t *testing.T) {
var status NodeAgentStatus
- if err := json.Unmarshal([]byte(`{"state":"connected","environmentId":"env-1","connected":true}`), &status); err != nil {
- t.Fatalf("unmarshal legacy status: %v", err)
- }
- if status.State != NodeAgentStateConnected {
- t.Fatalf("state = %q, want %q", status.State, NodeAgentStateConnected)
- }
- if status.EnvironmentID == nil || *status.EnvironmentID != "env-1" {
- t.Fatalf("environmentId = %v, want env-1", status.EnvironmentID)
- }
- if status.BindingKind != nil {
- t.Fatalf("bindingKind = %v, want nil", *status.BindingKind)
- }
- if len(status.Candidates) != 0 {
- t.Fatalf("candidates = %v, want empty", status.Candidates)
+ {
+ err := json.Unmarshal([]byte(`{"state":"connected","environmentId":"env-1","connected":true}`), &status)
+ require.NoError(t, err,
+ "unmarshal legacy status: %v", err)
}
+
+ require.Equal(t, NodeAgentStateConnected, status.State,
+ "state = %q, want %q", status.State, NodeAgentStateConnected)
+
+ require.False(t, status.EnvironmentID == nil || *status.EnvironmentID != "env-1",
+ "environmentId = %v, want env-1", status.EnvironmentID)
+
+ require.Nil(t, status.BindingKind,
+ "bindingKind = %v, want nil", status.BindingKind)
+
+ require.Empty(t, status.Candidates,
+ "candidates = %v, want empty", status.Candidates)
+
}
func TestNodeAgentStatusAmbiguousJSON(t *testing.T) {
@@ -37,28 +42,36 @@ func TestNodeAgentStatusAmbiguousJSON(t *testing.T) {
}
encoded, err := json.Marshal(status)
- if err != nil {
- t.Fatalf("marshal ambiguous status: %v", err)
- }
+
+ require.NoError(t, err,
+ "marshal ambiguous status: %v", err)
+
var actual, expected any
- if err := json.Unmarshal(encoded, &actual); err != nil {
- t.Fatalf("unmarshal actual JSON: %v", err)
- }
- if err := json.Unmarshal([]byte(`{"state":"ambiguous","candidates":[{"environmentId":"env-1","environmentName":"worker-1","environmentType":"edge"}]}`), &expected); err != nil {
- t.Fatalf("unmarshal expected JSON: %v", err)
+ {
+ err := json.Unmarshal(encoded, &actual)
+ require.NoError(t, err,
+ "unmarshal actual JSON: %v", err)
}
- if !reflect.DeepEqual(actual, expected) {
- t.Fatalf("JSON = %s, want ambiguous candidate payload", encoded)
+ {
+
+ err := json.Unmarshal([]byte(`{"state":"ambiguous","candidates":[{"environmentId":"env-1","environmentName":"worker-1","environmentType":"edge"}]}`), &expected)
+ require.NoError(t, err,
+ "unmarshal expected JSON: %v", err)
}
+
+ require.True(t, reflect.DeepEqual(actual, expected),
+ "JSON = %s, want ambiguous candidate payload", encoded)
+
}
func TestSwarmJoinEnvironmentResultDoesNotExposeToken(t *testing.T) {
result := SwarmJoinEnvironmentResult{EnvironmentID: "env-1", State: SwarmJoinEnvironmentResultJoined}
encoded, err := json.Marshal(result)
- if err != nil {
- t.Fatalf("marshal join result: %v", err)
- }
- if string(encoded) == "" || strings.Contains(string(encoded), "token") {
- t.Fatalf("join result unexpectedly exposes a token field: %s", encoded)
- }
+
+ require.NoError(t, err,
+ "marshal join result: %v", err)
+
+ require.False(t, string(encoded) == "" || strings.Contains(string(encoded), "token"),
+ "join result unexpectedly exposes a token field: %s", encoded)
+
}