diff --git a/.golangci.yml b/.golangci.yml index 775851d3066a..3204ba9699e7 100644 --- a/.golangci.yml +++ b/.golangci.yml @@ -13,7 +13,12 @@ linters: - noctx - unparam - usestdlibvars + - hypershiftlinter settings: + custom: + hypershiftlinter: + path: hack/tools/bin/hypershiftlinter.so + description: "Enforces HyperShift test conventions from TESTING.md and test/e2e/v2/AGENTS.md" gocyclo: min-complexity: 30 govet: diff --git a/Makefile b/Makefile index 39e74aba7a8f..6ebc2f5de956 100644 --- a/Makefile +++ b/Makefile @@ -103,7 +103,7 @@ $(KUBEAPILINTER_PLUGIN): $(TOOLS_DIR)/go.mod # Build kube-api-linter as Go plugi HYPERSHIFTLINTER_PLUGIN := $(abspath $(TOOLS_BIN_DIR)/hypershiftlinter.so) HYPERSHIFTLINTER_SRC := $(shell find $(TOOLS_DIR)/hypershiftlinter -name '*.go' 2>/dev/null) $(HYPERSHIFTLINTER_PLUGIN): $(TOOLS_DIR)/go.mod $(HYPERSHIFTLINTER_SRC) # Build hypershiftlinter as Go plugin - cd $(TOOLS_DIR); $(GO) build -a -buildmode=plugin -o $(HYPERSHIFTLINTER_PLUGIN) ./hypershiftlinter/cmd/plugin + cd $(TOOLS_DIR); CGO_ENABLED=1 $(GO) build -a -buildmode=plugin -o $(HYPERSHIFTLINTER_PLUGIN) ./hypershiftlinter/cmd/plugin # When not otherwise set, diff/lint against the upstream main branch. # This is always set in OpenShift CI. @@ -123,13 +123,13 @@ precommit-api-lint-fix: $(GOLANGCI_LINT) cd api && $(GOLANGCI_LINT) fmt --config ./.golangci.yml --enable gci $(patsubst api/%,%,$(FILES)) .PHONY: lint -lint: generate +lint: generate $(HYPERSHIFTLINTER_PLUGIN) $(MAKE) api-lint; api_rc=$$?; \ $(GOLANGCI_LINT) run --config ./.golangci.yml --modules-download-mode=readonly -v; main_rc=$$?; \ exit $$(( api_rc > main_rc ? api_rc : main_rc )) .PHONY: main-lint-fix -main-lint-fix: generate $(GOLANGCI_LINT) +main-lint-fix: generate $(GOLANGCI_LINT) $(HYPERSHIFTLINTER_PLUGIN) $(GOLANGCI_LINT) run --config ./.golangci.yml --fix -v $(if $(PULL_BASE_SHA),--new-from-rev=$(PULL_BASE_SHA) --whole-files) .PHONY: precommit-main-lint-fix @@ -137,7 +137,7 @@ precommit-main-lint-fix: $(GOLANGCI_LINT) $(GOLANGCI_LINT) fmt --config ./.golangci.yml --enable gci $(FILES) .PHONY: lint-fix -lint-fix: generate +lint-fix: generate $(HYPERSHIFTLINTER_PLUGIN) $(MAKE) api-lint-fix; api_rc=$$?; \ $(GOLANGCI_LINT) run --config ./.golangci.yml --fix -v; main_rc=$$?; \ exit $$(( api_rc > main_rc ? api_rc : main_rc )) diff --git a/api/karpenter/v1/kubelet_config_test.go b/api/karpenter/v1/kubelet_config_test.go index be17f6a3ad2b..ac8244cdd72f 100644 --- a/api/karpenter/v1/kubelet_config_test.go +++ b/api/karpenter/v1/kubelet_config_test.go @@ -14,7 +14,7 @@ func TestKubeletConfigurationMarshalRoundTrip(t *testing.T) { config KubeletConfiguration }{ { - name: "When all typed fields are set they should round-trip", + name: "When all typed fields are set, it should round-trip", config: KubeletConfiguration{ MaxPods: 110, PodsPerCore: 10, @@ -42,7 +42,7 @@ func TestKubeletConfigurationMarshalRoundTrip(t *testing.T) { }, }, { - name: "When only some fields are set they should round-trip", + name: "When only some fields are set, it should round-trip", config: KubeletConfiguration{ MaxPods: 50, CPUCFSQuota: ptr.To(false), diff --git a/cmd/cluster/agent/create_test.go b/cmd/cluster/agent/create_test.go index 0a35cd1bc06b..9757bf7ec07d 100644 --- a/cmd/cluster/agent/create_test.go +++ b/cmd/cluster/agent/create_test.go @@ -33,7 +33,7 @@ func TestCreateCluster(t *testing.T) { args []string }{ { - name: "minimal flags necessary to render", + name: "When minimal flags are provided, it should render successfully", args: []string{ "--api-server-address=fakeAddress", // if we don't set it, the machine's IP is looked up, which isn't portable "--render-sensitive", diff --git a/cmd/cluster/agent/testdata/zz_fixture_TestCreateCluster_minimal_flags_necessary_to_render.yaml b/cmd/cluster/agent/testdata/zz_fixture_TestCreateCluster_When_minimal_flags_are_provided__it_should_render_successfully.yaml similarity index 100% rename from cmd/cluster/agent/testdata/zz_fixture_TestCreateCluster_minimal_flags_necessary_to_render.yaml rename to cmd/cluster/agent/testdata/zz_fixture_TestCreateCluster_When_minimal_flags_are_provided__it_should_render_successfully.yaml diff --git a/cmd/cluster/aws/create_test.go b/cmd/cluster/aws/create_test.go index ba17aea0c82e..1473ed5185a6 100644 --- a/cmd/cluster/aws/create_test.go +++ b/cmd/cluster/aws/create_test.go @@ -58,22 +58,22 @@ func TestValidateCreateCredentialInfo(t *testing.T) { kubeconfigPath string expectError bool }{ - "when CredentialSecretName is blank and aws-creds is also blank": { + "When CredentialSecretName and aws-creds are blank, it should return an error": { expectError: true, }, - "when CredentialSecretName is blank, aws-creds is not blank, and pull-secret is blank": { + "When CredentialSecretName and pull-secret are blank and aws-creds is set, it should return an error": { pullSecretFile: "", credentialSecretName: "", credentials: awsutil.AWSCredentialsOptions{AWSCredentialsFile: "asdf"}, expectError: true, }, - "when CredentialSecretName is blank, aws-creds is not blank, and pull-secret is not blank": { + "When CredentialSecretName is blank and aws-creds and pull-secret are set, it should succeed": { pullSecretFile: "asdf", credentialSecretName: "", credentials: awsutil.AWSCredentialsOptions{AWSCredentialsFile: "asdf"}, expectError: false, }, - "when CredentialSecretName is set with invalid kubeconfig it should fail": { + "When CredentialSecretName is set with invalid kubeconfig, it should fail": { credentialSecretName: "my-secret", kubeconfigPath: "/nonexistent/kubeconfig", credentials: awsutil.AWSCredentialsOptions{AWSCredentialsFile: "/some/creds"}, @@ -180,7 +180,7 @@ func TestCreateCluster(t *testing.T) { args []string }{ { - name: "minimal flags necessary to render", + name: "When minimal flags are provided, it should render successfully", args: []string{ "--sts-creds=" + credentialsFile, "--infra-json=" + infraFile, @@ -192,7 +192,7 @@ func TestCreateCluster(t *testing.T) { }, }, { - name: "default creation flags for cesar", + name: "When default creation flags are provided, it should create cluster with expected configuration", args: []string{ "--pull-secret=" + pullSecretFile, "--name=example", @@ -215,7 +215,7 @@ func TestCreateCluster(t *testing.T) { }, }, { - name: "minimal with KubeAPIServerDNSName", + name: "When KubeAPIServerDNSName is provided, it should configure custom DNS name", args: []string{ "--name=example", "--sts-creds=" + credentialsFile, @@ -227,7 +227,7 @@ func TestCreateCluster(t *testing.T) { }, }, { - name: "minimal with OVNKubernetesMTU", + name: "When OVNKubernetesMTU is provided, it should configure custom MTU", args: []string{ "--name=example", "--sts-creds=" + credentialsFile, diff --git a/cmd/cluster/aws/destroy_test.go b/cmd/cluster/aws/destroy_test.go index 0cdfd33b9fba..c08e84c9e72d 100644 --- a/cmd/cluster/aws/destroy_test.go +++ b/cmd/cluster/aws/destroy_test.go @@ -9,12 +9,12 @@ import ( awsutil "github.com/openshift/hypershift/cmd/infra/aws/util" ) -func Test_ValidateCredentialInfo(t *testing.T) { +func TestValidateCredentialInfo(t *testing.T) { tests := map[string]struct { inputOptions *core.DestroyOptions expectError bool }{ - "when CredentialSecretName is blank and aws-creds is also blank it should fall back to SDK default chain": { + "When CredentialSecretName is blank and aws-creds is also blank, it should fall back to SDK default chain": { inputOptions: &core.DestroyOptions{ CredentialSecretName: "", AWSPlatform: core.AWSPlatformDestroyOptions{ @@ -25,7 +25,7 @@ func Test_ValidateCredentialInfo(t *testing.T) { }, expectError: false, }, - "when CredentialSecretName is blank and aws-creds is not blank": { + "When CredentialSecretName is blank and aws-creds is not blank, it should succeed": { inputOptions: &core.DestroyOptions{ CredentialSecretName: "", AWSPlatform: core.AWSPlatformDestroyOptions{ @@ -36,7 +36,7 @@ func Test_ValidateCredentialInfo(t *testing.T) { }, expectError: false, }, - "when CredentialSecretName is set and AWSCredentialsFile is empty and RoleArn is empty it should fail": { + "When CredentialSecretName is set and AWSCredentialsFile is empty and RoleArn is empty, it should fail": { inputOptions: &core.DestroyOptions{ CredentialSecretName: "my-secret", AWSPlatform: core.AWSPlatformDestroyOptions{ @@ -48,7 +48,7 @@ func Test_ValidateCredentialInfo(t *testing.T) { }, expectError: true, }, - "when CredentialSecretName is set and AWSCredentialsFile is not empty it should try to validate the secret": { + "When CredentialSecretName is set and AWSCredentialsFile is not empty, it should try to validate the secret": { inputOptions: &core.DestroyOptions{ CredentialSecretName: "my-secret", Kubeconfig: "/nonexistent/kubeconfig", @@ -60,7 +60,7 @@ func Test_ValidateCredentialInfo(t *testing.T) { }, expectError: true, }, - "when CredentialSecretName is set and RoleArn is set it should try to validate the secret": { + "When CredentialSecretName is set and RoleArn is set, it should try to validate the secret": { inputOptions: &core.DestroyOptions{ CredentialSecretName: "my-secret", Kubeconfig: "/nonexistent/kubeconfig", diff --git a/cmd/cluster/aws/testdata/zz_fixture_TestCreateCluster_minimal_with_KubeAPIServerDNSName.yaml b/cmd/cluster/aws/testdata/zz_fixture_TestCreateCluster_When_KubeAPIServerDNSName_is_provided__it_should_configure_custom_DNS_name.yaml similarity index 100% rename from cmd/cluster/aws/testdata/zz_fixture_TestCreateCluster_minimal_with_KubeAPIServerDNSName.yaml rename to cmd/cluster/aws/testdata/zz_fixture_TestCreateCluster_When_KubeAPIServerDNSName_is_provided__it_should_configure_custom_DNS_name.yaml diff --git a/cmd/cluster/aws/testdata/zz_fixture_TestCreateCluster_minimal_with_OVNKubernetesMTU.yaml b/cmd/cluster/aws/testdata/zz_fixture_TestCreateCluster_When_OVNKubernetesMTU_is_provided__it_should_configure_custom_MTU.yaml similarity index 100% rename from cmd/cluster/aws/testdata/zz_fixture_TestCreateCluster_minimal_with_OVNKubernetesMTU.yaml rename to cmd/cluster/aws/testdata/zz_fixture_TestCreateCluster_When_OVNKubernetesMTU_is_provided__it_should_configure_custom_MTU.yaml diff --git a/cmd/cluster/aws/testdata/zz_fixture_TestCreateCluster_default_creation_flags_for_cesar.yaml b/cmd/cluster/aws/testdata/zz_fixture_TestCreateCluster_When_default_creation_flags_are_provided__it_should_create_cluster_with_expected_configuration.yaml similarity index 100% rename from cmd/cluster/aws/testdata/zz_fixture_TestCreateCluster_default_creation_flags_for_cesar.yaml rename to cmd/cluster/aws/testdata/zz_fixture_TestCreateCluster_When_default_creation_flags_are_provided__it_should_create_cluster_with_expected_configuration.yaml diff --git a/cmd/cluster/aws/testdata/zz_fixture_TestCreateCluster_minimal_flags_necessary_to_render.yaml b/cmd/cluster/aws/testdata/zz_fixture_TestCreateCluster_When_minimal_flags_are_provided__it_should_render_successfully.yaml similarity index 100% rename from cmd/cluster/aws/testdata/zz_fixture_TestCreateCluster_minimal_flags_necessary_to_render.yaml rename to cmd/cluster/aws/testdata/zz_fixture_TestCreateCluster_When_minimal_flags_are_provided__it_should_render_successfully.yaml diff --git a/cmd/cluster/azure/create_test.go b/cmd/cluster/azure/create_test.go index e4d5df20ae4d..602167fbb1b9 100644 --- a/cmd/cluster/azure/create_test.go +++ b/cmd/cluster/azure/create_test.go @@ -33,25 +33,25 @@ func TestValidateEndpointAccess(t *testing.T) { expectError bool expectedErrorMsg string }{ - "When endpoint-access has an invalid value it should return an error": { + "When endpoint-access has an invalid value, it should return an error": { endpointAccess: "InvalidValue", expectError: true, expectedErrorMsg: "--endpoint-access must be one of: Public, PublicAndPrivate, Private", }, - "When endpoint-access is Private without nat-subnet-id it should succeed (controller auto-creates)": { + "When endpoint-access is Private without nat-subnet-id, it should succeed (controller auto-creates)": { endpointAccess: "Private", expectError: false, }, - "When endpoint-access is PublicAndPrivate without nat-subnet-id it should succeed (controller auto-creates)": { + "When endpoint-access is PublicAndPrivate without nat-subnet-id, it should succeed (controller auto-creates)": { endpointAccess: "PublicAndPrivate", expectError: false, }, - "When endpoint-access is Private with nat-subnet-id it should succeed without additional subscriptions": { + "When endpoint-access is Private with nat-subnet-id, it should succeed without additional subscriptions": { endpointAccess: "Private", endpointAccessPrivateNATSubnetID: "/subscriptions/sub-1/resourceGroups/rg/providers/Microsoft.Network/virtualNetworks/vnet/subnets/nat-subnet", expectError: false, }, - "When endpoint-access is Public it should succeed without private connectivity fields": { + "When endpoint-access is Public, it should succeed without private connectivity fields": { endpointAccess: "Public", expectError: false, }, @@ -96,14 +96,14 @@ func TestDNSZoneRGValidation(t *testing.T) { expectError bool errContains string }{ - "When assign-service-principal-roles is set without dns-zone-rg-name it should return an error": { + "When assign-service-principal-roles is set without dns-zone-rg-name, it should return an error": { extraArgs: []string{ "--assign-service-principal-roles", }, expectError: true, errContains: "--dns-zone-rg-name is required when --assign-service-principal-roles or --assign-custom-hcp-roles is set", }, - "When assign-custom-hcp-roles is set without dns-zone-rg-name it should return an error": { + "When assign-custom-hcp-roles is set without dns-zone-rg-name, it should return an error": { extraArgs: []string{ "--assign-custom-hcp-roles", }, @@ -210,14 +210,14 @@ func TestRoleAssignmentWithInfraJSON(t *testing.T) { expectError bool errContains string }{ - "When assign-custom-hcp-roles is set with infra-json it should return an error": { + "When assign-custom-hcp-roles is set with infra-json, it should return an error": { extraArgs: []string{ "--assign-custom-hcp-roles", }, expectError: true, errContains: "role assignment flags cannot be used with --infra-json", }, - "When assign-service-principal-roles is set with infra-json it should return an error": { + "When assign-service-principal-roles is set with infra-json, it should return an error": { extraArgs: []string{ "--assign-service-principal-roles", "--dns-zone-rg-name=my-dns-rg", @@ -225,7 +225,7 @@ func TestRoleAssignmentWithInfraJSON(t *testing.T) { expectError: true, errContains: "role assignment flags cannot be used with --infra-json", }, - "When role assignment flags are not set with infra-json it should succeed": { + "When role assignment flags are not set with infra-json, it should succeed": { extraArgs: nil, expectError: false, }, @@ -283,7 +283,7 @@ func TestCreateCluster(t *testing.T) { args []string }{ { - name: "minimal flags necessary to render", + name: "When minimal flags are provided, it should render successfully", args: []string{ "--azure-creds=" + credentialsFile, "--infra-json=" + infraFile, @@ -295,7 +295,7 @@ func TestCreateCluster(t *testing.T) { }, }, { - name: "complicated invocation from bryan", + name: "When complex configuration flags are provided, it should create cluster with all options", args: []string{ "--azure-creds=" + credentialsFile, "--infra-json=" + infraFile, @@ -314,7 +314,7 @@ func TestCreateCluster(t *testing.T) { }, }, { - name: "create with azure marketplace image", + name: "When Azure Marketplace image flags are provided, it should configure marketplace image", args: []string{ "--azure-creds=" + credentialsFile, "--infra-json=" + infraFile, @@ -336,7 +336,7 @@ func TestCreateCluster(t *testing.T) { }, }, { - name: "with availability zones", + name: "When availability zones are provided, it should configure zones", args: []string{ "--azure-creds=" + credentialsFile, "--infra-json=" + infraFile, @@ -349,7 +349,7 @@ func TestCreateCluster(t *testing.T) { }, }, { - name: "with disabled capabilities", + name: "When disabled capabilities are provided, it should configure disabled capabilities", args: []string{ "--name=example", "--pull-secret=" + pullSecretFile, @@ -362,7 +362,7 @@ func TestCreateCluster(t *testing.T) { }, }, { - name: "with KubeAPIServerDNSName", + name: "When KubeAPIServerDNSName is provided, it should configure custom DNS name", args: []string{ "--name=example", "--pull-secret=" + pullSecretFile, @@ -375,7 +375,7 @@ func TestCreateCluster(t *testing.T) { }, }, { - name: "with image generation Gen1", + name: "When image generation Gen1 is provided, it should configure Gen1 images", args: []string{ "--azure-creds=" + credentialsFile, "--infra-json=" + infraFile, @@ -387,7 +387,7 @@ func TestCreateCluster(t *testing.T) { }, }, { - name: "with image generation Gen2", + name: "When image generation Gen2 is provided, it should configure Gen2 images", args: []string{ "--azure-creds=" + credentialsFile, "--infra-json=" + infraFile, @@ -399,7 +399,7 @@ func TestCreateCluster(t *testing.T) { }, }, { - name: "with marketplace flags and image generation Gen1", + name: "When marketplace flags and image generation Gen1 are provided, it should configure marketplace with Gen1", args: []string{ "--azure-creds=" + credentialsFile, "--infra-json=" + infraFile, @@ -415,7 +415,7 @@ func TestCreateCluster(t *testing.T) { }, }, { - name: "with availability zones and image generation Gen1", + name: "When availability zones and image generation Gen1 are provided, it should configure zones with Gen1", args: []string{ "--azure-creds=" + credentialsFile, "--infra-json=" + infraFile, @@ -428,7 +428,7 @@ func TestCreateCluster(t *testing.T) { }, }, { - name: "When endpoint-access is Private with endpoint-access-private flags it should render HostedCluster with Private endpoint access", + name: "When endpoint-access is Private with private flags, it should configure private endpoint access", args: []string{ "--azure-creds=" + credentialsFile, "--infra-json=" + infraFile, @@ -443,7 +443,7 @@ func TestCreateCluster(t *testing.T) { }, }, { - name: "When oauth-publishing-strategy is LoadBalancer with workload identities it should render HostedCluster with OAuth LoadBalancer", + name: "When oauth-publishing-strategy is LoadBalancer, it should configure OAuth LoadBalancer", args: []string{ "--azure-creds=" + credentialsFile, "--infra-json=" + infraFile, diff --git a/cmd/cluster/azure/destroy_test.go b/cmd/cluster/azure/destroy_test.go index 1d8f9ef1d52b..6ecd539d77ce 100644 --- a/cmd/cluster/azure/destroy_test.go +++ b/cmd/cluster/azure/destroy_test.go @@ -19,7 +19,7 @@ func TestDestroyClusterSetsCloudFromHostedCluster(t *testing.T) { expectedCloud string expectError bool }{ - "When HostedCluster has a custom cloud it should set Cloud to that value": { + "When HostedCluster has a custom cloud, it should set Cloud to that value": { hostedCluster: &hyperv1.HostedCluster{ Spec: hyperv1.HostedClusterSpec{ InfraID: "test-infra", @@ -33,7 +33,7 @@ func TestDestroyClusterSetsCloudFromHostedCluster(t *testing.T) { }, expectedCloud: "AzureUSGovernmentCloud", }, - "When HostedCluster has empty cloud it should default to DefaultAzureCloud": { + "When HostedCluster has empty cloud, it should default to DefaultAzureCloud": { hostedCluster: &hyperv1.HostedCluster{ Spec: hyperv1.HostedClusterSpec{ InfraID: "test-infra", @@ -47,16 +47,16 @@ func TestDestroyClusterSetsCloudFromHostedCluster(t *testing.T) { }, expectedCloud: config.DefaultAzureCloud, }, - "When HostedCluster is nil and no cloud is set it should default to DefaultAzureCloud": { + "When HostedCluster is nil and no cloud is set, it should default to DefaultAzureCloud": { hostedCluster: nil, expectedCloud: config.DefaultAzureCloud, }, - "When HostedCluster is nil and caller provided a cloud it should preserve the caller value": { + "When HostedCluster is nil and caller provided a cloud, it should preserve the caller value": { hostedCluster: nil, initialCloud: "AzureUSGovernmentCloud", expectedCloud: "AzureUSGovernmentCloud", }, - "When HostedCluster has nil Azure platform it should return an error": { + "When HostedCluster has nil Azure platform, it should return an error": { hostedCluster: &hyperv1.HostedCluster{ Spec: hyperv1.HostedClusterSpec{ Platform: hyperv1.PlatformSpec{}, diff --git a/cmd/cluster/azure/testdata/zz_fixture_TestCreateCluster_create_with_azure_marketplace_image.yaml b/cmd/cluster/azure/testdata/zz_fixture_TestCreateCluster_When_Azure_Marketplace_image_flags_are_provided__it_should_configure_marketplace_image.yaml similarity index 100% rename from cmd/cluster/azure/testdata/zz_fixture_TestCreateCluster_create_with_azure_marketplace_image.yaml rename to cmd/cluster/azure/testdata/zz_fixture_TestCreateCluster_When_Azure_Marketplace_image_flags_are_provided__it_should_configure_marketplace_image.yaml diff --git a/cmd/cluster/azure/testdata/zz_fixture_TestCreateCluster_with_KubeAPIServerDNSName.yaml b/cmd/cluster/azure/testdata/zz_fixture_TestCreateCluster_When_KubeAPIServerDNSName_is_provided__it_should_configure_custom_DNS_name.yaml similarity index 100% rename from cmd/cluster/azure/testdata/zz_fixture_TestCreateCluster_with_KubeAPIServerDNSName.yaml rename to cmd/cluster/azure/testdata/zz_fixture_TestCreateCluster_When_KubeAPIServerDNSName_is_provided__it_should_configure_custom_DNS_name.yaml diff --git a/cmd/cluster/azure/testdata/zz_fixture_TestCreateCluster_with_availability_zones_and_image_generation_Gen1.yaml b/cmd/cluster/azure/testdata/zz_fixture_TestCreateCluster_When_availability_zones_and_image_generation_Gen1_are_provided__it_should_configure_zones_with_Gen1.yaml similarity index 100% rename from cmd/cluster/azure/testdata/zz_fixture_TestCreateCluster_with_availability_zones_and_image_generation_Gen1.yaml rename to cmd/cluster/azure/testdata/zz_fixture_TestCreateCluster_When_availability_zones_and_image_generation_Gen1_are_provided__it_should_configure_zones_with_Gen1.yaml diff --git a/cmd/cluster/azure/testdata/zz_fixture_TestCreateCluster_with_availability_zones.yaml b/cmd/cluster/azure/testdata/zz_fixture_TestCreateCluster_When_availability_zones_are_provided__it_should_configure_zones.yaml similarity index 100% rename from cmd/cluster/azure/testdata/zz_fixture_TestCreateCluster_with_availability_zones.yaml rename to cmd/cluster/azure/testdata/zz_fixture_TestCreateCluster_When_availability_zones_are_provided__it_should_configure_zones.yaml diff --git a/cmd/cluster/azure/testdata/zz_fixture_TestCreateCluster_complicated_invocation_from_bryan.yaml b/cmd/cluster/azure/testdata/zz_fixture_TestCreateCluster_When_complex_configuration_flags_are_provided__it_should_create_cluster_with_all_options.yaml similarity index 100% rename from cmd/cluster/azure/testdata/zz_fixture_TestCreateCluster_complicated_invocation_from_bryan.yaml rename to cmd/cluster/azure/testdata/zz_fixture_TestCreateCluster_When_complex_configuration_flags_are_provided__it_should_create_cluster_with_all_options.yaml diff --git a/cmd/cluster/azure/testdata/zz_fixture_TestCreateCluster_with_disabled_capabilities.yaml b/cmd/cluster/azure/testdata/zz_fixture_TestCreateCluster_When_disabled_capabilities_are_provided__it_should_configure_disabled_capabilities.yaml similarity index 100% rename from cmd/cluster/azure/testdata/zz_fixture_TestCreateCluster_with_disabled_capabilities.yaml rename to cmd/cluster/azure/testdata/zz_fixture_TestCreateCluster_When_disabled_capabilities_are_provided__it_should_configure_disabled_capabilities.yaml diff --git a/cmd/cluster/azure/testdata/zz_fixture_TestCreateCluster_When_endpoint_access_is_Private_with_endpoint_access_private_flags_it_should_render_HostedCluster_with_Private_endpoint_access.yaml b/cmd/cluster/azure/testdata/zz_fixture_TestCreateCluster_When_endpoint_access_is_Private_with_private_flags__it_should_configure_private_endpoint_access.yaml similarity index 100% rename from cmd/cluster/azure/testdata/zz_fixture_TestCreateCluster_When_endpoint_access_is_Private_with_endpoint_access_private_flags_it_should_render_HostedCluster_with_Private_endpoint_access.yaml rename to cmd/cluster/azure/testdata/zz_fixture_TestCreateCluster_When_endpoint_access_is_Private_with_private_flags__it_should_configure_private_endpoint_access.yaml diff --git a/cmd/cluster/azure/testdata/zz_fixture_TestCreateCluster_with_image_generation_Gen1.yaml b/cmd/cluster/azure/testdata/zz_fixture_TestCreateCluster_When_image_generation_Gen1_is_provided__it_should_configure_Gen1_images.yaml similarity index 100% rename from cmd/cluster/azure/testdata/zz_fixture_TestCreateCluster_with_image_generation_Gen1.yaml rename to cmd/cluster/azure/testdata/zz_fixture_TestCreateCluster_When_image_generation_Gen1_is_provided__it_should_configure_Gen1_images.yaml diff --git a/cmd/cluster/azure/testdata/zz_fixture_TestCreateCluster_with_image_generation_Gen2.yaml b/cmd/cluster/azure/testdata/zz_fixture_TestCreateCluster_When_image_generation_Gen2_is_provided__it_should_configure_Gen2_images.yaml similarity index 100% rename from cmd/cluster/azure/testdata/zz_fixture_TestCreateCluster_with_image_generation_Gen2.yaml rename to cmd/cluster/azure/testdata/zz_fixture_TestCreateCluster_When_image_generation_Gen2_is_provided__it_should_configure_Gen2_images.yaml diff --git a/cmd/cluster/azure/testdata/zz_fixture_TestCreateCluster_with_marketplace_flags_and_image_generation_Gen1.yaml b/cmd/cluster/azure/testdata/zz_fixture_TestCreateCluster_When_marketplace_flags_and_image_generation_Gen1_are_provided__it_should_configure_marketplace_with_Gen1.yaml similarity index 100% rename from cmd/cluster/azure/testdata/zz_fixture_TestCreateCluster_with_marketplace_flags_and_image_generation_Gen1.yaml rename to cmd/cluster/azure/testdata/zz_fixture_TestCreateCluster_When_marketplace_flags_and_image_generation_Gen1_are_provided__it_should_configure_marketplace_with_Gen1.yaml diff --git a/cmd/cluster/azure/testdata/zz_fixture_TestCreateCluster_minimal_flags_necessary_to_render.yaml b/cmd/cluster/azure/testdata/zz_fixture_TestCreateCluster_When_minimal_flags_are_provided__it_should_render_successfully.yaml similarity index 100% rename from cmd/cluster/azure/testdata/zz_fixture_TestCreateCluster_minimal_flags_necessary_to_render.yaml rename to cmd/cluster/azure/testdata/zz_fixture_TestCreateCluster_When_minimal_flags_are_provided__it_should_render_successfully.yaml diff --git a/cmd/cluster/azure/testdata/zz_fixture_TestCreateCluster_When_oauth_publishing_strategy_is_LoadBalancer_with_workload_identities_it_should_render_HostedCluster_with_OAuth_LoadBalancer.yaml b/cmd/cluster/azure/testdata/zz_fixture_TestCreateCluster_When_oauth_publishing_strategy_is_LoadBalancer__it_should_configure_OAuth_LoadBalancer.yaml similarity index 100% rename from cmd/cluster/azure/testdata/zz_fixture_TestCreateCluster_When_oauth_publishing_strategy_is_LoadBalancer_with_workload_identities_it_should_render_HostedCluster_with_OAuth_LoadBalancer.yaml rename to cmd/cluster/azure/testdata/zz_fixture_TestCreateCluster_When_oauth_publishing_strategy_is_LoadBalancer__it_should_configure_OAuth_LoadBalancer.yaml diff --git a/cmd/cluster/azure/testdata/zz_fixture_TestCreateCluster_create_with_a_ure_marketplace_image.yaml b/cmd/cluster/azure/testdata/zz_fixture_TestCreateCluster_create_with_a_ure_marketplace_image.yaml deleted file mode 100644 index f5fdf7a50b84..000000000000 --- a/cmd/cluster/azure/testdata/zz_fixture_TestCreateCluster_create_with_a_ure_marketplace_image.yaml +++ /dev/null @@ -1,146 +0,0 @@ -apiVersion: v1 -kind: Namespace -metadata: - creationTimestamp: null - name: clusters -spec: {} -status: {} ---- -apiVersion: hypershift.openshift.io/v1beta1 -kind: HostedCluster -metadata: - creationTimestamp: null - name: bryans-cluster - namespace: clusters -spec: - autoscaling: {} - capabilities: {} - configuration: {} - controllerAvailabilityPolicy: SingleReplica - dns: - baseDomain: fakeBaseDomain - privateZoneID: fakePrivateZoneID - publicZoneID: fakePublicZoneID - etcd: - managed: - storage: - persistentVolume: - size: 8Gi - type: PersistentVolume - managementType: Managed - fips: false - infraID: fakeInfraID - networking: - clusterNetwork: - - cidr: 10.132.0.0/14 - networkType: OVNKubernetes - serviceNetwork: - - cidr: 172.31.0.0/16 - olmCatalogPlacement: management - platform: - azure: - location: fakeLocation - managedIdentities: - controlPlane: - cloudProvider: - credentialsSecretName: "" - objectEncoding: utf-8 - controlPlaneOperator: - credentialsSecretName: "" - objectEncoding: utf-8 - disk: - credentialsSecretName: "" - objectEncoding: utf-8 - file: - credentialsSecretName: "" - objectEncoding: utf-8 - imageRegistry: - credentialsSecretName: "" - objectEncoding: utf-8 - ingress: - credentialsSecretName: "" - objectEncoding: utf-8 - managedIdentitiesKeyVault: - name: "" - tenantID: "" - network: - credentialsSecretName: "" - objectEncoding: utf-8 - nodePoolManagement: - credentialsSecretName: "" - objectEncoding: utf-8 - dataPlane: - diskMSIClientID: "" - fileMSIClientID: "" - imageRegistryMSIClientID: "" - resourceGroup: fakeResourceGroupName - securityGroupID: fakeSecurityGroupID - subnetID: fakeSubnetID - subscriptionID: fakeSubscriptionID - tenantID: fakeTenantID - vnetID: fakeVNetID - type: Azure - pullSecret: - name: bryans-cluster-pull-secret - release: - image: fake-release-image - secretEncryption: - aescbc: - activeKey: - name: bryans-cluster-etcd-encryption-key - type: aescbc - services: - - service: APIServer - servicePublishingStrategy: - type: LoadBalancer - - service: Ignition - servicePublishingStrategy: - type: Route - - service: Konnectivity - servicePublishingStrategy: - type: Route - - service: OAuthServer - servicePublishingStrategy: - type: Route - sshKey: {} -status: - controlPlaneEndpoint: - host: "" - port: 0 ---- -apiVersion: hypershift.openshift.io/v1beta1 -kind: NodePool -metadata: - creationTimestamp: null - name: bryans-cluster - namespace: clusters -spec: - arch: amd64 - clusterName: bryans-cluster - management: - autoRepair: false - upgradeType: Replace - nodeDrainTimeout: 0s - nodeVolumeDetachTimeout: 0s - platform: - azure: - image: - azureMarketplace: - offer: aro4 - publisher: azureopenshift - sku: aro_414 - version: 414.92.2024021 - type: AzureMarketplace - osDisk: - diskStorageAccountType: Standard_LRS - persistence: Ephemeral - sizeGiB: 120 - subnetID: fakeSubnetID - vmSize: Standard_DS2_v2 - type: Azure - release: - image: fake-release-image - replicas: 312 -status: - replicas: 0 ---- diff --git a/cmd/cluster/azure/testdata/zz_fixture_TestCreateCluster_with_availability_ones.yaml b/cmd/cluster/azure/testdata/zz_fixture_TestCreateCluster_with_availability_ones.yaml deleted file mode 100644 index a5af6ce1d4e0..000000000000 --- a/cmd/cluster/azure/testdata/zz_fixture_TestCreateCluster_with_availability_ones.yaml +++ /dev/null @@ -1,207 +0,0 @@ -apiVersion: v1 -kind: Namespace -metadata: - creationTimestamp: null - name: clusters -spec: {} -status: {} ---- -apiVersion: v1 -data: - .dockerconfigjson: ZmFrZQ== -kind: Secret -metadata: - creationTimestamp: null - labels: - hypershift.openshift.io/safe-to-delete-with-cluster: "true" - name: example-pull-secret - namespace: clusters ---- -apiVersion: v1 -data: - AZURE_SUBSCRIPTION_ID: ZmFrZVN1YnNjcmlwdGlvbklE - AZURE_TENANT_ID: ZmFrZVRlbmFudElE -kind: Secret -metadata: - creationTimestamp: null - name: example-cloud-credentials - namespace: clusters ---- -apiVersion: v1 -data: - key: RtBxtzupSh9bkzEqKY5VZOOLLDVYsAKqPIYkEMK7R1A= -kind: Secret -metadata: - creationTimestamp: null - labels: - hypershift.openshift.io/safe-to-delete-with-cluster: "true" - name: example-etcd-encryption-key - namespace: clusters -type: Opaque ---- -apiVersion: hypershift.openshift.io/v1beta1 -kind: HostedCluster -metadata: - creationTimestamp: null - name: example - namespace: clusters -spec: - autoscaling: {} - capabilities: {} - configuration: {} - controllerAvailabilityPolicy: SingleReplica - dns: - baseDomain: fakeBaseDomain - privateZoneID: fakePrivateZoneID - publicZoneID: fakePublicZoneID - etcd: - managed: - storage: - persistentVolume: - size: 8Gi - type: PersistentVolume - managementType: Managed - fips: false - infraID: fakeInfraID - networking: - clusterNetwork: - - cidr: 10.132.0.0/14 - networkType: OVNKubernetes - serviceNetwork: - - cidr: 172.31.0.0/16 - olmCatalogPlacement: management - platform: - azure: - location: fakeLocation - managedIdentities: - controlPlane: - cloudProvider: - credentialsSecretName: "" - objectEncoding: utf-8 - controlPlaneOperator: - credentialsSecretName: "" - objectEncoding: utf-8 - disk: - credentialsSecretName: "" - objectEncoding: utf-8 - file: - credentialsSecretName: "" - objectEncoding: utf-8 - imageRegistry: - credentialsSecretName: "" - objectEncoding: utf-8 - ingress: - credentialsSecretName: "" - objectEncoding: utf-8 - managedIdentitiesKeyVault: - name: "" - tenantID: "" - network: - credentialsSecretName: "" - objectEncoding: utf-8 - nodePoolManagement: - credentialsSecretName: "" - objectEncoding: utf-8 - dataPlane: - diskMSIClientID: "" - fileMSIClientID: "" - imageRegistryMSIClientID: "" - resourceGroup: fakeResourceGroupName - securityGroupID: fakeSecurityGroupID - subnetID: fakeSubnetID - subscriptionID: fakeSubscriptionID - tenantID: fakeTenantID - vnetID: fakeVNetID - type: Azure - pullSecret: - name: example-pull-secret - release: - image: "" - secretEncryption: - aescbc: - activeKey: - name: example-etcd-encryption-key - type: aescbc - services: - - service: APIServer - servicePublishingStrategy: - type: LoadBalancer - - service: Ignition - servicePublishingStrategy: - type: Route - - service: Konnectivity - servicePublishingStrategy: - type: Route - - service: OAuthServer - servicePublishingStrategy: - type: Route - sshKey: {} -status: - controlPlaneEndpoint: - host: "" - port: 0 ---- -apiVersion: hypershift.openshift.io/v1beta1 -kind: NodePool -metadata: - creationTimestamp: null - name: example-1 - namespace: clusters -spec: - arch: amd64 - clusterName: example - management: - autoRepair: false - upgradeType: Replace - nodeDrainTimeout: 0s - nodeVolumeDetachTimeout: 0s - platform: - azure: - availabilityZone: "1" - image: - imageID: fakeBootImageID - type: ImageID - osDisk: - diskStorageAccountType: Premium_LRS - sizeGiB: 120 - subnetID: fakeSubnetID - vmSize: Standard_D4s_v5 - type: Azure - release: - image: "" - replicas: 0 -status: - replicas: 0 ---- -apiVersion: hypershift.openshift.io/v1beta1 -kind: NodePool -metadata: - creationTimestamp: null - name: example-2 - namespace: clusters -spec: - arch: amd64 - clusterName: example - management: - autoRepair: false - upgradeType: Replace - nodeDrainTimeout: 0s - nodeVolumeDetachTimeout: 0s - platform: - azure: - availabilityZone: "2" - image: - imageID: fakeBootImageID - type: ImageID - osDisk: - diskStorageAccountType: Premium_LRS - sizeGiB: 120 - subnetID: fakeSubnetID - vmSize: Standard_D4s_v5 - type: Azure - release: - image: "" - replicas: 0 -status: - replicas: 0 ---- diff --git a/cmd/cluster/core/create_test.go b/cmd/cluster/core/create_test.go index 7e09115b761a..56047eae7bf1 100644 --- a/cmd/cluster/core/create_test.go +++ b/cmd/cluster/core/create_test.go @@ -93,7 +93,7 @@ func TestValidateMgmtClusterAndNodePoolCPUArchitectures(t *testing.T) { expectError bool }{ { - name: "When a multi-arch release is passed, the function should return no errors", + name: "When a multi-arch release is passed, it should return no errors", opts: &RawCreateOptions{ ReleaseImage: "quay.io/openshift-release-dev/ocp-release:4.16.13-multi", PullSecretFile: "../../../hack/dev/fakePullSecret.json", @@ -103,7 +103,7 @@ func TestValidateMgmtClusterAndNodePoolCPUArchitectures(t *testing.T) { expectError: false, }, { - name: "When no release image was passed and a valid multi-arch stream is passed, the function should return no errors", + name: "When no release image is provided and a valid multi-arch stream is passed, it should return no errors", opts: &RawCreateOptions{ ReleaseImage: "", PullSecretFile: "../../../hack/dev/fakePullSecret.json", @@ -113,7 +113,7 @@ func TestValidateMgmtClusterAndNodePoolCPUArchitectures(t *testing.T) { expectError: false, }, { - name: "When a single arch release is passed and the NodePool arch matches the arch of the release, the function should return no errors", + name: "When a single arch release is passed and the NodePool arch matches the release arch, it should return no errors", opts: &RawCreateOptions{ ReleaseImage: "quay.io/openshift-release-dev/ocp-release:4.16.13-x86_64", PullSecretFile: "../../../hack/dev/fakePullSecret.json", @@ -123,7 +123,7 @@ func TestValidateMgmtClusterAndNodePoolCPUArchitectures(t *testing.T) { expectError: false, }, { - name: "When a single arch release is passed and the NodePool arch doesn't match the arch of the release, the function should return an error", + name: "When a single arch release is passed and the NodePool arch doesn't match the release arch, it should return an error", opts: &RawCreateOptions{ ReleaseImage: "quay.io/openshift-release-dev/ocp-release:4.16.13-x86_64", PullSecretFile: "../../../hack/dev/fakePullSecret.json", @@ -1785,7 +1785,7 @@ func TestValidateClusterExistence(t *testing.T) { expectError bool errorMsg string }{ - "When the cluster does not exist it should succeed": { + "When the cluster does not exist, it should succeed": { opts: &RawCreateOptions{ Namespace: "test-ns", Name: "test-cluster", @@ -1793,7 +1793,7 @@ func TestValidateClusterExistence(t *testing.T) { client: fake.NewClientBuilder().WithScheme(scheme).Build(), expectError: false, }, - "When the cluster already exists it should return an error": { + "When the cluster already exists, it should return an error": { opts: &RawCreateOptions{ Namespace: "test-ns", Name: "test-cluster", @@ -1809,7 +1809,7 @@ func TestValidateClusterExistence(t *testing.T) { expectError: true, errorMsg: "already exists", }, - "When the API server returns a transient timeout it should retry and succeed": { + "When the API server returns a transient timeout, it should retry and succeed": { opts: &RawCreateOptions{ Namespace: "test-ns", Name: "test-cluster", @@ -1817,7 +1817,7 @@ func TestValidateClusterExistence(t *testing.T) { client: &transientErrorClient{callsBeforeSuccess: 2, scheme: scheme}, expectError: false, }, - "When the API server returns persistent timeouts it should eventually fail": { + "When the API server returns persistent timeouts, it should eventually fail": { opts: &RawCreateOptions{ Namespace: "test-ns", Name: "test-cluster", @@ -1826,7 +1826,7 @@ func TestValidateClusterExistence(t *testing.T) { expectError: true, errorMsg: "hostedcluster doesn't exist validation failed", }, - "When the API server returns a forbidden error it should fail immediately without retry": { + "When the API server returns a forbidden error, it should fail immediately without retry": { opts: &RawCreateOptions{ Namespace: "test-ns", Name: "test-cluster", @@ -1835,7 +1835,7 @@ func TestValidateClusterExistence(t *testing.T) { expectError: true, errorMsg: "forbidden", }, - "When the API server returns a service unavailable error it should retry and succeed": { + "When the API server returns a service unavailable error, it should retry and succeed": { opts: &RawCreateOptions{ Namespace: "test-ns", Name: "test-cluster", @@ -1843,7 +1843,7 @@ func TestValidateClusterExistence(t *testing.T) { client: &transientErrorClient{callsBeforeSuccess: 2, scheme: scheme, errFunc: func() error { return apierrors.NewServiceUnavailable("service unavailable") }}, expectError: false, }, - "When the API server times out then finds the cluster exists it should return already exists": { + "When the API server times out then finds the cluster exists, it should return already exists": { opts: &RawCreateOptions{ Namespace: "test-ns", Name: "test-cluster", diff --git a/cmd/cluster/core/dump_test.go b/cmd/cluster/core/dump_test.go index 4c686e6dbff5..f057d1b14f40 100644 --- a/cmd/cluster/core/dump_test.go +++ b/cmd/cluster/core/dump_test.go @@ -37,19 +37,19 @@ func TestIsResourceRegistered(t *testing.T) { expectError bool }{ { - name: "group version not found", + name: "When group version is not found, it should return false", gvk: schema.GroupVersionKind{Group: "non.existing.group.io", Version: dummyVersion, Kind: dummyKind}, expected: false, expectError: false, }, { - name: "group version found but kind not found", + name: "When group version is found but kind is not found, it should return false", gvk: schema.GroupVersionKind{Group: dummyGroup, Version: dummyVersion, Kind: "non-existing-kind"}, expected: false, expectError: false, }, { - name: "group version kind found", + name: "When group version kind is found, it should return true", gvk: schema.GroupVersionKind{Group: dummyGroup, Version: dummyVersion, Kind: dummyKind}, expected: true, expectError: false, diff --git a/cmd/cluster/gcp/create_test.go b/cmd/cluster/gcp/create_test.go index 2092915aeb4b..7d17ec6b6aaa 100644 --- a/cmd/cluster/gcp/create_test.go +++ b/cmd/cluster/gcp/create_test.go @@ -92,42 +92,42 @@ func TestValidateGCPOptions(t *testing.T) { expectErr bool expectSubstr string }{ - "missing project": { + "When project is missing, it should return an error": { opts: RawCreateOptions{Region: validOpts.Region, Network: validOpts.Network, PrivateServiceConnectSubnet: validOpts.PrivateServiceConnectSubnet, WorkloadIdentityProjectNumber: validOpts.WorkloadIdentityProjectNumber, WorkloadIdentityPoolID: validOpts.WorkloadIdentityPoolID, WorkloadIdentityProviderID: validOpts.WorkloadIdentityProviderID, NodePoolServiceAccount: validOpts.NodePoolServiceAccount, ControlPlaneServiceAccount: validOpts.ControlPlaneServiceAccount, CloudControllerServiceAccount: validOpts.CloudControllerServiceAccount, StorageServiceAccount: validOpts.StorageServiceAccount, ImageRegistryServiceAccount: validOpts.ImageRegistryServiceAccount, NetworkServiceAccount: validOpts.NetworkServiceAccount}, expectErr: true, expectSubstr: "required flag(s) \"project\" not set", }, - "missing region": { + "When region is missing, it should return an error": { opts: RawCreateOptions{Project: validOpts.Project, Network: validOpts.Network, PrivateServiceConnectSubnet: validOpts.PrivateServiceConnectSubnet, WorkloadIdentityProjectNumber: validOpts.WorkloadIdentityProjectNumber, WorkloadIdentityPoolID: validOpts.WorkloadIdentityPoolID, WorkloadIdentityProviderID: validOpts.WorkloadIdentityProviderID, NodePoolServiceAccount: validOpts.NodePoolServiceAccount, ControlPlaneServiceAccount: validOpts.ControlPlaneServiceAccount, CloudControllerServiceAccount: validOpts.CloudControllerServiceAccount, StorageServiceAccount: validOpts.StorageServiceAccount, ImageRegistryServiceAccount: validOpts.ImageRegistryServiceAccount, NetworkServiceAccount: validOpts.NetworkServiceAccount}, expectErr: true, expectSubstr: "required flag(s) \"region\" not set", }, - "missing network": { + "When network is missing, it should return an error": { opts: RawCreateOptions{Project: validOpts.Project, Region: validOpts.Region, PrivateServiceConnectSubnet: validOpts.PrivateServiceConnectSubnet, WorkloadIdentityProjectNumber: validOpts.WorkloadIdentityProjectNumber, WorkloadIdentityPoolID: validOpts.WorkloadIdentityPoolID, WorkloadIdentityProviderID: validOpts.WorkloadIdentityProviderID, NodePoolServiceAccount: validOpts.NodePoolServiceAccount, ControlPlaneServiceAccount: validOpts.ControlPlaneServiceAccount, CloudControllerServiceAccount: validOpts.CloudControllerServiceAccount, StorageServiceAccount: validOpts.StorageServiceAccount, ImageRegistryServiceAccount: validOpts.ImageRegistryServiceAccount, NetworkServiceAccount: validOpts.NetworkServiceAccount}, expectErr: true, expectSubstr: "required flag(s) \"network\" not set", }, - "missing cloud-controller-service-account": { + "When cloud-controller-service-account is missing, it should return an error": { opts: RawCreateOptions{Project: validOpts.Project, Region: validOpts.Region, Network: validOpts.Network, PrivateServiceConnectSubnet: validOpts.PrivateServiceConnectSubnet, WorkloadIdentityProjectNumber: validOpts.WorkloadIdentityProjectNumber, WorkloadIdentityPoolID: validOpts.WorkloadIdentityPoolID, WorkloadIdentityProviderID: validOpts.WorkloadIdentityProviderID, NodePoolServiceAccount: validOpts.NodePoolServiceAccount, ControlPlaneServiceAccount: validOpts.ControlPlaneServiceAccount, StorageServiceAccount: validOpts.StorageServiceAccount, ImageRegistryServiceAccount: validOpts.ImageRegistryServiceAccount, NetworkServiceAccount: validOpts.NetworkServiceAccount}, expectErr: true, expectSubstr: "required flag(s) \"cloud-controller-service-account\" not set", }, - "missing storage service account": { + "When storage-service-account is missing, it should return an error": { opts: RawCreateOptions{Project: validOpts.Project, Region: validOpts.Region, Network: validOpts.Network, PrivateServiceConnectSubnet: validOpts.PrivateServiceConnectSubnet, WorkloadIdentityProjectNumber: validOpts.WorkloadIdentityProjectNumber, WorkloadIdentityPoolID: validOpts.WorkloadIdentityPoolID, WorkloadIdentityProviderID: validOpts.WorkloadIdentityProviderID, NodePoolServiceAccount: validOpts.NodePoolServiceAccount, ControlPlaneServiceAccount: validOpts.ControlPlaneServiceAccount, CloudControllerServiceAccount: validOpts.CloudControllerServiceAccount, ImageRegistryServiceAccount: validOpts.ImageRegistryServiceAccount, NetworkServiceAccount: validOpts.NetworkServiceAccount}, expectErr: true, expectSubstr: "required flag(s) \"storage-service-account\" not set", }, - "missing image-registry-service-account": { + "When image-registry-service-account is missing, it should return an error": { opts: RawCreateOptions{Project: validOpts.Project, Region: validOpts.Region, Network: validOpts.Network, PrivateServiceConnectSubnet: validOpts.PrivateServiceConnectSubnet, WorkloadIdentityProjectNumber: validOpts.WorkloadIdentityProjectNumber, WorkloadIdentityPoolID: validOpts.WorkloadIdentityPoolID, WorkloadIdentityProviderID: validOpts.WorkloadIdentityProviderID, NodePoolServiceAccount: validOpts.NodePoolServiceAccount, ControlPlaneServiceAccount: validOpts.ControlPlaneServiceAccount, CloudControllerServiceAccount: validOpts.CloudControllerServiceAccount, StorageServiceAccount: validOpts.StorageServiceAccount, NetworkServiceAccount: validOpts.NetworkServiceAccount}, expectErr: true, expectSubstr: "required flag(s) \"image-registry-service-account\" not set", }, - "missing network-service-account": { + "When network-service-account is missing, it should return an error": { opts: RawCreateOptions{Project: validOpts.Project, Region: validOpts.Region, Network: validOpts.Network, PrivateServiceConnectSubnet: validOpts.PrivateServiceConnectSubnet, WorkloadIdentityProjectNumber: validOpts.WorkloadIdentityProjectNumber, WorkloadIdentityPoolID: validOpts.WorkloadIdentityPoolID, WorkloadIdentityProviderID: validOpts.WorkloadIdentityProviderID, NodePoolServiceAccount: validOpts.NodePoolServiceAccount, ControlPlaneServiceAccount: validOpts.ControlPlaneServiceAccount, CloudControllerServiceAccount: validOpts.CloudControllerServiceAccount, StorageServiceAccount: validOpts.StorageServiceAccount, ImageRegistryServiceAccount: validOpts.ImageRegistryServiceAccount}, expectErr: true, expectSubstr: "required flag(s) \"network-service-account\" not set", }, - "all required fields provided": { + "When all required fields are provided, it should succeed": { opts: validOpts, expectErr: false, }, @@ -165,7 +165,7 @@ func TestCreateCluster(t *testing.T) { args []string }{ { - name: "minimal flags necessary to render", + name: "When minimal flags are provided, it should render successfully", args: []string{ "--project=test-project-123", "--region=us-central1", diff --git a/cmd/cluster/gcp/testdata/zz_fixture_TestCreateCluster_minimal_flags_necessary_to_render.yaml b/cmd/cluster/gcp/testdata/zz_fixture_TestCreateCluster_When_minimal_flags_are_provided__it_should_render_successfully.yaml similarity index 100% rename from cmd/cluster/gcp/testdata/zz_fixture_TestCreateCluster_minimal_flags_necessary_to_render.yaml rename to cmd/cluster/gcp/testdata/zz_fixture_TestCreateCluster_When_minimal_flags_are_provided__it_should_render_successfully.yaml diff --git a/cmd/cluster/kubevirt/create_test.go b/cmd/cluster/kubevirt/create_test.go index 768abffbac4b..162158aa4fae 100644 --- a/cmd/cluster/kubevirt/create_test.go +++ b/cmd/cluster/kubevirt/create_test.go @@ -25,14 +25,14 @@ func TestRawCreateOptions_Validate(t *testing.T) { expectedError string }{ { - name: "unsupported publishing strategy", + name: "When unsupported publishing strategy is provided, it should return an error", input: RawCreateOptions{ ServicePublishingStrategy: "whatever", }, expectedError: "service publish strategy whatever is not supported, supported options: Ingress, NodePort", }, { - name: "api server address invalid for ingress", + name: "When API server address is provided with Ingress strategy, it should return an error", input: RawCreateOptions{ ServicePublishingStrategy: IngressServicePublishingStrategy, APIServerAddress: "whatever", @@ -40,7 +40,7 @@ func TestRawCreateOptions_Validate(t *testing.T) { expectedError: "external-api-server-address is supported only for NodePort service publishing strategy, service publishing strategy Ingress is used", }, { - name: "invalid infra storage class mappings", + name: "When invalid infra storage class mappings are provided, it should return an error", input: RawCreateOptions{ ServicePublishingStrategy: IngressServicePublishingStrategy, InfraStorageClassMappings: []string{"bad"}, @@ -48,7 +48,7 @@ func TestRawCreateOptions_Validate(t *testing.T) { expectedError: "invalid infra storageclass mapping [bad]", }, { - name: "kubeconfig present without namespace", + name: "When kubeconfig is provided without namespace, it should return an error", input: RawCreateOptions{ ServicePublishingStrategy: IngressServicePublishingStrategy, InfraKubeConfigFile: "something", @@ -56,7 +56,7 @@ func TestRawCreateOptions_Validate(t *testing.T) { expectedError: "external infra cluster kubeconfig was provided but an infra namespace is missing", }, { - name: "kubeconfig missing with namespace", + name: "When namespace is provided without kubeconfig, it should return an error", input: RawCreateOptions{ ServicePublishingStrategy: IngressServicePublishingStrategy, InfraNamespace: "something", @@ -134,7 +134,7 @@ func TestCreateCluster(t *testing.T) { args []string }{ { - name: "minimal flags necessary to render", + name: "When minimal flags are provided, it should render successfully", args: []string{ "--render-sensitive", "--name=example", @@ -142,7 +142,7 @@ func TestCreateCluster(t *testing.T) { }, }, { - name: "test from dvossel", + name: "When complex configuration flags are provided, it should create cluster with all options", args: []string{ "--name", "test1", "--etcd-storage-class=gp3-csi", diff --git a/cmd/cluster/kubevirt/testdata/zz_fixture_TestCreateCluster_test_from_dvossel.yaml b/cmd/cluster/kubevirt/testdata/zz_fixture_TestCreateCluster_When_complex_configuration_flags_are_provided__it_should_create_cluster_with_all_options.yaml similarity index 100% rename from cmd/cluster/kubevirt/testdata/zz_fixture_TestCreateCluster_test_from_dvossel.yaml rename to cmd/cluster/kubevirt/testdata/zz_fixture_TestCreateCluster_When_complex_configuration_flags_are_provided__it_should_create_cluster_with_all_options.yaml diff --git a/cmd/cluster/kubevirt/testdata/zz_fixture_TestCreateCluster_minimal_flags_necessary_to_render.yaml b/cmd/cluster/kubevirt/testdata/zz_fixture_TestCreateCluster_When_minimal_flags_are_provided__it_should_render_successfully.yaml similarity index 100% rename from cmd/cluster/kubevirt/testdata/zz_fixture_TestCreateCluster_minimal_flags_necessary_to_render.yaml rename to cmd/cluster/kubevirt/testdata/zz_fixture_TestCreateCluster_When_minimal_flags_are_provided__it_should_render_successfully.yaml diff --git a/cmd/cluster/none/create_test.go b/cmd/cluster/none/create_test.go index 37263d5f798e..f5667ec623d9 100644 --- a/cmd/cluster/none/create_test.go +++ b/cmd/cluster/none/create_test.go @@ -32,7 +32,7 @@ func TestCreateCluster(t *testing.T) { args []string }{ { - name: "minimal flags necessary to render", + name: "When minimal flags are provided, it should render successfully", args: []string{ "--external-api-server-address=fakeAddress", // if we don't set it, the machine's IP is looked up, which isn't portable "--render-sensitive", diff --git a/cmd/cluster/none/testdata/zz_fixture_TestCreateCluster_minimal_flags_necessary_to_render.yaml b/cmd/cluster/none/testdata/zz_fixture_TestCreateCluster_When_minimal_flags_are_provided__it_should_render_successfully.yaml similarity index 100% rename from cmd/cluster/none/testdata/zz_fixture_TestCreateCluster_minimal_flags_necessary_to_render.yaml rename to cmd/cluster/none/testdata/zz_fixture_TestCreateCluster_When_minimal_flags_are_provided__it_should_render_successfully.yaml diff --git a/cmd/cluster/openstack/create_test.go b/cmd/cluster/openstack/create_test.go index ea1215e517fe..9b06e6f2e611 100644 --- a/cmd/cluster/openstack/create_test.go +++ b/cmd/cluster/openstack/create_test.go @@ -25,7 +25,7 @@ func TestCreateOptions_Validate(t *testing.T) { expectedError string }{ { - name: "missing OpenStack credentials file", + name: "When OpenStack credentials file is missing, it should return an error", input: RawCreateOptions{ OpenStackCredentialsFile: "thisisajunkfilename.yaml", }, @@ -78,7 +78,7 @@ func TestCreateCluster(t *testing.T) { args []string }{ { - name: "minimal flags necessary to render", + name: "When minimal flags are provided, it should render successfully", args: []string{ "--openstack-credentials-file=" + credentialsFile, "--openstack-node-flavor=m1.xlarge", @@ -89,7 +89,7 @@ func TestCreateCluster(t *testing.T) { }, }, { - name: "default creation flags", + name: "When default creation flags are provided, it should render successfully", args: []string{ "--openstack-credentials-file=" + credentialsFile, "--openstack-external-network-id=5387f86a-a10e-47fe-91c6-41ac131f9f30", @@ -147,7 +147,7 @@ func TestExtractCloud(t *testing.T) { } } - t.Run("invalid path", func(t *testing.T) { + t.Run("When path is invalid it should return an error", func(t *testing.T) { tempDir := t.TempDir() // we know a new temporary directory will be empty so this file will never exist cloudsYAMLPath := filepath.Join(tempDir, "clouds.yaml") @@ -159,7 +159,7 @@ func TestExtractCloud(t *testing.T) { assert.Error(t, err) }) - t.Run("empty clouds.yaml", func(t *testing.T) { + t.Run("When clouds.yaml contains invalid YAML it should return an error", func(t *testing.T) { tempDir := t.TempDir() cloudsYAMLPath := filepath.Join(tempDir, "clouds.yaml") junkData := []byte("{ this is not valid YAML }") @@ -174,7 +174,7 @@ func TestExtractCloud(t *testing.T) { assert.Error(t, err) }) - t.Run("incomplete clouds.yaml", func(t *testing.T) { + t.Run("When clouds.yaml is empty it should return an error", func(t *testing.T) { tempDir := t.TempDir() cloudsYAMLPath := filepath.Join(tempDir, "clouds.yaml") junkData := []byte("") @@ -189,7 +189,7 @@ func TestExtractCloud(t *testing.T) { assert.Error(t, err) }) - t.Run("invalid cloud for clouds.yaml", func(t *testing.T) { + t.Run("When cloud name is not found in clouds.yaml it should return an error", func(t *testing.T) { tempDir := t.TempDir() cloudsYAMLPath := filepath.Join(tempDir, "clouds.yaml") clouds := map[string]any{ @@ -204,7 +204,7 @@ func TestExtractCloud(t *testing.T) { assert.Error(t, err) }) - t.Run("invalid cacert path in clouds.yaml", func(t *testing.T) { + t.Run("When cacert path in clouds.yaml is invalid it should return an error", func(t *testing.T) { tempDir := t.TempDir() cloudsYAMLPath := filepath.Join(tempDir, "clouds.yaml") // we know a new temporary directory will be empty so this file will not exist @@ -228,7 +228,7 @@ func TestExtractCloud(t *testing.T) { assert.Error(t, err) }) - t.Run("drop any additional clouds specified in clouds.yaml", func(t *testing.T) { + t.Run("When additional clouds are specified in clouds.yaml it should drop them", func(t *testing.T) { tempDir := t.TempDir() cloudsYAMLPath := filepath.Join(tempDir, "clouds.yaml") caCertPath := filepath.Join(tempDir, "valid-ca.crt") @@ -270,7 +270,7 @@ func TestExtractCloud(t *testing.T) { assert.Nil(t, err) }) - t.Run("explicit cacert preferred to clouds.yaml", func(t *testing.T) { + t.Run("When explicit cacert is provided it should be preferred over clouds.yaml cacert", func(t *testing.T) { tempDir := t.TempDir() cloudsYAMLPath := filepath.Join(tempDir, "clouds.yaml") // we know a new temporary directory will be empty so this file will not exist diff --git a/cmd/cluster/openstack/testdata/zz_fixture_TestCreateCluster_default_creation_flags.yaml b/cmd/cluster/openstack/testdata/zz_fixture_TestCreateCluster_When_default_creation_flags_are_provided__it_should_render_successfully.yaml similarity index 100% rename from cmd/cluster/openstack/testdata/zz_fixture_TestCreateCluster_default_creation_flags.yaml rename to cmd/cluster/openstack/testdata/zz_fixture_TestCreateCluster_When_default_creation_flags_are_provided__it_should_render_successfully.yaml diff --git a/cmd/cluster/openstack/testdata/zz_fixture_TestCreateCluster_minimal_flags_necessary_to_render.yaml b/cmd/cluster/openstack/testdata/zz_fixture_TestCreateCluster_When_minimal_flags_are_provided__it_should_render_successfully.yaml similarity index 100% rename from cmd/cluster/openstack/testdata/zz_fixture_TestCreateCluster_minimal_flags_necessary_to_render.yaml rename to cmd/cluster/openstack/testdata/zz_fixture_TestCreateCluster_When_minimal_flags_are_provided__it_should_render_successfully.yaml diff --git a/cmd/cluster/powervs/create_test.go b/cmd/cluster/powervs/create_test.go index f97d93a31021..420c44bed7e7 100644 --- a/cmd/cluster/powervs/create_test.go +++ b/cmd/cluster/powervs/create_test.go @@ -94,7 +94,7 @@ func TestCreateCluster(t *testing.T) { args []string }{ { - name: "minimal flags necessary to render", + name: "When minimal flags are provided, it should render successfully", args: []string{ "--infra-json=" + infraFile, "--render-sensitive", diff --git a/cmd/cluster/powervs/testdata/zz_fixture_TestCreateCluster_minimal_flags_necessary_to_render.yaml b/cmd/cluster/powervs/testdata/zz_fixture_TestCreateCluster_When_minimal_flags_are_provided__it_should_render_successfully.yaml similarity index 100% rename from cmd/cluster/powervs/testdata/zz_fixture_TestCreateCluster_minimal_flags_necessary_to_render.yaml rename to cmd/cluster/powervs/testdata/zz_fixture_TestCreateCluster_When_minimal_flags_are_provided__it_should_render_successfully.yaml diff --git a/cmd/fix/dr_oidc_iam_test.go b/cmd/fix/dr_oidc_iam_test.go index 66b91a557deb..90044a9bc3f8 100644 --- a/cmd/fix/dr_oidc_iam_test.go +++ b/cmd/fix/dr_oidc_iam_test.go @@ -48,14 +48,14 @@ func TestDrOidcIamOptions_ValidateCredentials(t *testing.T) { expectError bool errorMsg string }{ - "valid aws-creds only": { + "When only aws-creds is provided, it should succeed": { opts: &DrOidcIamOptions{ InfraID: "test-cluster", Region: "us-east-1", AWSCredentialsFile: "/path/to/aws-creds", }, }, - "valid sts-creds and role-arn": { + "When sts-creds and role-arn are provided, it should succeed": { opts: &DrOidcIamOptions{ InfraID: "test-cluster", Region: "us-east-1", @@ -63,7 +63,7 @@ func TestDrOidcIamOptions_ValidateCredentials(t *testing.T) { RoleArn: "arn:aws:iam::123456789:role/test", }, }, - "aws-creds with sts-creds conflict": { + "When aws-creds and sts-creds are provided, it should return a conflict error": { opts: &DrOidcIamOptions{ InfraID: "test-cluster", Region: "us-east-1", @@ -73,7 +73,7 @@ func TestDrOidcIamOptions_ValidateCredentials(t *testing.T) { expectError: true, errorMsg: "only one of 'aws-creds' or 'sts-creds'/'role-arn' can be provided", }, - "aws-creds with role-arn conflict": { + "When aws-creds and role-arn are provided, it should return a conflict error": { opts: &DrOidcIamOptions{ InfraID: "test-cluster", Region: "us-east-1", @@ -83,7 +83,7 @@ func TestDrOidcIamOptions_ValidateCredentials(t *testing.T) { expectError: true, errorMsg: "only one of 'aws-creds' or 'sts-creds'/'role-arn' can be provided", }, - "sts-creds without role-arn": { + "When sts-creds is provided without role-arn, it should return an error": { opts: &DrOidcIamOptions{ InfraID: "test-cluster", Region: "us-east-1", @@ -92,7 +92,7 @@ func TestDrOidcIamOptions_ValidateCredentials(t *testing.T) { expectError: true, errorMsg: "role-arn is required when using sts-creds", }, - "role-arn without sts-creds": { + "When role-arn is provided without sts-creds, it should return an error": { opts: &DrOidcIamOptions{ InfraID: "test-cluster", Region: "us-east-1", @@ -101,7 +101,7 @@ func TestDrOidcIamOptions_ValidateCredentials(t *testing.T) { expectError: true, errorMsg: "sts-creds is required when using role-arn", }, - "no credentials provided": { + "When no credentials are provided, it should return an error": { opts: &DrOidcIamOptions{ InfraID: "test-cluster", Region: "us-east-1", @@ -133,28 +133,28 @@ func TestDrOidcIamOptions_Validate(t *testing.T) { expectError bool errorMsg string }{ - "valid with infra-id and region": { + "When infra-id and region are provided, it should succeed": { opts: &DrOidcIamOptions{ InfraID: "test-cluster", Region: "us-east-1", AWSCredentialsFile: "/path/to/creds", }, }, - "valid with hc-name and hc-namespace": { + "When hc-name and hc-namespace are provided, it should succeed": { opts: &DrOidcIamOptions{ HostedClusterName: "my-hc", HostedClusterNamespace: "clusters", AWSCredentialsFile: "/path/to/creds", }, }, - "missing both infra-id and region when no hc-name": { + "When infra-id region and hc-name are missing, it should return an error": { opts: &DrOidcIamOptions{ AWSCredentialsFile: "/path/to/creds", }, expectError: true, errorMsg: "--infra-id and --region are required when --hc-name is not set", }, - "missing region when no hc-name": { + "When region and hc-name are missing, it should return an error": { opts: &DrOidcIamOptions{ InfraID: "test-cluster", AWSCredentialsFile: "/path/to/creds", @@ -162,7 +162,7 @@ func TestDrOidcIamOptions_Validate(t *testing.T) { expectError: true, errorMsg: "--infra-id and --region are required when --hc-name is not set", }, - "missing infra-id when no hc-name": { + "When infra-id and hc-name are missing, it should return an error": { opts: &DrOidcIamOptions{ Region: "us-east-1", AWSCredentialsFile: "/path/to/creds", @@ -170,7 +170,7 @@ func TestDrOidcIamOptions_Validate(t *testing.T) { expectError: true, errorMsg: "--infra-id and --region are required when --hc-name is not set", }, - "hc-namespace without hc-name": { + "When hc-namespace is provided without hc-name, it should return an error": { opts: &DrOidcIamOptions{ HostedClusterNamespace: "clusters", AWSCredentialsFile: "/path/to/creds", @@ -178,7 +178,7 @@ func TestDrOidcIamOptions_Validate(t *testing.T) { expectError: true, errorMsg: "--hc-namespace can only be used with --hc-name", }, - "hc-name without hc-namespace": { + "When hc-name is provided without hc-namespace, it should return an error": { opts: &DrOidcIamOptions{ HostedClusterName: "my-hc", AWSCredentialsFile: "/path/to/creds", @@ -186,7 +186,7 @@ func TestDrOidcIamOptions_Validate(t *testing.T) { expectError: true, errorMsg: "--hc-namespace is required when using --hc-name", }, - "hc-name with infra-id conflict": { + "When hc-name and infra-id are provided, it should return a conflict error": { opts: &DrOidcIamOptions{ HostedClusterName: "my-hc", HostedClusterNamespace: "clusters", @@ -196,7 +196,7 @@ func TestDrOidcIamOptions_Validate(t *testing.T) { expectError: true, errorMsg: "when using --hc-name, --infra-id and --region should not be specified", }, - "hc-name with region conflict": { + "When hc-name and region are provided, it should return a conflict error": { opts: &DrOidcIamOptions{ HostedClusterName: "my-hc", HostedClusterNamespace: "clusters", diff --git a/cmd/infra/aws/create_operator_roles_test.go b/cmd/infra/aws/create_operator_roles_test.go index 1d77ec6ccee5..002963276024 100644 --- a/cmd/infra/aws/create_operator_roles_test.go +++ b/cmd/infra/aws/create_operator_roles_test.go @@ -27,20 +27,20 @@ func TestCreateOperatorRolesValidate(t *testing.T) { opts CreateOperatorRolesOptions expectError bool }{ - "When both oidc-issuer-url and instance-role-arn are provided it should error": { + "When both oidc-issuer-url and instance-role-arn are provided, it should error": { opts: CreateOperatorRolesOptions{ OIDCIssuerURL: "https://oidc.example.com", InstanceRoleARN: "arn:aws:iam::123456789012:role/instance-role", }, expectError: true, }, - "When oidc-issuer-url is provided it should succeed": { + "When oidc-issuer-url is provided, it should succeed": { opts: CreateOperatorRolesOptions{ OIDCIssuerURL: "https://oidc.example.com", }, expectError: false, }, - "When instance-role-arn is provided it should succeed": { + "When instance-role-arn is provided, it should succeed": { opts: CreateOperatorRolesOptions{ InstanceRoleARN: "arn:aws:iam::123456789012:role/instance-role", }, @@ -71,7 +71,7 @@ func TestResolveOIDCProvider(t *testing.T) { expectError bool errorContains string }{ - "When matching provider exists it should return its ARN": { + "When matching provider exists, it should return its ARN": { issuerURL: "https://oidc.eks.us-east-1.amazonaws.com/id/EXAMPLE123", providers: []iamtypes.OpenIDConnectProviderListEntry{ {Arn: aws.String("arn:aws:iam::123456789012:oidc-provider/oidc.eks.us-east-1.amazonaws.com/id/EXAMPLE123")}, @@ -79,7 +79,7 @@ func TestResolveOIDCProvider(t *testing.T) { expectARN: "arn:aws:iam::123456789012:oidc-provider/oidc.eks.us-east-1.amazonaws.com/id/EXAMPLE123", expectName: "oidc.eks.us-east-1.amazonaws.com/id/EXAMPLE123", }, - "When no matching provider exists it should error": { + "When no matching provider exists, it should error": { issuerURL: "https://oidc.example.com", providers: []iamtypes.OpenIDConnectProviderListEntry{ {Arn: aws.String("arn:aws:iam::123456789012:oidc-provider/other.example.com")}, @@ -87,19 +87,19 @@ func TestResolveOIDCProvider(t *testing.T) { expectError: true, errorContains: "no OIDC provider found", }, - "When listing providers fails it should error": { + "When listing providers fails, it should error": { issuerURL: "https://oidc.example.com", listErr: fmt.Errorf("access denied"), expectError: true, errorContains: "failed to list OIDC providers", }, - "When provider list is empty it should error": { + "When provider list is empty, it should error": { issuerURL: "https://oidc.example.com", providers: []iamtypes.OpenIDConnectProviderListEntry{}, expectError: true, errorContains: "no OIDC provider found", }, - "When issuer URL has https prefix it should strip it for matching": { + "When issuer URL has https prefix, it should strip it for matching": { issuerURL: "https://s3.us-east-1.amazonaws.com/mybucket", providers: []iamtypes.OpenIDConnectProviderListEntry{ {Arn: aws.String("arn:aws:iam::123456789012:oidc-provider/s3.us-east-1.amazonaws.com/mybucket")}, @@ -107,7 +107,7 @@ func TestResolveOIDCProvider(t *testing.T) { expectARN: "arn:aws:iam::123456789012:oidc-provider/s3.us-east-1.amazonaws.com/mybucket", expectName: "s3.us-east-1.amazonaws.com/mybucket", }, - "When substring match exists but not suffix match it should not match": { + "When substring match exists but not suffix match, it should not match": { issuerURL: "https://example.com", providers: []iamtypes.OpenIDConnectProviderListEntry{ {Arn: aws.String("arn:aws:iam::123456789012:oidc-provider/my-example.com")}, @@ -153,7 +153,7 @@ func TestBuildTrustPolicies(t *testing.T) { errorContains string validate func(*GomegaWithT, *operatorTrustPolicies) }{ - "When instance role ARN is provided it should use instance role trust policy": { + "When instance role ARN is provided, it should use instance role trust policy": { opts: CreateOperatorRolesOptions{ InstanceRoleARN: "arn:aws:iam::123456789012:role/instance-role", OperatorNamespace: "hypershift", @@ -165,7 +165,7 @@ func TestBuildTrustPolicies(t *testing.T) { g.Expect(tp.operatorTrust).To(Equal(tp.externalDNSTrust)) }, }, - "When OIDC issuer URL is provided it should resolve provider and build trust policies": { + "When OIDC issuer URL is provided, it should resolve provider and build trust policies": { opts: CreateOperatorRolesOptions{ OIDCIssuerURL: "https://oidc.example.com", OperatorNamespace: "hypershift", @@ -184,7 +184,7 @@ func TestBuildTrustPolicies(t *testing.T) { g.Expect(tp.operatorTrust).ToNot(Equal(tp.externalDNSTrust)) }, }, - "When OIDC provider resolution fails it should return error": { + "When OIDC provider resolution fails, it should return error": { opts: CreateOperatorRolesOptions{ OIDCIssuerURL: "https://unknown.example.com", OperatorNamespace: "hypershift", @@ -233,7 +233,7 @@ func TestCreateOrUpdateRole(t *testing.T) { expectError bool errorContains string }{ - "When role creation and trust update succeed it should return the ARN": { + "When role creation and trust update succeed, it should return the ARN": { setupMock: func(m *awsapi.MockIAMAPI) { m.EXPECT().GetRole(gomock.Any(), gomock.Any(), gomock.Any()). Return(&iam.GetRoleOutput{Role: &iamtypes.Role{ @@ -247,7 +247,7 @@ func TestCreateOrUpdateRole(t *testing.T) { }, expectARN: roleARN, }, - "When trust policy update fails it should return error": { + "When trust policy update fails, it should return error": { setupMock: func(m *awsapi.MockIAMAPI) { m.EXPECT().GetRole(gomock.Any(), gomock.Any(), gomock.Any()). Return(&iam.GetRoleOutput{Role: &iamtypes.Role{ @@ -333,7 +333,7 @@ func TestCreateOperatorRoles(t *testing.T) { errorContains string validate func(*GomegaWithT, *CreateOperatorRolesOutput) }{ - "When all roles are created successfully with OIDC it should return all ARNs": { + "When all roles are created successfully with OIDC, it should return all ARNs": { opts: CreateOperatorRolesOptions{ OIDCIssuerURL: "https://oidc.example.com", NamePrefix: "hypershift", @@ -347,7 +347,7 @@ func TestCreateOperatorRoles(t *testing.T) { g.Expect(output.ExternalDNSRoleARN).To(Equal(dnsRoleARN)) }, }, - "When Route53 hosted zone ID is specified it should scope the policy": { + "When Route53 hosted zone ID is specified, it should scope the policy": { opts: CreateOperatorRolesOptions{ InstanceRoleARN: "arn:aws:iam::123456789012:role/instance-role", NamePrefix: "hypershift", @@ -419,11 +419,11 @@ func TestParseAdditionalTags(t *testing.T) { expectError bool expectCount int }{ - "When no tags provided it should succeed with empty list": { + "When no tags provided, it should succeed with empty list": { tags: nil, expectCount: 0, }, - "When valid tags provided it should parse them": { + "When valid tags provided, it should parse them": { tags: []string{"env=prod", "team=platform"}, expectCount: 2, }, diff --git a/cmd/infra/aws/destroy_iam_test.go b/cmd/infra/aws/destroy_iam_test.go index 18d755ff4c4b..be974d6064b3 100644 --- a/cmd/infra/aws/destroy_iam_test.go +++ b/cmd/infra/aws/destroy_iam_test.go @@ -126,7 +126,7 @@ func TestDestroyOIDCRole(t *testing.T) { expectRemoved: true, }, { - name: "When GetRole returns an API error it should return a wrapped error", + name: "When GetRole returns an API error, it should return a wrapped error", setupMock: func(m *awsapi.MockIAMAPI) { m.EXPECT().GetRole(gomock.Any(), &iam.GetRoleInput{RoleName: aws.String(roleName)}, gomock.Any()). Return(nil, errors.New("api error")) @@ -135,7 +135,7 @@ func TestDestroyOIDCRole(t *testing.T) { errorContains: "cannot check for existing role", }, { - name: "When ListAttachedRolePolicies fails it should return the error", + name: "When ListAttachedRolePolicies fails, it should return the error", setupMock: func(m *awsapi.MockIAMAPI) { gomock.InOrder( m.EXPECT().GetRole(gomock.Any(), &iam.GetRoleInput{RoleName: aws.String(roleName)}, gomock.Any()). @@ -148,7 +148,7 @@ func TestDestroyOIDCRole(t *testing.T) { errorContains: "failed to list attached policies", }, { - name: "When DetachRolePolicy fails it should return the error", + name: "When DetachRolePolicy fails, it should return the error", setupMock: func(m *awsapi.MockIAMAPI) { gomock.InOrder( m.EXPECT().GetRole(gomock.Any(), &iam.GetRoleInput{RoleName: aws.String(roleName)}, gomock.Any()). @@ -167,7 +167,7 @@ func TestDestroyOIDCRole(t *testing.T) { errorContains: "failed to detach policy", }, { - name: "When ListRolePolicies fails it should return the error", + name: "When ListRolePolicies fails, it should return the error", setupMock: func(m *awsapi.MockIAMAPI) { gomock.InOrder( m.EXPECT().GetRole(gomock.Any(), &iam.GetRoleInput{RoleName: aws.String(roleName)}, gomock.Any()). @@ -182,7 +182,7 @@ func TestDestroyOIDCRole(t *testing.T) { errorContains: "failed to list inline policies", }, { - name: "When DeleteRole fails it should return the error", + name: "When DeleteRole fails, it should return the error", setupMock: func(m *awsapi.MockIAMAPI) { gomock.InOrder( m.EXPECT().GetRole(gomock.Any(), &iam.GetRoleInput{RoleName: aws.String(roleName)}, gomock.Any()). @@ -331,7 +331,7 @@ func TestDestroyWorkerInstanceProfile(t *testing.T) { }, }, { - name: "When GetInstanceProfile returns an API error it should return the error", + name: "When GetInstanceProfile returns an API error, it should return the error", setupMock: func(m *awsapi.MockIAMAPI) { m.EXPECT().GetInstanceProfile(gomock.Any(), &iam.GetInstanceProfileInput{InstanceProfileName: aws.String(profileName)}, gomock.Any()). Return(nil, errors.New("api error")) @@ -340,7 +340,7 @@ func TestDestroyWorkerInstanceProfile(t *testing.T) { errorContains: "cannot check for existing instance profile", }, { - name: "When RemoveRoleFromInstanceProfile fails it should return the error", + name: "When RemoveRoleFromInstanceProfile fails, it should return the error", setupMock: func(m *awsapi.MockIAMAPI) { gomock.InOrder( m.EXPECT().GetInstanceProfile(gomock.Any(), &iam.GetInstanceProfileInput{InstanceProfileName: aws.String(profileName)}, gomock.Any()). @@ -458,7 +458,7 @@ func TestDestroyOIDCResources(t *testing.T) { }, }, { - name: "When ListOpenIDConnectProviders fails it should return the error", + name: "When ListOpenIDConnectProviders fails, it should return the error", setupMock: func(m *awsapi.MockIAMAPI) { m.EXPECT().ListOpenIDConnectProviders(gomock.Any(), gomock.Any(), gomock.Any()). Return(nil, errors.New("api error")) @@ -467,7 +467,7 @@ func TestDestroyOIDCResources(t *testing.T) { errorContains: "api error", }, { - name: "When DeleteOpenIDConnectProvider fails with a non-NSE error it should still attempt role cleanup and return the error", + name: "When DeleteOpenIDConnectProvider fails with a non-NSE error, it should still attempt role cleanup and return the error", setupMock: func(m *awsapi.MockIAMAPI) { gomock.InOrder( m.EXPECT().ListOpenIDConnectProviders(gomock.Any(), gomock.Any(), gomock.Any()). @@ -487,7 +487,7 @@ func TestDestroyOIDCResources(t *testing.T) { errorContains: "permission denied", }, { - name: "When shared-role fails it should still attempt all component role deletions and aggregate errors", + name: "When shared-role fails, it should still attempt all component role deletions and aggregate errors", setupMock: func(m *awsapi.MockIAMAPI) { sharedRoleName := testInfraID + "-shared-role" ingressRoleName := testInfraID + "-openshift-ingress" @@ -509,7 +509,7 @@ func TestDestroyOIDCResources(t *testing.T) { errorContainsAll: []string{"shared-role api error", "ingress api error"}, }, { - name: "When multiple component role deletions fail it should aggregate all errors", + name: "When multiple component role deletions fail, it should aggregate all errors", setupMock: func(m *awsapi.MockIAMAPI) { sharedRoleName := testInfraID + "-shared-role" ingressRoleName := testInfraID + "-openshift-ingress" @@ -577,7 +577,7 @@ func TestDestroySharedVPCRoles(t *testing.T) { errorContainsAll []string }{ { - name: "When PrivateZonesInClusterAccount is false ingress role should use vpcOwnerClient", + name: "When PrivateZonesInClusterAccount is false, it should use vpcOwnerClient for ingress role", privateZonesInCluster: false, setupIAMMock: func(_ *awsapi.MockIAMAPI) {}, setupVPCOwnerMock: func(m *awsapi.MockIAMAPI) { @@ -590,7 +590,7 @@ func TestDestroySharedVPCRoles(t *testing.T) { }, }, { - name: "When PrivateZonesInClusterAccount is true ingress role should use iamClient", + name: "When PrivateZonesInClusterAccount is true, it should use iamClient for ingress role", privateZonesInCluster: true, setupIAMMock: func(m *awsapi.MockIAMAPI) { m.EXPECT().GetRole(gomock.Any(), &iam.GetRoleInput{RoleName: aws.String(ingressRoleName)}, gomock.Any()). @@ -602,7 +602,7 @@ func TestDestroySharedVPCRoles(t *testing.T) { }, }, { - name: "When destroying the ingress role fails it should still attempt control-plane role and return the error", + name: "When destroying the ingress role fails, it should still attempt control-plane role and return the error", privateZonesInCluster: false, setupIAMMock: func(_ *awsapi.MockIAMAPI) {}, setupVPCOwnerMock: func(m *awsapi.MockIAMAPI) { @@ -615,7 +615,7 @@ func TestDestroySharedVPCRoles(t *testing.T) { errorContains: "cannot check for existing role", }, { - name: "When destroying the control-plane role fails it should return the error", + name: "When destroying the control-plane role fails, it should return the error", privateZonesInCluster: false, setupIAMMock: func(_ *awsapi.MockIAMAPI) {}, setupVPCOwnerMock: func(m *awsapi.MockIAMAPI) { @@ -630,7 +630,7 @@ func TestDestroySharedVPCRoles(t *testing.T) { errorContains: "cannot check for existing role", }, { - name: "When both ingress and control-plane role deletions fail it should aggregate all errors", + name: "When both ingress and control-plane role deletions fail, it should aggregate all errors", privateZonesInCluster: false, setupIAMMock: func(_ *awsapi.MockIAMAPI) {}, setupVPCOwnerMock: func(m *awsapi.MockIAMAPI) { diff --git a/cmd/infra/aws/destroy_test.go b/cmd/infra/aws/destroy_test.go index c8564f3c882f..92453e23fc70 100644 --- a/cmd/infra/aws/destroy_test.go +++ b/cmd/infra/aws/destroy_test.go @@ -132,7 +132,7 @@ func TestEmptyBucket(t *testing.T) { errorContains string }{ { - name: "When deleting objects succeeds it should return nil", + name: "When deleting objects succeeds, it should return nil", bucketName: "test-bucket", setupMock: func(m *awsapi.MockS3API) { m.EXPECT().ListObjectsV2(gomock.Any(), gomock.Any(), gomock.Any()).Return( @@ -157,7 +157,7 @@ func TestEmptyBucket(t *testing.T) { expectError: false, }, { - name: "When partial deletion fails it should return error", + name: "When partial deletion fails, it should return error", bucketName: "test-bucket", setupMock: func(m *awsapi.MockS3API) { m.EXPECT().ListObjectsV2(gomock.Any(), gomock.Any(), gomock.Any()).Return( @@ -189,7 +189,7 @@ func TestEmptyBucket(t *testing.T) { errorContains: "failed to delete 1 objects from bucket test-bucket", }, { - name: "When bucket does not exist it should succeed", + name: "When bucket does not exist, it should succeed", bucketName: "non-existent-bucket", setupMock: func(m *awsapi.MockS3API) { m.EXPECT().ListObjectsV2(gomock.Any(), gomock.Any(), gomock.Any()).Return( @@ -199,7 +199,7 @@ func TestEmptyBucket(t *testing.T) { expectError: false, }, { - name: "When API error occurs it should return error", + name: "When API error occurs, it should return error", bucketName: "test-bucket", setupMock: func(m *awsapi.MockS3API) { m.EXPECT().ListObjectsV2(gomock.Any(), gomock.Any(), gomock.Any()).Return( diff --git a/cmd/infra/aws/ec2_test.go b/cmd/infra/aws/ec2_test.go index b5a65c83d4a3..38b021fe93d2 100644 --- a/cmd/infra/aws/ec2_test.go +++ b/cmd/infra/aws/ec2_test.go @@ -25,32 +25,32 @@ func TestIsRetriableVPCEndpointError(t *testing.T) { expected bool }{ { - name: "When error is invalidRouteTableID it should be retriable", + name: "When error is invalidRouteTableID, it should be retriable", err: &testAPIError{code: invalidRouteTableID}, expected: true, }, { - name: "When error is RequestLimitExceeded it should be retriable", + name: "When error is RequestLimitExceeded, it should be retriable", err: &testAPIError{code: "RequestLimitExceeded"}, expected: true, }, { - name: "When error is Throttling it should be retriable", + name: "When error is Throttling, it should be retriable", err: &testAPIError{code: "Throttling"}, expected: true, }, { - name: "When error is EC2ThrottledException it should be retriable", + name: "When error is EC2ThrottledException, it should be retriable", err: &testAPIError{code: "EC2ThrottledException"}, expected: true, }, { - name: "When error is a non-retriable API error it should not be retriable", + name: "When error is a non-retriable API error, it should not be retriable", err: &testAPIError{code: "InvalidParameterValue"}, expected: false, }, { - name: "When error is not an API error it should not be retriable", + name: "When error is not an API error, it should not be retriable", err: fmt.Errorf("network timeout"), expected: false, }, diff --git a/cmd/infra/aws/iam_test.go b/cmd/infra/aws/iam_test.go index efe9b7ab6147..38a88bd9e165 100644 --- a/cmd/infra/aws/iam_test.go +++ b/cmd/infra/aws/iam_test.go @@ -68,7 +68,7 @@ func TestCreateRole(t *testing.T) { expectARN: roleARN, }, { - name: "When GetRole returns an API error it should return the error", + name: "When GetRole returns an API error, it should return the error", setupMock: func(m *awsapi.MockIAMAPI) { m.EXPECT().GetRole(gomock.Any(), gomock.Any(), gomock.Any()). Return(nil, errors.New("api error")) @@ -77,7 +77,7 @@ func TestCreateRole(t *testing.T) { errorContains: "api error", }, { - name: "When CreateRole fails it should return the error", + name: "When CreateRole fails, it should return the error", setupMock: func(m *awsapi.MockIAMAPI) { gomock.InOrder( m.EXPECT().GetRole(gomock.Any(), gomock.Any(), gomock.Any()). @@ -171,7 +171,7 @@ func TestCreateRoleWithInlinePolicy(t *testing.T) { expectARN: roleARN, }, { - name: "When PutRolePolicy fails it should return the error", + name: "When PutRolePolicy fails, it should return the error", setupMock: func(m *awsapi.MockIAMAPI) { gomock.InOrder( m.EXPECT().GetRole(gomock.Any(), gomock.Any(), gomock.Any()). @@ -273,7 +273,7 @@ func TestCreateRoleWithManagedPolicy(t *testing.T) { expectARN: "arn:aws:iam::123456789012:role/" + roleName, }, { - name: "When AttachRolePolicy fails it should return the error", + name: "When AttachRolePolicy fails, it should return the error", setupMock: func(m *awsapi.MockIAMAPI) { gomock.InOrder( m.EXPECT().GetRole(gomock.Any(), gomock.Any(), gomock.Any()). @@ -369,7 +369,7 @@ func TestCreateOIDCProvider(t *testing.T) { expectARN: newARN, }, { - name: "When ListOpenIDConnectProviders fails it should return the error", + name: "When ListOpenIDConnectProviders fails, it should return the error", setupMock: func(m *awsapi.MockIAMAPI) { m.EXPECT().ListOpenIDConnectProviders(gomock.Any(), gomock.Any(), gomock.Any()). Return(nil, errors.New("api error")) @@ -378,7 +378,7 @@ func TestCreateOIDCProvider(t *testing.T) { errorContains: "api error", }, { - name: "When DeleteOpenIDConnectProvider fails it should return the error", + name: "When DeleteOpenIDConnectProvider fails, it should return the error", setupMock: func(m *awsapi.MockIAMAPI) { gomock.InOrder( m.EXPECT().ListOpenIDConnectProviders(gomock.Any(), gomock.Any(), gomock.Any()). @@ -395,7 +395,7 @@ func TestCreateOIDCProvider(t *testing.T) { errorContains: "delete failed", }, { - name: "When CreateOpenIDConnectProvider fails it should return the error", + name: "When CreateOpenIDConnectProvider fails, it should return the error", setupMock: func(m *awsapi.MockIAMAPI) { gomock.InOrder( m.EXPECT().ListOpenIDConnectProviders(gomock.Any(), gomock.Any(), gomock.Any()). @@ -522,7 +522,7 @@ func TestCreateWorkerInstanceProfile(t *testing.T) { }, }, { - name: "When CreateRole fails it should return the error", + name: "When CreateRole fails, it should return the error", setupMock: func(m *awsapi.MockIAMAPI) { gomock.InOrder( m.EXPECT().GetRole(gomock.Any(), gomock.Any(), gomock.Any()). @@ -535,7 +535,7 @@ func TestCreateWorkerInstanceProfile(t *testing.T) { errorContains: "cannot create worker role", }, { - name: "When CreateInstanceProfile fails it should return the error", + name: "When CreateInstanceProfile fails, it should return the error", setupMock: func(m *awsapi.MockIAMAPI) { gomock.InOrder( m.EXPECT().GetRole(gomock.Any(), gomock.Any(), gomock.Any()). @@ -689,12 +689,12 @@ func TestEnsureHostedZonePrefix(t *testing.T) { expectOut string }{ { - name: "When hostedZone lacks prefix it should prepend hostedzone/", + name: "When hostedZone lacks prefix, it should prepend hostedzone/", input: "Z1234567890ABC", expectOut: "hostedzone/Z1234567890ABC", }, { - name: "When hostedZone already has prefix it should return it unchanged", + name: "When hostedZone already has prefix, it should return it unchanged", input: "hostedzone/Z1234567890ABC", expectOut: "hostedzone/Z1234567890ABC", }, diff --git a/cmd/infra/aws/route53_test.go b/cmd/infra/aws/route53_test.go index 99e0d8e1e1b5..048af4b85251 100644 --- a/cmd/infra/aws/route53_test.go +++ b/cmd/infra/aws/route53_test.go @@ -104,7 +104,7 @@ func TestLookupPublicZone(t *testing.T) { expectID: "PUBZONE", }, { - name: "When the zone API call fails it should return an error", + name: "When the zone API call fails, it should return an error", baseDomain: testBaseDomain, useCtx: cancelledCtx, setupMock: func(m *awsapi.MockROUTE53API) { @@ -114,7 +114,7 @@ func TestLookupPublicZone(t *testing.T) { expectError: true, }, { - name: "When redact is true and zone lookup fails it should return error without logging the domain", + name: "When redact is true and zone lookup fails, it should return error without logging the domain", baseDomain: "secret.example.com", redact: true, useCtx: cancelledCtx, @@ -253,7 +253,7 @@ func TestCreatePrivateZone(t *testing.T) { expectID: "AUTHZONE", }, { - name: "When CreateHostedZone fails it should return a wrapped error", + name: "When CreateHostedZone fails, it should return a wrapped error", zoneName: testZoneName, vpcID: testVPCID, useCtx: cancelledCtx, @@ -268,7 +268,7 @@ func TestCreatePrivateZone(t *testing.T) { errorContains: "failed to create hosted zone", }, { - name: "When setSOAMinimum fails on an existing zone it should return an error", + name: "When setSOAMinimum fails on an existing zone, it should return an error", zoneName: testZoneName, vpcID: testVPCID, setupMock: func(m *awsapi.MockROUTE53API) { @@ -388,7 +388,7 @@ func TestCleanupPublicZone(t *testing.T) { }, }, { - name: "When LookupZone fails with a non-not-found error it should return a wrapped error", + name: "When LookupZone fails with a non-not-found error, it should return a wrapped error", useCtx: cancelledCtx, setupMock: func(m *awsapi.MockROUTE53API) { m.EXPECT().ListHostedZones(gomock.Any(), gomock.Any(), gomock.Any()). @@ -398,7 +398,7 @@ func TestCleanupPublicZone(t *testing.T) { errorContains: "failed to lookup public hosted zone", }, { - name: "When ChangeResourceRecordSets fails with a non-404 error it should return the error", + name: "When ChangeResourceRecordSets fails with a non-404 error, it should return the error", setupMock: func(m *awsapi.MockROUTE53API) { m.EXPECT().ListHostedZones(gomock.Any(), gomock.Any(), gomock.Any()). Return(publicZonePage("PUBZONE", testBaseDomain), nil) @@ -484,7 +484,7 @@ func TestDestroyDNS(t *testing.T) { }, }, { - name: "When CleanupPublicZone fails it should return the error", + name: "When CleanupPublicZone fails, it should return the error", setupMock: func(m *awsapi.MockROUTE53API) { m.EXPECT().ListHostedZones(gomock.Any(), gomock.Any(), gomock.Any()). Return(publicZonePage("PUBZONE", testBaseDomain), nil) @@ -574,7 +574,7 @@ func TestDestroyPrivateZones(t *testing.T) { setupRecsMock: func(_ *awsapi.MockROUTE53API) {}, }, { - name: "When ListHostedZonesByVPC fails it should return the error", + name: "When ListHostedZonesByVPC fails, it should return the error", useCtx: cancelledCtx, setupListMock: func(m *awsapi.MockROUTE53API) { m.EXPECT().ListHostedZonesByVPC(gomock.Any(), gomock.Any(), gomock.Any()). @@ -585,7 +585,7 @@ func TestDestroyPrivateZones(t *testing.T) { errorContains: "failed to list hosted zones for vpc", }, { - name: "When deleteZone fails it should return the error", + name: "When deleteZone fails, it should return the error", setupListMock: func(m *awsapi.MockROUTE53API) { m.EXPECT().ListHostedZonesByVPC(gomock.Any(), gomock.Any(), gomock.Any()). Return(&route53.ListHostedZonesByVPCOutput{ diff --git a/cmd/infra/aws/util/errors_test.go b/cmd/infra/aws/util/errors_test.go index 2e2ed1fb5364..b4bbb4a9545f 100644 --- a/cmd/infra/aws/util/errors_test.go +++ b/cmd/infra/aws/util/errors_test.go @@ -20,32 +20,32 @@ func TestIsErrorRetryable(t *testing.T) { expected bool }{ { - name: "When error is a generic error it should be retryable", + name: "When error is a generic error, it should be retryable", err: errors.New("some transient error"), expected: true, }, { - name: "When error is a credential load error it should not be retryable", + name: "When error is a credential load error, it should not be retryable", err: config.SharedConfigLoadError{}, expected: false, }, { - name: "When error is a wrapped credential load error it should not be retryable", + name: "When error is a wrapped credential load error, it should not be retryable", err: fmt.Errorf("loading config: %w", config.SharedConfigLoadError{}), expected: false, }, { - name: "When aggregate has single generic error it should be retryable", + name: "When aggregate has single generic error, it should be retryable", err: utilerrors.NewAggregate([]error{errors.New("transient")}), expected: true, }, { - name: "When aggregate has single credential load error it should not be retryable", + name: "When aggregate has single credential load error, it should not be retryable", err: utilerrors.NewAggregate([]error{config.SharedConfigLoadError{}}), expected: false, }, { - name: "When aggregate has only credential load errors it should not be retryable", + name: "When aggregate has only credential load errors, it should not be retryable", err: utilerrors.NewAggregate([]error{ config.SharedConfigLoadError{}, config.SharedConfigLoadError{}, @@ -53,7 +53,7 @@ func TestIsErrorRetryable(t *testing.T) { expected: false, }, { - name: "When aggregate has mixed errors it should be retryable", + name: "When aggregate has mixed errors, it should be retryable", err: utilerrors.NewAggregate([]error{ config.SharedConfigLoadError{}, errors.New("some other error"), @@ -61,7 +61,7 @@ func TestIsErrorRetryable(t *testing.T) { expected: true, }, { - name: "When wrapped aggregate has single generic error it should be retryable", + name: "When wrapped aggregate has single generic error, it should be retryable", err: fmt.Errorf("operation failed: %w", utilerrors.NewAggregate([]error{errors.New("transient")})), expected: true, }, diff --git a/cmd/infra/azure/destroy_test.go b/cmd/infra/azure/destroy_test.go index 37801c4f5d10..3c123634169f 100644 --- a/cmd/infra/azure/destroy_test.go +++ b/cmd/infra/azure/destroy_test.go @@ -75,62 +75,62 @@ func TestGetAPIVersionForResourceType(t *testing.T) { expected string }{ { - name: "When resource type is public IP addresses it should return correct API version", + name: "When resource type is public IP addresses, it should return correct API version", resourceType: "Microsoft.Network/publicIPAddresses", expected: "2023-11-01", }, { - name: "When resource type is load balancers it should return correct API version", + name: "When resource type is load balancers, it should return correct API version", resourceType: "Microsoft.Network/loadBalancers", expected: "2023-11-01", }, { - name: "When resource type is network interfaces it should return correct API version", + name: "When resource type is network interfaces, it should return correct API version", resourceType: "Microsoft.Network/networkInterfaces", expected: "2023-11-01", }, { - name: "When resource type is network security groups it should return correct API version", + name: "When resource type is network security groups, it should return correct API version", resourceType: "Microsoft.Network/networkSecurityGroups", expected: "2023-11-01", }, { - name: "When resource type is virtual networks it should return correct API version", + name: "When resource type is virtual networks, it should return correct API version", resourceType: "Microsoft.Network/virtualNetworks", expected: "2023-11-01", }, { - name: "When resource type is private DNS zones it should return correct API version", + name: "When resource type is private DNS zones, it should return correct API version", resourceType: "Microsoft.Network/privateDnsZones", expected: "2020-06-01", }, { - name: "When resource type is private DNS zone virtual network links it should return correct API version", + name: "When resource type is private DNS zone virtual network links, it should return correct API version", resourceType: "Microsoft.Network/privateDnsZones/virtualNetworkLinks", expected: "2020-06-01", }, { - name: "When resource type is virtual machines it should return correct API version", + name: "When resource type is virtual machines, it should return correct API version", resourceType: "Microsoft.Compute/virtualMachines", expected: "2024-03-01", }, { - name: "When resource type is disks it should return correct API version", + name: "When resource type is disks, it should return correct API version", resourceType: "Microsoft.Compute/disks", expected: "2023-10-02", }, { - name: "When resource type is storage accounts it should return correct API version", + name: "When resource type is storage accounts, it should return correct API version", resourceType: "Microsoft.Storage/storageAccounts", expected: "2023-01-01", }, { - name: "When resource type is user assigned identities it should return correct API version", + name: "When resource type is user assigned identities, it should return correct API version", resourceType: "Microsoft.ManagedIdentity/userAssignedIdentities", expected: "2023-01-31", }, { - name: "When resource type is unknown it should return default API version", + name: "When resource type is unknown, it should return default API version", resourceType: "Microsoft.Unknown/someResource", expected: "2021-04-01", }, @@ -153,7 +153,7 @@ func TestGetResourceGroupName(t *testing.T) { expected string }{ { - name: "When custom resource group name is provided it should use that name", + name: "When custom resource group name is provided, it should use that name", opts: DestroyInfraOptions{ Name: "test-cluster", InfraID: "abc123", @@ -162,7 +162,7 @@ func TestGetResourceGroupName(t *testing.T) { expected: "custom-rg-name", }, { - name: "When no resource group name is provided it should use default format", + name: "When no resource group name is provided, it should use default format", opts: DestroyInfraOptions{ Name: "test-cluster", InfraID: "abc123", @@ -171,7 +171,7 @@ func TestGetResourceGroupName(t *testing.T) { expected: "test-cluster-abc123", }, { - name: "When empty resource group name is provided it should use default format", + name: "When empty resource group name is provided, it should use default format", opts: DestroyInfraOptions{ Name: "my-cluster", InfraID: "xyz789", diff --git a/cmd/infra/azure/networking_test.go b/cmd/infra/azure/networking_test.go index c8037bba4885..b6bb07a092e6 100644 --- a/cmd/infra/azure/networking_test.go +++ b/cmd/infra/azure/networking_test.go @@ -176,50 +176,50 @@ func TestIsAzureConflictError(t *testing.T) { err error expected bool }{ - "When the error is a 409 ConflictingConcurrentWriteNotAllowed it should be retryable": { + "When the error is a 409 ConflictingConcurrentWriteNotAllowed, it should be retryable": { err: &azcore.ResponseError{ StatusCode: http.StatusConflict, ErrorCode: "ConflictingConcurrentWriteNotAllowed", }, expected: true, }, - "When the error is a 409 with different error code it should be retryable": { + "When the error is a 409 with different error code, it should be retryable": { err: &azcore.ResponseError{ StatusCode: http.StatusConflict, ErrorCode: "AnotherConflict", }, expected: true, }, - "When the error is a 429 too many requests it should not be retryable": { + "When the error is a 429 too many requests, it should not be retryable": { err: &azcore.ResponseError{ StatusCode: http.StatusTooManyRequests, }, expected: false, }, - "When the error is a 500 internal server error it should not be retryable": { + "When the error is a 500 internal server error, it should not be retryable": { err: &azcore.ResponseError{ StatusCode: http.StatusInternalServerError, }, expected: false, }, - "When the error is a 400 bad request it should not be retryable": { + "When the error is a 400 bad request, it should not be retryable": { err: &azcore.ResponseError{ StatusCode: http.StatusBadRequest, }, expected: false, }, - "When the error is not an Azure ResponseError it should not be retryable": { + "When the error is not an Azure ResponseError, it should not be retryable": { err: fmt.Errorf("some random error"), expected: false, }, - "When the error wraps a 409 Azure ResponseError it should be retryable": { + "When the error wraps a 409 Azure ResponseError, it should be retryable": { err: fmt.Errorf("wrapped: %w", &azcore.ResponseError{ StatusCode: http.StatusConflict, ErrorCode: "ConflictingConcurrentWriteNotAllowed", }), expected: true, }, - "When the error is nil it should not be retryable": { + "When the error is nil, it should not be retryable": { err: nil, expected: false, }, diff --git a/cmd/infra/azure/rbac_test.go b/cmd/infra/azure/rbac_test.go index d78fb514f42d..49d8bc7285c0 100644 --- a/cmd/infra/azure/rbac_test.go +++ b/cmd/infra/azure/rbac_test.go @@ -121,7 +121,7 @@ func TestAssignRole(t *testing.T) { expectErr bool }{ // --- LIST behaviors --- - "When LIST finds matching assignment it should skip creation": { + "When LIST finds matching assignment, it should skip creation": { listItems: []*azureauth.RoleAssignment{ { Properties: &azureauth.RoleAssignmentProperties{ @@ -135,7 +135,7 @@ func TestAssignRole(t *testing.T) { expectCreate: false, expectDelete: false, }, - "When LIST returns items with nil properties it should skip them and fall through to GET": { + "When LIST returns items with nil properties, it should skip them and fall through to GET": { listItems: []*azureauth.RoleAssignment{ {Properties: nil}, {Properties: &azureauth.RoleAssignmentProperties{ @@ -148,13 +148,13 @@ func TestAssignRole(t *testing.T) { expectCreate: true, expectDelete: false, }, - "When LIST page returns error it should return error": { + "When LIST page returns error, it should return error": { listErr: internalServerError(), expectErr: true, }, // --- GET behaviors --- - "When GET finds assignment with matching principal and role it should skip creation": { + "When GET finds assignment with matching principal and role, it should skip creation": { getResponse: &azureauth.RoleAssignmentsClientGetResponse{ RoleAssignment: azureauth.RoleAssignment{ Properties: &azureauth.RoleAssignmentProperties{ @@ -166,7 +166,7 @@ func TestAssignRole(t *testing.T) { expectCreate: false, expectDelete: false, }, - "When GET finds assignment with different principal it should delete stale and create new": { + "When GET finds assignment with different principal, it should delete stale and create new": { getResponse: &azureauth.RoleAssignmentsClientGetResponse{ RoleAssignment: azureauth.RoleAssignment{ Properties: &azureauth.RoleAssignmentProperties{ @@ -177,7 +177,7 @@ func TestAssignRole(t *testing.T) { expectCreate: true, expectDelete: true, }, - "When GET finds assignment with nil PrincipalID it should delete stale and create new": { + "When GET finds assignment with nil PrincipalID, it should delete stale and create new": { getResponse: &azureauth.RoleAssignmentsClientGetResponse{ RoleAssignment: azureauth.RoleAssignment{ Properties: &azureauth.RoleAssignmentProperties{ @@ -188,7 +188,7 @@ func TestAssignRole(t *testing.T) { expectCreate: true, expectDelete: true, }, - "When GET finds assignment with nil Properties it should delete stale and create new": { + "When GET finds assignment with nil Properties, it should delete stale and create new": { getResponse: &azureauth.RoleAssignmentsClientGetResponse{ RoleAssignment: azureauth.RoleAssignment{ Properties: nil, @@ -197,7 +197,7 @@ func TestAssignRole(t *testing.T) { expectCreate: true, expectDelete: true, }, - "When GET finds stale assignment but delete fails it should return error": { + "When GET finds stale assignment but delete fails, it should return error": { getResponse: &azureauth.RoleAssignmentsClientGetResponse{ RoleAssignment: azureauth.RoleAssignment{ Properties: &azureauth.RoleAssignmentProperties{ @@ -210,34 +210,34 @@ func TestAssignRole(t *testing.T) { expectCreate: false, expectErr: true, }, - "When GET returns 404 it should create new assignment": { + "When GET returns 404, it should create new assignment": { getErr: notFoundError(), expectCreate: true, expectDelete: false, }, - "When GET returns 403 it should fall through to create": { + "When GET returns 403, it should fall through to create": { getErr: forbiddenError(), expectCreate: true, expectDelete: false, }, - "When GET returns unexpected API error it should return error": { + "When GET returns unexpected API error, it should return error": { getErr: internalServerError(), expectErr: true, }, - "When GET returns non-API error it should return error": { + "When GET returns non-API error, it should return error": { getErr: fmt.Errorf("network timeout"), expectErr: true, }, // --- Create behaviors --- - "When create returns 409 conflict it should succeed": { + "When create returns 409 conflict, it should succeed": { getErr: notFoundError(), createErr: conflictError(), expectCreate: true, expectDelete: false, expectErr: false, }, - "When create returns unexpected error it should return error": { + "When create returns unexpected error, it should return error": { getErr: notFoundError(), createErr: internalServerError(), expectCreate: true, @@ -357,15 +357,15 @@ func TestDeleteRoleAssignmentByName(t *testing.T) { deleteErr error expectError bool }{ - "When assignment exists it should delete successfully": { + "When assignment exists, it should delete successfully": { deleteErr: nil, expectError: false, }, - "When assignment does not exist it should skip gracefully": { + "When assignment does not exist, it should skip gracefully": { deleteErr: notFoundError(), expectError: false, }, - "When delete fails with unexpected error it should return error": { + "When delete fails with unexpected error, it should return error": { deleteErr: forbiddenError(), expectError: true, }, diff --git a/cmd/infra/gcp/create_infra_test.go b/cmd/infra/gcp/create_infra_test.go index 909e958d7f27..1b60b28ff666 100644 --- a/cmd/infra/gcp/create_infra_test.go +++ b/cmd/infra/gcp/create_infra_test.go @@ -90,7 +90,7 @@ func TestCreateInfraOptionsOutput(t *testing.T) { validateJSON bool }{ { - name: "When output file is specified it should write JSON to file", + name: "When output file is specified, it should write JSON to file", outputFile: "output.json", result: &CreateInfraOutput{ Region: "us-central1", @@ -107,7 +107,7 @@ func TestCreateInfraOptionsOutput(t *testing.T) { validateJSON: true, }, { - name: "When output file is in invalid directory it should return error", + name: "When output file is in invalid directory, it should return error", outputFile: "/nonexistent/directory/output.json", result: &CreateInfraOutput{ ProjectID: "test-project", @@ -115,7 +115,7 @@ func TestCreateInfraOptionsOutput(t *testing.T) { expectedError: "cannot create output file", }, { - name: "When output file is empty string it should write to stdout without error", + name: "When output file is empty string, it should write to stdout without error", outputFile: "", result: &CreateInfraOutput{ Region: "us-central1", diff --git a/cmd/infra/gcp/destroy_infra_test.go b/cmd/infra/gcp/destroy_infra_test.go index c0f9bdcab021..386b1ee1360d 100644 --- a/cmd/infra/gcp/destroy_infra_test.go +++ b/cmd/infra/gcp/destroy_infra_test.go @@ -78,24 +78,24 @@ func TestFormatOperationErrors(t *testing.T) { expected string }{ { - name: "When errors is nil it should return unknown error", + name: "When errors is nil, it should return unknown error", errors: nil, expected: "unknown error", }, { - name: "When errors is empty it should return unknown error", + name: "When errors is empty, it should return unknown error", errors: []*compute.OperationErrorErrors{}, expected: "unknown error", }, { - name: "When single error it should format correctly", + name: "When single error, it should format correctly", errors: []*compute.OperationErrorErrors{ {Code: "RESOURCE_IN_USE", Message: "Resource is in use"}, }, expected: "[RESOURCE_IN_USE: Resource is in use]", }, { - name: "When multiple errors it should format all", + name: "When multiple errors, it should format all", errors: []*compute.OperationErrorErrors{ {Code: "ERROR_1", Message: "First error"}, {Code: "ERROR_2", Message: "Second error"}, diff --git a/cmd/infra/gcp/iam_test.go b/cmd/infra/gcp/iam_test.go index 277e17ad8bfa..e2328be08a68 100644 --- a/cmd/infra/gcp/iam_test.go +++ b/cmd/infra/gcp/iam_test.go @@ -28,25 +28,25 @@ func TestIAMManagerFormatServiceAccountMethods(t *testing.T) { expected string }{ { - name: "When formatServiceAccountID is called it should return correct ID", + name: "When formatServiceAccountID is called, it should return correct ID", method: manager.formatServiceAccountID, arg: "nodepool-mgmt", expected: "test-infra-nodepool-mgmt", }, { - name: "When formatServiceAccountEmail is called it should return correct email", + name: "When formatServiceAccountEmail is called, it should return correct email", method: manager.formatServiceAccountEmail, arg: "nodepool-mgmt", expected: "test-infra-nodepool-mgmt@test-project.iam.gserviceaccount.com", }, { - name: "When formatServiceAccountResource is called it should return correct resource path", + name: "When formatServiceAccountResource is called, it should return correct resource path", method: manager.formatServiceAccountResource, arg: "test-infra-nodepool-mgmt@test-project.iam.gserviceaccount.com", expected: "projects/test-project/serviceAccounts/test-infra-nodepool-mgmt@test-project.iam.gserviceaccount.com", }, { - name: "When formatServiceAccountMember is called it should return correct member format", + name: "When formatServiceAccountMember is called, it should return correct member format", method: manager.formatServiceAccountMember, arg: "test-infra-nodepool-mgmt@test-project.iam.gserviceaccount.com", expected: "serviceAccount:test-infra-nodepool-mgmt@test-project.iam.gserviceaccount.com", @@ -75,13 +75,13 @@ func TestIAMManagerFormatWIFPrincipal(t *testing.T) { expected string }{ { - name: "When formatWIFPrincipal is called with kube-system namespace it should return correct principal", + name: "When formatWIFPrincipal is called with kube-system namespace, it should return correct principal", namespace: "kube-system", saName: "control-plane-operator", expected: "principal://iam.googleapis.com/projects/123456789/locations/global/workloadIdentityPools/test-infra-wi-pool/subject/system:serviceaccount:kube-system:control-plane-operator", }, { - name: "When formatWIFPrincipal is called with custom namespace it should return correct principal", + name: "When formatWIFPrincipal is called with custom namespace, it should return correct principal", namespace: "openshift-cloud-controller-manager", saName: "cloud-controller-manager", expected: "principal://iam.googleapis.com/projects/123456789/locations/global/workloadIdentityPools/test-infra-wi-pool/subject/system:serviceaccount:openshift-cloud-controller-manager:cloud-controller-manager", @@ -104,13 +104,13 @@ func TestIAMManagerFormatIssuerUri(t *testing.T) { expected string }{ { - name: "When custom OIDC issuer URL is set it should return the custom URL", + name: "When custom OIDC issuer URL is set, it should return the custom URL", oidcIssuerURL: "https://custom-oidc.example.com", infraID: "test-infra", expected: "https://custom-oidc.example.com", }, { - name: "When no custom OIDC issuer URL is set it should derive from infraID", + name: "When no custom OIDC issuer URL is set, it should derive from infraID", oidcIssuerURL: "", infraID: "test-infra", expected: "https://hypershift-test-infra-oidc", @@ -397,37 +397,37 @@ func TestIsTransientIAMError(t *testing.T) { expected bool }{ { - name: "When error is nil it should return false", + name: "When error is nil, it should return false", err: nil, expected: false, }, { - name: "When error is a 429 rate limit error it should return true", + name: "When error is a 429 rate limit error, it should return true", err: &googleapi.Error{Code: 429, Message: "A quota has been reached"}, expected: true, }, { - name: "When error is a 404 not found error it should return true", + name: "When error is a 404 not found error, it should return true", err: &googleapi.Error{Code: 404, Message: "Not found"}, expected: true, }, { - name: "When error is a 403 permission error it should return true", + name: "When error is a 403 permission error, it should return true", err: &googleapi.Error{Code: 403, Message: "Permission denied"}, expected: true, }, { - name: "When error is a 403 non-permission error it should return false", + name: "When error is a 403 non-permission error, it should return false", err: &googleapi.Error{Code: 403, Message: "Forbidden"}, expected: false, }, { - name: "When error is a 500 server error it should return false", + name: "When error is a 500 server error, it should return false", err: &googleapi.Error{Code: 500, Message: "Internal server error"}, expected: false, }, { - name: "When error is a non-googleapi error it should return false", + name: "When error is a non-googleapi error, it should return false", err: fmt.Errorf("some other error"), expected: false, }, @@ -448,7 +448,7 @@ func TestIsAlreadyExistsError(t *testing.T) { expected bool }{ { - name: "When error is nil it should return false", + name: "When error is nil, it should return false", err: nil, expected: false, }, @@ -536,55 +536,55 @@ func TestCompareJWKS(t *testing.T) { expected bool }{ { - name: "When both are empty it should return true", + name: "When both are empty, it should return true", jwks1: "", jwks2: "", expected: true, }, { - name: "When both are whitespace-only it should return true", + name: "When both are whitespace-only, it should return true", jwks1: " ", jwks2: " \t ", expected: true, }, { - name: "When first is empty and second is not it should return false", + name: "When first is empty and second is not, it should return false", jwks1: "", jwks2: `{"keys": []}`, expected: false, }, { - name: "When first is non-empty and second is empty it should return false", + name: "When first is non-empty and second is empty, it should return false", jwks1: `{"keys": []}`, jwks2: "", expected: false, }, { - name: "When both contain identical JSON it should return true", + name: "When both contain identical JSON, it should return true", jwks1: `{"keys": [{"kty": "RSA"}]}`, jwks2: `{"keys": [{"kty": "RSA"}]}`, expected: true, }, { - name: "When both contain semantically equal JSON with different formatting it should return true", + name: "When both contain semantically equal JSON with different formatting, it should return true", jwks1: `{"keys":[{"kty":"RSA"}]}`, jwks2: `{ "keys" : [ { "kty" : "RSA" } ] }`, expected: true, }, { - name: "When JSON content differs it should return false", + name: "When JSON content differs, it should return false", jwks1: `{"keys": [{"kty": "RSA"}]}`, jwks2: `{"keys": [{"kty": "EC"}]}`, expected: false, }, { - name: "When first contains invalid JSON it should return false", + name: "When first contains invalid JSON, it should return false", jwks1: `{not json}`, jwks2: `{"keys": []}`, expected: false, }, { - name: "When second contains invalid JSON it should return false", + name: "When second contains invalid JSON, it should return false", jwks1: `{"keys": []}`, jwks2: `{not json}`, expected: false, diff --git a/cmd/infra/powervs/create_test.go b/cmd/infra/powervs/create_test.go index 3a7eef5768ce..ed3e1a2cad39 100644 --- a/cmd/infra/powervs/create_test.go +++ b/cmd/infra/powervs/create_test.go @@ -22,11 +22,11 @@ func TestUseExistingDHCP(t *testing.T) { input models.DHCPServers expected expected }{ - "DHCPServerDetail returned with no error": { + "When one DHCP server exists, it should return its details without an error": { input: models.DHCPServers{{ID: &id1}}, expected: expected{dhcpServerID: id1, err: nil, errExpected: false}, }, - "Error expected when more than one DHCPServer exist": { + "When more than one DHCP server exists, it should return an error": { input: models.DHCPServers{{ID: &id1}, {ID: &id2}}, expected: expected{"", dhcpServerLimitExceeds(2), true}, }, diff --git a/cmd/infra/powervs/service_id_test.go b/cmd/infra/powervs/service_id_test.go index 07b9408ca680..4f46685b4342 100644 --- a/cmd/infra/powervs/service_id_test.go +++ b/cmd/infra/powervs/service_id_test.go @@ -22,7 +22,7 @@ func TestCreateServiceIDClient(t *testing.T) { input args errExpected bool }{ - "Create client ID with proper CR YAML": { + "When the CR YAML is valid, it should create the client ID": { input: args{ name: "name", apiKey: "apiKey", @@ -34,7 +34,7 @@ func TestCreateServiceIDClient(t *testing.T) { }, errExpected: false, }, - "Create client ID with invalid CR YAML": { + "When the CR YAML is invalid, it should return an error": { input: args{ name: "name", apiKey: "apiKey", diff --git a/cmd/install/install_test.go b/cmd/install/install_test.go index 2b8075dc0abb..44b96b26338e 100644 --- a/cmd/install/install_test.go +++ b/cmd/install/install_test.go @@ -45,13 +45,13 @@ func TestOptions_Validate(t *testing.T) { inputOptions Options expectError bool }{ - "when aws private platform without private creds or secret reference and region it errors": { + "When AWS private platform has no credentials or region, it should return an error": { inputOptions: Options{ PrivatePlatform: string(hyperv1.AWSPlatform), }, expectError: true, }, - "when aws private platform with private creds and region there is no error": { + "When AWS private platform has private credentials and region, it should succeed": { inputOptions: Options{ PrivatePlatform: string(hyperv1.AWSPlatform), AWSPrivateCreds: "/path/to/credentials", @@ -59,7 +59,7 @@ func TestOptions_Validate(t *testing.T) { }, expectError: false, }, - "when aws private platform with secret and region there is no error": { + "When AWS private platform has a secret and region, it should succeed": { inputOptions: Options{ PrivatePlatform: string(hyperv1.AWSPlatform), AWSPrivateCredentialsSecret: "my-secret", @@ -67,7 +67,7 @@ func TestOptions_Validate(t *testing.T) { }, expectError: false, }, - "When AWS private platform with role ARN and region it should succeed": { + "When AWS private platform with role ARN and region, it should succeed": { inputOptions: Options{ PrivatePlatform: string(hyperv1.AWSPlatform), AWSPrivateRoleARN: "arn:aws:iam::123456789012:role/op-ec2", @@ -76,7 +76,7 @@ func TestOptions_Validate(t *testing.T) { }, expectError: false, }, - "When AWS private platform with role ARN and creds file it should error": { + "When AWS private platform with role ARN and creds file, it should error": { inputOptions: Options{ PrivatePlatform: string(hyperv1.AWSPlatform), AWSPrivateRoleARN: "arn:aws:iam::123456789012:role/op-ec2", @@ -86,7 +86,7 @@ func TestOptions_Validate(t *testing.T) { }, expectError: true, }, - "When AWS private platform with both creds file and secret it should error": { + "When AWS private platform with both creds file and secret, it should error": { inputOptions: Options{ PrivatePlatform: string(hyperv1.AWSPlatform), AWSPrivateCreds: "/path/to/credentials", @@ -95,7 +95,7 @@ func TestOptions_Validate(t *testing.T) { }, expectError: true, }, - "When AWS private platform with role ARN and no region it should error": { + "When AWS private platform with role ARN and no region, it should error": { inputOptions: Options{ PrivatePlatform: string(hyperv1.AWSPlatform), AWSPrivateRoleARN: "arn:aws:iam::123456789012:role/op-ec2", @@ -103,7 +103,7 @@ func TestOptions_Validate(t *testing.T) { }, expectError: true, }, - "When role ARN is set with invalid credential source it should error": { + "When role ARN is set with invalid credential source, it should error": { inputOptions: Options{ PrivatePlatform: string(hyperv1.AWSPlatform), AWSPrivateRoleARN: "arn:aws:iam::123456789012:role/op-ec2", @@ -112,7 +112,7 @@ func TestOptions_Validate(t *testing.T) { }, expectError: true, }, - "When role ARN is set with web-identity credential source it should succeed": { + "When role ARN is set with web-identity credential source, it should succeed": { inputOptions: Options{ PrivatePlatform: string(hyperv1.AWSPlatform), AWSPrivateRoleARN: "arn:aws:iam::123456789012:role/op-ec2", @@ -121,7 +121,7 @@ func TestOptions_Validate(t *testing.T) { }, expectError: false, }, - "When role ARN is set with ec2-instance-metadata credential source it should succeed": { + "When role ARN is set with ec2-instance-metadata credential source, it should succeed": { inputOptions: Options{ PrivatePlatform: string(hyperv1.AWSPlatform), AWSPrivateRoleARN: "arn:aws:iam::123456789012:role/op-ec2", @@ -130,30 +130,30 @@ func TestOptions_Validate(t *testing.T) { }, expectError: false, }, - "when empty private platform is specified it errors": { + "When private platform is empty, it should return an error": { inputOptions: Options{}, expectError: true, }, - "when partially specified oauth creds used (OIDCStorageProviderS3Credentials) it errors": { + "When only OIDCStorageProviderS3Credentials is provided, it should return an error": { inputOptions: Options{ OIDCStorageProviderS3Credentials: "mycreds", }, expectError: true, }, - "when partially specified oauth creds used (OIDCStorageProviderS3CredentialsSecret) it errors": { + "When only OIDCStorageProviderS3CredentialsSecret is provided, it should return an error": { inputOptions: Options{ OIDCStorageProviderS3CredentialsSecret: "mysecret", }, expectError: true, }, - "when external-dns provider is set without creds it errors": { + "When external-dns provider is set without credentials, it should return an error": { inputOptions: Options{ ExternalDNSProvider: "aws", ExternalDNSDomainFilter: "test.com", }, expectError: true, }, - "when external-dns provider is set with both creds methods it errors": { + "When external-dns provider is set with both credential methods, it should return an error": { inputOptions: Options{ ExternalDNSProvider: "aws", ExternalDNSCredentials: "/path/to/credentials", @@ -162,28 +162,28 @@ func TestOptions_Validate(t *testing.T) { }, expectError: true, }, - "when external-dns provider is set without domain filter it errors": { + "When external-dns provider is set without a domain filter, it should return an error": { inputOptions: Options{ ExternalDNSProvider: "aws", ExternalDNSCredentials: "/path/to/credentials", }, expectError: true, }, - "when GCP private platform with only gcp-project it errors": { + "When GCP private platform has only gcp-project, it should return an error": { inputOptions: Options{ PrivatePlatform: string(hyperv1.GCPPlatform), GCPProject: "my-project", }, expectError: true, }, - "when GCP private platform with only gcp-region it errors": { + "When GCP private platform has only gcp-region, it should return an error": { inputOptions: Options{ PrivatePlatform: string(hyperv1.GCPPlatform), GCPRegion: "us-central1", }, expectError: true, }, - "when GCP private platform with both gcp-project and gcp-region it succeeds": { + "When GCP private platform has gcp-project and gcp-region, it should succeed": { inputOptions: Options{ PrivatePlatform: string(hyperv1.GCPPlatform), GCPProject: "my-project", @@ -191,13 +191,13 @@ func TestOptions_Validate(t *testing.T) { }, expectError: false, }, - "when GCP private platform without gcp-project and gcp-region it succeeds": { + "When GCP private platform has no gcp-project or gcp-region, it should succeed": { inputOptions: Options{ PrivatePlatform: string(hyperv1.GCPPlatform), }, expectError: false, }, - "when external-dns GCP provider is set without credentials it succeeds (Workload Identity)": { + "When external-dns GCP provider is set without credentials, it should use Workload Identity": { inputOptions: Options{ PrivatePlatform: string(hyperv1.GCPPlatform), ExternalDNSProvider: "google", @@ -206,7 +206,7 @@ func TestOptions_Validate(t *testing.T) { }, expectError: false, }, - "when external-dns GCP provider is set with credentials it succeeds": { + "When external-dns GCP provider is set with credentials, it should succeed": { inputOptions: Options{ PrivatePlatform: string(hyperv1.GCPPlatform), ExternalDNSProvider: "google", @@ -216,7 +216,7 @@ func TestOptions_Validate(t *testing.T) { }, expectError: false, }, - "when external-dns GCP provider is set without google-project it succeeds": { + "When external-dns GCP provider is set without google-project, it should succeed": { inputOptions: Options{ PrivatePlatform: string(hyperv1.GCPPlatform), ExternalDNSProvider: "google", @@ -302,7 +302,7 @@ func TestOptions_Validate(t *testing.T) { }, expectError: true, }, - "when all data specified there is no error": { + "When all data is specified, it should succeed": { inputOptions: Options{ PrivatePlatform: string(hyperv1.NonePlatform), OIDCStorageProviderS3CredentialsSecret: "mysecret", @@ -312,27 +312,27 @@ func TestOptions_Validate(t *testing.T) { }, expectError: false, }, - "when image pull policy is not set there is no error": { + "When image pull policy is not set, it should succeed": { inputOptions: Options{ PrivatePlatform: string(hyperv1.NonePlatform), }, expectError: false, }, - "when valid image pull policy is set there is no error": { + "When a valid image pull policy is set, it should succeed": { inputOptions: Options{ PrivatePlatform: string(hyperv1.NonePlatform), ImagePullPolicy: "Always", }, expectError: false, }, - "when invalid image pull policy is set it errors": { + "When an invalid image pull policy is set, it should return an error": { inputOptions: Options{ PrivatePlatform: string(hyperv1.NonePlatform), ImagePullPolicy: "InvalidPolicy", }, expectError: true, }, - "When Azure private platform with managed identity and creds file it should error": { + "When Azure private platform with managed identity and creds file, it should error": { inputOptions: Options{ PrivatePlatform: string(hyperv1.AzurePlatform), AzurePrivateCreds: "/path/to/credentials", @@ -341,7 +341,7 @@ func TestOptions_Validate(t *testing.T) { }, expectError: true, }, - "When Azure private platform with managed identity and secret it should error": { + "When Azure private platform with managed identity and secret, it should error": { inputOptions: Options{ PrivatePlatform: string(hyperv1.AzurePlatform), AzurePrivateCredentialsSecret: "my-secret", @@ -350,14 +350,14 @@ func TestOptions_Validate(t *testing.T) { }, expectError: true, }, - "When Azure private platform with managed identity but no subscription ID it should error": { + "When Azure private platform with managed identity but no subscription ID, it should error": { inputOptions: Options{ PrivatePlatform: string(hyperv1.AzurePlatform), AzurePLSManagedIdentityClientID: "client-id", }, expectError: true, }, - "When Azure private platform with managed identity and subscription ID it should succeed": { + "When Azure private platform with managed identity and subscription ID, it should succeed": { inputOptions: Options{ PrivatePlatform: string(hyperv1.AzurePlatform), AzurePLSManagedIdentityClientID: "client-id", @@ -366,7 +366,7 @@ func TestOptions_Validate(t *testing.T) { }, expectError: false, }, - "When Azure private platform with creds file it should succeed": { + "When Azure private platform with creds file, it should succeed": { inputOptions: Options{ PrivatePlatform: string(hyperv1.AzurePlatform), AzurePrivateCreds: "/path/to/credentials", @@ -374,7 +374,7 @@ func TestOptions_Validate(t *testing.T) { }, expectError: false, }, - "when scale-from-zero provider is missing but creds provided it errors": { + "When scale-from-zero credentials are provided without a provider, it should return an error": { inputOptions: Options{ PrivatePlatform: string(hyperv1.AWSPlatform), AWSPrivateCreds: "/dev/null", @@ -383,7 +383,7 @@ func TestOptions_Validate(t *testing.T) { }, expectError: true, }, - "when scale-from-zero provider is invalid it errors": { + "When scale-from-zero provider is invalid, it should return an error": { inputOptions: Options{ PrivatePlatform: string(hyperv1.AWSPlatform), AWSPrivateCreds: "/dev/null", @@ -393,7 +393,7 @@ func TestOptions_Validate(t *testing.T) { }, expectError: true, }, - "when scale-from-zero both creds and secret provided it errors": { + "When scale-from-zero credentials and secret are both provided, it should return an error": { inputOptions: Options{ PrivatePlatform: string(hyperv1.AWSPlatform), AWSPrivateCreds: "/dev/null", @@ -404,7 +404,7 @@ func TestOptions_Validate(t *testing.T) { }, expectError: true, }, - "when scale-from-zero provider is aws with creds file there is no error": { + "When scale-from-zero provider is AWS with a credentials file, it should succeed": { inputOptions: Options{ PrivatePlatform: string(hyperv1.AWSPlatform), AWSPrivateCreds: "/dev/null", @@ -414,7 +414,7 @@ func TestOptions_Validate(t *testing.T) { }, expectError: false, }, - "when scale-from-zero provider is aws with secret reference there is no error": { + "When scale-from-zero provider is AWS with a secret reference, it should succeed": { inputOptions: Options{ PrivatePlatform: string(hyperv1.AWSPlatform), AWSPrivateCreds: "/dev/null", @@ -425,35 +425,35 @@ func TestOptions_Validate(t *testing.T) { }, expectError: false, }, - "when install-scope is all it should not error": { + "When install-scope is all, it should not error": { inputOptions: Options{ PrivatePlatform: string(hyperv1.NonePlatform), InstallScope: string(OutputAll), }, expectError: false, }, - "when install-scope is crds it should not error": { + "When install-scope is crds, it should not error": { inputOptions: Options{ PrivatePlatform: string(hyperv1.NonePlatform), InstallScope: string(OutputCRDs), }, expectError: false, }, - "when install-scope is resources it should not error": { + "When install-scope is resources, it should not error": { inputOptions: Options{ PrivatePlatform: string(hyperv1.NonePlatform), InstallScope: string(OutputResources), }, expectError: false, }, - "when install-scope is invalid it should error": { + "When install-scope is invalid, it should error": { inputOptions: Options{ PrivatePlatform: string(hyperv1.NonePlatform), InstallScope: "bogus", }, expectError: true, }, - "when install-scope is crds with wait-until-available it should error": { + "When install-scope is crds with wait-until-available, it should error": { inputOptions: Options{ PrivatePlatform: string(hyperv1.NonePlatform), InstallScope: string(OutputCRDs), @@ -583,21 +583,21 @@ func TestCRDIncludeFilter(t *testing.T) { expect: false, }, { - name: "When PlatformsToInstall includes aws, AWS provider CRDs should be included", + name: "When PlatformsToInstall includes aws, it should include AWS provider CRDs", opts: Options{PlatformsToInstall: []string{"aws"}}, path: "cluster-api-provider-aws/infrastructure.cluster.x-k8s.io_awsclusters.yaml", crd: defaultCRD(), expect: true, }, { - name: "When PlatformsToInstall includes only azure, AWS provider CRDs should be excluded", + name: "When PlatformsToInstall includes only azure, it should exclude AWS provider CRDs", opts: Options{PlatformsToInstall: []string{"azure"}}, path: "cluster-api-provider-aws/infrastructure.cluster.x-k8s.io_awsclusters.yaml", crd: defaultCRD(), expect: false, }, { - name: "When PlatformsToInstall is empty, all platform CRDs should be included", + name: "When PlatformsToInstall is empty, it should include all platform CRDs", path: "cluster-api-provider-aws/infrastructure.cluster.x-k8s.io_awsclusters.yaml", crd: defaultCRD(), expect: true, @@ -647,19 +647,19 @@ func TestSetupCRDs(t *testing.T) { inputOptions: Options{}, }, { - name: "When PlatformOptions is set to Azure only Azure CAPI CRDs should be present", + name: "When PlatformOptions is set to Azure, it should include only Azure CAPI CRDs", inputOptions: Options{ PlatformsToInstall: []string{"azure"}, }, }, { - name: "When PlatformOptions is set to AWS only AWS CAPI CRDs should be present", + name: "When PlatformOptions is set to AWS, it should include only AWS CAPI CRDs", inputOptions: Options{ PlatformsToInstall: []string{"aws"}, }, }, { - name: "When PlatformOptions is set to AWS,Azure only AWS & Azure CAPI CRDs should be present", + name: "When PlatformOptions is set to AWS,Azure, it should include only AWS When PlatformOptions is set to AWS,Azure, only AWS & Azure CAPI CRDs it should be present Azure CAPI CRDs", inputOptions: Options{ PlatformsToInstall: []string{"aws", "azure"}, }, @@ -2476,7 +2476,7 @@ func TestLoadOperatorRolesFile(t *testing.T) { expectError bool validate func(*GomegaWithT, Options) }{ - "When no roles file is specified it should be a no-op": { + "When no roles file is specified, it should be a no-op": { setup: func(t *testing.T) Options { return Options{} }, @@ -2486,7 +2486,7 @@ func TestLoadOperatorRolesFile(t *testing.T) { g.Expect(o.ExternalDNSRoleARN).To(BeEmpty()) }, }, - "When a valid roles file is specified it should populate role ARN fields": { + "When a valid roles file is specified, it should populate role ARN fields": { setup: func(t *testing.T) Options { roles := aws.CreateOperatorRolesOutput{ OperatorEC2RoleARN: "arn:aws:iam::123456789012:role/op-ec2", @@ -2509,7 +2509,7 @@ func TestLoadOperatorRolesFile(t *testing.T) { g.Expect(o.ExternalDNSRoleARN).To(Equal("arn:aws:iam::123456789012:role/ext-dns")) }, }, - "When roles file conflicts with --aws-private-role-arn it should error": { + "When roles file conflicts with --aws-private-role-arn, it should error": { setup: func(t *testing.T) Options { f := filepath.Join(t.TempDir(), "roles.json") if err := os.WriteFile(f, []byte(`{}`), 0644); err != nil { @@ -2522,7 +2522,7 @@ func TestLoadOperatorRolesFile(t *testing.T) { }, expectError: true, }, - "When roles file conflicts with --oidc-storage-provider-s3-role-arn it should error": { + "When roles file conflicts with --oidc-storage-provider-s3-role-arn, it should error": { setup: func(t *testing.T) Options { f := filepath.Join(t.TempDir(), "roles.json") if err := os.WriteFile(f, []byte(`{}`), 0644); err != nil { @@ -2535,7 +2535,7 @@ func TestLoadOperatorRolesFile(t *testing.T) { }, expectError: true, }, - "When roles file conflicts with --external-dns-role-arn it should error": { + "When roles file conflicts with --external-dns-role-arn, it should error": { setup: func(t *testing.T) Options { f := filepath.Join(t.TempDir(), "roles.json") if err := os.WriteFile(f, []byte(`{}`), 0644); err != nil { @@ -2548,13 +2548,13 @@ func TestLoadOperatorRolesFile(t *testing.T) { }, expectError: true, }, - "When roles file does not exist it should error": { + "When roles file does not exist, it should error": { setup: func(t *testing.T) Options { return Options{AWSOperatorRolesFile: "/nonexistent/path/roles.json"} }, expectError: true, }, - "When roles file contains invalid JSON it should error": { + "When roles file contains invalid JSON, it should error": { setup: func(t *testing.T) Options { f := filepath.Join(t.TempDir(), "roles.json") if err := os.WriteFile(f, []byte("not json"), 0644); err != nil { @@ -2589,12 +2589,12 @@ func TestComplete(t *testing.T) { expectError bool validate func(*GomegaWithT, Options) }{ - "When no operator roles file it should complete successfully": { + "When no operator roles file, it should complete successfully": { setup: func(t *testing.T) Options { return Options{} }, }, - "When ScaleFromZeroProvider has whitespace and uppercase it should normalize": { + "When ScaleFromZeroProvider has whitespace and uppercase, it should normalize": { setup: func(t *testing.T) Options { return Options{ScaleFromZeroProvider: " AWS "} }, @@ -2602,7 +2602,7 @@ func TestComplete(t *testing.T) { g.Expect(o.ScaleFromZeroProvider).To(Equal("aws")) }, }, - "When a valid operator roles file is specified it should load ARNs": { + "When a valid operator roles file is specified, it should load ARNs": { setup: func(t *testing.T) Options { roles := aws.CreateOperatorRolesOutput{ OperatorEC2RoleARN: "arn:aws:iam::123456789012:role/op-ec2", @@ -2623,7 +2623,7 @@ func TestComplete(t *testing.T) { g.Expect(o.AWSPrivateRoleARN).To(Equal("arn:aws:iam::123456789012:role/op-ec2")) }, }, - "When operator roles file does not exist it should return error": { + "When operator roles file does not exist, it should return error": { setup: func(t *testing.T) Options { return Options{AWSOperatorRolesFile: "/nonexistent/path/roles.json"} }, diff --git a/cmd/nodepool/aws/create_test.go b/cmd/nodepool/aws/create_test.go index ab1e02906262..b06618a094ab 100644 --- a/cmd/nodepool/aws/create_test.go +++ b/cmd/nodepool/aws/create_test.go @@ -17,14 +17,14 @@ func TestCreateNodePool_When_flags_are_parsed_it_should_generate_correct_nodepoo args []string }{ { - name: "minimal configuration", + name: "When minimal configuration is provided, it should generate correct nodepool", args: []string{ "--instance-type=m5.large", "--subnet-id=subnet-test123", }, }, { - name: "full configuration", + name: "When full configuration is provided, it should generate correct nodepool", args: []string{ "--instance-type=m5.xlarge", "--subnet-id=subnet-test456", @@ -37,7 +37,7 @@ func TestCreateNodePool_When_flags_are_parsed_it_should_generate_correct_nodepoo }, }, { - name: "custom root volume configuration", + name: "When custom root volume configuration is provided, it should generate correct nodepool", args: []string{ "--instance-type=m6g.large", "--subnet-id=subnet-arm64", @@ -140,9 +140,9 @@ func TestValidate_When_root_volume_size_is_valid_it_should_succeed(t *testing.T) name string size int64 }{ - {"minimum size", 8}, - {"default size", 120}, - {"large size", 1000}, + {"When size is minimum it should succeed", 8}, + {"When size is default it should succeed", 120}, + {"When size is large it should succeed", 1000}, } for _, tc := range testCases { diff --git a/cmd/nodepool/aws/testdata/zz_fixture_TestCreateNodePool_When_flags_are_parsed_it_should_generate_correct_nodepool_custom_root_volume_configuration.yaml b/cmd/nodepool/aws/testdata/zz_fixture_TestCreateNodePool_When_flags_are_parsed_it_should_generate_correct_nodepool_When_custom_root_volume_configuration_is_provided__it_should_generate_correct_nodepool.yaml similarity index 100% rename from cmd/nodepool/aws/testdata/zz_fixture_TestCreateNodePool_When_flags_are_parsed_it_should_generate_correct_nodepool_custom_root_volume_configuration.yaml rename to cmd/nodepool/aws/testdata/zz_fixture_TestCreateNodePool_When_flags_are_parsed_it_should_generate_correct_nodepool_When_custom_root_volume_configuration_is_provided__it_should_generate_correct_nodepool.yaml diff --git a/cmd/nodepool/aws/testdata/zz_fixture_TestCreateNodePool_When_flags_are_parsed_it_should_generate_correct_nodepool_full_configuration.yaml b/cmd/nodepool/aws/testdata/zz_fixture_TestCreateNodePool_When_flags_are_parsed_it_should_generate_correct_nodepool_When_full_configuration_is_provided__it_should_generate_correct_nodepool.yaml similarity index 100% rename from cmd/nodepool/aws/testdata/zz_fixture_TestCreateNodePool_When_flags_are_parsed_it_should_generate_correct_nodepool_full_configuration.yaml rename to cmd/nodepool/aws/testdata/zz_fixture_TestCreateNodePool_When_flags_are_parsed_it_should_generate_correct_nodepool_When_full_configuration_is_provided__it_should_generate_correct_nodepool.yaml diff --git a/cmd/nodepool/aws/testdata/zz_fixture_TestCreateNodePool_When_flags_are_parsed_it_should_generate_correct_nodepool_minimal_configuration.yaml b/cmd/nodepool/aws/testdata/zz_fixture_TestCreateNodePool_When_flags_are_parsed_it_should_generate_correct_nodepool_When_minimal_configuration_is_provided__it_should_generate_correct_nodepool.yaml similarity index 100% rename from cmd/nodepool/aws/testdata/zz_fixture_TestCreateNodePool_When_flags_are_parsed_it_should_generate_correct_nodepool_minimal_configuration.yaml rename to cmd/nodepool/aws/testdata/zz_fixture_TestCreateNodePool_When_flags_are_parsed_it_should_generate_correct_nodepool_When_minimal_configuration_is_provided__it_should_generate_correct_nodepool.yaml diff --git a/cmd/nodepool/azure/create_test.go b/cmd/nodepool/azure/create_test.go index c465a8f74ea9..88c51589f312 100644 --- a/cmd/nodepool/azure/create_test.go +++ b/cmd/nodepool/azure/create_test.go @@ -37,7 +37,7 @@ func TestCreateNodePool_When_flags_are_parsed_it_should_generate_correct_nodepoo args []string }{ { - name: "minimal configuration", + name: "When minimal configuration is provided, it should generate correct nodepool", args: []string{ "--instance-type=" + testInstanceType, "--nodepool-subnet-id=" + testSubnetID, @@ -48,7 +48,7 @@ func TestCreateNodePool_When_flags_are_parsed_it_should_generate_correct_nodepoo }, }, { - name: "full configuration with Gen2", + name: "When full configuration with Gen2 is provided, it should generate correct nodepool", args: []string{ "--instance-type=Standard_D8s_v5", "--nodepool-subnet-id=" + testSubnetID, @@ -127,37 +127,37 @@ func TestNodePoolPlatformImageGeneration(t *testing.T) { expectedImageGeneration *hyperv1.AzureVMImageGeneration }{ { - name: "Gen1 specified with AMD64", + name: "When Gen1 is specified with AMD64 it should set Gen1", imageGeneration: "Gen1", nodePoolArch: string(hyperv1.ArchitectureAMD64), expectedImageGeneration: ptr.To(hyperv1.Gen1), }, { - name: "Gen2 specified with AMD64", + name: "When Gen2 is specified with AMD64 it should set Gen2", imageGeneration: "Gen2", nodePoolArch: string(hyperv1.ArchitectureAMD64), expectedImageGeneration: ptr.To(hyperv1.Gen2), }, { - name: "Gen1 specified with ARM64", + name: "When Gen1 is specified with ARM64 it should set Gen1", imageGeneration: "Gen1", nodePoolArch: string(hyperv1.ArchitectureARM64), expectedImageGeneration: ptr.To(hyperv1.Gen1), }, { - name: "Gen2 specified with ARM64", + name: "When Gen2 is specified with ARM64 it should set Gen2", imageGeneration: "Gen2", nodePoolArch: string(hyperv1.ArchitectureARM64), expectedImageGeneration: ptr.To(hyperv1.Gen2), }, { - name: "No generation specified with AMD64", + name: "When no generation is specified with AMD64 it should leave generation nil", imageGeneration: "", nodePoolArch: string(hyperv1.ArchitectureAMD64), expectedImageGeneration: nil, }, { - name: "No generation specified with ARM64", + name: "When no generation is specified with ARM64 it should leave generation nil", imageGeneration: "", nodePoolArch: string(hyperv1.ArchitectureARM64), expectedImageGeneration: nil, @@ -228,46 +228,46 @@ func TestValidateImageGeneration(t *testing.T) { expectedError string }{ { - name: "Valid Gen1", + name: "When Gen1 is specified it should pass validation", imageGen: "Gen1", shouldError: false, }, { - name: "Valid Gen2", + name: "When Gen2 is specified it should pass validation", imageGen: "Gen2", shouldError: false, }, { - name: "Empty is valid", + name: "When image generation is empty it should pass validation", imageGen: "", shouldError: false, }, { - name: "Invalid Gen3", + name: "When Gen3 is specified it should fail validation", imageGen: "Gen3", shouldError: true, expectedError: "invalid value for --image-generation: Gen3. Supported values: Gen1, Gen2", }, { - name: "Invalid lowercase", + name: "When lowercase gen1 is specified it should fail validation", imageGen: "gen1", shouldError: true, expectedError: "invalid value for --image-generation: gen1. Supported values: Gen1, Gen2", }, { - name: "Invalid upper case", + name: "When upper case GEN1 is specified it should fail validation", imageGen: "GEN1", shouldError: true, expectedError: "invalid value for --image-generation: GEN1. Supported values: Gen1, Gen2", }, { - name: "Invalid numeric", + name: "When numeric value is specified it should fail validation", imageGen: "1", shouldError: true, expectedError: "invalid value for --image-generation: 1. Supported values: Gen1, Gen2", }, { - name: "Invalid random string", + name: "When random string is specified it should fail validation", imageGen: "invalid", shouldError: true, expectedError: "invalid value for --image-generation: invalid. Supported values: Gen1, Gen2", @@ -310,14 +310,14 @@ func TestAzureBoundaryConditions(t *testing.T) { expectedError string }{ { - name: "valid minimal configuration", + name: "When valid minimal configuration is provided it should pass validation", modifyOpts: func(opts *RawAzurePlatformCreateOptions) { // No modifications - should be valid }, shouldError: false, }, { - name: "whitespace only image generation", + name: "When whitespace only image generation is provided it should fail validation", modifyOpts: func(opts *RawAzurePlatformCreateOptions) { opts.ImageGeneration = " " }, diff --git a/cmd/nodepool/azure/testdata/zz_fixture_TestCreateNodePool_When_flags_are_parsed_it_should_generate_correct_nodepool_full_configuration_with_Gen2.yaml b/cmd/nodepool/azure/testdata/zz_fixture_TestCreateNodePool_When_flags_are_parsed_it_should_generate_correct_nodepool_When_full_configuration_with_Gen2_is_provided__it_should_generate_correct_nodepool.yaml similarity index 100% rename from cmd/nodepool/azure/testdata/zz_fixture_TestCreateNodePool_When_flags_are_parsed_it_should_generate_correct_nodepool_full_configuration_with_Gen2.yaml rename to cmd/nodepool/azure/testdata/zz_fixture_TestCreateNodePool_When_flags_are_parsed_it_should_generate_correct_nodepool_When_full_configuration_with_Gen2_is_provided__it_should_generate_correct_nodepool.yaml diff --git a/cmd/nodepool/azure/testdata/zz_fixture_TestCreateNodePool_When_flags_are_parsed_it_should_generate_correct_nodepool_minimal_configuration.yaml b/cmd/nodepool/azure/testdata/zz_fixture_TestCreateNodePool_When_flags_are_parsed_it_should_generate_correct_nodepool_When_minimal_configuration_is_provided__it_should_generate_correct_nodepool.yaml similarity index 100% rename from cmd/nodepool/azure/testdata/zz_fixture_TestCreateNodePool_When_flags_are_parsed_it_should_generate_correct_nodepool_minimal_configuration.yaml rename to cmd/nodepool/azure/testdata/zz_fixture_TestCreateNodePool_When_flags_are_parsed_it_should_generate_correct_nodepool_When_minimal_configuration_is_provided__it_should_generate_correct_nodepool.yaml diff --git a/cmd/nodepool/kubevirt/create_test.go b/cmd/nodepool/kubevirt/create_test.go index afedafb8df1c..b89fa3b63b7b 100644 --- a/cmd/nodepool/kubevirt/create_test.go +++ b/cmd/nodepool/kubevirt/create_test.go @@ -72,7 +72,7 @@ func TestRawKubevirtPlatformCreateOptions_Validate(t *testing.T) { expectedErrorSubstring string }{ { - name: "should fail excluding default network without additional ones", + name: "When default network is attached without additional ones, it should succeed", input: RawKubevirtPlatformCreateOptions{ KubevirtPlatformOptions: &KubevirtPlatformOptions{ Cores: 1, @@ -83,7 +83,7 @@ func TestRawKubevirtPlatformCreateOptions_Validate(t *testing.T) { expectedErrorSubstring: "", }, { - name: "When memory value is invalid it should return a validation error", + name: "When memory value is invalid, it should return a validation error", input: RawKubevirtPlatformCreateOptions{ KubevirtPlatformOptions: &KubevirtPlatformOptions{ Memory: "not-a-quantity", @@ -117,7 +117,7 @@ func TestCreateNodePool_When_flags_are_parsed_it_should_generate_correct_nodepoo args []string }{ { - name: "minimal configuration", + name: "When minimal configuration is provided, it should generate correct nodepool", args: []string{ "--cores=2", "--memory=4Gi", @@ -125,7 +125,7 @@ func TestCreateNodePool_When_flags_are_parsed_it_should_generate_correct_nodepoo }, }, { - name: "full configuration with additional networks", + name: "When full configuration with additional networks is provided, it should generate correct nodepool", args: []string{ "--cores=4", "--memory=8Gi", @@ -141,7 +141,7 @@ func TestCreateNodePool_When_flags_are_parsed_it_should_generate_correct_nodepoo }, }, { - name: "with host devices", + name: "When host devices are configured, it should generate correct nodepool", args: []string{ "--cores=8", "--memory=16Gi", @@ -213,7 +213,7 @@ func TestValidatedKubevirtPlatformCreateOptions_Complete(t *testing.T) { expectedError string }{ { - name: "should succeed configuring additional networks", + name: "When additional networks are configured, it should succeed", input: RawKubevirtPlatformCreateOptions{ KubevirtPlatformOptions: &KubevirtPlatformOptions{ Cores: 1, @@ -235,7 +235,7 @@ func TestValidatedKubevirtPlatformCreateOptions_Complete(t *testing.T) { }, }, { - name: "should fail with unexpected additional network parameters", + name: "When unexpected additional network parameters are provided, it should fail", input: RawKubevirtPlatformCreateOptions{ KubevirtPlatformOptions: &KubevirtPlatformOptions{ Cores: 1, @@ -249,7 +249,7 @@ func TestValidatedKubevirtPlatformCreateOptions_Complete(t *testing.T) { expectedError: `failed to parse "--additional-network" flag: unknown param(s): badfield:ns2/nad2`, }, { - name: "should succeed configuring NetworkInterfaceMultiQueue=Enable", + name: "When NetworkInterfaceMultiQueue is set to Enable, it should succeed", input: RawKubevirtPlatformCreateOptions{ KubevirtPlatformOptions: &KubevirtPlatformOptions{ Cores: 1, @@ -272,7 +272,7 @@ func TestValidatedKubevirtPlatformCreateOptions_Complete(t *testing.T) { }, }, { - name: "should succeed configuring NetworkInterfaceMultiQueue=Disable", + name: "When NetworkInterfaceMultiQueue is set to Disable, it should succeed", input: RawKubevirtPlatformCreateOptions{ KubevirtPlatformOptions: &KubevirtPlatformOptions{ Cores: 1, @@ -295,7 +295,7 @@ func TestValidatedKubevirtPlatformCreateOptions_Complete(t *testing.T) { }, }, { - name: "should fail configuring NetworkInterfaceMultiQueue", + name: "When NetworkInterfaceMultiQueue has wrong value, it should fail", input: RawKubevirtPlatformCreateOptions{ KubevirtPlatformOptions: &KubevirtPlatformOptions{ Cores: 1, @@ -311,7 +311,7 @@ func TestValidatedKubevirtPlatformCreateOptions_Complete(t *testing.T) { expectedError: `wrong value for the --network-multiqueue parameter. Supported values are "Enable" or "Disable"`, }, { - name: "should succeed configuring two Host Devices", + name: "When two Host Devices are configured, it should succeed", input: RawKubevirtPlatformCreateOptions{ KubevirtPlatformOptions: &KubevirtPlatformOptions{ Cores: 2, @@ -324,7 +324,7 @@ func TestValidatedKubevirtPlatformCreateOptions_Complete(t *testing.T) { }, }, { - name: "should fail configuring Host Devices without misspelled count", + name: "When Host Device has misspelled count, it should fail", input: RawKubevirtPlatformCreateOptions{ KubevirtPlatformOptions: &KubevirtPlatformOptions{ Cores: 2, @@ -337,7 +337,7 @@ func TestValidatedKubevirtPlatformCreateOptions_Complete(t *testing.T) { expectedError: "invalid KubeVirt host device setting: [my-fabulous-gpu,cuont:2]", }, { - name: "should fail configuring Host Devices with an unsupported option", + name: "When Host Device has an unsupported option, it should fail", input: RawKubevirtPlatformCreateOptions{ KubevirtPlatformOptions: &KubevirtPlatformOptions{ Cores: 2, @@ -350,7 +350,7 @@ func TestValidatedKubevirtPlatformCreateOptions_Complete(t *testing.T) { expectedError: "invalid KubeVirt host device setting: [my-fabulous-gpu,count:2,speed:100GFLOPS]", }, { - name: "should fail configuring Host Devices with a non-integer count", + name: "When Host Device has a non-integer count, it should fail", input: RawKubevirtPlatformCreateOptions{ KubevirtPlatformOptions: &KubevirtPlatformOptions{ Cores: 2, @@ -363,7 +363,7 @@ func TestValidatedKubevirtPlatformCreateOptions_Complete(t *testing.T) { expectedError: "could not parse host device count: [my-fabulous-gpu,count:1K]", }, { - name: "should fail configuring Host Devices with a negative count", + name: "When Host Device has a negative count, it should fail", input: RawKubevirtPlatformCreateOptions{ KubevirtPlatformOptions: &KubevirtPlatformOptions{ Cores: 2, diff --git a/cmd/nodepool/kubevirt/testdata/zz_fixture_TestCreateNodePool_When_flags_are_parsed_it_should_generate_correct_nodepool_full_configuration_with_additional_networks.yaml b/cmd/nodepool/kubevirt/testdata/zz_fixture_TestCreateNodePool_When_flags_are_parsed_it_should_generate_correct_nodepool_When_full_configuration_with_additional_networks_is_provided__it_should_generate_correct_nodepool.yaml similarity index 100% rename from cmd/nodepool/kubevirt/testdata/zz_fixture_TestCreateNodePool_When_flags_are_parsed_it_should_generate_correct_nodepool_full_configuration_with_additional_networks.yaml rename to cmd/nodepool/kubevirt/testdata/zz_fixture_TestCreateNodePool_When_flags_are_parsed_it_should_generate_correct_nodepool_When_full_configuration_with_additional_networks_is_provided__it_should_generate_correct_nodepool.yaml diff --git a/cmd/nodepool/kubevirt/testdata/zz_fixture_TestCreateNodePool_When_flags_are_parsed_it_should_generate_correct_nodepool_with_host_devices.yaml b/cmd/nodepool/kubevirt/testdata/zz_fixture_TestCreateNodePool_When_flags_are_parsed_it_should_generate_correct_nodepool_When_host_devices_are_configured__it_should_generate_correct_nodepool.yaml similarity index 100% rename from cmd/nodepool/kubevirt/testdata/zz_fixture_TestCreateNodePool_When_flags_are_parsed_it_should_generate_correct_nodepool_with_host_devices.yaml rename to cmd/nodepool/kubevirt/testdata/zz_fixture_TestCreateNodePool_When_flags_are_parsed_it_should_generate_correct_nodepool_When_host_devices_are_configured__it_should_generate_correct_nodepool.yaml diff --git a/cmd/nodepool/kubevirt/testdata/zz_fixture_TestCreateNodePool_When_flags_are_parsed_it_should_generate_correct_nodepool_minimal_configuration.yaml b/cmd/nodepool/kubevirt/testdata/zz_fixture_TestCreateNodePool_When_flags_are_parsed_it_should_generate_correct_nodepool_When_minimal_configuration_is_provided__it_should_generate_correct_nodepool.yaml similarity index 100% rename from cmd/nodepool/kubevirt/testdata/zz_fixture_TestCreateNodePool_When_flags_are_parsed_it_should_generate_correct_nodepool_minimal_configuration.yaml rename to cmd/nodepool/kubevirt/testdata/zz_fixture_TestCreateNodePool_When_flags_are_parsed_it_should_generate_correct_nodepool_When_minimal_configuration_is_provided__it_should_generate_correct_nodepool.yaml diff --git a/cmd/nodepool/openstack/create_test.go b/cmd/nodepool/openstack/create_test.go index ab7d103d515f..cc0a70c5abd7 100644 --- a/cmd/nodepool/openstack/create_test.go +++ b/cmd/nodepool/openstack/create_test.go @@ -18,14 +18,14 @@ func TestCreateNodePool_When_flags_are_parsed_it_should_generate_correct_nodepoo args []string }{ { - name: "minimal configuration", + name: "When minimal configuration is provided, it should generate correct nodepool", args: []string{ "--openstack-node-flavor=m1.large", "--openstack-node-image-name=rhcos-openstack", }, }, { - name: "full configuration with availability zone", + name: "When full configuration with availability zone is provided, it should generate correct nodepool", args: []string{ "--openstack-node-flavor=m1.xlarge", "--openstack-node-image-name=rhcos-openstack-latest", @@ -94,14 +94,14 @@ func TestRawOpenStackPlatformCreateOptions_Validate(t *testing.T) { expectedError string }{ { - name: "should fail if flavor is missing", + name: "When flavor is missing, it should fail", input: RawOpenStackPlatformCreateOptions{ OpenStackPlatformOptions: &OpenStackPlatformOptions{}, }, expectedError: "flavor is required", }, { - name: "should pass when AZ is provided", + name: "When AZ is provided, it should pass validation", input: RawOpenStackPlatformCreateOptions{ OpenStackPlatformOptions: &OpenStackPlatformOptions{ Flavor: "flavor", diff --git a/cmd/nodepool/openstack/testdata/zz_fixture_TestCreateNodePool_When_flags_are_parsed_it_should_generate_correct_nodepool_full_configuration_with_availability_zone.yaml b/cmd/nodepool/openstack/testdata/zz_fixture_TestCreateNodePool_When_flags_are_parsed_it_should_generate_correct_nodepool_When_full_configuration_with_availability_zone_is_provided__it_should_generate_correct_nodepool.yaml similarity index 100% rename from cmd/nodepool/openstack/testdata/zz_fixture_TestCreateNodePool_When_flags_are_parsed_it_should_generate_correct_nodepool_full_configuration_with_availability_zone.yaml rename to cmd/nodepool/openstack/testdata/zz_fixture_TestCreateNodePool_When_flags_are_parsed_it_should_generate_correct_nodepool_When_full_configuration_with_availability_zone_is_provided__it_should_generate_correct_nodepool.yaml diff --git a/cmd/nodepool/openstack/testdata/zz_fixture_TestCreateNodePool_When_flags_are_parsed_it_should_generate_correct_nodepool_minimal_configuration.yaml b/cmd/nodepool/openstack/testdata/zz_fixture_TestCreateNodePool_When_flags_are_parsed_it_should_generate_correct_nodepool_When_minimal_configuration_is_provided__it_should_generate_correct_nodepool.yaml similarity index 100% rename from cmd/nodepool/openstack/testdata/zz_fixture_TestCreateNodePool_When_flags_are_parsed_it_should_generate_correct_nodepool_minimal_configuration.yaml rename to cmd/nodepool/openstack/testdata/zz_fixture_TestCreateNodePool_When_flags_are_parsed_it_should_generate_correct_nodepool_When_minimal_configuration_is_provided__it_should_generate_correct_nodepool.yaml diff --git a/cmd/oadp/backup_test.go b/cmd/oadp/backup_test.go index f068bfd856a8..d98cec2468c1 100644 --- a/cmd/oadp/backup_test.go +++ b/cmd/oadp/backup_test.go @@ -470,52 +470,52 @@ func TestValidateBackupName(t *testing.T) { errorMsg string }{ { - name: "Valid short name", + name: "When valid short name is provided, it should pass validation", backupName: "test-backup", expectError: false, }, { - name: "Valid name with numbers", + name: "When valid name with numbers is provided, it should pass validation", backupName: "test-backup-123", expectError: false, }, { - name: "Valid 63 character name", + name: "When valid 63 character name is provided, it should pass validation", backupName: "a1234567890123456789012345678901234567890123456789012345678901b", expectError: false, }, { - name: "Name too long (64 characters)", + name: "When name is too long (64 characters), it should return an error", backupName: "a12345678901234567890123456789012345678901234567890123456789012b", expectError: true, errorMsg: "too long (64 characters)", }, { - name: "Name with uppercase letters", + name: "When name has uppercase letters, it should return an error", backupName: "Test-backup", expectError: true, errorMsg: "a lowercase RFC 1123 subdomain must consist of lower case alphanumeric characters", }, { - name: "Name starting with hyphen", + name: "When name starts with hyphen, it should return an error", backupName: "-test-backup", expectError: true, errorMsg: "a lowercase RFC 1123 subdomain must consist of lower case alphanumeric characters", }, { - name: "Name ending with hyphen", + name: "When name ends with hyphen, it should return an error", backupName: "test-backup-", expectError: true, errorMsg: "a lowercase RFC 1123 subdomain must consist of lower case alphanumeric characters", }, { - name: "Name with invalid characters", + name: "When name has invalid characters, it should return an error", backupName: "test_backup", expectError: true, errorMsg: "a lowercase RFC 1123 subdomain must consist of lower case alphanumeric characters", }, { - name: "Empty name should be valid (auto-generation)", + name: "When name is empty, it should pass validation (auto-generation)", backupName: "", expectError: false, }, diff --git a/cmd/oadp/common_test.go b/cmd/oadp/common_test.go index 9c247991d77d..817b8a4f52fb 100644 --- a/cmd/oadp/common_test.go +++ b/cmd/oadp/common_test.go @@ -217,7 +217,7 @@ func TestValidateEtcdSnapshotFlags(t *testing.T) { errMsg string }{ { - name: "When etcd snapshot is disabled it should accept any flags", + name: "When etcd snapshot is disabled, it should accept any flags", useEtcdSnapshot: false, snapshotMoveData: true, defaultVolumesToFsBackup: true, @@ -225,14 +225,14 @@ func TestValidateEtcdSnapshotFlags(t *testing.T) { expectErr: false, }, { - name: "When etcd snapshot is enabled without explicit conflicting flags it should pass", + name: "When etcd snapshot is enabled without conflicting flags, it should pass", useEtcdSnapshot: true, snapshotMoveData: true, // default value, but not explicitly changed changedFlags: map[string]bool{"use-etcd-snapshot": true}, expectErr: false, }, { - name: "When etcd snapshot is enabled with explicit snapshot-move-data it should return error", + name: "When etcd snapshot is enabled with snapshot-move-data, it should return error", useEtcdSnapshot: true, snapshotMoveData: true, changedFlags: map[string]bool{"use-etcd-snapshot": true, "snapshot-move-data": true}, @@ -240,7 +240,7 @@ func TestValidateEtcdSnapshotFlags(t *testing.T) { errMsg: "--snapshot-move-data cannot be used with --use-etcd-snapshot", }, { - name: "When etcd snapshot is enabled with explicit default-volumes-to-fs-backup it should return error", + name: "When etcd snapshot is enabled with default-volumes-to-fs-backup, it should return error", useEtcdSnapshot: true, defaultVolumesToFsBackup: true, changedFlags: map[string]bool{"use-etcd-snapshot": true, "default-volumes-to-fs-backup": true}, @@ -248,7 +248,7 @@ func TestValidateEtcdSnapshotFlags(t *testing.T) { errMsg: "--default-volumes-to-fs-backup cannot be used with --use-etcd-snapshot", }, { - name: "When etcd snapshot is enabled with explicit restore-pvs it should return error", + name: "When etcd snapshot is enabled with restore-pvs, it should return error", useEtcdSnapshot: true, changedFlags: map[string]bool{"use-etcd-snapshot": true, "restore-pvs": true}, expectErr: true, diff --git a/cmd/oadp/restore_test.go b/cmd/oadp/restore_test.go index 0ed2f43a2516..f9d879a5e113 100644 --- a/cmd/oadp/restore_test.go +++ b/cmd/oadp/restore_test.go @@ -347,52 +347,52 @@ func TestValidateRestoreName(t *testing.T) { errorMsg string }{ { - name: "Valid short name", + name: "When valid short name is provided, it should pass validation", restoreName: "test-restore", expectError: false, }, { - name: "Valid name with numbers", + name: "When valid name with numbers is provided, it should pass validation", restoreName: "test-restore-123", expectError: false, }, { - name: "Valid 63 character name", + name: "When valid 63 character name is provided, it should pass validation", restoreName: "a1234567890123456789012345678901234567890123456789012345678901b", expectError: false, }, { - name: "Name too long (64 characters)", + name: "When name is too long (64 characters), it should return an error", restoreName: "a12345678901234567890123456789012345678901234567890123456789012b", expectError: true, errorMsg: "too long (64 characters)", }, { - name: "Name with uppercase letters", + name: "When name has uppercase letters, it should return an error", restoreName: "Test-restore", expectError: true, errorMsg: "a lowercase RFC 1123 subdomain must consist of lower case alphanumeric characters", }, { - name: "Name starting with hyphen", + name: "When name starts with hyphen, it should return an error", restoreName: "-test-restore", expectError: true, errorMsg: "a lowercase RFC 1123 subdomain must consist of lower case alphanumeric characters", }, { - name: "Name ending with hyphen", + name: "When name ends with hyphen, it should return an error", restoreName: "test-restore-", expectError: true, errorMsg: "a lowercase RFC 1123 subdomain must consist of lower case alphanumeric characters", }, { - name: "Name with invalid characters", + name: "When name has invalid characters, it should return an error", restoreName: "test_restore", expectError: true, errorMsg: "a lowercase RFC 1123 subdomain must consist of lower case alphanumeric characters", }, { - name: "Empty name should be valid", + name: "When name is empty, it should pass validation", restoreName: "", expectError: false, }, diff --git a/cmd/oadp/schedule_test.go b/cmd/oadp/schedule_test.go index b7175dd82607..9f6c1d729855 100644 --- a/cmd/oadp/schedule_test.go +++ b/cmd/oadp/schedule_test.go @@ -545,118 +545,118 @@ func TestValidateSchedulePace(t *testing.T) { }{ // Valid cron expressions { - name: "Valid daily schedule", + name: "When valid daily schedule is provided, it should pass validation", schedule: "0 2 * * *", expectErr: false, }, { - name: "Valid weekly schedule", + name: "When valid weekly schedule is provided, it should pass validation", schedule: "0 1 * * 0", expectErr: false, }, { - name: "Valid monthly schedule", + name: "When valid monthly schedule is provided, it should pass validation", schedule: "0 3 1 * *", expectErr: false, }, { - name: "Valid hourly schedule", + name: "When valid hourly schedule is provided, it should pass validation", schedule: "0 * * * *", expectErr: false, }, { - name: "Valid specific weekday schedule", + name: "When valid specific weekday schedule is provided, it should pass validation", schedule: "30 14 * * 1-5", // Monday to Friday at 2:30 PM expectErr: false, }, // Valid Velero verb schedules { - name: "Valid daily verb", + name: "When valid daily verb is provided, it should pass validation", schedule: "daily", expectErr: false, }, { - name: "Valid weekly verb", + name: "When valid weekly verb is provided, it should pass validation", schedule: "weekly", expectErr: false, }, { - name: "Valid monthly verb", + name: "When valid monthly verb is provided, it should pass validation", schedule: "monthly", expectErr: false, }, { - name: "Valid @daily verb", + name: "When valid @daily verb is provided, it should pass validation", schedule: "@daily", expectErr: false, }, { - name: "Valid @weekly verb", + name: "When valid @weekly verb is provided, it should pass validation", schedule: "@weekly", expectErr: false, }, { - name: "Valid @monthly verb", + name: "When valid @monthly verb is provided, it should pass validation", schedule: "@monthly", expectErr: false, }, { - name: "Valid yearly verb", + name: "When valid yearly verb is provided, it should pass validation", schedule: "yearly", expectErr: false, }, { - name: "Valid hourly verb", + name: "When valid hourly verb is provided, it should pass validation", schedule: "hourly", expectErr: false, }, { - name: "Valid daily-2am verb", + name: "When valid daily-2am verb is provided, it should pass validation", schedule: "daily-2am", expectErr: false, }, { - name: "Valid weekly-friday verb", + name: "When valid weekly-friday verb is provided, it should pass validation", schedule: "weekly-friday", expectErr: false, }, { - name: "Valid case-insensitive DAILY", + name: "When valid case-insensitive DAILY is provided, it should pass validation", schedule: "DAILY", expectErr: false, }, { - name: "Valid case-insensitive @Weekly", + name: "When valid case-insensitive @Weekly is provided, it should pass validation", schedule: "@Weekly", expectErr: false, }, // Invalid cron expressions { - name: "Empty schedule", + name: "When empty schedule is provided, it should return an error", schedule: "", expectErr: true, errMsg: "schedule expression is required", }, { - name: "Too few fields", + name: "When schedule has too few fields, it should return an error", schedule: "0 2 *", expectErr: true, errMsg: "invalid cron schedule", }, { - name: "Too many fields", + name: "When schedule has too many fields, it should return an error", schedule: "0 2 * * * *", expectErr: true, errMsg: "invalid cron schedule", }, { - name: "Too few fields with spaces", + name: "When schedule has too few fields with spaces, it should return an error", schedule: "0 * * *", expectErr: true, errMsg: "invalid cron schedule", }, { - name: "Too few fields with trailing space", + name: "When schedule has too few fields with trailing space, it should return an error", schedule: "0 2 * * ", expectErr: true, errMsg: "invalid cron schedule", @@ -946,7 +946,7 @@ func TestRunSchedule(t *testing.T) { expect func(g Gomega, err error) }{ { - name: "When client is unavailable in render mode it should fallback to AWS and render", + name: "When client is unavailable in render mode, it should fallback to AWS and render", setup: func(t *testing.T, opts *CreateOptions) { t.Setenv("KUBECONFIG", "/nonexistent/kubeconfig") t.Setenv("KUBERNETES_SERVICE_HOST", "") @@ -958,7 +958,7 @@ func TestRunSchedule(t *testing.T) { }, }, { - name: "When client is available in render mode it should render with validation warnings", + name: "When client is available in render mode, it should render with validation warnings", setup: func(t *testing.T, opts *CreateOptions) { opts.Render = true scheme := runtime.NewScheme() @@ -969,7 +969,7 @@ func TestRunSchedule(t *testing.T) { }, }, { - name: "When client has valid resources in non-render mode it should create the schedule", + name: "When client has valid resources in non-render mode, it should create the schedule", setup: func(t *testing.T, opts *CreateOptions) { opts.Render = false @@ -1039,7 +1039,7 @@ func TestRunSchedule(t *testing.T) { }, }, { - name: "When client is unavailable in non-render mode it should return an error", + name: "When client is unavailable in non-render mode, it should return an error", setup: func(t *testing.T, opts *CreateOptions) { t.Setenv("KUBECONFIG", "/nonexistent/kubeconfig") t.Setenv("KUBERNETES_SERVICE_HOST", "") @@ -1052,7 +1052,7 @@ func TestRunSchedule(t *testing.T) { }, }, { - name: "When HostedCluster is not found in non-render mode it should return platform detection error", + name: "When HostedCluster is not found in non-render mode, it should return platform detection error", setup: func(t *testing.T, opts *CreateOptions) { opts.Render = false scheme := runtime.NewScheme() @@ -1065,7 +1065,7 @@ func TestRunSchedule(t *testing.T) { }, }, { - name: "When OADP components are missing in non-render mode it should return OADP validation error", + name: "When OADP components are missing in non-render mode, it should return OADP validation error", setup: func(t *testing.T, opts *CreateOptions) { opts.Render = false scheme := runtime.NewScheme() @@ -1086,7 +1086,7 @@ func TestRunSchedule(t *testing.T) { }, }, { - name: "When DPA is missing in non-render mode it should return DPA verification error", + name: "When DPA is missing in non-render mode, it should return DPA verification error", setup: func(t *testing.T, opts *CreateOptions) { opts.Render = false scheme := runtime.NewScheme() @@ -1147,52 +1147,52 @@ func TestScheduleNameValidation(t *testing.T) { errorMsg string }{ { - name: "Valid short name", + name: "When valid short name is provided, it should pass validation", scheduleName: "test-schedule", expectError: false, }, { - name: "Valid name with numbers", + name: "When valid name with numbers is provided, it should pass validation", scheduleName: "test-schedule-123", expectError: false, }, { - name: "Valid 63 character name", + name: "When valid 63 character name is provided, it should pass validation", scheduleName: "a1234567890123456789012345678901234567890123456789012345678901b", expectError: false, }, { - name: "Name too long (64 characters)", + name: "When name is too long (64 characters), it should return an error", scheduleName: "a12345678901234567890123456789012345678901234567890123456789012b", expectError: true, errorMsg: "too long (64 characters)", }, { - name: "Name with uppercase letters", + name: "When name has uppercase letters, it should return an error", scheduleName: "Test-schedule", expectError: true, errorMsg: "a lowercase RFC 1123 subdomain must consist of lower case alphanumeric characters", }, { - name: "Name starting with hyphen", + name: "When name starts with hyphen, it should return an error", scheduleName: "-test-schedule", expectError: true, errorMsg: "a lowercase RFC 1123 subdomain must consist of lower case alphanumeric characters", }, { - name: "Name ending with hyphen", + name: "When name ends with hyphen, it should return an error", scheduleName: "test-schedule-", expectError: true, errorMsg: "a lowercase RFC 1123 subdomain must consist of lower case alphanumeric characters", }, { - name: "Name with invalid characters", + name: "When name has invalid characters, it should return an error", scheduleName: "test_schedule", expectError: true, errorMsg: "a lowercase RFC 1123 subdomain must consist of lower case alphanumeric characters", }, { - name: "Empty name should be valid", + name: "When name is empty, it should pass validation", scheduleName: "", expectError: false, }, diff --git a/cmd/util/azure_test.go b/cmd/util/azure_test.go index aa27cf0c2f51..497fc34d30aa 100644 --- a/cmd/util/azure_test.go +++ b/cmd/util/azure_test.go @@ -10,7 +10,7 @@ import ( "github.com/Azure/azure-sdk-for-go/sdk/azidentity" ) -func Test_SetupAzureCredentials(t *testing.T) { +func TestSetupAzureCredentials(t *testing.T) { tests := map[string]struct { testName string credentials *AzureCreds @@ -19,7 +19,7 @@ func Test_SetupAzureCredentials(t *testing.T) { expectedAzureCreds *azidentity.DefaultAzureCredential expectedError bool }{ - "valid credentials": { + "When credentials are valid it should return the subscription ID": { credentialsFile: "../../test/setup/fake_credentials", credentials: &AzureCreds{ SubscriptionID: "89a", @@ -30,7 +30,7 @@ func Test_SetupAzureCredentials(t *testing.T) { expectedSubscriptionID: "89a", expectedError: false, }, - "invalid credentials": { + "When credentials file is invalid it should still return the subscription ID": { credentialsFile: "../../test/setup/fake_credential", credentials: &AzureCreds{ SubscriptionID: "89a", @@ -56,13 +56,13 @@ func Test_SetupAzureCredentials(t *testing.T) { } } -func Test_ReadCredentials(t *testing.T) { +func TestReadCredentials(t *testing.T) { tests := map[string]struct { path string expectedAzureCreds *AzureCreds expectedError bool }{ - "valid file": { + "When file is valid it should return credentials": { path: "../../test/setup/fake_credentials", expectedAzureCreds: &AzureCreds{ SubscriptionID: "89a", @@ -72,7 +72,7 @@ func Test_ReadCredentials(t *testing.T) { }, expectedError: false, }, - "invalid file": { + "When file is invalid it should return an error": { path: "../../test/setup/fake_credential", expectedError: true, }, @@ -91,12 +91,12 @@ func Test_ReadCredentials(t *testing.T) { } } -func Test_ValidateMarketplaceFlags(t *testing.T) { +func TestValidateMarketplaceFlags(t *testing.T) { tests := map[string]struct { marketplaceImageInfo map[string]*string expectedError bool }{ - "valid marketplace image": { + "When marketplace image is valid it should pass validation": { marketplaceImageInfo: map[string]*string{ "marketplace-publisher": newStringPtr("publisher"), "marketplace-offer": newStringPtr("offer"), @@ -105,7 +105,7 @@ func Test_ValidateMarketplaceFlags(t *testing.T) { }, expectedError: false, }, - "invalid marketplace image": { + "When marketplace image has empty offer it should return an error": { marketplaceImageInfo: map[string]*string{ "marketplace-publisher": newStringPtr("publisher"), "marketplace-offer": newStringPtr(""), @@ -114,7 +114,7 @@ func Test_ValidateMarketplaceFlags(t *testing.T) { }, expectedError: true, }, - "empty marketplace image": { + "When marketplace image is empty it should pass validation": { marketplaceImageInfo: map[string]*string{ "marketplace-publisher": newStringPtr(""), "marketplace-offer": newStringPtr(""), diff --git a/cmd/util/params_test.go b/cmd/util/params_test.go index 1ea333975f56..e996d2c0f44f 100644 --- a/cmd/util/params_test.go +++ b/cmd/util/params_test.go @@ -21,17 +21,17 @@ func TestSupported(t *testing.T) { expected string }{ { - name: "Valid struct with all supported types", + name: "When struct has all supported types, it should return correct format", input: TestStruct{}, expected: "param1:string,param2:uint,param3:resource.Quantity,param4:[]string,param5:bool", }, { - name: "Empty struct", + name: "When struct is empty, it should return empty string", input: struct{}{}, expected: "", }, { - name: "Struct with unsupported type", + name: "When struct has unsupported type, it should panic", input: struct { Param1 int `param:"param1"` }{}, @@ -73,7 +73,7 @@ func TestMap(t *testing.T) { err bool }{ { - name: "Valid parameters", + name: "When parameters are valid, it should map correctly", flagName: "test-flag", paramsStr: "param1:value1,param2:42,param3:100Mi,param4:true", input: &TestStruct{}, @@ -86,7 +86,7 @@ func TestMap(t *testing.T) { err: false, }, { - name: "Unknown parameter", + name: "When parameter is unknown, it should return an error", flagName: "test-flag", paramsStr: "param1:value1,param6:value6", input: &TestStruct{}, @@ -94,7 +94,7 @@ func TestMap(t *testing.T) { err: true, }, { - name: "Invalid uint parameter", + name: "When uint parameter is invalid, it should return an error", flagName: "test-flag", paramsStr: "param2:invalid", input: &TestStruct{}, @@ -102,7 +102,7 @@ func TestMap(t *testing.T) { err: true, }, { - name: "Invalid bool parameter", + name: "When bool parameter is invalid, it should return an error", flagName: "test-flag", paramsStr: "param5:invalid", input: &TestStruct{}, @@ -110,7 +110,7 @@ func TestMap(t *testing.T) { err: true, }, { - name: "Empty parameters", + name: "When parameters are empty, it should return an error", flagName: "test-flag", paramsStr: "", input: &TestStruct{}, diff --git a/control-plane-operator/controllers/awsprivatelink/awsprivatelink_controller_test.go b/control-plane-operator/controllers/awsprivatelink/awsprivatelink_controller_test.go index 2fc9c04dfe6b..d651a00c4289 100644 --- a/control-plane-operator/controllers/awsprivatelink/awsprivatelink_controller_test.go +++ b/control-plane-operator/controllers/awsprivatelink/awsprivatelink_controller_test.go @@ -35,7 +35,7 @@ import ( "go.uber.org/mock/gomock" ) -func Test_diffIDs(t *testing.T) { +func TestDiffIDs(t *testing.T) { subnet1 := "1" subnet2 := "2" subnet3 := "3" @@ -50,7 +50,7 @@ func Test_diffIDs(t *testing.T) { wantRemoved []string }{ { - name: "no subnets, no change", + name: "When no subnets exist, it should return no changes", args: args{ desired: []string{}, existing: []string{}, @@ -59,7 +59,7 @@ func Test_diffIDs(t *testing.T) { wantRemoved: nil, }, { - name: "two subnet, no change", + name: "When two subnets match, it should return no changes", args: args{ desired: []string{subnet1, subnet2}, existing: []string{subnet1, subnet2}, @@ -68,7 +68,7 @@ func Test_diffIDs(t *testing.T) { wantRemoved: nil, }, { - name: "one new subnet", + name: "When one new subnet is desired, it should return it as added", args: args{ desired: []string{subnet1, subnet2}, existing: []string{subnet1}, @@ -77,7 +77,7 @@ func Test_diffIDs(t *testing.T) { wantRemoved: nil, }, { - name: "one removed subnet", + name: "When one subnet is removed, it should return it as removed", args: args{ desired: []string{subnet1}, existing: []string{subnet1, subnet2}, @@ -86,7 +86,7 @@ func Test_diffIDs(t *testing.T) { wantRemoved: []string{subnet2}, }, { - name: "one removed subnet, one added subnet", + name: "When one subnet is added and one removed, it should return both", args: args{ desired: []string{subnet1, subnet2}, existing: []string{subnet2, subnet3}, @@ -108,7 +108,7 @@ func Test_diffIDs(t *testing.T) { } } -func Test_deduplicateSubnetsByAZ(t *testing.T) { +func TestDeduplicateSubnetsByAZ(t *testing.T) { tests := []struct { name string subnetIDs []string @@ -187,7 +187,7 @@ func Test_deduplicateSubnetsByAZ(t *testing.T) { expectedSubnets: []string{"subnet-aaa", "subnet-bbb", "subnet-ccc"}, }, { - name: "When DescribeSubnets fails it should return error", + name: "When DescribeSubnets fails, it should return error", subnetIDs: []string{"subnet-aaa", "subnet-bbb"}, describeErr: fmt.Errorf("access denied"), expectDescribeCall: true, @@ -230,16 +230,16 @@ func TestRecordForService(t *testing.T) { expected []string }{ { - name: "Unknown service, no entry", + name: "When service is unknown it should return no entry", in: &hyperv1.AWSEndpointService{ObjectMeta: metav1.ObjectMeta{Name: "unknown"}}, }, { - name: "KAS service gets api entry", + name: "When service is KAS, it should return api entry", in: &hyperv1.AWSEndpointService{ObjectMeta: metav1.ObjectMeta{Name: "kube-apiserver-private"}}, expected: []string{"api"}, }, { - name: "Router service gets api and apps entry when kas is exposed through route", + name: "When router service has KAS exposed through route, it should return api and apps entries", in: &hyperv1.AWSEndpointService{ObjectMeta: metav1.ObjectMeta{Name: "private-router"}}, serviceMapping: []hyperv1.ServicePublishingStrategyMapping{{ Service: hyperv1.APIServer, @@ -248,7 +248,7 @@ func TestRecordForService(t *testing.T) { expected: []string{"api", "*.apps"}, }, { - name: "Router service gets apps entry only when kas is not exposed through route", + name: "When router service has KAS not exposed through route, it should return only apps entry", in: &hyperv1.AWSEndpointService{ObjectMeta: metav1.ObjectMeta{Name: "private-router"}}, expected: []string{"*.apps"}, }, @@ -330,8 +330,13 @@ func TestDiffPermissions(t *testing.T) { }, } + testNames := []string{ + "When no actual permissions exist it should return all required as needed", + "When actual contains required permissions it should return empty diff", + "When partially matching permissions exist it should return only missing ones", + } for i, test := range tests { - t.Run(fmt.Sprintf("test-%d", i), func(t *testing.T) { + t.Run(testNames[i], func(t *testing.T) { g := NewGomegaWithT(t) result := diffPermissions(test.actual, test.required) g.Expect(result).To(Equal(test.expected)) @@ -365,7 +370,7 @@ func TestReconcileDeletion(t *testing.T) { expectRequeue bool }{ { - name: "When all AWS resources are cleaned up successfully it should remove the finalizer", + name: "When all AWS resources are cleaned up successfully, it should remove the finalizer", awsEndpointSvc: &hyperv1.AWSEndpointService{ ObjectMeta: metav1.ObjectMeta{ Name: "private-router", @@ -419,7 +424,7 @@ func TestReconcileDeletion(t *testing.T) { expectFinalizer: false, }, { - name: "When status has no AWS resources it should remove the finalizer", + name: "When status has no AWS resources, it should remove the finalizer", awsEndpointSvc: &hyperv1.AWSEndpointService{ ObjectMeta: metav1.ObjectMeta{ Name: "private-router", @@ -440,7 +445,7 @@ func TestReconcileDeletion(t *testing.T) { expectFinalizer: false, }, { - name: "When HCP exists after restart it should initialize clients and complete deletion", + name: "When HCP exists after restart, it should initialize clients and complete deletion", awsEndpointSvc: &hyperv1.AWSEndpointService{ ObjectMeta: metav1.ObjectMeta{ Name: "private-router", @@ -506,7 +511,7 @@ func TestReconcileDeletion(t *testing.T) { expectFinalizer: false, }, { - name: "When VPC endpoint deletion fails it should return error and preserve the finalizer", + name: "When VPC endpoint deletion fails, it should return error and preserve the finalizer", awsEndpointSvc: &hyperv1.AWSEndpointService{ ObjectMeta: metav1.ObjectMeta{ Name: "private-router", @@ -530,7 +535,7 @@ func TestReconcileDeletion(t *testing.T) { expectFinalizer: true, }, { - name: "When security group deletion returns DependencyViolation it should requeue without error", + name: "When security group deletion returns DependencyViolation, it should requeue without error", awsEndpointSvc: &hyperv1.AWSEndpointService{ ObjectMeta: metav1.ObjectMeta{ Name: "private-router", @@ -564,7 +569,7 @@ func TestReconcileDeletion(t *testing.T) { expectFinalizer: true, }, { - name: "When Route53 hosted zone is already deleted externally it should treat deletion as successful", + name: "When Route53 hosted zone is already deleted externally, it should treat deletion as successful", awsEndpointSvc: &hyperv1.AWSEndpointService{ ObjectMeta: metav1.ObjectMeta{ Name: "private-router", @@ -1636,7 +1641,7 @@ func TestReconcileDeletionSharedVPC(t *testing.T) { // deleted, role ARNs lost. The controller errors on every retry because it // cannot initialize clients without the HCP. After the 10-minute grace period // the hypershift-operator will force-remove the finalizer, leaking resources. - name: "When SharedVPC operator restarts with no HCP it should return error and preserve finalizer", + name: "When SharedVPC operator restarts with no HCP, it should return error and preserve finalizer", hasHCP: false, setupMocks: func(mockCtrl *gomock.Controller) *MockawsClientProvider { mockBuilder := NewMockawsClientProvider(mockCtrl) @@ -1657,7 +1662,7 @@ func TestReconcileDeletionSharedVPC(t *testing.T) { // SharedVPC roles. In production the subsequent delete calls would fail with // AccessDenied because the security group and VPC endpoint live in a // different AWS account — a mocked error simulates this deterministically. - name: "When SharedVPC client is initialized without role ARNs it should fail to create AWS session", + name: "When SharedVPC client is initialized without role ARNs, it should fail to create AWS session", hasHCP: false, setupMocks: func(mockCtrl *gomock.Controller) *MockawsClientProvider { mockBuilder := NewMockawsClientProvider(mockCtrl) @@ -1769,17 +1774,17 @@ func TestExtractNLBName(t *testing.T) { expected string }{ { - name: "When standard NLB hostname it should extract name without hyphens", + name: "When standard NLB hostname, it should extract name without hyphens", hostname: "a1b2c3d4e5f6g7-1234567890abcdef.elb.us-east-1.amazonaws.com", expected: "a1b2c3d4e5f6g7", }, { - name: "When EKS Auto Mode NLB hostname it should extract full name with hyphens", + name: "When EKS Auto Mode NLB hostname, it should extract full name with hyphens", hostname: "k8s-clusters-kubeapis-db6fee3a62-8008741421d14306.elb.us-east-1.amazonaws.com", expected: "k8s-clusters-kubeapis-db6fee3a62", }, { - name: "When hostname has no hyphens it should return the first label as-is", + name: "When hostname has no hyphens, it should return the first label as-is", hostname: "somename.elb.us-east-1.amazonaws.com", expected: "somename", }, @@ -2068,37 +2073,37 @@ func TestIsAWSThrottleError(t *testing.T) { expected bool }{ { - name: "Throttling error should be detected", + name: "When error code is Throttling, it should be detected", err: &testAPIError{code: "Throttling"}, expected: true, }, { - name: "ThrottlingException should be detected", + name: "When error code is ThrottlingException, it should be detected", err: &testAPIError{code: "ThrottlingException"}, expected: true, }, { - name: "RequestLimitExceeded should be detected", + name: "When error code is RequestLimitExceeded, it should be detected", err: &testAPIError{code: "RequestLimitExceeded"}, expected: true, }, { - name: "TooManyRequestsException should be detected", + name: "When error code is TooManyRequestsException, it should be detected", err: &testAPIError{code: "TooManyRequestsException"}, expected: true, }, { - name: "Non-throttle AWS error should not be detected", + name: "When error code is non-throttle AWS error, it should not be detected", err: &testAPIError{code: "NoSuchHostedZone"}, expected: false, }, { - name: "Non-AWS error should not be detected", + name: "When error is not an AWS error, it should not be detected", err: errors.New("network error"), expected: false, }, { - name: "Nil error should not be detected", + name: "When error is nil, it should not be detected", err: nil, expected: false, }, diff --git a/control-plane-operator/controllers/awsprivatelink/route53_test.go b/control-plane-operator/controllers/awsprivatelink/route53_test.go index 3916d54738d4..bc702a1bcefc 100644 --- a/control-plane-operator/controllers/awsprivatelink/route53_test.go +++ b/control-plane-operator/controllers/awsprivatelink/route53_test.go @@ -98,7 +98,7 @@ func TestFindRecord(t *testing.T) { expectNil: true, }, { - name: "When API returns an error it should propagate the error", + name: "When API returns an error, it should propagate the error", setupMock: func(m *awsapi.MockROUTE53API) { m.EXPECT().ListResourceRecordSets(gomock.Any(), gomock.Any(), gomock.Any()).Return( nil, errors.New("api error"), @@ -149,7 +149,7 @@ func TestCreateRecord(t *testing.T) { checkErrorType func(*testing.T, error) }{ { - name: "When ChangeResourceRecordSets succeeds it should return nil", + name: "When ChangeResourceRecordSets succeeds, it should return nil", setupMock: func(m *awsapi.MockROUTE53API) { m.EXPECT().ChangeResourceRecordSets(gomock.Any(), gomock.Any(), gomock.Any()).Return( &route53.ChangeResourceRecordSetsOutput{}, nil, @@ -158,7 +158,7 @@ func TestCreateRecord(t *testing.T) { expectError: false, }, { - name: "When API returns a smithy error it should preserve the original error type", + name: "When API returns a smithy error, it should preserve the original error type", setupMock: func(m *awsapi.MockROUTE53API) { m.EXPECT().ChangeResourceRecordSets(gomock.Any(), gomock.Any(), gomock.Any()).Return( nil, &testAPIError{code: "NoSuchHostedZone"}, @@ -174,7 +174,7 @@ func TestCreateRecord(t *testing.T) { }, }, { - name: "When API returns a non-smithy error it should propagate the original error", + name: "When API returns a non-smithy error, it should propagate the original error", setupMock: func(m *awsapi.MockROUTE53API) { m.EXPECT().ChangeResourceRecordSets(gomock.Any(), gomock.Any(), gomock.Any()).Return( nil, errors.New("network error"), @@ -226,7 +226,7 @@ func TestDeleteRecord(t *testing.T) { errorContains string }{ { - name: "When ChangeResourceRecordSets succeeds it should return nil", + name: "When ChangeResourceRecordSets succeeds, it should return nil", setupMock: func(m *awsapi.MockROUTE53API) { m.EXPECT().ChangeResourceRecordSets(gomock.Any(), gomock.Any(), gomock.Any()).Return( &route53.ChangeResourceRecordSetsOutput{}, nil, @@ -235,7 +235,7 @@ func TestDeleteRecord(t *testing.T) { expectError: false, }, { - name: "When ChangeResourceRecordSets fails it should propagate the error", + name: "When ChangeResourceRecordSets fails, it should propagate the error", setupMock: func(m *awsapi.MockROUTE53API) { m.EXPECT().ChangeResourceRecordSets(gomock.Any(), gomock.Any(), gomock.Any()).Return( nil, errors.New("delete failed"), diff --git a/control-plane-operator/controllers/azureprivatelinkservice/controller_test.go b/control-plane-operator/controllers/azureprivatelinkservice/controller_test.go index 813f2355634f..31c86720bcc7 100644 --- a/control-plane-operator/controllers/azureprivatelinkservice/controller_test.go +++ b/control-plane-operator/controllers/azureprivatelinkservice/controller_test.go @@ -283,12 +283,12 @@ func TestPrivateEndpointName(t *testing.T) { expected string }{ { - name: "When CR name is simple it should append PE suffix", + name: "When CR name is simple, it should append PE suffix", crName: "kube-apiserver-lb", expected: "kube-apiserver-lb-pe", }, { - name: "When CR name is longer it should still append PE suffix", + name: "When CR name is longer, it should still append PE suffix", crName: "my-hosted-cluster-kas-svc", expected: "my-hosted-cluster-kas-svc-pe", }, @@ -312,7 +312,7 @@ func TestVNetLinkName(t *testing.T) { expected string }{ { - name: "When CR name is simple it should append VNet link suffix", + name: "When CR name is simple, it should append VNet link suffix", crName: "kube-apiserver-lb", expected: "kube-apiserver-lb-vnet-link", }, @@ -336,7 +336,7 @@ func TestExtractPrivateEndpointIP(t *testing.T) { expected string }{ { - name: "When CustomDNSConfigs has IPs it should return the first IP", + name: "When CustomDNSConfigs has IPs, it should return the first IP", pe: armnetwork.PrivateEndpoint{ Properties: &armnetwork.PrivateEndpointProperties{ CustomDNSConfigs: []*armnetwork.CustomDNSConfigPropertiesFormat{ @@ -349,7 +349,7 @@ func TestExtractPrivateEndpointIP(t *testing.T) { expected: "10.0.1.5", }, { - name: "When CustomDNSConfigs is empty it should fall back to network interfaces", + name: "When CustomDNSConfigs is empty, it should fall back to network interfaces", pe: armnetwork.PrivateEndpoint{ Properties: &armnetwork.PrivateEndpointProperties{ NetworkInterfaces: []*armnetwork.Interface{ @@ -370,14 +370,14 @@ func TestExtractPrivateEndpointIP(t *testing.T) { expected: "10.0.1.6", }, { - name: "When Properties is nil it should return empty string", + name: "When Properties is nil, it should return empty string", pe: armnetwork.PrivateEndpoint{ Properties: nil, }, expected: "", }, { - name: "When no IPs are available it should return empty string", + name: "When no IPs are available, it should return empty string", pe: armnetwork.PrivateEndpoint{ Properties: &armnetwork.PrivateEndpointProperties{}, }, @@ -784,7 +784,7 @@ func TestGetHostedControlPlane(t *testing.T) { expectHCP string }{ { - name: "When owner reference exists it should find the HCP", + name: "When owner reference exists, it should find the HCP", azPLS: &hyperv1.AzurePrivateLinkService{ ObjectMeta: metav1.ObjectMeta{ Name: "test-pls", @@ -805,7 +805,7 @@ func TestGetHostedControlPlane(t *testing.T) { expectHCP: "my-hcp", }, { - name: "When no owner reference exists it should return error", + name: "When no owner reference exists, it should return error", azPLS: &hyperv1.AzurePrivateLinkService{ ObjectMeta: metav1.ObjectMeta{ Name: "test-pls", @@ -816,7 +816,7 @@ func TestGetHostedControlPlane(t *testing.T) { expectErr: true, }, { - name: "When HCP does not exist it should return error", + name: "When HCP does not exist, it should return error", azPLS: &hyperv1.AzurePrivateLinkService{ ObjectMeta: metav1.ObjectMeta{ Name: "test-pls", @@ -973,7 +973,7 @@ func TestExtractPrivateEndpointConnectionState(t *testing.T) { expected string }{ { - name: "When PE connection is approved it should return Approved", + name: "When PE connection is approved, it should return Approved", pe: armnetwork.PrivateEndpoint{ Properties: &armnetwork.PrivateEndpointProperties{ ManualPrivateLinkServiceConnections: []*armnetwork.PrivateLinkServiceConnection{ @@ -990,7 +990,7 @@ func TestExtractPrivateEndpointConnectionState(t *testing.T) { expected: "Approved", }, { - name: "When PE connection is pending it should return Pending", + name: "When PE connection is pending, it should return Pending", pe: armnetwork.PrivateEndpoint{ Properties: &armnetwork.PrivateEndpointProperties{ ManualPrivateLinkServiceConnections: []*armnetwork.PrivateLinkServiceConnection{ @@ -1007,7 +1007,7 @@ func TestExtractPrivateEndpointConnectionState(t *testing.T) { expected: "Pending", }, { - name: "When PE connection is rejected it should return Rejected", + name: "When PE connection is rejected, it should return Rejected", pe: armnetwork.PrivateEndpoint{ Properties: &armnetwork.PrivateEndpointProperties{ ManualPrivateLinkServiceConnections: []*armnetwork.PrivateLinkServiceConnection{ @@ -1024,14 +1024,14 @@ func TestExtractPrivateEndpointConnectionState(t *testing.T) { expected: "Rejected", }, { - name: "When PE properties is nil it should return empty string", + name: "When PE properties is nil, it should return empty string", pe: armnetwork.PrivateEndpoint{ Properties: nil, }, expected: "", }, { - name: "When ManualPrivateLinkServiceConnections is empty it should return empty string", + name: "When ManualPrivateLinkServiceConnections is empty, it should return empty string", pe: armnetwork.PrivateEndpoint{ Properties: &armnetwork.PrivateEndpointProperties{ ManualPrivateLinkServiceConnections: []*armnetwork.PrivateLinkServiceConnection{}, @@ -1040,7 +1040,7 @@ func TestExtractPrivateEndpointConnectionState(t *testing.T) { expected: "", }, { - name: "When connection has nil Properties it should return empty string", + name: "When connection has nil Properties, it should return empty string", pe: armnetwork.PrivateEndpoint{ Properties: &armnetwork.PrivateEndpointProperties{ ManualPrivateLinkServiceConnections: []*armnetwork.PrivateLinkServiceConnection{ @@ -2407,12 +2407,12 @@ func TestErrMsgQualifier(t *testing.T) { expected string }{ { - name: "When logPrefix is empty it should return empty string", + name: "When logPrefix is empty, it should return empty string", logPrefix: "", expected: "", }, { - name: "When logPrefix is set it should return prefix with trailing space", + name: "When logPrefix is set, it should return prefix with trailing space", logPrefix: "base domain", expected: "base domain ", }, diff --git a/control-plane-operator/controllers/azureprivatelinkservice/observer_test.go b/control-plane-operator/controllers/azureprivatelinkservice/observer_test.go index 8ca40590be5b..7ffd8a342651 100644 --- a/control-plane-operator/controllers/azureprivatelinkservice/observer_test.go +++ b/control-plane-operator/controllers/azureprivatelinkservice/observer_test.go @@ -29,17 +29,17 @@ func TestControllerName(t *testing.T) { expected string }{ { - name: "private-router service", + name: "When input is private-router, it should return private-router-observer", input: "private-router", expected: "private-router-observer", }, { - name: "custom service name", + name: "When input is custom service name, it should return custom name with observer suffix", input: "my-service", expected: "my-service-observer", }, { - name: "empty service name", + name: "When input is empty, it should return observer suffix only", input: "", expected: "-observer", }, @@ -208,7 +208,7 @@ func TestReconcile(t *testing.T) { expectPLSCreated: false, }, { - name: "When HCP has nil Azure platform it should return an error", + name: "When HCP has nil Azure platform, it should return an error", serviceName: testServiceName, requestName: testServiceName, service: defaultService(), @@ -221,7 +221,7 @@ func TestReconcile(t *testing.T) { expectPLSCreated: false, }, { - name: "When HCP has empty private connectivity type it should return an error", + name: "When HCP has empty private connectivity type, it should return an error", serviceName: testServiceName, requestName: testServiceName, service: defaultService(), diff --git a/control-plane-operator/controllers/gcpprivateserviceconnect/dns_test.go b/control-plane-operator/controllers/gcpprivateserviceconnect/dns_test.go index a6f2a706a021..455c27424077 100644 --- a/control-plane-operator/controllers/gcpprivateserviceconnect/dns_test.go +++ b/control-plane-operator/controllers/gcpprivateserviceconnect/dns_test.go @@ -19,32 +19,32 @@ func TestEnsureDNSDot(t *testing.T) { expected string }{ { - name: "When name has no trailing dot it should add one", + name: "When name has no trailing dot, it should add one", input: "example.com", expected: "example.com.", }, { - name: "When name already has trailing dot it should not add another", + name: "When name already has trailing dot, it should not add another", input: "example.com.", expected: "example.com.", }, { - name: "When name is empty it should add trailing dot", + name: "When name is empty, it should add trailing dot", input: "", expected: ".", }, { - name: "When name is just a dot it should remain a single dot", + name: "When name is just a dot, it should remain a single dot", input: ".", expected: ".", }, { - name: "When name has subdomain without dot it should add one", + name: "When name has subdomain without dot, it should add one", input: "api.cluster.hypershift.local", expected: "api.cluster.hypershift.local.", }, { - name: "When name has wildcard without dot it should add one", + name: "When name has wildcard without dot, it should add one", input: "*.apps.cluster.example.com", expected: "*.apps.cluster.example.com.", }, @@ -65,62 +65,62 @@ func TestIsNotFound(t *testing.T) { expected bool }{ { - name: "When error is googleapi 404 it should return true", + name: "When error is googleapi 404, it should return true", err: &googleapi.Error{Code: 404, Message: "not found"}, expected: true, }, { - name: "When error is googleapi 403 it should return false", + name: "When error is googleapi 403, it should return false", err: &googleapi.Error{Code: 403, Message: "forbidden"}, expected: false, }, { - name: "When error is googleapi 500 it should return false", + name: "When error is googleapi 500, it should return false", err: &googleapi.Error{Code: 500, Message: "internal error"}, expected: false, }, { - name: "When error is googleapi 400 it should return false", + name: "When error is googleapi 400, it should return false", err: &googleapi.Error{Code: 400, Message: "bad request"}, expected: false, }, { - name: "When error message contains 'error 404' it should return true", + name: "When error message contains 'error 404', it should return true", err: errors.New("error 404: resource not found"), expected: true, }, { - name: "When error message contains 'notfound' it should return true", + name: "When error message contains 'notfound', it should return true", err: errors.New("googleapi: Error 404: notfound"), expected: true, }, { - name: "When error message contains 'not found' it should return true", + name: "When error message contains 'not found', it should return true", err: errors.New("the resource was not found"), expected: true, }, { - name: "When error message contains 'NOT FOUND' in uppercase it should return true", + name: "When error message contains 'NOT FOUND' in uppercase, it should return true", err: errors.New("RESOURCE NOT FOUND"), expected: true, }, { - name: "When error is a wrapped googleapi 404 it should return true", + name: "When error is a wrapped googleapi 404, it should return true", err: fmt.Errorf("operation failed: %w", &googleapi.Error{Code: 404, Message: "not found"}), expected: true, }, { - name: "When error is a wrapped googleapi 500 it should return false", + name: "When error is a wrapped googleapi 500, it should return false", err: fmt.Errorf("operation failed: %w", &googleapi.Error{Code: 500, Message: "internal error"}), expected: false, }, { - name: "When error is generic without 404 it should return false", + name: "When error is generic without 404, it should return false", err: errors.New("connection timeout"), expected: false, }, { - name: "When error is permission denied it should return false", + name: "When error is permission denied, it should return false", err: errors.New("permission denied"), expected: false, }, @@ -142,37 +142,37 @@ func TestTruncateName(t *testing.T) { expected string }{ { - name: "When name is shorter than max it should not truncate", + name: "When name is shorter than max, it should not truncate", input: "short-name", maxLen: 63, expected: "short-name", }, { - name: "When name equals max length it should not truncate", + name: "When name equals max length, it should not truncate", input: "exactly-ten", maxLen: 11, expected: "exactly-ten", }, { - name: "When name exceeds max length it should truncate", + name: "When name exceeds max length, it should truncate", input: "this-is-a-very-long-name-that-exceeds-the-maximum-length-allowed", maxLen: 20, expected: "this-is-a-very-long-", }, { - name: "When max is 63 and name is 64 chars it should truncate to 63", + name: "When max is 63 and name is 64 chars, it should truncate to 63", input: "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", // 64 chars maxLen: 63, expected: "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", // 63 chars }, { - name: "When max is 0 it should return empty string", + name: "When max is 0, it should return empty string", input: "any-name", maxLen: 0, expected: "", }, { - name: "When name is empty it should return empty", + name: "When name is empty, it should return empty", input: "", maxLen: 63, expected: "", @@ -290,13 +290,13 @@ func TestValidateReconcileInput(t *testing.T) { errorContains string }{ { - name: "When all inputs are valid it should return nil", + name: "When all inputs are valid, it should return nil", hcp: validHCP, pscEndpointIP: "10.0.1.5", expectError: false, }, { - name: "When GCP platform spec is nil it should return error", + name: "When GCP platform spec is nil, it should return error", hcp: &hyperv1.HostedControlPlane{ Spec: hyperv1.HostedControlPlaneSpec{ Platform: hyperv1.PlatformSpec{ @@ -309,7 +309,7 @@ func TestValidateReconcileInput(t *testing.T) { errorContains: "GCP platform spec is nil", }, { - name: "When baseDomain is empty it should return error", + name: "When baseDomain is empty, it should return error", hcp: &hyperv1.HostedControlPlane{ Spec: hyperv1.HostedControlPlaneSpec{ Platform: hyperv1.PlatformSpec{ @@ -332,7 +332,7 @@ func TestValidateReconcileInput(t *testing.T) { errorContains: "DNS baseDomain is required", }, { - name: "When GCP project is empty it should return error", + name: "When GCP project is empty, it should return error", hcp: &hyperv1.HostedControlPlane{ Spec: hyperv1.HostedControlPlaneSpec{ Platform: hyperv1.PlatformSpec{ @@ -355,7 +355,7 @@ func TestValidateReconcileInput(t *testing.T) { errorContains: "GCP project is required", }, { - name: "When VPC network name is empty it should return error", + name: "When VPC network name is empty, it should return error", hcp: &hyperv1.HostedControlPlane{ Spec: hyperv1.HostedControlPlaneSpec{ Platform: hyperv1.PlatformSpec{ @@ -378,7 +378,7 @@ func TestValidateReconcileInput(t *testing.T) { errorContains: "VPC network name is required", }, { - name: "When PSC endpoint IP is empty it should return error", + name: "When PSC endpoint IP is empty, it should return error", hcp: validHCP, pscEndpointIP: "", expectError: true, @@ -457,57 +457,57 @@ func TestValidateZoneName(t *testing.T) { expectError bool }{ { - name: "When zone name starts with lowercase letter it should be valid", + name: "When zone name starts with lowercase letter, it should be valid", zoneName: "my-zone", expectError: false, }, { - name: "When zone name contains only lowercase letters it should be valid", + name: "When zone name contains only lowercase letters, it should be valid", zoneName: "myzone", expectError: false, }, { - name: "When zone name contains lowercase letters and numbers it should be valid", + name: "When zone name contains lowercase letters and numbers, it should be valid", zoneName: "my-zone-123", expectError: false, }, { - name: "When zone name contains hyphens it should be valid", + name: "When zone name contains hyphens, it should be valid", zoneName: "my-cluster-hypershift-local", expectError: false, }, { - name: "When zone name starts with 'in-' (managed service pattern) it should be valid", + name: "When zone name starts with 'in-' (managed service pattern), it should be valid", zoneName: "in-cluster-abc123-public", expectError: false, }, { - name: "When zone name starts with digit it should be invalid", + name: "When zone name starts with digit, it should be invalid", zoneName: "123-zone", expectError: true, }, { - name: "When zone name starts with hyphen it should be invalid", + name: "When zone name starts with hyphen, it should be invalid", zoneName: "-my-zone", expectError: true, }, { - name: "When zone name contains uppercase letters it should be invalid", + name: "When zone name contains uppercase letters, it should be invalid", zoneName: "My-Zone", expectError: true, }, { - name: "When zone name contains underscore it should be invalid", + name: "When zone name contains underscore, it should be invalid", zoneName: "my_zone", expectError: true, }, { - name: "When zone name contains dot it should be invalid", + name: "When zone name contains dot, it should be invalid", zoneName: "my.zone", expectError: true, }, { - name: "When zone name is empty it should be invalid", + name: "When zone name is empty, it should be invalid", zoneName: "", expectError: true, }, diff --git a/control-plane-operator/controllers/gcpprivateserviceconnect/observer_test.go b/control-plane-operator/controllers/gcpprivateserviceconnect/observer_test.go index 9bcc2282e6e7..e5392947324a 100644 --- a/control-plane-operator/controllers/gcpprivateserviceconnect/observer_test.go +++ b/control-plane-operator/controllers/gcpprivateserviceconnect/observer_test.go @@ -27,17 +27,17 @@ func TestControllerName(t *testing.T) { expected string }{ { - name: "private-router service", + name: "When input is private-router, it should return private-router-observer", input: "private-router", expected: "private-router-observer", }, { - name: "custom service name", + name: "When input is custom service name, it should return custom name with observer suffix", input: "my-service", expected: "my-service-observer", }, { - name: "empty service name", + name: "When input is empty, it should return observer suffix only", input: "", expected: "-observer", }, @@ -59,7 +59,7 @@ func TestGetConsumerAcceptList(t *testing.T) { expected []string }{ { - name: "valid GCP platform with project", + name: "When GCP platform has valid project, it should return project in list", hcp: &hyperv1.HostedControlPlane{ Spec: hyperv1.HostedControlPlaneSpec{ Platform: hyperv1.PlatformSpec{ @@ -73,7 +73,7 @@ func TestGetConsumerAcceptList(t *testing.T) { expected: []string{"my-gcp-project"}, }, { - name: "project with numeric project ID", + name: "When GCP platform has numeric project ID, it should return it in list", hcp: &hyperv1.HostedControlPlane{ Spec: hyperv1.HostedControlPlaneSpec{ Platform: hyperv1.PlatformSpec{ @@ -109,7 +109,7 @@ func TestReconcileIntegration(t *testing.T) { expectGCPPSCCreated bool }{ { - name: "When reconciling target service it should create GCPPrivateServiceConnect CR", + name: "When reconciling target service, it should create GCPPrivateServiceConnect CR", serviceName: "private-router", requestName: "private-router", service: &corev1.Service{ @@ -154,7 +154,7 @@ func TestReconcileIntegration(t *testing.T) { expectGCPPSCCreated: true, }, { - name: "When reconciling non-target service it should skip processing", + name: "When reconciling non-target service, it should skip processing", serviceName: "private-router", requestName: "other-service", service: &corev1.Service{ @@ -178,7 +178,7 @@ func TestReconcileIntegration(t *testing.T) { expectGCPPSCCreated: false, }, { - name: "When service has no LoadBalancer IP it should skip processing", + name: "When service has no LoadBalancer IP, it should skip processing", serviceName: "private-router", requestName: "private-router", service: &corev1.Service{ @@ -200,7 +200,7 @@ func TestReconcileIntegration(t *testing.T) { expectGCPPSCCreated: false, }, { - name: "When service is External LoadBalancer it should skip processing", + name: "When service is External LoadBalancer, it should skip processing", serviceName: "private-router", requestName: "private-router", service: &corev1.Service{ diff --git a/control-plane-operator/controllers/gcpprivateserviceconnect/psc_endpoint_controller_test.go b/control-plane-operator/controllers/gcpprivateserviceconnect/psc_endpoint_controller_test.go index 70641acdc819..a80bc299a341 100644 --- a/control-plane-operator/controllers/gcpprivateserviceconnect/psc_endpoint_controller_test.go +++ b/control-plane-operator/controllers/gcpprivateserviceconnect/psc_endpoint_controller_test.go @@ -34,7 +34,7 @@ func TestConstructEndpointName(t *testing.T) { expected string }{ { - name: "When constructing endpoint name it should use service attachment name with endpoint suffix", + name: "When constructing endpoint name, it should use service attachment name with endpoint suffix", gcpPSC: &hyperv1.GCPPrivateServiceConnect{ Status: hyperv1.GCPPrivateServiceConnectStatus{ ServiceAttachmentName: "private-router-4bcf17df-cveiga-test-3-psc-sa", @@ -43,7 +43,7 @@ func TestConstructEndpointName(t *testing.T) { expected: "private-router-4bcf17df-cveiga-test-3-psc-sa-endpoint", }, { - name: "When service attachment name is short it should append endpoint suffix", + name: "When service attachment name is short, it should append endpoint suffix", gcpPSC: &hyperv1.GCPPrivateServiceConnect{ Status: hyperv1.GCPPrivateServiceConnectStatus{ ServiceAttachmentName: "test-sa", @@ -70,7 +70,7 @@ func TestConstructIPAddressName(t *testing.T) { expected string }{ { - name: "When constructing IP name it should use service attachment name with ip suffix", + name: "When constructing IP name, it should use service attachment name with ip suffix", gcpPSC: &hyperv1.GCPPrivateServiceConnect{ Status: hyperv1.GCPPrivateServiceConnectStatus{ ServiceAttachmentName: "private-router-4bcf17df-cveiga-test-3-psc-sa", @@ -79,7 +79,7 @@ func TestConstructIPAddressName(t *testing.T) { expected: "private-router-4bcf17df-cveiga-test-3-psc-sa-ip", }, { - name: "When service attachment name is short it should append ip suffix", + name: "When service attachment name is short, it should append ip suffix", gcpPSC: &hyperv1.GCPPrivateServiceConnect{ Status: hyperv1.GCPPrivateServiceConnectStatus{ ServiceAttachmentName: "test-sa", @@ -133,21 +133,21 @@ func TestConstructAddressURL(t *testing.T) { expected string }{ { - name: "When constructing address URL it should include project, region, and name", + name: "When constructing address URL, it should include project, region, and name", addressName: "clusters-test-cluster-1-private-router-psc-endpoint-ip", customerProject: "customer-project-123", region: "us-central1", expected: "projects/customer-project-123/regions/us-central1/addresses/clusters-test-cluster-1-private-router-psc-endpoint-ip", }, { - name: "When using different region it should construct correctly", + name: "When using different region, it should construct correctly", addressName: "test-address", customerProject: "my-gcp-project", region: "europe-west1", expected: "projects/my-gcp-project/regions/europe-west1/addresses/test-address", }, { - name: "When using numeric project ID it should work", + name: "When using numeric project ID, it should work", addressName: "my-psc-ip", customerProject: "123456789", region: "asia-southeast1", @@ -172,7 +172,7 @@ func TestIsServiceAttachmentReady(t *testing.T) { expected bool }{ { - name: "When ServiceAttachmentURI is empty it should return false", + name: "When ServiceAttachmentURI is empty, it should return false", gcpPSC: &hyperv1.GCPPrivateServiceConnect{ Status: hyperv1.GCPPrivateServiceConnectStatus{ ServiceAttachmentURI: "", @@ -182,7 +182,7 @@ func TestIsServiceAttachmentReady(t *testing.T) { expected: false, }, { - name: "When ServiceAttachmentName is empty it should return false", + name: "When ServiceAttachmentName is empty, it should return false", gcpPSC: &hyperv1.GCPPrivateServiceConnect{ Status: hyperv1.GCPPrivateServiceConnectStatus{ ServiceAttachmentURI: "projects/mgmt-project/regions/us-central1/serviceAttachments/test-sa", @@ -192,7 +192,7 @@ func TestIsServiceAttachmentReady(t *testing.T) { expected: false, }, { - name: "When both URI and Name exist but condition is missing it should return false", + name: "When both URI and Name exist but condition is missing, it should return false", gcpPSC: &hyperv1.GCPPrivateServiceConnect{ Status: hyperv1.GCPPrivateServiceConnectStatus{ ServiceAttachmentURI: "projects/mgmt-project/regions/us-central1/serviceAttachments/test-sa", @@ -202,7 +202,7 @@ func TestIsServiceAttachmentReady(t *testing.T) { expected: false, }, { - name: "When both URI and Name exist but condition is False it should return false", + name: "When both URI and Name exist but condition is False, it should return false", gcpPSC: &hyperv1.GCPPrivateServiceConnect{ Status: hyperv1.GCPPrivateServiceConnectStatus{ ServiceAttachmentURI: "projects/mgmt-project/regions/us-central1/serviceAttachments/test-sa", @@ -218,7 +218,7 @@ func TestIsServiceAttachmentReady(t *testing.T) { expected: false, }, { - name: "When both URI and Name exist and condition is True it should return true", + name: "When both URI and Name exist and condition is True, it should return true", gcpPSC: &hyperv1.GCPPrivateServiceConnect{ Status: hyperv1.GCPPrivateServiceConnectStatus{ ServiceAttachmentURI: "projects/mgmt-project/regions/us-central1/serviceAttachments/test-sa", @@ -250,32 +250,32 @@ func TestIsNotFoundError(t *testing.T) { expected bool }{ { - name: "When given nil error it should return false", + name: "When given nil error, it should return false", err: nil, expected: false, }, { - name: "When given non-GCP error it should return false", + name: "When given non-GCP error, it should return false", err: assert.AnError, expected: false, }, { - name: "When given a GCP 404 error it should return true", + name: "When given a GCP 404 error, it should return true", err: &googleapi.Error{Code: 404, Message: "not found"}, expected: true, }, { - name: "When given a GCP 500 error it should return false", + name: "When given a GCP 500 error, it should return false", err: &googleapi.Error{Code: 500, Message: "internal error"}, expected: false, }, { - name: "When given a wrapped GCP 404 error it should return true", + name: "When given a wrapped GCP 404 error, it should return true", err: fmt.Errorf("operation failed: %w", &googleapi.Error{Code: 404, Message: "not found"}), expected: true, }, { - name: "When given a wrapped GCP 500 error it should return false", + name: "When given a wrapped GCP 500 error, it should return false", err: fmt.Errorf("operation failed: %w", &googleapi.Error{Code: 500, Message: "internal error"}), expected: false, }, @@ -372,7 +372,7 @@ func TestHCPExternalNamesGCP(t *testing.T) { expected map[string]string }{ { - name: "When no external hostnames are configured it should return empty map", + name: "When no external hostnames are configured, it should return empty map", hcp: &hyperv1.HostedControlPlane{ Spec: hyperv1.HostedControlPlaneSpec{ Services: []hyperv1.ServicePublishingStrategyMapping{}, @@ -381,7 +381,7 @@ func TestHCPExternalNamesGCP(t *testing.T) { expected: map[string]string{}, }, { - name: "When API server has Route hostname it should return api entry", + name: "When API server has Route hostname, it should return api entry", hcp: &hyperv1.HostedControlPlane{ Spec: hyperv1.HostedControlPlaneSpec{ Services: []hyperv1.ServicePublishingStrategyMapping{ @@ -402,7 +402,7 @@ func TestHCPExternalNamesGCP(t *testing.T) { }, }, { - name: "When OAuth server has Route hostname it should return oauth entry", + name: "When OAuth server has Route hostname, it should return oauth entry", hcp: &hyperv1.HostedControlPlane{ Spec: hyperv1.HostedControlPlaneSpec{ Services: []hyperv1.ServicePublishingStrategyMapping{ @@ -423,7 +423,7 @@ func TestHCPExternalNamesGCP(t *testing.T) { }, }, { - name: "When both API and OAuth have Route hostnames it should return both entries", + name: "When both API and OAuth have Route hostnames, it should return both entries", hcp: &hyperv1.HostedControlPlane{ Spec: hyperv1.HostedControlPlaneSpec{ Services: []hyperv1.ServicePublishingStrategyMapping{ @@ -454,7 +454,7 @@ func TestHCPExternalNamesGCP(t *testing.T) { }, }, { - name: "When API server uses LoadBalancer type it should return empty map", + name: "When API server uses LoadBalancer type, it should return empty map", hcp: &hyperv1.HostedControlPlane{ Spec: hyperv1.HostedControlPlaneSpec{ Services: []hyperv1.ServicePublishingStrategyMapping{ @@ -470,7 +470,7 @@ func TestHCPExternalNamesGCP(t *testing.T) { expected: map[string]string{}, }, { - name: "When Route has no hostname it should return empty map", + name: "When Route has no hostname, it should return empty map", hcp: &hyperv1.HostedControlPlane{ Spec: hyperv1.HostedControlPlaneSpec{ Services: []hyperv1.ServicePublishingStrategyMapping{ @@ -609,25 +609,25 @@ func TestNameserverTrailingDotTrimming(t *testing.T) { description string }{ { - name: "When nameservers have trailing dots they should be removed", + name: "When nameservers have trailing dots, it should remove them", nameservers: []string{"ns-cloud-c1.googledomains.com.", "ns-cloud-c2.googledomains.com."}, expected: []string{"ns-cloud-c1.googledomains.com", "ns-cloud-c2.googledomains.com"}, description: "GCP Cloud DNS returns nameservers with trailing dots but external-dns rejects them", }, { - name: "When nameservers have no trailing dots they should remain unchanged", + name: "When nameservers have no trailing dots, it should leave them unchanged", nameservers: []string{"ns1.example.com", "ns2.example.com"}, expected: []string{"ns1.example.com", "ns2.example.com"}, description: "Already in correct format for external-dns", }, { - name: "When nameservers list is empty it should return empty", + name: "When nameservers list is empty, it should return empty", nameservers: []string{}, expected: []string{}, description: "Edge case: empty nameserver list", }, { - name: "When mixed trailing dots present only those with dots should be trimmed", + name: "When mixed trailing dots present, it should trim only those with dots", nameservers: []string{"ns1.example.com.", "ns2.example.com"}, expected: []string{"ns1.example.com", "ns2.example.com"}, description: "Mixed case with some trailing dots", @@ -658,7 +658,7 @@ func TestDNSEndpointNaming(t *testing.T) { expectedName: "test-cluster-123-ingress-delegation", }, { - name: "When HCP name is long the full name should be used", + name: "When HCP name is long, it should use the full name", hcpName: "very-long-hosted-control-plane-name", expectedName: "very-long-hosted-control-plane-name-ingress-delegation", }, @@ -684,7 +684,7 @@ func TestDNSEndpointNameserverFormat(t *testing.T) { description string }{ { - name: "When nameservers are GCP Cloud DNS format they should be valid", + name: "When nameservers are GCP Cloud DNS format, it should accept them as valid", nameservers: []string{ "ns-cloud-a1.googledomains.com.", "ns-cloud-a2.googledomains.com.", @@ -694,7 +694,7 @@ func TestDNSEndpointNameserverFormat(t *testing.T) { description: "Standard GCP Cloud DNS nameserver format with trailing dots", }, { - name: "When nameservers are custom they should be accepted", + name: "When nameservers are custom, it should accept them", nameservers: []string{ "ns1.custom-dns.example.com", "ns2.custom-dns.example.com", @@ -725,7 +725,7 @@ func TestDNSEndpointErrorHandling(t *testing.T) { description string }{ { - name: "When DNSEndpoint CRD is not installed reconciliation should continue", + name: "When DNSEndpoint CRD is not installed, it should continue reconciliation", err: &apierrors.StatusError{ ErrStatus: metav1.Status{ Reason: metav1.StatusReasonNotFound, @@ -738,27 +738,27 @@ func TestDNSEndpointErrorHandling(t *testing.T) { description: "CRD not found - best-effort operation, continue PSC reconciliation", }, { - name: "When error mentions no matches for kind reconciliation should continue", + name: "When error mentions no matches for kind, it should continue reconciliation", err: errors.New("no matches for kind \"DNSEndpoint\" in version \"externaldns.k8s.io/v1alpha1\""), description: "Schema/kind match error - best-effort operation, continue PSC reconciliation", }, { - name: "When error is validation webhook failure reconciliation should continue", + name: "When error is validation webhook failure, it should continue reconciliation", err: errors.New("admission webhook denied the request: invalid DNSEndpoint"), description: "Validation webhook error - best-effort operation, continue PSC reconciliation", }, { - name: "When error is permission denied reconciliation should continue", + name: "When error is permission denied, it should continue reconciliation", err: errors.New("forbidden: user cannot create resource \"dnsendpoints\""), description: "Permission error - best-effort operation, continue PSC reconciliation", }, { - name: "When error is generic API error reconciliation should continue", + name: "When error is generic API error, it should continue reconciliation", err: errors.New("failed to connect to API server"), description: "API connectivity error - best-effort operation, continue PSC reconciliation", }, { - name: "When error is timeout reconciliation should continue", + name: "When error is timeout, it should continue reconciliation", err: errors.New("context deadline exceeded"), description: "Timeout error - best-effort operation, continue PSC reconciliation", }, diff --git a/control-plane-operator/controllers/hostedcontrolplane/creatorupdate_ownerref_enforcer_test.go b/control-plane-operator/controllers/hostedcontrolplane/creatorupdate_ownerref_enforcer_test.go index c2518721e998..46a3a180c144 100644 --- a/control-plane-operator/controllers/hostedcontrolplane/creatorupdate_ownerref_enforcer_test.go +++ b/control-plane-operator/controllers/hostedcontrolplane/creatorupdate_ownerref_enforcer_test.go @@ -28,7 +28,7 @@ func TestCreateOrUpdateWithOwnerRefFactory(t *testing.T) { mutateFN func(crclient.Object) controllerutil.MutateFn }{ { - name: "Owner ref is added", + name: "When creating an object, it should add the owner reference", obj: &corev1.ConfigMap{ ObjectMeta: metav1.ObjectMeta{ Name: "foo", @@ -38,7 +38,7 @@ func TestCreateOrUpdateWithOwnerRefFactory(t *testing.T) { expected: []metav1.OwnerReference{*ownerRef.Reference}, }, { - name: "Adding takes precedence", + name: "When mutate function clears owner refs, it should still add the owner reference", obj: &corev1.ConfigMap{ ObjectMeta: metav1.ObjectMeta{ Name: "foo", @@ -54,7 +54,7 @@ func TestCreateOrUpdateWithOwnerRefFactory(t *testing.T) { expected: []metav1.OwnerReference{*ownerRef.Reference}, }, { - name: "Do not add ownerRef to cluster scoped resources", + name: "When object is cluster scoped it should not add owner reference", obj: &corev1.Namespace{ ObjectMeta: metav1.ObjectMeta{ Name: "foo", diff --git a/control-plane-operator/controllers/hostedcontrolplane/hostedcontrolplane_controller_test.go b/control-plane-operator/controllers/hostedcontrolplane/hostedcontrolplane_controller_test.go index 566db12edcc5..d1e87d440db9 100644 --- a/control-plane-operator/controllers/hostedcontrolplane/hostedcontrolplane_controller_test.go +++ b/control-plane-operator/controllers/hostedcontrolplane/hostedcontrolplane_controller_test.go @@ -96,7 +96,7 @@ func TestReconcileKubeadminPassword(t *testing.T) { expectedOutputSecret *corev1.Secret }{ { - name: "When OAuth config specified results in no kubeadmin secret", + name: "When OAuth config is specified it should not create kubeadmin secret", hcp: &hyperv1.HostedControlPlane{ TypeMeta: metav1.TypeMeta{}, ObjectMeta: metav1.ObjectMeta{ @@ -134,7 +134,7 @@ func TestReconcileKubeadminPassword(t *testing.T) { expectedOutputSecret: nil, }, { - name: "When Oauth config not specified results in default kubeadmin secret", + name: "When OAuth config is not specified it should create default kubeadmin secret", hcp: &hyperv1.HostedControlPlane{ ObjectMeta: metav1.ObjectMeta{ Namespace: targetNamespace, @@ -248,13 +248,13 @@ func TestReconcileIgnitionServer(t *testing.T) { servingCert *corev1.Secret }{ { - name: "No certs, no extra annotations", + name: "When no certs or extra annotations exist it should reconcile successfully", annotations: map[string]string{}, caCert: nil, servingCert: nil, }, { - name: "Premade certs, DisablePKIReconciliation annotation present", + name: "When premade certs exist with DisablePKIReconciliation annotation it should preserve them", annotations: map[string]string{ hyperv1.DisablePKIReconciliationAnnotation: "true", }, @@ -280,7 +280,7 @@ func TestReconcileIgnitionServer(t *testing.T) { }, }, { - name: "No certs, DisablePKIReconciliation annotation present", + name: "When no certs exist with DisablePKIReconciliation annotation it should skip cert creation", annotations: map[string]string{ hyperv1.DisablePKIReconciliationAnnotation: "true", }, @@ -377,7 +377,7 @@ func TestEtcdRestoredCondition(t *testing.T) { expectedCondition metav1.Condition }{ { - name: "single replica, pod ready - condition true", + name: "When single replica pod is ready it should return condition true", sts: &appsv1.StatefulSet{ ObjectMeta: metav1.ObjectMeta{ Name: "etcd", @@ -417,7 +417,7 @@ func TestEtcdRestoredCondition(t *testing.T) { }, }, { - name: "Pod not ready - condition false", + name: "When pod is not ready it should return condition false", sts: &appsv1.StatefulSet{ ObjectMeta: metav1.ObjectMeta{ Name: "etcd", @@ -463,7 +463,7 @@ func TestEtcdRestoredCondition(t *testing.T) { }, }, { - name: "multiple replica, pods ready - condition true", + name: "When multiple replica pods are ready it should return condition true", sts: &appsv1.StatefulSet{ ObjectMeta: metav1.ObjectMeta{ Name: "etcd", @@ -927,12 +927,12 @@ func TestIncludeServingCertificates(t *testing.T) { expectError bool }{ { - name: "APIServer servingCerts is nil", + name: "When APIServer servingCerts is empty it should return only root CA cert", servingCerts: &configv1.APIServerServingCerts{}, expectedCert: "root-ca-cert", }, { - name: "APIServer servingCerts configuration with one named certificates", + name: "When APIServer has one named certificate it should append it to root CA", servingCerts: &configv1.APIServerServingCerts{ NamedCertificates: []configv1.APIServerNamedServingCert{ { @@ -956,7 +956,7 @@ func TestIncludeServingCertificates(t *testing.T) { expectedCert: "root-ca-cert\ncert-1", }, { - name: "APIServer servingCerts configuration with multiple named certificates", + name: "When APIServer has multiple named certificates it should append all to root CA", servingCerts: &configv1.APIServerServingCerts{ NamedCertificates: []configv1.APIServerNamedServingCert{ { @@ -994,7 +994,7 @@ func TestIncludeServingCertificates(t *testing.T) { expectedCert: "root-ca-cert\ncert-1\ncert-2", }, { - name: "APIServer servingCerts configuration with missing named certificate", + name: "When APIServer has missing named certificate, it should return error", servingCerts: &configv1.APIServerServingCerts{ NamedCertificates: []configv1.APIServerNamedServingCert{ { @@ -1057,27 +1057,27 @@ func TestControlPlaneComponents(t *testing.T) { subDirSuffix string }{ { - name: "Default feature set, default platform type", + name: "When using default feature set and platform type it should reconcile components", featureSet: configv1.Default, platformType: nil, }, { - name: "TechPreviewNoUpgrade feature set, default platform type", + name: "When using TechPreviewNoUpgrade feature set it should reconcile components", featureSet: configv1.TechPreviewNoUpgrade, platformType: nil, }, { - name: "Default feature set, IBM Cloud platform type", + name: "When using IBM Cloud platform type it should reconcile components", featureSet: configv1.Default, platformType: ptr.To(hyperv1.IBMCloudPlatform), }, { - name: "TechPreviewNoUpgrade feature set, GCP platform type", + name: "When using TechPreviewNoUpgrade with GCP platform it should reconcile components", featureSet: configv1.TechPreviewNoUpgrade, platformType: ptr.To(hyperv1.GCPPlatform), }, { - name: "Default feature set, Azure platform with ARO Swift", + name: "When using Azure platform with ARO Swift, it should reconcile components", featureSet: configv1.Default, platformType: ptr.To(hyperv1.AzurePlatform), hcpAnnotations: map[string]string{ @@ -1141,7 +1141,7 @@ func TestControlPlaneComponents(t *testing.T) { subDirSuffix: "AROSwift", }, { - name: "Default feature set, Modern TLS profile", + name: "When using Modern TLS profile it should reconcile components", featureSet: configv1.Default, platformType: nil, mutateHCP: func(hcp *hyperv1.HostedControlPlane) { @@ -1366,7 +1366,7 @@ func TestAWSSecurityGroupTags(t *testing.T) { expectedTags map[string]string }{ { - name: "No additional tags, no AutoNode", + name: "When no additional tags or AutoNode exist it should return default tags", hcp: &hyperv1.HostedControlPlane{ Spec: hyperv1.HostedControlPlaneSpec{ InfraID: "test-infra", @@ -1383,7 +1383,7 @@ func TestAWSSecurityGroupTags(t *testing.T) { }, }, { - name: "Additional tags override Name and cluster key", + name: "When additional tags override defaults it should use custom values", hcp: &hyperv1.HostedControlPlane{ Spec: hyperv1.HostedControlPlaneSpec{ InfraID: "myinfra", @@ -1405,7 +1405,7 @@ func TestAWSSecurityGroupTags(t *testing.T) { }, }, { - name: "AutoNode with Karpenter AWS adds karpenter.sh/discovery", + name: "When AutoNode uses Karpenter AWS it should add discovery tag", hcp: &hyperv1.HostedControlPlane{ Spec: hyperv1.HostedControlPlaneSpec{ InfraID: "karpenter-infra", @@ -1871,7 +1871,7 @@ func TestRemoveHCPIngressFromRoutes(t *testing.T) { }, }, { - name: "Route with HCPRouteLabel is skipped", + name: "When route has HCPRouteLabel it should skip processing", hcp: &hyperv1.HostedControlPlane{ ObjectMeta: metav1.ObjectMeta{ Name: "hcp", @@ -1914,7 +1914,7 @@ func TestRemoveHCPIngressFromRoutes(t *testing.T) { }, }, { - name: "Route without HCPRouteLabel has router ingress removed", + name: "When route has no HCPRouteLabel it should remove router ingress", hcp: &hyperv1.HostedControlPlane{ ObjectMeta: metav1.ObjectMeta{ Name: "hcp", @@ -1950,7 +1950,7 @@ func TestRemoveHCPIngressFromRoutes(t *testing.T) { }, }, { - name: "Route without router ingress is unchanged", + name: "When route has no router ingress it should remain unchanged", hcp: &hyperv1.HostedControlPlane{ ObjectMeta: metav1.ObjectMeta{ Name: "hcp", @@ -1987,7 +1987,7 @@ func TestRemoveHCPIngressFromRoutes(t *testing.T) { }, }, { - name: "Route with only router ingress has all ingress removed", + name: "When route has only router ingress it should remove all ingress", hcp: &hyperv1.HostedControlPlane{ ObjectMeta: metav1.ObjectMeta{ Name: "hcp", @@ -2020,7 +2020,7 @@ func TestRemoveHCPIngressFromRoutes(t *testing.T) { }, }, { - name: "Multiple routes handled correctly", + name: "When multiple routes exist it should handle each correctly", hcp: &hyperv1.HostedControlPlane{ ObjectMeta: metav1.ObjectMeta{ Name: "hcp", @@ -2106,7 +2106,7 @@ func TestRemoveHCPIngressFromRoutes(t *testing.T) { }, }, { - name: "Route with empty ingress list is unchanged", + name: "When route has empty ingress list it should remain unchanged", hcp: &hyperv1.HostedControlPlane{ ObjectMeta: metav1.ObjectMeta{ Name: "hcp", @@ -2137,7 +2137,7 @@ func TestRemoveHCPIngressFromRoutes(t *testing.T) { }, }, { - name: "Route with multiple router ingress entries removes all", + name: "When route has multiple router ingress entries it should remove all", hcp: &hyperv1.HostedControlPlane{ ObjectMeta: metav1.ObjectMeta{ Name: "hcp", @@ -4356,7 +4356,7 @@ func TestReconcileDeletion(t *testing.T) { wantCondStatus: metav1.ConditionFalse, }, { - name: "When DescribeSecurityGroups returns InvalidIdentityToken it should extract the error code and skip gracefully", + name: "When DescribeSecurityGroups returns InvalidIdentityToken, it should extract the error code and skip gracefully", setupEC2Mock: func(mockCtrl *gomock.Controller) *awsapi.MockEC2API { m := awsapi.NewMockEC2API(mockCtrl) m.EXPECT().DescribeSecurityGroups(gomock.Any(), gomock.Any()).Return(nil, diff --git a/control-plane-operator/controllers/hostedcontrolplane/infra/infra_test.go b/control-plane-operator/controllers/hostedcontrolplane/infra/infra_test.go index aaf0665d5832..f3a476468daa 100644 --- a/control-plane-operator/controllers/hostedcontrolplane/infra/infra_test.go +++ b/control-plane-operator/controllers/hostedcontrolplane/infra/infra_test.go @@ -356,7 +356,7 @@ func TestReconcileInfrastructure(t *testing.T) { expectedStatus *InfrastructureStatus }{ { - name: "AWS_Public_Route", + name: "When AWS public cluster uses Route, it should configure external router", hcp: withServices( withAWSEndpointAccess(baseAWSHCP(), hyperv1.Public), allServicesRouteWithHostnames(), @@ -379,7 +379,7 @@ func TestReconcileInfrastructure(t *testing.T) { }, }, { - name: "AWS_Private_Route", + name: "When AWS private cluster uses Route, it should configure internal router", hcp: withServices( withAWSEndpointAccess(baseAWSHCP(), hyperv1.Private), allServicesRouteWithHostnames(), @@ -403,7 +403,7 @@ func TestReconcileInfrastructure(t *testing.T) { }, }, { - name: "AWS_PublicAndPrivate_Route", + name: "When AWS public and private cluster uses Route, it should configure both routers", hcp: withServices( withAWSEndpointAccess(baseAWSHCP(), hyperv1.PublicAndPrivate), allServicesRouteWithHostnames(), @@ -428,7 +428,7 @@ func TestReconcileInfrastructure(t *testing.T) { { // With LabelHCPRoutes logic: Public + KAS LoadBalancer = routes NOT labeled, // so no external HCP router is needed. - name: "AWS_Public_KAS_LoadBalancer", + name: "When AWS public cluster uses KAS LoadBalancer, it should not need external router", hcp: withServices( withAWSEndpointAccess(baseAWSHCP(), hyperv1.Public), kasServiceLoadBalancerOthersRoute(), @@ -451,7 +451,7 @@ func TestReconcileInfrastructure(t *testing.T) { }, }, { - name: "AWS_Private_KAS_LoadBalancer", + name: "When AWS private cluster uses KAS LoadBalancer, it should configure internal router", hcp: withServices( withAWSEndpointAccess(baseAWSHCP(), hyperv1.Private), kasServiceLoadBalancerOthersRoute(), @@ -474,7 +474,7 @@ func TestReconcileInfrastructure(t *testing.T) { }, }, { - name: "AWS_PublicAndPrivate_KAS_LoadBalancer", + name: "When AWS public and private cluster uses KAS LoadBalancer, it should configure internal router only", hcp: withServices( withAWSEndpointAccess(baseAWSHCP(), hyperv1.PublicAndPrivate), kasServiceLoadBalancerOthersRoute(), @@ -531,7 +531,7 @@ func TestReconcileInfrastructure(t *testing.T) { }, }, { - name: "Azure_Private_KAS_LoadBalancer", + name: "When Azure private cluster uses KAS LoadBalancer, it should configure internal router", hcp: withServices( withAzureTopology(baseAzureHCP(), hyperv1.AzureTopologyPrivate), kasServiceLoadBalancerOthersRoute(), @@ -555,7 +555,7 @@ func TestReconcileInfrastructure(t *testing.T) { }, }, { - name: "Azure_Private_OAuth_LoadBalancer", + name: "When Azure private cluster uses OAuth LoadBalancer, it should configure internal router", hcp: withServices( withAzureTopology(baseAzureHCP(), hyperv1.AzureTopologyPrivate), oauthServiceLoadBalancerOthersRoute(), @@ -581,7 +581,7 @@ func TestReconcileInfrastructure(t *testing.T) { }, // ARO HCP test cases - use shared ingress { - name: "ARO_Route_SharedIngress_AnnotationFallback", + name: "When ARO cluster uses shared ingress with annotation fallback, it should use direct hostname without routers", hcp: func() *hyperv1.HostedControlPlane { hcp := withServices(baseAzureHCP(), allServicesRouteWithHostnames()) hcp.Annotations = map[string]string{ @@ -613,7 +613,7 @@ func TestReconcileInfrastructure(t *testing.T) { }, }, { - name: "ARO_Route_Swift_PublicAndPrivate", + name: "When ARO cluster uses Swift with public and private topology, it should use shared ingress", hcp: func() *hyperv1.HostedControlPlane { hcp := withServices(baseAzureHCP(), allServicesRouteWithHostnames()) hcp.Spec.Platform.Azure.Topology = hyperv1.AzureTopologyPublicAndPrivate @@ -644,7 +644,7 @@ func TestReconcileInfrastructure(t *testing.T) { }, }, { - name: "ARO_Route_Swift_Private", + name: "When ARO cluster uses Swift with private topology, it should not need routers", hcp: func() *hyperv1.HostedControlPlane { hcp := withServices(baseAzureHCP(), allServicesRouteWithHostnames()) hcp.Annotations = map[string]string{ @@ -1115,7 +1115,7 @@ func TestReconcileOAuthService(t *testing.T) { expectedRoutes []routev1.Route }{ { - name: "Route strategy, Public", + name: "When public cluster uses OAuth Route, it should create ClusterIP service and public route", endpointAccess: hyperv1.Public, oauthPublishingStrategy: hyperv1.ServicePublishingStrategy{ Type: hyperv1.Route, @@ -1133,7 +1133,7 @@ func TestReconcileOAuthService(t *testing.T) { }, }, { - name: "Route strategy, PublicPrivate", + name: "When public and private cluster uses OAuth Route, it should create both public and internal routes", endpointAccess: hyperv1.PublicAndPrivate, oauthPublishingStrategy: hyperv1.ServicePublishingStrategy{ Type: hyperv1.Route, @@ -1153,7 +1153,7 @@ func TestReconcileOAuthService(t *testing.T) { }, }, { - name: "Route strategy, PublicPrivate, no hostname", + name: "When public and private cluster uses OAuth Route without hostname, it should create unlabeled external route", endpointAccess: hyperv1.PublicAndPrivate, oauthPublishingStrategy: hyperv1.ServicePublishingStrategy{ Type: hyperv1.Route, @@ -1174,7 +1174,7 @@ func TestReconcileOAuthService(t *testing.T) { }, }, { - name: "Route strategy, Private", + name: "When private cluster uses OAuth Route, it should create internal route only", endpointAccess: hyperv1.Private, oauthPublishingStrategy: hyperv1.ServicePublishingStrategy{ Type: hyperv1.Route, @@ -1406,7 +1406,7 @@ func TestReconcileAPIServerService(t *testing.T) { expectedRoutes []routev1.Route }{ { - name: "LB strategy, public", + name: "When public cluster uses LoadBalancer, it should create public LB service", endpointAccess: hyperv1.Public, apiPublishingStrategy: hyperv1.ServicePublishingStrategy{ Type: hyperv1.LoadBalancer, @@ -1420,7 +1420,7 @@ func TestReconcileAPIServerService(t *testing.T) { }, }, { - name: "LB strategy, publicPrivate", + name: "When public and private cluster uses LoadBalancer, it should create both public and private LB services", endpointAccess: hyperv1.PublicAndPrivate, apiPublishingStrategy: hyperv1.ServicePublishingStrategy{ Type: hyperv1.LoadBalancer, @@ -1435,7 +1435,7 @@ func TestReconcileAPIServerService(t *testing.T) { }, }, { - name: "LB strategy, private", + name: "When private cluster uses LoadBalancer, it should create ClusterIP and private LB services", endpointAccess: hyperv1.Private, apiPublishingStrategy: hyperv1.ServicePublishingStrategy{ Type: hyperv1.LoadBalancer, @@ -1454,7 +1454,7 @@ func TestReconcileAPIServerService(t *testing.T) { }, }, { - name: "Route strategy, public", + name: "When public cluster uses Route, it should create ClusterIP service and routes", endpointAccess: hyperv1.Public, apiPublishingStrategy: hyperv1.ServicePublishingStrategy{ Type: hyperv1.Route, @@ -1476,7 +1476,7 @@ func TestReconcileAPIServerService(t *testing.T) { }, }, { - name: "Route strategy, publicPrivate", + name: "When public and private cluster uses Route, it should create ClusterIP service and routes", endpointAccess: hyperv1.PublicAndPrivate, apiPublishingStrategy: hyperv1.ServicePublishingStrategy{ Type: hyperv1.Route, @@ -1498,7 +1498,7 @@ func TestReconcileAPIServerService(t *testing.T) { }, }, { - name: "Route strategy, private", + name: "When private cluster uses Route, it should create ClusterIP service and private routes", endpointAccess: hyperv1.Private, apiPublishingStrategy: hyperv1.ServicePublishingStrategy{ Type: hyperv1.Route, @@ -1664,7 +1664,7 @@ func TestReconcileHCPRouterServices(t *testing.T) { hcpModifier func(*hyperv1.HostedControlPlane) }{ { - name: "Public HCP gets public LB only", + name: "When public HCP uses Route, it should create public router LB service", endpointAccess: hyperv1.Public, exposeAPIServerThroughRouter: true, expectedServices: []corev1.Service{ @@ -1672,7 +1672,7 @@ func TestReconcileHCPRouterServices(t *testing.T) { }, }, { - name: "PublicPrivate gets public and private LB", + name: "When public and private HCP uses Route, it should create both router LB services", endpointAccess: hyperv1.PublicAndPrivate, exposeAPIServerThroughRouter: true, expectedServices: []corev1.Service{ @@ -1681,7 +1681,7 @@ func TestReconcileHCPRouterServices(t *testing.T) { }, }, { - name: "Private gets private LB only", + name: "When private HCP uses Route, it should create private router LB service only", endpointAccess: hyperv1.Private, exposeAPIServerThroughRouter: true, expectedServices: []corev1.Service{ @@ -1689,7 +1689,7 @@ func TestReconcileHCPRouterServices(t *testing.T) { }, }, { - name: "Public LB gets removed when switching to Private", + name: "When switching to private, it should remove public router LB service", endpointAccess: hyperv1.Private, exposeAPIServerThroughRouter: true, existingObjects: []client.Object{publicService(), privateService()}, @@ -1698,7 +1698,7 @@ func TestReconcileHCPRouterServices(t *testing.T) { }, }, { - name: "Private LB gets removed when switching to Public", + name: "When switching to public, it should remove private router LB service", endpointAccess: hyperv1.Public, exposeAPIServerThroughRouter: true, existingObjects: []client.Object{privateService()}, @@ -1707,7 +1707,7 @@ func TestReconcileHCPRouterServices(t *testing.T) { }, }, { - name: "Public LB gets removed when PublicAndPrivate but not using Route", + name: "When public and private cluster not using Route, it should remove public router LB service", endpointAccess: hyperv1.PublicAndPrivate, exposeAPIServerThroughRouter: false, existingObjects: []client.Object{publicService()}, @@ -1716,7 +1716,7 @@ func TestReconcileHCPRouterServices(t *testing.T) { }, }, { - name: "No LB created when public and not using Route", + name: "When public cluster not using Route, it should not create router LB services", endpointAccess: hyperv1.Public, exposeAPIServerThroughRouter: false, expectedServices: nil, @@ -1927,17 +1927,17 @@ func TestReconcileRouterServiceStatus(t *testing.T) { expectMsg bool }{ { - name: "Non-existent service", + name: "When service does not exist, it should return empty host", }, { - name: "Service that has not been provisioned", + name: "When service is not provisioned, it should return event message", svc: &corev1.Service{ ObjectMeta: metav1.ObjectMeta{Name: svcName, Namespace: namespace}, }, expectMsg: true, }, { - name: "Service with host populated", + name: "When service has hostname ingress, it should return hostname", svc: &corev1.Service{ ObjectMeta: metav1.ObjectMeta{Name: svcName, Namespace: namespace}, Status: corev1.ServiceStatus{ @@ -1953,7 +1953,7 @@ func TestReconcileRouterServiceStatus(t *testing.T) { expectedHost: "test.host", }, { - name: "Service with IP populated", + name: "When service has IP ingress, it should return IP address", svc: &corev1.Service{ ObjectMeta: metav1.ObjectMeta{Name: svcName, Namespace: namespace}, Status: corev1.ServiceStatus{ @@ -2016,7 +2016,7 @@ func TestReconcileInternalRouterServiceStatus(t *testing.T) { wantMsg string }{ { - name: "When ARO swift is enabled via annotation fallback it should not need internal router", + name: "When ARO swift is enabled via annotation fallback, it should not need internal router", setup: func(t *testing.T) { t.Setenv("MANAGED_SERVICE", hyperv1.AroHCP) }, @@ -2040,7 +2040,7 @@ func TestReconcileInternalRouterServiceStatus(t *testing.T) { wantNeeded: false, }, { - name: "When ARO swift is enabled via API field it should not need internal router", + name: "When ARO swift is enabled via API field, it should not need internal router", setup: func(t *testing.T) { t.Setenv("MANAGED_SERVICE", hyperv1.AroHCP) }, @@ -2067,7 +2067,7 @@ func TestReconcileInternalRouterServiceStatus(t *testing.T) { wantNeeded: false, }, { - name: "When ARO swift is enabled via both annotation and API field it should not need internal router", + name: "When ARO swift is enabled via both annotation and API field, it should not need internal router", setup: func(t *testing.T) { t.Setenv("MANAGED_SERVICE", hyperv1.AroHCP) }, diff --git a/control-plane-operator/controllers/hostedcontrolplane/infra/testdata/zz_fixture_TestReconcileInfrastructure_ARO_Route_Swift_Private.yaml b/control-plane-operator/controllers/hostedcontrolplane/infra/testdata/zz_fixture_TestReconcileInfrastructure_When_ARO_cluster_uses_Swift_with_private_topology__it_should_not_need_routers.yaml similarity index 100% rename from control-plane-operator/controllers/hostedcontrolplane/infra/testdata/zz_fixture_TestReconcileInfrastructure_ARO_Route_Swift_Private.yaml rename to control-plane-operator/controllers/hostedcontrolplane/infra/testdata/zz_fixture_TestReconcileInfrastructure_When_ARO_cluster_uses_Swift_with_private_topology__it_should_not_need_routers.yaml diff --git a/control-plane-operator/controllers/hostedcontrolplane/infra/testdata/zz_fixture_TestReconcileInfrastructure_ARO_Route_SharedIngress_AnnotationFallback.yaml b/control-plane-operator/controllers/hostedcontrolplane/infra/testdata/zz_fixture_TestReconcileInfrastructure_When_ARO_cluster_uses_Swift_with_public_and_private_topology__it_should_use_shared_ingress.yaml similarity index 100% rename from control-plane-operator/controllers/hostedcontrolplane/infra/testdata/zz_fixture_TestReconcileInfrastructure_ARO_Route_SharedIngress_AnnotationFallback.yaml rename to control-plane-operator/controllers/hostedcontrolplane/infra/testdata/zz_fixture_TestReconcileInfrastructure_When_ARO_cluster_uses_Swift_with_public_and_private_topology__it_should_use_shared_ingress.yaml diff --git a/control-plane-operator/controllers/hostedcontrolplane/infra/testdata/zz_fixture_TestReconcileInfrastructure_ARO_Route_Swift_PublicAndPrivate.yaml b/control-plane-operator/controllers/hostedcontrolplane/infra/testdata/zz_fixture_TestReconcileInfrastructure_When_ARO_cluster_uses_shared_ingress_with_annotation_fallback__it_should_use_direct_hostname_without_routers.yaml similarity index 100% rename from control-plane-operator/controllers/hostedcontrolplane/infra/testdata/zz_fixture_TestReconcileInfrastructure_ARO_Route_Swift_PublicAndPrivate.yaml rename to control-plane-operator/controllers/hostedcontrolplane/infra/testdata/zz_fixture_TestReconcileInfrastructure_When_ARO_cluster_uses_shared_ingress_with_annotation_fallback__it_should_use_direct_hostname_without_routers.yaml diff --git a/control-plane-operator/controllers/hostedcontrolplane/infra/testdata/zz_fixture_TestReconcileInfrastructure_AWS_Private_KAS_LoadBalancer.yaml b/control-plane-operator/controllers/hostedcontrolplane/infra/testdata/zz_fixture_TestReconcileInfrastructure_When_AWS_private_cluster_uses_KAS_LoadBalancer__it_should_configure_internal_router.yaml similarity index 100% rename from control-plane-operator/controllers/hostedcontrolplane/infra/testdata/zz_fixture_TestReconcileInfrastructure_AWS_Private_KAS_LoadBalancer.yaml rename to control-plane-operator/controllers/hostedcontrolplane/infra/testdata/zz_fixture_TestReconcileInfrastructure_When_AWS_private_cluster_uses_KAS_LoadBalancer__it_should_configure_internal_router.yaml diff --git a/control-plane-operator/controllers/hostedcontrolplane/infra/testdata/zz_fixture_TestReconcileInfrastructure_AWS_Private_Route.yaml b/control-plane-operator/controllers/hostedcontrolplane/infra/testdata/zz_fixture_TestReconcileInfrastructure_When_AWS_private_cluster_uses_Route__it_should_configure_internal_router.yaml similarity index 100% rename from control-plane-operator/controllers/hostedcontrolplane/infra/testdata/zz_fixture_TestReconcileInfrastructure_AWS_Private_Route.yaml rename to control-plane-operator/controllers/hostedcontrolplane/infra/testdata/zz_fixture_TestReconcileInfrastructure_When_AWS_private_cluster_uses_Route__it_should_configure_internal_router.yaml diff --git a/control-plane-operator/controllers/hostedcontrolplane/infra/testdata/zz_fixture_TestReconcileInfrastructure_AWS_PublicAndPrivate_KAS_LoadBalancer.yaml b/control-plane-operator/controllers/hostedcontrolplane/infra/testdata/zz_fixture_TestReconcileInfrastructure_When_AWS_public_and_private_cluster_uses_KAS_LoadBalancer__it_should_configure_internal_router_only.yaml similarity index 100% rename from control-plane-operator/controllers/hostedcontrolplane/infra/testdata/zz_fixture_TestReconcileInfrastructure_AWS_PublicAndPrivate_KAS_LoadBalancer.yaml rename to control-plane-operator/controllers/hostedcontrolplane/infra/testdata/zz_fixture_TestReconcileInfrastructure_When_AWS_public_and_private_cluster_uses_KAS_LoadBalancer__it_should_configure_internal_router_only.yaml diff --git a/control-plane-operator/controllers/hostedcontrolplane/infra/testdata/zz_fixture_TestReconcileInfrastructure_AWS_PublicAndPrivate_Route.yaml b/control-plane-operator/controllers/hostedcontrolplane/infra/testdata/zz_fixture_TestReconcileInfrastructure_When_AWS_public_and_private_cluster_uses_Route__it_should_configure_both_routers.yaml similarity index 100% rename from control-plane-operator/controllers/hostedcontrolplane/infra/testdata/zz_fixture_TestReconcileInfrastructure_AWS_PublicAndPrivate_Route.yaml rename to control-plane-operator/controllers/hostedcontrolplane/infra/testdata/zz_fixture_TestReconcileInfrastructure_When_AWS_public_and_private_cluster_uses_Route__it_should_configure_both_routers.yaml diff --git a/control-plane-operator/controllers/hostedcontrolplane/infra/testdata/zz_fixture_TestReconcileInfrastructure_AWS_Public_KAS_LoadBalancer.yaml b/control-plane-operator/controllers/hostedcontrolplane/infra/testdata/zz_fixture_TestReconcileInfrastructure_When_AWS_public_cluster_uses_KAS_LoadBalancer__it_should_not_need_external_router.yaml similarity index 100% rename from control-plane-operator/controllers/hostedcontrolplane/infra/testdata/zz_fixture_TestReconcileInfrastructure_AWS_Public_KAS_LoadBalancer.yaml rename to control-plane-operator/controllers/hostedcontrolplane/infra/testdata/zz_fixture_TestReconcileInfrastructure_When_AWS_public_cluster_uses_KAS_LoadBalancer__it_should_not_need_external_router.yaml diff --git a/control-plane-operator/controllers/hostedcontrolplane/infra/testdata/zz_fixture_TestReconcileInfrastructure_AWS_Public_Route.yaml b/control-plane-operator/controllers/hostedcontrolplane/infra/testdata/zz_fixture_TestReconcileInfrastructure_When_AWS_public_cluster_uses_Route__it_should_configure_external_router.yaml similarity index 100% rename from control-plane-operator/controllers/hostedcontrolplane/infra/testdata/zz_fixture_TestReconcileInfrastructure_AWS_Public_Route.yaml rename to control-plane-operator/controllers/hostedcontrolplane/infra/testdata/zz_fixture_TestReconcileInfrastructure_When_AWS_public_cluster_uses_Route__it_should_configure_external_router.yaml diff --git a/control-plane-operator/controllers/hostedcontrolplane/infra/testdata/zz_fixture_TestReconcileInfrastructure_Azure_Private_KAS_LoadBalancer.yaml b/control-plane-operator/controllers/hostedcontrolplane/infra/testdata/zz_fixture_TestReconcileInfrastructure_When_Azure_private_cluster_uses_KAS_LoadBalancer__it_should_configure_internal_router.yaml similarity index 100% rename from control-plane-operator/controllers/hostedcontrolplane/infra/testdata/zz_fixture_TestReconcileInfrastructure_Azure_Private_KAS_LoadBalancer.yaml rename to control-plane-operator/controllers/hostedcontrolplane/infra/testdata/zz_fixture_TestReconcileInfrastructure_When_Azure_private_cluster_uses_KAS_LoadBalancer__it_should_configure_internal_router.yaml diff --git a/control-plane-operator/controllers/hostedcontrolplane/infra/testdata/zz_fixture_TestReconcileInfrastructure_Azure_Private_OAuth_LoadBalancer.yaml b/control-plane-operator/controllers/hostedcontrolplane/infra/testdata/zz_fixture_TestReconcileInfrastructure_When_Azure_private_cluster_uses_OAuth_LoadBalancer__it_should_configure_internal_router.yaml similarity index 100% rename from control-plane-operator/controllers/hostedcontrolplane/infra/testdata/zz_fixture_TestReconcileInfrastructure_Azure_Private_OAuth_LoadBalancer.yaml rename to control-plane-operator/controllers/hostedcontrolplane/infra/testdata/zz_fixture_TestReconcileInfrastructure_When_Azure_private_cluster_uses_OAuth_LoadBalancer__it_should_configure_internal_router.yaml diff --git a/control-plane-operator/controllers/hostedcontrolplane/konnectivity/params_test.go b/control-plane-operator/controllers/hostedcontrolplane/konnectivity/params_test.go index adff13c3f0cb..a2e377e695c6 100644 --- a/control-plane-operator/controllers/hostedcontrolplane/konnectivity/params_test.go +++ b/control-plane-operator/controllers/hostedcontrolplane/konnectivity/params_test.go @@ -20,7 +20,7 @@ func TestNewKonnectivityServiceParams(t *testing.T) { validate func(*testing.T, *KonnectivityServiceParams) }{ { - name: "When HCP is provided it should create params with owner ref", + name: "When HCP is provided, it should create params with owner ref", hcp: &hyperv1.HostedControlPlane{ ObjectMeta: metav1.ObjectMeta{ Name: "test-hcp", @@ -38,7 +38,7 @@ func TestNewKonnectivityServiceParams(t *testing.T) { }, }, { - name: "When HCP has empty metadata it should still create params", + name: "When HCP has empty metadata, it should still create params", hcp: &hyperv1.HostedControlPlane{ ObjectMeta: metav1.ObjectMeta{}, }, diff --git a/control-plane-operator/controllers/hostedcontrolplane/oauth/idp_convert_test.go b/control-plane-operator/controllers/hostedcontrolplane/oauth/idp_convert_test.go index c76051057ffb..8236fd1139be 100644 --- a/control-plane-operator/controllers/hostedcontrolplane/oauth/idp_convert_test.go +++ b/control-plane-operator/controllers/hostedcontrolplane/oauth/idp_convert_test.go @@ -935,7 +935,7 @@ func TestTransportForCARef(t *testing.T) { expectedProxyRequestURL string }{ { - name: "When no proxy configuration is provided, the transport should not be modified", + name: "When no proxy configuration is provided, it should not modify the transport", hcp: &hyperv1.HostedControlPlane{ ObjectMeta: metav1.ObjectMeta{ Name: "hcp-test", @@ -947,7 +947,7 @@ func TestTransportForCARef(t *testing.T) { expectedProxyRequestURL: "", }, { - name: "When proxy configuration is provided, the transport should use proxy", + name: "When proxy configuration is provided, it should use proxy for the transport", hcp: &hyperv1.HostedControlPlane{ ObjectMeta: metav1.ObjectMeta{ Name: "hcp-test", @@ -971,7 +971,7 @@ func TestTransportForCARef(t *testing.T) { expectedProxyRequestURL: "https://10.0.0.1", }, { - name: "When proxy configuration is provided and request is to ignored url, the transport should not use proxy", + name: "When proxy configuration is provided and request is to ignored url, it should not use proxy for the transport", hcp: &hyperv1.HostedControlPlane{ ObjectMeta: metav1.ObjectMeta{ Name: "hcp-test", diff --git a/control-plane-operator/controllers/hostedcontrolplane/pki/kas_test.go b/control-plane-operator/controllers/hostedcontrolplane/pki/kas_test.go index e34bfa78268c..60f321039e51 100644 --- a/control-plane-operator/controllers/hostedcontrolplane/pki/kas_test.go +++ b/control-plane-operator/controllers/hostedcontrolplane/pki/kas_test.go @@ -18,37 +18,37 @@ func TestAddBracketsIfIPv6(t *testing.T) { want string }{ { - name: "given ipv4, it should not have brackets", + name: "When given an IPv4 address, it should not add brackets", apiAddress: "192.168.1.1", want: "192.168.1.1", }, { - name: "given an URL, it should not have brackets", + name: "When given a URL with port, it should not add brackets", apiAddress: "https://test.tld:8451", want: "https://test.tld:8451", }, { - name: "given another URL sample, it should not have brackets", + name: "When given a URL without port, it should not add brackets", apiAddress: "https://test", want: "https://test", }, { - name: "given an URL, it should not have brackets", + name: "When given a hostname with port, it should not add brackets", apiAddress: "test.tld:8451", want: "test.tld:8451", }, { - name: "given simplified ipv6, it should return URL with brackets", + name: "When given a simplified IPv6 address, it should return it with brackets", apiAddress: "fd00::1", want: "[fd00::1]", }, { - name: "given an ipv6, it should return URL with brackets", + name: "When given a full IPv6 address, it should return it with brackets", apiAddress: "fd00:0000:0000:0000:0000:0000:1:99", want: "[fd00:0000:0000:0000:0000:0000:1:99]", }, { - name: "given wrong ipv6, it should return same URL without brackets", + name: "When given an invalid IPv6 address, it should return it without brackets", apiAddress: "fd00:0000:0000:0000:0000:0000:1:99000:00000000000", want: "fd00:0000:0000:0000:0000:0000:1:99000:00000000000", }, diff --git a/control-plane-operator/controllers/hostedcontrolplane/v2/assets/assets_test.go b/control-plane-operator/controllers/hostedcontrolplane/v2/assets/assets_test.go index bc2dc43c5e4b..63dd539cc142 100644 --- a/control-plane-operator/controllers/hostedcontrolplane/v2/assets/assets_test.go +++ b/control-plane-operator/controllers/hostedcontrolplane/v2/assets/assets_test.go @@ -445,7 +445,7 @@ func TestLoadManifestTemplated(t *testing.T) { validate func(g Gomega, obj client.Object, gvk *schema.GroupVersionKind, err error) }{ { - name: "When Name=etcd, service.yaml should render to original hardcoded values", + name: "When Name=etcd, it should render service.yaml to original hardcoded values", componentName: "etcd", fileName: "service.yaml", templateData: map[string]string{"Name": "etcd", "ClientServiceName": "etcd-client", "DiscoveryServiceName": "etcd-discovery"}, @@ -458,7 +458,7 @@ func TestLoadManifestTemplated(t *testing.T) { }, }, { - name: "When Name=etcd-events, service.yaml should render shard-specific names", + name: "When Name=etcd-events, it should render service.yaml with shard-specific names", componentName: "etcd", fileName: "service.yaml", templateData: map[string]string{"Name": "etcd-events", "ClientServiceName": "etcd-client-events", "DiscoveryServiceName": "etcd-discovery-events"}, @@ -471,7 +471,7 @@ func TestLoadManifestTemplated(t *testing.T) { }, }, { - name: "When Name=etcd, discovery-service.yaml should render to original values", + name: "When Name=etcd, it should render discovery-service.yaml to original values", componentName: "etcd", fileName: "discovery-service.yaml", templateData: map[string]string{"Name": "etcd", "ClientServiceName": "etcd-client", "DiscoveryServiceName": "etcd-discovery"}, @@ -483,7 +483,7 @@ func TestLoadManifestTemplated(t *testing.T) { }, }, { - name: "When Name=etcd-events, discovery-service.yaml should render shard names", + name: "When Name=etcd-events, it should render discovery-service.yaml with shard names", componentName: "etcd", fileName: "discovery-service.yaml", templateData: map[string]string{"Name": "etcd-events", "ClientServiceName": "etcd-client-events", "DiscoveryServiceName": "etcd-discovery-events"}, @@ -495,7 +495,7 @@ func TestLoadManifestTemplated(t *testing.T) { }, }, { - name: "When Name=etcd, pdb.yaml should render to original values", + name: "When Name=etcd, it should render pdb.yaml to original values", componentName: "etcd", fileName: "pdb.yaml", templateData: map[string]string{"Name": "etcd", "ClientServiceName": "etcd-client", "DiscoveryServiceName": "etcd-discovery"}, @@ -505,7 +505,7 @@ func TestLoadManifestTemplated(t *testing.T) { }, }, { - name: "When Name=etcd-events, pdb.yaml should render shard name", + name: "When Name=etcd-events, it should render pdb.yaml with shard name", componentName: "etcd", fileName: "pdb.yaml", templateData: map[string]string{"Name": "etcd-events", "ClientServiceName": "etcd-client-events", "DiscoveryServiceName": "etcd-discovery-events"}, diff --git a/control-plane-operator/controllers/hostedcontrolplane/v2/autoscaler/component_test.go b/control-plane-operator/controllers/hostedcontrolplane/v2/autoscaler/component_test.go index 479595c54bc5..dc244392565b 100644 --- a/control-plane-operator/controllers/hostedcontrolplane/v2/autoscaler/component_test.go +++ b/control-plane-operator/controllers/hostedcontrolplane/v2/autoscaler/component_test.go @@ -37,16 +37,16 @@ func TestPredicate(t *testing.T) { expected bool }{ { - name: "when CAPI kubeconfig secret exist predicate returns true", + name: "When CAPI kubeconfig secret exists, it should return true", capiKubeconfigSecret: manifests.KASServiceCAPIKubeconfigSecret(hcp.Namespace, hcp.Spec.InfraID), expected: true, }, { - name: "when CAPI kubeconfig secret doesn't exist, predicate return false", + name: "When CAPI kubeconfig secret does not exist, it should return false", expected: false, }, { - name: "when HCP has DisableMachineManagement annotation predicate return false", + name: "When HCP has DisableMachineManagement annotation, it should return false", hcpAnnotations: map[string]string{ hyperv1.DisableMachineManagement: "true", }, @@ -101,14 +101,14 @@ func TestAdaptDeployment(t *testing.T) { expectedReplicas int32 }{ { - name: "when HCP has DisableClusterAutoscalerAnnotation annotation replicas should be 0", + name: "When HCP has DisableClusterAutoscalerAnnotation annotation, it should set replicas to 0", hcpAnnotations: map[string]string{ hyperv1.DisableClusterAutoscalerAnnotation: "true", }, expectedReplicas: 0, }, { - name: "when autoscaling options is set, container has optional arguments", + name: "When autoscaling options are set, it should include optional arguments", AutoscalerOptions: hyperv1.ClusterAutoscaling{ MaxNodesTotal: ptr.To[int32](100), MaxPodGracePeriod: ptr.To[int32](300), @@ -129,7 +129,7 @@ func TestAdaptDeployment(t *testing.T) { expectedReplicas: 1, }, { - name: "when scale down is disabled, container has scale down disabled argument", + name: "When scale down is disabled, it should include scale-down-enabled=false argument", AutoscalerOptions: hyperv1.ClusterAutoscaling{ Scaling: hyperv1.ScaleUpOnly, ScaleDown: &hyperv1.ScaleDownConfig{}, @@ -140,7 +140,7 @@ func TestAdaptDeployment(t *testing.T) { expectedReplicas: 1, }, { - name: "when scale down is enabled with all options, container has all scale down arguments", + name: "When scale down is enabled with all options, it should include all scale down arguments", AutoscalerOptions: hyperv1.ClusterAutoscaling{ Scaling: hyperv1.ScaleUpAndScaleDown, ScaleDown: &hyperv1.ScaleDownConfig{ @@ -162,7 +162,7 @@ func TestAdaptDeployment(t *testing.T) { expectedReplicas: 1, }, { - name: "when expanders are configured, container has expander arguments", + name: "When expanders are configured, it should include expander arguments", AutoscalerOptions: hyperv1.ClusterAutoscaling{ Expanders: []hyperv1.ExpanderString{ hyperv1.LeastWasteExpander, @@ -176,7 +176,7 @@ func TestAdaptDeployment(t *testing.T) { expectedReplicas: 1, }, { - name: "when balancing ignored labels are configured, container has balancing ignore label arguments", + name: "When balancing ignored labels are configured, it should include balancing-ignore-label arguments", AutoscalerOptions: hyperv1.ClusterAutoscaling{ BalancingIgnoredLabels: []string{ "custom.label/zone", @@ -190,7 +190,7 @@ func TestAdaptDeployment(t *testing.T) { expectedReplicas: 1, }, { - name: "when MaxFreeDifferenceRatioPercent is set, container has max-free-difference-ratio argument", + name: "When MaxFreeDifferenceRatioPercent is set, it should include max-free-difference-ratio argument", AutoscalerOptions: hyperv1.ClusterAutoscaling{ MaxFreeDifferenceRatioPercent: ptr.To[int32](20), }, diff --git a/control-plane-operator/controllers/hostedcontrolplane/v2/cno/component_test.go b/control-plane-operator/controllers/hostedcontrolplane/v2/cno/component_test.go index 355b439d0f64..78de303ee822 100644 --- a/control-plane-operator/controllers/hostedcontrolplane/v2/cno/component_test.go +++ b/control-plane-operator/controllers/hostedcontrolplane/v2/cno/component_test.go @@ -15,47 +15,47 @@ func TestPlatformHasCloudNetworkConfigController(t *testing.T) { expected bool }{ { - name: "When platform is AWS it should have cloud-network-config-controller", + name: "When platform is AWS, it should have cloud-network-config-controller", platformType: hyperv1.AWSPlatform, expected: true, }, { - name: "When platform is Azure it should have cloud-network-config-controller", + name: "When platform is Azure, it should have cloud-network-config-controller", platformType: hyperv1.AzurePlatform, expected: true, }, { - name: "When platform is GCP it should have cloud-network-config-controller", + name: "When platform is GCP, it should have cloud-network-config-controller", platformType: hyperv1.GCPPlatform, expected: true, }, { - name: "When platform is OpenStack it should have cloud-network-config-controller", + name: "When platform is OpenStack, it should have cloud-network-config-controller", platformType: hyperv1.OpenStackPlatform, expected: true, }, { - name: "When platform is KubeVirt it should not have cloud-network-config-controller", + name: "When platform is KubeVirt, it should not have cloud-network-config-controller", platformType: hyperv1.KubevirtPlatform, expected: false, }, { - name: "When platform is Agent it should not have cloud-network-config-controller", + name: "When platform is Agent, it should not have cloud-network-config-controller", platformType: hyperv1.AgentPlatform, expected: false, }, { - name: "When platform is None it should not have cloud-network-config-controller", + name: "When platform is None, it should not have cloud-network-config-controller", platformType: hyperv1.NonePlatform, expected: false, }, { - name: "When platform is IBMCloud it should not have cloud-network-config-controller", + name: "When platform is IBMCloud, it should not have cloud-network-config-controller", platformType: hyperv1.IBMCloudPlatform, expected: false, }, { - name: "When platform is PowerVS it should not have cloud-network-config-controller", + name: "When platform is PowerVS, it should not have cloud-network-config-controller", platformType: hyperv1.PowerVSPlatform, expected: false, }, diff --git a/control-plane-operator/controllers/hostedcontrolplane/v2/etcd/etcd_test.go b/control-plane-operator/controllers/hostedcontrolplane/v2/etcd/etcd_test.go index 534aae556e07..242198228175 100644 --- a/control-plane-operator/controllers/hostedcontrolplane/v2/etcd/etcd_test.go +++ b/control-plane-operator/controllers/hostedcontrolplane/v2/etcd/etcd_test.go @@ -223,7 +223,7 @@ func TestDefragControllerPredicate(t *testing.T) { } } -func Test_minTLSVersion(t *testing.T) { +func TestMinTLSVersion(t *testing.T) { t.Parallel() testCases := []struct { @@ -306,7 +306,7 @@ func Test_minTLSVersion(t *testing.T) { } } -func Test_adaptStatefulSet(t *testing.T) { +func TestAdaptStatefulSet(t *testing.T) { t.Parallel() testStatefulSet := &appsv1.StatefulSet{ @@ -354,13 +354,13 @@ func Test_adaptStatefulSet(t *testing.T) { expectedCipherSuites string }{ { - name: "when api server is nil tls version must be 1.2 and cipher suites must be set.", + name: "When API server config is nil, it should set TLS 1.2 and cipher suites", configuration: nil, expectedTLSMinVersion: "TLS1.2", expectCipherSuites: true, }, { - name: "when tls profile is modern it should set min tls version and not set ciphers", + name: "When TLS profile is modern, it should set min TLS version without ciphers", configuration: &hyperv1.ClusterConfiguration{ APIServer: &configv1.APIServerSpec{ TLSSecurityProfile: &configv1.TLSSecurityProfile{Type: configv1.TLSProfileModernType}, @@ -370,7 +370,7 @@ func Test_adaptStatefulSet(t *testing.T) { expectCipherSuites: false, }, { - name: "when tls profile is intermediate it should set both min tls version and ciphers", + name: "When TLS profile is intermediate, it should set both min TLS version and ciphers", configuration: &hyperv1.ClusterConfiguration{ APIServer: &configv1.APIServerSpec{ TLSSecurityProfile: &configv1.TLSSecurityProfile{Type: configv1.TLSProfileIntermediateType}, @@ -380,7 +380,7 @@ func Test_adaptStatefulSet(t *testing.T) { expectCipherSuites: true, }, { - name: "when tls profile has custom cipher suites, it should set min tls version and cipher suites (openssl to iana conversion)", + name: "When TLS profile has custom cipher suites, it should set min TLS version and convert ciphers from OpenSSL to IANA", configuration: &hyperv1.ClusterConfiguration{ APIServer: &configv1.APIServerSpec{ TLSSecurityProfile: &configv1.TLSSecurityProfile{ @@ -402,7 +402,7 @@ func Test_adaptStatefulSet(t *testing.T) { expectedCipherSuites: "TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256,TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256", }, { - name: "when tls profile has unsupported cipher suites, it should set only min tls version", + name: "When TLS profile has unsupported cipher suites, it should set only min TLS version", configuration: &hyperv1.ClusterConfiguration{ APIServer: &configv1.APIServerSpec{ TLSSecurityProfile: &configv1.TLSSecurityProfile{ @@ -423,7 +423,7 @@ func Test_adaptStatefulSet(t *testing.T) { expectCipherSuites: false, }, { - name: "when tls 1.3 is specified with tls 1.3 cipher suites, it should set min tls version, not cipher suites", + name: "When TLS 1.3 is specified with TLS 1.3 cipher suites, it should set min TLS version without cipher suites", configuration: &hyperv1.ClusterConfiguration{ APIServer: &configv1.APIServerSpec{ TLSSecurityProfile: &configv1.TLSSecurityProfile{ diff --git a/control-plane-operator/controllers/hostedcontrolplane/v2/karpenter/component_test.go b/control-plane-operator/controllers/hostedcontrolplane/v2/karpenter/component_test.go index 2e65cc9c1aab..731062f3d78f 100644 --- a/control-plane-operator/controllers/hostedcontrolplane/v2/karpenter/component_test.go +++ b/control-plane-operator/controllers/hostedcontrolplane/v2/karpenter/component_test.go @@ -45,12 +45,12 @@ func TestPredicate(t *testing.T) { expected bool }{ { - name: "when CAPI kubeconfig secret exist predicate returns true", + name: "When CAPI kubeconfig secret exists, it should return true", capiKubeconfigSecret: manifests.KASServiceCAPIKubeconfigSecret(hcp.Namespace, hcp.Spec.InfraID), expected: true, }, { - name: "when CAPI kubeconfig secret doesn't exist, predicate return false", + name: "When CAPI kubeconfig secret does not exist, it should return false", expected: false, }, } @@ -104,14 +104,14 @@ func TestAdaptDeployment(t *testing.T) { expectedImage string }{ { - name: "when HCP has KarpenterProviderAWSImage annotation, image should be overridden", + name: "When HCP has KarpenterProviderAWSImage annotation, it should override the image", hcpAnnotations: map[string]string{ hyperkarpenterv1.KarpenterProviderAWSImage: "some-override-karpenter-image", }, expectedImage: "some-override-karpenter-image", }, { - name: "expect default image", + name: "When no image override annotation is set, it should use the default image", expectedImage: "aws-karpenter-provider-aws", }, } diff --git a/control-plane-operator/controllers/hostedcontrolplane/v2/kas/config_test.go b/control-plane-operator/controllers/hostedcontrolplane/v2/kas/config_test.go index abc7232ea824..c1ac1045bc7b 100644 --- a/control-plane-operator/controllers/hostedcontrolplane/v2/kas/config_test.go +++ b/control-plane-operator/controllers/hostedcontrolplane/v2/kas/config_test.go @@ -25,12 +25,12 @@ func TestGenerateConfig(t *testing.T) { testcases := []testcase{ { - name: "defaults", + name: "When using default params, it should return default config", params: KubeAPIServerConfigParams{}, expected: defaultKASConfig(), }, { - name: "with additional named cerfiticates", + name: "When additional named certificates are provided, it should add them to serving info", params: KubeAPIServerConfigParams{ NamedCertificates: []configv1.APIServerNamedServingCert{ { @@ -62,7 +62,7 @@ func TestGenerateConfig(t *testing.T) { ), }, { - name: "with ExternalIPRanger configuration, with AutoAssignCIDRs", + name: "When ExternalIPRanger is configured with AutoAssignCIDRs, it should enable allowIngressIP", params: KubeAPIServerConfigParams{ ExternalIPConfig: &configv1.ExternalIPConfig{ Policy: &configv1.ExternalIPPolicy{ @@ -100,7 +100,7 @@ func TestGenerateConfig(t *testing.T) { ), }, { - name: "with ExternalIPRanger configuration, without AutoAssignCIDRs", + name: "When ExternalIPRanger is configured without AutoAssignCIDRs, it should disable allowIngressIP", params: KubeAPIServerConfigParams{ ExternalIPConfig: &configv1.ExternalIPConfig{ Policy: &configv1.ExternalIPPolicy{ @@ -135,7 +135,7 @@ func TestGenerateConfig(t *testing.T) { ), }, { - name: "with ClusterNetwork and ServiceNetwork configuration", + name: "When ClusterNetwork and ServiceNetwork are configured, it should set restricted CIDRs and services subnet", params: KubeAPIServerConfigParams{ ClusterNetwork: []string{ "10.0.0.0/16", @@ -168,7 +168,7 @@ func TestGenerateConfig(t *testing.T) { ), }, { - name: "with KAS Pod port configuration", + name: "When KAS Pod port is configured, it should set bind address", params: KubeAPIServerConfigParams{ KASPodPort: 8080, }, @@ -179,7 +179,7 @@ func TestGenerateConfig(t *testing.T) { ), }, { - name: "with TLS profile configuration", + name: "When TLS profile is configured, it should set TLS version and cipher suites", params: KubeAPIServerConfigParams{ TLSSecurityProfile: &configv1.TLSSecurityProfile{ Type: configv1.TLSProfileModernType, @@ -195,7 +195,7 @@ func TestGenerateConfig(t *testing.T) { ), }, { - name: "with additional CORS allowed origin configuration", + name: "When additional CORS allowed origins are provided, it should append them to the list", params: KubeAPIServerConfigParams{ AdditionalCORSAllowedOrigins: []string{ "abcdef", @@ -208,7 +208,7 @@ func TestGenerateConfig(t *testing.T) { ), }, { - name: "with console public URL configuration", + name: "When console public URL is configured, it should set the console public URL", params: KubeAPIServerConfigParams{ ConsolePublicURL: "https://console.public.io", }, @@ -219,7 +219,7 @@ func TestGenerateConfig(t *testing.T) { ), }, { - name: "with image policy configuration", + name: "When image policy is configured, it should set registry hostnames", params: KubeAPIServerConfigParams{ InternalRegistryHostName: "internal", ExternalRegistryHostNames: []string{ @@ -240,7 +240,7 @@ func TestGenerateConfig(t *testing.T) { ), }, { - name: "with default node selector configuration", + name: "When default node selector is configured, it should set project config", params: KubeAPIServerConfigParams{ DefaultNodeSelector: "foo=bar", }, @@ -253,7 +253,7 @@ func TestGenerateConfig(t *testing.T) { ), }, { - name: "with feature gate OpenShiftPodSecurityAdmission=true configuration", + name: "When OpenShiftPodSecurityAdmission feature gate is enabled, it should configure restricted pod security defaults", params: KubeAPIServerConfigParams{ FeatureGates: []string{ "OpenShiftPodSecurityAdmission=true", @@ -291,7 +291,7 @@ func TestGenerateConfig(t *testing.T) { ), }, { - name: "with auth type None", + name: "When auth type is None, it should clear OAuth metadata file", params: KubeAPIServerConfigParams{ Authentication: &configv1.AuthenticationSpec{ Type: configv1.AuthenticationTypeNone, @@ -304,7 +304,7 @@ func TestGenerateConfig(t *testing.T) { ), }, { - name: "with advertise address", + name: "When advertise address is provided, it should set the advertise-address argument", params: KubeAPIServerConfigParams{ AdvertiseAddress: "foo", }, @@ -315,7 +315,7 @@ func TestGenerateConfig(t *testing.T) { ), }, { - name: "with service account issuer URL", + name: "When service account issuer URL is provided, it should configure SA issuer arguments", params: KubeAPIServerConfigParams{ ServiceAccountIssuerURL: "https://issuer.io", }, @@ -328,7 +328,7 @@ func TestGenerateConfig(t *testing.T) { ), }, { - name: "with cloud provider config ref", + name: "When cloud provider config ref is provided, it should set cloud-config argument", params: KubeAPIServerConfigParams{ CloudProviderConfigRef: &corev1.LocalObjectReference{ Name: "foo", @@ -341,7 +341,7 @@ func TestGenerateConfig(t *testing.T) { ), }, { - name: "with unrecognized cloud provider config", + name: "When unrecognized cloud provider is configured, it should set cloud-provider argument", params: KubeAPIServerConfigParams{ CloudProvider: "alibaba", }, @@ -352,7 +352,7 @@ func TestGenerateConfig(t *testing.T) { ), }, { - name: "with audit webhook enabled", + name: "When audit webhook is enabled, it should configure audit webhook arguments", params: KubeAPIServerConfigParams{ AuditWebhookEnabled: true, }, @@ -365,7 +365,7 @@ func TestGenerateConfig(t *testing.T) { ), }, { - name: "with profiling disabled", + name: "When profiling is disabled, it should set profiling argument to false", params: KubeAPIServerConfigParams{ DisableProfiling: true, }, @@ -376,7 +376,7 @@ func TestGenerateConfig(t *testing.T) { ), }, { - name: "with profiling disabled", + name: "When profiling is disabled, it should set profiling argument to false", params: KubeAPIServerConfigParams{ DisableProfiling: true, }, @@ -387,7 +387,7 @@ func TestGenerateConfig(t *testing.T) { ), }, { - name: "with OAuth disabled", + name: "When OAuth is disabled, it should configure OIDC authentication", params: KubeAPIServerConfigParams{ Authentication: &configv1.AuthenticationSpec{ Type: configv1.AuthenticationTypeOIDC, @@ -458,7 +458,7 @@ func TestGenerateConfig(t *testing.T) { ), }, { - name: "with etcd URL", + name: "When etcd URL is provided, it should set etcd-servers argument", params: KubeAPIServerConfigParams{ EtcdURL: "https://etcd.io", }, @@ -469,7 +469,7 @@ func TestGenerateConfig(t *testing.T) { ), }, { - name: "with goaway chance", + name: "When goaway chance is configured, it should set goaway-chance argument", params: KubeAPIServerConfigParams{ GoAwayChance: "something", }, @@ -480,7 +480,7 @@ func TestGenerateConfig(t *testing.T) { ), }, { - name: "with max mutating requests in flight", + name: "When max mutating requests in flight is configured, it should set the argument", params: KubeAPIServerConfigParams{ MaxMutatingRequestsInflight: "20", }, @@ -491,7 +491,7 @@ func TestGenerateConfig(t *testing.T) { ), }, { - name: "with max requests in flight", + name: "When max requests in flight is configured, it should set the argument", params: KubeAPIServerConfigParams{ MaxRequestsInflight: "20", }, @@ -502,7 +502,7 @@ func TestGenerateConfig(t *testing.T) { ), }, { - name: "with DynamicResourceAllocation feature gate enabled", + name: "When DynamicResourceAllocation feature gate is enabled, it should configure runtime-config", params: KubeAPIServerConfigParams{ FeatureGates: []string{ "DynamicResourceAllocation=true", @@ -516,7 +516,7 @@ func TestGenerateConfig(t *testing.T) { ), }, { - name: "with ValidatingAdmissionPolicy feature gate explicitly enabled", + name: "When ValidatingAdmissionPolicy feature gate is explicitly enabled, it should return default config", params: KubeAPIServerConfigParams{ FeatureGates: []string{ "ValidatingAdmissionPolicy=true", @@ -526,7 +526,7 @@ func TestGenerateConfig(t *testing.T) { expected: defaultKASConfig(), }, { - name: "with ValidatingAdmissionPolicy feature gate explicitly disabled", + name: "When ValidatingAdmissionPolicy feature gate is explicitly disabled, it should return default config", params: KubeAPIServerConfigParams{ FeatureGates: []string{ "ValidatingAdmissionPolicy=false", @@ -536,7 +536,7 @@ func TestGenerateConfig(t *testing.T) { expected: defaultKASConfig(), }, { - name: "with StructuredAuthenticationConfiguration feature gate explicitly disabled", + name: "When StructuredAuthenticationConfiguration feature gate is explicitly disabled, it should return default config", params: KubeAPIServerConfigParams{ FeatureGates: []string{ "StructuredAuthenticationConfiguration=false", @@ -546,7 +546,7 @@ func TestGenerateConfig(t *testing.T) { expected: defaultKASConfig(), }, { - name: "with strict transport security directive", + name: "When strict transport security directive is configured, it should set the directive argument", params: KubeAPIServerConfigParams{ APIServerSTSDirectives: "foo", }, @@ -557,7 +557,7 @@ func TestGenerateConfig(t *testing.T) { ), }, { - name: "with MutatingAdmissionPolicy feature gate enabled", + name: "When MutatingAdmissionPolicy feature gate is enabled, it should configure runtime-config", params: KubeAPIServerConfigParams{ FeatureGates: []string{ "MutatingAdmissionPolicy=true", @@ -571,7 +571,7 @@ func TestGenerateConfig(t *testing.T) { ), }, { - name: "with service account max token expiration", + name: "When service account max token expiration is configured, it should set the argument", params: KubeAPIServerConfigParams{ ServiceAccountMaxTokenExpiration: "24h", }, diff --git a/control-plane-operator/controllers/hostedcontrolplane/v2/kas/kms/aws_test.go b/control-plane-operator/controllers/hostedcontrolplane/v2/kas/kms/aws_test.go index 0d415cd57bc2..cde77fe3c102 100644 --- a/control-plane-operator/controllers/hostedcontrolplane/v2/kas/kms/aws_test.go +++ b/control-plane-operator/controllers/hostedcontrolplane/v2/kas/kms/aws_test.go @@ -178,7 +178,7 @@ func TestGenerateKMSEncryptionConfig(t *testing.T) { }, }, { - name: "When called, the KMS provider name should be based on a hash of the ARN", + name: "When called, it should base KMS provider name on a hash of the ARN", provider: func() (*awsKMSProvider, error) { return NewAWSKMSProvider( hyperv1.AWSKMSKeyEntry{ARN: "arn:aws:kms:us-east-1:123456789:key/test-key-id"}, diff --git a/control-plane-operator/controllers/hostedcontrolplane/v2/kas/kms/azure_test.go b/control-plane-operator/controllers/hostedcontrolplane/v2/kas/kms/azure_test.go index f4f26bd64c20..bc9fdcc9283c 100644 --- a/control-plane-operator/controllers/hostedcontrolplane/v2/kas/kms/azure_test.go +++ b/control-plane-operator/controllers/hostedcontrolplane/v2/kas/kms/azure_test.go @@ -61,7 +61,7 @@ func TestNewAzureKMSProvider(t *testing.T) { errContains string }{ { - name: "When kmsSpec is nil it should return an error", + name: "When kmsSpec is nil, it should return an error", kmsSpec: nil, image: "test-image:latest", opts: AzureKMSProviderOptions{}, @@ -69,7 +69,7 @@ func TestNewAzureKMSProvider(t *testing.T) { errContains: "azure kms metadata not specified", }, { - name: "When self-managed with empty kmsClientID it should return an error", + name: "When self-managed with empty kmsClientID, it should return an error", kmsSpec: validAzureKMSSpec(), image: "test-image:latest", opts: AzureKMSProviderOptions{ @@ -81,7 +81,7 @@ func TestNewAzureKMSProvider(t *testing.T) { errContains: "kmsClientID and tenantID are required", }, { - name: "When self-managed with empty tenantID it should return an error", + name: "When self-managed with empty tenantID, it should return an error", kmsSpec: validAzureKMSSpec(), image: "test-image:latest", opts: AzureKMSProviderOptions{ @@ -93,7 +93,7 @@ func TestNewAzureKMSProvider(t *testing.T) { errContains: "kmsClientID and tenantID are required", }, { - name: "When self-managed with empty tokenMinterImage it should return an error", + name: "When self-managed with empty tokenMinterImage, it should return an error", kmsSpec: validAzureKMSSpec(), image: "test-image:latest", opts: AzureKMSProviderOptions{ @@ -106,7 +106,7 @@ func TestNewAzureKMSProvider(t *testing.T) { errContains: "tokenMinterImage is required", }, { - name: "When managed Azure it should create provider successfully", + name: "When managed Azure, it should create provider successfully", kmsSpec: validAzureKMSSpec(), image: "test-image:latest", opts: AzureKMSProviderOptions{ @@ -115,7 +115,7 @@ func TestNewAzureKMSProvider(t *testing.T) { expectError: false, }, { - name: "When self-managed Azure with valid options it should create provider successfully", + name: "When self-managed Azure with valid options, it should create provider successfully", kmsSpec: validAzureKMSSpec(), image: "test-image:latest", opts: AzureKMSProviderOptions{ @@ -151,7 +151,7 @@ func TestGenerateKMSPodConfig_SelfManaged(t *testing.T) { check func(g Gomega, podConfig *KMSPodConfig) }{ { - name: "When self-managed it should include token minter container with correct config", + name: "When self-managed, it should include token minter container with correct config", check: func(g Gomega, podConfig *KMSPodConfig) { var tokenMinter *containerInfo for i, c := range podConfig.Containers { @@ -182,7 +182,7 @@ func TestGenerateKMSPodConfig_SelfManaged(t *testing.T) { }, }, { - name: "When self-managed it should include cloud-token emptyDir volume", + name: "When self-managed, it should include cloud-token emptyDir volume", check: func(g Gomega, podConfig *KMSPodConfig) { found := false for _, v := range podConfig.Volumes { @@ -196,7 +196,7 @@ func TestGenerateKMSPodConfig_SelfManaged(t *testing.T) { }, }, { - name: "When self-managed it should NOT include secret-store CSI volume", + name: "When self-managed, it should NOT include secret-store CSI volume", check: func(g Gomega, podConfig *KMSPodConfig) { for _, v := range podConfig.Volumes { g.Expect(v.Name).NotTo(Equal(config.ManagedAzureKMSSecretStoreVolumeName), @@ -205,7 +205,7 @@ func TestGenerateKMSPodConfig_SelfManaged(t *testing.T) { }, }, { - name: "When self-managed the KMS container should mount cloud-token volume", + name: "When self-managed, it should mount cloud-token volume in KMS container", check: func(g Gomega, podConfig *KMSPodConfig) { for _, c := range podConfig.Containers { if c.Name == "azure-kms-provider-active" { @@ -226,7 +226,7 @@ func TestGenerateKMSPodConfig_SelfManaged(t *testing.T) { }, }, { - name: "When self-managed the KMS container should have workload identity env vars", + name: "When self-managed, it should have workload identity env vars in KMS container", check: func(g Gomega, podConfig *KMSPodConfig) { for _, c := range podConfig.Containers { if c.Name == "azure-kms-provider-active" { @@ -278,7 +278,7 @@ func TestGenerateKMSPodConfig_Managed(t *testing.T) { check func(g Gomega, podConfig *KMSPodConfig) }{ { - name: "When managed it should NOT include token minter container", + name: "When managed, it should NOT include token minter container", check: func(g Gomega, podConfig *KMSPodConfig) { for _, c := range podConfig.Containers { g.Expect(c.Name).NotTo(Equal("azure-kms-token-minter"), @@ -287,7 +287,7 @@ func TestGenerateKMSPodConfig_Managed(t *testing.T) { }, }, { - name: "When managed it should include secret-store CSI volume", + name: "When managed, it should include secret-store CSI volume", check: func(g Gomega, podConfig *KMSPodConfig) { found := false for _, v := range podConfig.Volumes { @@ -302,7 +302,7 @@ func TestGenerateKMSPodConfig_Managed(t *testing.T) { }, }, { - name: "When managed it should NOT include cloud-token volume", + name: "When managed, it should NOT include cloud-token volume", check: func(g Gomega, podConfig *KMSPodConfig) { for _, v := range podConfig.Volumes { g.Expect(v.Name).NotTo(Equal("azure-kms-cloud-token"), @@ -311,7 +311,7 @@ func TestGenerateKMSPodConfig_Managed(t *testing.T) { }, }, { - name: "When managed the KMS container should NOT have workload identity env vars", + name: "When managed, it should NOT have workload identity env vars in KMS container", check: func(g Gomega, podConfig *KMSPodConfig) { for _, c := range podConfig.Containers { if c.Name == "azure-kms-provider-active" { @@ -441,39 +441,39 @@ func TestGenerateKMSPodConfig_ActiveContainerArgs(t *testing.T) { expected string }{ { - name: "When active KMS container is created it should pass the key vault name", + name: "When active KMS container is created, it should pass the key vault name", expected: "--keyvault-name=test-vault", }, { - name: "When active KMS container is created it should pass the key name", + name: "When active KMS container is created, it should pass the key name", expected: "--key-name=test-key", }, { - name: "When active KMS container is created it should pass the key version", + name: "When active KMS container is created, it should pass the key version", expected: "--key-version=1", }, { - name: "When active KMS container is created it should listen on the active unix socket", + name: "When active KMS container is created, it should listen on the active unix socket", expected: fmt.Sprintf("--listen-addr=unix:///opt/%s", azureActiveKMSUnixSocketFileName), }, { - name: "When active KMS container is created it should use port 8787 for health checks", + name: "When active KMS container is created, it should use port 8787 for health checks", expected: fmt.Sprintf("--healthz-port=%d", azureActiveKMSHealthPort), }, { - name: "When active KMS container is created it should expose metrics on port 8095", + name: "When active KMS container is created, it should expose metrics on port 8095", expected: fmt.Sprintf("--metrics-addr=%s", azureActiveKMSMetricsAddr), }, { - name: "When active KMS container is created it should set the healthz path", + name: "When active KMS container is created, it should set the healthz path", expected: "--healthz-path=/healthz", }, { - name: "When active KMS container is created it should point to the azure.json config file", + name: "When active KMS container is created, it should point to the azure.json config file", expected: "--config-file-path=/etc/kubernetes/azure.json", }, { - name: "When active KMS container is created it should enable verbose logging", + name: "When active KMS container is created, it should enable verbose logging", expected: "-v=1", }, } @@ -505,23 +505,23 @@ func TestGenerateKMSPodConfig_BackupContainerArgs(t *testing.T) { expected string }{ { - name: "When backup KMS container is created it should pass the backup key vault name", + name: "When backup KMS container is created, it should pass the backup key vault name", expected: "--keyvault-name=test-vault", }, { - name: "When backup KMS container is created it should pass the backup key name", + name: "When backup KMS container is created, it should pass the backup key name", expected: "--key-name=backup-key", }, { - name: "When backup KMS container is created it should listen on the backup unix socket", + name: "When backup KMS container is created, it should listen on the backup unix socket", expected: fmt.Sprintf("--listen-addr=unix:///opt/%s", azureBackupKMSUnixSocketFileName), }, { - name: "When backup KMS container is created it should use port 8788 for health checks", + name: "When backup KMS container is created, it should use port 8788 for health checks", expected: fmt.Sprintf("--healthz-port=%d", azureBackupKMSHealthPort), }, { - name: "When backup KMS container is created it should expose metrics on port 8096", + name: "When backup KMS container is created, it should expose metrics on port 8096", expected: fmt.Sprintf("--metrics-addr=%s", azureBackupKMSMetricsAddr), }, } @@ -902,13 +902,13 @@ func TestAdaptAzureSecretProvider(t *testing.T) { errContains string }{ { - name: "When managed identity credentials secret name is empty it should return an error", + name: "When managed identity credentials secret name is empty, it should return an error", credSecret: "", expectError: true, errContains: "managed identity credentials secret name is required", }, { - name: "When managed identity credentials secret name is set it should succeed", + name: "When managed identity credentials secret name is set, it should succeed", credSecret: "kms-identity-creds", expectError: false, }, diff --git a/control-plane-operator/controllers/hostedcontrolplane/v2/kas/kms_test.go b/control-plane-operator/controllers/hostedcontrolplane/v2/kas/kms_test.go index b15d1f75b370..c34fe210704d 100644 --- a/control-plane-operator/controllers/hostedcontrolplane/v2/kas/kms_test.go +++ b/control-plane-operator/controllers/hostedcontrolplane/v2/kas/kms_test.go @@ -23,7 +23,7 @@ func TestDeriveKMSKeys(t *testing.T) { validate func(g Gomega, keys kmsWriteReadKeys) }{ { - name: "When AWS with nil status it should use spec active key as write with spec backup as read", + name: "When AWS with nil status, it should use spec active key as write with spec backup as read", kmsSpec: &hyperv1.KMSSpec{ Provider: hyperv1.AWS, AWS: &hyperv1.AWSKMSSpec{ @@ -41,7 +41,7 @@ func TestDeriveKMSKeys(t *testing.T) { }, }, { - name: "When AWS with status set but no target key it should use only write key", + name: "When AWS with status set but no target key, it should use only write key", kmsSpec: &hyperv1.KMSSpec{ Provider: hyperv1.AWS, AWS: &hyperv1.AWSKMSSpec{ @@ -62,7 +62,7 @@ func TestDeriveKMSKeys(t *testing.T) { }, }, { - name: "When AWS rotation in progress and target key absent from config it should use old key as write (ReadOnlyDeploy)", + name: "When AWS rotation in progress and target key absent from config, it should use old key as write (ReadOnlyDeploy)", kmsSpec: &hyperv1.KMSSpec{ Provider: hyperv1.AWS, AWS: &hyperv1.AWSKMSSpec{ @@ -87,7 +87,7 @@ func TestDeriveKMSKeys(t *testing.T) { }, }, { - name: "When AWS rotation in progress and target key present in config it should promote target to write (WritePromote)", + name: "When AWS rotation in progress and target key present in config, it should promote target to write (WritePromote)", kmsSpec: &hyperv1.KMSSpec{ Provider: hyperv1.AWS, AWS: &hyperv1.AWSKMSSpec{ @@ -116,7 +116,7 @@ func TestDeriveKMSKeys(t *testing.T) { }, }, { - name: "When Azure rotation in progress and target key absent from config it should use old key as write", + name: "When Azure rotation in progress and target key absent from config, it should use old key as write", kmsSpec: &hyperv1.KMSSpec{ Provider: hyperv1.AZURE, Azure: &hyperv1.AzureKMSSpec{ diff --git a/control-plane-operator/controllers/hostedcontrolplane/v2/kas/params_test.go b/control-plane-operator/controllers/hostedcontrolplane/v2/kas/params_test.go index 2011fc141157..b80a1f9bceef 100644 --- a/control-plane-operator/controllers/hostedcontrolplane/v2/kas/params_test.go +++ b/control-plane-operator/controllers/hostedcontrolplane/v2/kas/params_test.go @@ -29,27 +29,27 @@ func TestNewAPIServerParamsAPIAdvertiseAddressAndPort(t *testing.T) { expectedPort int32 }{ { - name: "not specified", + name: "When advertise address and port are not specified, it should use defaults", expectedAddress: config.DefaultAdvertiseIPv4Address, serviceNetworkCIDR: "10.0.0.0/24", expectedPort: config.KASPodDefaultPort, }, { - name: "address specified", + name: "When advertise address is specified, it should use the configured address", advertiseAddress: "1.2.3.4", serviceNetworkCIDR: "10.0.0.0/24", expectedAddress: "1.2.3.4", expectedPort: config.KASPodDefaultPort, }, { - name: "port set for default service publishing strategies", + name: "When port is set for default service publishing strategies, it should use the configured port", port: ptr.To[int32](6789), serviceNetworkCIDR: "10.0.0.0/24", expectedAddress: config.DefaultAdvertiseIPv4Address, expectedPort: 6789, }, { - name: "port set for NodePort service Publishing Strategy", + name: "When port is set for NodePort service publishing strategy, it should use the configured port", apiServiceMapping: hyperv1.ServicePublishingStrategyMapping{ Service: hyperv1.APIServer, ServicePublishingStrategy: hyperv1.ServicePublishingStrategy{ @@ -140,14 +140,14 @@ func TestNewConfigParams(t *testing.T) { expected func(*hyperv1.HostedControlPlane, []string) KubeAPIServerConfigParams }{ { - name: "defaults", + name: "When no custom configuration is provided, it should use defaults", hcp: createDefaultHostedControlPlane(), expected: func(hcp *hyperv1.HostedControlPlane, featureGates []string) KubeAPIServerConfigParams { return defaultKubeAPIServerConfigParams() }, }, { - name: "with feature gates", + name: "When feature gates are provided, it should include them in params", hcp: createDefaultHostedControlPlane(), featureGates: []string{"SomeFeatureGate=true", "AnotherFeatureGate=false"}, expected: func(hcp *hyperv1.HostedControlPlane, featureGates []string) KubeAPIServerConfigParams { @@ -157,7 +157,7 @@ func TestNewConfigParams(t *testing.T) { }, }, { - name: "AWS platform", + name: "When platform is AWS, it should set cloud provider to aws", hcp: func() *hyperv1.HostedControlPlane { hcp := createDefaultHostedControlPlane() hcp.Spec.Platform.Type = hyperv1.AWSPlatform @@ -171,7 +171,7 @@ func TestNewConfigParams(t *testing.T) { }, }, { - name: "IBM Cloud platform", + name: "When platform is IBM Cloud, it should customize STS directives and console URL", hcp: func() *hyperv1.HostedControlPlane { hcp := createDefaultHostedControlPlane() hcp.Spec.Platform.Type = hyperv1.IBMCloudPlatform @@ -186,7 +186,7 @@ func TestNewConfigParams(t *testing.T) { }, }, { - name: "managed etcd", + name: "When etcd is managed, it should set etcd URL to cluster service", hcp: func() *hyperv1.HostedControlPlane { hcp := createDefaultHostedControlPlane() hcp.Spec.Etcd.ManagementType = hyperv1.Managed @@ -201,7 +201,7 @@ func TestNewConfigParams(t *testing.T) { }, }, { - name: "unmanaged etcd", + name: "When etcd is unmanaged, it should use external endpoint", hcp: func() *hyperv1.HostedControlPlane { hcp := createDefaultHostedControlPlane() hcp.Spec.Etcd.ManagementType = hyperv1.Unmanaged @@ -218,7 +218,7 @@ func TestNewConfigParams(t *testing.T) { }, }, { - name: "managed etcd with shards", + name: "When managed etcd has shards, it should configure server overrides", hcp: func() *hyperv1.HostedControlPlane { hcp := createDefaultHostedControlPlane() hcp.Spec.Etcd.ManagementType = hyperv1.Managed @@ -258,7 +258,7 @@ func TestNewConfigParams(t *testing.T) { }, }, { - name: "unmanaged etcd with shards", + name: "When unmanaged etcd has shards, it should configure server overrides", hcp: func() *hyperv1.HostedControlPlane { hcp := createDefaultHostedControlPlane() hcp.Spec.Etcd.ManagementType = hyperv1.Unmanaged @@ -287,7 +287,7 @@ func TestNewConfigParams(t *testing.T) { }, }, { - name: "single replica controller availability policy", + name: "When controller availability policy is single replica, it should disable GoAway", hcp: func() *hyperv1.HostedControlPlane { hcp := createDefaultHostedControlPlane() hcp.Spec.ControllerAvailabilityPolicy = hyperv1.SingleReplica @@ -301,7 +301,7 @@ func TestNewConfigParams(t *testing.T) { }, }, { - name: "single replica controller availability policy with custom annotation", + name: "When single replica has custom GoAway annotation, it should use the annotation value", hcp: func() *hyperv1.HostedControlPlane { hcp := createDefaultHostedControlPlane() hcp.Annotations = map[string]string{ @@ -318,7 +318,7 @@ func TestNewConfigParams(t *testing.T) { }, }, { - name: "audit webhook enabled", + name: "When audit webhook is configured, it should enable audit webhook", hcp: func() *hyperv1.HostedControlPlane { hcp := createDefaultHostedControlPlane() hcp.Spec.AuditWebhook = &corev1.LocalObjectReference{Name: "audit-webhook"} @@ -332,7 +332,7 @@ func TestNewConfigParams(t *testing.T) { }, }, { - name: "with custom annotations", + name: "When custom resource and profiling annotations are set, it should apply them to params", hcp: func() *hyperv1.HostedControlPlane { hcp := createDefaultHostedControlPlane() hcp.Annotations = map[string]string{ @@ -354,7 +354,7 @@ func TestNewConfigParams(t *testing.T) { }, }, { - name: "with service account token max expiration annotation", + name: "When service account token max expiration is set, it should configure token expiration", hcp: func() *hyperv1.HostedControlPlane { hcp := createDefaultHostedControlPlane() hcp.Annotations = map[string]string{ @@ -370,7 +370,7 @@ func TestNewConfigParams(t *testing.T) { }, }, { - name: "with full configuration", + name: "When full configuration is provided, it should apply all custom settings", hcp: func() *hyperv1.HostedControlPlane { hcp := createDefaultHostedControlPlane() hcp.Spec.Configuration = &hyperv1.ClusterConfiguration{ @@ -425,7 +425,7 @@ func TestNewConfigParams(t *testing.T) { }, }, { - name: "when image registry is disabled, it should clear internal registry hostname", + name: "When image registry is disabled, it should clear internal registry hostname", hcp: func() *hyperv1.HostedControlPlane { hcp := createDefaultHostedControlPlane() hcp.Spec.Capabilities = &hyperv1.Capabilities{ @@ -441,7 +441,7 @@ func TestNewConfigParams(t *testing.T) { }, }, { - name: "when service network is IPv6, it should use IPv6 advertise address", + name: "When service network is IPv6, it should use IPv6 advertise address", hcp: func() *hyperv1.HostedControlPlane { hcp := createDefaultHostedControlPlane() hcp.Spec.Networking.ServiceNetwork = []hyperv1.ServiceNetworkEntry{ @@ -462,7 +462,7 @@ func TestNewConfigParams(t *testing.T) { }, }, { - name: "when networks are dual-stack, it should include all CIDRs", + name: "When networks are dual-stack, it should include all CIDRs", hcp: func() *hyperv1.HostedControlPlane { hcp := createDefaultHostedControlPlane() hcp.Spec.Networking.ClusterNetwork = []hyperv1.ClusterNetworkEntry{ @@ -484,7 +484,7 @@ func TestNewConfigParams(t *testing.T) { }, }, { - name: "when named certificates are configured, it should set them on params", + name: "When named certificates are configured, it should set them on params", hcp: func() *hyperv1.HostedControlPlane { hcp := createDefaultHostedControlPlane() hcp.Spec.Configuration = &hyperv1.ClusterConfiguration{ @@ -514,7 +514,7 @@ func TestNewConfigParams(t *testing.T) { }, }, { - name: "when audit webhook name is empty, it should not enable audit webhook", + name: "When audit webhook name is empty, it should not enable audit webhook", hcp: func() *hyperv1.HostedControlPlane { hcp := createDefaultHostedControlPlane() hcp.Spec.AuditWebhook = &corev1.LocalObjectReference{Name: ""} @@ -527,7 +527,7 @@ func TestNewConfigParams(t *testing.T) { }, }, { - name: "when disable profiling targets non-KAS component, it should not disable profiling", + name: "When disable profiling targets non-KAS component, it should not disable profiling", hcp: func() *hyperv1.HostedControlPlane { hcp := createDefaultHostedControlPlane() hcp.Annotations = map[string]string{ @@ -542,7 +542,7 @@ func TestNewConfigParams(t *testing.T) { }, }, { - name: "when custom DNS base domain prefix is set, it should use it in console URL", + name: "When custom DNS base domain prefix is set, it should use it in console URL", hcp: func() *hyperv1.HostedControlPlane { hcp := createDefaultHostedControlPlane() hcp.Spec.DNS.BaseDomainPrefix = ptr.To("custom-prefix") @@ -556,7 +556,7 @@ func TestNewConfigParams(t *testing.T) { }, }, { - name: "when DNS base domain prefix is empty, it should omit prefix from console URL", + name: "When DNS base domain prefix is empty, it should omit prefix from console URL", hcp: func() *hyperv1.HostedControlPlane { hcp := createDefaultHostedControlPlane() hcp.Spec.DNS.BaseDomainPrefix = ptr.To("") diff --git a/control-plane-operator/controllers/hostedcontrolplane/v2/kas/secretencryption_test.go b/control-plane-operator/controllers/hostedcontrolplane/v2/kas/secretencryption_test.go index 09206f0a1b25..fb4cab106810 100644 --- a/control-plane-operator/controllers/hostedcontrolplane/v2/kas/secretencryption_test.go +++ b/control-plane-operator/controllers/hostedcontrolplane/v2/kas/secretencryption_test.go @@ -713,7 +713,7 @@ func TestDeriveAESCBCEncryptionConfig(t *testing.T) { }, }, { - name: "When rotation in progress and target key should be promoted it should swap keys", + name: "When rotation is in progress and target key should be promoted, it should swap keys", secretObjects: []*corev1.Secret{ newAESCBCKeySecret("old-key-secret", []byte("old-key-data")), newAESCBCKeySecret("new-key-secret", []byte("new-key-data")), diff --git a/control-plane-operator/controllers/hostedcontrolplane/v2/kas/servicemonitor_test.go b/control-plane-operator/controllers/hostedcontrolplane/v2/kas/servicemonitor_test.go index 97f6c0f2aa38..653ad4978f16 100644 --- a/control-plane-operator/controllers/hostedcontrolplane/v2/kas/servicemonitor_test.go +++ b/control-plane-operator/controllers/hostedcontrolplane/v2/kas/servicemonitor_test.go @@ -79,7 +79,7 @@ func TestAdaptServiceMonitor(t *testing.T) { }, }, { - name: "When metrics set is SRE with no config loaded, MetricRelabelConfigs should only contain cluster ID", + name: "When metrics set is SRE with no config loaded, it should only contain cluster ID in MetricRelabelConfigs", metricsSet: metrics.MetricsSetSRE, clusterID: "test-cluster", validate: func(t *testing.T, sm *prometheusoperatorv1.ServiceMonitor, err error) { diff --git a/control-plane-operator/controllers/hostedcontrolplane/v2/konnectivity_agent/component_test.go b/control-plane-operator/controllers/hostedcontrolplane/v2/konnectivity_agent/component_test.go index 2c6290ee0809..5b972ec207f6 100644 --- a/control-plane-operator/controllers/hostedcontrolplane/v2/konnectivity_agent/component_test.go +++ b/control-plane-operator/controllers/hostedcontrolplane/v2/konnectivity_agent/component_test.go @@ -14,7 +14,7 @@ func TestKonnectivityAgentIsRequestServing(t *testing.T) { expected bool }{ { - name: "When called it should return false", + name: "When called, it should return false", expected: false, }, } @@ -40,7 +40,7 @@ func TestKonnectivityAgentMultiZoneSpread(t *testing.T) { expected bool }{ { - name: "When called it should return true", + name: "When called, it should return true", expected: true, }, } @@ -66,7 +66,7 @@ func TestKonnectivityAgentNeedsManagementKASAccess(t *testing.T) { expected bool }{ { - name: "When called it should return false", + name: "When called, it should return false", expected: false, }, } diff --git a/control-plane-operator/controllers/hostedcontrolplane/v2/kube_scheduler/servicemonitor_test.go b/control-plane-operator/controllers/hostedcontrolplane/v2/kube_scheduler/servicemonitor_test.go index 836acbf94653..9c2646ac1174 100644 --- a/control-plane-operator/controllers/hostedcontrolplane/v2/kube_scheduler/servicemonitor_test.go +++ b/control-plane-operator/controllers/hostedcontrolplane/v2/kube_scheduler/servicemonitor_test.go @@ -24,7 +24,7 @@ func TestAdaptServiceMonitor(t *testing.T) { validate func(*testing.T, *prometheusoperatorv1.ServiceMonitor, error) }{ { - name: "When service monitor is adapted it should set namespace selector", + name: "When service monitor is adapted, it should set namespace selector", metricsSet: metrics.MetricsSetTelemetry, clusterID: "test-cluster-id", validate: func(t *testing.T, sm *prometheusoperatorv1.ServiceMonitor, err error) { @@ -34,7 +34,7 @@ func TestAdaptServiceMonitor(t *testing.T) { }, }, { - name: "When service monitor is adapted it should apply cluster ID label to both endpoints", + name: "When service monitor is adapted, it should apply cluster ID label to both endpoints", metricsSet: metrics.MetricsSetAll, clusterID: "cluster-abc-123", validate: func(t *testing.T, sm *prometheusoperatorv1.ServiceMonitor, err error) { @@ -55,7 +55,7 @@ func TestAdaptServiceMonitor(t *testing.T) { }, }, { - name: "When metrics set is Telemetry it should drop all metrics on both endpoints", + name: "When metrics set is Telemetry, it should drop all metrics on both endpoints", metricsSet: metrics.MetricsSetTelemetry, clusterID: "test-cluster", validate: func(t *testing.T, sm *prometheusoperatorv1.ServiceMonitor, err error) { @@ -73,7 +73,7 @@ func TestAdaptServiceMonitor(t *testing.T) { }, }, { - name: "When metrics set is All it should not add metric relabel configs on the resources endpoint", + name: "When metrics set is All, it should not add metric relabel configs on the resources endpoint", metricsSet: metrics.MetricsSetAll, clusterID: "test-cluster", validate: func(t *testing.T, sm *prometheusoperatorv1.ServiceMonitor, err error) { diff --git a/control-plane-operator/controllers/hostedcontrolplane/v2/oauth/idp_convert_test.go b/control-plane-operator/controllers/hostedcontrolplane/v2/oauth/idp_convert_test.go index a5e6e474c9db..dc9bb5d98829 100644 --- a/control-plane-operator/controllers/hostedcontrolplane/v2/oauth/idp_convert_test.go +++ b/control-plane-operator/controllers/hostedcontrolplane/v2/oauth/idp_convert_test.go @@ -935,7 +935,7 @@ func TestTransportForCARef(t *testing.T) { expectedProxyRequestURL string }{ { - name: "When no proxy configuration is provided, the transport should not be modified", + name: "When no proxy configuration is provided, it should not modify the transport", hcp: &hyperv1.HostedControlPlane{ ObjectMeta: metav1.ObjectMeta{ Name: "hcp-test", @@ -947,7 +947,7 @@ func TestTransportForCARef(t *testing.T) { expectedProxyRequestURL: "", }, { - name: "When proxy configuration is provided, the transport should use proxy", + name: "When proxy configuration is provided, it should use proxy for the transport", hcp: &hyperv1.HostedControlPlane{ ObjectMeta: metav1.ObjectMeta{ Name: "hcp-test", @@ -971,7 +971,7 @@ func TestTransportForCARef(t *testing.T) { expectedProxyRequestURL: "https://10.0.0.1", }, { - name: "When proxy configuration is provided and request is to ignored url, the transport should not use proxy", + name: "When proxy configuration is provided and request is to ignored url, it should not use proxy for the transport", hcp: &hyperv1.HostedControlPlane{ ObjectMeta: metav1.ObjectMeta{ Name: "hcp-test", diff --git a/control-plane-operator/controllers/hostedcontrolplane/v2/router/component_test.go b/control-plane-operator/controllers/hostedcontrolplane/v2/router/component_test.go index 8650e7786e7c..78c4c28f9b09 100644 --- a/control-plane-operator/controllers/hostedcontrolplane/v2/router/component_test.go +++ b/control-plane-operator/controllers/hostedcontrolplane/v2/router/component_test.go @@ -28,7 +28,7 @@ func TestUseHCPRouter(t *testing.T) { want bool }{ { - name: "When platform is IBMCloud it should return false", + name: "When platform is IBMCloud, it should return false", hcp: &hyperv1.HostedControlPlane{ Spec: hyperv1.HostedControlPlaneSpec{ Platform: hyperv1.PlatformSpec{ @@ -39,7 +39,7 @@ func TestUseHCPRouter(t *testing.T) { want: false, }, { - name: "When ARO Swift is enabled it should return true because the HCP router handles routing", + name: "When ARO Swift is enabled, it should return true because the HCP router handles routing", hcp: &hyperv1.HostedControlPlane{ ObjectMeta: metav1.ObjectMeta{ Annotations: map[string]string{ @@ -58,7 +58,7 @@ func TestUseHCPRouter(t *testing.T) { want: true, }, { - name: "When ARO with no Swift annotation (CI) it should return false", + name: "When ARO with no Swift annotation (CI), it should return false", hcp: &hyperv1.HostedControlPlane{ Spec: hyperv1.HostedControlPlaneSpec{ Platform: hyperv1.PlatformSpec{ @@ -72,7 +72,7 @@ func TestUseHCPRouter(t *testing.T) { want: false, }, { - name: "When NonePlatform has services exposed with Routes it should return true", + name: "When NonePlatform has services exposed with Routes, it should return true", hcp: &hyperv1.HostedControlPlane{ Spec: hyperv1.HostedControlPlaneSpec{ Platform: hyperv1.PlatformSpec{ @@ -121,7 +121,7 @@ func TestUseHCPRouter(t *testing.T) { want: true, }, { - name: "When AWS has private endpoint access it should return true", + name: "When AWS has private endpoint access, it should return true", hcp: &hyperv1.HostedControlPlane{ Spec: hyperv1.HostedControlPlaneSpec{ Platform: hyperv1.PlatformSpec{ @@ -135,7 +135,7 @@ func TestUseHCPRouter(t *testing.T) { want: true, }, { - name: "When AWS has public and private endpoint access with KAS LoadBalancer it should return true", + name: "When AWS has public and private endpoint access with KAS LoadBalancer, it should return true", hcp: &hyperv1.HostedControlPlane{ Spec: hyperv1.HostedControlPlaneSpec{ Platform: hyperv1.PlatformSpec{ @@ -157,7 +157,7 @@ func TestUseHCPRouter(t *testing.T) { want: true, // Router infrastructure needed for internal routes }, { - name: "When AWS has public and private endpoint access with KAS Route it should return true", + name: "When AWS has public and private endpoint access with KAS Route, it should return true", hcp: &hyperv1.HostedControlPlane{ Spec: hyperv1.HostedControlPlaneSpec{ Platform: hyperv1.PlatformSpec{ @@ -182,7 +182,7 @@ func TestUseHCPRouter(t *testing.T) { want: true, }, { - name: "When AWS has public endpoint access without DNS it should return false", + name: "When AWS has public endpoint access without DNS, it should return false", hcp: &hyperv1.HostedControlPlane{ Spec: hyperv1.HostedControlPlaneSpec{ Platform: hyperv1.PlatformSpec{ @@ -196,7 +196,7 @@ func TestUseHCPRouter(t *testing.T) { want: false, }, { - name: "When AWS has public endpoint access with DNS for APIServer it should return true", + name: "When AWS has public endpoint access with DNS for APIServer, it should return true", hcp: &hyperv1.HostedControlPlane{ Spec: hyperv1.HostedControlPlaneSpec{ Platform: hyperv1.PlatformSpec{ @@ -221,7 +221,7 @@ func TestUseHCPRouter(t *testing.T) { want: true, }, { - name: "When GCP has private endpoint access it should return true", + name: "When GCP has private endpoint access, it should return true", hcp: &hyperv1.HostedControlPlane{ Spec: hyperv1.HostedControlPlaneSpec{ Platform: hyperv1.PlatformSpec{ @@ -235,7 +235,7 @@ func TestUseHCPRouter(t *testing.T) { want: true, }, { - name: "When GCP has public and private endpoint access with KAS Route it should return true", + name: "When GCP has public and private endpoint access with KAS Route, it should return true", hcp: &hyperv1.HostedControlPlane{ Spec: hyperv1.HostedControlPlaneSpec{ Platform: hyperv1.PlatformSpec{ @@ -260,7 +260,7 @@ func TestUseHCPRouter(t *testing.T) { want: true, }, { - name: "When Agent platform has KAS LoadBalancer it should return false", + name: "When Agent platform has KAS LoadBalancer, it should return false", hcp: &hyperv1.HostedControlPlane{ Spec: hyperv1.HostedControlPlaneSpec{ Platform: hyperv1.PlatformSpec{ @@ -282,7 +282,7 @@ func TestUseHCPRouter(t *testing.T) { want: false, // Router infrastructure not needed when KAS uses LoadBalancer }, { - name: "When Agent platform has KAS Route it should return true", + name: "When Agent platform has KAS Route, it should return true", hcp: &hyperv1.HostedControlPlane{ Spec: hyperv1.HostedControlPlaneSpec{ Platform: hyperv1.PlatformSpec{ @@ -307,7 +307,7 @@ func TestUseHCPRouter(t *testing.T) { want: true, }, { - name: "When platform is None it should return false", + name: "When platform is None, it should return false", hcp: &hyperv1.HostedControlPlane{ Spec: hyperv1.HostedControlPlaneSpec{ Platform: hyperv1.PlatformSpec{ diff --git a/control-plane-operator/hostedclusterconfigoperator/controllers/globalps/globalps_test.go b/control-plane-operator/hostedclusterconfigoperator/controllers/globalps/globalps_test.go index e544a4533136..ea99448e8f00 100644 --- a/control-plane-operator/hostedclusterconfigoperator/controllers/globalps/globalps_test.go +++ b/control-plane-operator/hostedclusterconfigoperator/controllers/globalps/globalps_test.go @@ -444,7 +444,7 @@ func TestValidateAdditionalPullSecret(t *testing.T) { wantErr bool }{ { - name: "valid pull secret", + name: "When pull secret has valid docker config, it should pass validation", secret: &corev1.Secret{ Data: map[string][]byte{ corev1.DockerConfigJsonKey: composePullSecretBytes(map[string]string{"quay.io": validAuth}), @@ -453,7 +453,7 @@ func TestValidateAdditionalPullSecret(t *testing.T) { wantErr: false, }, { - name: "missing docker config key", + name: "When pull secret is missing docker config key, it should return error", secret: &corev1.Secret{ Data: map[string][]byte{ "wrong-key": composePullSecretBytes(map[string]string{"quay.io": validAuth}), @@ -462,7 +462,7 @@ func TestValidateAdditionalPullSecret(t *testing.T) { wantErr: true, }, { - name: "invalid json", + name: "When pull secret has invalid json, it should return error", secret: &corev1.Secret{ Data: map[string][]byte{ corev1.DockerConfigJsonKey: []byte(`invalid json`), @@ -471,7 +471,7 @@ func TestValidateAdditionalPullSecret(t *testing.T) { wantErr: true, }, { - name: "empty auths", + name: "When pull secret has empty auths, it should return error", secret: &corev1.Secret{ Data: map[string][]byte{ corev1.DockerConfigJsonKey: []byte(`{"auths":{}}`), @@ -503,68 +503,68 @@ func TestMergePullSecrets(t *testing.T) { wantErr bool }{ { - name: "successful merge with 1 entries", + name: "When merging one entry from each secret, it should combine both registries", originalSecret: composePullSecretBytes(map[string]string{"registry1": validAuth}), additionalSecret: composePullSecretBytes(map[string]string{"registry2": validAuth}), expectedResult: composePullSecretBytes(map[string]string{"registry1": validAuth, "registry2": validAuth}), wantErr: false, }, { - name: "successful merge with 2 entries in additional secret", + name: "When additional secret has two entries, it should merge all registries", originalSecret: composePullSecretBytes(map[string]string{"registry1": validAuth}), additionalSecret: composePullSecretBytes(map[string]string{"registry2": validAuth, "registry3": validAuth}), expectedResult: composePullSecretBytes(map[string]string{"registry1": validAuth, "registry2": validAuth, "registry3": validAuth}), wantErr: false, }, { - name: "successful merge with 2 entries in original secret", + name: "When original secret has two entries, it should merge all registries", originalSecret: composePullSecretBytes(map[string]string{"registry1": validAuth, "registry2": validAuth}), additionalSecret: composePullSecretBytes(map[string]string{"registry3": validAuth}), expectedResult: composePullSecretBytes(map[string]string{"registry1": validAuth, "registry2": validAuth, "registry3": validAuth}), wantErr: false, }, { - name: "conflict resolution - original always wins", + name: "When registries conflict, it should preserve original secret credentials", originalSecret: composePullSecretBytes(map[string]string{"registry1": oldAuth}), additionalSecret: composePullSecretBytes(map[string]string{"registry1": validAuth}), expectedResult: composePullSecretBytes(map[string]string{"registry1": oldAuth}), wantErr: false, }, { - name: "precedence test - original always has precedence", + name: "When registries overlap, it should give precedence to original secret", originalSecret: composePullSecretBytes(map[string]string{"registry1": oldAuth, "registry2": oldAuth}), additionalSecret: composePullSecretBytes(map[string]string{"registry1": validAuth, "registry3": validAuth}), expectedResult: composePullSecretBytes(map[string]string{"registry1": oldAuth, "registry2": oldAuth, "registry3": validAuth}), wantErr: false, }, { - name: "multiple conflicts - original always wins", + name: "When multiple registries conflict, it should preserve all original credentials", originalSecret: composePullSecretBytes(map[string]string{"registry1": oldAuth, "registry2": oldAuth}), additionalSecret: composePullSecretBytes(map[string]string{"registry1": validAuth, "registry2": validAuth, "registry3": validAuth}), expectedResult: composePullSecretBytes(map[string]string{"registry1": oldAuth, "registry2": oldAuth, "registry3": validAuth}), wantErr: false, }, { - name: "invalid original secret", + name: "When original secret has invalid json, it should return error", originalSecret: []byte(`invalid json`), additionalSecret: composePullSecretBytes(map[string]string{"registry1": validAuth}), wantErr: true, }, { - name: "invalid additional secret", + name: "When additional secret has invalid json, it should return error", originalSecret: composePullSecretBytes(map[string]string{"registry1": validAuth}), additionalSecret: []byte(`invalid json`), wantErr: true, }, { - name: "empty additional secret, invalid JSON", + name: "When additional secret has empty invalid json, it should return error", originalSecret: composePullSecretBytes(map[string]string{"registry1": validAuth}), additionalSecret: []byte{}, expectedResult: composePullSecretBytes(map[string]string{"registry1": validAuth}), wantErr: true, }, { - name: "empty additional secret with valid JSON", + name: "When additional secret has empty valid json, it should return original secret unchanged", originalSecret: composePullSecretBytes(map[string]string{"registry1": validAuth, "registry2": validAuth}), additionalSecret: []byte(`{"auths":{}}`), expectedResult: composePullSecretBytes(map[string]string{"registry1": validAuth, "registry2": validAuth}), @@ -612,7 +612,7 @@ func TestAdditionalPullSecretExists(t *testing.T) { objects []client.Object }{ { - name: "secret exists", + name: "When additional pull secret exists, it should return true with secret data", secretExists: true, expectedExists: true, expectedSecret: &corev1.Secret{ @@ -637,7 +637,7 @@ func TestAdditionalPullSecretExists(t *testing.T) { }, }, { - name: "secret exists but has no content", + name: "When additional pull secret exists without content, it should return true with nil data", secretExists: true, expectedExists: true, expectedSecret: &corev1.Secret{ @@ -658,7 +658,7 @@ func TestAdditionalPullSecretExists(t *testing.T) { }, }, { - name: "secret exists but has incorrect content", + name: "When additional pull secret exists with invalid content, it should return true with raw data", secretExists: true, expectedExists: true, expectedSecret: &corev1.Secret{ @@ -683,7 +683,7 @@ func TestAdditionalPullSecretExists(t *testing.T) { }, }, { - name: "secret does not exist", + name: "When additional pull secret does not exist, it should return false", secretExists: false, expectedExists: false, expectedSecret: nil, diff --git a/control-plane-operator/hostedclusterconfigoperator/controllers/globalps/setup_test.go b/control-plane-operator/hostedclusterconfigoperator/controllers/globalps/setup_test.go index b471cce2632c..140941fb938f 100644 --- a/control-plane-operator/hostedclusterconfigoperator/controllers/globalps/setup_test.go +++ b/control-plane-operator/hostedclusterconfigoperator/controllers/globalps/setup_test.go @@ -10,21 +10,21 @@ import ( metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" ) -func Test_kubeSystemSecretPredicateFunc(t *testing.T) { +func TestKubeSystemSecretPredicateFunc(t *testing.T) { tests := []struct { name string object *corev1.Secret want bool }{ { - name: "When secret is in kube-system it should return true", + name: "When secret is in kube-system, it should return true", object: &corev1.Secret{ ObjectMeta: metav1.ObjectMeta{Namespace: "kube-system", Name: "any-secret"}, }, want: true, }, { - name: "When secret is in a different namespace it should return false", + name: "When secret is in a different namespace, it should return false", object: &corev1.Secret{ ObjectMeta: metav1.ObjectMeta{Namespace: "openshift-config", Name: "pull-secret"}, }, @@ -40,7 +40,7 @@ func Test_kubeSystemSecretPredicateFunc(t *testing.T) { } } -func Test_namespacedNamePredicateFunc(t *testing.T) { +func TestNamespacedNamePredicateFunc(t *testing.T) { predicate := namespacedNamePredicateFunc("my-hcp-namespace", "pull-secret") tests := []struct { @@ -49,21 +49,21 @@ func Test_namespacedNamePredicateFunc(t *testing.T) { want bool }{ { - name: "When namespace and name match it should return true", + name: "When namespace and name match, it should return true", object: &corev1.Secret{ ObjectMeta: metav1.ObjectMeta{Namespace: "my-hcp-namespace", Name: "pull-secret"}, }, want: true, }, { - name: "When namespace differs it should return false", + name: "When namespace differs, it should return false", object: &corev1.Secret{ ObjectMeta: metav1.ObjectMeta{Namespace: "other-namespace", Name: "pull-secret"}, }, want: false, }, { - name: "When name differs it should return false", + name: "When name differs, it should return false", object: &corev1.Secret{ ObjectMeta: metav1.ObjectMeta{Namespace: "my-hcp-namespace", Name: "other-secret"}, }, @@ -79,7 +79,7 @@ func Test_namespacedNamePredicateFunc(t *testing.T) { } } -func Test_staticReconcileMapper(t *testing.T) { +func TestStaticReconcileMapper(t *testing.T) { t.Run("When called it should return a single empty reconcile request", func(t *testing.T) { g := NewWithT(t) requests := staticReconcileMapper(context.Background(), &corev1.Secret{}) diff --git a/control-plane-operator/hostedclusterconfigoperator/controllers/hcpstatus/hcpstatus_test.go b/control-plane-operator/hostedclusterconfigoperator/controllers/hcpstatus/hcpstatus_test.go index 73655f694287..2a065cb0d020 100644 --- a/control-plane-operator/hostedclusterconfigoperator/controllers/hcpstatus/hcpstatus_test.go +++ b/control-plane-operator/hostedclusterconfigoperator/controllers/hcpstatus/hcpstatus_test.go @@ -55,7 +55,7 @@ func TestHCPStatusReconciler(t *testing.T) { expectedOAuthName: expectedOAuthConfigMapName, }, { - name: "When Authentication resource is missing it should return an error", + name: "When Authentication resource is missing, it should return an error", hostedClusterObjects: []crclient.Object{ &configv1.ClusterVersion{ObjectMeta: metav1.ObjectMeta{Name: "version"}}, }, diff --git a/control-plane-operator/hostedclusterconfigoperator/controllers/inplaceupgrader/inplaceupgrader_test.go b/control-plane-operator/hostedclusterconfigoperator/controllers/inplaceupgrader/inplaceupgrader_test.go index faab83854bcd..da06464eae52 100644 --- a/control-plane-operator/hostedclusterconfigoperator/controllers/inplaceupgrader/inplaceupgrader_test.go +++ b/control-plane-operator/hostedclusterconfigoperator/controllers/inplaceupgrader/inplaceupgrader_test.go @@ -169,7 +169,7 @@ func TestInPlaceUpgradeComplete(t *testing.T) { complete bool }{ { - name: "freshly installed nodepool", + name: "When nodepool is freshly installed, it should report complete", currentConfig: currentConfigHash, desiredConfig: currentConfigHash, nodes: []*corev1.Node{ @@ -183,7 +183,7 @@ func TestInPlaceUpgradeComplete(t *testing.T) { complete: true, }, { - name: "update starting", + name: "When update is starting, it should report not complete", currentConfig: currentConfigHash, desiredConfig: desiredConfigHash, nodes: []*corev1.Node{ @@ -197,7 +197,7 @@ func TestInPlaceUpgradeComplete(t *testing.T) { complete: false, }, { - name: "update in progress", + name: "When update is in progress, it should report not complete", currentConfig: currentConfigHash, desiredConfig: desiredConfigHash, nodes: []*corev1.Node{ @@ -219,7 +219,7 @@ func TestInPlaceUpgradeComplete(t *testing.T) { complete: false, }, { - name: "update completed but uncordon not yet finished", + name: "When update is completed but uncordon is pending, it should report not complete", currentConfig: currentConfigHash, desiredConfig: desiredConfigHash, nodes: []*corev1.Node{ @@ -247,7 +247,7 @@ func TestInPlaceUpgradeComplete(t *testing.T) { complete: false, }, { - name: "fully completed update", + name: "When update is fully completed, it should report complete", currentConfig: currentConfigHash, desiredConfig: desiredConfigHash, nodes: []*corev1.Node{ @@ -337,7 +337,7 @@ func TestGetNodesToUpgrade(t *testing.T) { selectedNodes []*corev1.Node }{ { - name: "pick first node to upgrade", + name: "When multiple nodes await upgrade, it should pick first node", inputNodes: []*corev1.Node{ awaitingNode1, awaitingNode2, @@ -349,7 +349,7 @@ func TestGetNodesToUpgrade(t *testing.T) { }, }, { - name: "select multiple nodes to upgrade", + name: "When maxUnavailable allows two, it should select multiple nodes", inputNodes: []*corev1.Node{ awaitingNode1, awaitingNode2, @@ -362,7 +362,7 @@ func TestGetNodesToUpgrade(t *testing.T) { }, }, { - name: "maxUnavailable reached", + name: "When maxUnavailable is reached, it should select no nodes", inputNodes: []*corev1.Node{ inProgressNode, }, @@ -371,7 +371,7 @@ func TestGetNodesToUpgrade(t *testing.T) { selectedNodes: nil, }, { - name: "all nodes comeplete", + name: "When all nodes are complete, it should select no nodes", inputNodes: []*corev1.Node{ completedNode, }, @@ -380,7 +380,7 @@ func TestGetNodesToUpgrade(t *testing.T) { selectedNodes: nil, }, { - name: "pick 1 ready node if possible", + name: "When one ready node exists with in-progress node, it should pick the ready node", inputNodes: []*corev1.Node{ awaitingNode1, inProgressNode, @@ -393,7 +393,7 @@ func TestGetNodesToUpgrade(t *testing.T) { }, }, { - name: "pick correct nodes to upgrade", + name: "When nodes are in mixed states, it should pick correct awaiting nodes", inputNodes: []*corev1.Node{ inProgressNode, completedNode, @@ -409,7 +409,7 @@ func TestGetNodesToUpgrade(t *testing.T) { }, // This test case covers a scenario where a new update comes in while an update is in progress { - name: "points in progress nodes to latest version", + name: "When new update arrives during upgrade, it should redirect in-progress nodes", inputNodes: []*corev1.Node{ awaitingNode1, completedNode, @@ -422,7 +422,7 @@ func TestGetNodesToUpgrade(t *testing.T) { }, }, { - name: "points in progress nodes to latest version, while also picking based on maxUnavailable", + name: "When new update arrives with capacity, it should redirect in-progress and pick awaiting nodes", inputNodes: []*corev1.Node{ awaitingNode1, completedNode, @@ -483,7 +483,7 @@ func TestGetAvailableCandidates(t *testing.T) { selectedNodes []*corev1.Node }{ { - name: "pick first node to upgrade", + name: "When multiple candidates exist, it should pick first node", inputNodes: []*corev1.Node{ awaitingNode1, awaitingNode2, @@ -495,7 +495,7 @@ func TestGetAvailableCandidates(t *testing.T) { }, }, { - name: "select non-completed node", + name: "When completed and awaiting nodes exist, it should select non-completed node", inputNodes: []*corev1.Node{ completedNode, awaitingNode1, @@ -507,7 +507,7 @@ func TestGetAvailableCandidates(t *testing.T) { }, }, { - name: "pick more nodes up to capacity", + name: "When capacity allows multiple, it should pick available nodes up to capacity", inputNodes: []*corev1.Node{ awaitingNode1, awaitingNode2, @@ -522,7 +522,7 @@ func TestGetAvailableCandidates(t *testing.T) { }, }, { - name: "do nothing while no additional capacity", + name: "When capacity is zero, it should select no nodes", inputNodes: []*corev1.Node{ awaitingNode1, awaitingNode2, @@ -549,7 +549,7 @@ func TestCreateUpgradePod(t *testing.T) { expectedEnvs []corev1.EnvVar }{ { - name: "when proxy is configured, it should create a pod with proxy environment variables", + name: "When proxy is configured, it should create a pod with proxy environment variables", node: &corev1.Node{ ObjectMeta: metav1.ObjectMeta{ Name: "test-node", @@ -569,7 +569,7 @@ func TestCreateUpgradePod(t *testing.T) { }, }, { - name: "when no proxy is configured it should create a pod without proxy environment variables", + name: "When no proxy is configured, it should create a pod without proxy environment variables", node: &corev1.Node{ ObjectMeta: metav1.ObjectMeta{ Name: "test-node", @@ -989,14 +989,14 @@ func TestReconcileInPlaceUpgradeDegradedNodeErrorMessage(t *testing.T) { expectError bool }{ { - name: "when a node is degraded it should include the node name in the error message", + name: "When a node is degraded, it should include the node name in the error message", nodeName: "degraded-node-xyz", mcdState: MachineConfigDaemonStateDegraded, mcdMessage: degradedReason, expectError: true, }, { - name: "when a node is not degraded it should not return a degraded error", + name: "When a node is not degraded, it should not return a degraded error", nodeName: "healthy-node", mcdState: MachineConfigDaemonStateDone, mcdMessage: "", diff --git a/control-plane-operator/hostedclusterconfigoperator/controllers/reencryption/reencryption_test.go b/control-plane-operator/hostedclusterconfigoperator/controllers/reencryption/reencryption_test.go index 0cc894ba1dbb..4c97d4e9a82a 100644 --- a/control-plane-operator/hostedclusterconfigoperator/controllers/reencryption/reencryption_test.go +++ b/control-plane-operator/hostedclusterconfigoperator/controllers/reencryption/reencryption_test.go @@ -382,7 +382,7 @@ func TestReconcile(t *testing.T) { validate func(*testing.T, Gomega, client.Client, *fakeMigrator) }{ { - name: "When encryption is not configured it should remove the condition and clear targetKey", + name: "When encryption is not configured, it should remove the condition and clear targetKey", cpObjects: []client.Object{ newHCP(), // no encryption spec convergedKASDeployment(testNamespace), @@ -395,7 +395,7 @@ func TestReconcile(t *testing.T) { }, }, { - name: "When encryption is configured with AESCBC and no active key in status it should initialize active key", + name: "When encryption is configured with AESCBC and no active key in status, it should initialize active key", cpObjects: []client.Object{ newHCP(withAESCBCEncryption("aescbc-key-1")), aescbcKeySecret("aescbc-key-1", testNamespace, "test-key-data-1"), @@ -419,7 +419,7 @@ func TestReconcile(t *testing.T) { }, }, { - name: "When encryption key is already up to date it should remain in steady state", + name: "When encryption key is already up to date, it should remain in steady state", cpObjects: func() []client.Object { dataHash := secretencryption.DataHash([]byte("test-key-data-1")) return []client.Object{ @@ -438,7 +438,7 @@ func TestReconcile(t *testing.T) { }, }, { - name: "When AESCBC key data changes it should start a new rotation", + name: "When AESCBC key data changes, it should start a new rotation", cpObjects: func() []client.Object { oldHash := secretencryption.DataHash([]byte("old-key-data")) return []client.Object{ @@ -469,7 +469,7 @@ func TestReconcile(t *testing.T) { }, }, { - name: "When in ReadOnlyDeploy phase and KAS is not converged it should wait", + name: "When in ReadOnlyDeploy phase and KAS is not converged, it should wait", cpObjects: func() []client.Object { oldHash := secretencryption.DataHash([]byte("old-key-data")) newHash := secretencryption.DataHash([]byte("new-key-data")) @@ -508,7 +508,7 @@ func TestReconcile(t *testing.T) { }, }, { - name: "When in ReadOnlyDeploy phase and KAS deployment is ready but config hash mismatches it should wait", + name: "When in ReadOnlyDeploy phase and KAS deployment is ready but config hash mismatches, it should wait", cpObjects: func() []client.Object { oldHash := secretencryption.DataHash([]byte("old-key-data")) newHash := secretencryption.DataHash([]byte("new-key-data")) @@ -547,7 +547,7 @@ func TestReconcile(t *testing.T) { }, }, { - name: "When in ReadOnlyDeploy phase and KAS is converged it should advance to WritePromote", + name: "When in ReadOnlyDeploy phase and KAS is converged, it should advance to WritePromote", cpObjects: func() []client.Object { oldHash := secretencryption.DataHash([]byte("old-key-data")) newHash := secretencryption.DataHash([]byte("new-key-data")) @@ -585,7 +585,7 @@ func TestReconcile(t *testing.T) { }, }, { - name: "When in WritePromote phase and KAS is converged it should advance to Migrating", + name: "When in WritePromote phase and KAS is converged, it should advance to Migrating", cpObjects: func() []client.Object { oldHash := secretencryption.DataHash([]byte("old-key-data")) newHash := secretencryption.DataHash([]byte("new-key-data")) @@ -626,7 +626,7 @@ func TestReconcile(t *testing.T) { }, }, { - name: "When in Migrating phase and migrations are in progress it should wait", + name: "When in Migrating phase and migrations are in progress, it should wait", cpObjects: func() []client.Object { oldHash := secretencryption.DataHash([]byte("old-key-data")) newHash := secretencryption.DataHash([]byte("new-key-data")) @@ -660,7 +660,7 @@ func TestReconcile(t *testing.T) { }, }, { - name: "When in Migrating phase and all AESCBC migrations complete it should complete rotation", + name: "When in Migrating phase and all AESCBC migrations complete, it should complete rotation", cpObjects: func() []client.Object { oldHash := secretencryption.DataHash([]byte("old-key-data")) newHash := secretencryption.DataHash([]byte("new-key-data")) @@ -713,7 +713,7 @@ func TestReconcile(t *testing.T) { }, }, { - name: "When in Migrating phase and a migration fails it should set failed condition", + name: "When in Migrating phase and a migration fails, it should set failed condition", cpObjects: func() []client.Object { oldHash := secretencryption.DataHash([]byte("old-key-data")) newHash := secretencryption.DataHash([]byte("new-key-data")) @@ -759,7 +759,7 @@ func TestReconcile(t *testing.T) { }, }, { - name: "When using AWS KMS and key ARN changes it should start rotation with 5 encrypted resources", + name: "When using AWS KMS and key ARN changes, it should start rotation with 5 encrypted resources", cpObjects: func() []client.Object { oldKS := awsKeyStatus("arn:aws:kms:us-east-1:123456789012:key/old-key") return []client.Object{ @@ -782,7 +782,7 @@ func TestReconcile(t *testing.T) { }, }, { - name: "When in Migrating phase with KMS and all 5 migrations complete it should complete rotation", + name: "When in Migrating phase with KMS and all 5 migrations complete, it should complete rotation", cpObjects: func() []client.Object { oldKS := awsKeyStatus("arn:aws:kms:us-east-1:123456789012:key/old-key") newKS := awsKeyStatus("arn:aws:kms:us-east-1:123456789012:key/test-key-1") @@ -833,7 +833,7 @@ func TestReconcile(t *testing.T) { }, }, { - name: "When spec key changes mid-rotation it should let current rotation complete first", + name: "When spec key changes mid-rotation, it should let current rotation complete first", cpObjects: func() []client.Object { oldHash := secretencryption.DataHash([]byte("old-key-data")) midHash := secretencryption.DataHash([]byte("mid-key-data")) @@ -881,7 +881,7 @@ func TestReconcile(t *testing.T) { }, }, { - name: "When in Migrating phase with KMS and some resources are not discoverable it should skip them and complete", + name: "When in Migrating phase with KMS and some resources are not discoverable, it should skip them and complete", cpObjects: func() []client.Object { oldKS := awsKeyStatus("arn:aws:kms:us-east-1:123456789012:key/old-key") newKS := awsKeyStatus("arn:aws:kms:us-east-1:123456789012:key/test-key-1") @@ -970,27 +970,27 @@ func TestParseGroupResource(t *testing.T) { expected schema.GroupResource }{ { - name: "When parsing a core resource it should return empty group", + name: "When parsing a core resource, it should return empty group", input: "secrets", expected: schema.GroupResource{Group: "", Resource: "secrets"}, }, { - name: "When parsing a core resource configmaps it should return empty group", + name: "When parsing a core resource configmaps, it should return empty group", input: "configmaps", expected: schema.GroupResource{Group: "", Resource: "configmaps"}, }, { - name: "When parsing a route resource it should split group correctly", + name: "When parsing a route resource, it should split group correctly", input: "routes.route.openshift.io", expected: schema.GroupResource{Group: "route.openshift.io", Resource: "routes"}, }, { - name: "When parsing an oauth resource it should split group correctly", + name: "When parsing an oauth resource, it should split group correctly", input: "oauthaccesstokens.oauth.openshift.io", expected: schema.GroupResource{Group: "oauth.openshift.io", Resource: "oauthaccesstokens"}, }, { - name: "When parsing oauthauthorizetokens resource it should split group correctly", + name: "When parsing oauthauthorizetokens resource, it should split group correctly", input: "oauthauthorizetokens.oauth.openshift.io", expected: schema.GroupResource{Group: "oauth.openshift.io", Resource: "oauthauthorizetokens"}, }, diff --git a/control-plane-operator/hostedclusterconfigoperator/controllers/resources/ingress/params_test.go b/control-plane-operator/hostedclusterconfigoperator/controllers/resources/ingress/params_test.go index 9d2b0c266b27..34ee187209a1 100644 --- a/control-plane-operator/hostedclusterconfigoperator/controllers/resources/ingress/params_test.go +++ b/control-plane-operator/hostedclusterconfigoperator/controllers/resources/ingress/params_test.go @@ -23,7 +23,7 @@ func TestNewIngressParams(t *testing.T) { want *IngressParams }{ { - name: "DefaultParams", + name: "When HCP has default configuration, it should return default ingress params", args: args{ hcp: &hyperv1.HostedControlPlane{}}, want: &IngressParams{ @@ -36,7 +36,7 @@ func TestNewIngressParams(t *testing.T) { }, }, { - name: "PrivateIngress", + name: "When private ingress annotation is set, it should set IsPrivate to true", args: args{ hcp: &hyperv1.HostedControlPlane{ ObjectMeta: metav1.ObjectMeta{ @@ -56,7 +56,7 @@ func TestNewIngressParams(t *testing.T) { }, }, { - name: "HighlyAvailable", + name: "When infrastructure is highly available, it should set replicas to two", args: args{ hcp: &hyperv1.HostedControlPlane{ Spec: hyperv1.HostedControlPlaneSpec{ @@ -74,7 +74,7 @@ func TestNewIngressParams(t *testing.T) { }, }, { - name: "IBMCloudUPI", + name: "When platform is IBMCloud UPI, it should set IBMCloudUPI to true", args: args{ hcp: &hyperv1.HostedControlPlane{ Spec: hyperv1.HostedControlPlaneSpec{ @@ -96,7 +96,7 @@ func TestNewIngressParams(t *testing.T) { }, }, { - name: "AWSNLB", + name: "When AWS platform uses NLB, it should set AWSNLB to true", args: args{ hcp: &hyperv1.HostedControlPlane{ Spec: hyperv1.HostedControlPlaneSpec{ @@ -127,7 +127,7 @@ func TestNewIngressParams(t *testing.T) { }, }, { - name: "AWSInternalNLB", + name: "When AWS platform is private with NLB, it should set internal load balancer scope", args: args{ hcp: &hyperv1.HostedControlPlane{ Spec: hyperv1.HostedControlPlaneSpec{ @@ -160,7 +160,7 @@ func TestNewIngressParams(t *testing.T) { }, }, { - name: "When Azure endpoint access is Private it should set internal load balancer scope", + name: "When Azure endpoint access is Private, it should set internal load balancer scope", args: args{ hcp: &hyperv1.HostedControlPlane{ Spec: hyperv1.HostedControlPlaneSpec{ @@ -184,7 +184,7 @@ func TestNewIngressParams(t *testing.T) { }, }, { - name: "When Azure endpoint access is PublicAndPrivate it should set internal load balancer scope", + name: "When Azure endpoint access is PublicAndPrivate, it should set internal load balancer scope", args: args{ hcp: &hyperv1.HostedControlPlane{ Spec: hyperv1.HostedControlPlaneSpec{ @@ -208,7 +208,7 @@ func TestNewIngressParams(t *testing.T) { }, }, { - name: "When ARO HCP Azure topology is PublicAndPrivate it should set external load balancer scope", + name: "When ARO HCP Azure topology is PublicAndPrivate, it should set external load balancer scope", args: args{ hcp: &hyperv1.HostedControlPlane{ Spec: hyperv1.HostedControlPlaneSpec{ @@ -235,7 +235,7 @@ func TestNewIngressParams(t *testing.T) { }, }, { - name: "When ARO HCP Azure topology is Private it should set external load balancer scope", + name: "When ARO HCP Azure topology is Private, it should set external load balancer scope", args: args{ hcp: &hyperv1.HostedControlPlane{ Spec: hyperv1.HostedControlPlaneSpec{ @@ -262,7 +262,7 @@ func TestNewIngressParams(t *testing.T) { }, }, { - name: "When ARO HCP has IngressControllerLoadBalancerScope annotation set to Internal it should respect it", + name: "When ARO HCP has IngressControllerLoadBalancerScope annotation set to Internal, it should respect it", args: args{ hcp: &hyperv1.HostedControlPlane{ ObjectMeta: metav1.ObjectMeta{ @@ -294,7 +294,7 @@ func TestNewIngressParams(t *testing.T) { }, }, { - name: "When Azure endpoint access is Public it should set external load balancer scope", + name: "When Azure endpoint access is Public, it should set external load balancer scope", args: args{ hcp: &hyperv1.HostedControlPlane{ Spec: hyperv1.HostedControlPlaneSpec{ diff --git a/control-plane-operator/hostedclusterconfigoperator/controllers/resources/recovery/recovery_test.go b/control-plane-operator/hostedclusterconfigoperator/controllers/resources/recovery/recovery_test.go index 2557d1fed606..bd124dbe6006 100644 --- a/control-plane-operator/hostedclusterconfigoperator/controllers/resources/recovery/recovery_test.go +++ b/control-plane-operator/hostedclusterconfigoperator/controllers/resources/recovery/recovery_test.go @@ -38,7 +38,7 @@ func TestRecoverMonitoringStack(t *testing.T) { multipleCalls bool }{ { - name: "When monitoring stack is healthy it should return true", + name: "When monitoring stack is healthy, it should return true", setupObjects: []client.Object{ &appsv1.StatefulSet{ ObjectMeta: metav1.ObjectMeta{ @@ -63,14 +63,14 @@ func TestRecoverMonitoringStack(t *testing.T) { expectError: false, }, { - name: "When prometheus statefulset is not found it should return error", + name: "When prometheus statefulset is not found, it should return error", setupObjects: []client.Object{}, expectedResult: false, expectError: true, errorContains: "prometheus statefulSet is still starting, rescheduling reconciliation", }, { - name: "When prometheus statefulset is not ready it should delete PVCs and pods and return false", + name: "When prometheus statefulset is not ready, it should delete PVCs and pods and return false", setupObjects: []client.Object{ &appsv1.StatefulSet{ ObjectMeta: metav1.ObjectMeta{ @@ -125,7 +125,7 @@ func TestRecoverMonitoringStack(t *testing.T) { expectError: false, }, { - name: "When prometheus statefulset is not ready and no pods exist it should delete PVCs and return false", + name: "When prometheus statefulset is not ready and no pods exist, it should delete PVCs and return false", setupObjects: []client.Object{ &appsv1.StatefulSet{ ObjectMeta: metav1.ObjectMeta{ @@ -156,7 +156,7 @@ func TestRecoverMonitoringStack(t *testing.T) { expectError: false, }, { - name: "When prometheus statefulset is not ready and PVC listing fails it should return error", + name: "When prometheus statefulset is not ready and PVC listing fails, it should return error", setupObjects: []client.Object{ &appsv1.StatefulSet{ ObjectMeta: metav1.ObjectMeta{ @@ -182,7 +182,7 @@ func TestRecoverMonitoringStack(t *testing.T) { errorContains: "failed to list PVCs", }, { - name: "When prometheus statefulset is not ready and PVC deletion fails it should return error", + name: "When prometheus statefulset is not ready and PVC deletion fails, it should return error", setupObjects: []client.Object{ &appsv1.StatefulSet{ ObjectMeta: metav1.ObjectMeta{ @@ -214,7 +214,7 @@ func TestRecoverMonitoringStack(t *testing.T) { errorContains: "failed to delete PVC", }, { - name: "When prometheus statefulset is not ready and pod listing fails it should return error", + name: "When prometheus statefulset is not ready and pod listing fails, it should return error", setupObjects: []client.Object{ &appsv1.StatefulSet{ ObjectMeta: metav1.ObjectMeta{ @@ -240,7 +240,7 @@ func TestRecoverMonitoringStack(t *testing.T) { errorContains: "failed to list prometheus pods", }, { - name: "When prometheus statefulset is not ready and pod deletion fails it should return error", + name: "When prometheus statefulset is not ready and pod deletion fails, it should return error", setupObjects: []client.Object{ &appsv1.StatefulSet{ ObjectMeta: metav1.ObjectMeta{ @@ -275,7 +275,7 @@ func TestRecoverMonitoringStack(t *testing.T) { errorContains: "failed to delete pod", }, { - name: "When prometheus statefulset is not ready and called multiple times it should only delete PVCs and pods once", + name: "When prometheus statefulset is not ready and called multiple times, it should only delete PVCs and pods once", setupObjects: []client.Object{ &appsv1.StatefulSet{ ObjectMeta: metav1.ObjectMeta{ @@ -331,22 +331,22 @@ func TestRecoverMonitoringStack(t *testing.T) { var fakeClient client.Client switch tt.name { - case "When prometheus statefulset is not ready and PVC listing fails it should return error": + case "When prometheus statefulset is not ready and PVC listing fails, it should return error": // Create a client that will fail on PVC List operations fakeClient = &failingPVCListClient{ Client: fake.NewClientBuilder().WithScheme(scheme).WithObjects(tt.setupObjects...).Build(), } - case "When prometheus statefulset is not ready and PVC deletion fails it should return error": + case "When prometheus statefulset is not ready and PVC deletion fails, it should return error": // Create a client that will fail on PVC Delete operations fakeClient = &failingPVCDeleteClient{ Client: fake.NewClientBuilder().WithScheme(scheme).WithObjects(tt.setupObjects...).Build(), } - case "When prometheus statefulset is not ready and pod listing fails it should return error": + case "When prometheus statefulset is not ready and pod listing fails, it should return error": // Create a client that will fail on Pod List operations fakeClient = &failingPodListClient{ Client: fake.NewClientBuilder().WithScheme(scheme).WithObjects(tt.setupObjects...).Build(), } - case "When prometheus statefulset is not ready and pod deletion fails it should return error": + case "When prometheus statefulset is not ready and pod deletion fails, it should return error": // Create a client that will fail on Pod Delete operations fakeClient = &failingPodDeleteClient{ Client: fake.NewClientBuilder().WithScheme(scheme).WithObjects(tt.setupObjects...).Build(), diff --git a/control-plane-operator/hostedclusterconfigoperator/controllers/resources/registry/admissionpolicies_test.go b/control-plane-operator/hostedclusterconfigoperator/controllers/resources/registry/admissionpolicies_test.go index 1d509f15275a..9e37de37a0cf 100644 --- a/control-plane-operator/hostedclusterconfigoperator/controllers/resources/registry/admissionpolicies_test.go +++ b/control-plane-operator/hostedclusterconfigoperator/controllers/resources/registry/admissionpolicies_test.go @@ -34,7 +34,7 @@ func TestReconcileRegistryConfigManagementStateValidatingAdmissionPolicy(t *test expectedResourceRules int }{ { - name: "When cluster is active it should set expression to restrict managementState", + name: "When cluster is active, it should set expression to restrict managementState", hcp: &hyperv1.HostedControlPlane{ ObjectMeta: metav1.ObjectMeta{ Name: "test-cluster", @@ -158,7 +158,7 @@ func TestReconcileRegistryConfigValidatingAdmissionPolicies(t *testing.T) { errSubstr string }{ { - name: "When reconciliation succeeds it should return no error", + name: "When reconciliation succeeds, it should return no error", hcp: &hyperv1.HostedControlPlane{ ObjectMeta: metav1.ObjectMeta{ Name: "test-cluster", @@ -168,7 +168,7 @@ func TestReconcileRegistryConfigValidatingAdmissionPolicies(t *testing.T) { expectError: false, }, { - name: "When cluster is being deleted it should still succeed", + name: "When cluster is being deleted, it should still succeed", hcp: &hyperv1.HostedControlPlane{ ObjectMeta: metav1.ObjectMeta{ Name: "test-cluster", diff --git a/control-plane-operator/hostedclusterconfigoperator/controllers/resources/resources_test.go b/control-plane-operator/hostedclusterconfigoperator/controllers/resources/resources_test.go index 46b670501e88..abb19a09d5d5 100644 --- a/control-plane-operator/hostedclusterconfigoperator/controllers/resources/resources_test.go +++ b/control-plane-operator/hostedclusterconfigoperator/controllers/resources/resources_test.go @@ -265,13 +265,13 @@ func TestReconcileOLM(t *testing.T) { want *configv1.OperatorHubSpec }{ { - name: "PlacementStrategy is management and no configuration provided", + name: "When placement is management with no configuration, it should return empty OperatorHub spec", hcpClusterConfig: nil, olmCatalogPlacement: hyperv1.ManagementOLMCatalogPlacement, want: &configv1.OperatorHubSpec{}, }, { - name: "PlacementStrategy is management and allDefaultSources disabled", + name: "When placement is management with allDefaultSources disabled, it should disable all default sources", hcpClusterConfig: &hyperv1.ClusterConfiguration{ OperatorHub: &configv1.OperatorHubSpec{ DisableAllDefaultSources: true, @@ -283,7 +283,7 @@ func TestReconcileOLM(t *testing.T) { }, }, { - name: "PlacementStrategy is management and allDefaultSources enabled", + name: "When placement is management with allDefaultSources enabled, it should enable all default sources", hcpClusterConfig: &hyperv1.ClusterConfiguration{ OperatorHub: &configv1.OperatorHubSpec{ DisableAllDefaultSources: false, @@ -295,7 +295,7 @@ func TestReconcileOLM(t *testing.T) { }, }, { - name: "PlacementStrategy is guest and no configuration provided", + name: "When placement is guest with no configuration, it should return empty OperatorHub spec", hcpClusterConfig: nil, olmCatalogPlacement: hyperv1.GuestOLMCatalogPlacement, want: &configv1.OperatorHubSpec{}, @@ -303,7 +303,7 @@ func TestReconcileOLM(t *testing.T) { { // We expect here the OperatorHub in guest to keep the already set value and // don't overwrite the value with the new one. - name: "PlacementStrategy is guest and allDefaultSources disabled, the first reconciliation loop already happened", + name: "When placement is guest with allDefaultSources disabled after first reconcile, it should preserve existing value", hcpClusterConfig: &hyperv1.ClusterConfiguration{ OperatorHub: &configv1.OperatorHubSpec{ DisableAllDefaultSources: true, @@ -315,7 +315,7 @@ func TestReconcileOLM(t *testing.T) { }, }, { - name: "PlacementStrategy is guest and allDefaultSources enabled", + name: "When placement is guest with allDefaultSources enabled, it should enable all default sources", hcpClusterConfig: &hyperv1.ClusterConfiguration{ OperatorHub: &configv1.OperatorHubSpec{ DisableAllDefaultSources: false, @@ -505,7 +505,7 @@ func TestReconcileKubeadminPasswordHashSecret(t *testing.T) { expectKubeadminPasswordHashSecretToExist bool expectHashPreserved bool }{ - "when kubeadminPasswordSecret exists the hash secret is created": { + "When kubeadminPasswordSecret exists, it should create the hash secret": { inputHCP: &hyperv1.HostedControlPlane{ ObjectMeta: metav1.ObjectMeta{ Name: testHCPName, @@ -581,7 +581,7 @@ func TestReconcileKubeadminPasswordHashSecret(t *testing.T) { expectKubeadminPasswordHashSecretToExist: true, expectHashPreserved: true, }, - "when kubeadminPasswordSecret doesn't exist the hash secret is not created": { + "When kubeadminPasswordSecret does not exist, it should not create the hash secret": { inputHCP: &hyperv1.HostedControlPlane{ ObjectMeta: metav1.ObjectMeta{ Name: testHCPName, @@ -649,7 +649,7 @@ func TestReconcileUserCertCABundle(t *testing.T) { existingGuestObjects []client.Object expectUserCAConfigMap bool }{ - "No AdditionalTrustBundle": { + "When no AdditionalTrustBundle is set, it should not create user CA configmap": { inputHCP: &hyperv1.HostedControlPlane{ ObjectMeta: metav1.ObjectMeta{ Name: testHCPName, @@ -660,7 +660,7 @@ func TestReconcileUserCertCABundle(t *testing.T) { existingGuestObjects: []client.Object{}, expectUserCAConfigMap: false, }, - "AdditionalTrustBundle": { + "When AdditionalTrustBundle is set, it should create user CA configmap": { inputHCP: &hyperv1.HostedControlPlane{ ObjectMeta: metav1.ObjectMeta{ Name: testHCPName, @@ -683,7 +683,7 @@ func TestReconcileUserCertCABundle(t *testing.T) { existingGuestObjects: []client.Object{}, expectUserCAConfigMap: true, }, - "AdditionalTrustBundle removed - should delete existing user-ca-bundle": { + "When AdditionalTrustBundle is removed, it should delete existing user-ca-bundle": { inputHCP: &hyperv1.HostedControlPlane{ ObjectMeta: metav1.ObjectMeta{ Name: testHCPName, @@ -926,18 +926,18 @@ func TestDestroyCloudResources(t *testing.T) { verifyDoneCond bool }{ { - name: "no existing resources", + name: "When no resources exist, it should mark done condition", verifyDoneCond: true, }, { - name: "image registry with storage", + name: "When image registry has managed storage, it should set management state to removed", existing: []client.Object{ managedImageRegistry(), }, verify: verifyImageRegistryConfig, }, { - name: "existing ingress controller", + name: "When ingress controllers exist, it should remove all ingress controllers", existing: []client.Object{ ingressController("default"), ingressController("foobar"), @@ -945,7 +945,7 @@ func TestDestroyCloudResources(t *testing.T) { verify: verifyIngressControllersRemoved, }, { - name: "existing service load balancers", + name: "When service load balancers exist, it should remove load balancers but preserve ClusterIP services", existing: []client.Object{ serviceLoadBalancer("foo"), serviceLoadBalancer("bar"), @@ -958,7 +958,7 @@ func TestDestroyCloudResources(t *testing.T) { verifyDoneCond: true, }, { - name: "existing service load balancers owned by ingress controller", + name: "When load balancers are owned by ingress controller, it should preserve them", existing: []client.Object{ serviceLoadBalancerOwnedByIngressController("bar"), clusterIPService("baz"), @@ -969,7 +969,7 @@ func TestDestroyCloudResources(t *testing.T) { }, }, { - name: "existing pv/pvc", + name: "When PVs and PVCs exist, it should remove PVCs and pods", existing: []client.Object{ pv("foo"), pvc("foo"), pv("bar"), pvc("bar"), @@ -983,7 +983,7 @@ func TestDestroyCloudResources(t *testing.T) { }, }, { - name: "existing everything", + name: "When all resource types exist, it should clean up everything", existing: []client.Object{ managedImageRegistry(), ingressController("default"), @@ -1067,12 +1067,12 @@ func TestDestroyCloudResourcesWithKASUnavailable(t *testing.T) { expectFailureTracking bool }{ { - name: "KAS deployment not found - cleanup skipped", + name: "When KAS deployment is not found, it should skip cleanup", kasDeploymentExists: false, expectCleanupSkipped: true, }, { - name: "KAS deployment exists - cleanup proceeds", + name: "When KAS deployment exists, it should proceed with cleanup", kasDeploymentExists: true, expectCleanupSkipped: false, }, @@ -1141,22 +1141,22 @@ func TestConnectionErrorTracking(t *testing.T) { expectedConnection bool }{ { - name: "K8s timeout error", + name: "When K8s timeout error occurs, it should return true", err: apierrors.NewTimeoutError("request timeout", 5), expectedConnection: true, }, { - name: "K8s server timeout error", + name: "When K8s server timeout error occurs, it should return true", err: apierrors.NewServerTimeout(schema.GroupResource{Group: "", Resource: "pods"}, "get", 5), expectedConnection: true, }, { - name: "K8s service unavailable error", + name: "When K8s service unavailable error occurs, it should return true", err: apierrors.NewServiceUnavailable("service unavailable"), expectedConnection: true, }, { - name: "net.Error with timeout", + name: "When net.Error has timeout, it should return true", err: &mockNetError{ error: fmt.Errorf("connection timeout"), timeout: true, @@ -1164,7 +1164,7 @@ func TestConnectionErrorTracking(t *testing.T) { expectedConnection: true, }, { - name: "net.Error temporary", + name: "When net.Error is temporary, it should return true", err: &mockNetError{ error: fmt.Errorf("temporary network error"), temporary: true, @@ -1172,22 +1172,22 @@ func TestConnectionErrorTracking(t *testing.T) { expectedConnection: true, }, { - name: "wrapped net.Error", + name: "When net.Error is wrapped, it should return true", err: fmt.Errorf("failed to connect: %w", &mockNetError{error: fmt.Errorf("connection refused"), timeout: false}), expectedConnection: true, }, { - name: "other K8s error (not found)", + name: "When K8s error is not found, it should return false", err: apierrors.NewNotFound(schema.GroupResource{Group: "", Resource: "pods"}, "test-pod"), expectedConnection: false, }, { - name: "other error", + name: "When error is generic, it should return false", err: fmt.Errorf("permission denied"), expectedConnection: false, }, { - name: "nil error", + name: "When error is nil, it should return false", err: nil, expectedConnection: false, }, @@ -1542,15 +1542,15 @@ func TestReconcileImageContentPolicyType(t *testing.T) { removeICSAndReconcile bool }{ { - name: "ICS with content, it should return an IDMS with the same content", + name: "When ICS has content, it should return an IDMS with the same content", hcp: withICS(fakeHCP()), }, { - name: "ICS empty, is should return an empty IDMS", + name: "When ICS is empty, it should return an empty IDMS", hcp: fakeHCP(), }, { - name: "ICS And IDMS should be in sync always", + name: "When ICS is removed after reconcile, it should sync IDMS to match", hcp: withICS(fakeHCP()), removeICSAndReconcile: true, }, @@ -1617,7 +1617,7 @@ func TestReconcileKASEndpoints(t *testing.T) { expectedPort int32 }{ { - name: "When HC has hcp.spec.networking.apiServer.port set to 443, endpoint and slice should have port 443", + name: "When HC has hcp.spec.networking.apiServer.port set to 443, it should set endpoint and slice port to 443", hcp: &hyperv1.HostedControlPlane{ Spec: hyperv1.HostedControlPlaneSpec{ Networking: hyperv1.ClusterNetworking{ @@ -1630,7 +1630,7 @@ func TestReconcileKASEndpoints(t *testing.T) { expectedPort: int32(443), }, { - name: "When HC has no hcp.spec.networking.apiServer.port set, endpoint and slice should have port 6443", + name: "When HC has no hcp.spec.networking.apiServer.port set, it should set endpoint and slice port to 6443", hcp: &hyperv1.HostedControlPlane{ Spec: hyperv1.HostedControlPlaneSpec{}, }, @@ -1689,7 +1689,7 @@ func TestReconcileKubeletConfig(t *testing.T) { preservedObjects []client.Object }{ { - name: "copy kubelet config from control plane NS", + name: "When kubelet config exists in control plane namespace, it should copy to hosted cluster", hostedControlPlaneObjects: []client.Object{ makeKubeletConfigConfigMap(netutil.ShortenName("bar", npName1, validation.LabelValueMaxLength), hcpNamespace, kubeletConfig1), }, @@ -1698,7 +1698,7 @@ func TestReconcileKubeletConfig(t *testing.T) { }, }, { - name: "some CM already exist and some are not, expect HCCO to catch up", + name: "When some ConfigMaps already exist, it should reconcile missing ones", hostedControlPlaneObjects: []client.Object{ makeKubeletConfigConfigMap(netutil.ShortenName("bar", npName1, validation.LabelValueMaxLength), hcpNamespace, kubeletConfig1), makeKubeletConfigConfigMap(netutil.ShortenName("foo", npName2, validation.LabelValueMaxLength), hcpNamespace, kubeletConfig1), @@ -1712,7 +1712,7 @@ func TestReconcileKubeletConfig(t *testing.T) { }, }, { - name: "CM need to be deleted", + name: "When ConfigMaps are removed from source, it should delete from hosted cluster", hostedControlPlaneObjects: []client.Object{ makeKubeletConfigConfigMap(netutil.ShortenName("bar", npName1, validation.LabelValueMaxLength), hcpNamespace, kubeletConfig1), }, @@ -1900,7 +1900,7 @@ func TestBuildAWSWebIdentityCredentials(t *testing.T) { } tests := []test{ { - name: "should fail if the role ARN is empty", + name: "When role ARN is empty, it should return error", args: args{ roleArn: "", region: "us-east-1", @@ -1908,7 +1908,7 @@ func TestBuildAWSWebIdentityCredentials(t *testing.T) { wantErr: true, }, { - name: "should fail if the region is empty", + name: "When region is empty, it should return error", wantErr: true, args: args{ roleArn: "arn:aws:iam::123456789012:role/some-role", @@ -1916,7 +1916,7 @@ func TestBuildAWSWebIdentityCredentials(t *testing.T) { }, }, { - name: "should succeed and return the creds template populated with role arn and region otherwise", + name: "When role ARN and region are valid, it should return populated credentials template", wantErr: false, args: args{ roleArn: "arn:aws:iam::123456789012:role/some-role", @@ -2005,7 +2005,7 @@ func TestReconcileAuthOIDC(t *testing.T) { expectedErrorMessages []string setAROHCP bool }{ - "when OAuth is enabled, should not copy OIDC resources": { + "When OAuth is enabled, it should not copy OIDC resources": { inputHCP: &hyperv1.HostedControlPlane{ ObjectMeta: metav1.ObjectMeta{ Name: testHCPName, @@ -2031,7 +2031,7 @@ func TestReconcileAuthOIDC(t *testing.T) { expectOIDCClientSecrets: []string{}, expectErrors: false, }, - "when OAuth is disabled and no OIDC providers, should not copy anything": { + "When OAuth is disabled with no OIDC providers, it should not copy anything": { inputHCP: &hyperv1.HostedControlPlane{ ObjectMeta: metav1.ObjectMeta{ Name: testHCPName, @@ -2050,7 +2050,7 @@ func TestReconcileAuthOIDC(t *testing.T) { expectOIDCClientSecrets: []string{}, expectErrors: false, }, - "when OAuth is disabled with OIDC provider with CA configmap, should copy CA": { + "When OAuth is disabled with OIDC CA configmap, it should copy CA": { inputHCP: &hyperv1.HostedControlPlane{ ObjectMeta: metav1.ObjectMeta{ Name: testHCPName, @@ -2090,7 +2090,7 @@ func TestReconcileAuthOIDC(t *testing.T) { expectOIDCClientSecrets: []string{}, expectErrors: false, }, - "when OAuth is disabled with OIDC provider with OIDC clients, should copy client secrets": { + "When OAuth is disabled with OIDC clients, it should copy client secrets": { inputHCP: &hyperv1.HostedControlPlane{ ObjectMeta: metav1.ObjectMeta{ Name: testHCPName, @@ -2154,7 +2154,7 @@ func TestReconcileAuthOIDC(t *testing.T) { expectOIDCClientSecrets: []string{"console-client-secret", "cli-client-secret"}, expectErrors: false, }, - "when OAuth is disabled with OIDC provider with both CA and client secrets, should copy both": { + "When OAuth is disabled with OIDC CA and client secrets, it should copy both": { inputHCP: &hyperv1.HostedControlPlane{ ObjectMeta: metav1.ObjectMeta{ Name: testHCPName, @@ -2213,7 +2213,7 @@ func TestReconcileAuthOIDC(t *testing.T) { expectOIDCClientSecrets: []string{"console-client-secret"}, expectErrors: false, }, - "when OAuth is disabled with OIDC provider with confidential and public OIDC clients, should copy confidential client secret": { + "When OAuth is disabled with mixed OIDC clients, it should copy only confidential client secret": { inputHCP: &hyperv1.HostedControlPlane{ ObjectMeta: metav1.ObjectMeta{ Name: testHCPName, @@ -2268,7 +2268,7 @@ func TestReconcileAuthOIDC(t *testing.T) { expectOIDCClientSecrets: []string{"console-client-secret"}, expectErrors: false, }, - "when OAuth is disabled with OIDC provider with a hosted-cluster-sourced annotated client secret and ARO-HCP platform, should not copy the client secret": { + "When ARO-HCP has hosted-cluster-sourced client secret, it should not copy the secret": { inputHCP: &hyperv1.HostedControlPlane{ ObjectMeta: metav1.ObjectMeta{ Name: testHCPName, @@ -2330,7 +2330,7 @@ func TestReconcileAuthOIDC(t *testing.T) { expectErrors: false, setAROHCP: true, }, - "when OAuth is disabled with OIDC provider and not ARO-HCP platform, setting hosted-cluster-sourced annotation on a client secret should not skip copying the secret": { + "When non-ARO-HCP has hosted-cluster-sourced annotation, it should still copy the secret": { inputHCP: &hyperv1.HostedControlPlane{ ObjectMeta: metav1.ObjectMeta{ Name: testHCPName, @@ -2381,7 +2381,7 @@ func TestReconcileAuthOIDC(t *testing.T) { expectErrors: false, setAROHCP: false, }, - "when OAuth is disabled but CA configmap is missing, should return error": { + "When OAuth is disabled but CA configmap is missing, it should return error": { inputHCP: &hyperv1.HostedControlPlane{ ObjectMeta: metav1.ObjectMeta{ Name: testHCPName, @@ -2412,7 +2412,7 @@ func TestReconcileAuthOIDC(t *testing.T) { expectErrors: true, expectedErrorMessages: []string{"failed to get issuer CA configmap missing-ca-bundle"}, }, - "when OAuth is disabled but client secret is missing, should return error": { + "When OAuth is disabled but client secret is missing, it should return error": { inputHCP: &hyperv1.HostedControlPlane{ ObjectMeta: metav1.ObjectMeta{ Name: testHCPName, @@ -2450,7 +2450,7 @@ func TestReconcileAuthOIDC(t *testing.T) { expectErrors: true, expectedErrorMessages: []string{"failed to get OIDCClient secret missing-client-secret"}, }, - "when OAuth is disabled with multiple OIDC providers, should handle first provider only": { + "When OAuth is disabled with multiple OIDC providers, it should handle first provider only": { inputHCP: &hyperv1.HostedControlPlane{ ObjectMeta: metav1.ObjectMeta{ Name: testHCPName, @@ -2681,7 +2681,7 @@ func newCondition(conditionType string, status metav1.ConditionStatus, reason, m } } -func Test_reconciler_reconcileDataPlaneConnectionAvailable(t *testing.T) { +func TestReconcileDataPlaneConnectionAvailable(t *testing.T) { t.Parallel() newKonnectivityAgentPod := func(name string, phase corev1.PodPhase) corev1.Pod { return corev1.Pod{ @@ -2723,7 +2723,7 @@ func Test_reconciler_reconcileDataPlaneConnectionAvailable(t *testing.T) { mockedGetPodLogs func(context context.Context, clientet *clientset.Clientset, namespace, name, container string) ([]byte, error) }{ { - name: "no worker nodes Condition Unknown", + name: "When no worker nodes exist, it should set condition to Unknown", hcp: fakeHCP(), wantErr: false, expectedCondition: newCondition(string(hyperv1.DataPlaneConnectionAvailable), @@ -2737,7 +2737,7 @@ func Test_reconciler_reconcileDataPlaneConnectionAvailable(t *testing.T) { }, }, { - name: "no konnectivity-agent PODs condition False", + name: "When no konnectivity-agent pods exist, it should set condition to False", hcp: fakeHCP(), wantErr: false, expectedCondition: newCondition(string(hyperv1.DataPlaneConnectionAvailable), @@ -2752,7 +2752,7 @@ func Test_reconciler_reconcileDataPlaneConnectionAvailable(t *testing.T) { }, }, { - name: "only one pending POD condition False", + name: "When only pending konnectivity-agent pods exist, it should set condition to False", hcp: fakeHCP(), wantErr: false, expectedCondition: newCondition(string(hyperv1.DataPlaneConnectionAvailable), @@ -2767,7 +2767,7 @@ func Test_reconciler_reconcileDataPlaneConnectionAvailable(t *testing.T) { }, }, { - name: "one konnectivity-agent PODs running condition OK", + name: "When one konnectivity-agent pod is running, it should set condition to True", hcp: fakeHCP(), wantErr: false, expectedCondition: newCondition(string(hyperv1.DataPlaneConnectionAvailable), @@ -2782,7 +2782,7 @@ func Test_reconciler_reconcileDataPlaneConnectionAvailable(t *testing.T) { }, }, { - name: "may konnectivity-agent PODs only one running condition OK", + name: "When many konnectivity-agent pods exist with one running, it should set condition to True", hcp: fakeHCP(), wantErr: false, expectedCondition: newCondition(string(hyperv1.DataPlaneConnectionAvailable), @@ -2801,7 +2801,7 @@ func Test_reconciler_reconcileDataPlaneConnectionAvailable(t *testing.T) { }, }, { - name: "one konnectivity-agent PODs running bad since error getting LOG", + name: "When konnectivity-agent pod has log retrieval error, it should set condition to False", hcp: fakeHCP(), wantErr: false, expectedCondition: newCondition(string(hyperv1.DataPlaneConnectionAvailable), @@ -2817,7 +2817,7 @@ func Test_reconciler_reconcileDataPlaneConnectionAvailable(t *testing.T) { }, }, { - name: "one konnectivity-agent PODs running bad since no LOG", // unsure this is possible + name: "When konnectivity-agent pod has no log output, it should set condition to False", // unsure this is possible hcp: fakeHCP(), wantErr: false, expectedCondition: newCondition(string(hyperv1.DataPlaneConnectionAvailable), @@ -2877,7 +2877,7 @@ func Test_reconciler_reconcileDataPlaneConnectionAvailable(t *testing.T) { } } -func Test_reconciler_reconcileControlPlaneConnectionAvailable(t *testing.T) { +func TestReconcileControlPlaneConnectionAvailable(t *testing.T) { t.Parallel() newConnectivityConfigMap := func(data map[string]string) *corev1.ConfigMap { return &corev1.ConfigMap{ @@ -2914,7 +2914,7 @@ func Test_reconciler_reconcileControlPlaneConnectionAvailable(t *testing.T) { nodes []corev1.Node }{ { - name: "When no worker nodes exist it should set condition to Unknown with NoWorkerNodesAvailable reason", + name: "When no worker nodes exist, it should set condition to Unknown with NoWorkerNodesAvailable reason", hcp: fakeHCP(), wantErr: false, expectedCondition: newCondition( @@ -2927,7 +2927,7 @@ func Test_reconciler_reconcileControlPlaneConnectionAvailable(t *testing.T) { nodes: []corev1.Node{}, }, { - name: "When ConfigMap does not exist it should set condition to Unknown with ConfigMapNotFound reason", + name: "When ConfigMap does not exist, it should set condition to Unknown with ConfigMapNotFound reason", hcp: fakeHCP(), wantErr: false, expectedCondition: newCondition( @@ -2941,7 +2941,7 @@ func Test_reconciler_reconcileControlPlaneConnectionAvailable(t *testing.T) { nodes: []corev1.Node{newReadyNode("node1")}, }, { - name: "When ConfigMap has no lastSucceeded key it should set condition to False with KASAccessFailed reason", + name: "When ConfigMap has no lastSucceeded key, it should set condition to False with KASAccessFailed reason", hcp: fakeHCP(), wantErr: false, expectedCondition: newCondition( @@ -2954,7 +2954,7 @@ func Test_reconciler_reconcileControlPlaneConnectionAvailable(t *testing.T) { nodes: []corev1.Node{newReadyNode("node1")}, }, { - name: "When ConfigMap has empty lastSucceeded it should set condition to False with KASAccessFailed reason", + name: "When ConfigMap has empty lastSucceeded, it should set condition to False with KASAccessFailed reason", hcp: fakeHCP(), wantErr: false, expectedCondition: newCondition( @@ -2967,7 +2967,7 @@ func Test_reconciler_reconcileControlPlaneConnectionAvailable(t *testing.T) { nodes: []corev1.Node{newReadyNode("node1")}, }, { - name: "When lastSucceeded is recent it should set condition to True", + name: "When lastSucceeded is recent, it should set condition to True", hcp: fakeHCP(), wantErr: false, expectedCondition: newCondition( @@ -2982,7 +2982,7 @@ func Test_reconciler_reconcileControlPlaneConnectionAvailable(t *testing.T) { nodes: []corev1.Node{newReadyNode("node1")}, }, { - name: "When lastSucceeded is stale it should set condition to False with ConnectionCheckStale reason", + name: "When lastSucceeded is stale, it should set condition to False with ConnectionCheckStale reason", hcp: fakeHCP(), wantErr: false, expectedCondition: newCondition( @@ -3209,7 +3209,7 @@ func getKASCheckerDeployment(t *testing.T, c client.Client) *appsv1.Deployment { return dep } -func Test_reconciler_reconcileKASConnectionCheckerDeployment(t *testing.T) { +func TestReconcileKASConnectionCheckerDeployment(t *testing.T) { t.Parallel() const testCLIImage = "quay.io/openshift-release-dev/ocp-v4.0-art-dev@sha256:cli-test" @@ -3221,7 +3221,7 @@ func Test_reconciler_reconcileKASConnectionCheckerDeployment(t *testing.T) { validate func(t *testing.T, c client.Client) }{ { - name: "When Deployment does not exist it should create it with correct spec", + name: "When Deployment does not exist, it should create it with correct spec", hcp: fakeHCP(), existingDeployment: nil, wantErr: false, @@ -3247,7 +3247,7 @@ func Test_reconciler_reconcileKASConnectionCheckerDeployment(t *testing.T) { }, }, { - name: "When platform is IBM Cloud it should use IBM Cloud specific endpoint in curl script", + name: "When platform is IBM Cloud, it should use IBM Cloud specific endpoint in curl script", hcp: &hyperv1.HostedControlPlane{ ObjectMeta: metav1.ObjectMeta{ Name: "test-hcp", @@ -3271,7 +3271,7 @@ func Test_reconciler_reconcileKASConnectionCheckerDeployment(t *testing.T) { }, }, { - name: "When Deployment already exists it should update it", + name: "When Deployment already exists, it should update it", hcp: fakeHCP(), existingDeployment: &appsv1.Deployment{ ObjectMeta: metav1.ObjectMeta{ @@ -3492,7 +3492,7 @@ func TestReconcileMetricsForwarder(t *testing.T) { } } -func Test_namespacedNamePredicateFunc(t *testing.T) { +func TestNamespacedNamePredicateFunc(t *testing.T) { predicate := namespacedNamePredicateFunc("my-hcp-namespace", "pull-secret") tests := []struct { @@ -3501,21 +3501,21 @@ func Test_namespacedNamePredicateFunc(t *testing.T) { want bool }{ { - name: "When namespace and name match it should return true", + name: "When namespace and name match, it should return true", object: &corev1.Secret{ ObjectMeta: metav1.ObjectMeta{Namespace: "my-hcp-namespace", Name: "pull-secret"}, }, want: true, }, { - name: "When namespace differs it should return false", + name: "When namespace differs, it should return false", object: &corev1.Secret{ ObjectMeta: metav1.ObjectMeta{Namespace: "other-namespace", Name: "pull-secret"}, }, want: false, }, { - name: "When name differs it should return false", + name: "When name differs, it should return false", object: &corev1.Secret{ ObjectMeta: metav1.ObjectMeta{Namespace: "my-hcp-namespace", Name: "other-secret"}, }, diff --git a/control-plane-operator/hostedclusterconfigoperator/controllers/spotremediation/spotremediation_test.go b/control-plane-operator/hostedclusterconfigoperator/controllers/spotremediation/spotremediation_test.go index 84c4f58dbe7a..769c819e0aa3 100644 --- a/control-plane-operator/hostedclusterconfigoperator/controllers/spotremediation/spotremediation_test.go +++ b/control-plane-operator/hostedclusterconfigoperator/controllers/spotremediation/spotremediation_test.go @@ -188,7 +188,7 @@ func TestNthTaintKey(t *testing.T) { expected string }{ { - name: "When node has rebalance-recommendation taint it should return the taint key", + name: "When node has rebalance-recommendation taint, it should return the taint key", node: &corev1.Node{ Spec: corev1.NodeSpec{ Taints: []corev1.Taint{ @@ -199,7 +199,7 @@ func TestNthTaintKey(t *testing.T) { expected: "aws-node-termination-handler/rebalance-recommendation", }, { - name: "When node has spot-itn taint it should return the taint key", + name: "When node has spot-itn taint, it should return the taint key", node: &corev1.Node{ Spec: corev1.NodeSpec{ Taints: []corev1.Taint{ @@ -210,7 +210,7 @@ func TestNthTaintKey(t *testing.T) { expected: "aws-node-termination-handler/spot-itn", }, { - name: "When node has no NTH taints it should return empty string", + name: "When node has no NTH taints, it should return empty string", node: &corev1.Node{ Spec: corev1.NodeSpec{ Taints: []corev1.Taint{ @@ -221,7 +221,7 @@ func TestNthTaintKey(t *testing.T) { expected: "", }, { - name: "When node has no taints it should return empty string", + name: "When node has no taints, it should return empty string", node: &corev1.Node{ Spec: corev1.NodeSpec{}, }, diff --git a/control-plane-pki-operator/certificaterevocationcontroller/certificaterevocationcontroller_test.go b/control-plane-pki-operator/certificaterevocationcontroller/certificaterevocationcontroller_test.go index 7a3af9fc9bf5..011d3e1c3b02 100644 --- a/control-plane-pki-operator/certificaterevocationcontroller/certificaterevocationcontroller_test.go +++ b/control-plane-pki-operator/certificaterevocationcontroller/certificaterevocationcontroller_test.go @@ -213,7 +213,7 @@ func TestCertificateRevocationController_processCertificateRevocationRequest(t * expected *actions }{ { - name: "invalid signer class is flagged", + name: "When signer class is invalid, it should flag the error", now: revocationClock.Now, crrNamespace: "crr-ns", crrName: "crr-name", @@ -240,7 +240,7 @@ func TestCertificateRevocationController_processCertificateRevocationRequest(t * }, }, { - name: "a timestamp is chosen if one does not exist", + name: "When no timestamp exists, it should choose one", now: revocationClock.Now, crrNamespace: "crr-ns", crrName: "crr-name", @@ -268,7 +268,7 @@ func TestCertificateRevocationController_processCertificateRevocationRequest(t * }, }, { - name: "current signer is copied if none exists", + name: "When no signer copy exists, it should copy the current signer", now: postRevocationClock.Now, crrNamespace: "crr-ns", crrName: "crr-name", @@ -309,7 +309,7 @@ func TestCertificateRevocationController_processCertificateRevocationRequest(t * }, }, { - name: "status updated to contain copied signer when copy exists", + name: "When signer copy exists, it should update status with copied signer reference", now: postRevocationClock.Now, crrNamespace: "crr-ns", crrName: "crr-name", @@ -362,7 +362,7 @@ func TestCertificateRevocationController_processCertificateRevocationRequest(t * }, }, { - name: "copies finished means we annotate for regeneration", + name: "When copies are finished, it should annotate for regeneration", now: postRevocationClock.Now, crrNamespace: "crr-ns", crrName: "crr-name", @@ -406,7 +406,7 @@ func TestCertificateRevocationController_processCertificateRevocationRequest(t * }, }, { - name: "new signer generated, mark as such", + name: "When new signer is generated, it should mark regeneration as complete", now: postRevocationClock.Now, crrNamespace: "crr-ns", crrName: "crr-name", @@ -466,7 +466,7 @@ func TestCertificateRevocationController_processCertificateRevocationRequest(t * }, }, { - name: "not yet propagated, nothing to do", + name: "When new cert is not yet propagated, it should requeue", now: postRevocationClock.Now, crrNamespace: "crr-ns", crrName: "crr-name", @@ -513,7 +513,7 @@ func TestCertificateRevocationController_processCertificateRevocationRequest(t * }}, }, { - name: "propagated, mark as trusted", + name: "When new cert is propagated, it should mark as trusted", now: postRevocationClock.Now, crrNamespace: "crr-ns", crrName: "crr-name", @@ -586,7 +586,7 @@ func TestCertificateRevocationController_processCertificateRevocationRequest(t * }, }, { - name: "leaf certificate not yet regenerated, annotate them", + name: "When leaf certificate is not regenerated, it should annotate for regeneration", now: postRevocationClock.Now, crrNamespace: "crr-ns", crrName: "crr-name", @@ -665,7 +665,7 @@ func TestCertificateRevocationController_processCertificateRevocationRequest(t * }, }, { - name: "leaf certificate already regenerated", + name: "When leaf certificate is already regenerated, it should update the CA bundle", now: postRevocationClock.Now, crrNamespace: "crr-ns", crrName: "crr-name", @@ -744,7 +744,7 @@ func TestCertificateRevocationController_processCertificateRevocationRequest(t * }, }, { - name: "bundle only has new signers", + name: "When bundle has only new signers, it should mark leaves regenerated and revocation pending", now: postRevocationClock.Now, crrNamespace: "crr-ns", crrName: "crr-name", @@ -851,7 +851,7 @@ func TestCertificateRevocationController_processCertificateRevocationRequest(t * }, }, { - name: "validating, previous still valid", + name: "When validating and previous signer is still valid, it should requeue", now: postRevocationClock.Now, crrNamespace: "crr-ns", crrName: "crr-name", @@ -926,7 +926,7 @@ func TestCertificateRevocationController_processCertificateRevocationRequest(t * }}, }, { - name: "validating, previous invalid", + name: "When validating and previous signer is invalid, it should mark revoked", now: postRevocationClock.Now, crrNamespace: "crr-ns", crrName: "crr-name", @@ -1039,7 +1039,7 @@ func TestCertificateRevocationController_processCertificateRevocationRequest(t * }, }, { - name: "SRE signer: validating, previous still valid (requeue path)", + name: "When SRE signer is validating and previous is still valid, it should requeue", now: postRevocationClock.Now, crrNamespace: "crr-ns", crrName: "crr-name-sre", diff --git a/control-plane-pki-operator/certificatesigningcontroller/certificatesigningcontroller_test.go b/control-plane-pki-operator/certificatesigningcontroller/certificatesigningcontroller_test.go index 92f8a7e22f05..d99bce7495ee 100644 --- a/control-plane-pki-operator/certificatesigningcontroller/certificatesigningcontroller_test.go +++ b/control-plane-pki-operator/certificatesigningcontroller/certificatesigningcontroller_test.go @@ -188,7 +188,7 @@ func TestCertificateSigningController_processCertificateSigningRequest(t *testin expectedErr bool }{ { - description: "csr missing", + description: "When CSR is missing, it should return no error", name: "test-csr", getCSR: func(name string) (*certificatesv1.CertificateSigningRequest, error) { return nil, apierrors.NewNotFound(certificatesv1.SchemeGroupVersion.WithResource("certificatesigningrequests").GroupResource(), name) @@ -196,7 +196,7 @@ func TestCertificateSigningController_processCertificateSigningRequest(t *testin expectedErr: false, // nothing to do, no need to error & requeue }, { - description: "csr not approved", + description: "When CSR is not approved, it should take no action", name: "test-csr", getCSR: func(name string) (*certificatesv1.CertificateSigningRequest, error) { if name != "test-csr" { @@ -210,7 +210,7 @@ func TestCertificateSigningController_processCertificateSigningRequest(t *testin }, }, { - description: "csr failed", + description: "When CSR has failed, it should take no action", name: "test-csr", getCSR: func(name string) (*certificatesv1.CertificateSigningRequest, error) { if name != "test-csr" { @@ -230,7 +230,7 @@ func TestCertificateSigningController_processCertificateSigningRequest(t *testin }, }, { - description: "csr fulfilled", + description: "When CSR is already fulfilled, it should take no action", name: "test-csr", getCSR: func(name string) (*certificatesv1.CertificateSigningRequest, error) { if name != "test-csr" { @@ -251,7 +251,7 @@ func TestCertificateSigningController_processCertificateSigningRequest(t *testin }, }, { - description: "invalid request encoding", + description: "When request encoding is invalid, it should return error", name: "test-csr", signerName: certificates.SignerNameForHCP(hcp, certificates.CustomerBreakGlassSigner), getCSR: func(name string) (*certificatesv1.CertificateSigningRequest, error) { @@ -277,7 +277,7 @@ func TestCertificateSigningController_processCertificateSigningRequest(t *testin expectedErr: true, }, { - description: "invalid csr", + description: "When CSR is invalid, it should fail validation", name: "test-csr", getCSR: func(name string) (*certificatesv1.CertificateSigningRequest, error) { if name != "test-csr" { @@ -320,7 +320,7 @@ func TestCertificateSigningController_processCertificateSigningRequest(t *testin expectedValidationErr: true, }, { - description: "valid csr", + description: "When CSR is valid, it should sign the certificate", name: "test-csr", getCSR: func(name string) (*certificatesv1.CertificateSigningRequest, error) { if name != "test-csr" { @@ -353,7 +353,7 @@ func TestCertificateSigningController_processCertificateSigningRequest(t *testin }, }, { - description: "valid sre csr", + description: "When SRE CSR is valid, it should sign the certificate", name: "test-csr", getCSR: func(name string) (*certificatesv1.CertificateSigningRequest, error) { if name != "test-csr" { @@ -569,43 +569,43 @@ func TestDuration(t *testing.T) { want time.Duration }{ { - name: "can request shorter duration than TTL", + name: "When requesting shorter duration than TTL, it should use requested duration", certTTL: time.Hour, expirationSeconds: csr.DurationToExpirationSeconds(30 * time.Minute), want: 30 * time.Minute, }, { - name: "cannot request longer duration than TTL", + name: "When requesting longer duration than TTL, it should use TTL", certTTL: time.Hour, expirationSeconds: csr.DurationToExpirationSeconds(3 * time.Hour), want: time.Hour, }, { - name: "cannot request negative duration", + name: "When requesting negative duration, it should use minimum duration", certTTL: time.Hour, expirationSeconds: csr.DurationToExpirationSeconds(-time.Minute), want: 10 * time.Minute, }, { - name: "cannot request duration less than 10 mins", + name: "When requesting duration less than 10 mins, it should use minimum duration", certTTL: time.Hour, expirationSeconds: csr.DurationToExpirationSeconds(10*time.Minute - time.Second), want: 10 * time.Minute, }, { - name: "can request duration of exactly 10 mins", + name: "When requesting exactly 10 mins, it should use requested duration", certTTL: time.Hour, expirationSeconds: csr.DurationToExpirationSeconds(10 * time.Minute), want: 10 * time.Minute, }, { - name: "can request duration equal to the default", + name: "When requesting duration equal to TTL, it should use TTL", certTTL: time.Hour, expirationSeconds: csr.DurationToExpirationSeconds(time.Hour), want: time.Hour, }, { - name: "can choose not to request a duration to get the default", + name: "When no duration is requested, it should use TTL as default", certTTL: time.Hour, expirationSeconds: nil, want: time.Hour, diff --git a/dnsresolver/cmd_test.go b/dnsresolver/cmd_test.go index fa14e80f8fc1..d8ea924529df 100644 --- a/dnsresolver/cmd_test.go +++ b/dnsresolver/cmd_test.go @@ -22,27 +22,27 @@ func TestParseServiceName(t *testing.T) { expectError bool }{ { - name: "When given a standard headless service DNS name it should extract the service name", + name: "When given a standard headless service DNS name, it should extract the service name", dnsName: "etcd-0.etcd-discovery.my-namespace.svc", expected: "etcd-discovery", }, { - name: "When given a fully qualified DNS name it should extract the service name", + name: "When given a fully qualified DNS name, it should extract the service name", dnsName: "etcd-0.etcd-discovery.my-namespace.svc.cluster.local", expected: "etcd-discovery", }, { - name: "When given a DNS name with a long namespace it should extract the service name", + name: "When given a DNS name with a long namespace, it should extract the service name", dnsName: "etcd-2.etcd-discovery.ocm-arohcpci01-2q7h5rjtm2oud3pn6i3890qa6p37sts3-i2y6k1a2u2a0z1h.svc", expected: "etcd-discovery", }, { - name: "When given a DNS name with too few components it should return an error", + name: "When given a DNS name with too few components, it should return an error", dnsName: "etcd-0.etcd-discovery", expectError: true, }, { - name: "When given a single component it should return an error", + name: "When given a single component, it should return an error", dnsName: "etcd-0", expectError: true, }, diff --git a/etcd-backup/etcdbackup_test.go b/etcd-backup/etcdbackup_test.go index 0010a7d2c24b..7f17a9eef036 100644 --- a/etcd-backup/etcdbackup_test.go +++ b/etcd-backup/etcdbackup_test.go @@ -46,7 +46,7 @@ func TestMapToTags(t *testing.T) { validateFunc func(t *testing.T, result string) }{ { - name: "When tags are provided it should URL-encode them correctly", + name: "When tags are provided, it should URL-encode them correctly", input: map[string]string{ "env": "production", "team": "platform", @@ -78,7 +78,7 @@ func TestMapToTags(t *testing.T) { }, }, { - name: "When map is empty or nil it should return empty string", + name: "When map is empty or nil, it should return empty string", input: nil, validateFunc: func(t *testing.T, result string) { if result != "" { @@ -92,7 +92,7 @@ func TestMapToTags(t *testing.T) { }, }, { - name: "When single tag is provided it should not have ampersand", + name: "When single tag is provided, it should not have ampersand", input: map[string]string{ "env": "prod", }, @@ -106,7 +106,7 @@ func TestMapToTags(t *testing.T) { }, }, { - name: "When tags contain complex values it should preserve them in round-trip", + name: "When tags contain complex values, it should preserve them in round-trip", input: map[string]string{ "url": "https://example.com?key=value", "key": "value&special=chars@test", diff --git a/etcd-backup/fetchcerts_test.go b/etcd-backup/fetchcerts_test.go index 418f2143af19..c66bb4b1fdce 100644 --- a/etcd-backup/fetchcerts_test.go +++ b/etcd-backup/fetchcerts_test.go @@ -75,21 +75,21 @@ func TestFetchAndWriteCerts(t *testing.T) { }, }, { - name: "When etcd-client-tls secret is missing it should return an error", + name: "When etcd-client-tls secret is missing, it should return an error", objects: []crclient.Object{fullCAConfigMap}, outputDir: func(t *testing.T) string { return t.TempDir() }, expectErr: true, errSubstring: "failed to get etcd client TLS secret", }, { - name: "When etcd-ca configmap is missing it should return an error", + name: "When etcd-ca configmap is missing, it should return an error", objects: []crclient.Object{fullSecret}, outputDir: func(t *testing.T) string { return t.TempDir() }, expectErr: true, errSubstring: "failed to get etcd CA configmap", }, { - name: "When etcd-client.crt is missing from the secret it should return an error", + name: "When etcd-client.crt is missing from the secret, it should return an error", objects: []crclient.Object{ &corev1.Secret{ ObjectMeta: metav1.ObjectMeta{ @@ -107,7 +107,7 @@ func TestFetchAndWriteCerts(t *testing.T) { errSubstring: "missing key", }, { - name: "When etcd-client.key is missing from the secret it should return an error", + name: "When etcd-client.key is missing from the secret, it should return an error", objects: []crclient.Object{ &corev1.Secret{ ObjectMeta: metav1.ObjectMeta{ @@ -125,7 +125,7 @@ func TestFetchAndWriteCerts(t *testing.T) { errSubstring: "missing key", }, { - name: "When ca.crt is missing from the configmap it should return an error", + name: "When ca.crt is missing from the configmap, it should return an error", objects: []crclient.Object{ fullSecret, &corev1.ConfigMap{ diff --git a/hack/tools/hypershiftlinter/analyzers/testcasename/testcasename.go b/hack/tools/hypershiftlinter/analyzers/testcasename/testcasename.go index bbb1958c2daa..965da0290bfb 100644 --- a/hack/tools/hypershiftlinter/analyzers/testcasename/testcasename.go +++ b/hack/tools/hypershiftlinter/analyzers/testcasename/testcasename.go @@ -18,7 +18,7 @@ var Analyzer = &analysis.Analyzer{ Run: run, } -var namePattern = regexp.MustCompile(`(?i)^when .+,? it should .+$`) +var namePattern = regexp.MustCompile(`^When .+, it should .+$`) func run(pass *analysis.Pass) (any, error) { for _, file := range pass.Files { diff --git a/hack/tools/hypershiftlinter/analyzers/testcasename/testdata/src/a/bad/bad_test.go b/hack/tools/hypershiftlinter/analyzers/testcasename/testdata/src/a/bad/bad_test.go index e12da59f6f13..120053fa980d 100644 --- a/hack/tools/hypershiftlinter/analyzers/testcasename/testdata/src/a/bad/bad_test.go +++ b/hack/tools/hypershiftlinter/analyzers/testcasename/testdata/src/a/bad/bad_test.go @@ -19,6 +19,14 @@ func TestBadNames(t *testing.T) { name: "When X should Y", // want `test case name "When X should Y" must match format "When , it should "` want: "Y", }, + { + name: "when x, it should y", // want `test case name "when x, it should y" must match format "When , it should "` + want: "y", + }, + { + name: "When X it should Y", // want `test case name "When X it should Y" must match format "When , it should "` + want: "Y", + }, { name: "happy path", // want `test case name "happy path" must match format "When , it should "` want: "success", diff --git a/hack/tools/hypershiftlinter/analyzers/testcasename/testdata/src/a/good/good_test.go b/hack/tools/hypershiftlinter/analyzers/testcasename/testdata/src/a/good/good_test.go index 7ccbfd661837..180b4792de25 100644 --- a/hack/tools/hypershiftlinter/analyzers/testcasename/testdata/src/a/good/good_test.go +++ b/hack/tools/hypershiftlinter/analyzers/testcasename/testdata/src/a/good/good_test.go @@ -11,18 +11,10 @@ func TestSomething(t *testing.T) { name: "When X is set, it should return Y", want: "Y", }, - { - name: "when x, it should y", - want: "y", - }, { name: "When the user provides valid input, it should succeed", want: "success", }, - { - name: "WHEN something happens, IT SHOULD respond", - want: "ok", - }, } for _, tt := range tests { @@ -79,28 +71,6 @@ func TestNamedStructTypeDirect(t *testing.T) { _ = tc } -func TestNoCommaInName(t *testing.T) { - tests := []struct { - name string - want string - }{ - { - name: "When X it should Y", - want: "Y", - }, - { - name: "WHEN the condition is met IT SHOULD work", - want: "ok", - }, - } - - for _, tt := range tests { - t.Run(tt.name, func(t *testing.T) { - // test implementation - }) - } -} - func TestMapBasedGoodNames(t *testing.T) { tests := map[string]struct { input string @@ -108,7 +78,7 @@ func TestMapBasedGoodNames(t *testing.T) { "When input is valid, it should succeed": { input: "a", }, - "When nothing is provided it should use defaults": { + "When nothing is provided, it should use defaults": { input: "", }, } diff --git a/hack/tools/hypershiftlinter/plugin.go b/hack/tools/hypershiftlinter/plugin.go index 00fe56a55569..89dd6e5c770c 100644 --- a/hack/tools/hypershiftlinter/plugin.go +++ b/hack/tools/hypershiftlinter/plugin.go @@ -16,16 +16,16 @@ import ( "golang.org/x/tools/go/analysis" ) -type Settings struct { - Analyzers *AnalyzerSettings `json:"analyzers"` +type settings struct { + Analyzers *analyzerSettings `json:"analyzers"` } -type AnalyzerSettings struct { +type analyzerSettings struct { Enable []string `json:"enable"` } func BuildAnalyzers(rawSettings any) ([]*analysis.Analyzer, error) { - all := AllAnalyzers() + all := allAnalyzers() if rawSettings == nil { return all, nil @@ -56,7 +56,7 @@ func BuildAnalyzers(rawSettings any) ([]*analysis.Analyzer, error) { return filtered, nil } -func AllAnalyzers() []*analysis.Analyzer { +func allAnalyzers() []*analysis.Analyzer { return []*analysis.Analyzer{ testcasename.Analyzer, testfuncname.Analyzer, @@ -68,18 +68,18 @@ func AllAnalyzers() []*analysis.Analyzer { } } -func decodeSettings(raw any) (Settings, error) { +func decodeSettings(raw any) (settings, error) { data, err := json.Marshal(raw) if err != nil { - return Settings{}, err + return settings{}, err } // Reject unknown fields so that a typo such as "enbale" surfaces as an error // instead of silently leaving Enable empty and enabling every analyzer. dec := json.NewDecoder(bytes.NewReader(data)) dec.DisallowUnknownFields() - var s Settings + var s settings if err := dec.Decode(&s); err != nil { - return Settings{}, err + return settings{}, err } return s, nil } diff --git a/hack/tools/hypershiftlinter/plugin_test.go b/hack/tools/hypershiftlinter/plugin_test.go index a324b9588a77..85d6e7b7f23c 100644 --- a/hack/tools/hypershiftlinter/plugin_test.go +++ b/hack/tools/hypershiftlinter/plugin_test.go @@ -49,9 +49,9 @@ func TestBuildAnalyzersNilSettingsEnablesAll(t *testing.T) { if err != nil { t.Fatalf("unexpected error: %v", err) } - if len(got) != len(AllAnalyzers()) { + if len(got) != len(allAnalyzers()) { t.Fatalf("expected all analyzers, got %d of %d: %s", - len(got), len(AllAnalyzers()), strings.Join(analyzerNames(got), ", ")) + len(got), len(allAnalyzers()), strings.Join(analyzerNames(got), ", ")) } } diff --git a/hypershift-operator/controllers/etcdbackup/reconciler_test.go b/hypershift-operator/controllers/etcdbackup/reconciler_test.go index 077e00f19579..f3ff3a89b64d 100644 --- a/hypershift-operator/controllers/etcdbackup/reconciler_test.go +++ b/hypershift-operator/controllers/etcdbackup/reconciler_test.go @@ -1042,7 +1042,7 @@ func TestBuildUploadArgs(t *testing.T) { wantContain: []string{"--azure-encryption-scope", "https://myvault.vault.azure.net/keys/mykey"}, }, { - name: "When storage type is unsupported it should return an error", + name: "When storage type is unsupported, it should return an error", backup: &hyperv1.HCPEtcdBackup{ Spec: hyperv1.HCPEtcdBackupSpec{ Storage: hyperv1.HCPEtcdBackupStorage{StorageType: "UnknownStorage"}, diff --git a/hypershift-operator/controllers/hostedcluster/createorupdate_annotation_enforcer_test.go b/hypershift-operator/controllers/hostedcluster/createorupdate_annotation_enforcer_test.go index 8b0731d83657..d4c234c4faac 100644 --- a/hypershift-operator/controllers/hostedcluster/createorupdate_annotation_enforcer_test.go +++ b/hypershift-operator/controllers/hostedcluster/createorupdate_annotation_enforcer_test.go @@ -28,7 +28,7 @@ func TestCreateOrUpdateWithAnnotationFactory(t *testing.T) { mutateFN func(crclient.Object) controllerutil.MutateFn }{ { - name: "No annotations", + name: "When object has no annotations, it should add the hosted cluster annotation", obj: &corev1.ConfigMap{ TypeMeta: metav1.TypeMeta{ Kind: "ConfigMap", @@ -53,7 +53,7 @@ func TestCreateOrUpdateWithAnnotationFactory(t *testing.T) { }, }, { - name: "Existing annotations are kept", + name: "When object has existing annotations, it should keep them and add the hosted cluster annotation", obj: &corev1.ConfigMap{ TypeMeta: metav1.TypeMeta{ Kind: "ConfigMap", @@ -84,7 +84,7 @@ func TestCreateOrUpdateWithAnnotationFactory(t *testing.T) { }, }, { - name: "Do not annotate cluster scoped resources", + name: "When object is cluster scoped, it should not add annotations", obj: &corev1.Namespace{ TypeMeta: metav1.TypeMeta{ Kind: "Namespace", diff --git a/hypershift-operator/controllers/hostedcluster/gcp_oidc_test.go b/hypershift-operator/controllers/hostedcluster/gcp_oidc_test.go index 0610971b54e7..68654663db01 100644 --- a/hypershift-operator/controllers/hostedcluster/gcp_oidc_test.go +++ b/hypershift-operator/controllers/hostedcluster/gcp_oidc_test.go @@ -174,7 +174,7 @@ func TestReconcileGCPOIDCDocuments(t *testing.T) { expectFinalizer: false, }, { - name: "When GCS client is nil and no signing key it should return an error", + name: "When GCS client is nil and no signing key, it should return an error", hcluster: &hyperv1.HostedCluster{ ObjectMeta: metav1.ObjectMeta{Name: "test", Namespace: "clusters"}, Spec: hyperv1.HostedClusterSpec{InfraID: "test-infra"}, @@ -189,7 +189,7 @@ func TestReconcileGCPOIDCDocuments(t *testing.T) { expectErrMsg: "GCP OIDC document management requires either a ServiceAccountSigningKey", }, { - name: "When bucket name is empty and no signing key it should return an error", + name: "When bucket name is empty and no signing key, it should return an error", hcluster: &hyperv1.HostedCluster{ ObjectMeta: metav1.ObjectMeta{Name: "test", Namespace: "clusters"}, Spec: hyperv1.HostedClusterSpec{InfraID: "test-infra"}, @@ -219,7 +219,7 @@ func TestReconcileGCPOIDCDocuments(t *testing.T) { expectFinalizer: false, }, { - name: "When sa-signing-key secret is missing the public key it should return an error", + name: "When sa-signing-key secret is missing the public key, it should return an error", hcluster: &hyperv1.HostedCluster{ ObjectMeta: metav1.ObjectMeta{Name: "test", Namespace: "clusters"}, Spec: hyperv1.HostedClusterSpec{InfraID: "test-infra"}, @@ -257,7 +257,7 @@ func TestReconcileGCPOIDCDocuments(t *testing.T) { expectFinalizer: true, }, { - name: "When GCS upload fails it should return an error", + name: "When GCS upload fails, it should return an error", hcluster: &hyperv1.HostedCluster{ ObjectMeta: metav1.ObjectMeta{Name: "test", Namespace: "clusters"}, Spec: hyperv1.HostedClusterSpec{InfraID: "test-infra"}, @@ -350,7 +350,7 @@ func TestCleanupGCPOIDCBucketData(t *testing.T) { expectFinalizer: false, }, { - name: "When GCS client is nil it should return an error", + name: "When GCS client is nil, it should return an error", hcluster: &hyperv1.HostedCluster{ ObjectMeta: metav1.ObjectMeta{ Name: "test", @@ -381,7 +381,7 @@ func TestCleanupGCPOIDCBucketData(t *testing.T) { expectFinalizer: false, }, { - name: "When GCS delete fails it should return an error and keep finalizer", + name: "When GCS delete fails, it should return an error and keep finalizer", hcluster: &hyperv1.HostedCluster{ ObjectMeta: metav1.ObjectMeta{ Name: "test", diff --git a/hypershift-operator/controllers/hostedcluster/hostedcluster_controller_test.go b/hypershift-operator/controllers/hostedcluster/hostedcluster_controller_test.go index f4ce7ee8f84d..76c944b738b4 100644 --- a/hypershift-operator/controllers/hostedcluster/hostedcluster_controller_test.go +++ b/hypershift-operator/controllers/hostedcluster/hostedcluster_controller_test.go @@ -132,11 +132,11 @@ func TestHasBeenAvailable(t *testing.T) { isExpectingAnnotationToBeSet bool }{ { - name: "When cluster just got created, annotation is not yet set", + name: "When cluster just got created it should not have annotation set", timestamp: now, }, { - name: "When available condition is false, annotation is not set", + name: "When available condition is false it should not set annotation", timestamp: now.Add(5 * time.Minute), hcpConditions: []metav1.Condition{ { @@ -146,7 +146,7 @@ func TestHasBeenAvailable(t *testing.T) { }, }, { - name: "When available condition is true, annotation is set", + name: "When available condition is true it should set annotation", timestamp: now.Add(5 * time.Minute), hcpConditions: []metav1.Condition{ { @@ -158,7 +158,7 @@ func TestHasBeenAvailable(t *testing.T) { isExpectingAnnotationToBeSet: true, }, { - name: "When available condition is false again, annotation is not unset if already set", + name: "When available condition is false again it should not unset annotation if already set", timestamp: now.Add(10 * time.Minute), hcAnnotationsBeforeReconciliation: map[string]string{ hcmetrics.HasBeenAvailableAnnotation: "true", @@ -473,7 +473,7 @@ func TestReconcileHostedControlPlaneAdditionalTrustBundle(t *testing.T) { expectedAdditionalTrustBundle *corev1.LocalObjectReference }{ { - name: "no additional trust bundle", + name: "When no additional trust bundle is set it should not set trust bundle on HCP", cluster: hyperv1.HostedCluster{ Spec: hyperv1.HostedClusterSpec{}, }, @@ -483,7 +483,7 @@ func TestReconcileHostedControlPlaneAdditionalTrustBundle(t *testing.T) { expectedAdditionalTrustBundle: nil, }, { - name: "additional trust bundle", + name: "When additional trust bundle is set it should copy trust bundle to HCP", cluster: hyperv1.HostedCluster{ Spec: hyperv1.HostedClusterSpec{ AdditionalTrustBundle: &corev1.LocalObjectReference{Name: "test-bundle"}, @@ -495,7 +495,7 @@ func TestReconcileHostedControlPlaneAdditionalTrustBundle(t *testing.T) { expectedAdditionalTrustBundle: &corev1.LocalObjectReference{Name: "user-ca-bundle"}, }, { - name: "additional trust bundle removed", + name: "When additional trust bundle is removed it should clear trust bundle on HCP", cluster: hyperv1.HostedCluster{ Spec: hyperv1.HostedClusterSpec{}, }, @@ -777,27 +777,27 @@ func TestReconcileHostedControlPlaneAPINetwork(t *testing.T) { expectedAPIPort *int32 }{ { - name: "not specified", + name: "When API networking is not specified it should leave address and port nil", networking: nil, expectedAPIAdvertiseAddress: nil, expectedAPIPort: nil, }, { - name: "advertise address specified", + name: "When advertise address is specified it should set the address on HCP", networking: &hyperv1.APIServerNetworking{ AdvertiseAddress: ptr.To("1.2.3.4"), }, expectedAPIAdvertiseAddress: ptr.To("1.2.3.4"), }, { - name: "port specified", + name: "When port is specified it should set the port on HCP", networking: &hyperv1.APIServerNetworking{ Port: ptr.To[int32](1234), }, expectedAPIPort: ptr.To[int32](1234), }, { - name: "both specified", + name: "When both address and port are specified it should set both on HCP", networking: &hyperv1.APIServerNetworking{ Port: ptr.To[int32](6789), AdvertiseAddress: ptr.To("9.8.7.6"), @@ -843,11 +843,11 @@ func TestReconcileHostedControlPlaneConfiguration(t *testing.T) { configuration *hyperv1.ClusterConfiguration }{ { - name: "not specified", + name: "When configuration is not specified it should leave HCP configuration nil", configuration: nil, }, { - name: "cluster configuration specified", + name: "When cluster configuration is specified it should copy it to HCP", configuration: &hyperv1.ClusterConfiguration{ OAuth: &configv1.OAuthSpec{ IdentityProviders: []configv1.IdentityProvider{ @@ -1007,7 +1007,7 @@ func TestReconcileHostedControlPlaneAnnotations(t *testing.T) { tests := []testCase{ { - name: "Swift annotation is mirrored", + name: "When Swift annotation is set on HC it should mirror to HCP", hcAnnotations: map[string]string{ hyperv1.SwiftPodNetworkInstanceAnnotation: "swift-network-instance", }, @@ -1019,7 +1019,7 @@ func TestReconcileHostedControlPlaneAnnotations(t *testing.T) { }, }, { - name: "Newly set restart annotation", + name: "When restart annotation is newly set it should propagate to HCP", hcAnnotations: map[string]string{ hyperv1.RestartDateAnnotation: "01012024", }, @@ -1032,7 +1032,7 @@ func TestReconcileHostedControlPlaneAnnotations(t *testing.T) { }, }, { - name: "Existing restart annotation (different value)", + name: "When restart annotation has a different value it should update HCP", hcAnnotations: map[string]string{ hyperv1.RestartDateAnnotation: "05012024", }, @@ -1049,7 +1049,7 @@ func TestReconcileHostedControlPlaneAnnotations(t *testing.T) { }, }, { - name: "Previously applied restart annotation, different actual value", + name: "When previously applied restart annotation has different actual value it should preserve HCP value", hcAnnotations: map[string]string{ hyperv1.RestartDateAnnotation: "01012024", }, @@ -1066,7 +1066,7 @@ func TestReconcileHostedControlPlaneAnnotations(t *testing.T) { }, }, { - name: "Previously applied restart annotation, new value", + name: "When previously applied restart annotation has new value it should update HCP", hcAnnotations: map[string]string{ hyperv1.RestartDateAnnotation: "05012024", }, @@ -1083,7 +1083,7 @@ func TestReconcileHostedControlPlaneAnnotations(t *testing.T) { }, }, { - name: "Initial reconcile", + name: "When initial reconcile with annotations it should copy known annotations to HCP", hcAnnotations: map[string]string{ k8sutil.DebugDeploymentsAnnotation: "control-plane-operator", hyperv1.EtcdPriorityClass: "high-priority", @@ -1106,7 +1106,7 @@ func TestReconcileHostedControlPlaneAnnotations(t *testing.T) { }, }, { - name: "Initial reconcile - autoscaling needed", + name: "When initial reconcile with autoscaling needed it should not set disable autoscaling annotation", hcAnnotations: map[string]string{ k8sutil.DebugDeploymentsAnnotation: "control-plane-operator", hyperv1.EtcdPriorityClass: "high-priority", @@ -1127,7 +1127,7 @@ func TestReconcileHostedControlPlaneAnnotations(t *testing.T) { isAutoscalingNeeded: true, }, { - name: "Existing disable autoscaling annotation, autoscaling no longer needed", + name: "When autoscaling is no longer needed it should remove disable autoscaling annotation", hcAnnotations: map[string]string{ k8sutil.DebugDeploymentsAnnotation: "control-plane-operator", }, @@ -1142,7 +1142,7 @@ func TestReconcileHostedControlPlaneAnnotations(t *testing.T) { isAutoscalingNeeded: true, }, { - name: "Remove known annotations that are no longer set", + name: "When known annotations are no longer set on HC it should remove them from HCP", hcAnnotations: map[string]string{ hyperv1.EtcdPriorityClass: "high-priority", hyperv1.RequestServingNodeAdditionalSelectorAnnotation: "node-size=m5xl", @@ -1187,7 +1187,7 @@ func TestReconcileHostedControlPlaneAnnotations(t *testing.T) { }, }, { - name: "When AWS node termination handler is needed, disable annotation should not be set", + name: "When AWS node termination handler is needed, it should not set disable annotation", isAWSNodeTerminationHandlerNeeded: true, hcAnnotations: map[string]string{}, hcpAnnotations: map[string]string{}, @@ -1197,7 +1197,7 @@ func TestReconcileHostedControlPlaneAnnotations(t *testing.T) { }, }, { - name: "When AWS node termination handler is no longer needed, disable annotation should be added", + name: "When AWS node termination handler is no longer needed, it should add disable annotation", isAWSNodeTerminationHandlerNeeded: false, hcAnnotations: map[string]string{}, hcpAnnotations: map[string]string{}, @@ -1208,7 +1208,7 @@ func TestReconcileHostedControlPlaneAnnotations(t *testing.T) { }, }, { - name: "When AWS node termination handler becomes needed, existing disable annotation should be removed", + name: "When AWS node termination handler becomes needed, it should remove existing disable annotation", isAWSNodeTerminationHandlerNeeded: true, hcAnnotations: map[string]string{}, hcpAnnotations: map[string]string{ @@ -1248,14 +1248,14 @@ func TestAnnotationsForCertRenewal(t *testing.T) { expected map[string]string }{ { - name: "should not check", + name: "When check is skipped, it should not return annotations", shouldSkip: true, hashFromSecret: "12345", hashFromEndpoint: "67890", expected: nil, }, { - name: "no existing hash annotation on hcp, endpoint hash matches", + name: "When no existing hash annotation and endpoint hash matches, it should set hash annotation", hashFromSecret: "12345", hashFromEndpoint: "12345", expected: map[string]string{ @@ -1263,7 +1263,7 @@ func TestAnnotationsForCertRenewal(t *testing.T) { }, }, { - name: "no existing hash annotation on hcp, endpoint hash does not match", + name: "When no existing hash annotation and endpoint hash does not match, it should set hash and restart annotations", hashFromSecret: "12345", hashFromEndpoint: "67890", expected: map[string]string{ @@ -1272,7 +1272,7 @@ func TestAnnotationsForCertRenewal(t *testing.T) { }, }, { - name: "existing hash annotation, secret hash matches", + name: "When existing hash annotation and secret hash matches, it should return nil", hashFromSecret: "12345", hcpAnnotations: map[string]string{ kasServingCertHashAnnotation: "12345", @@ -1280,7 +1280,7 @@ func TestAnnotationsForCertRenewal(t *testing.T) { expected: nil, }, { - name: "existing hash annotation, secret hash does not match", + name: "When existing hash annotation and secret hash does not match, it should set hash and restart annotations", hashFromSecret: "67890", hcpAnnotations: map[string]string{ kasServingCertHashAnnotation: "12345", @@ -1319,7 +1319,7 @@ func TestShouldCheckForStaleCerts(t *testing.T) { expectedResult bool }{ { - name: "cpo without cpov2label", + name: "When CPO has no cpov2 label it should check for stale certs", hcAnnotations: map[string]string{ hcmetrics.HasBeenAvailableAnnotation: "true", }, @@ -1327,7 +1327,7 @@ func TestShouldCheckForStaleCerts(t *testing.T) { expectedResult: true, }, { - name: "cpo with cpov2label", + name: "When CPO has cpov2 label it should not check for stale certs", hcAnnotations: map[string]string{ hcmetrics.HasBeenAvailableAnnotation: "true", }, @@ -1335,13 +1335,13 @@ func TestShouldCheckForStaleCerts(t *testing.T) { expectedResult: false, }, { - name: "has not been available", + name: "When cluster has not been available it should not check for stale certs", hcAnnotations: nil, cpov2label: false, expectedResult: false, }, { - name: "has been available, does not reconcile pki", + name: "When cluster has been available but PKI reconciliation is disabled it should not check for stale certs", hcAnnotations: map[string]string{ hcmetrics.HasBeenAvailableAnnotation: "true", hyperv1.DisablePKIReconciliationAnnotation: "true", @@ -1370,12 +1370,12 @@ func TestServiceFirstNodePortAvailable(t *testing.T) { expectedAvailable bool }{ { - name: "not specified", + name: "When service is not specified it should not be available", inputService: nil, expectedAvailable: false, }, { - name: "node port not available", + name: "When node port is not available it should return false", inputService: &corev1.Service{ ObjectMeta: metav1.ObjectMeta{ Name: "test-service", @@ -1394,7 +1394,7 @@ func TestServiceFirstNodePortAvailable(t *testing.T) { expectedAvailable: false, }, { - name: "node port available", + name: "When node port is available it should return true", inputService: &corev1.Service{ ObjectMeta: metav1.ObjectMeta{ Name: "test-service", @@ -1432,7 +1432,7 @@ func TestServicePublishingStrategyByType(t *testing.T) { expectedServicePublishingStrategy *hyperv1.ServicePublishingStrategyMapping }{ { - name: "ignition node port", + name: "When ignition node port strategy exists it should return it", inputHostedCluster: &hyperv1.HostedCluster{ Spec: hyperv1.HostedClusterSpec{ Services: []hyperv1.ServicePublishingStrategyMapping{ @@ -1454,7 +1454,7 @@ func TestServicePublishingStrategyByType(t *testing.T) { }, }, { - name: "not found", + name: "When service type is not found it should return nil", inputHostedCluster: &hyperv1.HostedCluster{ Spec: hyperv1.HostedClusterSpec{ Services: []hyperv1.ServicePublishingStrategyMapping{ @@ -1497,7 +1497,7 @@ func TestReconcileCAPICluster(t *testing.T) { expectedCAPICluster *v1beta1.Cluster }{ { - name: "IBM Cloud cluster", + name: "When platform is IBM Cloud it should reconcile CAPI cluster correctly", capiCluster: controlplaneoperator.CAPICluster("master-cluster1", "cluster1"), hostedCluster: &hyperv1.HostedCluster{ TypeMeta: metav1.TypeMeta{ @@ -1555,7 +1555,7 @@ func TestReconcileCAPICluster(t *testing.T) { }, }, { - name: "AWS cluster", + name: "When platform is AWS it should reconcile CAPI cluster correctly", capiCluster: controlplaneoperator.CAPICluster("master-cluster1", "cluster1"), hostedCluster: &hyperv1.HostedCluster{ TypeMeta: metav1.TypeMeta{ @@ -1633,10 +1633,10 @@ func TestReconcileAWSResourceTags(t *testing.T) { expected hyperv1.HostedClusterSpec }{ { - name: "Not an aws cluster, no change", + name: "When cluster is not AWS it should make no change", }, { - name: "Tag is added", + name: "When tag is missing, it should add the tag", in: hyperv1.HostedClusterSpec{ InfraID: "123", Platform: hyperv1.PlatformSpec{ @@ -1656,7 +1656,7 @@ func TestReconcileAWSResourceTags(t *testing.T) { }, }, { - name: "Tag already exists, nothing to do", + name: "When tag already exists with correct value, it should not change anything", in: hyperv1.HostedClusterSpec{ InfraID: "123", Platform: hyperv1.PlatformSpec{ @@ -1681,7 +1681,7 @@ func TestReconcileAWSResourceTags(t *testing.T) { }, }, { - name: "Tag already exists with wrong value", + name: "When tag already exists with wrong value, it should update the tag", in: hyperv1.HostedClusterSpec{ InfraID: "123", Platform: hyperv1.PlatformSpec{ @@ -2249,7 +2249,7 @@ func TestReconcileCLISecrets(t *testing.T) { expectedWithRef int }{ { - name: "secret with both labels and with no ownerRef", + name: "When secret has both labels and no ownerRef it should set the ownerRef", secrets: []crclient.Object{ &corev1.Secret{ ObjectMeta: metav1.ObjectMeta{ @@ -2262,7 +2262,7 @@ func TestReconcileCLISecrets(t *testing.T) { expectedWithRef: 1, }, { - name: "multiple secret with both labels and with no ownerRef", + name: "When multiple secrets have both labels and no ownerRef it should set ownerRefs on all", secrets: []crclient.Object{ &corev1.Secret{ ObjectMeta: metav1.ObjectMeta{ @@ -2289,7 +2289,7 @@ func TestReconcileCLISecrets(t *testing.T) { expectedWithRef: 3, }, { - name: "mix cases", + name: "When secrets have mixed label and ownerRef states it should only update those needing ownerRefs", secrets: []crclient.Object{ &corev1.Secret{ ObjectMeta: metav1.ObjectMeta{ @@ -2468,7 +2468,7 @@ func TestValidateConfigAndClusterCapabilities(t *testing.T) { infraK8sVersion string }{ { - name: "Cluster uses route but not supported, error", + name: "When cluster uses route but not supported it should return error", hostedCluster: &hyperv1.HostedCluster{ ObjectMeta: metav1.ObjectMeta{ Name: "test-cluster", @@ -2487,7 +2487,7 @@ func TestValidateConfigAndClusterCapabilities(t *testing.T) { expectedResult: errors.New(`cluster does not support Routes, but service "" is exposed via a Route`), }, { - name: "Cluster uses routes and supported, success", + name: "When cluster uses routes and platform supports them it should succeed", hostedCluster: &hyperv1.HostedCluster{ ObjectMeta: metav1.ObjectMeta{ Name: "test-cluster", @@ -2505,7 +2505,7 @@ func TestValidateConfigAndClusterCapabilities(t *testing.T) { managementClusterCapabilities: &fakecapabilities.FakeSupportAllCapabilities{}, }, { - name: "invalid cluster uuid", + name: "When cluster UUID is invalid it should return error", hostedCluster: &hyperv1.HostedCluster{ ObjectMeta: metav1.ObjectMeta{ Name: "test-cluster", @@ -2519,7 +2519,7 @@ func TestValidateConfigAndClusterCapabilities(t *testing.T) { expectedResult: errors.New(`cannot parse cluster ID "foobar": invalid UUID length: 6`), }, { - name: "Setting Service network CIDR and NodePort IP overlapping, not allowed", + name: "When service network CIDR and NodePort IP overlap it should not be allowed", hostedCluster: &hyperv1.HostedCluster{ ObjectMeta: metav1.ObjectMeta{ Name: "test-cluster", @@ -2547,7 +2547,7 @@ func TestValidateConfigAndClusterCapabilities(t *testing.T) { expectedResult: errors.New(`[spec.networking.MachineNetwork: Invalid value: "172.16.1.0/24": spec.networking.MachineNetwork and spec.networking.ServiceNetwork overlap: 172.16.1.0/24 and 172.16.1.252/32, spec.networking.ServiceNetwork: Invalid value: "172.16.3.0/24": Nodeport IP is within the service network range: 172.16.3.3 is within 172.16.3.0/24]`), }, { - name: "Setting network CIDRs overlapped, not allowed", + name: "When network CIDRs overlap it should not be allowed", hostedCluster: &hyperv1.HostedCluster{ ObjectMeta: metav1.ObjectMeta{ Name: "test-cluster", @@ -2563,7 +2563,7 @@ func TestValidateConfigAndClusterCapabilities(t *testing.T) { expectedResult: errors.New(`spec.networking.MachineNetwork: Invalid value: "172.16.1.0/24": spec.networking.MachineNetwork and spec.networking.ServiceNetwork overlap: 172.16.1.0/24 and 172.16.1.252/32`), }, { - name: "multiple published services use the same hostname, error", + name: "When multiple published services use the same hostname it should return error", hostedCluster: &hyperv1.HostedCluster{ ObjectMeta: metav1.ObjectMeta{ Name: "test-cluster", @@ -2593,7 +2593,7 @@ func TestValidateConfigAndClusterCapabilities(t *testing.T) { managementClusterCapabilities: &fakecapabilities.FakeSupportAllCapabilities{}, }, { - name: "KubeVirt cluster meeting min infra cluster versions should succeed", + name: "When KubeVirt cluster meets min infra cluster versions it should succeed", hostedCluster: &hyperv1.HostedCluster{ ObjectMeta: metav1.ObjectMeta{ Name: "test-cluster", @@ -2613,7 +2613,7 @@ func TestValidateConfigAndClusterCapabilities(t *testing.T) { infraK8sVersion: "v1.27.0", }, { - name: "KubeVirt cluster not meeting min infra cluster versions should fail", + name: "When KubeVirt cluster does not meet min infra cluster versions it should fail", hostedCluster: &hyperv1.HostedCluster{ ObjectMeta: metav1.ObjectMeta{ Name: "test-cluster", @@ -2667,7 +2667,7 @@ func TestValidateReleaseImage(t *testing.T) { expectedNotFoundError bool }{ { - name: "no pull secret, error", + name: "When no pull secret is provided it should return error", hostedCluster: &hyperv1.HostedCluster{ Spec: hyperv1.HostedClusterSpec{ Networking: hyperv1.ClusterNetworking{ @@ -2685,7 +2685,7 @@ func TestValidateReleaseImage(t *testing.T) { expectedNotFoundError: true, }, { - name: "invalid pull secret, error", + name: "When pull secret is invalid it should return error", other: []crclient.Object{ &corev1.Secret{ ObjectMeta: metav1.ObjectMeta{Name: "pull-secret"}, @@ -2708,7 +2708,7 @@ func TestValidateReleaseImage(t *testing.T) { expectedResult: errors.New("pull secret unavailable: expected .dockerconfigjson key in secret \"pull-secret\""), }, { - name: "unable to pull release image, error", + name: "When unable to pull release image it should return error", other: []crclient.Object{ &corev1.Secret{ ObjectMeta: metav1.ObjectMeta{Name: "pull-secret"}, @@ -2736,7 +2736,7 @@ func TestValidateReleaseImage(t *testing.T) { expectedResult: errors.New("failed to lookup release image: unable to lookup release image"), }, { - name: "unsupported release, error", + name: "When release is unsupported it should return error", other: []crclient.Object{ &corev1.Secret{ ObjectMeta: metav1.ObjectMeta{Name: "pull-secret"}, @@ -2764,7 +2764,7 @@ func TestValidateReleaseImage(t *testing.T) { expectedResult: errors.New(`releases before 4.8 are not supported. Attempting to use: "4.7.0"`), }, { - name: "unsupported y-stream downgrade, error", + name: "When y-stream downgrade is attempted it should return error", other: []crclient.Object{ &corev1.Secret{ ObjectMeta: metav1.ObjectMeta{Name: "pull-secret"}, @@ -2799,7 +2799,7 @@ func TestValidateReleaseImage(t *testing.T) { expectedResult: errors.New(`y-stream downgrade from "4.16.0" to "4.15.0" is not supported`), }, { - name: "unsupported y-stream upgrade, error", + name: "When unsupported y-stream upgrade is attempted it should return error", other: []crclient.Object{ &corev1.Secret{ ObjectMeta: metav1.ObjectMeta{Name: "pull-secret"}, @@ -2834,7 +2834,7 @@ func TestValidateReleaseImage(t *testing.T) { expectedResult: errors.New(`y-stream upgrade from "4.12.0" to "4.15.0" is not for OpenShiftSDN`), }, { - name: "supported y-stream upgrade, success", + name: "When supported y-stream upgrade is attempted it should succeed", other: []crclient.Object{ &corev1.Secret{ ObjectMeta: metav1.ObjectMeta{Name: "pull-secret"}, @@ -2869,7 +2869,7 @@ func TestValidateReleaseImage(t *testing.T) { expectedResult: nil, }, { - name: "valid create, success", + name: "When creating with valid release image it should succeed", other: []crclient.Object{ &corev1.Secret{ ObjectMeta: metav1.ObjectMeta{Name: "pull-secret"}, @@ -2897,7 +2897,7 @@ func TestValidateReleaseImage(t *testing.T) { expectedResult: nil, }, { - name: "no-op, success", + name: "When release image is unchanged it should succeed", other: []crclient.Object{ &corev1.Secret{ ObjectMeta: metav1.ObjectMeta{Name: "pull-secret"}, @@ -2932,7 +2932,7 @@ func TestValidateReleaseImage(t *testing.T) { }, }, { - name: "z-stream upgrade, success", + name: "When z-stream upgrade is attempted it should succeed", other: []crclient.Object{ &corev1.Secret{ ObjectMeta: metav1.ObjectMeta{Name: "pull-secret"}, @@ -2967,7 +2967,7 @@ func TestValidateReleaseImage(t *testing.T) { }, }, { - name: "y-stream upgrade, success", + name: "When y-stream upgrade is supported it should succeed", other: []crclient.Object{ &corev1.Secret{ ObjectMeta: metav1.ObjectMeta{Name: "pull-secret"}, @@ -3002,7 +3002,7 @@ func TestValidateReleaseImage(t *testing.T) { expectedResult: nil, }, { - name: "skip release image validation with annotation, success", + name: "When skip release image validation annotation is set it should succeed", other: []crclient.Object{ &corev1.Secret{ ObjectMeta: metav1.ObjectMeta{Name: "pull-secret"}, @@ -3090,7 +3090,7 @@ func TestPauseHostedControlPlane(t *testing.T) { expectedHostedControlPlaneObject *hyperv1.HostedControlPlane }{ { - name: "if a hostedControlPlane exists then the pauseReconciliation annotation is added to it", + name: "When a hostedControlPlane exists it should add the pauseReconciliation annotation to it", inputHostedControlPlane: manifests.HostedControlPlane(fakeHCPNamespace, fakeHCPName), inputObjects: []crclient.Object{ &hyperv1.HostedControlPlane{ @@ -3111,7 +3111,7 @@ func TestPauseHostedControlPlane(t *testing.T) { }, }, { - name: "if a hostedControlPlane does not exist it is not created", + name: "When a hostedControlPlane does not exist it should not create one", inputHostedControlPlane: manifests.HostedControlPlane(fakeHCPNamespace, fakeHCPName), inputObjects: []crclient.Object{}, expectedHostedControlPlaneObject: nil, @@ -3307,19 +3307,19 @@ func TestDefaultClusterIDsIfNeeded(t *testing.T) { hc *hyperv1.HostedCluster }{ { - name: "generate both", + name: "When both IDs are missing it should generate both", hc: testHC("", ""), }, { - name: "generate clusterid", + name: "When cluster ID is missing it should generate cluster ID", hc: testHC("fake-infra", ""), }, { - name: "generate infra-id", + name: "When infra ID is missing it should generate infra ID", hc: testHC("", "fake-uuid"), }, { - name: "generate none", + name: "When both IDs are already set it should not generate any", hc: testHC("fake-infra", "fake-uuid"), }, } @@ -3362,7 +3362,7 @@ func TestIsUpgradeable(t *testing.T) { err bool }{ { - name: "version not reported yet", + name: "When version is not reported yet it should be upgradeable", hc: &hyperv1.HostedCluster{ Spec: hyperv1.HostedClusterSpec{ Release: hyperv1.Release{ @@ -3383,7 +3383,7 @@ func TestIsUpgradeable(t *testing.T) { err: false, }, { - name: "not upgrading", + name: "When cluster is not upgrading it should be upgradeable", hc: &hyperv1.HostedCluster{ Spec: hyperv1.HostedClusterSpec{ Release: hyperv1.Release{ @@ -3409,7 +3409,7 @@ func TestIsUpgradeable(t *testing.T) { err: false, }, { - name: "not upgradeable, no force annotation", + name: "When not upgradeable and no force annotation it should not be upgradeable", hc: &hyperv1.HostedCluster{ Spec: hyperv1.HostedClusterSpec{ Release: hyperv1.Release{ @@ -3441,7 +3441,7 @@ func TestIsUpgradeable(t *testing.T) { err: true, }, { - name: "not upgradeable, old force annotation", + name: "When not upgradeable with old force annotation it should not be upgradeable", hc: &hyperv1.HostedCluster{ ObjectMeta: metav1.ObjectMeta{ Annotations: map[string]string{ @@ -3478,7 +3478,7 @@ func TestIsUpgradeable(t *testing.T) { err: true, }, { - name: "not upgradeable, force annotation", + name: "When not upgradeable with current force annotation it should be upgradeable", hc: &hyperv1.HostedCluster{ ObjectMeta: metav1.ObjectMeta{ Annotations: map[string]string{ @@ -3510,7 +3510,7 @@ func TestIsUpgradeable(t *testing.T) { err: false, }, { - name: "not upgradeable but z-stream upgrade allowed", + name: "When not upgradeable but z-stream upgrade is attempted it should be upgradeable", hc: &hyperv1.HostedCluster{ Spec: hyperv1.HostedClusterSpec{ Release: hyperv1.Release{ @@ -3603,7 +3603,7 @@ func TestReconciliationSuccessConditionSetting(t *testing.T) { expectedConditions []metav1.Condition }{ { - name: "Success, success condition gets set", + name: "When reconciliation succeeds it should set success condition", expectedConditions: []metav1.Condition{{ Type: string(hyperv1.ReconciliationSucceeded), Status: metav1.ConditionTrue, @@ -3613,7 +3613,7 @@ func TestReconciliationSuccessConditionSetting(t *testing.T) { }}, }, { - name: "Success, existing success condition transition timestamp stays", + name: "When reconciliation succeeds with existing condition it should preserve transition timestamp", existingConditions: []metav1.Condition{{ Type: string(hyperv1.ReconciliationSucceeded), Status: metav1.ConditionTrue, @@ -3630,7 +3630,7 @@ func TestReconciliationSuccessConditionSetting(t *testing.T) { }}, }, { - name: "Success, error condition gets cleared", + name: "When reconciliation succeeds it should clear error condition", existingConditions: []metav1.Condition{{ Type: string(hyperv1.ReconciliationSucceeded), Status: metav1.ConditionFalse, @@ -3646,7 +3646,7 @@ func TestReconciliationSuccessConditionSetting(t *testing.T) { }}, }, { - name: "Error, error gets set", + name: "When reconciliation errors it should set error condition", reconcileResult: errors.New("things went sideways"), expectedConditions: []metav1.Condition{{ Type: string(hyperv1.ReconciliationSucceeded), @@ -3657,7 +3657,7 @@ func TestReconciliationSuccessConditionSetting(t *testing.T) { }}, }, { - name: "Error, errors gets updated", + name: "When reconciliation errors again it should update error condition", reconcileResult: errors.New("things went sideways"), existingConditions: []metav1.Condition{{ Type: string(hyperv1.ReconciliationSucceeded), @@ -3675,7 +3675,7 @@ func TestReconciliationSuccessConditionSetting(t *testing.T) { }}, }, { - name: "Error, success condition gets cleaned up", + name: "When reconciliation errors it should clean up success condition", reconcileResult: errors.New("things went sideways"), existingConditions: []metav1.Condition{{ Type: string(hyperv1.ReconciliationSucceeded), @@ -3749,7 +3749,7 @@ func TestIsProgressing(t *testing.T) { wantErr bool }{ { - name: "stable at release", + name: "When cluster is stable at release, it should not be progressing", hc: &hyperv1.HostedCluster{ Spec: hyperv1.HostedClusterSpec{ Release: hyperv1.Release{ @@ -3772,7 +3772,7 @@ func TestIsProgressing(t *testing.T) { wantErr: false, }, { - name: "stable at release with digest", + name: "When cluster is stable at release with digest, it should not be progressing", hc: &hyperv1.HostedCluster{ Spec: hyperv1.HostedClusterSpec{ Release: hyperv1.Release{ @@ -3796,7 +3796,7 @@ func TestIsProgressing(t *testing.T) { wantErr: false, }, { - name: "cluster is rolling out", + name: "When cluster is rolling out, it should be progressing", hc: &hyperv1.HostedCluster{ Spec: hyperv1.HostedClusterSpec{ Release: hyperv1.Release{ @@ -3811,7 +3811,7 @@ func TestIsProgressing(t *testing.T) { wantErr: false, }, { - name: "cluster is upgrading with digest", + name: "When cluster is upgrading with digest, it should be progressing", hc: &hyperv1.HostedCluster{ Spec: hyperv1.HostedClusterSpec{ Release: hyperv1.Release{ @@ -3835,7 +3835,7 @@ func TestIsProgressing(t *testing.T) { wantErr: false, }, { - name: "cluster is upgrading", + name: "When cluster is upgrading, it should be progressing", hc: &hyperv1.HostedCluster{ Spec: hyperv1.HostedClusterSpec{ Release: hyperv1.Release{ @@ -3858,7 +3858,7 @@ func TestIsProgressing(t *testing.T) { wantErr: false, }, { - name: "cluster update is blocked by condition", + name: "When cluster update is blocked by condition, it should not be progressing", hc: &hyperv1.HostedCluster{ Spec: hyperv1.HostedClusterSpec{ Release: hyperv1.Release{ @@ -3887,7 +3887,7 @@ func TestIsProgressing(t *testing.T) { wantErr: true, }, { - name: "cluster upgrade is blocked by ClusterVersionUpgradeable", + name: "When cluster upgrade is blocked by ClusterVersionUpgradeable, it should not be progressing", hc: &hyperv1.HostedCluster{ Spec: hyperv1.HostedClusterSpec{ Release: hyperv1.Release{ @@ -3916,7 +3916,7 @@ func TestIsProgressing(t *testing.T) { wantErr: true, }, { - name: "cluster upgrade is forced", + name: "When cluster upgrade is forced, it should be progressing", hc: &hyperv1.HostedCluster{ ObjectMeta: metav1.ObjectMeta{ Annotations: map[string]string{ @@ -4004,22 +4004,22 @@ func TestInvertConditionStatus(t *testing.T) { expectedStatus metav1.ConditionStatus }{ { - name: "When status is True it should invert to False", + name: "When status is True, it should invert to False", input: metav1.ConditionTrue, expectedStatus: metav1.ConditionFalse, }, { - name: "When status is False it should invert to True", + name: "When status is False, it should invert to True", input: metav1.ConditionFalse, expectedStatus: metav1.ConditionTrue, }, { - name: "When status is Unknown it should produce Unknown", + name: "When status is Unknown, it should produce Unknown", input: metav1.ConditionUnknown, expectedStatus: metav1.ConditionUnknown, }, { - name: "When status is empty string it should produce Unknown", + name: "When status is empty string, it should produce Unknown", input: metav1.ConditionStatus(""), expectedStatus: metav1.ConditionUnknown, }, @@ -4210,7 +4210,7 @@ func TestComputeAWSEndpointServiceCondition(t *testing.T) { expected metav1.Condition }{ { - name: "Both endpoints condition is true", + name: "When both endpoints condition is true, it should report true", endpointAConditions: []metav1.Condition{ { Type: string(hyperv1.AWSEndpointAvailable), @@ -4235,7 +4235,7 @@ func TestComputeAWSEndpointServiceCondition(t *testing.T) { }, }, { - name: "endpointA condition true, endpointB condition false", + name: "When endpointA is true and endpointB is false, it should report false", endpointAConditions: []metav1.Condition{ { Type: string(hyperv1.AWSEndpointAvailable), @@ -4260,7 +4260,7 @@ func TestComputeAWSEndpointServiceCondition(t *testing.T) { }, }, { - name: "endpointA condition false, endpointB condition true", + name: "When endpointA is false and endpointB is true, it should report false", endpointAConditions: []metav1.Condition{ { Type: string(hyperv1.AWSEndpointAvailable), @@ -4285,7 +4285,7 @@ func TestComputeAWSEndpointServiceCondition(t *testing.T) { }, }, { - name: "Both endpoints condition is false", + name: "When both endpoints condition is false, it should report false", endpointAConditions: []metav1.Condition{ { Type: string(hyperv1.AWSEndpointAvailable), @@ -4354,7 +4354,7 @@ func TestValidateSliceNetworkCIDRs(t *testing.T) { wantErr bool }{ { - name: "given a conflicting IPv6 clusterNetwork overlapped with machineNetwork, it should fail", + name: "When a conflicting IPv6 clusterNetwork overlaps with machineNetwork, it should fail", mn: []hyperv1.MachineNetworkEntry{{CIDR: *ipnet.MustParseCIDR("fd02::/48")}}, cn: []hyperv1.ClusterNetworkEntry{{CIDR: *ipnet.MustParseCIDR("fd02::/64")}}, sn: []hyperv1.ServiceNetworkEntry{{CIDR: *ipnet.MustParseCIDR("2620:52:0:1306::1/64")}}, @@ -4363,7 +4363,7 @@ func TestValidateSliceNetworkCIDRs(t *testing.T) { wantErr: true, }, { - name: "given different IPv6 network CIDRs, it should success", + name: "When different IPv6 network CIDRs are provided, it should succeed", mn: []hyperv1.MachineNetworkEntry{{CIDR: *ipnet.MustParseCIDR("fd02::/48")}}, cn: []hyperv1.ClusterNetworkEntry{{CIDR: *ipnet.MustParseCIDR("fd01::/64")}}, sn: []hyperv1.ServiceNetworkEntry{{CIDR: *ipnet.MustParseCIDR("2620:52:0:1306::1/64")}}, @@ -4372,7 +4372,7 @@ func TestValidateSliceNetworkCIDRs(t *testing.T) { wantErr: false, }, { - name: "given a conflicting IPv4 clusterNetwork overlapped with serviceNetwork, it should fail", + name: "When a conflicting IPv4 clusterNetwork overlaps with serviceNetwork, it should fail", mn: []hyperv1.MachineNetworkEntry{{CIDR: *ipnet.MustParseCIDR("192.168.1.0/24")}}, cn: []hyperv1.ClusterNetworkEntry{{CIDR: *ipnet.MustParseCIDR("172.16.0.0/16")}}, sn: []hyperv1.ServiceNetworkEntry{{CIDR: *ipnet.MustParseCIDR("172.16.0.0/24")}}, @@ -4381,7 +4381,7 @@ func TestValidateSliceNetworkCIDRs(t *testing.T) { wantErr: true, }, { - name: "given different IPv4 network CIDRs, it should success", + name: "When different IPv4 network CIDRs are provided, it should succeed", mn: []hyperv1.MachineNetworkEntry{{CIDR: *ipnet.MustParseCIDR("192.168.1.0/24")}}, cn: []hyperv1.ClusterNetworkEntry{{CIDR: *ipnet.MustParseCIDR("172.16.1.0/24")}}, sn: []hyperv1.ServiceNetworkEntry{{CIDR: *ipnet.MustParseCIDR("172.16.0.0/24")}}, @@ -4484,7 +4484,7 @@ func TestValidateSliceNetworkCIDRs(t *testing.T) { wantErr: false, }, { - name: "When network type is not OVN-Kubernetes, OVN config should be ignored", + name: "When network type is not OVN-Kubernetes, it should ignore OVN config", mn: []hyperv1.MachineNetworkEntry{{CIDR: *ipnet.MustParseCIDR("192.168.1.0/24")}}, cn: []hyperv1.ClusterNetworkEntry{{CIDR: *ipnet.MustParseCIDR("10.128.0.0/14")}}, sn: []hyperv1.ServiceNetworkEntry{{CIDR: *ipnet.MustParseCIDR("172.30.0.0/16")}}, @@ -4497,7 +4497,7 @@ func TestValidateSliceNetworkCIDRs(t *testing.T) { wantErr: false, }, { - name: "When OVN-Kubernetes with valid IPv6 InternalJoinSubnet it should succeed", + name: "When OVN-Kubernetes with valid IPv6 InternalJoinSubnet, it should succeed", mn: []hyperv1.MachineNetworkEntry{{CIDR: *ipnet.MustParseCIDR("fd02::/48")}}, cn: []hyperv1.ClusterNetworkEntry{{CIDR: *ipnet.MustParseCIDR("fd01::/64")}}, sn: []hyperv1.ServiceNetworkEntry{{CIDR: *ipnet.MustParseCIDR("fd03::/112")}}, @@ -4510,7 +4510,7 @@ func TestValidateSliceNetworkCIDRs(t *testing.T) { wantErr: false, }, { - name: "When OVN-Kubernetes with valid IPv6 InternalTransitSwitchSubnet it should succeed", + name: "When OVN-Kubernetes with valid IPv6 InternalTransitSwitchSubnet, it should succeed", mn: []hyperv1.MachineNetworkEntry{{CIDR: *ipnet.MustParseCIDR("fd02::/48")}}, cn: []hyperv1.ClusterNetworkEntry{{CIDR: *ipnet.MustParseCIDR("fd01::/64")}}, sn: []hyperv1.ServiceNetworkEntry{{CIDR: *ipnet.MustParseCIDR("fd03::/112")}}, @@ -4523,7 +4523,7 @@ func TestValidateSliceNetworkCIDRs(t *testing.T) { wantErr: false, }, { - name: "When OVN-Kubernetes IPv6 InternalJoinSubnet overlaps with MachineNetwork it should fail", + name: "When OVN-Kubernetes IPv6 InternalJoinSubnet overlaps with MachineNetwork, it should fail", mn: []hyperv1.MachineNetworkEntry{{CIDR: *ipnet.MustParseCIDR("fd99::/48")}}, cn: []hyperv1.ClusterNetworkEntry{{CIDR: *ipnet.MustParseCIDR("fd01::/64")}}, sn: []hyperv1.ServiceNetworkEntry{{CIDR: *ipnet.MustParseCIDR("fd03::/112")}}, @@ -4536,7 +4536,7 @@ func TestValidateSliceNetworkCIDRs(t *testing.T) { wantErr: true, }, { - name: "When OVN-Kubernetes IPv6 subnets overlap with each other it should fail", + name: "When OVN-Kubernetes IPv6 subnets overlap with each other, it should fail", mn: []hyperv1.MachineNetworkEntry{{CIDR: *ipnet.MustParseCIDR("fd02::/48")}}, cn: []hyperv1.ClusterNetworkEntry{{CIDR: *ipnet.MustParseCIDR("fd01::/64")}}, sn: []hyperv1.ServiceNetworkEntry{{CIDR: *ipnet.MustParseCIDR("fd03::/112")}}, @@ -4550,7 +4550,7 @@ func TestValidateSliceNetworkCIDRs(t *testing.T) { wantErr: true, }, { - name: "When OVN-Kubernetes with both valid IPv4 and IPv6 subnets it should succeed", + name: "When OVN-Kubernetes with both valid IPv4 and IPv6 subnets, it should succeed", mn: []hyperv1.MachineNetworkEntry{{CIDR: *ipnet.MustParseCIDR("192.168.1.0/24")}}, cn: []hyperv1.ClusterNetworkEntry{{CIDR: *ipnet.MustParseCIDR("10.128.0.0/14")}}, sn: []hyperv1.ServiceNetworkEntry{{CIDR: *ipnet.MustParseCIDR("172.30.0.0/16")}}, @@ -4566,7 +4566,7 @@ func TestValidateSliceNetworkCIDRs(t *testing.T) { wantErr: false, }, { - name: "When OVN-Kubernetes with empty IPv6 subnet strings it should succeed", + name: "When OVN-Kubernetes with empty IPv6 subnet strings, it should succeed", mn: []hyperv1.MachineNetworkEntry{{CIDR: *ipnet.MustParseCIDR("192.168.1.0/24")}}, cn: []hyperv1.ClusterNetworkEntry{{CIDR: *ipnet.MustParseCIDR("10.128.0.0/14")}}, sn: []hyperv1.ServiceNetworkEntry{{CIDR: *ipnet.MustParseCIDR("172.30.0.0/16")}}, @@ -4580,7 +4580,7 @@ func TestValidateSliceNetworkCIDRs(t *testing.T) { wantErr: false, }, { - name: "When KubeVirt OVN-Kubernetes with no IPv6 config and MachineNetwork overlaps default fd99::/64 it should fail", + name: "When KubeVirt OVN-Kubernetes with no IPv6 config and MachineNetwork overlaps default fd99::/64, it should fail", mn: []hyperv1.MachineNetworkEntry{{CIDR: *ipnet.MustParseCIDR("fd99::/48")}}, cn: []hyperv1.ClusterNetworkEntry{{CIDR: *ipnet.MustParseCIDR("fd01::/64")}}, sn: []hyperv1.ServiceNetworkEntry{{CIDR: *ipnet.MustParseCIDR("fd02::/112")}}, @@ -4590,7 +4590,7 @@ func TestValidateSliceNetworkCIDRs(t *testing.T) { wantErr: true, }, { - name: "When KubeVirt OVN-Kubernetes with no IPv6 config and non-overlapping networks it should succeed", + name: "When KubeVirt OVN-Kubernetes with no IPv6 config and non-overlapping networks, it should succeed", mn: []hyperv1.MachineNetworkEntry{{CIDR: *ipnet.MustParseCIDR("fd01::/48")}}, cn: []hyperv1.ClusterNetworkEntry{{CIDR: *ipnet.MustParseCIDR("fd02::/64")}}, sn: []hyperv1.ServiceNetworkEntry{{CIDR: *ipnet.MustParseCIDR("fd03::/112")}}, @@ -4600,7 +4600,7 @@ func TestValidateSliceNetworkCIDRs(t *testing.T) { wantErr: false, }, { - name: "When KubeVirt OVN-Kubernetes with explicit IPv6 join subnet it should use explicit value not default", + name: "When KubeVirt OVN-Kubernetes with explicit IPv6 join subnet, it should use explicit value not default", mn: []hyperv1.MachineNetworkEntry{{CIDR: *ipnet.MustParseCIDR("fd99::/48")}}, cn: []hyperv1.ClusterNetworkEntry{{CIDR: *ipnet.MustParseCIDR("fd01::/64")}}, sn: []hyperv1.ServiceNetworkEntry{{CIDR: *ipnet.MustParseCIDR("fd02::/112")}}, @@ -4614,7 +4614,7 @@ func TestValidateSliceNetworkCIDRs(t *testing.T) { wantErr: false, }, { - name: "When KubeVirt OVN-Kubernetes with no IPv4 config and MachineNetwork overlaps default 100.66.0.0/16 it should fail", + name: "When KubeVirt OVN-Kubernetes with no IPv4 config and MachineNetwork overlaps default 100.66.0.0/16, it should fail", mn: []hyperv1.MachineNetworkEntry{{CIDR: *ipnet.MustParseCIDR("100.66.0.0/24")}}, cn: []hyperv1.ClusterNetworkEntry{{CIDR: *ipnet.MustParseCIDR("10.128.0.0/14")}}, sn: []hyperv1.ServiceNetworkEntry{{CIDR: *ipnet.MustParseCIDR("172.30.0.0/16")}}, @@ -4624,7 +4624,7 @@ func TestValidateSliceNetworkCIDRs(t *testing.T) { wantErr: true, }, { - name: "When KubeVirt OVN-Kubernetes with no IPv4 config and non-overlapping networks it should succeed", + name: "When KubeVirt OVN-Kubernetes with no IPv4 config and non-overlapping networks, it should succeed", mn: []hyperv1.MachineNetworkEntry{{CIDR: *ipnet.MustParseCIDR("192.168.1.0/24")}}, cn: []hyperv1.ClusterNetworkEntry{{CIDR: *ipnet.MustParseCIDR("10.128.0.0/14")}}, sn: []hyperv1.ServiceNetworkEntry{{CIDR: *ipnet.MustParseCIDR("172.30.0.0/16")}}, @@ -4777,7 +4777,7 @@ func TestCheckAdvertiseAddressOverlapping(t *testing.T) { wantErr bool }{ { - name: "given an IPv6 defined AdvertiseAddress overlapped with ClusterNetwork, it should fail", + name: "When an IPv6 defined AdvertiseAddress overlaps with ClusterNetwork, it should fail", aa: &hyperv1.APIServerNetworking{AdvertiseAddress: ptr.To("fd03::1")}, mn: []hyperv1.MachineNetworkEntry{{CIDR: *ipnet.MustParseCIDR("fd02::/48")}}, cn: []hyperv1.ClusterNetworkEntry{{CIDR: *ipnet.MustParseCIDR("fd03::/64")}}, @@ -4785,14 +4785,14 @@ func TestCheckAdvertiseAddressOverlapping(t *testing.T) { wantErr: true, }, { - name: "given not overlapped IPv6 networks CIDRs and not defined AdvertiseAddress, it should success", + name: "When IPv6 networks CIDRs do not overlap and AdvertiseAddress is not defined, it should succeed", mn: []hyperv1.MachineNetworkEntry{{CIDR: *ipnet.MustParseCIDR("fd02::/48")}}, cn: []hyperv1.ClusterNetworkEntry{{CIDR: *ipnet.MustParseCIDR("fd01::/64")}}, sn: []hyperv1.ServiceNetworkEntry{{CIDR: *ipnet.MustParseCIDR("2620:52:0:1306::1/64")}}, wantErr: false, }, { - name: "given an IPv4 defined AdvertiseAddress overlapped with MachineNetwork, it should fail", + name: "When an IPv4 defined AdvertiseAddress overlaps with MachineNetwork, it should fail", aa: &hyperv1.APIServerNetworking{AdvertiseAddress: ptr.To("192.168.1.1")}, mn: []hyperv1.MachineNetworkEntry{{CIDR: *ipnet.MustParseCIDR("192.168.1.0/24")}}, cn: []hyperv1.ClusterNetworkEntry{{CIDR: *ipnet.MustParseCIDR("172.16.0.0/16")}}, @@ -4800,14 +4800,14 @@ func TestCheckAdvertiseAddressOverlapping(t *testing.T) { wantErr: true, }, { - name: "given not overlapped IPv4 networks CIDRs and not defined AdvertiseAddress, it should success", + name: "When IPv4 networks CIDRs do not overlap and AdvertiseAddress is not defined, it should succeed", mn: []hyperv1.MachineNetworkEntry{{CIDR: *ipnet.MustParseCIDR("192.168.1.0/24")}}, cn: []hyperv1.ClusterNetworkEntry{{CIDR: *ipnet.MustParseCIDR("172.16.1.0/24")}}, sn: []hyperv1.ServiceNetworkEntry{{CIDR: *ipnet.MustParseCIDR("172.16.0.0/24")}}, wantErr: false, }, { - name: "given a not valid AdvertiseAddress, it should fail", + name: "When AdvertiseAddress is not valid, it should fail", aa: &hyperv1.APIServerNetworking{AdvertiseAddress: ptr.To("192.168.2.1.2")}, mn: []hyperv1.MachineNetworkEntry{{CIDR: *ipnet.MustParseCIDR("192.168.1.0/24")}}, cn: []hyperv1.ClusterNetworkEntry{{CIDR: *ipnet.MustParseCIDR("172.16.1.0/24")}}, @@ -4849,35 +4849,35 @@ func TestFindAdvertiseAddress(t *testing.T) { wantErr bool }{ { - name: "given a defined AdvertiseAddress, should be the result and IPv4", + name: "When AdvertiseAddress is defined it should return that address as IPv4", aa: &hyperv1.APIServerNetworking{AdvertiseAddress: ptr.To("192.168.1.1")}, cn: []hyperv1.ClusterNetworkEntry{{CIDR: *ipnet.MustParseCIDR("172.16.1.0/24")}}, resultAdvAddress: "192.168.1.1", }, { - name: "given a hc without AdvertiseAddress, it should return the default IPv4 address", + name: "When HC has no AdvertiseAddress it should return the default IPv4 address", cn: []hyperv1.ClusterNetworkEntry{{CIDR: *ipnet.MustParseCIDR("172.16.1.0/24")}}, resultAdvAddress: config.DefaultAdvertiseIPv4Address, }, { - name: "given an IPv6 hc with defined AdvertiseAddress, it should return that address", + name: "When IPv6 HC has defined AdvertiseAddress it should return that address", aa: &hyperv1.APIServerNetworking{AdvertiseAddress: ptr.To("fd03::1")}, cn: []hyperv1.ClusterNetworkEntry{{CIDR: *ipnet.MustParseCIDR("fd01::/64")}}, resultAdvAddress: "fd03::1", }, { - name: "given an IPv6 hc without AdvertiseAddress, it return IPv6 default address", + name: "When IPv6 HC has no AdvertiseAddress it should return IPv6 default address", cn: []hyperv1.ClusterNetworkEntry{{CIDR: *ipnet.MustParseCIDR("fd01::/64")}}, resultAdvAddress: config.DefaultAdvertiseIPv6Address, }, { - name: "given an invalid IPv4 AdvertiseAddress, it should fail", + name: "When an invalid IPv4 AdvertiseAddress is provided, it should fail", aa: &hyperv1.APIServerNetworking{AdvertiseAddress: ptr.To("192.168.1.1222")}, cn: []hyperv1.ClusterNetworkEntry{{CIDR: *ipnet.MustParseCIDR("172.16.1.0/24")}}, wantErr: true, }, { - name: "given an invalid IPv6 AdvertiseAddress, it should fail", + name: "When an invalid IPv6 AdvertiseAddress is provided, it should fail", aa: &hyperv1.APIServerNetworking{AdvertiseAddress: ptr.To("fd03::4444444")}, cn: []hyperv1.ClusterNetworkEntry{{CIDR: *ipnet.MustParseCIDR("fd01::/64")}}, wantErr: true, @@ -4920,7 +4920,7 @@ func TestValidateNetworkStackAddresses(t *testing.T) { wantErr bool }{ { - name: "given an IPv6 clusterNetwork and an IPv4 ServiceNetwork, it should fail", + name: "When IPv6 clusterNetwork and IPv4 ServiceNetwork are mixed, it should fail", aa: &hyperv1.APIServerNetworking{AdvertiseAddress: ptr.To("fd03::1")}, mn: []hyperv1.MachineNetworkEntry{{CIDR: *ipnet.MustParseCIDR("fd02::/48")}}, cn: []hyperv1.ClusterNetworkEntry{{CIDR: *ipnet.MustParseCIDR("fd03::/64")}}, @@ -4928,7 +4928,7 @@ func TestValidateNetworkStackAddresses(t *testing.T) { wantErr: true, }, { - name: "on IPv6 and IPv4 Advertise Address, it should fail", + name: "When IPv6 network has IPv4 Advertise Address, it should fail", aa: &hyperv1.APIServerNetworking{AdvertiseAddress: ptr.To("192.168.1.1")}, mn: []hyperv1.MachineNetworkEntry{{CIDR: *ipnet.MustParseCIDR("fd02::/48")}}, cn: []hyperv1.ClusterNetworkEntry{{CIDR: *ipnet.MustParseCIDR("fd01::/64")}}, @@ -4936,7 +4936,7 @@ func TestValidateNetworkStackAddresses(t *testing.T) { wantErr: true, }, { - name: "on IPv6 and defining Advertise Address, it should success", + name: "When IPv6 network has matching IPv6 Advertise Address, it should succeed", aa: &hyperv1.APIServerNetworking{AdvertiseAddress: ptr.To("fd03::1")}, mn: []hyperv1.MachineNetworkEntry{{CIDR: *ipnet.MustParseCIDR("fd02::/48")}}, cn: []hyperv1.ClusterNetworkEntry{{CIDR: *ipnet.MustParseCIDR("fd01::/64")}}, @@ -4944,7 +4944,7 @@ func TestValidateNetworkStackAddresses(t *testing.T) { wantErr: false, }, { - name: "given an IPv4 clusterNetwork and an IPv6 ServiceNetwork, it should fail", + name: "When IPv4 clusterNetwork and IPv6 ServiceNetwork are mixed, it should fail", aa: &hyperv1.APIServerNetworking{AdvertiseAddress: ptr.To("192.168.1.1")}, mn: []hyperv1.MachineNetworkEntry{{CIDR: *ipnet.MustParseCIDR("192.168.1.0/24")}}, cn: []hyperv1.ClusterNetworkEntry{{CIDR: *ipnet.MustParseCIDR("172.16.0.0/16")}}, @@ -4952,7 +4952,7 @@ func TestValidateNetworkStackAddresses(t *testing.T) { wantErr: true, }, { - name: "on IPv4 and defining IPv6 Advertise Address, it should fail", + name: "When IPv4 network has IPv6 Advertise Address, it should fail", aa: &hyperv1.APIServerNetworking{AdvertiseAddress: ptr.To("fd03::1")}, mn: []hyperv1.MachineNetworkEntry{{CIDR: *ipnet.MustParseCIDR("192.168.1.0/24")}}, cn: []hyperv1.ClusterNetworkEntry{{CIDR: *ipnet.MustParseCIDR("172.16.1.0/24")}}, @@ -4960,7 +4960,7 @@ func TestValidateNetworkStackAddresses(t *testing.T) { wantErr: true, }, { - name: "on IPv4 and defining Advertise Address, it should success", + name: "When IPv4 network has matching IPv4 Advertise Address, it should succeed", aa: &hyperv1.APIServerNetworking{AdvertiseAddress: ptr.To("192.168.1.1")}, mn: []hyperv1.MachineNetworkEntry{{CIDR: *ipnet.MustParseCIDR("192.168.0.0/24")}}, cn: []hyperv1.ClusterNetworkEntry{{CIDR: *ipnet.MustParseCIDR("172.16.1.0/24")}}, @@ -4968,21 +4968,21 @@ func TestValidateNetworkStackAddresses(t *testing.T) { wantErr: false, }, { - name: "on IPv4, it should success", + name: "When using IPv4 networks, it should succeed", mn: []hyperv1.MachineNetworkEntry{{CIDR: *ipnet.MustParseCIDR("192.168.1.0/24")}}, cn: []hyperv1.ClusterNetworkEntry{{CIDR: *ipnet.MustParseCIDR("172.16.1.0/24")}}, sn: []hyperv1.ServiceNetworkEntry{{CIDR: *ipnet.MustParseCIDR("172.16.0.0/24")}}, wantErr: false, }, { - name: "on IPv6, it should success", + name: "When using IPv6 networks, it should succeed", mn: []hyperv1.MachineNetworkEntry{{CIDR: *ipnet.MustParseCIDR("fd02::/48")}}, cn: []hyperv1.ClusterNetworkEntry{{CIDR: *ipnet.MustParseCIDR("fd01::/64")}}, sn: []hyperv1.ServiceNetworkEntry{{CIDR: *ipnet.MustParseCIDR("2620:52:0:1306::1/64")}}, wantErr: false, }, { - name: "given an IPv4 invalid advertise address, it should fail", + name: "When IPv4 advertise address is invalid, it should fail", aa: &hyperv1.APIServerNetworking{AdvertiseAddress: ptr.To("192.168.1.1.2")}, mn: []hyperv1.MachineNetworkEntry{{CIDR: *ipnet.MustParseCIDR("192.168.1.0/24")}}, cn: []hyperv1.ClusterNetworkEntry{{CIDR: *ipnet.MustParseCIDR("172.16.0.0/24")}}, @@ -4990,7 +4990,7 @@ func TestValidateNetworkStackAddresses(t *testing.T) { wantErr: true, }, { - name: "given an IPv6 invalid advertise address, it should fail", + name: "When IPv6 advertise address is invalid, it should fail", aa: &hyperv1.APIServerNetworking{AdvertiseAddress: ptr.To("fd03::1::32")}, mn: []hyperv1.MachineNetworkEntry{{CIDR: *ipnet.MustParseCIDR("fd02::/48")}}, cn: []hyperv1.ClusterNetworkEntry{{CIDR: *ipnet.MustParseCIDR("fd03::/64")}}, @@ -5032,7 +5032,7 @@ func TestKubevirtETCDEncKey(t *testing.T) { objects []crclient.Object }{ { - name: "secret encryption already defined", + name: "When secret encryption is already defined it should preserve existing key", hc: &hyperv1.HostedCluster{ ObjectMeta: metav1.ObjectMeta{ Name: "kubevirt", @@ -5094,7 +5094,7 @@ func TestKubevirtETCDEncKey(t *testing.T) { }, }, { - name: "secret encryption not defined", + name: "When secret encryption is not defined it should generate a new key", hc: &hyperv1.HostedCluster{ ObjectMeta: metav1.ObjectMeta{ Name: "kubevirt", @@ -5136,7 +5136,7 @@ func TestKubevirtETCDEncKey(t *testing.T) { secretExpected: true, }, { - name: "secret encryption with no type", + name: "When secret encryption has no type it should default correctly", hc: &hyperv1.HostedCluster{ ObjectMeta: metav1.ObjectMeta{ Name: "kubevirt", @@ -5179,7 +5179,7 @@ func TestKubevirtETCDEncKey(t *testing.T) { secretExpected: true, }, { - name: "secret encryption with no details", + name: "When secret encryption has no details it should handle gracefully", hc: &hyperv1.HostedCluster{ ObjectMeta: metav1.ObjectMeta{ Name: "kubevirt", @@ -5224,7 +5224,7 @@ func TestKubevirtETCDEncKey(t *testing.T) { secretExpected: true, }, { - name: "secret encryption with no name", + name: "When secret encryption has no name it should generate default name", hc: &hyperv1.HostedCluster{ ObjectMeta: metav1.ObjectMeta{ Name: "kubevirt", @@ -5270,7 +5270,7 @@ func TestKubevirtETCDEncKey(t *testing.T) { secretExpected: true, }, { - name: "secret encryption with custom name", + name: "When secret encryption has custom name it should use that name", hc: &hyperv1.HostedCluster{ ObjectMeta: metav1.ObjectMeta{ Name: "kubevirt", @@ -5332,7 +5332,7 @@ func TestKubevirtETCDEncKey(t *testing.T) { }, }, { - name: "secret encryption not defined and secret exists with no key", + name: "When secret encryption is not defined and secret exists with no key it should generate a new key", hc: &hyperv1.HostedCluster{ ObjectMeta: metav1.ObjectMeta{ Name: "kubevirt", @@ -5619,28 +5619,28 @@ func TestEnsureHostedResourcesAreEmpty(t *testing.T) { errorMessage string }{ { - name: "non-ARO-HCP environment should pass", + name: "When environment is non-ARO-HCP, it should pass", setAROHCP: false, annotations: map[string]string{hyperv1.HostedClusterSourcedAnnotation: "true"}, secretContent: map[string][]byte{"key": []byte("value")}, expectError: false, }, { - name: "ARO-HCP without annotation should pass", + name: "When ARO-HCP has no annotation, it should pass", setAROHCP: true, annotations: nil, secretContent: map[string][]byte{"key": []byte("value")}, expectError: false, }, { - name: "ARO-HCP with annotation but empty secret should pass", + name: "When ARO-HCP has annotation but empty secret, it should pass", setAROHCP: true, annotations: map[string]string{hyperv1.HostedClusterSourcedAnnotation: "true"}, secretContent: map[string][]byte{}, expectError: false, }, { - name: "ARO-HCP with annotation and non-empty secret should fail", + name: "When ARO-HCP has annotation and non-empty secret, it should fail", setAROHCP: true, annotations: map[string]string{hyperv1.HostedClusterSourcedAnnotation: "true"}, secretContent: map[string][]byte{"key": []byte("value")}, @@ -5745,7 +5745,7 @@ func TestReconcileAdditionalTrustBundle(t *testing.T) { expectedErrorSubstring string }{ { - name: "creates configmap when AdditionalTrustBundle is specified", + name: "When AdditionalTrustBundle is specified, it should create configmap", hostedCluster: &hyperv1.HostedCluster{ ObjectMeta: metav1.ObjectMeta{ Name: hostedClusterName, @@ -5772,7 +5772,7 @@ func TestReconcileAdditionalTrustBundle(t *testing.T) { expectConfigMapCreated: true, }, { - name: "deletes configmap when AdditionalTrustBundle is nil", + name: "When AdditionalTrustBundle is nil, it should delete configmap", hostedCluster: &hyperv1.HostedCluster{ ObjectMeta: metav1.ObjectMeta{ Name: hostedClusterName, @@ -5797,7 +5797,7 @@ func TestReconcileAdditionalTrustBundle(t *testing.T) { expectConfigMapDeleted: true, }, { - name: "returns error when source configmap does not exist", + name: "When source configmap does not exist, it should return error", hostedCluster: &hyperv1.HostedCluster{ ObjectMeta: metav1.ObjectMeta{ Name: hostedClusterName, @@ -5814,7 +5814,7 @@ func TestReconcileAdditionalTrustBundle(t *testing.T) { expectedErrorSubstring: "failed to get hostedcluster AdditionalTrustBundle ConfigMap", }, { - name: "returns error when source configmap missing ca-bundle.crt key", + name: "When source configmap is missing ca-bundle.crt key, it should return error", hostedCluster: &hyperv1.HostedCluster{ ObjectMeta: metav1.ObjectMeta{ Name: hostedClusterName, @@ -5906,7 +5906,7 @@ func TestValidateNodePortVsServiceNetwork(t *testing.T) { expectedErrorList field.ErrorList }{ { - name: "no nodeport, error", + name: "When no nodeport is configured it should return error", hostedCluster: &hyperv1.HostedCluster{ Spec: hyperv1.HostedClusterSpec{ Services: []hyperv1.ServicePublishingStrategyMapping{ @@ -5922,7 +5922,7 @@ func TestValidateNodePortVsServiceNetwork(t *testing.T) { expectedErrorList: field.ErrorList{field.Required(field.NewPath("spec.Services[0].NodePort"), "Nodeport can not be empty")}, }, { - name: "nodeport set, success", + name: "When nodeport is set it should succeed", hostedCluster: &hyperv1.HostedCluster{ Spec: hyperv1.HostedClusterSpec{ Services: []hyperv1.ServicePublishingStrategyMapping{ @@ -5961,72 +5961,72 @@ func TestParseNodePortRange(t *testing.T) { expectError bool }{ { - name: "empty range uses default", + name: "When range is empty, it should use default", rangeStr: "", expectedMin: 30000, expectedMax: 32767, expectError: false, }, { - name: "valid default range", + name: "When valid default range is provided, it should parse correctly", rangeStr: "30000-32767", expectedMin: 30000, expectedMax: 32767, expectError: false, }, { - name: "valid custom range", + name: "When valid custom range is provided, it should parse correctly", rangeStr: "25000-35000", expectedMin: 25000, expectedMax: 35000, expectError: false, }, { - name: "valid small range", + name: "When valid small range is provided, it should parse correctly", rangeStr: "31000-31010", expectedMin: 31000, expectedMax: 31010, expectError: false, }, { - name: "invalid format - no dash", + name: "When format has no dash, it should return error", rangeStr: "30000", expectError: true, }, { - name: "invalid format - multiple dashes", + name: "When format has multiple dashes, it should return error", rangeStr: "30000-31000-32000", expectError: true, }, { - name: "invalid minimum port", + name: "When minimum port is invalid, it should return error", rangeStr: "abc-32767", expectError: true, }, { - name: "invalid maximum port", + name: "When maximum port is invalid, it should return error", rangeStr: "30000-xyz", expectError: true, }, { - name: "negative port", + name: "When port is negative, it should return error", rangeStr: "-1-32767", expectError: true, }, { - name: "port too large", + name: "When port is too large, it should return error", rangeStr: "30000-99999", expectedMin: 30000, expectedMax: 99999, expectError: false, // parseNodePortRange doesn't validate port limits }, { - name: "min greater than max - invalid range", + name: "When min is greater than max, it should return error", rangeStr: "32767-30000", expectError: true, }, { - name: "min equals max - valid single port range", + name: "When min equals max, it should parse as valid single port range", rangeStr: "31000-31000", expectedMin: 31000, expectedMax: 31000, @@ -6064,7 +6064,7 @@ func TestValidateNodePortPortRange(t *testing.T) { expectedErrorList field.ErrorList }{ { - name: "valid port in default range", + name: "When port is valid in default range it should succeed", hostedCluster: &hyperv1.HostedCluster{ Spec: hyperv1.HostedClusterSpec{ Services: []hyperv1.ServicePublishingStrategyMapping{ @@ -6083,7 +6083,7 @@ func TestValidateNodePortPortRange(t *testing.T) { }, }, { - name: "port 0 for dynamic assignment - always valid", + name: "When port is 0 for dynamic assignment it should always be valid", hostedCluster: &hyperv1.HostedCluster{ Spec: hyperv1.HostedClusterSpec{ Services: []hyperv1.ServicePublishingStrategyMapping{ @@ -6102,7 +6102,7 @@ func TestValidateNodePortPortRange(t *testing.T) { }, }, { - name: "port below default range", + name: "When port is below default range it should return error", hostedCluster: &hyperv1.HostedCluster{ Spec: hyperv1.HostedClusterSpec{ Services: []hyperv1.ServicePublishingStrategyMapping{ @@ -6124,7 +6124,7 @@ func TestValidateNodePortPortRange(t *testing.T) { }, }, { - name: "port above default range", + name: "When port is above default range it should return error", hostedCluster: &hyperv1.HostedCluster{ Spec: hyperv1.HostedClusterSpec{ Services: []hyperv1.ServicePublishingStrategyMapping{ @@ -6146,7 +6146,7 @@ func TestValidateNodePortPortRange(t *testing.T) { }, }, { - name: "valid port in custom range", + name: "When port is valid in custom range it should succeed", hostedCluster: &hyperv1.HostedCluster{ Spec: hyperv1.HostedClusterSpec{ Configuration: &hyperv1.ClusterConfiguration{ @@ -6170,7 +6170,7 @@ func TestValidateNodePortPortRange(t *testing.T) { }, }, { - name: "port outside custom range", + name: "When port is outside custom range it should return error", hostedCluster: &hyperv1.HostedCluster{ Spec: hyperv1.HostedClusterSpec{ Configuration: &hyperv1.ClusterConfiguration{ @@ -6197,7 +6197,7 @@ func TestValidateNodePortPortRange(t *testing.T) { }, }, { - name: "invalid range format", + name: "When range format is invalid it should return error", hostedCluster: &hyperv1.HostedCluster{ Spec: hyperv1.HostedClusterSpec{ Configuration: &hyperv1.ClusterConfiguration{ @@ -6224,7 +6224,7 @@ func TestValidateNodePortPortRange(t *testing.T) { }, }, { - name: "reversed range - min greater than max", + name: "When range is reversed with min greater than max it should return error", hostedCluster: &hyperv1.HostedCluster{ Spec: hyperv1.HostedClusterSpec{ Configuration: &hyperv1.ClusterConfiguration{ @@ -6251,7 +6251,7 @@ func TestValidateNodePortPortRange(t *testing.T) { }, }, { - name: "no nodeport service - no validation", + name: "When no nodeport service exists it should skip validation", hostedCluster: &hyperv1.HostedCluster{ Spec: hyperv1.HostedClusterSpec{ Services: []hyperv1.ServicePublishingStrategyMapping{ @@ -6714,7 +6714,7 @@ func TestComputeGCPPSCCondition(t *testing.T) { expected metav1.Condition }{ { - name: "When GCPEndpointAvailable is true it should return condition true", + name: "When GCPEndpointAvailable is true, it should return condition true", pscConditions: []metav1.Condition{ { Type: string(hyperv1.GCPEndpointAvailable), @@ -6732,7 +6732,7 @@ func TestComputeGCPPSCCondition(t *testing.T) { }, }, { - name: "When GCPEndpointAvailable is false it should return condition false", + name: "When GCPEndpointAvailable is false, it should return condition false", pscConditions: []metav1.Condition{ { Type: string(hyperv1.GCPEndpointAvailable), @@ -6750,7 +6750,7 @@ func TestComputeGCPPSCCondition(t *testing.T) { }, }, { - name: "When GCPServiceAttachmentAvailable is true it should return condition true", + name: "When GCPServiceAttachmentAvailable is true, it should return condition true", pscConditions: []metav1.Condition{ { Type: string(hyperv1.GCPServiceAttachmentAvailable), @@ -6768,7 +6768,7 @@ func TestComputeGCPPSCCondition(t *testing.T) { }, }, { - name: "When GCPServiceAttachmentAvailable is false it should return condition false", + name: "When GCPServiceAttachmentAvailable is false, it should return condition false", pscConditions: []metav1.Condition{ { Type: string(hyperv1.GCPServiceAttachmentAvailable), @@ -6786,7 +6786,7 @@ func TestComputeGCPPSCCondition(t *testing.T) { }, }, { - name: "When PSC has no conditions it should return condition unknown", + name: "When PSC has no conditions, it should return condition unknown", pscConditions: []metav1.Condition{}, conditionType: hyperv1.GCPEndpointAvailable, expected: metav1.Condition{ @@ -6797,7 +6797,7 @@ func TestComputeGCPPSCCondition(t *testing.T) { }, }, { - name: "When querying GCPEndpointAvailable it should ignore GCPServiceAttachmentAvailable", + name: "When querying GCPEndpointAvailable, it should ignore GCPServiceAttachmentAvailable", pscConditions: []metav1.Condition{ { Type: string(hyperv1.GCPEndpointAvailable), @@ -6821,7 +6821,7 @@ func TestComputeGCPPSCCondition(t *testing.T) { }, }, { - name: "When querying GCPServiceAttachmentAvailable it should ignore GCPEndpointAvailable", + name: "When querying GCPServiceAttachmentAvailable, it should ignore GCPEndpointAvailable", pscConditions: []metav1.Condition{ { Type: string(hyperv1.GCPEndpointAvailable), @@ -6978,7 +6978,7 @@ func TestComputeAzurePLSCondition(t *testing.T) { expected metav1.Condition }{ { - name: "When AzurePrivateLinkServiceAvailable is true it should return condition true", + name: "When AzurePrivateLinkServiceAvailable is true, it should return condition true", plsConditions: []metav1.Condition{ { Type: string(hyperv1.AzurePrivateLinkServiceAvailable), @@ -6996,7 +6996,7 @@ func TestComputeAzurePLSCondition(t *testing.T) { }, }, { - name: "When AzurePLSCreated is false it should return condition false", + name: "When AzurePLSCreated is false, it should return condition false", plsConditions: []metav1.Condition{ { Type: string(hyperv1.AzurePLSCreated), @@ -7014,7 +7014,7 @@ func TestComputeAzurePLSCondition(t *testing.T) { }, }, { - name: "When PLS has no conditions it should return condition unknown", + name: "When PLS has no conditions, it should return condition unknown", plsConditions: []metav1.Condition{}, conditionType: hyperv1.AzurePrivateLinkServiceAvailable, expected: metav1.Condition{ @@ -7025,7 +7025,7 @@ func TestComputeAzurePLSCondition(t *testing.T) { }, }, { - name: "When AzureInternalLoadBalancerAvailable is true it should return condition true", + name: "When AzureInternalLoadBalancerAvailable is true, it should return condition true", plsConditions: []metav1.Condition{ { Type: string(hyperv1.AzureInternalLoadBalancerAvailable), @@ -7043,7 +7043,7 @@ func TestComputeAzurePLSCondition(t *testing.T) { }, }, { - name: "When AzurePrivateEndpointAvailable is true it should return condition true", + name: "When AzurePrivateEndpointAvailable is true, it should return condition true", plsConditions: []metav1.Condition{ { Type: string(hyperv1.AzurePrivateEndpointAvailable), @@ -7061,7 +7061,7 @@ func TestComputeAzurePLSCondition(t *testing.T) { }, }, { - name: "When AzurePrivateDNSAvailable is true it should return condition true", + name: "When AzurePrivateDNSAvailable is true, it should return condition true", plsConditions: []metav1.Condition{ { Type: string(hyperv1.AzurePrivateDNSAvailable), @@ -7111,7 +7111,7 @@ func TestValidateAzureConfig(t *testing.T) { setup func(t *testing.T) }{ { - name: "When platform is not Azure it should return nil", + name: "When platform is not Azure, it should return nil", hc: &hyperv1.HostedCluster{ Spec: hyperv1.HostedClusterSpec{ Platform: hyperv1.PlatformSpec{ @@ -7122,7 +7122,7 @@ func TestValidateAzureConfig(t *testing.T) { expectError: false, }, { - name: "When platform is Azure but Azure spec is nil it should return an error", + name: "When platform is Azure but Azure spec is nil, it should return an error", hc: &hyperv1.HostedCluster{ Spec: hyperv1.HostedClusterSpec{ Platform: hyperv1.PlatformSpec{ @@ -7135,7 +7135,7 @@ func TestValidateAzureConfig(t *testing.T) { errorMsg: "azurecluster needs .spec.platform.azure to be filled", }, { - name: "When topology is Private without Private config it should return an error", + name: "When topology is Private without Private config, it should return an error", hc: &hyperv1.HostedCluster{ Spec: hyperv1.HostedClusterSpec{ Platform: hyperv1.PlatformSpec{ @@ -7150,7 +7150,7 @@ func TestValidateAzureConfig(t *testing.T) { errorMsg: `spec.platform.azure.private.type: Invalid value: "": private.type is required when topology is "Private"`, }, { - name: "When topology is PublicAndPrivate without Private config it should return an error", + name: "When topology is PublicAndPrivate without Private config, it should return an error", hc: &hyperv1.HostedCluster{ Spec: hyperv1.HostedClusterSpec{ Platform: hyperv1.PlatformSpec{ @@ -7165,7 +7165,7 @@ func TestValidateAzureConfig(t *testing.T) { errorMsg: `spec.platform.azure.private.type: Invalid value: "": private.type is required when topology is "PublicAndPrivate"`, }, { - name: "When topology is Public without Private config it should succeed", + name: "When topology is Public without Private config, it should succeed", hc: &hyperv1.HostedCluster{ Spec: hyperv1.HostedClusterSpec{ Platform: hyperv1.PlatformSpec{ @@ -7179,7 +7179,7 @@ func TestValidateAzureConfig(t *testing.T) { expectError: false, }, { - name: "When topology is Private with PrivateLink but no NATSubnetID it should succeed", + name: "When topology is Private with PrivateLink but no NATSubnetID, it should succeed", hc: &hyperv1.HostedCluster{ Spec: hyperv1.HostedClusterSpec{ Platform: hyperv1.PlatformSpec{ @@ -7197,7 +7197,7 @@ func TestValidateAzureConfig(t *testing.T) { expectError: false, }, { - name: "When topology is Private with Private config it should succeed", + name: "When topology is Private with Private config, it should succeed", hc: &hyperv1.HostedCluster{ Spec: hyperv1.HostedClusterSpec{ Platform: hyperv1.PlatformSpec{ @@ -7218,7 +7218,7 @@ func TestValidateAzureConfig(t *testing.T) { expectError: false, }, { - name: "When ARO HCP has Private topology without Private config it should succeed", + name: "When ARO HCP has Private topology without Private config, it should succeed", hc: &hyperv1.HostedCluster{ Spec: hyperv1.HostedClusterSpec{ Platform: hyperv1.PlatformSpec{ @@ -7241,7 +7241,7 @@ func TestValidateAzureConfig(t *testing.T) { }, }, { - name: "When endpointAccess is zero value it should succeed as it defaults to Public", + name: "When endpointAccess is zero value, it should succeed as it defaults to Public", hc: &hyperv1.HostedCluster{ Spec: hyperv1.HostedClusterSpec{ Platform: hyperv1.PlatformSpec{ @@ -7295,7 +7295,7 @@ func TestComputeEndpointServiceCondition(t *testing.T) { expected metav1.Condition }{ { - name: "When no resource conditions exist it should return unknown", + name: "When no resource conditions exist, it should return unknown", resourceConditions: [][]metav1.Condition{}, conditionType: testConditionType, expected: metav1.Condition{ @@ -7306,7 +7306,7 @@ func TestComputeEndpointServiceCondition(t *testing.T) { }, }, { - name: "When no matching condition type exists it should return unknown", + name: "When no matching condition type exists, it should return unknown", resourceConditions: [][]metav1.Condition{ { { @@ -7324,7 +7324,7 @@ func TestComputeEndpointServiceCondition(t *testing.T) { }, }, { - name: "When all conditions are true it should return true with success reason", + name: "When all conditions are true, it should return true with success reason", resourceConditions: [][]metav1.Condition{ { { @@ -7352,7 +7352,7 @@ func TestComputeEndpointServiceCondition(t *testing.T) { }, }, { - name: "When any condition is false it should return false with aggregated messages", + name: "When any condition is false, it should return false with aggregated messages", resourceConditions: [][]metav1.Condition{ { { @@ -7388,7 +7388,7 @@ func TestComputeEndpointServiceCondition(t *testing.T) { }, }, { - name: "When a single condition is false it should return false with error reason", + name: "When a single condition is false, it should return false with error reason", resourceConditions: [][]metav1.Condition{ { { diff --git a/hypershift-operator/controllers/hostedcluster/hostedcluster_webhook_test.go b/hypershift-operator/controllers/hostedcluster/hostedcluster_webhook_test.go index 76b6838d1539..5dd3ab8207b8 100644 --- a/hypershift-operator/controllers/hostedcluster/hostedcluster_webhook_test.go +++ b/hypershift-operator/controllers/hostedcluster/hostedcluster_webhook_test.go @@ -22,7 +22,7 @@ func TestValidateKVHostedClusterCreate(t *testing.T) { imageVersion string }{ { - name: "happy case - versions are valid", + name: "When versions are valid, it should not return an error", hc: &v1beta1.HostedCluster{ ObjectMeta: metav1.ObjectMeta{ Name: "cluster-under-test", @@ -47,7 +47,7 @@ func TestValidateKVHostedClusterCreate(t *testing.T) { imageVersion: "4.16.0", }, { - name: "wrong json", + name: "When JSON annotation is invalid, it should return an error", hc: &v1beta1.HostedCluster{ ObjectMeta: metav1.ObjectMeta{ Name: "cluster-under-test", @@ -103,7 +103,7 @@ func TestValidateKVHostedClusterUpdate(t *testing.T) { imageVersion string }{ { - name: "happy case - versions are valid", + name: "When versions are valid, it should not return an error", oldHC: &v1beta1.HostedCluster{ Spec: v1beta1.HostedClusterSpec{ Release: v1beta1.Release{ @@ -133,7 +133,7 @@ func TestValidateKVHostedClusterUpdate(t *testing.T) { imageVersion: "4.16.0", }, { - name: "wrong json", + name: "When JSON annotation is invalid, it should return an error", oldHC: &v1beta1.HostedCluster{ Spec: v1beta1.HostedClusterSpec{ Release: v1beta1.Release{ @@ -191,19 +191,19 @@ func TestValidateJsonAnnotation(t *testing.T) { expectError bool }{ { - name: "no annotation", + name: "When no annotation is present, it should not return an error", annotations: nil, expectError: false, }, { - name: "valid annotation", + name: "When annotation is valid, it should not return an error", annotations: map[string]string{ v1beta1.JSONPatchAnnotation: `[{"op": "replace","path": "/spec/domain/cpu/cores","value": 3}]`, }, expectError: false, }, { - name: "valid remove without value", + name: "When remove operation has no value, it should not return an error", annotations: map[string]string{ v1beta1.JSONPatchAnnotation: `[{"op": "remove","path": "/spec/template/metadata/annotations/kubevirt.io~1allow-pod-bridge-network-live-migration"}]`, }, @@ -211,42 +211,42 @@ func TestValidateJsonAnnotation(t *testing.T) { }, { - name: "not an array", + name: "When annotation is not an array, it should return an error", annotations: map[string]string{ v1beta1.JSONPatchAnnotation: `{"op": "replace","path": "/spec/domain/cpu/cores","value": 3}`, }, expectError: true, }, { - name: "corrupted json", + name: "When JSON is corrupted, it should return an error", annotations: map[string]string{ v1beta1.JSONPatchAnnotation: `[{"op": "replace","path": "/spec/domain/cpu/cores","value": 3}`, }, expectError: true, }, { - name: "missing op", + name: "When op field is missing, it should return an error", annotations: map[string]string{ v1beta1.JSONPatchAnnotation: `[{"path": "/spec/domain/cpu/cores","value": 3}]`, }, expectError: true, }, { - name: "missing path", + name: "When path field is missing, it should return an error", annotations: map[string]string{ v1beta1.JSONPatchAnnotation: `[{"op": "replace","value": 3}]`, }, expectError: true, }, { - name: "missing value", + name: "When value field is missing, it should return an error", annotations: map[string]string{ v1beta1.JSONPatchAnnotation: `[{"op": "replace","path": "/spec/domain/cpu/cores"}]`, }, expectError: true, }, { - name: "bad operation", + name: "When operation type is invalid, it should return an error", annotations: map[string]string{ v1beta1.JSONPatchAnnotation: `[{"op": "delete","path": "/spec/domain/cpu/cores", "value": "1"}]`, }, @@ -278,7 +278,7 @@ func TestValidateKVNodePoolCreate(t *testing.T) { imageVersion string }{ { - name: "happy case - versions are valid", + name: "When versions are valid, it should not return an error", hc: &v1beta1.HostedCluster{ ObjectMeta: metav1.ObjectMeta{ Name: "cluster-under-test", @@ -316,7 +316,7 @@ func TestValidateKVNodePoolCreate(t *testing.T) { imageVersion: "4.16.0", }, { - name: "wrong json", + name: "When JSON annotation is invalid, it should return an error", hc: &v1beta1.HostedCluster{ ObjectMeta: metav1.ObjectMeta{ Name: "cluster-under-test", @@ -386,7 +386,7 @@ func TestValidateKVNodePoolUpdate(t *testing.T) { imageVersion string }{ { - name: "happy case - versions are valid", + name: "When versions are valid, it should not return an error", hc: &v1beta1.HostedCluster{ ObjectMeta: metav1.ObjectMeta{ Name: "cluster-under-test", @@ -429,7 +429,7 @@ func TestValidateKVNodePoolUpdate(t *testing.T) { imageVersion: "4.16.0", }, { - name: "wrong json", + name: "When JSON annotation is invalid, it should return an error", hc: &v1beta1.HostedCluster{ ObjectMeta: metav1.ObjectMeta{ Name: "cluster-under-test", @@ -521,7 +521,7 @@ func TestKubevirtClusterServiceDefaulting(t *testing.T) { expectedServices []v1beta1.ServicePublishingStrategyMapping }{ { - name: "default services in webhook", + name: "When services are not specified it should default them", hc: &v1beta1.HostedCluster{ ObjectMeta: metav1.ObjectMeta{ Name: "cluster-under-test", @@ -540,7 +540,7 @@ func TestKubevirtClusterServiceDefaulting(t *testing.T) { expectedServices: core.GetIngressServicePublishingStrategyMapping(v1beta1.OVNKubernetes, false, false), }, { - name: "don't default when services already exist", + name: "When services already exist it should not override them", hc: &v1beta1.HostedCluster{ ObjectMeta: metav1.ObjectMeta{ Name: "cluster-under-test", @@ -594,7 +594,7 @@ func TestKubevirtNodePoolManagementDefaulting(t *testing.T) { expectedUpgradeType v1beta1.UpgradeType }{ { - name: "default upgrade type in webhook", + name: "When upgrade type is not specified it should default to Replace", np: &v1beta1.NodePool{ ObjectMeta: metav1.ObjectMeta{ Name: "cluster-under-test", @@ -612,7 +612,7 @@ func TestKubevirtNodePoolManagementDefaulting(t *testing.T) { expectedUpgradeType: v1beta1.UpgradeTypeReplace, }, { - name: "non default upgrade type in webhook", + name: "When upgrade type is InPlace it should not override it", np: &v1beta1.NodePool{ ObjectMeta: metav1.ObjectMeta{ Name: "cluster-under-test", diff --git a/hypershift-operator/controllers/hostedcluster/internal/platform/aws/aws_test.go b/hypershift-operator/controllers/hostedcluster/internal/platform/aws/aws_test.go index 722ccb5f1e8f..2bb07e699eda 100644 --- a/hypershift-operator/controllers/hostedcluster/internal/platform/aws/aws_test.go +++ b/hypershift-operator/controllers/hostedcluster/internal/platform/aws/aws_test.go @@ -27,7 +27,7 @@ func TestReconcileAWSCluster(t *testing.T) { expectedAWSCluster *capiaws.AWSCluster }{ { - name: "Tags get copied over", + name: "When hosted cluster has resource tags it should copy them to the AWS cluster", initialAWSCluster: &capiaws.AWSCluster{}, hostedCluster: &hyperv1.HostedCluster{Spec: hyperv1.HostedClusterSpec{Platform: hyperv1.PlatformSpec{AWS: &hyperv1.AWSPlatformSpec{ ResourceTags: []hyperv1.AWSResourceTag{ @@ -48,7 +48,7 @@ func TestReconcileAWSCluster(t *testing.T) { }, }, { - name: "Existing tags get removed", + name: "When AWS cluster has existing tags it should replace them with hosted cluster tags", initialAWSCluster: &capiaws.AWSCluster{Spec: capiaws.AWSClusterSpec{AdditionalTags: capiaws.Tags{ "to-be-removed": "value", }}}, @@ -71,7 +71,7 @@ func TestReconcileAWSCluster(t *testing.T) { }, }, { - name: "No tags on hostedcluster clears existing awscluster tags", + name: "When hosted cluster has no tags it should clear existing AWS cluster tags", initialAWSCluster: &capiaws.AWSCluster{Spec: capiaws.AWSClusterSpec{AdditionalTags: capiaws.Tags{ "to-be-removed": "value", }}}, @@ -211,7 +211,7 @@ func TestBuildAWSWebIdentityCredentials(t *testing.T) { } tests := []test{ { - name: "should fail if the role ARN is empty", + name: "When role ARN is empty, it should return an error", args: args{ roleArn: "", region: "us-east-1", @@ -219,7 +219,7 @@ func TestBuildAWSWebIdentityCredentials(t *testing.T) { wantErr: true, }, { - name: "should fail if the region is empty", + name: "When region is empty, it should return an error", wantErr: true, args: args{ roleArn: "arn:aws:iam::123456789012:role/some-role", @@ -227,7 +227,7 @@ func TestBuildAWSWebIdentityCredentials(t *testing.T) { }, }, { - name: "should succeed and return the creds template populated with role arn and region otherwise", + name: "When role ARN and region are provided, it should return populated credentials template", wantErr: false, args: args{ roleArn: "arn:aws:iam::123456789012:role/some-role", diff --git a/hypershift-operator/controllers/hostedcluster/internal/platform/azure/azure_test.go b/hypershift-operator/controllers/hostedcluster/internal/platform/azure/azure_test.go index 2d9c270681ea..88ec72729158 100644 --- a/hypershift-operator/controllers/hostedcluster/internal/platform/azure/azure_test.go +++ b/hypershift-operator/controllers/hostedcluster/internal/platform/azure/azure_test.go @@ -48,7 +48,7 @@ func TestReconcileAzureClusterIdentity(t *testing.T) { expectedAzureClusterIdentity *capiazure.AzureClusterIdentity }{ { - name: "when MANAGED_SERVICE is set to AROHCP, it should reconcile AzureClusterIdentity as UserAssignedIdentityCredential", + name: "When MANAGED_SERVICE is set to AROHCP it should reconcile AzureClusterIdentity as UserAssignedIdentityCredential", isManagedService: true, hc: &hyperv1.HostedCluster{ ObjectMeta: metav1.ObjectMeta{ @@ -88,7 +88,7 @@ func TestReconcileAzureClusterIdentity(t *testing.T) { }, }, { - name: "when MANAGED_SERVICE is not set, it should reconcile AzureClusterIdentity as WorkloadIdentity", + name: "When MANAGED_SERVICE is not set it should reconcile AzureClusterIdentity as WorkloadIdentity", isManagedService: false, hc: &hyperv1.HostedCluster{ ObjectMeta: metav1.ObjectMeta{ @@ -160,25 +160,25 @@ func TestParseCloudType(t *testing.T) { expectedError bool }{ { - name: "when input is AzurePublicCloud, expected output is public", + name: "When input is AzurePublicCloud, it should return public", input: "AzurePublicCloud", expectedOutput: "public", expectedError: false, }, { - name: "when input is AzureUSGovernmentCloud, expected output is usgovernment", + name: "When input is AzureUSGovernmentCloud, it should return usgovernment", input: "AzureUSGovernmentCloud", expectedOutput: "usgovernment", expectedError: false, }, { - name: "when input is AzureChinaCloud, expected output is china", + name: "When input is AzureChinaCloud, it should return china", input: "AzureChinaCloud", expectedOutput: "china", expectedError: false, }, { - name: "when input is an invalid cloud type, expect error", + name: "When input is an invalid cloud type, it should return an error", input: "AzureGermanCloud", expectedOutput: "", expectedError: true, @@ -263,7 +263,7 @@ func TestReconcileCredentials(t *testing.T) { validateSecrets func(secrets []*corev1.Secret) }{ { - name: "self-managed Azure with workload identities creates all credential secrets", + name: "When self-managed Azure has workload identities it should create all credential secrets", managedService: "", hcluster: createTestHostedCluster(true, &hyperv1.AzureWorkloadIdentities{ Ingress: hyperv1.WorkloadIdentity{ @@ -317,7 +317,7 @@ func TestReconcileCredentials(t *testing.T) { }, }, { - name: "self-managed Azure with disabled capabilities skips appropriate secrets", + name: "When self-managed Azure has disabled capabilities it should skip appropriate secrets", managedService: "", hcluster: func() *hyperv1.HostedCluster { hc := createTestHostedCluster(true, &hyperv1.AzureWorkloadIdentities{ @@ -361,7 +361,7 @@ func TestReconcileCredentials(t *testing.T) { }, }, { - name: "managed Azure (ARO-HCP) does not create workload identity secrets", + name: "When managed Azure ARO-HCP is used it should not create workload identity secrets", managedService: hyperv1.AroHCP, hcluster: createTestHostedCluster(false, nil), expectedSecretsCount: 1, // Only CNCC secret should be created @@ -461,7 +461,7 @@ func TestReconcileKMSConfigSecret(t *testing.T) { validate func(g Gomega, cfg azurecloud.AzureConfig) }{ { - name: "When ARO HCP it should set AADMSIDataPlaneIdentityPath", + name: "When ARO HCP, it should set AADMSIDataPlaneIdentityPath", managedService: hyperv1.AroHCP, hc: func() *hyperv1.HostedCluster { hc := baseHC() @@ -477,7 +477,7 @@ func TestReconcileKMSConfigSecret(t *testing.T) { }, }, { - name: "When self-managed Azure with workload identities it should set federated identity fields", + name: "When self-managed Azure with workload identities, it should set federated identity fields", hc: func() *hyperv1.HostedCluster { hc := baseHC() hc.Spec.SecretEncryption.KMS.Azure.WorkloadIdentity = hyperv1.WorkloadIdentity{ @@ -492,7 +492,7 @@ func TestReconcileKMSConfigSecret(t *testing.T) { }, }, { - name: "When Azure KMS without any credentials it should return an error", + name: "When Azure KMS without any credentials, it should return an error", hc: baseHC(), expectErr: true, }, @@ -569,7 +569,7 @@ func TestDeleteOrphanedMachines(t *testing.T) { expectedError bool }{ { - name: "when ManagedIdentities is nil it should return early without modifying machines", + name: "When ManagedIdentities is nil it should return early without modifying machines", hostedCluster: &hyperv1.HostedCluster{ Spec: hyperv1.HostedClusterSpec{ Platform: hyperv1.PlatformSpec{ @@ -596,14 +596,14 @@ func TestDeleteOrphanedMachines(t *testing.T) { expectedError: false, }, { - name: "when there are no machines it should succeed", + name: "When there are no machines it should succeed", hostedCluster: managedIdentitiesHC, azureMachines: []capiazure.AzureMachine{}, expectedFinalizersRemoved: false, expectedError: false, }, { - name: "when a machine has a stale DeletionTimestamp with DeletionFailed condition it should remove finalizers", + name: "When a machine has a stale DeletionTimestamp with DeletionFailed condition it should remove finalizers", hostedCluster: managedIdentitiesHC, azureMachines: []capiazure.AzureMachine{ { @@ -622,7 +622,7 @@ func TestDeleteOrphanedMachines(t *testing.T) { expectedError: false, }, { - name: "when a machine has a recent DeletionTimestamp with DeletionFailed condition it should not remove finalizers", + name: "When a machine has a recent DeletionTimestamp with DeletionFailed condition it should not remove finalizers", hostedCluster: managedIdentitiesHC, azureMachines: []capiazure.AzureMachine{ { @@ -641,7 +641,7 @@ func TestDeleteOrphanedMachines(t *testing.T) { expectedError: false, }, { - name: "when a machine has a stale DeletionTimestamp without DeletionFailed condition it should not remove finalizers", + name: "When a machine has a stale DeletionTimestamp without DeletionFailed condition it should not remove finalizers", hostedCluster: managedIdentitiesHC, azureMachines: []capiazure.AzureMachine{ { @@ -665,7 +665,7 @@ func TestDeleteOrphanedMachines(t *testing.T) { expectedError: false, }, { - name: "when a machine is not pending deletion it should not remove finalizers regardless of conditions", + name: "When a machine is not pending deletion it should not remove finalizers regardless of conditions", hostedCluster: managedIdentitiesHC, azureMachines: []capiazure.AzureMachine{ { diff --git a/hypershift-operator/controllers/hostedcluster/internal/platform/openstack/openstack_test.go b/hypershift-operator/controllers/hostedcluster/internal/platform/openstack/openstack_test.go index b587ad4317ca..af1936b90f90 100644 --- a/hypershift-operator/controllers/hostedcluster/internal/platform/openstack/openstack_test.go +++ b/hypershift-operator/controllers/hostedcluster/internal/platform/openstack/openstack_test.go @@ -38,7 +38,7 @@ func TestReconcileOpenStackCluster(t *testing.T) { wantErr bool }{ { - name: "CAPO provisioned network and subnet", + name: "When using CAPO provisioned network and subnet, it should reconcile the OpenStack cluster spec", hostedCluster: &hyperv1.HostedCluster{ Spec: hyperv1.HostedClusterSpec{ InfraID: "cluster-123", @@ -88,7 +88,7 @@ func TestReconcileOpenStackCluster(t *testing.T) { wantErr: false, }, { - name: "User provided network and subnet by ID on hosted cluster", + name: "When user provides network and subnet by ID, it should reconcile the OpenStack cluster spec", hostedCluster: &hyperv1.HostedCluster{ Spec: hyperv1.HostedClusterSpec{ InfraID: "cluster-123", @@ -134,7 +134,7 @@ func TestReconcileOpenStackCluster(t *testing.T) { wantErr: false, }, { - name: "User provided network and subnet by tag on hosted cluster", + name: "When user provides network and subnet by tag, it should reconcile the OpenStack cluster spec", hostedCluster: &hyperv1.HostedCluster{ Spec: hyperv1.HostedClusterSpec{ InfraID: "cluster-123", @@ -193,7 +193,7 @@ func TestReconcileOpenStackCluster(t *testing.T) { wantErr: false, }, { - name: "Missing machine networks", + name: "When machine networks are missing, it should return an error", hostedCluster: &hyperv1.HostedCluster{ Spec: hyperv1.HostedClusterSpec{ Platform: hyperv1.PlatformSpec{ @@ -353,7 +353,7 @@ func TestCAPIProviderDeploymentSpec(t *testing.T) { envVars map[string]string }{ { - name: "deployment spec on 4.18.0", + name: "When payload version is 4.18.0 it should return the expected deployment spec", hcluster: &hyperv1.HostedCluster{ ObjectMeta: metav1.ObjectMeta{ Name: "test-cluster", @@ -373,7 +373,7 @@ func TestCAPIProviderDeploymentSpec(t *testing.T) { envVars: map[string]string{}, }, { - name: "deployment spec on 4.19.0 (with ORC)", + name: "When payload version is 4.19.0 it should return the expected deployment spec with ORC", hcluster: &hyperv1.HostedCluster{ ObjectMeta: metav1.ObjectMeta{ Name: "test-cluster", diff --git a/hypershift-operator/controllers/hostedcluster/internal/proxy/validation_test.go b/hypershift-operator/controllers/hostedcluster/internal/proxy/validation_test.go index 23467ed2183b..1810e0eea7d8 100644 --- a/hypershift-operator/controllers/hostedcluster/internal/proxy/validation_test.go +++ b/hypershift-operator/controllers/hostedcluster/internal/proxy/validation_test.go @@ -36,7 +36,7 @@ func TestLoadCABundle(t *testing.T) { expectCerts int }{ { - name: "When ConfigMap has valid certificate it should succeed", + name: "When ConfigMap has valid certificate, it should succeed", configMap: corev1.ConfigMap{ ObjectMeta: metav1.ObjectMeta{ Name: "test-ca-bundle", @@ -50,7 +50,7 @@ func TestLoadCABundle(t *testing.T) { expectCerts: 1, }, { - name: "When ConfigMap has multiple certificates it should succeed", + name: "When ConfigMap has multiple certificates, it should succeed", configMap: corev1.ConfigMap{ ObjectMeta: metav1.ObjectMeta{ Name: "test-ca-bundle", @@ -64,7 +64,7 @@ func TestLoadCABundle(t *testing.T) { expectCerts: 2, }, { - name: "When ConfigMap is missing ca-bundle.crt key it should fail", + name: "When ConfigMap is missing ca-bundle.crt key, it should fail", configMap: corev1.ConfigMap{ ObjectMeta: metav1.ObjectMeta{ Name: "test-ca-bundle", @@ -78,7 +78,7 @@ func TestLoadCABundle(t *testing.T) { errorContains: "is missing \"ca-bundle.crt\"", }, { - name: "When ConfigMap has empty ca-bundle.crt it should fail", + name: "When ConfigMap has empty ca-bundle.crt, it should fail", configMap: corev1.ConfigMap{ ObjectMeta: metav1.ObjectMeta{ Name: "test-ca-bundle", @@ -92,7 +92,7 @@ func TestLoadCABundle(t *testing.T) { errorContains: "is empty", }, { - name: "When ConfigMap has invalid certificate data it should fail", + name: "When ConfigMap has invalid certificate data, it should fail", configMap: corev1.ConfigMap{ ObjectMeta: metav1.ObjectMeta{ Name: "test-ca-bundle", @@ -141,7 +141,7 @@ func TestValidateProxyCAValidity(t *testing.T) { errorContains string }{ { - name: "When no proxy configured it should succeed", + name: "When no proxy configured, it should succeed", hcluster: &hyperv1.HostedCluster{ ObjectMeta: metav1.ObjectMeta{ Name: "test-cluster", @@ -152,7 +152,7 @@ func TestValidateProxyCAValidity(t *testing.T) { expectError: false, }, { - name: "When proxy configured without CA it should succeed", + name: "When proxy configured without CA, it should succeed", hcluster: &hyperv1.HostedCluster{ ObjectMeta: metav1.ObjectMeta{ Name: "test-cluster", @@ -169,7 +169,7 @@ func TestValidateProxyCAValidity(t *testing.T) { expectError: false, }, { - name: "When valid certificate it should succeed", + name: "When valid certificate, it should succeed", hcluster: &hyperv1.HostedCluster{ ObjectMeta: metav1.ObjectMeta{ Name: "test-cluster", @@ -197,7 +197,7 @@ func TestValidateProxyCAValidity(t *testing.T) { expectError: false, }, { - name: "When expired certificate it should fail", + name: "When expired certificate, it should fail", hcluster: &hyperv1.HostedCluster{ ObjectMeta: metav1.ObjectMeta{ Name: "test-cluster", @@ -226,7 +226,7 @@ func TestValidateProxyCAValidity(t *testing.T) { errorContains: "no longer valid", }, { - name: "When future-dated certificate it should fail", + name: "When future-dated certificate, it should fail", hcluster: &hyperv1.HostedCluster{ ObjectMeta: metav1.ObjectMeta{ Name: "test-cluster", @@ -380,7 +380,7 @@ func TestExpiryTimeProxyCA(t *testing.T) { expectedExpiry: func() *time.Time { t := now.Add(24 * time.Hour); return &t }(), }, { - name: "When ConfigMap not found it should return error", + name: "When ConfigMap not found, it should return error", hcluster: &hyperv1.HostedCluster{ ObjectMeta: metav1.ObjectMeta{ Name: "test-cluster", diff --git a/hypershift-operator/controllers/hostedcluster/karpenter_test.go b/hypershift-operator/controllers/hostedcluster/karpenter_test.go index 5649e7b9a841..e6e6ccb23922 100644 --- a/hypershift-operator/controllers/hostedcluster/karpenter_test.go +++ b/hypershift-operator/controllers/hostedcluster/karpenter_test.go @@ -192,25 +192,25 @@ func TestIsKASAvailable(t *testing.T) { expectError bool }{ { - name: "deployment missing", + name: "When deployment is missing, it should return false", expected: false, }, { - name: "deployment exists, Available=True", + name: "When deployment exists with Available=True, it should return true", objects: []crclient.Object{ kasDeployment(cpNamespace, true), }, expected: true, }, { - name: "deployment exists, Available=False", + name: "When deployment exists with Available=False, it should return false", objects: []crclient.Object{ kasDeployment(cpNamespace, false), }, expected: false, }, { - name: "deployment exists, no Available condition", + name: "When deployment exists with no Available condition, it should return false", objects: []crclient.Object{ &appsv1.Deployment{ ObjectMeta: metav1.ObjectMeta{Name: "kube-apiserver", Namespace: cpNamespace}, @@ -303,7 +303,7 @@ func TestReconcileAutoNodeEnabledCondition(t *testing.T) { want metav1.Condition wantProgessing bool }{ - "When karpenter is enabled and components not yet created it should report progressing": { + "When karpenter is enabled and components not yet created, it should report progressing": { autoNode: karpenterEnabledAutoNode, components: nil, wantProgessing: true, @@ -313,7 +313,7 @@ func TestReconcileAutoNodeEnabledCondition(t *testing.T) { Reason: hyperv1.AutoNodeProgressingReason, }, }, - "When karpenter is enabled and only one component exists it should report progressing": { + "When karpenter is enabled and only one component exists, it should report progressing": { autoNode: karpenterEnabledAutoNode, components: []hyperv1.ControlPlaneComponent{ { @@ -328,7 +328,7 @@ func TestReconcileAutoNodeEnabledCondition(t *testing.T) { Reason: hyperv1.AutoNodeProgressingReason, }, }, - "When karpenter is enabled and one component is not rolled out it should report progressing": { + "When karpenter is enabled and one component is not rolled out, it should report progressing": { autoNode: karpenterEnabledAutoNode, components: []hyperv1.ControlPlaneComponent{ { @@ -347,7 +347,7 @@ func TestReconcileAutoNodeEnabledCondition(t *testing.T) { Reason: hyperv1.AutoNodeProgressingReason, }, }, - "When karpenter is enabled and both components are rolled out it should report ready": { + "When karpenter is enabled and both components are rolled out, it should report ready": { autoNode: karpenterEnabledAutoNode, components: []hyperv1.ControlPlaneComponent{ { @@ -365,7 +365,7 @@ func TestReconcileAutoNodeEnabledCondition(t *testing.T) { Reason: hyperv1.AsExpectedReason, }, }, - "When karpenter is disabled and deployments are still present it should report progressing": { + "When karpenter is disabled and deployments are still present, it should report progressing": { autoNode: hyperv1.AutoNode{}, deployments: []appsv1.Deployment{ {ObjectMeta: metav1.ObjectMeta{Name: karpenterv2.ComponentName, Namespace: hcpNamespace}}, @@ -378,7 +378,7 @@ func TestReconcileAutoNodeEnabledCondition(t *testing.T) { Reason: hyperv1.AutoNodeProgressingReason, }, }, - "When karpenter is disabled and only the karpenter deployment remains it should report progressing": { + "When karpenter is disabled and only the karpenter deployment remains, it should report progressing": { autoNode: hyperv1.AutoNode{}, deployments: []appsv1.Deployment{ {ObjectMeta: metav1.ObjectMeta{Name: karpenterv2.ComponentName, Namespace: hcpNamespace}}, @@ -390,7 +390,7 @@ func TestReconcileAutoNodeEnabledCondition(t *testing.T) { Reason: hyperv1.AutoNodeProgressingReason, }, }, - "When karpenter is disabled and CPC CRs remain but deployments are gone it should report not configured": { + "When karpenter is disabled and CPC CRs remain but deployments are gone, it should report not configured": { // CPC CRs are deleted before pods terminate; once Deployments are gone teardown is complete. autoNode: hyperv1.AutoNode{}, components: []hyperv1.ControlPlaneComponent{ @@ -406,7 +406,7 @@ func TestReconcileAutoNodeEnabledCondition(t *testing.T) { Reason: hyperv1.AutoNodeNotConfiguredReason, }, }, - "When karpenter is disabled and no deployments are present it should report not configured": { + "When karpenter is disabled and no deployments are present, it should report not configured": { autoNode: hyperv1.AutoNode{}, want: metav1.Condition{ Type: string(hyperv1.AutoNodeEnabled), diff --git a/hypershift-operator/controllers/hostedcluster/metrics/metrics_test.go b/hypershift-operator/controllers/hostedcluster/metrics/metrics_test.go index 8f077294c4ab..5f05d9306a9e 100644 --- a/hypershift-operator/controllers/hostedcluster/metrics/metrics_test.go +++ b/hypershift-operator/controllers/hostedcluster/metrics/metrics_test.go @@ -102,17 +102,17 @@ func TestReportWaitingInitialAvailabilityDuration(t *testing.T) { expected *dto.MetricFamily }{ { - name: "When cluster just got created, metric is reported with a value set to 0", + name: "When cluster is just created, it should report metric value 0", timestamp: now, expected: wrapExpectedValueAsMetric(0), }, { - name: "When annotation is not set, metric reports the elapsed time since the cluster has been created", + name: "When annotation is not set, it should report elapsed time since cluster creation", timestamp: now.Add(5 * time.Minute), expected: wrapExpectedValueAsMetric(300), }, { - name: "When annotation is set, metric is not reported anymore", + name: "When annotation is set it should not report the metric", timestamp: now.Add(5 * time.Minute), annotations: map[string]string{ HasBeenAvailableAnnotation: "true", @@ -165,12 +165,12 @@ func TestReportInitialRollingOutDuration(t *testing.T) { expected *dto.MetricFamily }{ { - name: "When cluster just got created, metric is reported with a value set to 0", + name: "When cluster is just created, it should report metric value 0", timestamp: now, expected: wrapExpectedValueAsMetric(0), }, { - name: "When cluster is not yet provisioned, metric reports the elapsed time since the cluster has been created", + name: "When cluster is not yet provisioned, it should report elapsed time since creation", timestamp: now.Add(30 * time.Minute), updateHistory: []configv1.UpdateHistory{{ StartedTime: metav1.Time{Time: now.Add(5 * time.Minute)}, @@ -179,7 +179,7 @@ func TestReportInitialRollingOutDuration(t *testing.T) { expected: wrapExpectedValueAsMetric(1800), }, { - name: "When cluster is provisioned, metric is not reported anymore", + name: "When cluster is provisioned it should not report the metric", timestamp: now.Add(30 * time.Minute), updateHistory: []configv1.UpdateHistory{{ StartedTime: metav1.Time{Time: now.Add(5 * time.Minute)}, @@ -188,7 +188,7 @@ func TestReportInitialRollingOutDuration(t *testing.T) { }}, }, { - name: "When cluster is upgrading, metric is not reported", + name: "When cluster is upgrading it should not report the metric", timestamp: now.Add(5*time.Hour + 30*time.Minute), updateHistory: []configv1.UpdateHistory{ { @@ -267,11 +267,11 @@ func TestReportUpgradingDuration(t *testing.T) { expected *dto.MetricFamily }{ { - name: "When cluster just got created, metric is not reported", + name: "When cluster is just created it should not report the metric", timestamp: now, }, { - name: "When cluster is not yet provisioned, metric is not reported", + name: "When cluster is not yet provisioned it should not report the metric", timestamp: now.Add(30 * time.Minute), updateHistory: []configv1.UpdateHistory{{ StartedTime: metav1.Time{Time: now.Add(5 * time.Minute)}, @@ -279,7 +279,7 @@ func TestReportUpgradingDuration(t *testing.T) { }}, }, { - name: "When cluster is provisioned, metric is not reported", + name: "When cluster is provisioned it should not report the metric", timestamp: now.Add(30 * time.Minute), updateHistory: []configv1.UpdateHistory{{ StartedTime: metav1.Time{Time: now.Add(5 * time.Minute)}, @@ -288,7 +288,7 @@ func TestReportUpgradingDuration(t *testing.T) { }}, }, { - name: "When cluster is upgrading, metric reports the time since the beginning of the upgrade", + name: "When cluster is upgrading, it should report the time since the upgrade began", timestamp: now.Add(5*time.Hour + 30*time.Minute), updateHistory: []configv1.UpdateHistory{ { @@ -304,7 +304,7 @@ func TestReportUpgradingDuration(t *testing.T) { expected: wrapExpectedValueAsMetric(1800, "1.0", "1.1"), }, { - name: "When cluster has upgraded, metric is not reported again", + name: "When cluster has upgraded it should not report the metric", timestamp: now.Add(5*time.Hour + 30*time.Minute), updateHistory: []configv1.UpdateHistory{ { @@ -320,7 +320,7 @@ func TestReportUpgradingDuration(t *testing.T) { }, }, { - name: "When cluster is upgrading again, metric reports the time since the beginning of the upgrade again", + name: "When cluster is upgrading again, it should report the time since the upgrade began", timestamp: now.Add(12*time.Hour + 20*time.Minute), updateHistory: []configv1.UpdateHistory{ { @@ -383,22 +383,22 @@ func TestReportLimitedSuportEnabled(t *testing.T) { expected *dto.MetricFamily }{ { - name: "When limited support label is set to true, metric is reported as one", + name: "When limited support label is set to true, it should report metric as one", labels: map[string]string{hyperv1.LimitedSupportLabel: "true"}, expected: wrapExpectedValueAsMetric(1), }, { - name: "When limited support label is set to false, metric is reported as zero", + name: "When limited support label is set to false, it should report metric as zero", labels: map[string]string{hyperv1.LimitedSupportLabel: "false"}, expected: wrapExpectedValueAsMetric(0), }, { - name: "When limited support label is set to anything unsupported, metric is reported as zero", + name: "When limited support label is set to anything unsupported, it should report metric as zero", labels: map[string]string{hyperv1.LimitedSupportLabel: "foo"}, expected: wrapExpectedValueAsMetric(0), }, { - name: "When limited support label is not set, metric is reported as zero", + name: "When limited support label is not set, it should report metric as zero", labels: map[string]string{}, expected: wrapExpectedValueAsMetric(0), }, @@ -441,12 +441,12 @@ func TestReportSilenceAlerts(t *testing.T) { expected *dto.MetricFamily }{ { - name: "When silenced alerts label is set, metric is reported as one", + name: "When silenced alerts label is set, it should report metric as one", labels: map[string]string{hyperv1.SilenceClusterAlertsLabel: "true"}, expected: wrapExpectedValueAsMetric(1), }, { - name: "When silenced alerts label is not set, metric is reported as zero", + name: "When silenced alerts label is not set, it should report metric as zero", labels: map[string]string{}, expected: wrapExpectedValueAsMetric(0), }, @@ -519,7 +519,7 @@ func TestReportProxy(t *testing.T) { expected *dto.MetricFamily }{ { - name: "When proxy configuration is set, metric is reported with a value set to 1, same for the metric labels", + name: "When proxy configuration is set, it should report metric value 1 with matching labels", clusterConf: hyperv1.ClusterConfiguration{ Proxy: &configv1.ProxySpec{ HTTPProxy: "fakeProxyServer", @@ -532,7 +532,7 @@ func TestReportProxy(t *testing.T) { expected: wrapExpectedValueAsMetric(1), }, { - name: "When Proxy configuration is not set, metric is reported with a value set to 0, metric labels are empty", + name: "When proxy configuration is not set, it should report metric value 0 with empty labels", expected: wrapExpectedValueAsMetric(0), }, } @@ -575,43 +575,43 @@ func TestReportInvalidAwsCreds(t *testing.T) { expected *dto.MetricFamily }{ { - name: "When both conditions are true, metric is reported with a value set to 0 (valid)", + name: "When both conditions are true, it should report metric value 0 as valid", ValidOIDCConfigurationConditionStatus: metav1.ConditionTrue, ValidAWSIdentityProviderConditionStatus: metav1.ConditionTrue, expected: wrapExpectedValueAsMetric(0), }, { - name: "When ValidOIDCConfigurationCondition status is false, metric is reported with a value set to 1 (invalid)", + name: "When ValidOIDCConfigurationCondition status is false, it should report metric value 1 as invalid", ValidOIDCConfigurationConditionStatus: metav1.ConditionFalse, ValidAWSIdentityProviderConditionStatus: metav1.ConditionTrue, expected: wrapExpectedValueAsMetric(1), }, { - name: "When ValidAWSIdentityProviderCondition status is false, metric is reported with a value set to 1 (invalid)", + name: "When ValidAWSIdentityProviderCondition status is false, it should report metric value 1 as invalid", ValidOIDCConfigurationConditionStatus: metav1.ConditionTrue, ValidAWSIdentityProviderConditionStatus: metav1.ConditionFalse, expected: wrapExpectedValueAsMetric(1), }, { - name: "When both conditions are false, metric is reported with a value set to 1 (invalid)", + name: "When both conditions are false, it should report metric value 1 as invalid", ValidOIDCConfigurationConditionStatus: metav1.ConditionFalse, ValidAWSIdentityProviderConditionStatus: metav1.ConditionFalse, expected: wrapExpectedValueAsMetric(1), }, { - name: "When ValidOIDCConfigurationCondition status is unknown, metric is reported with a value set to 2 (unknown)", + name: "When ValidOIDCConfigurationCondition status is unknown, it should report metric value 2 as unknown", ValidOIDCConfigurationConditionStatus: metav1.ConditionUnknown, ValidAWSIdentityProviderConditionStatus: metav1.ConditionTrue, expected: wrapExpectedValueAsMetric(2), }, { - name: "When ValidAWSIdentityProviderCondition status is unknown, metric is reported with a value set to 2 (unknown)", + name: "When ValidAWSIdentityProviderCondition status is unknown, it should report metric value 2 as unknown", ValidOIDCConfigurationConditionStatus: metav1.ConditionTrue, ValidAWSIdentityProviderConditionStatus: metav1.ConditionUnknown, expected: wrapExpectedValueAsMetric(2), }, { - name: "When both conditions are unknown, metric is reported with a value set to 2 (unknown)", + name: "When both conditions are unknown, it should report metric value 2 as unknown", ValidOIDCConfigurationConditionStatus: metav1.ConditionUnknown, ValidAWSIdentityProviderConditionStatus: metav1.ConditionUnknown, expected: wrapExpectedValueAsMetric(2), @@ -664,18 +664,18 @@ func TestReportGuestCloudResourcesDeletionDuration(t *testing.T) { expected *dto.MetricFamily }{ { - name: "When cluster is not yet deleting, metric is not reported", + name: "When cluster is not yet deleting it should not report the metric", timestamp: now, }, { - name: "When cluster just started to be deleted, metric is reported with a value set to 0", + name: "When cluster just started to be deleted, it should report metric value 0", timestamp: now, isDeleting: true, conditions: []metav1.Condition{}, expected: wrapExpectedValueAsMetric(0), }, { - name: "When destroyed condition is false, metric reports the elapsed time since the beginning of the delete", + name: "When destroyed condition is false, it should report elapsed time since delete began", timestamp: now.Add(5 * time.Minute), isDeleting: true, conditions: []metav1.Condition{ @@ -688,7 +688,7 @@ func TestReportGuestCloudResourcesDeletionDuration(t *testing.T) { expected: wrapExpectedValueAsMetric(300), }, { - name: "When destroyed condition is true, metric is not reported anymore", + name: "When destroyed condition is true it should not report the metric", timestamp: now.Add(5 * time.Minute), isDeleting: true, conditions: []metav1.Condition{ @@ -749,23 +749,23 @@ func TestReportDeletingDuration(t *testing.T) { expected *dto.MetricFamily }{ { - name: "When cluster is not yet deleting, metric is not reported", + name: "When cluster is not yet deleting it should not report the metric", timestamp: now, }, { - name: "When cluster just started to be deleted, metric is reported with a value set to 0", + name: "When cluster just started to be deleted, it should report metric value 0", timestamp: now, isDeleting: true, expected: wrapExpectedValueAsMetric(0), }, { - name: "When cluster is not yet deleted, metric reports the elapsed time since the beginning of the delete", + name: "When cluster is not yet deleted, it should report elapsed time since delete began", timestamp: now.Add(10 * time.Minute), isDeleting: true, expected: wrapExpectedValueAsMetric(600), }, { - name: "When cluster is deleted, metric is not reported anymore", + name: "When cluster is deleted it should not report the metric", timestamp: now, isDeleted: true, }, @@ -831,11 +831,11 @@ func TestReportEtcdManualInterventionRequired(t *testing.T) { expected *dto.MetricFamily }{ { - name: "When cluster does not have the required tags, metric is not reported", + name: "When cluster does not have the required tags it should not report the metric", timestamp: now, }, { - name: "When cluster has the required tags but etcd recovery is not active, metric is not reported", + name: "When cluster has the required tags but etcd recovery is not active it should not report the metric", timestamp: now, tags: map[string]string{ "red-hat-clustertype": "rosa", @@ -848,7 +848,7 @@ func TestReportEtcdManualInterventionRequired(t *testing.T) { }, }, { - name: "When cluster has the required tags and etcd recovery job failed, metric is reported", + name: "When cluster has the required tags and etcd recovery job failed, it should report the metric", timestamp: now, tags: map[string]string{ "red-hat-clustertype": "rosa", @@ -926,20 +926,20 @@ func TestProxyCAValidity(t *testing.T) { expected *dto.MetricFamily }{ { - name: "When cluster is not setting a CA bundle, the validity it not reported", + name: "When cluster is not setting a CA bundle it should not report validity", timestamp: now, caCertificate: "", caConfigMap: "", }, { - name: "When the configured certificates are expired, the CA is invalid", + name: "When the configured certificates are expired, it should report the CA as invalid", timestamp: now, caCertificate: invalidCAPEM, caConfigMap: "my-config-map", expected: wrapExpectedValueAsMetric(0), }, { - name: "When the configured certificates are valid, the CA is valid", + name: "When the configured certificates are valid, it should report the CA as valid", timestamp: now, caCertificate: validCAPEM, caConfigMap: "my-config-map", @@ -1026,20 +1026,20 @@ func TestProxyCAExpiry(t *testing.T) { expected *dto.MetricFamily }{ { - name: "When cluster is not setting a CA bundle, the validity it not reported", + name: "When cluster is not setting a CA bundle it should not report validity", timestamp: now, caCertificate: "", caConfigMap: "", }, { - name: "When the configured certificates are expired, the CA is invalid", + name: "When the configured certificates are expired, it should report the CA as invalid", timestamp: now, caCertificate: invalidCAPEM, caConfigMap: "my-config-map", expected: wrapExpectedValueAsMetric(float64(invalidCA.NotAfter.UTC().Unix())), }, { - name: "When the configured certificates are valid, the CA is valid", + name: "When the configured certificates are valid, it should report the CA as valid", timestamp: now, caCertificate: validCAPEM, caConfigMap: "my-config-map", @@ -1117,11 +1117,11 @@ func TestReportClusterSizeOverride(t *testing.T) { expected *dto.MetricFamily }{ { - name: "When cluster does not have the cluster override annotation, metric is not reported", + name: "When cluster does not have the cluster override annotation it should not report the metric", timestamp: now, }, { - name: "When cluster has the cluster size annotation with a large value, metric is reported", + name: "When cluster has the cluster size annotation with a large value, it should report the metric", timestamp: now, tags: map[string]string{ "red-hat-clustertype": "rosa", @@ -1132,7 +1132,7 @@ func TestReportClusterSizeOverride(t *testing.T) { expected: wrapExpectedValueAsMetric("large", 1.0), }, { - name: "When cluster has the cluster size annotation with a small value, metric is reported", + name: "When cluster has the cluster size annotation with a small value, it should report the metric", timestamp: now, tags: map[string]string{ "red-hat-clustertype": "rosa", @@ -1192,20 +1192,20 @@ func TestHostedClusterAzureInfo(t *testing.T) { expected *dto.MetricFamily }{ { - name: "no Azure Platform, no metric", + name: "When platform is not Azure it should not emit a metric", timestamp: now, platformType: hyperv1.IBMCloudPlatform, expectedMetricName: "no metric expected", }, { - name: "Azure platform but no data, no metric", + name: "When Azure platform has no spec data it should not emit a metric", timestamp: now, platformType: hyperv1.AzurePlatform, azureSpec: nil, expectedMetricName: "no metric expected", }, { - name: "Azure, simple unmanaged", + name: "When Azure platform is unmanaged, it should emit the unmanaged metric", timestamp: now, platformType: hyperv1.AzurePlatform, azureSpec: &hyperv1.AzurePlatformSpec{ @@ -1234,7 +1234,7 @@ func TestHostedClusterAzureInfo(t *testing.T) { }, }, { - name: "Azure, simple managed", + name: "When Azure platform is managed, it should emit the managed metric", timestamp: now, platformType: hyperv1.AzurePlatform, azureSpec: &hyperv1.AzurePlatformSpec{ @@ -1308,7 +1308,7 @@ func TestAcrPullIdentityConfigured(t *testing.T) { expectedMetricName: AcrPullIdentityConfiguredMetricName, }, { - name: "When Azure has no containerRegistry configured it should emit 0", + name: "When Azure has no containerRegistry configured, it should emit 0", platformType: hyperv1.AzurePlatform, azureSpec: &hyperv1.AzurePlatformSpec{ Cloud: "AzureCloud", @@ -1332,7 +1332,7 @@ func TestAcrPullIdentityConfigured(t *testing.T) { }, }, { - name: "When Azure has a containerRegistry configured it should emit 1", + name: "When Azure has a containerRegistry configured, it should emit 1", platformType: hyperv1.AzurePlatform, azureSpec: &hyperv1.AzurePlatformSpec{ Cloud: "AzureCloud", @@ -1395,7 +1395,7 @@ func TestReportTransitionDurationForAWSEndpointConditions(t *testing.T) { expectedConditions []string }{ { - name: "When no AWS endpoint conditions are set, no transition duration is recorded", + name: "When no AWS endpoint conditions are set it should not record transition duration", conditions: nil, expectedConditions: nil, }, @@ -1422,7 +1422,7 @@ func TestReportTransitionDurationForAWSEndpointConditions(t *testing.T) { expectedConditions: []string{string(hyperv1.AWSEndpointAvailable)}, }, { - name: "When both AWS endpoint conditions are true, both should be observed", + name: "When both AWS endpoint conditions are true, it should observe both", conditions: []metav1.Condition{ { Type: string(hyperv1.AWSEndpointServiceAvailable), diff --git a/hypershift-operator/controllers/hostedcluster/security_context_uid_test.go b/hypershift-operator/controllers/hostedcluster/security_context_uid_test.go index 7cea3986dcee..586e4be7c00a 100644 --- a/hypershift-operator/controllers/hostedcluster/security_context_uid_test.go +++ b/hypershift-operator/controllers/hostedcluster/security_context_uid_test.go @@ -28,14 +28,14 @@ func TestGetNextAvailableSecurityContextUID(t *testing.T) { expectErr bool }{ { - name: "when no namespaces, it should return first available UID", + name: "When no namespaces exist, it should return first available UID", namespaces: []corev1.Namespace{}, expectedUID: controlplanecomponent.DefaultSecurityContextUID, expectedFor3SubsequentCalls: []int64{controlplanecomponent.DefaultSecurityContextUID + 1, controlplanecomponent.DefaultSecurityContextUID + 2, controlplanecomponent.DefaultSecurityContextUID + 3}, expectErr: false, }, { - name: "when there are multiple namespaces, it should allocate the lower available UID", + name: "When there are multiple namespaces, it should allocate the lower available UID", namespaces: []corev1.Namespace{ { ObjectMeta: metav1.ObjectMeta{ @@ -65,7 +65,7 @@ func TestGetNextAvailableSecurityContextUID(t *testing.T) { expectErr: false, }, { - name: "when there are namespaces with invalid annotation it should be ignored", + name: "When namespaces have invalid annotations, it should ignore them and return first available UID", namespaces: []corev1.Namespace{ { ObjectMeta: metav1.ObjectMeta{ @@ -84,7 +84,7 @@ func TestGetNextAvailableSecurityContextUID(t *testing.T) { expectErr: false, }, { - name: "when there are namespaces without the control plane label it should be ignored", + name: "When namespaces lack the control plane label, it should ignore them and return first available UID", namespaces: []corev1.Namespace{ { ObjectMeta: metav1.ObjectMeta{ @@ -187,13 +187,13 @@ func TestInitializeFromNamespaces(t *testing.T) { expectedInitalized bool }{ { - name: "when namespace list is empty, it should initialize with no allocations", + name: "When namespace list is empty it should initialize with no allocations", namespaces: []corev1.Namespace{}, expectedAllocated: []int64{}, expectedInitalized: true, }, { - name: "when namespaces have control plane label and valid UIDs, it should load those UIDs", + name: "When namespaces have control plane label and valid UIDs it should load those UIDs", namespaces: []corev1.Namespace{ { ObjectMeta: metav1.ObjectMeta{ @@ -222,7 +222,7 @@ func TestInitializeFromNamespaces(t *testing.T) { expectedInitalized: true, }, { - name: "when namespaces lack control plane label, it should ignore them", + name: "When namespaces lack control plane label it should ignore them", namespaces: []corev1.Namespace{ { ObjectMeta: metav1.ObjectMeta{ @@ -237,7 +237,7 @@ func TestInitializeFromNamespaces(t *testing.T) { expectedInitalized: true, }, { - name: "when namespaces have invalid UID annotations, it should ignore those UIDs", + name: "When namespaces have invalid UID annotations it should ignore those UIDs", namespaces: []corev1.Namespace{ { ObjectMeta: metav1.ObjectMeta{ @@ -266,7 +266,7 @@ func TestInitializeFromNamespaces(t *testing.T) { expectedInitalized: true, }, { - name: "when namespaces have UIDs outside valid range, it should ignore those UIDs", + name: "When namespaces have UIDs outside valid range it should ignore those UIDs", namespaces: []corev1.Namespace{ { ObjectMeta: metav1.ObjectMeta{ diff --git a/hypershift-operator/controllers/hostedcluster/validations/ocpapiserver_test.go b/hypershift-operator/controllers/hostedcluster/validations/ocpapiserver_test.go index c301176847ec..a0527b8f6773 100644 --- a/hypershift-operator/controllers/hostedcluster/validations/ocpapiserver_test.go +++ b/hypershift-operator/controllers/hostedcluster/validations/ocpapiserver_test.go @@ -50,7 +50,7 @@ func TestValidateOCPAPIServerSANs(t *testing.T) { ipAddresses []string }{ { - name: "custom serving cert, hcp deployed, valid configuration with no conflicts", + name: "When custom serving cert is deployed with valid configuration it should not return errors", customCertSecret: &corev1.Secret{ ObjectMeta: metav1.ObjectMeta{ Name: customServingCertSecretName, @@ -72,7 +72,7 @@ func TestValidateOCPAPIServerSANs(t *testing.T) { expectedErrors: nil, }, { - name: "custom serving cert, hcp not deployed, valid configuration with no conflicts", + name: "When custom serving cert is not deployed with valid configuration it should not return errors", customCertSecret: &corev1.Secret{ ObjectMeta: metav1.ObjectMeta{ Name: customServingCertSecretName, @@ -90,7 +90,7 @@ func TestValidateOCPAPIServerSANs(t *testing.T) { expectedErrors: nil, }, { - name: "invalid certificate format, PKI reconciliation disabled", + name: "When certificate format is invalid and PKI reconciliation is disabled it should not return errors", annotation: hyperv1.DisablePKIReconciliationAnnotation, customCertSecret: &corev1.Secret{ ObjectMeta: metav1.ObjectMeta{ @@ -111,7 +111,7 @@ func TestValidateOCPAPIServerSANs(t *testing.T) { expectedErrors: nil, }, { - name: "invalid certificate format", + name: "When certificate format is invalid it should return an error", customCertSecret: &corev1.Secret{ ObjectMeta: metav1.ObjectMeta{ Name: customServingCertSecretName, @@ -133,7 +133,7 @@ func TestValidateOCPAPIServerSANs(t *testing.T) { }, }, { - name: "missing secret", + name: "When referenced secret is missing it should return an error", namedCertificates: []configv1.APIServerNamedServingCert{ { Names: []string{"test.example.com"}, @@ -145,12 +145,12 @@ func TestValidateOCPAPIServerSANs(t *testing.T) { }, }, { - name: "no custom serving cert, hcp not deployed, valid configuration with no conflicts", + name: "When no custom serving cert is configured and HCP is not deployed it should not return errors", secrets: []client.Object{}, expectedErrors: nil, }, { - name: "conflicting SANs with KAS", + name: "When custom cert SANs conflict with KAS it should return an error", customCertSecret: &corev1.Secret{ ObjectMeta: metav1.ObjectMeta{ @@ -174,7 +174,7 @@ func TestValidateOCPAPIServerSANs(t *testing.T) { }, }, { - name: "invalid certificate data", + name: "When certificate data is invalid it should return an error", customCertSecret: &corev1.Secret{ ObjectMeta: metav1.ObjectMeta{ Name: customServingCertSecretName, @@ -288,19 +288,19 @@ func TestAppendEntriesIfNotExists(t *testing.T) { expected []string }{ { - name: "empty slice and entries", + name: "When slice and entries are empty, it should return an empty slice", slice: []string{}, entries: []string{}, expected: []string{}, }, { - name: "add new entries", + name: "When adding new entries, it should append them to the slice", slice: []string{"a", "b"}, entries: []string{"c", "d"}, expected: []string{"a", "b", "c", "d"}, }, { - name: "add existing and new entries", + name: "When adding existing and new entries, it should only append new ones", slice: []string{"a", "b"}, entries: []string{"b", "c"}, expected: []string{"a", "b", "c"}, @@ -325,99 +325,99 @@ func TestIsDNSNameMatch(t *testing.T) { }{ // Exact matches { - name: "exact match - simple domain", + name: "When DNS name exactly matches a simple domain, it should return true", dnsName: "example.com", pattern: "example.com", expected: true, }, { - name: "exact match - subdomain", + name: "When DNS name exactly matches a subdomain, it should return true", dnsName: "sub.example.com", pattern: "sub.example.com", expected: true, }, { - name: "exact match - multiple subdomains", + name: "When DNS name exactly matches multiple subdomains, it should return true", dnsName: "a.b.c.example.com", pattern: "a.b.c.example.com", expected: true, }, { - name: "no match - different domains", + name: "When DNS names have different domains, it should return false", dnsName: "example.com", pattern: "other.com", expected: false, }, { - name: "no match - different subdomains", + name: "When DNS names have different subdomains, it should return false", dnsName: "sub.example.com", pattern: "other.example.com", expected: false, }, // Wildcard matches { - name: "wildcard match - single level", + name: "When wildcard pattern matches a single level subdomain, it should return true", dnsName: "sub.example.com", pattern: "*.example.com", expected: true, }, { - name: "wildcard match - multiple levels", + name: "When wildcard pattern matches multiple levels, it should return true", dnsName: "baz.foo.bar.com", pattern: "*.foo.bar.com", expected: true, }, { - name: "wildcard no match - too many levels", + name: "When DNS name has too many levels for wildcard, it should return false", dnsName: "sub.sub.example.com", pattern: "*.example.com", expected: false, }, { - name: "wildcard no match - too few levels", + name: "When DNS name has too few levels for wildcard, it should return false", dnsName: "example.com", pattern: "*.example.com", expected: false, }, { - name: "wildcard no match - different domain", + name: "When wildcard pattern has a different domain, it should return false", dnsName: "sub.example.com", pattern: "*.other.com", expected: false, }, { - name: "wildcard no match - partial domain match", + name: "When wildcard pattern partially matches the domain, it should return false", dnsName: "sub.example.com", pattern: "*.example.org", expected: false, }, // Edge cases { - name: "wildcard pattern not at start", + name: "When wildcard is not at the start of the pattern, it should return false", dnsName: "example.com", pattern: "example.*.com", expected: false, }, { - name: "wildcard pattern at end", + name: "When wildcard pattern matches at the TLD level, it should return true", dnsName: "example.com", pattern: "*.com", expected: true, }, { - name: "empty strings", + name: "When both strings are empty, it should return true", dnsName: "", pattern: "", expected: true, }, { - name: "empty dnsName", + name: "When DNS name is empty, it should return false", dnsName: "", pattern: "*.example.com", expected: false, }, { - name: "empty pattern", + name: "When pattern is empty, it should return false", dnsName: "example.com", pattern: "", expected: false, @@ -446,77 +446,77 @@ func TestCheckConflictingSANs(t *testing.T) { expectError bool }{ { - name: "no conflicts", + name: "When entries have no conflicts, it should not return an error", customEntries: []string{"a", "b"}, kasSANEntries: []string{"c", "d"}, entryType: "DNS names", expectError: false, }, { - name: "has conflicts", + name: "When entries have conflicts, it should return an error", customEntries: []string{"a", "b"}, kasSANEntries: []string{"b", "c"}, entryType: "DNS names", expectError: true, }, { - name: "empty entries", + name: "When entries are empty, it should not return an error", customEntries: []string{}, kasSANEntries: []string{}, entryType: "DNS names", expectError: false, }, { - name: "wildcard conflicts - custom entry matches KAS wildcard", + name: "When custom entry matches KAS wildcard, it should return an error", customEntries: []string{"sub.example.com"}, kasSANEntries: []string{"*.example.com"}, entryType: "DNS names", expectError: true, }, { - name: "wildcard conflicts - custom wildcard matches KAS entry", + name: "When custom wildcard matches KAS entry, it should return an error", customEntries: []string{"*.example.com"}, kasSANEntries: []string{"sub.example.com"}, entryType: "DNS names", expectError: true, }, { - name: "wildcard conflicts - both wildcards with same domain", + name: "When both wildcards have the same domain, it should return an error", customEntries: []string{"*.example.com"}, kasSANEntries: []string{"*.example.com"}, entryType: "DNS names", expectError: true, }, { - name: "wildcard conflicts - custom entry matches KAS wildcard with subdomain", + name: "When custom entry matches KAS wildcard with subdomain, it should return an error", customEntries: []string{"baz.foo.bar.com"}, kasSANEntries: []string{"*.foo.bar.com"}, entryType: "DNS names", expectError: true, }, { - name: "no wildcard conflicts - custom entry doesn't match KAS wildcard", + name: "When custom entry does not match KAS wildcard, it should not return an error", customEntries: []string{"sub.sub.example.com"}, kasSANEntries: []string{"*.example.com"}, entryType: "DNS names", expectError: false, }, { - name: "no wildcard conflicts - different domains", + name: "When wildcard entries have different domains, it should not return an error", customEntries: []string{"sub.example.com"}, kasSANEntries: []string{"*.other.com"}, entryType: "DNS names", expectError: false, }, { - name: "no wildcard conflicts - custom wildcard doesn't match KAS entry", + name: "When custom wildcard does not match KAS entry, it should not return an error", customEntries: []string{"*.example.com"}, kasSANEntries: []string{"other.com"}, entryType: "DNS names", expectError: false, }, { - name: "mixed conflicts - exact match and wildcard match", + name: "When entries have both exact match and wildcard conflicts, it should return an error", customEntries: []string{"exact.example.com", "sub.example.com"}, kasSANEntries: []string{"exact.example.com", "*.example.com"}, entryType: "DNS names", diff --git a/hypershift-operator/controllers/hostedclustersizing/hostedclustersizing_controller_test.go b/hypershift-operator/controllers/hostedclustersizing/hostedclustersizing_controller_test.go index cdacd1affe91..dd4625b194ed 100644 --- a/hypershift-operator/controllers/hostedclustersizing/hostedclustersizing_controller_test.go +++ b/hypershift-operator/controllers/hostedclustersizing/hostedclustersizing_controller_test.go @@ -76,7 +76,7 @@ func TestSizingController_Reconcile(t *testing.T) { expectedErr bool }{ { - name: "invalid config, do nothing", + name: "When config is invalid it should do nothing", hostedCluster: &hypershiftv1beta1.HostedCluster{ObjectMeta: metav1.ObjectMeta{Namespace: "ns", Name: "hc"}}, config: &schedulingv1alpha1.ClusterSizingConfiguration{ Status: schedulingv1alpha1.ClusterSizingConfigurationStatus{ @@ -85,12 +85,12 @@ func TestSizingController_Reconcile(t *testing.T) { }, }, { - name: "deleting hosted cluster, do nothing", + name: "When hosted cluster is being deleted it should do nothing", hostedCluster: &hypershiftv1beta1.HostedCluster{ObjectMeta: metav1.ObjectMeta{Namespace: "ns", Name: "hc", DeletionTimestamp: ptr.To(metav1.NewTime(fakeClock.Now()))}}, config: validCommonConfig, }, { - name: "paused cluster, wait", + name: "When cluster is paused, it should wait", hostedCluster: &hypershiftv1beta1.HostedCluster{ ObjectMeta: metav1.ObjectMeta{Namespace: "ns", Name: "hc"}, Spec: hypershiftv1beta1.HostedClusterSpec{ @@ -101,7 +101,7 @@ func TestSizingController_Reconcile(t *testing.T) { expected: &action{requeueAfter: 10 * time.Minute}, }, { - name: "transition, hcco doesn't report node count", + name: "When transitioning and HCCO does not report node count, it should compute size from node pools", config: validCommonConfig, hostedCluster: &hypershiftv1beta1.HostedCluster{ObjectMeta: metav1.ObjectMeta{Namespace: "ns", Name: "hc"}}, listHostedClusters: func(_ context.Context) (*hypershiftv1beta1.HostedClusterList, error) { @@ -147,7 +147,7 @@ func TestSizingController_Reconcile(t *testing.T) { }}, }, { - name: "transition, hcco reports node count", + name: "When transitioning and HCCO reports node count, it should compute size from HCP", config: validCommonConfig, hostedCluster: &hypershiftv1beta1.HostedCluster{ObjectMeta: metav1.ObjectMeta{Namespace: "ns", Name: "hc"}}, listHostedClusters: func(_ context.Context) (*hypershiftv1beta1.HostedClusterList, error) { @@ -191,7 +191,7 @@ func TestSizingController_Reconcile(t *testing.T) { }}, }, { - name: "pending transition, hcco doesn't report node count", + name: "When transition is pending and HCCO does not report node count, it should delay transition", config: validCommonConfig, hostedCluster: &hypershiftv1beta1.HostedCluster{ ObjectMeta: metav1.ObjectMeta{Namespace: "ns", Name: "hc"}, @@ -239,7 +239,7 @@ func TestSizingController_Reconcile(t *testing.T) { }, requeueAfter: 29 * time.Second}, }, { - name: "pending transition, hcco reports node count", + name: "When transition is pending and HCCO reports node count, it should delay transition", config: validCommonConfig, hostedCluster: &hypershiftv1beta1.HostedCluster{ ObjectMeta: metav1.ObjectMeta{Namespace: "ns", Name: "hc"}, @@ -285,7 +285,7 @@ func TestSizingController_Reconcile(t *testing.T) { }, requeueAfter: 29 * time.Second}, }, { - name: "transition, previously computed, hcco reports node count", + name: "When previously computed and HCCO reports node count, it should transition", config: validCommonConfig, hostedCluster: &hypershiftv1beta1.HostedCluster{ ObjectMeta: metav1.ObjectMeta{Namespace: "ns", Name: "hc"}, @@ -338,7 +338,7 @@ func TestSizingController_Reconcile(t *testing.T) { }}, }, { - name: "transition, previously computed, hcco does not report node count", + name: "When previously computed and HCCO does not report node count, it should transition", config: validCommonConfig, hostedCluster: &hypershiftv1beta1.HostedCluster{ ObjectMeta: metav1.ObjectMeta{Namespace: "ns", Name: "hc"}, @@ -395,7 +395,7 @@ func TestSizingController_Reconcile(t *testing.T) { }}, }, { - name: "transition, previously computed and tagged, hcco reports node count", + name: "When previously computed and tagged with HCCO reporting node count, it should transition", config: validCommonConfig, hostedCluster: &hypershiftv1beta1.HostedCluster{ ObjectMeta: metav1.ObjectMeta{Namespace: "ns", Name: "hc", Labels: map[string]string{hypershiftv1beta1.HostedClusterSizeLabel: "medium"}}, @@ -457,7 +457,7 @@ func TestSizingController_Reconcile(t *testing.T) { }}, }, { - name: "transition, previously computed and tagged, hcco reports node count, kas unavailable", + name: "When previously computed and tagged with KAS unavailable, it should transition", config: validCommonConfig, hostedCluster: &hypershiftv1beta1.HostedCluster{ ObjectMeta: metav1.ObjectMeta{Namespace: "ns", Name: "hc", Labels: map[string]string{hypershiftv1beta1.HostedClusterSizeLabel: "medium"}}, @@ -519,7 +519,7 @@ func TestSizingController_Reconcile(t *testing.T) { }}, }, { - name: "transition, previously computed and tagged, hcco does not report node count, no autoscaling, kas unavailable", + name: "When previously computed without autoscaling and KAS unavailable, it should transition", config: validCommonConfig, hostedCluster: &hypershiftv1beta1.HostedCluster{ ObjectMeta: metav1.ObjectMeta{Namespace: "ns", Name: "hc", Labels: map[string]string{hypershiftv1beta1.HostedClusterSizeLabel: "medium"}}, @@ -588,7 +588,7 @@ func TestSizingController_Reconcile(t *testing.T) { }}, }, { - name: "transition, previously computed and tagged, hcco does not report node count, has autoscaling, kas unavailable", + name: "When previously computed with autoscaling and KAS unavailable, it should not transition", config: validCommonConfig, hostedCluster: &hypershiftv1beta1.HostedCluster{ ObjectMeta: metav1.ObjectMeta{Namespace: "ns", Name: "hc", Labels: map[string]string{hypershiftv1beta1.HostedClusterSizeLabel: "medium"}}, @@ -630,7 +630,7 @@ func TestSizingController_Reconcile(t *testing.T) { expected: nil, }, { - name: "label, have previous condition", + name: "When previous condition exists, it should apply size label", config: validCommonConfig, hostedCluster: &hypershiftv1beta1.HostedCluster{ ObjectMeta: metav1.ObjectMeta{Namespace: "ns", Name: "hc"}, @@ -662,7 +662,7 @@ func TestSizingController_Reconcile(t *testing.T) { }}, }, { - name: "label, have previous condition, even when current calculation is different", + name: "When previous condition exists with different current calculation, it should apply size label from condition", config: validCommonConfig, hostedCluster: &hypershiftv1beta1.HostedCluster{ ObjectMeta: metav1.ObjectMeta{Namespace: "ns", Name: "hc"}, @@ -694,7 +694,7 @@ func TestSizingController_Reconcile(t *testing.T) { }}, }, { - name: "delay due to hosted cluster delay for increase", + name: "When increasing size within delay period, it should report transition pending", config: validCommonConfig, hostedCluster: &hypershiftv1beta1.HostedCluster{ ObjectMeta: metav1.ObjectMeta{ @@ -759,7 +759,7 @@ func TestSizingController_Reconcile(t *testing.T) { }, requeueAfter: 29 * time.Second}, }, { - name: "delay due to hosted cluster delay for decrease", + name: "When decreasing size within delay period, it should report transition pending", config: validCommonConfig, hostedCluster: &hypershiftv1beta1.HostedCluster{ ObjectMeta: metav1.ObjectMeta{ @@ -824,7 +824,7 @@ func TestSizingController_Reconcile(t *testing.T) { }, requeueAfter: 9 * time.Minute}, }, { - name: "delay due to hosted cluster delay, update target size during delay", + name: "When target size changes during delay period, it should update transition required reason", config: validCommonConfig, hostedCluster: &hypershiftv1beta1.HostedCluster{ ObjectMeta: metav1.ObjectMeta{ @@ -889,7 +889,7 @@ func TestSizingController_Reconcile(t *testing.T) { }, requeueAfter: 9 * time.Minute}, }, { - name: "transition, longer than delay", + name: "When delay period has elapsed, it should complete the transition", config: validCommonConfig, hostedCluster: &hypershiftv1beta1.HostedCluster{ ObjectMeta: metav1.ObjectMeta{ @@ -954,7 +954,7 @@ func TestSizingController_Reconcile(t *testing.T) { }}, }, { - name: "no-op, delay already exposed in status, preserves requeue", + name: "When delay is already exposed in status, it should preserve requeue", config: validCommonConfig, hostedCluster: &hypershiftv1beta1.HostedCluster{ ObjectMeta: metav1.ObjectMeta{ @@ -998,7 +998,7 @@ func TestSizingController_Reconcile(t *testing.T) { expected: &action{requeueAfter: 8 * time.Minute}, }, { - name: "delay for concurrency", + name: "When concurrency limit is reached, it should delay transition", config: validCommonConfig, hostedCluster: &hypershiftv1beta1.HostedCluster{ ObjectMeta: metav1.ObjectMeta{ @@ -1070,7 +1070,7 @@ func TestSizingController_Reconcile(t *testing.T) { }, requeueAfter: 5 * time.Minute}, }, { - name: "delay existing scheduled cluster without size for concurrency", + name: "When existing scheduled cluster has no size and concurrency limit is reached, it should delay transition", config: validCommonConfig, hostedCluster: &hypershiftv1beta1.HostedCluster{ ObjectMeta: metav1.ObjectMeta{ @@ -1118,7 +1118,7 @@ func TestSizingController_Reconcile(t *testing.T) { }, requeueAfter: 5 * time.Minute}, }, { - name: "delay for concurrency, no-op since condition already present, preserves requeue", + name: "When concurrency delay condition is already present, it should preserve requeue", config: validCommonConfig, hostedCluster: &hypershiftv1beta1.HostedCluster{ ObjectMeta: metav1.ObjectMeta{ @@ -1169,7 +1169,7 @@ func TestSizingController_Reconcile(t *testing.T) { expected: &action{requeueAfter: 5 * time.Minute}, }, { - name: "delay for concurrency, undo conditions since cluster returned to original size during delay", + name: "When cluster returns to original size during concurrency delay, it should undo transition conditions", config: validCommonConfig, hostedCluster: &hypershiftv1beta1.HostedCluster{ ObjectMeta: metav1.ObjectMeta{ @@ -1241,7 +1241,7 @@ func TestSizingController_Reconcile(t *testing.T) { }}, }, { - name: "transition, not enough previous transitions to limit concurrency", + name: "When previous transitions do not exceed concurrency limit, it should complete the transition", config: validCommonConfig, hostedCluster: &hypershiftv1beta1.HostedCluster{ ObjectMeta: metav1.ObjectMeta{ @@ -1312,7 +1312,7 @@ func TestSizingController_Reconcile(t *testing.T) { }}, }, { - name: "transition, don't delay unscheduled cluster for concurrency", + name: "When cluster is unscheduled, it should not delay for concurrency", config: validCommonConfig, hostedCluster: &hypershiftv1beta1.HostedCluster{ ObjectMeta: metav1.ObjectMeta{ @@ -1380,7 +1380,7 @@ func TestSizingController_Reconcile(t *testing.T) { }}, }, { - name: "transition, don't delay brand new cluster for concurrency", + name: "When cluster is brand new, it should not delay for concurrency", config: validCommonConfig, hostedCluster: &hypershiftv1beta1.HostedCluster{ ObjectMeta: metav1.ObjectMeta{ @@ -1434,7 +1434,7 @@ func TestSizingController_Reconcile(t *testing.T) { }}, }, { - name: "transition, use override size", + name: "When override size annotation is set, it should use the override size", config: validCommonConfig, hostedCluster: &hypershiftv1beta1.HostedCluster{ ObjectMeta: metav1.ObjectMeta{ @@ -1491,7 +1491,7 @@ func TestSizingController_Reconcile(t *testing.T) { }}, }, { - name: "transition, use resource based autoscaling", + name: "When resource based autoscaling is enabled, it should use recommended size", config: validCommonConfig, hostedCluster: &hypershiftv1beta1.HostedCluster{ ObjectMeta: metav1.ObjectMeta{ @@ -1549,7 +1549,7 @@ func TestSizingController_Reconcile(t *testing.T) { }}, }, { - name: "happy case: cluster has not changed size, already has condition and label", + name: "When cluster has not changed size and already has condition and label it should be a no-op", config: validCommonConfig, hostedCluster: &hypershiftv1beta1.HostedCluster{ ObjectMeta: metav1.ObjectMeta{ diff --git a/hypershift-operator/controllers/nodepool/apiserver-haproxy/haproxy_test.go b/hypershift-operator/controllers/nodepool/apiserver-haproxy/haproxy_test.go index c938f1a99620..1230898bccfa 100644 --- a/hypershift-operator/controllers/nodepool/apiserver-haproxy/haproxy_test.go +++ b/hypershift-operator/controllers/nodepool/apiserver-haproxy/haproxy_test.go @@ -132,82 +132,82 @@ func TestShouldSkipProxyForKAS(t *testing.T) { expected bool }{ { - name: "When noProxy is empty it should not skip proxy", + name: "When noProxy is empty, it should not skip proxy", noProxy: "", expected: false, }, { - name: "When noProxy contains exact external address it should skip proxy", + name: "When noProxy contains exact external address, it should skip proxy", noProxy: "localhost,127.0.0.1," + externalAddress, expected: true, }, { - name: "When noProxy contains exact internal address it should skip proxy", + name: "When noProxy contains exact internal address, it should skip proxy", noProxy: "localhost,127.0.0.1," + internalAddress, expected: true, }, { - name: "When noProxy contains leading-dot domain matching external address it should skip proxy", + name: "When noProxy contains leading-dot domain matching external address, it should skip proxy", noProxy: "localhost,.example.com", expected: true, }, { - name: "When noProxy contains bare parent domain matching external address it should skip proxy", + name: "When noProxy contains bare parent domain matching external address, it should skip proxy", noProxy: "localhost,example.com", expected: true, }, { - name: "When noProxy contains leading-dot partial domain matching external address it should skip proxy", + name: "When noProxy contains leading-dot partial domain matching external address, it should skip proxy", noProxy: "localhost,.test.example.com", expected: true, }, { - name: "When noProxy contains CIDR covering internal address it should skip proxy", + name: "When noProxy contains CIDR covering internal address, it should skip proxy", noProxy: "localhost,172.16.0.0/12", expected: true, }, { - name: "When noProxy contains kubernetes keyword it should skip proxy", + name: "When noProxy contains kubernetes keyword, it should skip proxy", noProxy: "localhost,kubernetes.svc,127.0.0.1", expected: true, }, { - name: "When noProxy contains exact service network CIDR it should skip proxy", + name: "When noProxy contains exact service network CIDR, it should skip proxy", noProxy: "localhost," + serviceNetwork, expected: true, }, { - name: "When noProxy contains exact cluster network CIDR it should skip proxy", + name: "When noProxy contains exact cluster network CIDR, it should skip proxy", noProxy: "localhost," + clusterNetwork, expected: true, }, { - name: "When noProxy contains wildcard it should skip proxy", + name: "When noProxy contains wildcard, it should skip proxy", noProxy: "*", expected: true, }, { - name: "When noProxy contains unrelated entries it should not skip proxy", + name: "When noProxy contains unrelated entries, it should not skip proxy", noProxy: "localhost,127.0.0.1,.other-domain.com,192.168.0.0/16", expected: false, }, { - name: "When noProxy has extra whitespace around entries it should still match", + name: "When noProxy has extra whitespace around entries, it should still match", noProxy: " localhost , .example.com , 127.0.0.1 ", expected: true, }, { - name: "When noProxy contains port-qualified domain matching KAS port it should skip proxy", + name: "When noProxy contains port-qualified domain matching KAS port, it should skip proxy", noProxy: "localhost,api.test.example.com:6443", expected: true, }, { - name: "When noProxy contains port-qualified IP matching KAS port it should skip proxy", + name: "When noProxy contains port-qualified IP matching KAS port, it should skip proxy", noProxy: "localhost,172.20.0.1:6443", expected: true, }, { - name: "When noProxy contains port-qualified domain with non-matching port it should not skip proxy", + name: "When noProxy contains port-qualified domain with non-matching port, it should not skip proxy", noProxy: "localhost,api.test.example.com:8080", expected: false, }, @@ -548,22 +548,22 @@ func TestJoinDefaultPortIfMissing(t *testing.T) { wantErr bool }{ { - name: "When HTTPS URL has no port it should add port 443", + name: "When HTTPS URL has no port, it should add port 443", addr: "https://proxy.example.com", expected: "https://proxy.example.com:443", }, { - name: "When HTTP URL has no port it should add port 80", + name: "When HTTP URL has no port, it should add port 80", addr: "http://proxy.example.com", expected: "http://proxy.example.com:80", }, { - name: "When HTTPS URL already has a port it should keep existing port", + name: "When HTTPS URL already has a port, it should keep existing port", addr: "https://proxy.example.com:8443", expected: "https://proxy.example.com:8443", }, { - name: "When URL has no scheme it should return an error", + name: "When URL has no scheme, it should return an error", addr: "proxy.example.com", wantErr: true, }, diff --git a/hypershift-operator/controllers/nodepool/aws_test.go b/hypershift-operator/controllers/nodepool/aws_test.go index 72fde5ebf7ad..3ff9bf4258ad 100644 --- a/hypershift-operator/controllers/nodepool/aws_test.go +++ b/hypershift-operator/controllers/nodepool/aws_test.go @@ -58,7 +58,7 @@ func TestAWSMachineTemplateSpec(t *testing.T) { checkError func(*testing.T, error) }{ { - name: "ebs size", + name: "When ebs volume is configured, it should set the root volume size", nodePool: hyperv1.NodePoolSpec{ ClusterName: "", Replicas: nil, @@ -78,7 +78,7 @@ func TestAWSMachineTemplateSpec(t *testing.T) { expected: defaultAWSMachineTemplate(withRootVolume(&volume)), }, { - name: "Tags from nodepool get copied", + name: "When nodepool has resource tags, it should copy them to the template", nodePool: hyperv1.NodePoolSpec{Platform: hyperv1.NodePoolPlatform{AWS: &hyperv1.AWSNodePoolPlatform{ ResourceTags: []hyperv1.AWSResourceTag{ {Key: "key", Value: "value"}, @@ -91,7 +91,7 @@ func TestAWSMachineTemplateSpec(t *testing.T) { }), }, { - name: "Tags from cluster get copied", + name: "When cluster has resource tags, it should copy them to the template", cluster: hyperv1.HostedClusterSpec{Platform: hyperv1.PlatformSpec{AWS: &hyperv1.AWSPlatformSpec{ ResourceTags: []hyperv1.AWSResourceTag{ {Key: "key", Value: "value"}, @@ -106,7 +106,7 @@ func TestAWSMachineTemplateSpec(t *testing.T) { }), }, { - name: "Cluster tags take precedence over nodepool tags", + name: "When both cluster and nodepool have tags, it should give cluster tags precedence", cluster: hyperv1.HostedClusterSpec{Platform: hyperv1.PlatformSpec{AWS: &hyperv1.AWSPlatformSpec{ ResourceTags: []hyperv1.AWSResourceTag{ {Key: "cluster-only", Value: "value"}, @@ -128,7 +128,7 @@ func TestAWSMachineTemplateSpec(t *testing.T) { }), }, { - name: "Cluster default sg is used when none specified", + name: "When no security group is specified, it should use the cluster default sg", clusterStatus: &hyperv1.HostedClusterStatus{Platform: &hyperv1.PlatformStatus{AWS: &hyperv1.AWSPlatformStatus{DefaultWorkerSecurityGroupID: "cluster-default"}}}, nodePool: hyperv1.NodePoolSpec{Platform: hyperv1.NodePoolPlatform{AWS: &hyperv1.AWSNodePoolPlatform{ AMI: amiName, @@ -138,7 +138,7 @@ func TestAWSMachineTemplateSpec(t *testing.T) { }), }, { - name: "NodePool sg is used in addition to cluster default", + name: "When nodepool has security groups, it should use them in addition to cluster default", nodePool: hyperv1.NodePoolSpec{Platform: hyperv1.NodePoolPlatform{AWS: &hyperv1.AWSNodePoolPlatform{ SecurityGroups: []hyperv1.AWSResourceReference{{ID: ptr.To("nodepool-specific")}}, AMI: amiName, @@ -148,7 +148,7 @@ func TestAWSMachineTemplateSpec(t *testing.T) { }), }, { - name: "NotReady error is returned if no sg specified and no cluster sg is available", + name: "When no sg is specified and no cluster sg is available, it should return NotReady error", clusterStatus: &hyperv1.HostedClusterStatus{Platform: &hyperv1.PlatformStatus{AWS: &hyperv1.AWSPlatformStatus{DefaultWorkerSecurityGroupID: ""}}}, checkError: func(t *testing.T, err error) { var notReadyErr *NotReadyError @@ -161,7 +161,7 @@ func TestAWSMachineTemplateSpec(t *testing.T) { }}}, }, { - name: "NodePool has ec2-http-tokens annotation with 'required' as a value", + name: "When nodePool has ec2-http-tokens annotation set to required, it should set HTTPTokens to required", nodePool: hyperv1.NodePoolSpec{Platform: hyperv1.NodePoolPlatform{AWS: &hyperv1.AWSNodePoolPlatform{ AMI: amiName, }}}, @@ -173,7 +173,7 @@ func TestAWSMachineTemplateSpec(t *testing.T) { }), }, { - name: "Windows ImageType without AMI specified should use Windows AMI mapping", + name: "When Windows ImageType is set without AMI specified, it should use Windows AMI mapping", cluster: hyperv1.HostedClusterSpec{Platform: hyperv1.PlatformSpec{AWS: &hyperv1.AWSPlatformSpec{ Region: "us-east-1", }}}, @@ -188,7 +188,7 @@ func TestAWSMachineTemplateSpec(t *testing.T) { }), }, { - name: "Windows ImageType with AMI specified should use specified AMI", + name: "When Windows ImageType is set with AMI specified, it should use the specified AMI", cluster: hyperv1.HostedClusterSpec{Platform: hyperv1.PlatformSpec{AWS: &hyperv1.AWSPlatformSpec{ Region: "us-east-1", }}}, @@ -386,7 +386,7 @@ func TestAWSMachineTemplate(t *testing.T) { expectedTags capiaws.Tags }{ { - name: "Migration: should avoid rollout on existing nodepools by reusing existing template name when nothing changes", + name: "When nothing changes on existing nodepools, it should reuse existing template name to avoid rollout", nodePool: &hyperv1.NodePool{ ObjectMeta: metav1.ObjectMeta{Name: "stable-nodepool"}, Spec: hyperv1.NodePoolSpec{ @@ -407,7 +407,7 @@ func TestAWSMachineTemplate(t *testing.T) { expectedTags: capiaws.Tags{"version": "stable"}, }, { - name: "should reuse existing template name when only tags change", + name: "When only tags change, it should reuse existing template name", nodePool: &hyperv1.NodePool{ ObjectMeta: metav1.ObjectMeta{Name: "test-nodepool"}, Spec: hyperv1.NodePoolSpec{ @@ -428,7 +428,7 @@ func TestAWSMachineTemplate(t *testing.T) { expectedTags: capiaws.Tags{"version": "new"}, }, { - name: "should create a new template name when instanceType changes", + name: "When instanceType changes, it should create a new template name", nodePool: &hyperv1.NodePool{ // Desired state has a new instance type. ObjectMeta: metav1.ObjectMeta{Name: "test-nodepool-structural"}, Spec: hyperv1.NodePoolSpec{ @@ -456,7 +456,7 @@ func TestAWSMachineTemplate(t *testing.T) { expectedTags: capiaws.Tags{"version": "new"}, }, { - name: "should create new template when none exists", + name: "When no template exists, it should create a new template", nodePool: &hyperv1.NodePool{ ObjectMeta: metav1.ObjectMeta{Name: "new-nodepool"}, Spec: hyperv1.NodePoolSpec{ @@ -482,7 +482,7 @@ func TestAWSMachineTemplate(t *testing.T) { }, { - name: "should find template via MachineSet when UpgradeType is InPlace", + name: "When UpgradeType is InPlace, it should find template via MachineSet", nodePool: &hyperv1.NodePool{ ObjectMeta: metav1.ObjectMeta{Name: "inplace-nodepool"}, Spec: hyperv1.NodePoolSpec{ @@ -617,7 +617,7 @@ func TestValidateAWSPlatformConfig(t *testing.T) { expectedError string }{ { - name: "If hostedCluster < 4.19 it should fail", + name: "When hostedCluster version is below 4.19, it should fail", hostedClusterVersion: "4.18.0", expectedError: "capacityReservation is only supported on 4.19+ clusters", }, @@ -680,14 +680,14 @@ func TestGetWindowsAMI(t *testing.T) { expectedError string }{ { - name: "nil release image", + name: "When release image is nil, it should return error", region: "us-east-1", arch: hyperv1.ArchitectureAMD64, releaseImage: nil, expectedError: "release image is nil", }, { - name: "nil stream metadata", + name: "When stream metadata is nil, it should return error", region: "us-east-1", arch: hyperv1.ArchitectureAMD64, releaseImage: &releaseinfo.ReleaseImage{ @@ -701,7 +701,7 @@ func TestGetWindowsAMI(t *testing.T) { expectedError: "release image stream metadata is nil", }, { - name: "architecture not found", + name: "When architecture is not found, it should return error", region: "us-east-1", arch: hyperv1.ArchitectureAMD64, releaseImage: &releaseinfo.ReleaseImage{ @@ -755,7 +755,7 @@ func TestGetWindowsAMI(t *testing.T) { expectedError: "no aws-winli regions data found in release image metadata", }, { - name: "no aws-winli regions data", + name: "When aws-winli regions data is nil, it should return error", region: "us-east-1", arch: hyperv1.ArchitectureAMD64, releaseImage: &releaseinfo.ReleaseImage{ @@ -779,7 +779,7 @@ func TestGetWindowsAMI(t *testing.T) { expectedError: "no aws-winli regions data found in release image metadata", }, { - name: "unsupported region", + name: "When region is unsupported, it should return error", region: "unsupported-region", arch: hyperv1.ArchitectureAMD64, releaseImage: &releaseinfo.ReleaseImage{ @@ -808,7 +808,7 @@ func TestGetWindowsAMI(t *testing.T) { expectedError: "no Windows AMI found for region unsupported-region in release image metadata", }, { - name: "empty AMI image", + name: "When AMI image is empty for region, it should return error", region: "us-east-1", arch: hyperv1.ArchitectureAMD64, releaseImage: &releaseinfo.ReleaseImage{ @@ -837,7 +837,7 @@ func TestGetWindowsAMI(t *testing.T) { expectedError: "windows AMI image is empty for region us-east-1 in release image metadata", }, { - name: "successful Windows AMI lookup", + name: "When looking up Windows AMI for us-east-1, it should return correct AMI", region: "us-east-1", arch: hyperv1.ArchitectureAMD64, releaseImage: &releaseinfo.ReleaseImage{ @@ -870,7 +870,7 @@ func TestGetWindowsAMI(t *testing.T) { expectedAMI: "ami-0abcdef1234567890", }, { - name: "successful Windows AMI lookup for different region", + name: "When looking up Windows AMI for eu-west-1, it should return correct AMI", region: "eu-west-1", arch: hyperv1.ArchitectureAMD64, releaseImage: &releaseinfo.ReleaseImage{ @@ -1124,7 +1124,7 @@ func TestSetAWSConditions(t *testing.T) { expectedCondValue: corev1.ConditionTrue, }, { - name: "When stream metadata is nil it should set ValidPlatformImage to false", + name: "When stream metadata is nil, it should set ValidPlatformImage to false", nodePool: &hyperv1.NodePool{ Spec: hyperv1.NodePoolSpec{ Arch: hyperv1.ArchitectureAMD64, @@ -1146,7 +1146,7 @@ func TestSetAWSConditions(t *testing.T) { expectedCondValue: corev1.ConditionFalse, }, { - name: "When region has no AMI it should set ValidPlatformImage to false", + name: "When region has no AMI, it should set ValidPlatformImage to false", nodePool: &hyperv1.NodePool{ Spec: hyperv1.NodePoolSpec{ Arch: hyperv1.ArchitectureAMD64, @@ -1165,7 +1165,7 @@ func TestSetAWSConditions(t *testing.T) { expectedCondValue: corev1.ConditionFalse, }, { - name: "When osImageStream is invalid for the release version it should return error", + name: "When osImageStream is invalid for the release version, it should return error", nodePool: &hyperv1.NodePool{ Spec: hyperv1.NodePoolSpec{ Arch: hyperv1.ArchitectureAMD64, @@ -1183,7 +1183,7 @@ func TestSetAWSConditions(t *testing.T) { expectError: true, }, { - name: "When HostedCluster has no AWS platform it should return error", + name: "When HostedCluster has no AWS platform, it should return error", nodePool: &hyperv1.NodePool{ Spec: hyperv1.NodePoolSpec{ Arch: hyperv1.ArchitectureAMD64, diff --git a/hypershift-operator/controllers/nodepool/capi_test.go b/hypershift-operator/controllers/nodepool/capi_test.go index b671d68cae91..b1cbbf73e916 100644 --- a/hypershift-operator/controllers/nodepool/capi_test.go +++ b/hypershift-operator/controllers/nodepool/capi_test.go @@ -104,8 +104,7 @@ func TestSetMachineSetReplicas(t *testing.T) { expectAutoscalerAnnotations map[string]string }{ { - name: "it sets current replicas to 1 and set annotations when autoscaling is enabled" + - " and the MachineSet has nil replicas", + name: "When autoscaling is enabled and the MachineSet has nil replicas, it should set current replicas to 1 and set annotations", nodePool: &hyperv1.NodePool{ ObjectMeta: metav1.ObjectMeta{}, Spec: hyperv1.NodePoolSpec{ @@ -130,8 +129,7 @@ func TestSetMachineSetReplicas(t *testing.T) { }, }, { - name: "it does not set current replicas but set annotations when autoscaling is enabled" + - " and the MachineSet has nil replicas", + name: "When autoscaling is enabled and the MachineSet has nil replicas with min=2, it should set replicas to min and set annotations", nodePool: &hyperv1.NodePool{ ObjectMeta: metav1.ObjectMeta{}, Spec: hyperv1.NodePoolSpec{ @@ -156,8 +154,7 @@ func TestSetMachineSetReplicas(t *testing.T) { }, }, { - name: "it sets current replicas to autoScaling.min and set annotations when autoscaling is enabled" + - " and the MachineSet has replicas < autoScaling.min", + name: "When autoscaling is enabled and the MachineSet has replicas below min, it should set replicas to autoScaling.min", nodePool: &hyperv1.NodePool{ ObjectMeta: metav1.ObjectMeta{}, Spec: hyperv1.NodePoolSpec{ @@ -182,8 +179,7 @@ func TestSetMachineSetReplicas(t *testing.T) { }, }, { - name: "it sets current replicas to autoScaling.max and set annotations when autoscaling is enabled" + - " and the MachineSet has replicas > autoScaling.max", + name: "When autoscaling is enabled and the MachineSet has replicas above max, it should set replicas to autoScaling.max", nodePool: &hyperv1.NodePool{ ObjectMeta: metav1.ObjectMeta{}, Spec: hyperv1.NodePoolSpec{ @@ -259,7 +255,7 @@ func TestSetMachineSetReplicas(t *testing.T) { }, }, { - name: "it enforces min=1 for KubeVirt platform even when NodePool specifies min=0", + name: "When KubeVirt platform specifies min=0, it should enforce min=1", nodePool: &hyperv1.NodePool{ ObjectMeta: metav1.ObjectMeta{}, Spec: hyperv1.NodePoolSpec{ @@ -287,7 +283,7 @@ func TestSetMachineSetReplicas(t *testing.T) { }, }, { - name: "it enforces min=1 for Agent platform even when NodePool specifies min=0", + name: "When Agent platform specifies min=0, it should enforce min=1", nodePool: &hyperv1.NodePool{ ObjectMeta: metav1.ObjectMeta{}, Spec: hyperv1.NodePoolSpec{ @@ -337,7 +333,7 @@ func TestSetMachineDeploymentReplicas(t *testing.T) { expectAutoscalerAnnotations map[string]string }{ { - name: "it sets replicas when autoscaling is disabled", + name: "When autoscaling is disabled, it should set replicas directly", nodePool: &hyperv1.NodePool{ ObjectMeta: metav1.ObjectMeta{}, Spec: hyperv1.NodePoolSpec{ @@ -356,7 +352,7 @@ func TestSetMachineDeploymentReplicas(t *testing.T) { }, }, { - name: "it keeps current replicas and set annotations when autoscaling is enabled", + name: "When autoscaling is enabled and replicas are within range, it should keep current replicas and set annotations", nodePool: &hyperv1.NodePool{ ObjectMeta: metav1.ObjectMeta{}, Spec: hyperv1.NodePoolSpec{ @@ -381,8 +377,7 @@ func TestSetMachineDeploymentReplicas(t *testing.T) { }, }, { - name: "it sets current replicas to 1 and set annotations when autoscaling is enabled" + - " and the MachineDeployment has not been created yet", + name: "When autoscaling is enabled and the MachineDeployment has not been created yet, it should set replicas to 1", nodePool: &hyperv1.NodePool{ ObjectMeta: metav1.ObjectMeta{}, Spec: hyperv1.NodePoolSpec{ @@ -400,8 +395,7 @@ func TestSetMachineDeploymentReplicas(t *testing.T) { }, }, { - name: "it sets current replicas to 1 and set annotations when autoscaling is enabled" + - " and the MachineDeployment has 0 replicas", + name: "When autoscaling is enabled and the MachineDeployment has 0 replicas, it should set replicas to 1", nodePool: &hyperv1.NodePool{ ObjectMeta: metav1.ObjectMeta{}, Spec: hyperv1.NodePoolSpec{ @@ -426,8 +420,7 @@ func TestSetMachineDeploymentReplicas(t *testing.T) { }, }, { - name: "it sets current replicas to 1 and set annotations when autoscaling is enabled" + - " and the MachineDeployment has nil replicas", + name: "When autoscaling is enabled and the MachineDeployment has nil replicas, it should set replicas to 1", nodePool: &hyperv1.NodePool{ ObjectMeta: metav1.ObjectMeta{}, Spec: hyperv1.NodePoolSpec{ @@ -452,8 +445,7 @@ func TestSetMachineDeploymentReplicas(t *testing.T) { }, }, { - name: "it does not set current replicas but set annotations when autoscaling is enabled" + - " and the MachineDeployment has nil replicas", + name: "When autoscaling is enabled and the MachineDeployment has nil replicas with min=2, it should set replicas to min", nodePool: &hyperv1.NodePool{ ObjectMeta: metav1.ObjectMeta{}, Spec: hyperv1.NodePoolSpec{ @@ -478,8 +470,7 @@ func TestSetMachineDeploymentReplicas(t *testing.T) { }, }, { - name: "it sets current replicas to autoScaling.min and set annotations when autoscaling is enabled" + - " and the MachineDeployment has replicas < autoScaling.min", + name: "When autoscaling is enabled and the MachineDeployment has replicas below min, it should set replicas to autoScaling.min", nodePool: &hyperv1.NodePool{ ObjectMeta: metav1.ObjectMeta{}, Spec: hyperv1.NodePoolSpec{ @@ -504,8 +495,7 @@ func TestSetMachineDeploymentReplicas(t *testing.T) { }, }, { - name: "it sets current replicas to autoScaling.max and set annotations when autoscaling is enabled" + - " and the MachineDeployment has replicas > autoScaling.max", + name: "When autoscaling is enabled and the MachineDeployment has replicas above max, it should set replicas to autoScaling.max", nodePool: &hyperv1.NodePool{ ObjectMeta: metav1.ObjectMeta{}, Spec: hyperv1.NodePoolSpec{ @@ -581,7 +571,7 @@ func TestSetMachineDeploymentReplicas(t *testing.T) { }, }, { - name: "it enforces min=1 for KubeVirt platform even when NodePool specifies min=0", + name: "When KubeVirt platform specifies min=0, it should enforce min=1", nodePool: &hyperv1.NodePool{ ObjectMeta: metav1.ObjectMeta{}, Spec: hyperv1.NodePoolSpec{ @@ -609,7 +599,7 @@ func TestSetMachineDeploymentReplicas(t *testing.T) { }, }, { - name: "it enforces min=1 for Agent platform even when NodePool specifies min=0", + name: "When Agent platform specifies min=0, it should enforce min=1", nodePool: &hyperv1.NodePool{ ObjectMeta: metav1.ObjectMeta{}, Spec: hyperv1.NodePoolSpec{ @@ -1001,7 +991,7 @@ func TestInPlaceUpgradeMaxUnavailable(t *testing.T) { expect int }{ { - name: "defaults to 1 when no maxUnavailable specified", + name: "When no maxUnavailable is specified, it should default to 1", nodePool: &hyperv1.NodePool{ Spec: hyperv1.NodePoolSpec{ Management: hyperv1.NodePoolManagement{ @@ -1013,7 +1003,7 @@ func TestInPlaceUpgradeMaxUnavailable(t *testing.T) { expect: 1, }, { - name: "can handle default value of 1", + name: "When maxUnavailable is set to 1, it should return 1", nodePool: &hyperv1.NodePool{ Spec: hyperv1.NodePoolSpec{ Management: hyperv1.NodePoolManagement{ @@ -1027,7 +1017,7 @@ func TestInPlaceUpgradeMaxUnavailable(t *testing.T) { expect: 1, }, { - name: "can handle other values", + name: "When maxUnavailable is set to 2, it should return 2", nodePool: &hyperv1.NodePool{ Spec: hyperv1.NodePoolSpec{ Management: hyperv1.NodePoolManagement{ @@ -1041,7 +1031,7 @@ func TestInPlaceUpgradeMaxUnavailable(t *testing.T) { expect: 2, }, { - name: "can handle percent values", + name: "When maxUnavailable is set to 75 percent, it should return 3", nodePool: &hyperv1.NodePool{ Spec: hyperv1.NodePoolSpec{ Management: hyperv1.NodePoolManagement{ @@ -1055,7 +1045,7 @@ func TestInPlaceUpgradeMaxUnavailable(t *testing.T) { expect: 3, }, { - name: "can handle roundable values", + name: "When maxUnavailable is set to 10 percent, it should return 1", nodePool: &hyperv1.NodePool{ Spec: hyperv1.NodePoolSpec{ Management: hyperv1.NodePoolManagement{ @@ -1089,12 +1079,12 @@ func TestTaintsToJSON(t *testing.T) { expected string }{ { - name: "", + name: "When taints are empty, it should return an empty JSON array", taints: []hyperv1.Taint{}, expected: "[]", }, { - name: "", + name: "When multiple taints are provided, it should return valid JSON with all taints", taints: []hyperv1.Taint{ { Key: "foo", @@ -1238,61 +1228,61 @@ func TestReconcileMachineHealthCheck(t *testing.T) { expected *capiv1.MachineHealthCheck }{ { - name: "defaults", + name: "When defaults are used, it should create MHC with default values", hc: hostedcluster(), np: nodepool(), expected: healthcheck(), }, { - name: "timeout override in hc", + name: "When timeout override is set in HostedCluster, it should use override value", hc: hostedcluster(withTimeoutOverride("10m")), np: nodepool(), expected: healthcheck(withTimeout(10 * time.Minute)), }, { - name: "timeout override in np", + name: "When timeout override is set in NodePool, it should use override value", hc: hostedcluster(), np: nodepool(withTimeoutOverride("40m")), expected: healthcheck(withTimeout(40 * time.Minute)), }, { - name: "timeout override in both, np takes precedence", + name: "When timeout override is set in both, it should use NodePool value", hc: hostedcluster(withTimeoutOverride("10m")), np: nodepool(withTimeoutOverride("40m")), expected: healthcheck(withTimeout(40 * time.Minute)), }, { - name: "invalid timeout override, retains default", + name: "When timeout override is invalid, it should retain default", hc: hostedcluster(withTimeoutOverride("foo")), np: nodepool(), expected: healthcheck(), }, { - name: "node startup timeout override in hc", + name: "When node startup timeout override is set in HostedCluster, it should use override value", hc: hostedcluster(withNodeStartupTimeoutOverride("10m")), np: nodepool(), expected: healthcheck(withNodeStartupTimeout(10 * time.Minute)), }, { - name: "node startup timeout override in np", + name: "When node startup timeout override is set in NodePool, it should use override value", hc: hostedcluster(), np: nodepool(withNodeStartupTimeoutOverride("40m")), expected: healthcheck(withNodeStartupTimeout(40 * time.Minute)), }, { - name: "node startup timeout override in both, np takes precedence", + name: "When node startup timeout override is set in both, it should use NodePool value", hc: hostedcluster(withNodeStartupTimeoutOverride("10m")), np: nodepool(withNodeStartupTimeoutOverride("40m")), expected: healthcheck(withNodeStartupTimeout(40 * time.Minute)), }, { - name: "node startup invalid timeout override, retains default", + name: "When node startup timeout override is invalid, it should retain default", hc: hostedcluster(withNodeStartupTimeoutOverride("foo")), np: nodepool(), expected: healthcheck(), }, { - name: "invalid maxunhealthy override value, default is preserved", + name: "When maxunhealthy override value is invalid, it should preserve default", hc: hostedcluster(), np: nodepool(withMaxUnhealthyOverride("foo")), expected: healthcheck(), @@ -1750,7 +1740,7 @@ func TestCAPIReconcile(t *testing.T) { expectedError: false, }, { - name: "When NodeDrainTimeout and NodeVolumeDetachTimeout are set, they should propagate to MachineDeployment", + name: "When NodeDrainTimeout and NodeVolumeDetachTimeout are set, it should propagate them to MachineDeployment", nodePool: &hyperv1.NodePool{ ObjectMeta: metav1.ObjectMeta{ Name: "test-nodepool", @@ -2032,7 +2022,7 @@ func TestCAPIReconcile_machineset(t *testing.T) { nodePool *hyperv1.NodePool }{ { - name: "When NodeDrainTimeout and NodeVolumeDetachTimeout are set, they should propagate to MachineSet", + name: "When NodeDrainTimeout and NodeVolumeDetachTimeout are set, it should propagate them to MachineSet", nodePool: &hyperv1.NodePool{ ObjectMeta: metav1.ObjectMeta{ Name: "test-nodepool", @@ -2057,7 +2047,7 @@ func TestCAPIReconcile_machineset(t *testing.T) { }, }, { - name: "When NodeDrainTimeout and NodeVolumeDetachTimeout are nil, they should propagate as nil to MachineSet", + name: "When NodeDrainTimeout and NodeVolumeDetachTimeout are nil, it should propagate them as nil to MachineSet", nodePool: &hyperv1.NodePool{ ObjectMeta: metav1.ObjectMeta{ Name: "test-nodepool", @@ -3547,13 +3537,13 @@ func TestNewCAPI(t *testing.T) { expectedErrorMsg string }{ { - name: "when token is nil it should fail", + name: "When token is nil, it should fail", token: nil, capiClusterName: "test-cluster", expectedErrorMsg: "token can not be nil", }, { - name: "when capiClusterName is empty it should fail", + name: "When capiClusterName is empty, it should fail", token: &Token{ ConfigGenerator: &ConfigGenerator{}, }, @@ -3561,7 +3551,7 @@ func TestNewCAPI(t *testing.T) { expectedErrorMsg: "capiClusterName can not be empty", }, { - name: "succeeds with valid parameters", + name: "When valid parameters are provided, it should succeed", token: &Token{ ConfigGenerator: &ConfigGenerator{}, }, @@ -3600,7 +3590,7 @@ func TestMachineDeploymentComplete(t *testing.T) { expected bool }{ { - name: "When all v1beta1 and v1beta2 fields agree it should return true", + name: "When all v1beta1 and v1beta2 fields agree, it should return true", md: &capiv1.MachineDeployment{ ObjectMeta: metav1.ObjectMeta{Generation: 2}, Spec: capiv1.MachineDeploymentSpec{Replicas: &two}, @@ -3615,7 +3605,7 @@ func TestMachineDeploymentComplete(t *testing.T) { expected: true, }, { - name: "When v1beta1 looks complete but v1beta2 upToDateReplicas disagrees it should return false", + name: "When v1beta1 looks complete but v1beta2 upToDateReplicas disagrees, it should return false", md: &capiv1.MachineDeployment{ ObjectMeta: metav1.ObjectMeta{Generation: 2}, Spec: capiv1.MachineDeploymentSpec{Replicas: &two}, @@ -3630,7 +3620,7 @@ func TestMachineDeploymentComplete(t *testing.T) { expected: false, }, { - name: "When v1beta1 looks complete but v1beta2 availableReplicas disagrees it should return false", + name: "When v1beta1 looks complete but v1beta2 availableReplicas disagrees, it should return false", md: &capiv1.MachineDeployment{ ObjectMeta: metav1.ObjectMeta{Generation: 2}, Spec: capiv1.MachineDeploymentSpec{Replicas: &two}, @@ -3645,7 +3635,7 @@ func TestMachineDeploymentComplete(t *testing.T) { expected: false, }, { - name: "When v1beta1 is not complete it should return false without checking v1beta2", + name: "When v1beta1 is not complete, it should return false without checking v1beta2", md: &capiv1.MachineDeployment{ ObjectMeta: metav1.ObjectMeta{Generation: 2}, Spec: capiv1.MachineDeploymentSpec{Replicas: &two}, @@ -3654,7 +3644,7 @@ func TestMachineDeploymentComplete(t *testing.T) { expected: false, }, { - name: "When v1beta2 status is nil it should fall back to v1beta1 only", + name: "When v1beta2 status is nil, it should fall back to v1beta1 only", md: &capiv1.MachineDeployment{ ObjectMeta: metav1.ObjectMeta{Generation: 1}, Spec: capiv1.MachineDeploymentSpec{Replicas: &two}, @@ -3663,7 +3653,7 @@ func TestMachineDeploymentComplete(t *testing.T) { expected: true, }, { - name: "When v1beta1 replicas does not match spec it should return false", + name: "When v1beta1 replicas does not match spec, it should return false", md: &capiv1.MachineDeployment{ ObjectMeta: metav1.ObjectMeta{Generation: 2}, Spec: capiv1.MachineDeploymentSpec{Replicas: &three}, @@ -3678,7 +3668,7 @@ func TestMachineDeploymentComplete(t *testing.T) { expected: false, }, { - name: "When v1beta2 upToDateReplicas is nil it should return false", + name: "When v1beta2 upToDateReplicas is nil, it should return false", md: &capiv1.MachineDeployment{ ObjectMeta: metav1.ObjectMeta{Generation: 2}, Spec: capiv1.MachineDeploymentSpec{Replicas: &two}, @@ -3692,7 +3682,7 @@ func TestMachineDeploymentComplete(t *testing.T) { expected: false, }, { - name: "When v1beta2 availableReplicas is nil it should return false", + name: "When v1beta2 availableReplicas is nil, it should return false", md: &capiv1.MachineDeployment{ ObjectMeta: metav1.ObjectMeta{Generation: 2}, Spec: capiv1.MachineDeploymentSpec{Replicas: &two}, @@ -3706,7 +3696,7 @@ func TestMachineDeploymentComplete(t *testing.T) { expected: false, }, { - name: "When desired replicas is zero and v1beta2 fields are nil it should return false", + name: "When desired replicas is zero and v1beta2 fields are nil, it should return false", md: func() *capiv1.MachineDeployment { zero := int32(0) return &capiv1.MachineDeployment{ diff --git a/hypershift-operator/controllers/nodepool/config_test.go b/hypershift-operator/controllers/nodepool/config_test.go index d4bec4eb5011..558d7e474023 100644 --- a/hypershift-operator/controllers/nodepool/config_test.go +++ b/hypershift-operator/controllers/nodepool/config_test.go @@ -615,7 +615,7 @@ func TestHash(t *testing.T) { expected string }{ { - name: "Base case", + name: "When base case inputs are used, it should produce the base case hash", mcoRawConfig: baseCaseMCORawConfig, releaseVersion: baseCaseReleaseVersion, pullSecretName: baseCasePullSecretName, @@ -624,7 +624,7 @@ func TestHash(t *testing.T) { expected: baseCaseHash, }, { - name: "A different version should change the hash", + name: "When a different version is used, it should change the hash", mcoRawConfig: baseCaseMCORawConfig, releaseVersion: "4.8.0", pullSecretName: baseCasePullSecretName, @@ -633,7 +633,7 @@ func TestHash(t *testing.T) { expected: "27bb7699", }, { - name: "A different mcoRawConfig should change the hash", + name: "When a different mcoRawConfig is used, it should change the hash", mcoRawConfig: "different", releaseVersion: baseCaseReleaseVersion, pullSecretName: baseCasePullSecretName, @@ -642,7 +642,7 @@ func TestHash(t *testing.T) { expected: "25f99ac5", }, { - name: "A different pullSecretName should change the hash", + name: "When a different pullSecretName is used, it should change the hash", mcoRawConfig: baseCaseMCORawConfig, releaseVersion: baseCaseReleaseVersion, pullSecretName: "different", @@ -651,7 +651,7 @@ func TestHash(t *testing.T) { expected: "d0d6f6e9", }, { - name: "A different trust-bundle should change the hash", + name: "When a different trust-bundle is used, it should change the hash", mcoRawConfig: baseCaseMCORawConfig, releaseVersion: baseCaseReleaseVersion, pullSecretName: baseCasePullSecretName, @@ -660,7 +660,7 @@ func TestHash(t *testing.T) { expected: "42d42744", }, { - name: "A different globalConfig should change the hash", + name: "When a different globalConfig is used, it should change the hash", mcoRawConfig: baseCaseMCORawConfig, releaseVersion: baseCaseReleaseVersion, pullSecretName: baseCasePullSecretName, @@ -704,7 +704,7 @@ func TestHash(t *testing.T) { hash := cg.Hash() g.Expect(hash).ToNot(BeEmpty()) g.Expect(hash).To(Equal(tc.expected)) - if tc.name != "Base case" { + if tc.name != "When base case inputs are used, it should produce the base case hash" { g.Expect(hash).ToNot(Equal(baseCaseHash)) } }) @@ -729,7 +729,7 @@ func TestHashWithoutVersion(t *testing.T) { expected string }{ { - name: "Base case", + name: "When base case inputs are used, it should produce the base case hash", mcoRawConfig: baseCaseMCORawConfig, releaseVersion: baseCaseReleaseVersion, pullSecretName: baseCasePullSecretName, @@ -738,7 +738,7 @@ func TestHashWithoutVersion(t *testing.T) { expected: baseCaseHash, }, { - name: "A different version should not change the hash", + name: "When a different version is used, it should not change the hash", mcoRawConfig: baseCaseMCORawConfig, releaseVersion: "4.8.0", pullSecretName: baseCasePullSecretName, @@ -747,7 +747,7 @@ func TestHashWithoutVersion(t *testing.T) { expected: baseCaseHash, }, { - name: "A different mcoRawConfig should change the hash", + name: "When a different mcoRawConfig is used, it should change the hash", mcoRawConfig: "different", releaseVersion: baseCaseReleaseVersion, pullSecretName: baseCasePullSecretName, @@ -756,7 +756,7 @@ func TestHashWithoutVersion(t *testing.T) { expected: "5ea671c5", }, { - name: "A different pullSecretName should change the hash", + name: "When a different pullSecretName is used, it should change the hash", mcoRawConfig: baseCaseMCORawConfig, releaseVersion: baseCaseReleaseVersion, pullSecretName: "different", @@ -765,7 +765,7 @@ func TestHashWithoutVersion(t *testing.T) { expected: "f6e82eb7", }, { - name: "A different trust-bundle should change the hash", + name: "When a different trust-bundle is used, it should change the hash", mcoRawConfig: baseCaseMCORawConfig, releaseVersion: baseCaseReleaseVersion, pullSecretName: baseCasePullSecretName, @@ -776,7 +776,7 @@ func TestHashWithoutVersion(t *testing.T) { { // TODO(alberto): This was left inconsistent in https://github.com/openshift/hypershift/pull/3795/files. It should also contain cg.globalConfig. // This is kept like this for now to contain the scope of the refactor and avoid backward compatibility issues. - name: "A different globalConfig should NOT change the hash", + name: "When a different globalConfig is used, it should NOT change the hash", mcoRawConfig: baseCaseMCORawConfig, releaseVersion: baseCaseReleaseVersion, pullSecretName: baseCasePullSecretName, @@ -1174,7 +1174,7 @@ status: error bool }{ { - name: "gets a single valid MachineConfig", + name: "When a single valid MachineConfig is provided, it should return the defaulted config", nodePool: &hyperv1.NodePool{ ObjectMeta: metav1.ObjectMeta{ Namespace: namespace, @@ -1204,7 +1204,7 @@ status: error: false, }, { - name: "gets three valid MachineConfig, two of them in a single config-map", + name: "When three valid MachineConfigs are provided in two config-maps, it should return all defaulted configs", nodePool: &hyperv1.NodePool{ ObjectMeta: metav1.ObjectMeta{ Namespace: namespace, @@ -1245,7 +1245,7 @@ status: error: false, }, { - name: "fails if a non existent config is referenced", + name: "When a non-existent config is referenced, it should fail", nodePool: &hyperv1.NodePool{ ObjectMeta: metav1.ObjectMeta{ Namespace: namespace, @@ -1264,7 +1264,7 @@ status: error: true, }, { - name: "gets a single valid ContainerRuntimeConfig", + name: "When a single valid ContainerRuntimeConfig is provided, it should return the defaulted config", nodePool: &hyperv1.NodePool{ ObjectMeta: metav1.ObjectMeta{ Namespace: namespace, @@ -1292,7 +1292,7 @@ status: error: false, }, { - name: "gets a single valid MachineConfig with a core MachineConfig", + name: "When a valid MachineConfig with a core MachineConfig is provided, it should return both defaulted configs", nodePool: &hyperv1.NodePool{ ObjectMeta: metav1.ObjectMeta{ Namespace: namespace, @@ -1357,7 +1357,7 @@ status: error: false, }, { - name: "gets a single valid MachineConfig with a core MachineConfig and ignores independent namespace", + name: "When a valid MachineConfig with a core MachineConfig and independent namespace is provided, it should ignore the independent namespace", nodePool: &hyperv1.NodePool{ ObjectMeta: metav1.ObjectMeta{ Namespace: namespace, @@ -1431,7 +1431,7 @@ status: error: false, }, { - name: "No configs, missingConfigs error is returned", + name: "When no configs are provided, it should return missingConfigs error", nodePool: &hyperv1.NodePool{ ObjectMeta: metav1.ObjectMeta{ Namespace: namespace, @@ -1441,7 +1441,7 @@ status: error: true, }, { - name: "Nodepool controller generates HAProxy config", + name: "When HAProxy config is set, it should include it in the generated config", nodePool: &hyperv1.NodePool{ ObjectMeta: metav1.ObjectMeta{ Namespace: namespace, @@ -1493,7 +1493,7 @@ status: expect: haproxyIgnititionConfig + "\n---\n" + machineConfig1Defaulted, // + "\n---\n" + machineConfig1Defaulted, }, { - name: "gets a single valid KubeletConfig", + name: "When a single valid KubeletConfig is provided, it should return the defaulted config", nodePool: &hyperv1.NodePool{ ObjectMeta: metav1.ObjectMeta{ Namespace: namespace, @@ -1523,7 +1523,7 @@ status: error: false, }, { - name: "gets two valid KubeletConfig", + name: "When two valid KubeletConfigs are provided, it should return both defaulted configs", nodePool: &hyperv1.NodePool{ ObjectMeta: metav1.ObjectMeta{ Namespace: namespace, @@ -1564,7 +1564,7 @@ status: error: false, }, { - name: "It should fail if spec.Configs has unsupported content", + name: "When spec.Configs has unsupported content, it should fail", nodePool: &hyperv1.NodePool{ ObjectMeta: metav1.ObjectMeta{ Namespace: namespace, @@ -1873,7 +1873,7 @@ func TestDefaultAndValidateConfigManifest(t *testing.T) { error error }{ { - name: "Valid MachineConfig", + name: "When a valid MachineConfig is provided, it should return the defaulted config", input: []byte(` apiVersion: machineconfiguration.openshift.io/v1 kind: MachineConfig @@ -1900,7 +1900,7 @@ spec: error: nil, }, { - name: "When the manifest is not valid it should fail to decode", + name: "When the manifest is not valid, it should fail to decode", input: []byte(` invalid: yaml - content @@ -1909,7 +1909,7 @@ invalid: yaml error: fmt.Errorf("error decoding config: Object 'Kind' is missing in '\ninvalid: yaml\n - content\n'"), }, { - name: "When the API is not supported config it should fail with unsupported type", + name: "When the API is not supported config, it should fail with unsupported type", input: []byte(` apiVersion: hypershift.openshift.io/v1beta1 kind: HostedCluster diff --git a/hypershift-operator/controllers/nodepool/instancetype/aws/provider_test.go b/hypershift-operator/controllers/nodepool/instancetype/aws/provider_test.go index 4841d15d1bdf..d3d26e6b08f4 100644 --- a/hypershift-operator/controllers/nodepool/instancetype/aws/provider_test.go +++ b/hypershift-operator/controllers/nodepool/instancetype/aws/provider_test.go @@ -51,7 +51,7 @@ func TestGetGpuCount(t *testing.T) { expected int32 }{ { - name: "When single GPU type it should return that count", + name: "When single GPU type, it should return that count", gpuInfo: &ec2types.GpuInfo{ Gpus: []ec2types.GpuDeviceInfo{ {Count: aws.Int32(4)}, @@ -60,7 +60,7 @@ func TestGetGpuCount(t *testing.T) { expected: 4, }, { - name: "When multiple GPU types it should sum all counts", + name: "When multiple GPU types, it should sum all counts", gpuInfo: &ec2types.GpuInfo{ Gpus: []ec2types.GpuDeviceInfo{ {Count: aws.Int32(4)}, @@ -71,7 +71,7 @@ func TestGetGpuCount(t *testing.T) { expected: 14, }, { - name: "When GPU has nil count it should skip it", + name: "When GPU has nil count, it should skip it", gpuInfo: &ec2types.GpuInfo{ Gpus: []ec2types.GpuDeviceInfo{ {Count: aws.Int32(4)}, @@ -82,19 +82,19 @@ func TestGetGpuCount(t *testing.T) { expected: 6, }, { - name: "When gpuInfo has empty Gpus slice it should return 0", + name: "When gpuInfo has empty Gpus slice, it should return 0", gpuInfo: &ec2types.GpuInfo{ Gpus: []ec2types.GpuDeviceInfo{}, }, expected: 0, }, { - name: "When gpuInfo is nil it should return 0", + name: "When gpuInfo is nil, it should return 0", gpuInfo: nil, expected: 0, }, { - name: "When gpuInfo.Gpus is nil it should return 0", + name: "When gpuInfo.Gpus is nil, it should return 0", gpuInfo: &ec2types.GpuInfo{ Gpus: nil, }, @@ -111,14 +111,14 @@ func TestGetGpuCount(t *testing.T) { } } -func TestTransformInstanceTypeInfo_WhenMissingRequiredFields_ItShouldReturnError(t *testing.T) { +func TestTransformInstanceTypeInfoWhenMissingRequiredFieldsItShouldReturnError(t *testing.T) { tests := []struct { name string input ec2types.InstanceTypeInfo expectedError string }{ { - name: "When InstanceType name is empty it should return error", + name: "When InstanceType name is empty, it should return error", input: ec2types.InstanceTypeInfo{ VCpuInfo: &ec2types.VCpuInfo{ DefaultVCpus: aws.Int32(4), @@ -130,7 +130,7 @@ func TestTransformInstanceTypeInfo_WhenMissingRequiredFields_ItShouldReturnError expectedError: "instance type name is missing", }, { - name: "When VCpuInfo is nil it should return error", + name: "When VCpuInfo is nil, it should return error", input: ec2types.InstanceTypeInfo{ InstanceType: ec2types.InstanceType("test.xlarge"), MemoryInfo: &ec2types.MemoryInfo{ @@ -140,7 +140,7 @@ func TestTransformInstanceTypeInfo_WhenMissingRequiredFields_ItShouldReturnError expectedError: "missing vCPU information", }, { - name: "When DefaultVCpus is nil it should return error", + name: "When DefaultVCpus is nil, it should return error", input: ec2types.InstanceTypeInfo{ InstanceType: ec2types.InstanceType("test.xlarge"), VCpuInfo: &ec2types.VCpuInfo{}, @@ -151,7 +151,7 @@ func TestTransformInstanceTypeInfo_WhenMissingRequiredFields_ItShouldReturnError expectedError: "missing vCPU information", }, { - name: "When vCPU count is zero it should return error", + name: "When vCPU count is zero, it should return error", input: ec2types.InstanceTypeInfo{ InstanceType: ec2types.InstanceType("test.xlarge"), VCpuInfo: &ec2types.VCpuInfo{ @@ -164,7 +164,7 @@ func TestTransformInstanceTypeInfo_WhenMissingRequiredFields_ItShouldReturnError expectedError: "invalid vCPU count", }, { - name: "When MemoryInfo is nil it should return error", + name: "When MemoryInfo is nil, it should return error", input: ec2types.InstanceTypeInfo{ InstanceType: ec2types.InstanceType("test.xlarge"), VCpuInfo: &ec2types.VCpuInfo{ @@ -174,7 +174,7 @@ func TestTransformInstanceTypeInfo_WhenMissingRequiredFields_ItShouldReturnError expectedError: "missing memory information", }, { - name: "When SizeInMiB is nil it should return error", + name: "When SizeInMiB is nil, it should return error", input: ec2types.InstanceTypeInfo{ InstanceType: ec2types.InstanceType("test.xlarge"), VCpuInfo: &ec2types.VCpuInfo{ @@ -185,7 +185,7 @@ func TestTransformInstanceTypeInfo_WhenMissingRequiredFields_ItShouldReturnError expectedError: "missing memory information", }, { - name: "When memory size is zero it should return error", + name: "When memory size is zero, it should return error", input: ec2types.InstanceTypeInfo{ InstanceType: ec2types.InstanceType("test.xlarge"), VCpuInfo: &ec2types.VCpuInfo{ @@ -198,7 +198,7 @@ func TestTransformInstanceTypeInfo_WhenMissingRequiredFields_ItShouldReturnError expectedError: "invalid memory size", }, { - name: "When ProcessorInfo is nil it should return error", + name: "When ProcessorInfo is nil, it should return error", input: ec2types.InstanceTypeInfo{ InstanceType: ec2types.InstanceType("test.xlarge"), VCpuInfo: &ec2types.VCpuInfo{ @@ -211,7 +211,7 @@ func TestTransformInstanceTypeInfo_WhenMissingRequiredFields_ItShouldReturnError expectedError: "missing CPU architecture information", }, { - name: "When architecture is unsupported it should return error", + name: "When architecture is unsupported, it should return error", input: makeInstanceTypeInfo("t2.micro", string(ec2types.ArchitectureTypeI386), 1, 1024, 0), expectedError: "unsupported CPU architecture", }, @@ -227,14 +227,14 @@ func TestTransformInstanceTypeInfo_WhenMissingRequiredFields_ItShouldReturnError } } -func TestTransformInstanceTypeInfo_WhenValidInput_ItShouldTransformCorrectly(t *testing.T) { +func TestTransformInstanceTypeInfoWhenValidInputItShouldTransformCorrectly(t *testing.T) { tests := []struct { name string input ec2types.InstanceTypeInfo expected *instancetype.InstanceTypeInfo }{ { - name: "When all fields are present it should transform correctly", + name: "When all fields are present, it should transform correctly", input: ec2types.InstanceTypeInfo{ InstanceType: ec2types.InstanceType("m6i.xlarge"), VCpuInfo: &ec2types.VCpuInfo{ @@ -256,7 +256,7 @@ func TestTransformInstanceTypeInfo_WhenValidInput_ItShouldTransformCorrectly(t * }, }, { - name: "When instance has GPU it should set GPU count", + name: "When instance has GPU, it should set GPU count", input: makeInstanceTypeInfo("p3.2xlarge", string(ec2types.ArchitectureTypeX8664), 8, 61440, 1), expected: &instancetype.InstanceTypeInfo{ InstanceType: "p3.2xlarge", @@ -267,7 +267,7 @@ func TestTransformInstanceTypeInfo_WhenValidInput_ItShouldTransformCorrectly(t * }, }, { - name: "When instance is ARM it should set correct architecture", + name: "When instance is ARM, it should set correct architecture", input: makeInstanceTypeInfo("m6g.xlarge", string(ec2types.ArchitectureTypeArm64), 4, 16384, 0), expected: &instancetype.InstanceTypeInfo{ InstanceType: "m6g.xlarge", @@ -299,7 +299,7 @@ func TestGetInstanceTypeInfo(t *testing.T) { expectedError string }{ { - name: "When instance type exists it should return info", + name: "When instance type exists, it should return info", instanceTypes: []ec2types.InstanceTypeInfo{ makeInstanceTypeInfo("m6i.xlarge", string(ec2types.ArchitectureTypeX8664), 4, 16384, 0), }, diff --git a/hypershift-operator/controllers/nodepool/instancetype/azure/provider_test.go b/hypershift-operator/controllers/nodepool/instancetype/azure/provider_test.go index 6e7744ebd811..476f84b6add2 100644 --- a/hypershift-operator/controllers/nodepool/instancetype/azure/provider_test.go +++ b/hypershift-operator/controllers/nodepool/instancetype/azure/provider_test.go @@ -61,7 +61,7 @@ func TestTransformSKU_WhenValidInput_ItShouldTransformCorrectly(t *testing.T) { expected *instancetype.InstanceTypeInfo }{ { - name: "When Standard_D4s_v3 with x64 arch it should transform correctly", + name: "When Standard_D4s_v3 with x64 arch, it should transform correctly", input: makeSKU("Standard_D4s_v3", "virtualMachines", map[string]string{ "vCPUs": "4", "MemoryGB": "16", @@ -76,7 +76,7 @@ func TestTransformSKU_WhenValidInput_ItShouldTransformCorrectly(t *testing.T) { }, }, { - name: "When GPU VM it should set GPU count", + name: "When GPU VM, it should set GPU count", input: makeSKU("Standard_NC16as_T4_v3", "virtualMachines", map[string]string{ "vCPUs": "16", "MemoryGB": "110", @@ -92,7 +92,7 @@ func TestTransformSKU_WhenValidInput_ItShouldTransformCorrectly(t *testing.T) { }, }, { - name: "When Arm64 VM it should set correct architecture", + name: "When Arm64 VM, it should set correct architecture", input: makeSKU("Standard_D4ps_v5", "virtualMachines", map[string]string{ "vCPUs": "4", "MemoryGB": "16", @@ -107,7 +107,7 @@ func TestTransformSKU_WhenValidInput_ItShouldTransformCorrectly(t *testing.T) { }, }, { - name: "When GPUs capability is absent it should default to 0", + name: "When GPUs capability is absent, it should default to 0", input: makeSKU("Standard_B2s", "virtualMachines", map[string]string{ "vCPUs": "2", "MemoryGB": "4", @@ -122,7 +122,7 @@ func TestTransformSKU_WhenValidInput_ItShouldTransformCorrectly(t *testing.T) { }, }, { - name: "When MemoryGB is fractional it should convert correctly", + name: "When MemoryGB is fractional, it should convert correctly", input: makeSKU("Standard_B1ls", "virtualMachines", map[string]string{ "vCPUs": "1", "MemoryGB": "0.5", @@ -137,7 +137,7 @@ func TestTransformSKU_WhenValidInput_ItShouldTransformCorrectly(t *testing.T) { }, }, { - name: "When MemoryGB is large it should convert correctly", + name: "When MemoryGB is large, it should convert correctly", input: makeSKU("Standard_M416ms_v2", "virtualMachines", map[string]string{ "vCPUs": "416", "MemoryGB": "11400", @@ -170,7 +170,7 @@ func TestTransformSKU_WhenMissingRequiredFields_ItShouldReturnError(t *testing.T expectedError string }{ { - name: "When SKU name is nil it should return error", + name: "When SKU name is nil, it should return error", input: &armcompute.ResourceSKU{ Name: nil, ResourceType: to.Ptr("virtualMachines"), @@ -181,7 +181,7 @@ func TestTransformSKU_WhenMissingRequiredFields_ItShouldReturnError(t *testing.T expectedError: "SKU name is missing", }, { - name: "When vCPUs capability is missing it should return error", + name: "When vCPUs capability is missing, it should return error", input: makeSKU("Standard_D4s_v3", "virtualMachines", map[string]string{ "MemoryGB": "16", "CpuArchitectureType": "x64", @@ -189,7 +189,7 @@ func TestTransformSKU_WhenMissingRequiredFields_ItShouldReturnError(t *testing.T expectedError: "missing vCPUs capability", }, { - name: "When MemoryGB capability is missing it should return error", + name: "When MemoryGB capability is missing, it should return error", input: makeSKU("Standard_D4s_v3", "virtualMachines", map[string]string{ "vCPUs": "4", "CpuArchitectureType": "x64", @@ -197,7 +197,7 @@ func TestTransformSKU_WhenMissingRequiredFields_ItShouldReturnError(t *testing.T expectedError: "missing MemoryGB capability", }, { - name: "When CpuArchitectureType capability is missing it should return error", + name: "When CpuArchitectureType capability is missing, it should return error", input: makeSKU("Standard_D4s_v3", "virtualMachines", map[string]string{ "vCPUs": "4", "MemoryGB": "16", @@ -205,7 +205,7 @@ func TestTransformSKU_WhenMissingRequiredFields_ItShouldReturnError(t *testing.T expectedError: "missing CpuArchitectureType capability", }, { - name: "When vCPUs value is not a valid integer it should return error", + name: "When vCPUs value is not a valid integer, it should return error", input: makeSKU("Standard_D4s_v3", "virtualMachines", map[string]string{ "vCPUs": "abc", "MemoryGB": "16", @@ -214,7 +214,7 @@ func TestTransformSKU_WhenMissingRequiredFields_ItShouldReturnError(t *testing.T expectedError: "invalid vCPUs value", }, { - name: "When MemoryGB value is not a valid float it should return error", + name: "When MemoryGB value is not a valid float, it should return error", input: makeSKU("Standard_D4s_v3", "virtualMachines", map[string]string{ "vCPUs": "4", "MemoryGB": "xyz", @@ -223,7 +223,7 @@ func TestTransformSKU_WhenMissingRequiredFields_ItShouldReturnError(t *testing.T expectedError: "invalid MemoryGB value", }, { - name: "When vCPUs value is zero it should return error", + name: "When vCPUs value is zero, it should return error", input: makeSKU("Standard_D4s_v3", "virtualMachines", map[string]string{ "vCPUs": "0", "MemoryGB": "16", @@ -232,7 +232,7 @@ func TestTransformSKU_WhenMissingRequiredFields_ItShouldReturnError(t *testing.T expectedError: "invalid vCPUs count", }, { - name: "When MemoryGB value is zero it should return error", + name: "When MemoryGB value is zero, it should return error", input: makeSKU("Standard_D4s_v3", "virtualMachines", map[string]string{ "vCPUs": "4", "MemoryGB": "0", @@ -241,7 +241,7 @@ func TestTransformSKU_WhenMissingRequiredFields_ItShouldReturnError(t *testing.T expectedError: "invalid MemoryGB value", }, { - name: "When CpuArchitectureType is unsupported it should return error", + name: "When CpuArchitectureType is unsupported, it should return error", input: makeSKU("Standard_D4s_v3", "virtualMachines", map[string]string{ "vCPUs": "4", "MemoryGB": "16", @@ -250,7 +250,7 @@ func TestTransformSKU_WhenMissingRequiredFields_ItShouldReturnError(t *testing.T expectedError: "unsupported CPU architecture", }, { - name: "When GPUs value is not a valid integer it should return error", + name: "When GPUs value is not a valid integer, it should return error", input: makeSKU("Standard_NC6", "virtualMachines", map[string]string{ "vCPUs": "6", "MemoryGB": "56", @@ -260,7 +260,7 @@ func TestTransformSKU_WhenMissingRequiredFields_ItShouldReturnError(t *testing.T expectedError: "invalid GPUs value", }, { - name: "When GPUs value is negative it should return error", + name: "When GPUs value is negative, it should return error", input: makeSKU("Standard_NC6", "virtualMachines", map[string]string{ "vCPUs": "6", "MemoryGB": "56", @@ -291,7 +291,7 @@ func TestGetInstanceTypeInfo(t *testing.T) { expectedError string }{ { - name: "When VM size exists it should return info", + name: "When VM size exists, it should return info", skus: []*armcompute.ResourceSKU{ makeSKU("Standard_D4s_v3", "virtualMachines", map[string]string{ "vCPUs": "4", "MemoryGB": "16", "CpuArchitectureType": "x64", @@ -333,7 +333,7 @@ func TestGetInstanceTypeInfo(t *testing.T) { expectedError: "not found", }, { - name: "When multiple SKUs returned it should match only virtualMachines type", + name: "When multiple SKUs returned, it should match only virtualMachines type", skus: []*armcompute.ResourceSKU{ makeSKU("Standard_D4s_v3", "disks", map[string]string{ "vCPUs": "99", "MemoryGB": "99", "CpuArchitectureType": "x64", diff --git a/hypershift-operator/controllers/nodepool/kubevirt/kubevirt_test.go b/hypershift-operator/controllers/nodepool/kubevirt/kubevirt_test.go index a73d3f6e65d7..c39acafdbaa2 100644 --- a/hypershift-operator/controllers/nodepool/kubevirt/kubevirt_test.go +++ b/hypershift-operator/controllers/nodepool/kubevirt/kubevirt_test.go @@ -49,7 +49,7 @@ func TestKubevirtMachineTemplate(t *testing.T) { expectedValidationError string }{ { - name: "happy flow", + name: "When basic valid nodepool is configured, it should create the expected template", nodePool: &hyperv1.NodePool{ ObjectMeta: metav1.ObjectMeta{ Name: poolName, @@ -97,7 +97,7 @@ func TestKubevirtMachineTemplate(t *testing.T) { }, }, { - name: "happy flow - QoS CLass Guaranteed", + name: "When QoS class is set to Guaranteed, it should create template with guaranteed resources", nodePool: &hyperv1.NodePool{ ObjectMeta: metav1.ObjectMeta{ Name: poolName, @@ -145,7 +145,7 @@ func TestKubevirtMachineTemplate(t *testing.T) { }, }, { - name: "NetworkInterfaceMultiQueue is Disable", + name: "When NetworkInterfaceMultiQueue is Disabled, it should not set multiqueue", nodePool: &hyperv1.NodePool{ ObjectMeta: metav1.ObjectMeta{ Name: poolName, @@ -194,7 +194,7 @@ func TestKubevirtMachineTemplate(t *testing.T) { }, }, { - name: "NetworkInterfaceMultiQueue is Enabled", + name: "When NetworkInterfaceMultiQueue is Enabled, it should set multiqueue on the template", nodePool: &hyperv1.NodePool{ ObjectMeta: metav1.ObjectMeta{ Name: poolName, @@ -244,7 +244,7 @@ func TestKubevirtMachineTemplate(t *testing.T) { }, }, { - name: "Additional networks are configured", + name: "When additional networks are configured, it should include them in the template", nodePool: &hyperv1.NodePool{ ObjectMeta: metav1.ObjectMeta{ Name: poolName, @@ -344,7 +344,7 @@ func TestKubevirtMachineTemplate(t *testing.T) { }, }, { - name: "Additional networks are configured excluding default one", + name: "When additional networks are configured excluding default, it should exclude default network", nodePool: &hyperv1.NodePool{ ObjectMeta: metav1.ObjectMeta{ Name: poolName, @@ -437,7 +437,7 @@ func TestKubevirtMachineTemplate(t *testing.T) { }, }, { - name: "Excluding default network with additional ones should fail validation", + name: "When default network is excluded without additional networks, it should fail validation", nodePool: &hyperv1.NodePool{ ObjectMeta: metav1.ObjectMeta{ Name: poolName, @@ -474,7 +474,7 @@ func TestKubevirtMachineTemplate(t *testing.T) { expectedValidationError: "default network cannot be disabled when no additional networks are configured", }, { - name: "Host Devices are configured properly", + name: "When host devices are configured, it should include them in the template", nodePool: &hyperv1.NodePool{ ObjectMeta: metav1.ObjectMeta{ Name: poolName, @@ -538,7 +538,7 @@ func TestKubevirtMachineTemplate(t *testing.T) { }, }, { - name: "Host Devices count has an invalid value", + name: "When host device count has invalid value, it should fail validation", nodePool: &hyperv1.NodePool{ ObjectMeta: metav1.ObjectMeta{ Name: poolName, @@ -642,14 +642,14 @@ func TestCacheImage(t *testing.T) { dvNamePrefix string }{ { - name: "happy flow - no existing PVC", + name: "When no existing PVC exists, it should create a new DataVolume", nodePool: nodePool, errExpected: false, dvNamePrefix: bootImageNamePrefix, asserFunc: assertDV, }, { - name: "happy flow - PVC already exists", + name: "When PVC already exists with matching hash, it should reuse it", nodePool: nodePool, errExpected: false, existingResources: []client.Object{ @@ -672,7 +672,7 @@ func TestCacheImage(t *testing.T) { asserFunc: assertDV, }, { - name: "cleanup - different hash", + name: "When existing DataVolume has different hash, it should clean up and create new one", nodePool: nodePool, errExpected: false, existingResources: []client.Object{ @@ -696,7 +696,7 @@ func TestCacheImage(t *testing.T) { asserFunc: assertDV, }, { - name: "cleanup - different cluster - should not clean", + name: "When existing DataVolume belongs to different cluster, it should not clean it", nodePool: nodePool, errExpected: false, existingResources: []client.Object{ @@ -763,7 +763,7 @@ func TestJsonPatch(t *testing.T) { expected *capikubevirt.KubevirtMachineTemplateSpec }{ { - name: "single json patch in the nodepool", + name: "When a single json patch is set in the nodepool, it should apply it", nodePool: &hyperv1.NodePool{ ObjectMeta: metav1.ObjectMeta{ Name: poolName, @@ -815,7 +815,7 @@ func TestJsonPatch(t *testing.T) { }, }, { - name: "several json patches in the nodepool", + name: "When several json patches are set in the nodepool, it should apply all of them", nodePool: &hyperv1.NodePool{ ObjectMeta: metav1.ObjectMeta{ Name: poolName, @@ -878,7 +878,7 @@ func TestJsonPatch(t *testing.T) { }, }, { - name: "single json patch in the hosted cluster", + name: "When a single json patch is set in the hosted cluster, it should apply it", nodePool: &hyperv1.NodePool{ ObjectMeta: metav1.ObjectMeta{ Name: poolName, @@ -930,7 +930,7 @@ func TestJsonPatch(t *testing.T) { }, }, { - name: "several json patches in the hosted cluster", + name: "When several json patches are set in the hosted cluster, it should apply all of them", nodePool: &hyperv1.NodePool{ ObjectMeta: metav1.ObjectMeta{ Name: poolName, @@ -993,7 +993,7 @@ func TestJsonPatch(t *testing.T) { }, }, { - name: "json patches both in the hosted cluster and the nodepool", + name: "When json patches are set in both the hosted cluster and the nodepool, it should apply all of them", nodePool: &hyperv1.NodePool{ ObjectMeta: metav1.ObjectMeta{ Name: poolName, @@ -1060,7 +1060,7 @@ func TestJsonPatch(t *testing.T) { }, }, { - name: "json patches in the hosted cluster, overrode by the one in the nodepool", + name: "When json patches conflict between hosted cluster and nodepool, it should use nodepool patch", nodePool: &hyperv1.NodePool{ ObjectMeta: metav1.ObjectMeta{ Name: poolName, @@ -1126,7 +1126,7 @@ func TestJsonPatch(t *testing.T) { }, }, { - name: "remove annotation in the nodepool", + name: "When a remove annotation json patch is set in the nodepool, it should remove the annotation", nodePool: &hyperv1.NodePool{ ObjectMeta: metav1.ObjectMeta{ Name: poolName, @@ -1556,19 +1556,19 @@ func TestDefaultImage(t *testing.T) { expectedError: true, }, { - name: "s390x architecture", + name: "When s390x architecture is used, it should return the s390x image", arch: hyperv1.ArchitectureS390X, expectedImage: "quay.io/openshift/release@sha256:s390x1234", expectedDigest: "sha256:s390x1234", }, { - name: "x86_64 architecture", + name: "When x86_64 architecture is used, it should return the x86_64 image", arch: hyperv1.ArchitectureAMD64, expectedImage: "quay.io/openshift/release@sha256:x86_641234", expectedDigest: "sha256:x86_641234", }, { - name: "unknown architecture falls back to x86_64", + name: "When unknown architecture is used, it should fall back to x86_64 image", arch: "", expectedImage: "quay.io/openshift/release@sha256:x86_641234", expectedDigest: "sha256:x86_641234", diff --git a/hypershift-operator/controllers/nodepool/nodepool_controller_test.go b/hypershift-operator/controllers/nodepool/nodepool_controller_test.go index 9f6b3e015bd7..2354dbbaf4d9 100644 --- a/hypershift-operator/controllers/nodepool/nodepool_controller_test.go +++ b/hypershift-operator/controllers/nodepool/nodepool_controller_test.go @@ -57,7 +57,7 @@ func TestIsUpdatingConfig(t *testing.T) { expect bool }{ { - name: "it is not updating when strings match", + name: "When strings match, it should not update", nodePool: &hyperv1.NodePool{ ObjectMeta: metav1.ObjectMeta{ Annotations: map[string]string{ @@ -69,7 +69,7 @@ func TestIsUpdatingConfig(t *testing.T) { expect: false, }, { - name: "it is updating when strings does not match", + name: "When strings do not match, it should update", nodePool: &hyperv1.NodePool{ ObjectMeta: metav1.ObjectMeta{ Annotations: map[string]string{ @@ -100,7 +100,7 @@ func TestIsUpdatingVersion(t *testing.T) { expect bool }{ { - name: "it is not updating when strings match", + name: "When strings match, it should not update", nodePool: &hyperv1.NodePool{ Status: hyperv1.NodePoolStatus{ Version: "same", @@ -110,7 +110,7 @@ func TestIsUpdatingVersion(t *testing.T) { expect: false, }, { - name: "it is updating when strings does not match", + name: "When strings do not match, it should update", nodePool: &hyperv1.NodePool{ Status: hyperv1.NodePoolStatus{ Version: "v1", @@ -138,7 +138,7 @@ func TestIsAutoscalingEnabled(t *testing.T) { expect bool }{ { - name: "it is enabled when the struct is not nil and has no values", + name: "When the struct is not nil and has no values, it should be enabled", nodePool: &hyperv1.NodePool{ Spec: hyperv1.NodePoolSpec{ AutoScaling: &hyperv1.NodePoolAutoScaling{ @@ -150,7 +150,7 @@ func TestIsAutoscalingEnabled(t *testing.T) { expect: true, }, { - name: "it is enabled when the struct is not nil and has values", + name: "When the struct is not nil and has values, it should be enabled", nodePool: &hyperv1.NodePool{ Spec: hyperv1.NodePoolSpec{ AutoScaling: &hyperv1.NodePoolAutoScaling{ @@ -162,7 +162,7 @@ func TestIsAutoscalingEnabled(t *testing.T) { expect: true, }, { - name: "it is not enabled when the struct is nil", + name: "When the struct is nil, it should not be enabled", nodePool: &hyperv1.NodePool{ Spec: hyperv1.NodePoolSpec{}, }, @@ -188,7 +188,7 @@ func TestValidateManagement(t *testing.T) { error bool }{ { - name: "it fails with bad upgradeType", + name: "When bad upgradeType is set, it should fail", nodePool: &hyperv1.NodePool{ ObjectMeta: metav1.ObjectMeta{}, Spec: hyperv1.NodePoolSpec{ @@ -204,7 +204,7 @@ func TestValidateManagement(t *testing.T) { error: true, }, { - name: "it fails with Replace type and no Replace settings", + name: "When Replace type has no Replace settings, it should fail", nodePool: &hyperv1.NodePool{ ObjectMeta: metav1.ObjectMeta{}, Spec: hyperv1.NodePoolSpec{ @@ -216,7 +216,7 @@ func TestValidateManagement(t *testing.T) { error: true, }, { - name: "it fails with Replace type and bad strategy", + name: "When Replace type has bad strategy, it should fail", nodePool: &hyperv1.NodePool{ ObjectMeta: metav1.ObjectMeta{}, Spec: hyperv1.NodePoolSpec{ @@ -235,7 +235,7 @@ func TestValidateManagement(t *testing.T) { error: true, }, { - name: "it fails with Replace type, RollingUpdate strategy and no rollingUpdate settings", + name: "When Replace type has RollingUpdate strategy and no rollingUpdate settings, it should fail", nodePool: &hyperv1.NodePool{ ObjectMeta: metav1.ObjectMeta{}, Spec: hyperv1.NodePoolSpec{ @@ -251,7 +251,7 @@ func TestValidateManagement(t *testing.T) { error: true, }, { - name: "it passes with Replace type, RollingUpdate strategy and RollingUpdate settings", + name: "When Replace type has RollingUpdate strategy and RollingUpdate settings, it should pass", nodePool: &hyperv1.NodePool{ ObjectMeta: metav1.ObjectMeta{}, Spec: hyperv1.NodePoolSpec{ @@ -270,7 +270,7 @@ func TestValidateManagement(t *testing.T) { error: false, }, { - name: "it passes with Replace type and OnDelete strategy", + name: "When Replace type has OnDelete strategy, it should pass", nodePool: &hyperv1.NodePool{ ObjectMeta: metav1.ObjectMeta{}, Spec: hyperv1.NodePoolSpec{ @@ -345,7 +345,7 @@ func TestGetNodePoolNamespacedName(t *testing.T) { error bool }{ { - name: "gets correct NodePool namespaced name", + name: "When HostedControlPlane has cluster annotation, it should return correct NodePool namespaced name", nodePoolName: testNodePoolName, controlPlaneNamespace: testControlPlaneNamespace, hostedControlPlane: &hyperv1.HostedControlPlane{ @@ -360,7 +360,7 @@ func TestGetNodePoolNamespacedName(t *testing.T) { error: false, }, { - name: "fails if HostedControlPlane missing HostedClusterAnnotation", + name: "When HostedControlPlane is missing HostedClusterAnnotation, it should fail", nodePoolName: testNodePoolName, controlPlaneNamespace: testControlPlaneNamespace, hostedControlPlane: &hyperv1.HostedControlPlane{ @@ -372,7 +372,7 @@ func TestGetNodePoolNamespacedName(t *testing.T) { error: true, }, { - name: "fails if HostedControlPlane does not exist", + name: "When HostedControlPlane does not exist, it should fail", nodePoolName: testNodePoolName, controlPlaneNamespace: testControlPlaneNamespace, hostedControlPlane: nil, @@ -452,7 +452,7 @@ func TestCreateValidGeneratedPayloadCondition(t *testing.T) { expectedCondition *hyperv1.NodePoolCondition }{ { - name: "when token secret is not found it should report it in the condition", + name: "When token secret is not found, it should report it in the condition", tokenSecret: &corev1.Secret{ TypeMeta: metav1.TypeMeta{}, ObjectMeta: metav1.ObjectMeta{ @@ -472,7 +472,7 @@ func TestCreateValidGeneratedPayloadCondition(t *testing.T) { }, }, { - name: "when token secret has data it should report it in the condition", + name: "When token secret has data, it should report it in the condition", tokenSecret: &corev1.Secret{ TypeMeta: metav1.TypeMeta{}, ObjectMeta: metav1.ObjectMeta{ @@ -495,7 +495,7 @@ func TestCreateValidGeneratedPayloadCondition(t *testing.T) { }, }, { - name: "when token secret has no data it should report unknown in the condition", + name: "When token secret has no data, it should report unknown in the condition", tokenSecret: &corev1.Secret{ TypeMeta: metav1.TypeMeta{}, ObjectMeta: metav1.ObjectMeta{ @@ -694,12 +694,12 @@ func TestGetHostedClusterVersion(t *testing.T) { expectedVersion string }{ { - name: "version history status is empty, should return release image version", + name: "When version history status is empty, it should return release image version", releaseImageVersion: "4.15.0", expectedVersion: "4.15.0", }, { - name: "version history status has a completed entry, should return the completed version", + name: "When version history status has a completed entry, it should return the completed version", versionStatus: &hyperv1.ClusterVersionStatus{ History: []configv1.UpdateHistory{ { @@ -712,7 +712,7 @@ func TestGetHostedClusterVersion(t *testing.T) { expectedVersion: "4.14.0", }, { - name: "version history status has no completed entries, should return release image version", + name: "When version history status has no completed entries, it should return release image version", versionStatus: &hyperv1.ClusterVersionStatus{ History: []configv1.UpdateHistory{ { @@ -725,7 +725,7 @@ func TestGetHostedClusterVersion(t *testing.T) { expectedVersion: "4.15.0", }, { - name: "version history status has multiple entries, should return the first completed version", + name: "When version history status has multiple entries, it should return the first completed version", versionStatus: &hyperv1.ClusterVersionStatus{ History: []configv1.UpdateHistory{ { @@ -782,7 +782,7 @@ func TestFindMachineStatusCondition(t *testing.T) { expected *machineConditionResult }{ { - name: "When condition is False it should return the condition values", + name: "When condition is False, it should return the condition values", machine: &capiv1.Machine{ Status: capiv1.MachineStatus{ Conditions: []capiv1.Condition{ @@ -803,7 +803,7 @@ func TestFindMachineStatusCondition(t *testing.T) { }, }, { - name: "When neither has condition it should return nil", + name: "When neither has condition, it should return nil", machine: &capiv1.Machine{ Status: capiv1.MachineStatus{ Conditions: []capiv1.Condition{ @@ -818,7 +818,7 @@ func TestFindMachineStatusCondition(t *testing.T) { expected: nil, }, { - name: "When condition is True it should return the condition values", + name: "When condition is True, it should return the condition values", machine: &capiv1.Machine{ Status: capiv1.MachineStatus{ Conditions: []capiv1.Condition{ @@ -839,7 +839,7 @@ func TestFindMachineStatusCondition(t *testing.T) { }, }, { - name: "When machine has no conditions it should return nil", + name: "When machine has no conditions, it should return nil", machine: &capiv1.Machine{ Status: capiv1.MachineStatus{ Conditions: []capiv1.Condition{}, @@ -849,7 +849,7 @@ func TestFindMachineStatusCondition(t *testing.T) { expected: nil, }, { - name: "When looking up MachineNodeHealthyCondition it should return matching values", + name: "When looking up MachineNodeHealthyCondition, it should return matching values", machine: &capiv1.Machine{ Status: capiv1.MachineStatus{ Conditions: []capiv1.Condition{ @@ -935,7 +935,7 @@ func TestSetMachineAndNodeConditions(t *testing.T) { expectedCIDRCollision *testCondition }{ { - name: "no cluster-api machines", + name: "When there are no cluster-api machines, it should set WaitingForMachines condition", machinesGenerator: func() []client.Object { return nil }, expectedAllMachine: &testCondition{ Status: corev1.ConditionFalse, @@ -948,7 +948,7 @@ func TestSetMachineAndNodeConditions(t *testing.T) { }, }, { - name: "good machines", + name: "When all machines are healthy, it should set AllMachinesReady condition", machinesGenerator: func() []client.Object { return []client.Object{ &capiv1.Machine{ @@ -1007,7 +1007,7 @@ func TestSetMachineAndNodeConditions(t *testing.T) { }, }, { - name: "no InfrastructureReady condition", + name: "When machines have no InfrastructureReady condition, it should report waiting", machinesGenerator: func() []client.Object { return []client.Object{ &capiv1.Machine{ @@ -1074,7 +1074,7 @@ func TestSetMachineAndNodeConditions(t *testing.T) { }, }, { - name: "mix InfrastructureReady condition; setup counter first", + name: "When machines have mixed InfrastructureReady conditions with setup counter first, it should report mixed status", machinesGenerator: func() []client.Object { return []client.Object{ &capiv1.Machine{ @@ -1177,7 +1177,7 @@ func TestSetMachineAndNodeConditions(t *testing.T) { }, }, { - name: "mix InfrastructureReady condition; failure text first", + name: "When machines have mixed InfrastructureReady conditions with failure text first, it should report mixed status", machinesGenerator: func() []client.Object { return []client.Object{ &capiv1.Machine{ @@ -1280,7 +1280,7 @@ func TestSetMachineAndNodeConditions(t *testing.T) { }, }, { - name: "too many not ready machines", + name: "When too many machines are not ready, it should truncate the message", machinesGenerator: func() []client.Object { longMessage := strings.Repeat("msg ", 50) @@ -1398,7 +1398,7 @@ func TestSetMachineAndNodeConditions(t *testing.T) { }, }, { - name: "machine cidr collision", + name: "When machine has cidr collision, it should report the collision", machinesGenerator: func() []client.Object { return []client.Object{ &capiv1.Machine{ @@ -2737,7 +2737,7 @@ func TestIsArchAndPlatformSupported(t *testing.T) { expect bool }{ { - name: "supported arch and platform used", + name: "When supported arch and platform are used, it should validate successfully", nodePool: &hyperv1.NodePool{ Spec: hyperv1.NodePoolSpec{ Platform: hyperv1.NodePoolPlatform{ @@ -2749,7 +2749,7 @@ func TestIsArchAndPlatformSupported(t *testing.T) { expect: true, }, { - name: "supported arch and platform used - s390x", + name: "When s390x arch and supported platform are used, it should validate successfully", nodePool: &hyperv1.NodePool{ Spec: hyperv1.NodePoolSpec{ Platform: hyperv1.NodePoolPlatform{ @@ -2761,7 +2761,7 @@ func TestIsArchAndPlatformSupported(t *testing.T) { expect: true, }, { - name: "supported platform with multiple arch baremetal - arm64", + name: "When arm64 arch is used on baremetal platform, it should validate successfully", nodePool: &hyperv1.NodePool{ Spec: hyperv1.NodePoolSpec{ Platform: hyperv1.NodePoolPlatform{ @@ -2773,7 +2773,7 @@ func TestIsArchAndPlatformSupported(t *testing.T) { expect: true, }, { - name: "supported platform with multiple arch - amd64", + name: "When amd64 arch is used on AWS platform, it should validate successfully", nodePool: &hyperv1.NodePool{ Spec: hyperv1.NodePoolSpec{ Platform: hyperv1.NodePoolPlatform{ @@ -2785,7 +2785,7 @@ func TestIsArchAndPlatformSupported(t *testing.T) { expect: true, }, { - name: "supported platform with multiple arch - ppc64le", + name: "When ppc64le arch is used on None platform, it should validate successfully", nodePool: &hyperv1.NodePool{ Spec: hyperv1.NodePoolSpec{ Platform: hyperv1.NodePoolPlatform{ @@ -2797,7 +2797,7 @@ func TestIsArchAndPlatformSupported(t *testing.T) { expect: true, }, { - name: "supported platform with multiple arch baremetal - arm64", + name: "When arm64 arch is used on agent platform, it should validate successfully", nodePool: &hyperv1.NodePool{ Spec: hyperv1.NodePoolSpec{ Platform: hyperv1.NodePoolPlatform{ @@ -2809,7 +2809,7 @@ func TestIsArchAndPlatformSupported(t *testing.T) { expect: true, }, { - name: "supported platform with multiple arch baremetal - amd64", + name: "When amd64 arch is used on agent platform, it should validate successfully", nodePool: &hyperv1.NodePool{ Spec: hyperv1.NodePoolSpec{ Platform: hyperv1.NodePoolPlatform{ @@ -2821,7 +2821,7 @@ func TestIsArchAndPlatformSupported(t *testing.T) { expect: true, }, { - name: "unsupported arch and platform used", + name: "When unsupported arch and platform are used, it should fail validation", nodePool: &hyperv1.NodePool{ Spec: hyperv1.NodePoolSpec{ Platform: hyperv1.NodePoolPlatform{ @@ -2843,7 +2843,7 @@ func TestIsArchAndPlatformSupported(t *testing.T) { } } -func Test_validateHCPayloadSupportsNodePoolCPUArch(t *testing.T) { +func TestValidateHCPayloadSupportsNodePoolCPUArch(t *testing.T) { t.Parallel() testCases := []struct { name string @@ -2852,7 +2852,7 @@ func Test_validateHCPayloadSupportsNodePoolCPUArch(t *testing.T) { expectedErr bool }{ { - name: "payload is multi", + name: "When payload is multi-arch, it should validate successfully", hc: &hyperv1.HostedCluster{ Status: hyperv1.HostedClusterStatus{ PayloadArch: hyperv1.Multi, @@ -2861,7 +2861,7 @@ func Test_validateHCPayloadSupportsNodePoolCPUArch(t *testing.T) { expectedErr: false, }, { - name: "payload is amd64; np is amd64", + name: "When payload is amd64 and nodepool is amd64, it should validate successfully", hc: &hyperv1.HostedCluster{ Status: hyperv1.HostedClusterStatus{ PayloadArch: hyperv1.AMD64, @@ -2875,7 +2875,7 @@ func Test_validateHCPayloadSupportsNodePoolCPUArch(t *testing.T) { expectedErr: false, }, { - name: "payload is amd64; np is arm64", + name: "When payload is amd64 and nodepool is arm64, it should fail validation", hc: &hyperv1.HostedCluster{ Status: hyperv1.HostedClusterStatus{ PayloadArch: hyperv1.AMD64, @@ -3285,7 +3285,7 @@ func TestSupportedVersionSkewCondition(t *testing.T) { expectedError string }{ { - name: "when nodePool version matches control plane version it should report valid condition", + name: "When nodePool version matches control plane version, it should report valid condition", nodePool: func() *hyperv1.NodePool { np := baseNodePool.DeepCopy() np.Spec.Release.Image = "quay.io/openshift-release-dev/ocp-release:4.18.5-x86_64" @@ -3305,7 +3305,7 @@ func TestSupportedVersionSkewCondition(t *testing.T) { expectedError: "", }, { - name: "when nodePool version is higher than control plane version it should report invalid condition", + name: "When nodePool version is higher than control plane version, it should report invalid condition", nodePool: func() *hyperv1.NodePool { np := baseNodePool.DeepCopy() np.Spec.Release.Image = "quay.io/openshift-release-dev/ocp-release:4.19.0-x86_64" @@ -3325,7 +3325,7 @@ func TestSupportedVersionSkewCondition(t *testing.T) { expectedError: "", }, { - name: "when nodePool version is two minor versions lower than control plane (odd version) it should report valid condition with n-3 support", + name: "When nodePool version is two minor versions lower than control plane (odd version), it should report valid condition with n-3 support", nodePool: func() *hyperv1.NodePool { np := baseNodePool.DeepCopy() np.Spec.Release.Image = "quay.io/openshift-release-dev/ocp-release:4.15.0-x86_64" @@ -3349,7 +3349,7 @@ func TestSupportedVersionSkewCondition(t *testing.T) { expectedError: "", }, { - name: "when nodePool version is two minor versions lower than control plane (even version) it should report valid condition", + name: "When nodePool version is two minor versions lower than control plane (even version), it should report valid condition", nodePool: func() *hyperv1.NodePool { np := baseNodePool.DeepCopy() np.Spec.Release.Image = "quay.io/openshift-release-dev/ocp-release:4.16.0-x86_64" @@ -3373,7 +3373,7 @@ func TestSupportedVersionSkewCondition(t *testing.T) { expectedError: "", }, { - name: "when hosted cluster version history is empty it should report valid condition", + name: "When hosted cluster version history is empty, it should report valid condition", nodePool: func() *hyperv1.NodePool { np := baseNodePool.DeepCopy() np.Spec.Release.Image = "quay.io/openshift-release-dev/ocp-release:4.18.5-x86_64" @@ -3400,7 +3400,7 @@ func TestSupportedVersionSkewCondition(t *testing.T) { expectedError: "", }, { - name: "when nodePool version is three minor versions lower (n-3) it should report valid condition", + name: "When nodePool version is three minor versions lower (n-3), it should report valid condition", nodePool: func() *hyperv1.NodePool { np := baseNodePool.DeepCopy() np.Spec.Release.Image = "quay.io/openshift-release-dev/ocp-release:4.15.0-x86_64" @@ -3424,7 +3424,7 @@ func TestSupportedVersionSkewCondition(t *testing.T) { expectedError: "", }, { - name: "when nodePool version is four minor versions lower (n-4) it should report invalid condition", + name: "When nodePool version is four minor versions lower (n-4), it should report invalid condition", nodePool: func() *hyperv1.NodePool { np := baseNodePool.DeepCopy() np.Spec.Release.Image = "quay.io/openshift-release-dev/ocp-release:4.14.0-x86_64" @@ -3448,7 +3448,7 @@ func TestSupportedVersionSkewCondition(t *testing.T) { expectedError: "", }, { - name: "when nodePool patch version is lower than control plane (same minor version) it should report valid condition", + name: "When nodePool patch version is lower than control plane (same minor version), it should report valid condition", nodePool: func() *hyperv1.NodePool { np := baseNodePool.DeepCopy() np.Spec.Release.Image = "quay.io/openshift-release-dev/ocp-release:4.18.5-x86_64" @@ -3472,7 +3472,7 @@ func TestSupportedVersionSkewCondition(t *testing.T) { expectedError: "", }, { - name: "when nodePool patch version is higher than control plane (same minor version) it should report invalid condition", + name: "When nodePool patch version is higher than control plane (same minor version), it should report invalid condition", nodePool: func() *hyperv1.NodePool { np := baseNodePool.DeepCopy() np.Spec.Release.Image = "quay.io/openshift-release-dev/ocp-release:4.18.10-x86_64" @@ -3542,7 +3542,7 @@ func TestNodePoolReconciler_reconcile(t *testing.T) { wantErr bool }{ { - name: "when NodePool and HostedCluster are valid it should reconcile successfully", + name: "When NodePool and HostedCluster are valid, it should reconcile successfully", hcluster: &hyperv1.HostedCluster{ ObjectMeta: metav1.ObjectMeta{ Name: "test-hc", @@ -3590,7 +3590,7 @@ func TestNodePoolReconciler_reconcile(t *testing.T) { wantErr: false, }, { - name: "when reconciling it should set conditions in the expected order", + name: "When reconciling, it should set conditions in the expected order", hcluster: &hyperv1.HostedCluster{ ObjectMeta: metav1.ObjectMeta{ Name: "test-hc", @@ -3638,7 +3638,7 @@ func TestNodePoolReconciler_reconcile(t *testing.T) { wantErr: false, }, { - name: "when ignition endpoint is missing it should exit early from condition loop", + name: "When ignition endpoint is missing, it should exit early from condition loop", hcluster: &hyperv1.HostedCluster{ ObjectMeta: metav1.ObjectMeta{ Name: "test-hc", @@ -3738,7 +3738,7 @@ func TestNodePoolReconciler_reconcile(t *testing.T) { g.Expect(got).To(Equal(tt.want)) // For the condition order test, verify conditions are set in the expected order - if tt.name == "when reconciling it should set conditions in the expected order" { + if tt.name == "When reconciling, it should set conditions in the expected order" { // Expected condition order based on reconcile() signalConditions array expectedConditionOrder := []string{ hyperv1.NodePoolAutoscalingEnabledConditionType, @@ -3779,7 +3779,7 @@ func TestNodePoolReconciler_reconcile(t *testing.T) { } // For the early exit test, verify the function exited early from the condition loop - if tt.name == "when ignition endpoint is missing it should exit early from condition loop" { + if tt.name == "When ignition endpoint is missing, it should exit early from condition loop" { // Verify IgnitionEndpointAvailable condition is set to False ignitionCondition := FindStatusCondition(tt.nodePool.Status.Conditions, string(hyperv1.IgnitionEndpointAvailable)) g.Expect(ignitionCondition).NotTo(BeNil(), "IgnitionEndpointAvailable condition should be set") diff --git a/hypershift-operator/controllers/nodepool/nto_test.go b/hypershift-operator/controllers/nodepool/nto_test.go index 3dfb6b6a9606..d862c761330f 100644 --- a/hypershift-operator/controllers/nodepool/nto_test.go +++ b/hypershift-operator/controllers/nodepool/nto_test.go @@ -208,7 +208,7 @@ status: {} error bool }{ { - name: "gets a single valid TunedConfig", + name: "When a single valid TunedConfig is provided, it should return the defaulted config", nodePool: &hyperv1.NodePool{ ObjectMeta: metav1.ObjectMeta{ Namespace: namespace, @@ -239,7 +239,7 @@ status: {} error: false, }, { - name: "gets two valid TunedConfigs", + name: "When two valid TunedConfigs are provided, it should return both defaulted configs", nodePool: &hyperv1.NodePool{ ObjectMeta: metav1.ObjectMeta{ Namespace: namespace, @@ -281,7 +281,7 @@ status: {} error: false, }, { - name: "fails if a non existent TunedConfig is referenced", + name: "When a non-existent TunedConfig is referenced, it should fail", nodePool: &hyperv1.NodePool{ ObjectMeta: metav1.ObjectMeta{ Namespace: namespace, @@ -302,7 +302,7 @@ status: {} }, //------------------------------------------------------------------------- { - name: "gets a single valid PerformanceProfileConfig", + name: "When a single valid PerformanceProfileConfig is provided, it should return the defaulted config", nodePool: &hyperv1.NodePool{ ObjectMeta: metav1.ObjectMeta{ Namespace: namespace, @@ -334,7 +334,7 @@ status: {} error: false, }, { - name: "Should be at most one PerformanceProfileConfig per NodePool", + name: "When more than one PerformanceProfileConfig is provided, it should fail", nodePool: &hyperv1.NodePool{ ObjectMeta: metav1.ObjectMeta{ Namespace: namespace, @@ -376,7 +376,7 @@ status: {} error: true, }, { - name: "fails if a non existent PerformanceProfile is referenced", + name: "When a non-existent PerformanceProfile is referenced, it should fail", nodePool: &hyperv1.NodePool{ ObjectMeta: metav1.ObjectMeta{ Namespace: namespace, @@ -396,7 +396,7 @@ status: {} error: true, }, { - name: "PerformanceProfiles and Tuned Configs could coexists", + name: "When PerformanceProfiles and Tuned Configs coexist, it should return both", nodePool: &hyperv1.NodePool{ ObjectMeta: metav1.ObjectMeta{ Namespace: namespace, @@ -531,7 +531,7 @@ func TestReconcileMirroredConfigs(t *testing.T) { expectedError bool }{ { - name: "with containerruntime", + name: "When containerruntime config is mirrored, it should create the mirrored configmap", nodePool: np, controlPlaneNamespace: hcpNamespace, configsToBeMirrored: []*MirrorConfig{ @@ -570,7 +570,7 @@ func TestReconcileMirroredConfigs(t *testing.T) { }, }, { - name: "with configs that need to be deleted", + name: "When configs change, it should delete outdated and create new mirrored configs", nodePool: np, controlPlaneNamespace: hcpNamespace, configsToBeMirrored: []*MirrorConfig{ @@ -630,7 +630,7 @@ func TestReconcileMirroredConfigs(t *testing.T) { }, }, { - name: "with kubeletconfig objects", + name: "When kubeletconfig is mirrored, it should create the mirrored configmap", nodePool: np, controlPlaneNamespace: hcpNamespace, configsToBeMirrored: []*MirrorConfig{ @@ -834,7 +834,7 @@ func TestReconcileMirroredConfigs(t *testing.T) { }, }, { - name: "negative: with multiple kubeletconfig objects expect validation error", + name: "When multiple kubeletconfig objects exist, it should return validation error", nodePool: np, controlPlaneNamespace: hcpNamespace, configsToBeMirrored: []*MirrorConfig{ @@ -917,14 +917,14 @@ func TestSetPerformanceProfileStatus(t *testing.T) { }{ { - name: "No Performance profile applied", + name: "When no performance profile is applied, it should not set performance profile conditions", PerformanceProfileStatusCM: &corev1.ConfigMap{}, wantConditions: map[string]hyperv1.NodePoolCondition{}, hasPerformanceProfileApplied: false, }, { - name: "Performance profile is available", + name: "When performance profile is available, it should set conditions to reflect availability", PerformanceProfileStatusCM: &corev1.ConfigMap{ TypeMeta: metav1.TypeMeta{ Kind: "ConfigMap", @@ -983,7 +983,7 @@ func TestSetPerformanceProfileStatus(t *testing.T) { hasPerformanceProfileApplied: true, }, { - name: "Performance profile is progressing", + name: "When performance profile is progressing, it should set conditions to reflect progress", PerformanceProfileStatusCM: &corev1.ConfigMap{ TypeMeta: metav1.TypeMeta{ Kind: "ConfigMap", @@ -1040,7 +1040,7 @@ func TestSetPerformanceProfileStatus(t *testing.T) { hasPerformanceProfileApplied: true, }, { - name: "Performance profile is degraded", + name: "When performance profile is degraded, it should set conditions to reflect degradation", PerformanceProfileStatusCM: &corev1.ConfigMap{ TypeMeta: metav1.TypeMeta{ Kind: "ConfigMap", @@ -1241,19 +1241,19 @@ spec: input []byte }{ { - name: "Valid MachineConfig", + name: "When a valid MachineConfig is provided, it should return mirror config", input: []byte(machineConfig), }, { - name: "Valid ContainerRuntimeConfig", + name: "When a valid ContainerRuntimeConfig is provided, it should return mirror config", input: []byte(containerRuntimeConfig), }, { - name: "Valid KubeletConfig", + name: "When a valid KubeletConfig is provided, it should return mirror config", input: []byte(kubeletConfig), }, { - name: "Valid ImageDigestMirrorSet", + name: "When a valid ImageDigestMirrorSet is provided, it should return mirror config", input: []byte(imageDigestMirrorSet), }, } diff --git a/hypershift-operator/controllers/nodepool/openstack/openstack_test.go b/hypershift-operator/controllers/nodepool/openstack/openstack_test.go index 384eb5fd09f4..5a705fa3f4fb 100644 --- a/hypershift-operator/controllers/nodepool/openstack/openstack_test.go +++ b/hypershift-operator/controllers/nodepool/openstack/openstack_test.go @@ -30,7 +30,7 @@ func TestOpenStackMachineTemplate(t *testing.T) { checkError func(*testing.T, error) }{ { - name: "basic valid node pool", + name: "When a basic valid node pool is configured, it should create the expected template", nodePool: hyperv1.NodePoolSpec{ ClusterName: "", Replicas: nil, @@ -61,7 +61,7 @@ func TestOpenStackMachineTemplate(t *testing.T) { }, }, { - name: "basic additional port", + name: "When an additional port is configured, it should include it in the template", nodePool: hyperv1.NodePoolSpec{ ClusterName: "", Replicas: nil, @@ -108,7 +108,7 @@ func TestOpenStackMachineTemplate(t *testing.T) { }, }, { - name: "additional port for SR-IOV", + name: "When an additional port is configured for SR-IOV, it should set VNICType and disable port security", nodePool: hyperv1.NodePoolSpec{ ClusterName: "", Replicas: nil, @@ -212,7 +212,7 @@ func TestOpenstackDefaultImage(t *testing.T) { expectedError bool }{ { - name: "valid metadata", + name: "When valid metadata is provided, it should return the image URL and hash", releaseImage: &releaseinfo.ReleaseImage{ StreamMetadata: &stream.Stream{ Architectures: map[string]stream.Arch{ @@ -238,12 +238,12 @@ func TestOpenstackDefaultImage(t *testing.T) { expectedError: false, }, { - name: "missing architecture", + name: "When architecture is missing, it should return error", releaseImage: &releaseinfo.ReleaseImage{StreamMetadata: &stream.Stream{Architectures: map[string]stream.Arch{}}}, expectedError: true, }, { - name: "missing openstack artifact", + name: "When openstack artifact is missing, it should return error", releaseImage: &releaseinfo.ReleaseImage{ StreamMetadata: &stream.Stream{ Architectures: map[string]stream.Arch{ @@ -254,7 +254,7 @@ func TestOpenstackDefaultImage(t *testing.T) { expectedError: true, }, { - name: "missing qcow2.gz format", + name: "When qcow2.gz format is missing, it should return error", releaseImage: &releaseinfo.ReleaseImage{ StreamMetadata: &stream.Stream{ Architectures: map[string]stream.Arch{ @@ -269,7 +269,7 @@ func TestOpenstackDefaultImage(t *testing.T) { expectedError: true, }, { - name: "missing disk artifact", + name: "When disk artifact is missing, it should return error", releaseImage: &releaseinfo.ReleaseImage{ StreamMetadata: &stream.Stream{ Architectures: map[string]stream.Arch{ @@ -348,7 +348,7 @@ func TestOpenStackReleaseImage(t *testing.T) { expectedError bool }{ { - name: "valid metadata", + name: "When valid metadata is provided, it should return the release version", releaseImage: &releaseinfo.ReleaseImage{ StreamMetadata: &stream.Stream{ Architectures: map[string]stream.Arch{ @@ -366,12 +366,12 @@ func TestOpenStackReleaseImage(t *testing.T) { expectedError: false, }, { - name: "missing architecture", + name: "When architecture is missing, it should return error", releaseImage: &releaseinfo.ReleaseImage{StreamMetadata: &stream.Stream{Architectures: map[string]stream.Arch{}}}, expectedError: true, }, { - name: "missing openstack artifact", + name: "When openstack artifact is missing, it should return error", releaseImage: &releaseinfo.ReleaseImage{ StreamMetadata: &stream.Stream{ Architectures: map[string]stream.Arch{ @@ -431,7 +431,7 @@ func TestReconcileOpenStackImageSpec(t *testing.T) { expectedErrorSubstring string }{ { - name: "valid configuration", + name: "When valid configuration is provided, it should reconcile the image spec", hostedCluster: &hyperv1.HostedCluster{ ObjectMeta: metav1.ObjectMeta{ Name: "test-cluster", @@ -491,7 +491,7 @@ func TestReconcileOpenStackImageSpec(t *testing.T) { }, }, { - name: "release image error", + name: "When release image has missing architecture, it should return error", hostedCluster: &hyperv1.HostedCluster{ Spec: hyperv1.HostedClusterSpec{ Platform: hyperv1.PlatformSpec{ @@ -553,7 +553,7 @@ func TestClusterImageName(t *testing.T) { expectedError bool }{ { - name: "valid release image", + name: "When valid release image is provided, it should return the cluster image name", hostedCluster: &hyperv1.HostedCluster{ ObjectMeta: metav1.ObjectMeta{ Name: "test-cluster", @@ -577,7 +577,7 @@ func TestClusterImageName(t *testing.T) { expectedError: false, }, { - name: "missing architecture", + name: "When architecture is missing, it should return error", hostedCluster: &hyperv1.HostedCluster{ ObjectMeta: metav1.ObjectMeta{ Name: "test-cluster", @@ -592,7 +592,7 @@ func TestClusterImageName(t *testing.T) { expectedError: true, }, { - name: "missing openstack artifact", + name: "When openstack artifact is missing, it should return error", hostedCluster: &hyperv1.HostedCluster{ ObjectMeta: metav1.ObjectMeta{ Name: "test-cluster", diff --git a/hypershift-operator/controllers/nodepool/platform_conditions_test.go b/hypershift-operator/controllers/nodepool/platform_conditions_test.go index f21bcf940537..e0724b717e0e 100644 --- a/hypershift-operator/controllers/nodepool/platform_conditions_test.go +++ b/hypershift-operator/controllers/nodepool/platform_conditions_test.go @@ -39,7 +39,7 @@ func TestSetPlatformConditions(t *testing.T) { expectedCondValue corev1.ConditionStatus }{ { - name: "When platform is AWS and image discovery fails it should return error", + name: "When platform is AWS and image discovery fails, it should return error", nodePool: &hyperv1.NodePool{ Spec: hyperv1.NodePoolSpec{ Platform: hyperv1.NodePoolPlatform{Type: hyperv1.AWSPlatform, AWS: &hyperv1.AWSNodePoolPlatform{}}, @@ -59,7 +59,7 @@ func TestSetPlatformConditions(t *testing.T) { expectedCondValue: corev1.ConditionFalse, }, { - name: "When platform is OpenStack and image discovery fails it should return error", + name: "When platform is OpenStack and image discovery fails, it should return error", nodePool: &hyperv1.NodePool{ Spec: hyperv1.NodePoolSpec{ Platform: hyperv1.NodePoolPlatform{Type: hyperv1.OpenStackPlatform, OpenStack: &hyperv1.OpenStackNodePoolPlatform{}}, @@ -103,7 +103,7 @@ func TestSetPlatformConditions(t *testing.T) { expectedCondValue: corev1.ConditionTrue, }, { - name: "When platform is OpenStack and architecture is missing it should set ValidPlatformImage to false", + name: "When platform is OpenStack and architecture is missing, it should set ValidPlatformImage to false", nodePool: &hyperv1.NodePool{ Spec: hyperv1.NodePoolSpec{ Platform: hyperv1.NodePoolPlatform{Type: hyperv1.OpenStackPlatform, OpenStack: &hyperv1.OpenStackNodePoolPlatform{}}, @@ -128,7 +128,7 @@ func TestSetPlatformConditions(t *testing.T) { expectError: true, }, { - name: "When platform is KubeVirt and image discovery fails it should return error", + name: "When platform is KubeVirt and image discovery fails, it should return error", nodePool: &hyperv1.NodePool{ Spec: hyperv1.NodePoolSpec{ Platform: hyperv1.NodePoolPlatform{Type: hyperv1.KubevirtPlatform, Kubevirt: &hyperv1.KubevirtNodePoolPlatform{ @@ -155,7 +155,7 @@ func TestSetPlatformConditions(t *testing.T) { expectedCondValue: corev1.ConditionFalse, }, { - name: "When platform is PowerVS and image discovery fails it should return error", + name: "When platform is PowerVS and image discovery fails, it should return error", nodePool: &hyperv1.NodePool{ Spec: hyperv1.NodePoolSpec{ Platform: hyperv1.NodePoolPlatform{Type: hyperv1.PowerVSPlatform, PowerVS: &hyperv1.PowerVSNodePoolPlatform{}}, diff --git a/hypershift-operator/controllers/nodepool/scale_from_zero_test.go b/hypershift-operator/controllers/nodepool/scale_from_zero_test.go index ae16ff360607..377059366aa1 100644 --- a/hypershift-operator/controllers/nodepool/scale_from_zero_test.go +++ b/hypershift-operator/controllers/nodepool/scale_from_zero_test.go @@ -35,26 +35,26 @@ func TestTaintsToAnnotation(t *testing.T) { expected string }{ { - name: "When taints are empty it should return empty string", + name: "When taints are empty, it should return empty string", taints: []hyperv1.Taint{}, expected: "", }, { - name: "When single taint it should format correctly", + name: "When single taint, it should format correctly", taints: []hyperv1.Taint{ {Key: "dedicated", Value: "gpu", Effect: corev1.TaintEffectNoSchedule}, }, expected: "dedicated=gpu:NoSchedule", }, { - name: "When single taint with empty value it should format as key:Effect", + name: "When single taint with empty value, it should format as key:Effect", taints: []hyperv1.Taint{ {Key: "node-role.kubernetes.io/infra", Value: "", Effect: corev1.TaintEffectNoSchedule}, }, expected: "node-role.kubernetes.io/infra:NoSchedule", }, { - name: "When multiple taints it should format and sort", + name: "When multiple taints, it should format and sort", taints: []hyperv1.Taint{ {Key: "critical", Value: "true", Effect: corev1.TaintEffectNoExecute}, {Key: "dedicated", Value: "gpu", Effect: corev1.TaintEffectNoSchedule}, @@ -62,7 +62,7 @@ func TestTaintsToAnnotation(t *testing.T) { expected: "critical=true:NoExecute,dedicated=gpu:NoSchedule", }, { - name: "When taints with different effects it should format correctly", + name: "When taints with different effects, it should format correctly", taints: []hyperv1.Taint{ {Key: "node-role.kubernetes.io/infra", Value: "", Effect: corev1.TaintEffectNoSchedule}, {Key: "workload", Value: "batch", Effect: corev1.TaintEffectPreferNoSchedule}, @@ -112,7 +112,7 @@ func TestSetScaleFromZeroAnnotationsOnObject(t *testing.T) { validate func(g Gomega, md *capiv1.MachineDeployment) }{ { - name: "When machine template is an unsupported type it should return an error", + name: "When machine template is an unsupported type, it should return an error", provider: &mockProvider{}, nodePool: &hyperv1.NodePool{}, object: &capiv1.MachineDeployment{}, @@ -121,7 +121,7 @@ func TestSetScaleFromZeroAnnotationsOnObject(t *testing.T) { errSubstring: "unsupported machine template type", }, { - name: "When instanceType is empty it should return an error", + name: "When instanceType is empty, it should return an error", provider: &mockProvider{}, nodePool: &hyperv1.NodePool{}, object: &capiv1.MachineDeployment{}, @@ -130,7 +130,7 @@ func TestSetScaleFromZeroAnnotationsOnObject(t *testing.T) { errSubstring: "instanceType is empty", }, { - name: "When provider returns an error it should propagate the error", + name: "When provider returns an error, it should propagate the error", provider: &mockProvider{err: fmt.Errorf("failed to describe instance type")}, nodePool: &hyperv1.NodePool{}, object: &capiv1.MachineDeployment{}, @@ -139,7 +139,7 @@ func TestSetScaleFromZeroAnnotationsOnObject(t *testing.T) { errSubstring: "failed to describe instance type", }, { - name: "When Status.Capacity is already provided it should remove scale-from-zero annotations", + name: "When Status.Capacity is already provided, it should remove scale-from-zero annotations", provider: &mockProvider{}, nodePool: &hyperv1.NodePool{}, object: &capiv1.MachineDeployment{ @@ -176,7 +176,7 @@ func TestSetScaleFromZeroAnnotationsOnObject(t *testing.T) { }, }, { - name: "When provider is nil it should return nil without setting annotations", + name: "When provider is nil, it should return nil without setting annotations", provider: nil, nodePool: &hyperv1.NodePool{}, object: &capiv1.MachineDeployment{}, @@ -187,7 +187,7 @@ func TestSetScaleFromZeroAnnotationsOnObject(t *testing.T) { }, }, { - name: "When instance has no GPU and no taints it should set basic annotations and remove stale ones", + name: "When instance has no GPU and no taints, it should set basic annotations and remove stale ones", provider: &mockProvider{info: &instancetype.InstanceTypeInfo{ VCPU: 2, MemoryMb: 8192, GPU: 0, CPUArchitecture: "amd64", }}, @@ -212,7 +212,7 @@ func TestSetScaleFromZeroAnnotationsOnObject(t *testing.T) { }, }, { - name: "When Azure template with valid VMSize and no GPU it should set basic annotations", + name: "When Azure template with valid VMSize and no GPU, it should set basic annotations", provider: &mockProvider{info: &instancetype.InstanceTypeInfo{ VCPU: 4, MemoryMb: 16384, GPU: 0, CPUArchitecture: "amd64", }}, @@ -229,7 +229,7 @@ func TestSetScaleFromZeroAnnotationsOnObject(t *testing.T) { }, }, { - name: "When Azure template with empty VMSize it should return error", + name: "When Azure template with empty VMSize, it should return error", provider: &mockProvider{}, nodePool: &hyperv1.NodePool{}, object: &capiv1.MachineDeployment{}, @@ -238,7 +238,7 @@ func TestSetScaleFromZeroAnnotationsOnObject(t *testing.T) { errSubstring: "instanceType is empty", }, { - name: "When Azure template with nil provider it should skip annotations", + name: "When Azure template with nil provider, it should skip annotations", provider: nil, nodePool: &hyperv1.NodePool{}, object: &capiv1.MachineDeployment{}, @@ -249,7 +249,7 @@ func TestSetScaleFromZeroAnnotationsOnObject(t *testing.T) { }, }, { - name: "When Azure template with GPU and taints it should set all annotations", + name: "When Azure template with GPU and taints, it should set all annotations", provider: &mockProvider{info: &instancetype.InstanceTypeInfo{ VCPU: 6, MemoryMb: 114688, GPU: 1, CPUArchitecture: "amd64", }}, @@ -272,7 +272,7 @@ func TestSetScaleFromZeroAnnotationsOnObject(t *testing.T) { }, }, { - name: "When instance has GPU, labels with arch override, taints, and existing annotations it should set all correctly", + name: "When instance has GPU, labels with arch override, taints, and existing annotations, it should set all correctly", provider: &mockProvider{info: &instancetype.InstanceTypeInfo{ VCPU: 8, MemoryMb: 61440, GPU: 1, CPUArchitecture: "arm64", }}, diff --git a/hypershift-operator/controllers/nodepool/secret_janitor_test.go b/hypershift-operator/controllers/nodepool/secret_janitor_test.go index 9ff1f7c4272e..3f1675532867 100644 --- a/hypershift-operator/controllers/nodepool/secret_janitor_test.go +++ b/hypershift-operator/controllers/nodepool/secret_janitor_test.go @@ -182,7 +182,7 @@ spec: expected *corev1.Secret }{ { - name: "unrelated secret untouched", + name: "When secret is unrelated, it should leave it untouched", input: &corev1.Secret{ ObjectMeta: metav1.ObjectMeta{ Name: "whatever", @@ -197,7 +197,7 @@ spec: }, }, { - name: "related but not known secret untouched", + name: "When secret is related but not known, it should leave it untouched", input: &corev1.Secret{ ObjectMeta: metav1.ObjectMeta{ Name: "related", @@ -218,7 +218,7 @@ spec: }, }, { - name: "related known secret with correct hash untouched", + name: "When secret is related and has correct hash, it should leave it untouched", input: &corev1.Secret{ ObjectMeta: metav1.ObjectMeta{ Name: "token-nodepool-name-64587037", @@ -239,7 +239,7 @@ spec: }, }, { - name: "related token secret with incorrect hash set for expiry", + name: "When token secret has incorrect hash, it should set it for expiry", input: &corev1.Secret{ ObjectMeta: metav1.ObjectMeta{ Name: "token-nodepool-name-jsadfkjh23", @@ -261,7 +261,7 @@ spec: }, }, { - name: "related ignition user data secret with incorrect hash deleted", + name: "When ignition user data secret has incorrect hash, it should delete it", input: &corev1.Secret{ ObjectMeta: metav1.ObjectMeta{ Name: "user-data-nodepool-name-jsadfkjh23", @@ -484,7 +484,7 @@ func TestShouldKeepOldUserData(t *testing.T) { expected bool }{ { - name: "when hosted cluster is not aws or kubevirt it should NOT keep old user data", + name: "When hosted cluster is not aws or kubevirt, it should NOT keep old user data", hc: &hyperv1.HostedCluster{ TypeMeta: metav1.TypeMeta{}, ObjectMeta: metav1.ObjectMeta{ @@ -507,7 +507,7 @@ func TestShouldKeepOldUserData(t *testing.T) { expected: false, }, { - name: "when hosted cluster is kubevirt it should keep old user data", + name: "When hosted cluster is kubevirt, it should keep old user data", hc: &hyperv1.HostedCluster{ TypeMeta: metav1.TypeMeta{}, ObjectMeta: metav1.ObjectMeta{ @@ -530,7 +530,7 @@ func TestShouldKeepOldUserData(t *testing.T) { expected: true, }, { - name: "when hosted cluster is less than 4.16 it should keep user data", + name: "When hosted cluster is less than 4.16, it should keep user data", hc: &hyperv1.HostedCluster{ TypeMeta: metav1.TypeMeta{}, ObjectMeta: metav1.ObjectMeta{ @@ -554,7 +554,7 @@ func TestShouldKeepOldUserData(t *testing.T) { expected: true, }, { - name: "when hosted cluster is equal or greater than 4.16 it should NOT keep user data", + name: "When hosted cluster is equal or greater than 4.16, it should NOT keep user data", hc: &hyperv1.HostedCluster{ TypeMeta: metav1.TypeMeta{}, ObjectMeta: metav1.ObjectMeta{ diff --git a/hypershift-operator/controllers/nodepool/stream_test.go b/hypershift-operator/controllers/nodepool/stream_test.go index 2293c7f0bc64..7a819333eaa1 100644 --- a/hypershift-operator/controllers/nodepool/stream_test.go +++ b/hypershift-operator/controllers/nodepool/stream_test.go @@ -104,13 +104,13 @@ func TestGetRHELStream(t *testing.T) { // --- Explicit rhel-10 --- { - name: "When explicit rhel-10 and release is 4.x it should return error", + name: "When explicit rhel-10 and release is 4.x, it should return error", explicitStream: "rhel-10", releaseVersion: semver.MustParse("4.19.0"), expectError: true, }, { - name: "When explicit rhel-10 and release is 4.x with runc it should return error", + name: "When explicit rhel-10 and release is 4.x with runc, it should return error", explicitStream: "rhel-10", releaseVersion: semver.MustParse("4.19.0"), usesRunc: true, @@ -123,7 +123,7 @@ func TestGetRHELStream(t *testing.T) { expectResult: "rhel-10", }, { - name: "When explicit rhel-10 and release is 5.0 with runc it should return error", + name: "When explicit rhel-10 and release is 5.0 with runc, it should return error", explicitStream: "rhel-10", releaseVersion: semver.MustParse("5.0.0"), usesRunc: true, @@ -136,7 +136,7 @@ func TestGetRHELStream(t *testing.T) { expectResult: "rhel-10", }, { - name: "When explicit rhel-10 and release is 5.1 with runc it should return error", + name: "When explicit rhel-10 and release is 5.1 with runc, it should return error", explicitStream: "rhel-10", releaseVersion: semver.MustParse("5.1.0"), usesRunc: true, @@ -145,13 +145,13 @@ func TestGetRHELStream(t *testing.T) { // --- Unknown stream --- { - name: "When explicit unknown stream and release is 4.x it should return error", + name: "When explicit unknown stream and release is 4.x, it should return error", explicitStream: "rhel-8", releaseVersion: semver.MustParse("4.18.0"), expectError: true, }, { - name: "When explicit unknown stream and release is 5.0 it should return error", + name: "When explicit unknown stream and release is 5.0, it should return error", explicitStream: "rhel-8", releaseVersion: semver.MustParse("5.0.0"), expectError: true, diff --git a/hypershift-operator/controllers/nodepool/token_test.go b/hypershift-operator/controllers/nodepool/token_test.go index e4d464784866..d661338c5eb7 100644 --- a/hypershift-operator/controllers/nodepool/token_test.go +++ b/hypershift-operator/controllers/nodepool/token_test.go @@ -358,7 +358,7 @@ func TestTokenCleanupOutdated(t *testing.T) { expectedError string }{ { - name: "When userdata and token secret are outdated userdata secret should be deleted and token secret should get and expiration timestamp", + name: "When userdata and token secret are outdated, it should delete userdata secret and add expiration timestamp to token secret", token: &Token{ ConfigGenerator: &ConfigGenerator{ nodePool: &hyperv1.NodePool{ @@ -435,7 +435,7 @@ func TestTokenCleanupOutdated(t *testing.T) { expectedError: "", }, { - name: "When platform is KubeVirt, outdated userdata secret should be preserved and token secret should get an expiration timestamp", + name: "When platform is KubeVirt, it should preserve outdated userdata secret and add expiration timestamp to token secret", token: &Token{ ConfigGenerator: &ConfigGenerator{ nodePool: &hyperv1.NodePool{ @@ -461,7 +461,7 @@ func TestTokenCleanupOutdated(t *testing.T) { expectedError: "", }, { - name: "When platform is AWS, outdated userdata secret should be preserved and token secret should get an expiration timestamp", + name: "When platform is AWS, it should preserve outdated userdata secret and add expiration timestamp to token secret", token: &Token{ ConfigGenerator: &ConfigGenerator{ nodePool: &hyperv1.NodePool{ diff --git a/hypershift-operator/controllers/nodepool/version_test.go b/hypershift-operator/controllers/nodepool/version_test.go index b22ddd0bfbf3..34d7a9695974 100644 --- a/hypershift-operator/controllers/nodepool/version_test.go +++ b/hypershift-operator/controllers/nodepool/version_test.go @@ -23,7 +23,7 @@ func TestNodeVersionsFromMachines(t *testing.T) { expected []hyperv1.NodeVersion }{ { - name: "When there are no machines it should return nil", + name: "When there are no machines, it should return nil", machines: nil, nodePool: &hyperv1.NodePool{ Status: hyperv1.NodePoolStatus{Version: "4.18.12"}, @@ -31,7 +31,7 @@ func TestNodeVersionsFromMachines(t *testing.T) { expected: nil, }, { - name: "When all machines have the same version and are healthy it should return a single entry", + name: "When all machines have the same version and are healthy, it should return a single entry", machines: []*v1beta1.Machine{ machineWithVersionAndHealth("m1", "v1.31.4", true, map[string]string{hyperv1.NodePoolReleaseVersionAnnotation: "4.18.12"}), machineWithVersionAndHealth("m2", "v1.31.4", true, map[string]string{hyperv1.NodePoolReleaseVersionAnnotation: "4.18.12"}), @@ -45,7 +45,7 @@ func TestNodeVersionsFromMachines(t *testing.T) { }, }, { - name: "When there are mixed versions during rolling upgrade it should return one entry per version", + name: "When there are mixed versions during rolling upgrade, it should return one entry per version", machines: []*v1beta1.Machine{ machineWithVersionAndHealth("m1", "v1.31.4", true, map[string]string{hyperv1.NodePoolReleaseVersionAnnotation: "4.18.12"}), machineWithVersionAndHealth("m2", "v1.31.4", true, map[string]string{hyperv1.NodePoolReleaseVersionAnnotation: "4.18.12"}), @@ -60,7 +60,7 @@ func TestNodeVersionsFromMachines(t *testing.T) { }, }, { - name: "When there is mixed health it should report ready and unready counts per version", + name: "When there is mixed health, it should report ready and unready counts per version", machines: []*v1beta1.Machine{ machineWithVersionAndHealth("m1", "v1.31.4", true, map[string]string{hyperv1.NodePoolReleaseVersionAnnotation: "4.18.12"}), machineWithVersionAndHealth("m2", "v1.32.1", true, map[string]string{hyperv1.NodePoolReleaseVersionAnnotation: "4.19.1"}), @@ -75,7 +75,7 @@ func TestNodeVersionsFromMachines(t *testing.T) { }, }, { - name: "When NodeHealthy condition is absent it should count the node as unready", + name: "When NodeHealthy condition is absent, it should count the node as unready", machines: []*v1beta1.Machine{ machineWithVersionAndConditions("m1", "v1.31.4", nil, map[string]string{hyperv1.NodePoolReleaseVersionAnnotation: "4.18.12"}), }, @@ -87,7 +87,7 @@ func TestNodeVersionsFromMachines(t *testing.T) { }, }, { - name: "When some machines have no NodeInfo it should skip them", + name: "When some machines have no NodeInfo, it should skip them", machines: []*v1beta1.Machine{ machineWithVersionAndHealth("m1", "v1.31.4", true, map[string]string{hyperv1.NodePoolReleaseVersionAnnotation: "4.18.12"}), { @@ -108,7 +108,7 @@ func TestNodeVersionsFromMachines(t *testing.T) { }, }, { - name: "When all machines have no NodeInfo it should return nil", + name: "When all machines have no NodeInfo, it should return nil", machines: []*v1beta1.Machine{ { ObjectMeta: metav1.ObjectMeta{Name: "m1"}, @@ -121,7 +121,7 @@ func TestNodeVersionsFromMachines(t *testing.T) { expected: nil, }, { - name: "When machine has release-version annotation it should use it for ocpVersion", + name: "When machine has release-version annotation, it should use it for ocpVersion", machines: []*v1beta1.Machine{ machineWithVersionAndHealth("m1", "v1.31.4", true, map[string]string{hyperv1.NodePoolReleaseVersionAnnotation: "4.18.12"}), }, @@ -133,7 +133,7 @@ func TestNodeVersionsFromMachines(t *testing.T) { }, }, { - name: "When machine has no annotation it should fall back to nodePool.Status.Version", + name: "When machine has no annotation, it should fall back to nodePool.Status.Version", machines: []*v1beta1.Machine{ machineWithVersionAndHealth("m1", "v1.31.4", true, nil), }, @@ -145,7 +145,7 @@ func TestNodeVersionsFromMachines(t *testing.T) { }, }, { - name: "When there are multiple versions it should sort by ocpVersion then kubeletVersion", + name: "When there are multiple versions, it should sort by ocpVersion then kubeletVersion", machines: []*v1beta1.Machine{ machineWithVersionAndHealth("m1", "v1.32.1", true, map[string]string{hyperv1.NodePoolReleaseVersionAnnotation: "4.19.1"}), machineWithVersionAndHealth("m2", "v1.31.4", true, map[string]string{hyperv1.NodePoolReleaseVersionAnnotation: "4.18.12"}), @@ -299,47 +299,47 @@ func TestRhcosStreamFromOSImage(t *testing.T) { expected string }{ { - name: "When OSImage is RHCOS 4xx it should return rhel-9", + name: "When OSImage is RHCOS 4xx, it should return rhel-9", osImage: "Red Hat Enterprise Linux CoreOS 419.97.202505081234-0 (Plow)", expected: StreamRHEL9, }, { - name: "When OSImage is RHCOS 5xx it should return rhel-10", + name: "When OSImage is RHCOS 5xx, it should return rhel-10", osImage: "Red Hat Enterprise Linux CoreOS 510.97.202506011200-0 (Plow)", expected: StreamRHEL10, }, { - name: "When OSImage has different 4xx version it should return rhel-9", + name: "When OSImage has different 4xx version, it should return rhel-9", osImage: "Red Hat Enterprise Linux CoreOS 418.94.202501011200-0 (Plow)", expected: StreamRHEL9, }, { - name: "When OSImage is empty it should return empty string", + name: "When OSImage is empty, it should return empty string", osImage: "", expected: "", }, { - name: "When OSImage is unrecognized it should return empty string", + name: "When OSImage is unrecognized, it should return empty string", osImage: "Ubuntu 22.04 LTS", expected: "", }, { - name: "When OSImage has unknown major version it should return empty string", + name: "When OSImage has unknown major version, it should return empty string", osImage: "Red Hat Enterprise Linux CoreOS 300.97.202505081234-0 (Plow)", expected: "", }, { - name: "When OSImage uses new OCP 5.0 format with RHEL 9 it should return rhel-9", + name: "When OSImage uses new OCP 5.0 format with RHEL 9, it should return rhel-9", osImage: "Red Hat Enterprise Linux CoreOS 9.8.20260721-0 (Plow)", expected: StreamRHEL9, }, { - name: "When OSImage uses new OCP 5.0 format with RHEL 10 it should return rhel-10", + name: "When OSImage uses new OCP 5.0 format with RHEL 10, it should return rhel-10", osImage: "Red Hat Enterprise Linux CoreOS 10.2.20260801-0 (Plow)", expected: StreamRHEL10, }, { - name: "When OSImage uses new format with unknown major it should return empty string", + name: "When OSImage uses new format with unknown major, it should return empty string", osImage: "Red Hat Enterprise Linux CoreOS 8.5.20260101-0 (Plow)", expected: "", }, @@ -360,19 +360,19 @@ func TestOsImageStreamFromMachines(t *testing.T) { expected string }{ { - name: "When there are no machines it should return empty string", + name: "When there are no machines, it should return empty string", machines: nil, expected: "", }, { - name: "When a single machine reports RHEL 9 it should return rhel-9", + name: "When a single machine reports RHEL 9, it should return rhel-9", machines: []*v1beta1.Machine{ machineWithOSImage("m1", "Red Hat Enterprise Linux CoreOS 419.97.202505081234-0 (Plow)"), }, expected: StreamRHEL9, }, { - name: "When all machines report RHEL 9 it should return rhel-9", + name: "When all machines report RHEL 9, it should return rhel-9", machines: []*v1beta1.Machine{ machineWithOSImage("m1", "Red Hat Enterprise Linux CoreOS 419.97.202505081234-0 (Plow)"), machineWithOSImage("m2", "Red Hat Enterprise Linux CoreOS 419.97.202505081234-0 (Plow)"), @@ -381,7 +381,7 @@ func TestOsImageStreamFromMachines(t *testing.T) { expected: StreamRHEL9, }, { - name: "When all machines report RHEL 10 it should return rhel-10", + name: "When all machines report RHEL 10, it should return rhel-10", machines: []*v1beta1.Machine{ machineWithOSImage("m1", "Red Hat Enterprise Linux CoreOS 510.97.202506011200-0 (Plow)"), machineWithOSImage("m2", "Red Hat Enterprise Linux CoreOS 510.97.202506011200-0 (Plow)"), @@ -389,7 +389,7 @@ func TestOsImageStreamFromMachines(t *testing.T) { expected: StreamRHEL10, }, { - name: "When a majority reports RHEL 10 during rolling upgrade it should return rhel-10", + name: "When a majority reports RHEL 10 during rolling upgrade, it should return rhel-10", machines: []*v1beta1.Machine{ machineWithOSImage("m1", "Red Hat Enterprise Linux CoreOS 419.97.202505081234-0 (Plow)"), machineWithOSImage("m2", "Red Hat Enterprise Linux CoreOS 510.97.202506011200-0 (Plow)"), @@ -398,7 +398,7 @@ func TestOsImageStreamFromMachines(t *testing.T) { expected: StreamRHEL10, }, { - name: "When streams are evenly split it should return empty string", + name: "When streams are evenly split, it should return empty string", machines: []*v1beta1.Machine{ machineWithOSImage("m1", "Red Hat Enterprise Linux CoreOS 419.97.202505081234-0 (Plow)"), machineWithOSImage("m2", "Red Hat Enterprise Linux CoreOS 510.97.202506011200-0 (Plow)"), @@ -406,21 +406,21 @@ func TestOsImageStreamFromMachines(t *testing.T) { expected: "", }, { - name: "When machines have no NodeInfo it should return empty string", + name: "When machines have no NodeInfo, it should return empty string", machines: []*v1beta1.Machine{ {ObjectMeta: metav1.ObjectMeta{Name: "m1"}, Status: v1beta1.MachineStatus{}}, }, expected: "", }, { - name: "When machines have unrecognized OSImage it should return empty string", + name: "When machines have unrecognized OSImage, it should return empty string", machines: []*v1beta1.Machine{ machineWithOSImage("m1", "Ubuntu 22.04 LTS"), }, expected: "", }, { - name: "When some machines have no NodeInfo it should count only those with NodeInfo", + name: "When some machines have no NodeInfo, it should count only those with NodeInfo", machines: []*v1beta1.Machine{ machineWithOSImage("m1", "Red Hat Enterprise Linux CoreOS 510.97.202506011200-0 (Plow)"), {ObjectMeta: metav1.ObjectMeta{Name: "m2"}, Status: v1beta1.MachineStatus{}}, diff --git a/hypershift-operator/controllers/platform/aws/controller_test.go b/hypershift-operator/controllers/platform/aws/controller_test.go index 9fec1cfeb25a..762f22372c75 100644 --- a/hypershift-operator/controllers/platform/aws/controller_test.go +++ b/hypershift-operator/controllers/platform/aws/controller_test.go @@ -52,25 +52,25 @@ func TestReconcileAWSEndpointServiceStatus(t *testing.T) { expectedPrincipalsToRemove []string }{ { - name: "no additional principals", + name: "When there are no additional principals it should add only the CPO role ARN", hasInfraCapability: true, expectedPrincipalsToAdd: []string{mockControlPlaneOperatorRoleArn}, }, { - name: "additional principals", + name: "When additional principals are specified it should add them alongside the CPO role ARN", hasInfraCapability: true, additionalAllowedPrincipals: []string{"additional1", "additional2"}, expectedPrincipalsToAdd: []string{mockControlPlaneOperatorRoleArn, "additional1", "additional2"}, }, { - name: "removing extra principals", + name: "When extra principals exist it should remove them", hasInfraCapability: true, existingAllowedPrincipals: []string{"existing1", "existing2"}, expectedPrincipalsToAdd: []string{mockControlPlaneOperatorRoleArn}, expectedPrincipalsToRemove: []string{"existing1", "existing2"}, }, { - name: "no infrastructure capability omits owned tag", + name: "When there is no infrastructure capability it should omit the owned tag", hasInfraCapability: false, expectedPrincipalsToAdd: []string{mockControlPlaneOperatorRoleArn}, }, @@ -213,7 +213,7 @@ func TestDeleteAWSEndpointService(t *testing.T) { expectErr bool }{ { - name: "When deletion succeeds it should return completed", + name: "When deletion succeeds, it should return completed", deleteOut: &ec2.DeleteVpcEndpointServiceConfigurationsOutput{ Unsuccessful: []ec2types.UnsuccessfulItem{}, }, @@ -221,7 +221,7 @@ func TestDeleteAWSEndpointService(t *testing.T) { expectErr: false, }, { - name: "When endpoint service no longer exists it should return completed", + name: "When endpoint service no longer exists, it should return completed", deleteOut: &ec2.DeleteVpcEndpointServiceConfigurationsOutput{ Unsuccessful: []ec2types.UnsuccessfulItem{ { @@ -237,7 +237,7 @@ func TestDeleteAWSEndpointService(t *testing.T) { expectErr: false, }, { - name: "When existing connections are in Available state it should reject them", + name: "When existing connections are in Available state, it should reject them", deleteOut: existingConnectionsDeleteOut, describeOut: &ec2.DescribeVpcEndpointConnectionsOutput{ VpcEndpointConnections: []ec2types.VpcEndpointConnection{ @@ -252,7 +252,7 @@ func TestDeleteAWSEndpointService(t *testing.T) { expectErr: true, }, { - name: "When existing connections are in Rejected state it should not reject and return not completed without error", + name: "When existing connections are in Rejected state, it should not reject and return not completed without error", deleteOut: existingConnectionsDeleteOut, describeOut: &ec2.DescribeVpcEndpointConnectionsOutput{ VpcEndpointConnections: []ec2types.VpcEndpointConnection{ @@ -267,7 +267,7 @@ func TestDeleteAWSEndpointService(t *testing.T) { expectErr: false, }, { - name: "When existing connections are in Deleting state it should not reject and return not completed without error", + name: "When existing connections are in Deleting state, it should not reject and return not completed without error", deleteOut: existingConnectionsDeleteOut, describeOut: &ec2.DescribeVpcEndpointConnectionsOutput{ VpcEndpointConnections: []ec2types.VpcEndpointConnection{ @@ -282,7 +282,7 @@ func TestDeleteAWSEndpointService(t *testing.T) { expectErr: false, }, { - name: "When existing connections are a mix of Available and Rejected it should reject the Available ones and return not completed without error", + name: "When existing connections are a mix of Available and Rejected, it should reject the Available ones and return not completed without error", deleteOut: existingConnectionsDeleteOut, describeOut: &ec2.DescribeVpcEndpointConnectionsOutput{ VpcEndpointConnections: []ec2types.VpcEndpointConnection{ @@ -305,7 +305,7 @@ func TestDeleteAWSEndpointService(t *testing.T) { expectErr: false, }, { - name: "When existing connections are all in terminal states it should return not completed with error", + name: "When existing connections are all in terminal states, it should return not completed with error", deleteOut: existingConnectionsDeleteOut, describeOut: &ec2.DescribeVpcEndpointConnectionsOutput{ VpcEndpointConnections: []ec2types.VpcEndpointConnection{ @@ -324,7 +324,7 @@ func TestDeleteAWSEndpointService(t *testing.T) { expectErr: true, }, { - name: "When DeleteVpcEndpointServiceConfigurations returns an API error it should attempt to reject and return error", + name: "When DeleteVpcEndpointServiceConfigurations returns an API error, it should attempt to reject and return error", deleteErr: fmt.Errorf("aws api error"), describeOut: &ec2.DescribeVpcEndpointConnectionsOutput{ VpcEndpointConnections: []ec2types.VpcEndpointConnection{}, @@ -333,14 +333,14 @@ func TestDeleteAWSEndpointService(t *testing.T) { expectErr: true, }, { - name: "When DescribeVpcEndpointConnections fails it should return error", + name: "When DescribeVpcEndpointConnections fails, it should return error", deleteOut: existingConnectionsDeleteOut, describeErr: fmt.Errorf("describe connections error"), expected: false, expectErr: true, }, { - name: "When RejectVpcEndpointConnections fails it should return error", + name: "When RejectVpcEndpointConnections fails, it should return error", deleteOut: existingConnectionsDeleteOut, describeOut: &ec2.DescribeVpcEndpointConnectionsOutput{ VpcEndpointConnections: []ec2types.VpcEndpointConnection{ @@ -619,14 +619,14 @@ func TestRejectVpcEndpointConnections(t *testing.T) { }) } -func Test_controlPlaneOperatorRoleARNWithoutPath(t *testing.T) { +func TestControlPlaneOperatorRoleARNWithoutPath(t *testing.T) { tests := []struct { name string hc *hyperv1.HostedCluster expected string }{ { - name: "ARN without path", + name: "When ARN has no path, it should return unchanged", hc: &hyperv1.HostedCluster{ Spec: hyperv1.HostedClusterSpec{ Platform: hyperv1.PlatformSpec{ @@ -641,7 +641,7 @@ func Test_controlPlaneOperatorRoleARNWithoutPath(t *testing.T) { expected: "arn:aws:iam::12345678910:role/test-name", }, { - name: "ARN with path", + name: "When ARN has a path, it should strip the path prefix", hc: &hyperv1.HostedCluster{ Spec: hyperv1.HostedClusterSpec{ Platform: hyperv1.PlatformSpec{ @@ -713,7 +713,7 @@ func TestListKarpenterSubnetIDs(t *testing.T) { expectedSubnets: []string{}, }, { - name: "When the ConfigMap contains malformed JSON it should return an error", + name: "When the ConfigMap contains malformed JSON, it should return an error", namespace: "test-namespace", objects: []client.Object{ &corev1.ConfigMap{ diff --git a/hypershift-operator/controllers/platform/gcp/privateserviceconnect_controller_test.go b/hypershift-operator/controllers/platform/gcp/privateserviceconnect_controller_test.go index 8aa7d4e012b3..e21f3d9420db 100644 --- a/hypershift-operator/controllers/platform/gcp/privateserviceconnect_controller_test.go +++ b/hypershift-operator/controllers/platform/gcp/privateserviceconnect_controller_test.go @@ -76,36 +76,36 @@ func TestIsNotFoundError(t *testing.T) { expected bool }{ { - name: "GCP 404 error", + name: "When given a GCP 404 error, it should return true", err: &googleapi.Error{ Code: 404, }, expected: true, }, { - name: "GCP 400 error", + name: "When given a GCP 400 error, it should return false", err: &googleapi.Error{ Code: 400, }, expected: false, }, { - name: "non-GCP error", + name: "When given a non-GCP error, it should return false", err: errors.New("some other error"), expected: false, }, { - name: "nil error", + name: "When given a nil error, it should return false", err: nil, expected: false, }, { - name: "When given a wrapped GCP 404 error it should return true", + name: "When given a wrapped GCP 404 error, it should return true", err: fmt.Errorf("operation failed: %w", &googleapi.Error{Code: 404}), expected: true, }, { - name: "When given a wrapped GCP 500 error it should return false", + name: "When given a wrapped GCP 500 error, it should return false", err: fmt.Errorf("operation failed: %w", &googleapi.Error{Code: 500}), expected: false, }, @@ -172,7 +172,7 @@ func TestReconcileGCPPrivateServiceConnectSpec(t *testing.T) { } } -func TestReconcile_NotFound(t *testing.T) { +func TestReconcileNotFound(t *testing.T) { client := fake.NewClientBuilder().WithScheme(hyperapi.Scheme).Build() r := &GCPPrivateServiceConnectReconciler{ @@ -199,7 +199,7 @@ func TestReconcile_NotFound(t *testing.T) { } } -func TestReconcile_PausedUntil(t *testing.T) { +func TestReconcilePausedUntil(t *testing.T) { // Use a dynamically computed future time so the test remains valid over time pausedUntil := time.Now().Add(24 * time.Hour).UTC().Format(time.RFC3339) @@ -281,12 +281,12 @@ func TestIPAddressFilterFormat(t *testing.T) { expected string }{ { - name: "When filtering by IPv4 address it should use AIP-160 exact match syntax", + name: "When filtering by IPv4 address, it should use AIP-160 exact match syntax", ip: "10.0.0.1", expected: `IPAddress = "10.0.0.1"`, }, { - name: "When filtering by IPv4 address with different octets it should quote properly", + name: "When filtering by IPv4 address with different octets, it should quote properly", ip: "192.168.1.100", expected: `IPAddress = "192.168.1.100"`, }, @@ -312,7 +312,7 @@ func TestConstructServiceAttachmentName(t *testing.T) { description string }{ { - name: "When given a cluster ID it should construct valid service attachment name", + name: "When given a cluster ID, it should construct valid service attachment name", hc: &hyperv1.HostedCluster{ ObjectMeta: metav1.ObjectMeta{Name: "test-cluster"}, Spec: hyperv1.HostedClusterSpec{ @@ -345,7 +345,7 @@ func TestNATSubnetFilterFormat(t *testing.T) { expected string }{ { - name: "When given a network URL it should include both purpose and network in the filter", + name: "When given a network URL, it should include both purpose and network in the filter", networkURL: "https://www.googleapis.com/compute/v1/projects/my-project/global/networks/my-vpc", expected: `purpose = "PRIVATE_SERVICE_CONNECT" AND network = "https://www.googleapis.com/compute/v1/projects/my-project/global/networks/my-vpc"`, }, @@ -384,7 +384,7 @@ func newGCPPSC(forwardingRuleName, natSubnet string) *hyperv1.GCPPrivateServiceC // --- lookupForwardingRule --- -func TestLookupForwardingRule_APIError(t *testing.T) { +func TestLookupForwardingRuleAPIError(t *testing.T) { r := newReconciler(t, &fakeComputeClient{forwardingRulesErr: errors.New("GCP unavailable")}) rule, err := r.lookupForwardingRule(context.Background(), newGCPPSC("", "")) if err == nil { @@ -395,7 +395,7 @@ func TestLookupForwardingRule_APIError(t *testing.T) { } } -func TestLookupForwardingRule_NoResults(t *testing.T) { +func TestLookupForwardingRuleNoResults(t *testing.T) { r := newReconciler(t, &fakeComputeClient{forwardingRules: nil}) rule, err := r.lookupForwardingRule(context.Background(), newGCPPSC("", "")) if err != nil { @@ -406,7 +406,7 @@ func TestLookupForwardingRule_NoResults(t *testing.T) { } } -func TestLookupForwardingRule_SingleResult(t *testing.T) { +func TestLookupForwardingRuleSingleResult(t *testing.T) { expected := &compute.ForwardingRule{Name: "fr-1", Network: "https://www.googleapis.com/compute/v1/projects/p/global/networks/my-vpc"} r := newReconciler(t, &fakeComputeClient{forwardingRules: []*compute.ForwardingRule{expected}}) rule, err := r.lookupForwardingRule(context.Background(), newGCPPSC("", "")) @@ -418,7 +418,7 @@ func TestLookupForwardingRule_SingleResult(t *testing.T) { } } -func TestLookupForwardingRule_MultipleResults_UsesFirst(t *testing.T) { +func TestLookupForwardingRuleMultipleResultsUsesFirst(t *testing.T) { rules := []*compute.ForwardingRule{ {Name: "fr-first", Network: "https://www.googleapis.com/compute/v1/projects/p/global/networks/my-vpc"}, {Name: "fr-second", Network: "https://www.googleapis.com/compute/v1/projects/p/global/networks/my-vpc"}, @@ -435,7 +435,7 @@ func TestLookupForwardingRule_MultipleResults_UsesFirst(t *testing.T) { // --- reconcileGCPPrivateServiceConnectSpec --- -func TestReconcileSpec_BothFieldsSet_EarlyReturn(t *testing.T) { +func TestReconcileSpecBothFieldsSetEarlyReturn(t *testing.T) { // GcpClient is nil — proves no GCP call is made when both fields are already set. r := newReconciler(t, nil) gcpPSC := newGCPPSC("existing-rule", "existing-subnet") @@ -444,7 +444,7 @@ func TestReconcileSpec_BothFieldsSet_EarlyReturn(t *testing.T) { } } -func TestReconcileSpec_ForwardingRuleLookupError(t *testing.T) { +func TestReconcileSpecForwardingRuleLookupError(t *testing.T) { r := newReconciler(t, &fakeComputeClient{forwardingRulesErr: errors.New("api error")}) err := r.reconcileGCPPrivateServiceConnectSpec(context.Background(), newGCPPSC("", ""), nil) if err == nil { @@ -452,7 +452,7 @@ func TestReconcileSpec_ForwardingRuleLookupError(t *testing.T) { } } -func TestReconcileSpec_ForwardingRuleNotYetProvisioned(t *testing.T) { +func TestReconcileSpecForwardingRuleNotYetProvisioned(t *testing.T) { // nil result from lookupForwardingRule — ILB not yet ready, should return nil (requeue). r := newReconciler(t, &fakeComputeClient{forwardingRules: nil}) err := r.reconcileGCPPrivateServiceConnectSpec(context.Background(), newGCPPSC("", ""), nil) @@ -461,7 +461,7 @@ func TestReconcileSpec_ForwardingRuleNotYetProvisioned(t *testing.T) { } } -func TestReconcileSpec_ForwardingRuleEmptyNetwork(t *testing.T) { +func TestReconcileSpecForwardingRuleEmptyNetwork(t *testing.T) { // Forwarding rule exists but has no Network field — cannot scope subnet discovery. r := newReconciler(t, &fakeComputeClient{ forwardingRules: []*compute.ForwardingRule{{Name: "fr-1", Network: ""}}, @@ -472,7 +472,7 @@ func TestReconcileSpec_ForwardingRuleEmptyNetwork(t *testing.T) { } } -func TestReconcileSpec_SetsForwardingRuleNameAndNATSubnet(t *testing.T) { +func TestReconcileSpecSetsForwardingRuleNameAndNATSubnet(t *testing.T) { networkURL := "https://www.googleapis.com/compute/v1/projects/p/global/networks/my-vpc" r := newReconciler(t, &fakeComputeClient{ forwardingRules: []*compute.ForwardingRule{{Name: "fr-1", Network: networkURL}}, @@ -492,7 +492,7 @@ func TestReconcileSpec_SetsForwardingRuleNameAndNATSubnet(t *testing.T) { } } -func TestReconcileSpec_PartialWrite_ForwardingRuleNamePreservedNATSubnetDiscovered(t *testing.T) { +func TestReconcileSpecPartialWriteForwardingRuleNamePreservedNATSubnetDiscovered(t *testing.T) { // Partial-write edge case: ForwardingRuleName was already written in a previous reconcile // but NATSubnet was not (e.g. discoverNATSubnet failed transiently). The controller must // preserve the existing ForwardingRuleName rather than overwriting it, and still use the @@ -526,7 +526,7 @@ func TestReconcileSpec_PartialWrite_ForwardingRuleNamePreservedNATSubnetDiscover // --- discoverNATSubnet --- -func TestDiscoverNATSubnet_APIError(t *testing.T) { +func TestDiscoverNATSubnetAPIError(t *testing.T) { networkURL := "https://example.com/network" fc := &fakeComputeClient{subnetworksErr: errors.New("api error")} r := newReconciler(t, fc) @@ -540,7 +540,7 @@ func TestDiscoverNATSubnet_APIError(t *testing.T) { } } -func TestDiscoverNATSubnet_NoSubnets(t *testing.T) { +func TestDiscoverNATSubnetNoSubnets(t *testing.T) { networkURL := "https://example.com/network" fc := &fakeComputeClient{subnetworks: nil} r := newReconciler(t, fc) @@ -554,7 +554,7 @@ func TestDiscoverNATSubnet_NoSubnets(t *testing.T) { } } -func TestDiscoverNATSubnet_SubnetInUse_SkipsToNext(t *testing.T) { +func TestDiscoverNATSubnetSubnetInUseSkipsToNext(t *testing.T) { networkURL := "https://example.com/network" fc := &fakeComputeClient{ subnetworks: []*compute.Subnetwork{ @@ -580,7 +580,7 @@ func TestDiscoverNATSubnet_SubnetInUse_SkipsToNext(t *testing.T) { } } -func TestDiscoverNATSubnet_AllSubnetsInUse(t *testing.T) { +func TestDiscoverNATSubnetAllSubnetsInUse(t *testing.T) { networkURL := "https://example.com/network" fc := &fakeComputeClient{ subnetworks: []*compute.Subnetwork{{Name: "only-subnet"}}, diff --git a/hypershift-operator/controllers/scheduler/aws/autoscaler_test.go b/hypershift-operator/controllers/scheduler/aws/autoscaler_test.go index a56331d7285a..86554e0c7fec 100644 --- a/hypershift-operator/controllers/scheduler/aws/autoscaler_test.go +++ b/hypershift-operator/controllers/scheduler/aws/autoscaler_test.go @@ -34,14 +34,14 @@ func TestHostedClusterMachineSetsToScaleDown(t *testing.T) { expectRequeueAfter time.Duration }{ { - name: "Hosted cluster has no additional node selector - (migrating from legacy scheduler)", + name: "When hosted cluster has no additional node selector it should not scale down any machinesets", hostedCluster: hc, machineSets: machineSets(10), nodes: nodes(10, withHC(hc, 0, 1, 2, 3, 4, 5), withPairLabel("pair1", 0, 1, 2, 3, 4, 5), withSizeLabel("small", 0, 1), withSizeLabel("medium", 2, 3), withSizeLabel("large", 4, 5)), machines: machines(10), }, { - name: "Hosted cluster has additional node selector (small)", + name: "When hosted cluster has additional node selector for small, it should scale down non-matching machinesets", hostedCluster: hostedCluster(withAdditionalNodeSelector(fmt.Sprintf("%s=small", hyperv1.NodeSizeLabel)), withHCSizeLabel("small")), machineSets: machineSets(10, withReplicas(1)), nodes: nodes(10, withHC(hc, 0, 1, 2, 3, 4, 5), withPairLabel("pair1", 0, 1, 2, 3, 4, 5), withSizeLabel("small", 0, 1), withSizeLabel("medium", 2, 3), withSizeLabel("large", 4, 5)), @@ -49,7 +49,7 @@ func TestHostedClusterMachineSetsToScaleDown(t *testing.T) { expected: machineSets(6, withReplicas(1))[2:], // machinesets 2, 3, 4, 5 }, { - name: "Hosted cluster has additional node selector (medium), some nodes are new", + name: "When hosted cluster has additional node selector for medium and some nodes are new, it should defer scale down", hostedCluster: hostedCluster(withAdditionalNodeSelector(fmt.Sprintf("%s=medium", hyperv1.NodeSizeLabel))), machineSets: machineSets(10, withReplicas(1)), nodes: nodes(10, withHC(hc, 0, 1, 2, 3, 4, 5), withPairLabel("pair1", 0, 1, 2, 3, 4, 5), withSizeLabel("small", 0, 1), withSizeLabel("medium", 2, 3), withSizeLabel("large", 4, 5), withCreationTimestamp(twoMinutesAgo, 0, 1)), @@ -58,7 +58,7 @@ func TestHostedClusterMachineSetsToScaleDown(t *testing.T) { expectRequeueAfter: nodeScaleDownDelay, }, { - name: "Hosted cluster has additional node selector (large), all nodes are new", + name: "When hosted cluster has additional node selector for large and all nodes are new, it should not scale down", hostedCluster: hostedCluster(withAdditionalNodeSelector(fmt.Sprintf("%s=large", hyperv1.NodeSizeLabel)), withHCSizeLabel("large")), machineSets: machineSets(4, withReplicas(1)), nodes: nodes(4, withHC(hc, 0, 1, 2, 3), withPairLabel("pair1", 0, 1, 2, 3), withSizeLabel("medium", 0, 1), withSizeLabel("large", 2, 3), withCreationTimestamp(twoMinutesAgo, 0, 1, 2, 3)), @@ -67,7 +67,7 @@ func TestHostedClusterMachineSetsToScaleDown(t *testing.T) { expectRequeueAfter: nodeScaleDownDelay, }, { - name: "Hosted cluster has additional node selector (medium) and size label(small)", + name: "When hosted cluster has additional node selector for small and size label for medium, it should scale down large machinesets", hostedCluster: hostedCluster(withAdditionalNodeSelector(fmt.Sprintf("%s=small", hyperv1.NodeSizeLabel)), withHCSizeLabel("medium")), machineSets: machineSets(6, withReplicas(1)), nodes: nodes(6, withHC(hc, 0, 1, 2, 3, 4, 5), withPairLabel("pair1", 0, 1, 2, 3, 4, 5), withSizeLabel("small", 0, 1), withSizeLabel("medium", 2, 3), withSizeLabel("large", 4, 5)), @@ -75,7 +75,7 @@ func TestHostedClusterMachineSetsToScaleDown(t *testing.T) { expected: machineSets(6, withReplicas(1))[4:], // machinesets 4, 5 }, { - name: "Do not scale down nodes without a size label", + name: "When nodes have no size label, it should not scale them down", hostedCluster: hostedCluster(withAdditionalNodeSelector(fmt.Sprintf("%s=small", hyperv1.NodeSizeLabel)), withHCSizeLabel("small")), machineSets: machineSets(6, withReplicas(1)), nodes: nodes(6, withHC(hc, 0, 1, 2, 3, 4, 5), withPairLabel("pair1", 0, 1, 2, 3, 4, 5), withSizeLabel("small", 0, 1), withSizeLabel("medium", 2, 3)), @@ -103,7 +103,7 @@ func TestNodeMachineSetsToScaleDown(t *testing.T) { expected []machinev1beta1.MachineSet }{ { - name: "There are multiple nodes with the same pair label, machinesets are scaled up", + name: "When there are multiple nodes with the same pair label and machinesets are scaled up, it should return all paired machinesets", node: &(nodes(8, withHC(hostedCluster(), 0, 1, 2, 3, 4, 5), withSizeLabel("small", 0, 1, 6, 7), withSizeLabel("medium", 2, 3), @@ -119,7 +119,7 @@ func TestNodeMachineSetsToScaleDown(t *testing.T) { expected: machineSets(8, withReplicas(1))[:6], // machinesets 0, 1, 2, 3, 4, 5 }, { - name: "There are multiple nodes with the same pair label, some machinesets are scaled up", + name: "When there are multiple nodes with the same pair label and some machinesets are scaled up, it should return only scaled-up ones", node: &(nodes(8, withHC(hostedCluster(), 0, 1, 2, 3, 4, 5), withSizeLabel("small", 0, 1, 6, 7), withSizeLabel("medium", 2, 3), @@ -135,7 +135,7 @@ func TestNodeMachineSetsToScaleDown(t *testing.T) { expected: append(machineSets(8, withReplicas(1))[:2], machineSets(8, withReplicas(1))[4:6]...), // machinesets 0, 1, 4, 5 }, { - name: "The node does not have a pair label", + name: "When the node does not have a pair label, it should return only its own machineset", node: &(nodes(8, withHC(hostedCluster(), 0, 1, 2, 3, 4, 5), withSizeLabel("small", 0, 1, 6, 7), withSizeLabel("medium", 2, 3), @@ -151,7 +151,7 @@ func TestNodeMachineSetsToScaleDown(t *testing.T) { expected: machineSets(8, withReplicas(1))[3:4], // machineset 3 }, { - name: "Do not scale down nodes without a size label", + name: "When nodes have no size label, it should not scale them down", node: &(nodes(8, withHC(hostedCluster(), 0, 1, 2, 3, 4, 5), withSizeLabel("small", 0, 1, 6, 7), withSizeLabel("medium", 2, 3), @@ -188,7 +188,7 @@ func TestMachineSetsToScaleUp(t *testing.T) { expected []string }{ { - name: "No pending pods", + name: "When there are no pending pods, it should return empty list", pods: pods(10), machines: machines(4), machineSets: machineSets(4), @@ -196,7 +196,7 @@ func TestMachineSetsToScaleUp(t *testing.T) { expected: []string{}, }, { - name: "Pending placeholder pods, available machinesets", + name: "When pending placeholder pods exist with available machinesets, it should scale up next available", pods: pods(10, pending(5, 6)), machines: machines(4), machineSets: machineSets(8), @@ -204,7 +204,7 @@ func TestMachineSetsToScaleUp(t *testing.T) { expected: []string{"machineset-4", "machineset-5"}, // 4 and 5 are the next available machinesets }, { - name: "Pending pods with pair label", + name: "When pending pods have pair labels, it should scale up matching machinesets", pods: pods(10, pending(5, 6), withPodPairLabel("pair-3", 5, 6)), machineSets: machineSets(10), expected: []string{"machineset-6", "machineset-7"}, // machinesets 6 and 7 have the matching pair label @@ -403,13 +403,13 @@ func TestDetermineRequiredNodes(t *testing.T) { expected []nodeRequirement }{ { - name: "No pending pods", + name: "When there are no pending pods, it should return nil", pods: pods(4, scheduled(0, 1, 2, 3)), nodes: nodes(4), expected: nil, }, { - name: "Paired pending pods", + name: "When paired pending pods exist, it should require nodes for them", pods: pods(8, pending(0, 1, 2, 3), scheduled(4, 5, 6, 7)), nodes: nodes(8), expected: []nodeRequirement{ @@ -420,7 +420,7 @@ func TestDetermineRequiredNodes(t *testing.T) { }, }, { - name: "Single pending pod", + name: "When a single pending pod exists, it should require one node with its pair label", pods: pods(4, pending(0), withPodPairLabel("foo", 0), scheduled(1, 2, 3)), nodes: nodes(4), expected: []nodeRequirement{ @@ -432,7 +432,7 @@ func TestDetermineRequiredNodes(t *testing.T) { }, }, { - name: "Single pending pod, with pending/scheduled pair", + name: "When a single pending pod has a pending and scheduled pair, it should require two nodes", pods: pods(4, pending(0, 1), scheduled(0, 2, 3)), nodes: nodes(4), expected: []nodeRequirement{ @@ -444,7 +444,7 @@ func TestDetermineRequiredNodes(t *testing.T) { }, }, { - name: "Pods of different pairs pending", + name: "When pods of different pairs are pending, it should require nodes for each pair", pods: pods(4, pending(0, 1, 2, 3), scheduled(1, 2)), nodes: nodes(4), expected: []nodeRequirement{ @@ -461,7 +461,7 @@ func TestDetermineRequiredNodes(t *testing.T) { }, }, { - name: "Pods of different pairs pending, along with unpaired", + name: "When pods of different pairs are pending along with unpaired, it should require nodes for each group", pods: pods(6, pending(0, 1, 2, 3, 4, 5), scheduled(1, 2)), nodes: nodes(4), expected: []nodeRequirement{ @@ -482,7 +482,7 @@ func TestDetermineRequiredNodes(t *testing.T) { }, }, { - name: "ignore unpaired pods without pair selector", + name: "When unpaired pods lack a pair selector, it should ignore them", pods: pods(3, pending(0, 1, 2)), nodes: nodes(4), expected: []nodeRequirement{ @@ -551,12 +551,12 @@ func TestValidateConfigForNonRequestServing(t *testing.T) { expectValid bool }{ { - name: "Invalid config (no status)", + name: "When config has no status it should be invalid", cfg: &schedulingv1alpha1.ClusterSizingConfiguration{}, expectValid: false, }, { - name: "Invalid config (valid condition false)", + name: "When config valid condition is false it should be invalid", cfg: &schedulingv1alpha1.ClusterSizingConfiguration{ Status: schedulingv1alpha1.ClusterSizingConfigurationStatus{ Conditions: []metav1.Condition{ @@ -570,7 +570,7 @@ func TestValidateConfigForNonRequestServing(t *testing.T) { expectValid: false, }, { - name: "Invalid config (no nodes per zone on all sizes)", + name: "When config has no nodes per zone on all sizes it should be invalid", cfg: &schedulingv1alpha1.ClusterSizingConfiguration{ Spec: schedulingv1alpha1.ClusterSizingConfigurationSpec{ Sizes: []schedulingv1alpha1.SizeConfiguration{ @@ -603,7 +603,7 @@ func TestValidateConfigForNonRequestServing(t *testing.T) { expectValid: false, }, { - name: "Valid config", + name: "When config has nodes per zone on all sizes it should be valid", cfg: &schedulingv1alpha1.ClusterSizingConfiguration{ Spec: schedulingv1alpha1.ClusterSizingConfigurationSpec{ Sizes: []schedulingv1alpha1.SizeConfiguration{ @@ -679,12 +679,12 @@ func TestValidateNonRequestServingMachineSets(t *testing.T) { expectValid bool }{ { - name: "Invalid machinesets, not 3", + name: "When machinesets count is not 3 it should be invalid", machineSets: []machinev1beta1.MachineSet{ms(1, "0", "1"), ms(2, "0", "1")}, expectValid: false, }, { - name: "Invalid machinesets, different min/max", + name: "When machinesets have different min and max it should be invalid", machineSets: []machinev1beta1.MachineSet{ ms(1, "0", "1"), ms(2, "0", "2"), @@ -693,7 +693,7 @@ func TestValidateNonRequestServingMachineSets(t *testing.T) { expectValid: false, }, { - name: "Invalid machinesets, no min/max", + name: "When machinesets have no min or max it should be invalid", machineSets: []machinev1beta1.MachineSet{ ms(1, "0", "1"), ms(2, "", "1"), @@ -702,7 +702,7 @@ func TestValidateNonRequestServingMachineSets(t *testing.T) { expectValid: false, }, { - name: "Invalid machinesets, invalid min/max", + name: "When machinesets have min greater than max it should be invalid", machineSets: []machinev1beta1.MachineSet{ ms(1, "0", "1"), ms(2, "1", "0"), @@ -711,7 +711,7 @@ func TestValidateNonRequestServingMachineSets(t *testing.T) { expectValid: false, }, { - name: "Invalid machinesets, parse error", + name: "When machinesets have unparsable min or max it should be invalid", machineSets: []machinev1beta1.MachineSet{ ms(1, "foo", "3"), ms(2, "foo", "3"), @@ -720,7 +720,7 @@ func TestValidateNonRequestServingMachineSets(t *testing.T) { expectValid: false, }, { - name: "Valid machinesets", + name: "When machinesets have consistent valid min and max it should be valid", machineSets: []machinev1beta1.MachineSet{ ms(1, "1", "3"), ms(2, "1", "3"), @@ -825,29 +825,29 @@ func TestNonRequestServingMachineSetsToScale(t *testing.T) { expect []machineSetReplicas }{ { - name: "No hosted clusters", + name: "When there are no hosted clusters it should not change machinesets", machineSets: []machinev1beta1.MachineSet{ms(1, 1), ms(2, 1), ms(3, 1)}, expect: nil, // no changes }, { - name: "No hosted clusters, one machineset scaled up", + name: "When there are no hosted clusters and one machineset is scaled up it should scale it down", machineSets: []machinev1beta1.MachineSet{ms(1, 1), ms(2, 2), ms(3, 1)}, expect: []machineSetReplicas{{ms(2, 2), 1}}, }, { - name: "Small hosted clusters", + name: "When small hosted clusters exist it should scale up machinesets with buffer", hostedClusters: []hyperv1.HostedCluster{hc(1, "small"), hc(2, "small"), hc(3, "small")}, // 0.6 should require 1 node + 1 buffer machineSets: []machinev1beta1.MachineSet{ms(1, 1), ms(2, 1), ms(3, 1)}, expect: []machineSetReplicas{{ms(1, 1), 2}, {ms(2, 1), 2}, {ms(3, 1), 2}}, }, { - name: "Small and medium hosted clusters, one machineset scaled up", + name: "When small and medium hosted clusters exist with one machineset already scaled up it should scale remaining", hostedClusters: []hyperv1.HostedCluster{hc(1, "medium"), hc(2, "medium"), hc(3, "small")}, // 1.2 should require 2 nodes + 1 buffer machineSets: []machinev1beta1.MachineSet{ms(1, 1), ms(2, 1), ms(3, 3)}, expect: []machineSetReplicas{{ms(1, 1), 3}, {ms(2, 1), 3}}, }, { - name: "Large hosted clusters, more than max", + name: "When large hosted clusters exceed max it should cap at max replicas", hostedClusters: hcs(20, "large"), // should require 20 nodes + 1 buffer, but we're limited to 10 machineSets: []machinev1beta1.MachineSet{ms(1, 1), ms(2, 1), ms(3, 1)}, expect: []machineSetReplicas{{ms(1, 1), 10}, {ms(2, 1), 10}, {ms(3, 1), 10}}, @@ -877,7 +877,7 @@ func TestCollectTakenPairLabels(t *testing.T) { expected: sets.New[string](), }, { - name: "When nodes have cluster labels, their pair labels should be collected", + name: "When nodes have cluster labels, it should collect their pair labels", pods: nil, nodes: []corev1.Node{ { @@ -902,7 +902,7 @@ func TestCollectTakenPairLabels(t *testing.T) { expected: sets.New[string]("pair-a", "pair-b"), }, { - name: "When nodes have no cluster label, their pair labels should not be collected", + name: "When nodes have no cluster label, it should not collect their pair labels", pods: nil, nodes: []corev1.Node{ { @@ -917,7 +917,7 @@ func TestCollectTakenPairLabels(t *testing.T) { expected: sets.New[string](), }, { - name: "When pods are scheduled on nodes with pair labels, those labels should be collected", + name: "When pods are scheduled on nodes with pair labels, it should collect those labels", pods: []corev1.Pod{ { ObjectMeta: metav1.ObjectMeta{Name: "p1"}, @@ -937,7 +937,7 @@ func TestCollectTakenPairLabels(t *testing.T) { expected: sets.New[string]("pair-c"), }, { - name: "When pods have pair label in node selector, those labels should be collected", + name: "When pods have pair label in node selector, it should collect those labels", pods: []corev1.Pod{ { ObjectMeta: metav1.ObjectMeta{Name: "p1"}, @@ -1077,7 +1077,7 @@ func TestScaleMachineSetsForRequirement(t *testing.T) { expectedNames: []string{"ms-1b"}, }, { - name: "When taken pair labels exclude some machinesets, those should be skipped", + name: "When taken pair labels exclude some machinesets, it should skip those", requirement: nodeRequirement{sizeLabel: "small", count: 2}, machineSets: []machinev1beta1.MachineSet{ mkMachineSet("ms-1a", "small", "pair-taken", 0, 0), diff --git a/hypershift-operator/controllers/scheduler/aws/dedicated_request_serving_nodes_test.go b/hypershift-operator/controllers/scheduler/aws/dedicated_request_serving_nodes_test.go index c074bc2991a9..30ddb12fa908 100644 --- a/hypershift-operator/controllers/scheduler/aws/dedicated_request_serving_nodes_test.go +++ b/hypershift-operator/controllers/scheduler/aws/dedicated_request_serving_nodes_test.go @@ -58,20 +58,20 @@ func TestNodeReaper(t *testing.T) { expectDelete bool }{ { - name: "no associated cluster", + name: "When there is no associated cluster it should not delete the node", existing: []client.Object{ node(), }, }, { - name: "associated existing cluster", + name: "When associated cluster exists it should not delete the node", existing: []client.Object{ node(withCluster("c1")), cluster("c1"), }, }, { - name: "associated with non-existent cluster", + name: "When associated with a non-existent cluster it should delete the node", existing: []client.Object{ node(withCluster("c1")), }, @@ -174,11 +174,11 @@ func TestHostedClusterScheduler(t *testing.T) { expectedPairLabel string }{ { - name: "deleted hosted cluster", + name: "When hosted cluster is deleted it should succeed without error", hc: hostedcluster(deletedHC), }, { - name: "scheduled hosted cluster with 2 existing Nodes", + name: "When scheduled hosted cluster has 2 existing nodes it should succeed", hc: hostedcluster(scheduledHC), nodes: nodes( node("n1", "zone-a", "id1", withCluster(hostedcluster())), @@ -186,7 +186,7 @@ func TestHostedClusterScheduler(t *testing.T) { ), }, { - name: "available nodes", + name: "When available nodes exist it should schedule them", hc: hostedcluster(), nodes: nodes( node("n1", "zone-a", "id1"), @@ -198,7 +198,7 @@ func TestHostedClusterScheduler(t *testing.T) { expectedPairLabel: "id1", }, { - name: "available node, existing assigned node", + name: "When an available node and existing assigned node are present it should schedule", hc: hostedcluster(), nodes: nodes( node("n1", "zone-a", "id1", withCluster(hostedcluster())), @@ -208,7 +208,7 @@ func TestHostedClusterScheduler(t *testing.T) { expectedPairLabel: "id1", }, { - name: "When there's no paired Nodes in different AZs it should fail", + name: "When there's no paired Nodes in different AZs, it should fail", hc: hostedcluster(), nodes: nodes( node("n1", "zone-a", "id1"), @@ -219,7 +219,7 @@ func TestHostedClusterScheduler(t *testing.T) { expectedPairLabel: "id1", }, { - name: "When all Nodes are already labeled with other HC it should fail", + name: "When all Nodes are already labeled with other HC, it should fail", hc: hostedcluster(), nodes: nodes( node("n1", "zone-a", "id1", withCluster(hostedcluster(hcName("other")))), @@ -237,7 +237,7 @@ func TestHostedClusterScheduler(t *testing.T) { expectedPairLabel: "id1", }, { - name: "When HostedCluster is scheduled, without 2 existing Nodes and there's no Nodes available it should fail", + name: "When HostedCluster is scheduled, without 2 existing Nodes and there's no Nodes available, it should fail", hc: hostedcluster(scheduledHC), nodes: nodes( node("n1", "zone-a", "id1", withCluster(hostedcluster())), @@ -558,7 +558,7 @@ func TestHostedClusterSchedulerAndSizer(t *testing.T) { }{ { - name: "scheduled hosted cluster with 2 existing Nodes", + name: "When scheduled hosted cluster has 2 existing nodes it should keep them scheduled", hc: hostedcluster(scheduledHC), nodes: nodes( node("n1", "zone-a", "small", "id1", withCluster(hostedcluster())), @@ -593,7 +593,7 @@ func TestHostedClusterSchedulerAndSizer(t *testing.T) { expectPlaceholder: true, }, { - name: "ensure allocated cluster node is labeled for cluster", + name: "When an allocated cluster node exists it should be labeled for the cluster", hc: hostedcluster(), nodes: nodes( node("n1", "zone-a", "small", "id1", withCluster(hostedcluster())), @@ -602,7 +602,7 @@ func TestHostedClusterSchedulerAndSizer(t *testing.T) { checkScheduledNodes: true, }, { - name: "ensure hosted cluster is annotated properly when nodes are scheduled", + name: "When nodes are scheduled it should annotate the hosted cluster properly", hc: hostedcluster(), nodes: nodes( node("n1", "zone-a", "small", "id1", withCluster(hostedcluster())), @@ -612,12 +612,12 @@ func TestHostedClusterSchedulerAndSizer(t *testing.T) { checkScheduledNodes: true, }, { - name: "expect placeholder deployment when no nodes are available", + name: "When no nodes are available it should create a placeholder deployment", hc: hostedcluster(withSize("medium")), expectPlaceholder: true, }, { - name: "expect placeholder deployment when only one node is available", + name: "When only one node is available it should create a placeholder deployment", hc: hostedcluster(withSize("medium")), nodes: nodes( node("n1", "zone-a", "small", "id1", withCluster(hostedcluster())), @@ -625,13 +625,13 @@ func TestHostedClusterSchedulerAndSizer(t *testing.T) { expectPlaceholder: true, }, { - name: "use existing placeholders for small cluster", + name: "When existing placeholders are available for a small cluster it should use them", hc: hostedcluster(), additionalObjects: placeholderResources(3), checkScheduledNodes: true, }, { - name: "expect placeholder deployment when not the right size", + name: "When nodes are not the right size it should create a placeholder deployment", hc: hostedcluster(scheduledHC, withSize("medium")), nodes: nodes( node("n1", "zone-a", "small", "id1", withCluster(hostedcluster())), @@ -640,7 +640,7 @@ func TestHostedClusterSchedulerAndSizer(t *testing.T) { expectPlaceholder: true, }, { - name: "label nodes when placeholder deployment is ready", + name: "When placeholder deployment is ready it should label the nodes", hc: hostedcluster(withSize("medium")), additionalObjects: provisionedDeployment(placeholderDeployment(hostedcluster()), "medium", []corev1.Node{ *(node("n1", "zone-a", "medium", "pair1")), @@ -761,7 +761,7 @@ func TestFilterNodeEvents(t *testing.T) { expected []reconcile.Request }{ { - name: "Incoming node is not a request serving node", + name: "When incoming node is not a request serving node, it should return nil", baselineNodes: []client.Object{}, incomingNode: &corev1.Node{ ObjectMeta: metav1.ObjectMeta{ @@ -772,7 +772,7 @@ func TestFilterNodeEvents(t *testing.T) { expected: nil, }, { - name: "Incoming node is already a dedicated request serving node", + name: "When incoming node is already a dedicated request serving node, it should return its cluster request", baselineNodes: []client.Object{}, incomingNode: &corev1.Node{ ObjectMeta: metav1.ObjectMeta{ @@ -796,7 +796,7 @@ func TestFilterNodeEvents(t *testing.T) { }, }, { - name: "Incoming node is a request serving node, no hostedcluster label, no matching pair", + name: "When incoming node is a request serving node with no hostedcluster label and no matching pair, it should return nil", baselineNodes: []client.Object{ &corev1.Node{ ObjectMeta: metav1.ObjectMeta{ @@ -823,7 +823,7 @@ func TestFilterNodeEvents(t *testing.T) { expected: nil, }, { - name: "Incoming node is a request serving node, no hostedcluster label, but existing pair with hostedcluster", + name: "When incoming node has no hostedcluster label but existing pair has one, it should return the paired cluster request", baselineNodes: []client.Object{ &corev1.Node{ ObjectMeta: metav1.ObjectMeta{ @@ -1586,7 +1586,7 @@ func TestClassifyDedicatedNodes(t *testing.T) { expectedAvailLen: 0, }, { - name: "When nodes are labeled for the cluster with matching size and pair, they should be goal nodes", + name: "When nodes are labeled for the cluster with matching size and pair, it should mark them as goal nodes", nodes: []client.Object{ func() client.Object { n := mkNode("n1", hcKey, "pair-1", "small", false); return &n }(), func() client.Object { n := mkNode("n2", hcKey, "pair-1", "small", false); return &n }(), @@ -1597,7 +1597,7 @@ func TestClassifyDedicatedNodes(t *testing.T) { expectedPairLabel: "pair-1", }, { - name: "When nodes have no cluster label, they should be available nodes", + name: "When nodes have no cluster label, it should mark them as available nodes", nodes: []client.Object{ func() client.Object { n := mkNode("n1", "", "pair-1", "small", false); return &n }(), }, @@ -1804,7 +1804,7 @@ func TestDeletePairConfigMaps(t *testing.T) { expectedRemaining: 0, }, { - name: "When configmaps match the cluster, they should be deleted", + name: "When configmaps match the cluster, it should delete them", existing: []client.Object{ &corev1.ConfigMap{ ObjectMeta: metav1.ObjectMeta{ @@ -1821,7 +1821,7 @@ func TestDeletePairConfigMaps(t *testing.T) { expectedRemaining: 0, }, { - name: "When configmaps belong to a different cluster, they should not be deleted", + name: "When configmaps belong to a different cluster, it should not delete them", existing: []client.Object{ &corev1.ConfigMap{ ObjectMeta: metav1.ObjectMeta{ diff --git a/hypershift-operator/controllers/scheduler/aws/placeholders_test.go b/hypershift-operator/controllers/scheduler/aws/placeholders_test.go index fe8121bd6b2a..53d68eb3d416 100644 --- a/hypershift-operator/controllers/scheduler/aws/placeholders_test.go +++ b/hypershift-operator/controllers/scheduler/aws/placeholders_test.go @@ -33,7 +33,7 @@ func TestDeploymentName(t *testing.T) { } } -func TestPlaceholderCreator_Reconcile(t *testing.T) { +func TestPlaceholderCreatorReconcile(t *testing.T) { ctrl.SetLogger(zap.New(zap.UseDevMode(true), zap.JSONEncoder(func(o *zapcore.EncoderConfig) { o.EncodeTime = zapcore.RFC3339TimeEncoder }))) @@ -54,7 +54,7 @@ func TestPlaceholderCreator_Reconcile(t *testing.T) { expectedErr bool }{ { - name: "invalid config, do nothing", + name: "When config is invalid it should do nothing", config: &schedulingv1alpha1.ClusterSizingConfiguration{ Status: schedulingv1alpha1.ClusterSizingConfigurationStatus{ Conditions: []metav1.Condition{{Type: schedulingv1alpha1.ClusterSizingConfigurationValidType, Status: metav1.ConditionFalse}}, @@ -62,7 +62,7 @@ func TestPlaceholderCreator_Reconcile(t *testing.T) { }, }, { - name: "no placeholders necessary, do nothing", + name: "When no placeholders are necessary it should do nothing", config: &schedulingv1alpha1.ClusterSizingConfiguration{ Spec: schedulingv1alpha1.ClusterSizingConfigurationSpec{ Sizes: []schedulingv1alpha1.SizeConfiguration{ @@ -74,7 +74,7 @@ func TestPlaceholderCreator_Reconcile(t *testing.T) { }, }, { - name: "some placeholders necessary, none exist, create first", + name: "When some placeholders are necessary and none exist, it should create the first", config: &schedulingv1alpha1.ClusterSizingConfiguration{ Spec: schedulingv1alpha1.ClusterSizingConfigurationSpec{ Sizes: []schedulingv1alpha1.SizeConfiguration{ @@ -92,7 +92,7 @@ func TestPlaceholderCreator_Reconcile(t *testing.T) { expected: newDeployment(placeholderNamespace, "small", 0, []string{}), }, { - name: "some placeholders necessary, some exist, create next", + name: "When some placeholders are necessary and some exist, it should create the next", config: &schedulingv1alpha1.ClusterSizingConfiguration{ Spec: schedulingv1alpha1.ClusterSizingConfigurationSpec{ Sizes: []schedulingv1alpha1.SizeConfiguration{ @@ -112,7 +112,7 @@ func TestPlaceholderCreator_Reconcile(t *testing.T) { expected: newDeployment(placeholderNamespace, "small", 1, []string{}), }, { - name: "some placeholders necessary, some exist, create missing", + name: "When some placeholders are necessary and some exist, it should create the missing one", config: &schedulingv1alpha1.ClusterSizingConfiguration{ Spec: schedulingv1alpha1.ClusterSizingConfigurationSpec{ Sizes: []schedulingv1alpha1.SizeConfiguration{ @@ -132,7 +132,7 @@ func TestPlaceholderCreator_Reconcile(t *testing.T) { expected: newDeployment(placeholderNamespace, "small", 0, []string{}), }, { - name: "some placeholders necessary, all exist, do nothing", + name: "When all necessary placeholders exist it should do nothing", config: &schedulingv1alpha1.ClusterSizingConfiguration{ Spec: schedulingv1alpha1.ClusterSizingConfigurationSpec{ Sizes: []schedulingv1alpha1.SizeConfiguration{ @@ -173,7 +173,7 @@ func TestPlaceholderCreator_Reconcile(t *testing.T) { } } -func TestPlaceholderUpdater_Reconcile(t *testing.T) { +func TestPlaceholderUpdaterReconcile(t *testing.T) { ctrl.SetLogger(zap.New(zap.UseDevMode(true), zap.JSONEncoder(func(o *zapcore.EncoderConfig) { o.EncodeTime = zapcore.RFC3339TimeEncoder }))) @@ -195,7 +195,7 @@ func TestPlaceholderUpdater_Reconcile(t *testing.T) { expectedErr bool }{ { - name: "non-placeholder deployment, do nothing", + name: "When deployment is not a placeholder it should do nothing", deployment: &appsv1.Deployment{ ObjectMeta: metav1.ObjectMeta{ Labels: map[string]string{ @@ -205,7 +205,7 @@ func TestPlaceholderUpdater_Reconcile(t *testing.T) { }, }, { - name: "placeholder deployment without size, do nothing", + name: "When placeholder deployment has no size it should do nothing", deployment: &appsv1.Deployment{ ObjectMeta: metav1.ObjectMeta{ Labels: map[string]string{ @@ -215,7 +215,7 @@ func TestPlaceholderUpdater_Reconcile(t *testing.T) { }, }, { - name: "invalid config, do nothing", + name: "When config is invalid it should do nothing", deployment: &appsv1.Deployment{ ObjectMeta: metav1.ObjectMeta{ Labels: map[string]string{ @@ -231,7 +231,7 @@ func TestPlaceholderUpdater_Reconcile(t *testing.T) { }, }, { - name: "invalid deployment name, do nothing", + name: "When deployment name is invalid it should do nothing", deployment: &appsv1.Deployment{ ObjectMeta: metav1.ObjectMeta{ Name: "whatever", @@ -248,7 +248,7 @@ func TestPlaceholderUpdater_Reconcile(t *testing.T) { }, }, { - name: "too-large placeholder deployment, delete", + name: "When placeholder deployment index is too large it should delete it", deployment: &appsv1.Deployment{ ObjectMeta: metav1.ObjectMeta{ Name: "placeholder-small-123", @@ -269,7 +269,7 @@ func TestPlaceholderUpdater_Reconcile(t *testing.T) { delete: true, }, { - name: "too-large placeholder deployment edge-case, delete", + name: "When placeholder deployment index equals placeholder count it should delete it", deployment: &appsv1.Deployment{ ObjectMeta: metav1.ObjectMeta{ Name: "placeholder-small-2", @@ -290,7 +290,7 @@ func TestPlaceholderUpdater_Reconcile(t *testing.T) { delete: true, }, { - name: "placeholder deployment paired nodes missing, update", + name: "When placeholder deployment has missing paired nodes, it should update it", deployment: &appsv1.Deployment{ ObjectMeta: metav1.ObjectMeta{ Name: "placeholder-small-1", @@ -338,7 +338,7 @@ func TestPlaceholderUpdater_Reconcile(t *testing.T) { expected: newDeployment(placeholderNamespace, "small", 1, []string{"first", "second"}), }, { - name: "placeholder deployment paired nodes out-of-date, update", + name: "When placeholder deployment paired nodes are out of date, it should update it", deployment: &appsv1.Deployment{ ObjectMeta: metav1.ObjectMeta{ Name: "placeholder-small-1", @@ -386,7 +386,7 @@ func TestPlaceholderUpdater_Reconcile(t *testing.T) { expected: newDeployment(placeholderNamespace, "small", 1, []string{"first", "second"}), }, { - name: "placeholder deployment correct, no-op", + name: "When placeholder deployment is correct it should be a no-op", deployment: &appsv1.Deployment{ ObjectMeta: metav1.ObjectMeta{ Name: "placeholder-small-1", diff --git a/hypershift-operator/controllers/scheduler/azure/controllers_test.go b/hypershift-operator/controllers/scheduler/azure/controllers_test.go index c8fa43e890b1..325250dc52a1 100644 --- a/hypershift-operator/controllers/scheduler/azure/controllers_test.go +++ b/hypershift-operator/controllers/scheduler/azure/controllers_test.go @@ -93,14 +93,14 @@ func TestReconcile(t *testing.T) { expectAnnotations map[string]string }{ { - name: "hosted cluster not found", + name: "When hosted cluster is not found, it should succeed without error", hc: nil, sizingConfig: sizingConfig, expectError: false, expectRequeue: false, }, { - name: "hosted cluster paused", + name: "When hosted cluster is paused, it should requeue", hc: hostedcluster(func(hc *hyperv1.HostedCluster) { hc.Spec.PausedUntil = ptr.To(time.Now().Add(time.Hour).Format(time.RFC3339Nano)) }), @@ -109,7 +109,7 @@ func TestReconcile(t *testing.T) { expectRequeue: true, }, { - name: "hosted cluster without size label", + name: "When hosted cluster has no size label, it should succeed without requeue", hc: hostedcluster(func(hc *hyperv1.HostedCluster) { delete(hc.Labels, hyperv1.HostedClusterSizeLabel) }), @@ -118,7 +118,7 @@ func TestReconcile(t *testing.T) { expectRequeue: false, }, { - name: "invalid cluster sizing configuration", + name: "When cluster sizing configuration is invalid, it should succeed without requeue", hc: hostedcluster(), sizingConfig: &schedulingv1alpha1.ClusterSizingConfiguration{ ObjectMeta: metav1.ObjectMeta{ @@ -137,7 +137,7 @@ func TestReconcile(t *testing.T) { expectRequeue: false, }, { - name: "size configuration not found", + name: "When size configuration is not found, it should return error", hc: hostedcluster(func(hc *hyperv1.HostedCluster) { hc.Labels[hyperv1.HostedClusterSizeLabel] = "extra-large" }), @@ -147,7 +147,7 @@ func TestReconcile(t *testing.T) { expectRequeue: false, }, { - name: "valid hosted cluster", + name: "When hosted cluster is valid, it should set scheduling annotations", hc: hostedcluster(), sizingConfig: sizingConfig, expectError: false, diff --git a/hypershift-operator/controllers/scheduler/util/scheduler_test.go b/hypershift-operator/controllers/scheduler/util/scheduler_test.go index 570c809bb85c..2209a3c3962c 100644 --- a/hypershift-operator/controllers/scheduler/util/scheduler_test.go +++ b/hypershift-operator/controllers/scheduler/util/scheduler_test.go @@ -26,7 +26,7 @@ func TestSetHostedClusterSchedulingAnnotations(t *testing.T) { expectedErr string }{ { - name: "NoSizeConfig", + name: "When no size config exists it should return error", hc: &hyperv1.HostedCluster{}, size: "small", config: &schedulingv1alpha1.ClusterSizingConfiguration{}, @@ -35,7 +35,7 @@ func TestSetHostedClusterSchedulingAnnotations(t *testing.T) { expectedErr: "could not find size configuration for size small", }, { - name: "ValidSizeConfigWithAnnotations", + name: "When valid size config has annotations it should set them on the hosted cluster", hc: &hyperv1.HostedCluster{ ObjectMeta: metav1.ObjectMeta{ Annotations: map[string]string{}, @@ -66,7 +66,7 @@ func TestSetHostedClusterSchedulingAnnotations(t *testing.T) { expectedErr: "", }, { - name: "ValidSizeConfigWithNodesProvidingAnnotations", + name: "When valid size config has nodes providing annotations it should use node annotations", hc: &hyperv1.HostedCluster{ ObjectMeta: metav1.ObjectMeta{ Annotations: map[string]string{}, @@ -106,7 +106,7 @@ func TestSetHostedClusterSchedulingAnnotations(t *testing.T) { expectedErr: "", }, { - name: "SizeConfigWithMissingOptionalFields", + name: "When size config has missing optional fields it should set only the scheduled annotation", hc: &hyperv1.HostedCluster{ ObjectMeta: metav1.ObjectMeta{ Annotations: map[string]string{}, @@ -133,7 +133,7 @@ func TestSetHostedClusterSchedulingAnnotations(t *testing.T) { expectedErr: "", }, { - name: "SizeConfigWithMachineHealthCheckTimeout", + name: "When size config has machine health check timeout it should set the timeout annotation", hc: &hyperv1.HostedCluster{ ObjectMeta: metav1.ObjectMeta{ Annotations: map[string]string{}, @@ -164,7 +164,7 @@ func TestSetHostedClusterSchedulingAnnotations(t *testing.T) { expectedErr: "", }, { - name: "SizeConfigWithMachineHealthCheckTimeoutRemoved", + name: "When size config removes machine health check timeout it should remove the timeout annotation", hc: &hyperv1.HostedCluster{ ObjectMeta: metav1.ObjectMeta{ Annotations: map[string]string{ @@ -199,7 +199,7 @@ func TestSetHostedClusterSchedulingAnnotations(t *testing.T) { expectedErr: "", }, { - name: "SizeConfigWithResourceRequests", + name: "When size config has resource requests it should set override annotations", hc: &hyperv1.HostedCluster{ ObjectMeta: metav1.ObjectMeta{ Annotations: map[string]string{}, @@ -237,7 +237,7 @@ func TestSetHostedClusterSchedulingAnnotations(t *testing.T) { expectedErr: "", }, { - name: "SizeConfigWithSubnets", + name: "When size config has subnet labels on nodes it should set the subnet annotation", hc: &hyperv1.HostedCluster{ ObjectMeta: metav1.ObjectMeta{ Annotations: map[string]string{}, @@ -275,7 +275,7 @@ func TestSetHostedClusterSchedulingAnnotations(t *testing.T) { }, { - name: "SizeConfigWithPriorityClasses", + name: "When size config has priority classes it should set priority class annotations", hc: &hyperv1.HostedCluster{ ObjectMeta: metav1.ObjectMeta{ Annotations: map[string]string{}, @@ -310,7 +310,7 @@ func TestSetHostedClusterSchedulingAnnotations(t *testing.T) { expectedErr: "", }, { - name: "SizeConfigWithMaximumRequestsInflight", + name: "When size config has maximum requests inflight it should set inflight annotations", hc: &hyperv1.HostedCluster{ ObjectMeta: metav1.ObjectMeta{ Annotations: map[string]string{}, @@ -365,12 +365,12 @@ func TestResourceRequestsToOverrideAnnotations(t *testing.T) { expected map[string]string }{ { - name: "empty input", + name: "When input is empty, it should return empty map", input: []schedulingv1alpha1.ResourceRequest{}, expected: map[string]string{}, }, { - name: "kube apiserver memory request", + name: "When kube apiserver has a memory request, it should set the override annotation", input: []schedulingv1alpha1.ResourceRequest{ { DeploymentName: "kube-apiserver", @@ -383,7 +383,7 @@ func TestResourceRequestsToOverrideAnnotations(t *testing.T) { }, }, { - name: "etcd memory and cpu request", + name: "When etcd has memory and cpu requests, it should set both in the override annotation", input: []schedulingv1alpha1.ResourceRequest{ { DeploymentName: "etcd", @@ -397,7 +397,7 @@ func TestResourceRequestsToOverrideAnnotations(t *testing.T) { }, }, { - name: "kube-controller manager cpu request", + name: "When kube-controller manager has a cpu request, it should set the override annotation", input: []schedulingv1alpha1.ResourceRequest{ { DeploymentName: "kube-controller-manager", @@ -410,7 +410,7 @@ func TestResourceRequestsToOverrideAnnotations(t *testing.T) { }, }, { - name: "kube-apiserver and etcd memory request", + name: "When kube-apiserver and etcd both have memory requests, it should set both override annotations", input: []schedulingv1alpha1.ResourceRequest{ { DeploymentName: "kube-apiserver", diff --git a/hypershift-operator/controllers/sharedingress/router_test.go b/hypershift-operator/controllers/sharedingress/router_test.go index 0e57f51caaad..9775e8e1d0a3 100644 --- a/hypershift-operator/controllers/sharedingress/router_test.go +++ b/hypershift-operator/controllers/sharedingress/router_test.go @@ -28,7 +28,7 @@ func TestReconcileRouterDeployment(t *testing.T) { wantErr bool }{ { - name: "Valid config map and deployment", + name: "When a valid config map and deployment are provided, it should reconcile without error", args: args{ deployment: &appsv1.Deployment{ ObjectMeta: metav1.ObjectMeta{ diff --git a/hypershift-operator/controllers/uwmtelemetry/uwm_telemetry_test.go b/hypershift-operator/controllers/uwmtelemetry/uwm_telemetry_test.go index 0d4be563b77a..2b2c0beafeb0 100644 --- a/hypershift-operator/controllers/uwmtelemetry/uwm_telemetry_test.go +++ b/hypershift-operator/controllers/uwmtelemetry/uwm_telemetry_test.go @@ -150,11 +150,11 @@ func TestReconcileUWMConfigContent(t *testing.T) { validateExtra func(*WithT, map[string]interface{}) }{ { - name: "no existing config", + name: "When there is no existing config it should create telemetry remote write", expectRWCount: 1, }, { - name: "other keys present should be preserved", + name: "When other keys are present it should preserve them", initial: `foo: bar goo: baz prometheus: @@ -171,7 +171,7 @@ prometheus: }, }, { - name: "other remote write configs should be preserved", + name: "When other remote write configs exist it should preserve them", initial: `prometheus: remoteWrite: - queueConfig: @@ -197,7 +197,7 @@ prometheus: }, }, { - name: "existing telemetry config should be updated", + name: "When existing telemetry config exists it should be updated", initial: `prometheus: remoteWrite: - queueConfig: @@ -369,11 +369,11 @@ func TestReconcile(t *testing.T) { validate func(*WithT, client.Client) }{ { - name: "no monitoring namespace", + name: "When there is no monitoring namespace, it should succeed without changes", validate: func(g *WithT, c client.Client) {}, }, { - name: "monitoring namespace exists", + name: "When monitoring namespace exists, it should create monitoring config", existing: []client.Object{monitoring.MonitoringNamespace()}, validate: func(g *WithT, c client.Client) { monitoringConfig := monitoring.MonitoringConfig() @@ -383,7 +383,7 @@ func TestReconcile(t *testing.T) { }, }, { - name: "uwm exists", + name: "When UWM namespace exists, it should configure monitoring and remote write", existing: []client.Object{ monitoring.MonitoringNamespace(), monitoring.UWMNamespace(), diff --git a/hypershift-operator/featuregate/feature_test.go b/hypershift-operator/featuregate/feature_test.go index 89bf095323b1..ecea193bbad5 100644 --- a/hypershift-operator/featuregate/feature_test.go +++ b/hypershift-operator/featuregate/feature_test.go @@ -94,7 +94,7 @@ func TestAllHypershiftOperatorFeatureGates(t *testing.T) { expected map[string]bool }{ { - name: "Default feature set", + name: "When using Default feature set, it should disable all feature gates", featureSet: configv1.Default, expected: map[string]bool{ "AROHCPManagedIdentities": false, @@ -105,7 +105,7 @@ func TestAllHypershiftOperatorFeatureGates(t *testing.T) { }, }, { - name: "TechPreviewNoUpgrade feature set", + name: "When using TechPreviewNoUpgrade feature set, it should enable all feature gates", featureSet: configv1.TechPreviewNoUpgrade, expected: map[string]bool{ "AROHCPManagedIdentities": true, @@ -116,7 +116,7 @@ func TestAllHypershiftOperatorFeatureGates(t *testing.T) { }, }, { - name: "DevPreviewNoUpgrade feature set", + name: "When using DevPreviewNoUpgrade feature set, it should disable all feature gates", featureSet: configv1.DevPreviewNoUpgrade, expected: map[string]bool{ "AROHCPManagedIdentities": false, diff --git a/ignition-server/controllers/local_ignitionprovider_test.go b/ignition-server/controllers/local_ignitionprovider_test.go index 819e14a9a2a4..6ce3836b2333 100644 --- a/ignition-server/controllers/local_ignitionprovider_test.go +++ b/ignition-server/controllers/local_ignitionprovider_test.go @@ -711,7 +711,7 @@ func TestCopyMCOOutputToMCC(t *testing.T) { } } -func Test_copyMCCConfigInputs(t *testing.T) { +func TestCopyMCCConfigInputs(t *testing.T) { t.Parallel() tests := []struct { @@ -1647,7 +1647,7 @@ func TestFetchMCSIgnitionPayload(t *testing.T) { expectOk: false, }, { - name: "When request succeeds, the correct Accept header should be sent", + name: "When request succeeds, it should send the correct Accept header", handler: func(w http.ResponseWriter, r *http.Request) { if r.Header.Get("Accept") != "application/vnd.coreos.ignition+json;version=3.2.0, */*;q=0.1" { w.WriteHeader(http.StatusBadRequest) diff --git a/ignition-server/controllers/tokensecret_controller_test.go b/ignition-server/controllers/tokensecret_controller_test.go index 04236a165b0a..db1c3974364e 100644 --- a/ignition-server/controllers/tokensecret_controller_test.go +++ b/ignition-server/controllers/tokensecret_controller_test.go @@ -266,7 +266,7 @@ func TestReconcile(t *testing.T) { }, }, { - name: "When the nodepool upgrade strategy is replace, the token secret should not contain the machine payload", + name: "When the nodepool upgrade strategy is replace, it should not contain the machine payload in the token secret", secret: &corev1.Secret{ ObjectMeta: metav1.ObjectMeta{ Name: "test", @@ -327,13 +327,13 @@ func TestGetTokenIDTimeLived(t *testing.T) { expectedError bool }{ { - name: "when there's no annotation it should return nil", + name: "When there is no annotation it should return nil", annotations: map[string]string{}, expectedDuration: nil, expectedError: false, }, { - name: "when the annotation has empty value it should error", + name: "When the annotation has empty value it should error", annotations: map[string]string{ TokenSecretTokenGenerationTime: "", }, @@ -341,7 +341,7 @@ func TestGetTokenIDTimeLived(t *testing.T) { expectedError: true, }, { - name: "when the annotation has no wrong format it should error", + name: "When the annotation has wrong format it should error", annotations: map[string]string{ TokenSecretTokenGenerationTime: "wrong format", }, @@ -349,7 +349,7 @@ func TestGetTokenIDTimeLived(t *testing.T) { expectedError: true, }, { - name: "when the annotation has a valid format it should return a duration", + name: "When the annotation has a valid format it should return a duration", annotations: map[string]string{ TokenSecretTokenGenerationTime: lastUpdated, }, @@ -382,17 +382,17 @@ func TestTokenIDNeedRotation(t *testing.T) { needRotation bool }{ { - name: "when the time lived is >= ttl it should return true", + name: "When the time lived is >= ttl it should return true", timeLived: &timeLivedHalfTTL, needRotation: true, }, { - name: "when the time lived is nil it should return true", + name: "When the time lived is nil it should return true", timeLived: nil, needRotation: true, }, { - name: "when the time lived is < ttl it should return true", + name: "When the time lived is less than ttl it should return false", timeLived: &timeLivedLessThanTTL, needRotation: false, }, @@ -460,26 +460,26 @@ func TestIsTokenExpired(t *testing.T) { expectedIsExpired bool }{ { - name: "when there's no token expiration timestamp annotation it should return that it is not expired (false)", + name: "When there is no token expiration timestamp annotation it should return that it is not expired", annotations: map[string]string{}, expectedIsExpired: false, }, { - name: "when the token expiration timestamp is in the past it should return that it is expired (true)", + name: "When the token expiration timestamp is in the past it should return that it is expired", annotations: map[string]string{ hyperv1.IgnitionServerTokenExpirationTimestampAnnotation: time.Now().Add(-4 * time.Hour).Format(time.RFC3339), }, expectedIsExpired: true, }, { - name: "when the token expiration timestamp is in the future it should return that it is not expired (false)", + name: "When the token expiration timestamp is in the future it should return that it is not expired", annotations: map[string]string{ hyperv1.IgnitionServerTokenExpirationTimestampAnnotation: time.Now().Add(4 * time.Hour).Format(time.RFC3339), }, expectedIsExpired: false, }, { - name: "when the token expiration timestamp has an invalid value it should return that it is expired (true)", + name: "When the token expiration timestamp has an invalid value it should return that it is expired", annotations: map[string]string{ hyperv1.IgnitionServerTokenExpirationTimestampAnnotation: "badvalue", }, @@ -511,7 +511,7 @@ func TestProcessedExpiredToken(t *testing.T) { expectedEntriesToBeRemoved map[string][]byte }{ { - name: "when a token secret exists and the cache is populated then the secret is deleted and the token entries removed from cache", + name: "When a token secret exists and the cache is populated it should delete the secret and remove the token entries from cache", inputEntries: map[string][]byte{ fakeCurrentTokenVal: fakeTokenContent, fakeOldTokenVal: fakeTokenContent, @@ -533,7 +533,7 @@ func TestProcessedExpiredToken(t *testing.T) { }, }, { - name: "when a token secret exists with only one token and the cache is populated then the secret is deleted and the token entries removed from cache", + name: "When a token secret exists with only one token and the cache is populated it should delete the secret and remove the token entries from cache", inputEntries: map[string][]byte{ fakeCurrentTokenVal: fakeTokenContent, }, @@ -552,7 +552,7 @@ func TestProcessedExpiredToken(t *testing.T) { }, }, { - name: "when a token secret exists and an independent secrets entry is also in the cache then only the processed tokens are removed", + name: "When a token secret exists and an independent secrets entry is also in the cache it should only remove the processed tokens", inputEntries: map[string][]byte{ fakeCurrentTokenVal: fakeTokenContent, fakeIndependentTokenVal: fakeTokenContent, @@ -619,7 +619,7 @@ func TestHasSameReasonAndMessage(t *testing.T) { expected bool }{ { - name: "Reason and message match", + name: "When reason and message match, it should return true", secret: &corev1.Secret{ Data: map[string][]byte{ TokenSecretReasonKey: []byte("reason1"), @@ -631,7 +631,7 @@ func TestHasSameReasonAndMessage(t *testing.T) { expected: true, }, { - name: "Reason does not match", + name: "When reason does not match, it should return false", secret: &corev1.Secret{ Data: map[string][]byte{ TokenSecretReasonKey: []byte("reason1"), @@ -643,7 +643,7 @@ func TestHasSameReasonAndMessage(t *testing.T) { expected: false, }, { - name: "Message does not match", + name: "When message does not match, it should return false", secret: &corev1.Secret{ Data: map[string][]byte{ TokenSecretReasonKey: []byte("reason1"), @@ -655,7 +655,7 @@ func TestHasSameReasonAndMessage(t *testing.T) { expected: false, }, { - name: "Both reason and message do not match", + name: "When both reason and message do not match, it should return false", secret: &corev1.Secret{ Data: map[string][]byte{ TokenSecretReasonKey: []byte("reason1"), @@ -667,7 +667,7 @@ func TestHasSameReasonAndMessage(t *testing.T) { expected: false, }, { - name: "Reason and message are empty", + name: "When reason and message are empty, it should return true", secret: &corev1.Secret{ Data: map[string][]byte{ TokenSecretReasonKey: []byte(""), diff --git a/karpenter-operator/controllers/karpenter/machine_approver_test.go b/karpenter-operator/controllers/karpenter/machine_approver_test.go index d4ffb5a9aaa9..b328bfc05ae1 100644 --- a/karpenter-operator/controllers/karpenter/machine_approver_test.go +++ b/karpenter-operator/controllers/karpenter/machine_approver_test.go @@ -47,13 +47,13 @@ func TestAuthorizeClientCSR(t *testing.T) { authorize bool }{ { - name: "When CSR request is invalid it should error", + name: "When CSR request is invalid, it should error", x509csr: []byte("-----BEGIN??\n"), wantErr: "PEM block type must be CERTIFICATE REQUEST", authorize: false, }, { - name: "When CSR common name is invalid node name it should error", + name: "When CSR common name is invalid node name, it should error", x509csr: createCSR("system:node:"), wantErr: "subject common name does not have a valid node name", authorize: false, @@ -149,7 +149,7 @@ func TestAuthorizeServingCSR(t *testing.T) { authorize bool }{ { - name: "When CSR username is invalid node name it should error", + name: "When CSR username is invalid node name, it should error", csrUserName: "system:node:", wantErr: "csr username does not have a valid node name", authorize: false, diff --git a/karpenter-operator/controllers/nodeclass/ec2_nodeclass_controller_test.go b/karpenter-operator/controllers/nodeclass/ec2_nodeclass_controller_test.go index 793f2f9e97b4..f9e9a1e60e68 100644 --- a/karpenter-operator/controllers/nodeclass/ec2_nodeclass_controller_test.go +++ b/karpenter-operator/controllers/nodeclass/ec2_nodeclass_controller_test.go @@ -93,7 +93,7 @@ func TestReconcileEC2NodeClass(t *testing.T) { }, }, { - name: "when OpenshiftEC2NodeClassSpec.spec is defined, all fields should be mirrored", + name: "When OpenshiftEC2NodeClassSpec.spec is defined, it should mirror all fields", spec: hyperkarpenterv1.OpenshiftEC2NodeClassSpec{ SubnetSelectorTerms: []hyperkarpenterv1.SubnetSelectorTerm{ { @@ -407,7 +407,7 @@ func TestReconcileEC2NodeClass(t *testing.T) { }, }, { - name: "when platform tags exist in HostedControlPlane, they should be merged with nodeclass tags with platform tags taking precedence", + name: "When platform tags exist in HostedControlPlane, it should merge them with nodeclass tags with platform tags taking precedence", spec: hyperkarpenterv1.OpenshiftEC2NodeClassSpec{ Tags: map[string]string{ "nodeclass-tag": "nodeclass-value", @@ -464,7 +464,7 @@ func TestReconcileEC2NodeClass(t *testing.T) { }, }, { - name: "when nodeclass has conflicting red-hat-clustertype tag, platform tag should take precedence", + name: "When nodeclass has conflicting red-hat-clustertype tag, it should use platform tag precedence", spec: hyperkarpenterv1.OpenshiftEC2NodeClassSpec{ Tags: map[string]string{ "red-hat-clustertype": "some-other-value", // This should be overridden by platform tag diff --git a/karpenter-operator/controllers/nodeclass/karpenter_util_test.go b/karpenter-operator/controllers/nodeclass/karpenter_util_test.go index a490e0477162..61fb835fdc4c 100644 --- a/karpenter-operator/controllers/nodeclass/karpenter_util_test.go +++ b/karpenter-operator/controllers/nodeclass/karpenter_util_test.go @@ -21,12 +21,12 @@ func TestKarpenterKubeletConfigurationFromNodeClassSpec(t *testing.T) { expected *awskarpenterv1.KubeletConfiguration }{ { - name: "When Kubelet is nil it should return nil", + name: "When Kubelet is nil, it should return nil", spec: hyperkarpenterv1.OpenshiftEC2NodeClassSpec{}, expected: nil, }, { - name: "When all karpenter-mapped fields are set it should map them", + name: "When all karpenter-mapped fields are set, it should map them", spec: hyperkarpenterv1.OpenshiftEC2NodeClassSpec{ Kubelet: hyperkarpenterv1.KubeletConfiguration{ MaxPods: 110, @@ -81,7 +81,7 @@ func TestKarpenterKubeletConfigurationFromNodeClassSpec(t *testing.T) { }, }, { - name: "When only some fields are set it should map only those", + name: "When only some fields are set, it should map only those", spec: hyperkarpenterv1.OpenshiftEC2NodeClassSpec{ Kubelet: hyperkarpenterv1.KubeletConfiguration{ MaxPods: 50, @@ -92,7 +92,7 @@ func TestKarpenterKubeletConfigurationFromNodeClassSpec(t *testing.T) { }, }, { - name: "When only overflow fields are set it should return nil", + name: "When only overflow fields are set, it should return nil", spec: hyperkarpenterv1.OpenshiftEC2NodeClassSpec{ Kubelet: hyperkarpenterv1.KubeletConfiguration{ Overflow: runtime.RawExtension{Raw: []byte(`{"podPidsLimit":4096}`)}, diff --git a/kas-bootstrap/kas_boostrap_test.go b/kas-bootstrap/kas_boostrap_test.go index 0e12616b031c..e4c39e11c288 100644 --- a/kas-bootstrap/kas_boostrap_test.go +++ b/kas-bootstrap/kas_boostrap_test.go @@ -73,7 +73,7 @@ func TestReconcileFeatureGate(t *testing.T) { expectedFeatureGates []configv1.FeatureGateDetails }{ { - name: "when the rendered feature gate is the same as the existing feature gate it should not update", + name: "When the rendered feature gate is the same as the existing feature gate it should not update", clusterVersion: configv1.ClusterVersion{ ObjectMeta: metav1.ObjectMeta{ Name: "version", @@ -118,7 +118,7 @@ func TestReconcileFeatureGate(t *testing.T) { }, }, { - name: "when the rendered feature gate is different from the existing feature gate it should update appending to the status", + name: "When the rendered feature gate is different from the existing feature gate it should update appending to the status", clusterVersion: configv1.ClusterVersion{ ObjectMeta: metav1.ObjectMeta{ Name: "version", @@ -168,7 +168,7 @@ func TestReconcileFeatureGate(t *testing.T) { }, }, { - name: "when the existing feature gate version is not in the clusterVersion it should be dropped from the status", + name: "When the existing feature gate version is not in the clusterVersion it should be dropped from the status", clusterVersion: configv1.ClusterVersion{ ObjectMeta: metav1.ObjectMeta{ Name: "version", @@ -225,7 +225,7 @@ func TestReconcileFeatureGate(t *testing.T) { }, }, { - name: "when the clusterVersion does not exist it should not fail and append everything to the status", + name: "When the clusterVersion does not exist it should not fail and append everything to the status", existingFeatureGate: configv1.FeatureGate{ ObjectMeta: metav1.ObjectMeta{ Name: "cluster", @@ -275,7 +275,7 @@ func TestReconcileFeatureGate(t *testing.T) { }, }, { - name: "when clusterVersion has a completed entry, it should only keep feature gates for versions after the completed entry", + name: "When clusterVersion has a completed entry, it should only keep feature gates for versions after the completed entry", clusterVersion: configv1.ClusterVersion{ ObjectMeta: metav1.ObjectMeta{ Name: "version", @@ -411,14 +411,14 @@ func TestApplyManifest(t *testing.T) { expectErr string }{ { - name: "when the manifest file does not exist it should return an error", + name: "When the manifest file does not exist, it should return an error", setup: func(t *testing.T, g Gomega) (Apply, string) { return newFakeApplyClient(), filepath.Join(t.TempDir(), "nonexistent.yaml") }, expectErr: "failed to read file", }, { - name: "when the manifest file contains invalid YAML it should return a decode error", + name: "When the manifest file contains invalid YAML, it should return a decode error", setup: func(t *testing.T, g Gomega) (Apply, string) { invalidPath := filepath.Join(t.TempDir(), "invalid.yaml") g.Expect(os.WriteFile(invalidPath, []byte("not: a: valid: k8s: resource"), 0644)).To(Succeed()) @@ -427,14 +427,14 @@ func TestApplyManifest(t *testing.T) { expectErr: "failed to decode file", }, { - name: "when the apply client returns an error it should propagate", + name: "When the apply client returns an error, it should propagate", setup: func(t *testing.T, g Gomega) (Apply, string) { return &errorApplyClient{err: fmt.Errorf("connection refused")}, filepath.Join(".", "testdata", kasBootstrapContainerRolebindingManifest) }, expectErr: "failed to apply file", }, { - name: "when the manifest is valid it should apply successfully", + name: "When the manifest is valid, it should apply successfully", setup: func(t *testing.T, g Gomega) (Apply, string) { return newFakeApplyClient(), "./testdata/0000_10_config-operator_01_featuregates.crd.yaml" }, diff --git a/konnectivity-https-proxy/cmd_test.go b/konnectivity-https-proxy/cmd_test.go index 10db240d73b3..d97b1d7f2698 100644 --- a/konnectivity-https-proxy/cmd_test.go +++ b/konnectivity-https-proxy/cmd_test.go @@ -127,7 +127,7 @@ func TestDialDirectFunc(t *testing.T) { }, }, { - name: "When the transport DialContext fails it should return an error", + name: "When the transport DialContext fails, it should return an error", dialCtx: func(ctx context.Context, network, addr string) (net.Conn, error) { return nil, dialErr }, @@ -181,7 +181,7 @@ func TestConnectDialFunc(t *testing.T) { expectDialProxy: true, }, { - name: "When shouldDialDirect returns an error it should propagate the error", + name: "When shouldDialDirect returns an error, it should propagate the error", shouldDialDirectErr: lookupErr, expectErr: lookupErr, }, diff --git a/pkg/etcdcli/health_test.go b/pkg/etcdcli/health_test.go index b92f03264abe..4e3298faddc4 100644 --- a/pkg/etcdcli/health_test.go +++ b/pkg/etcdcli/health_test.go @@ -16,7 +16,7 @@ func TestMemberHealthStatus(t *testing.T) { want string }{ { - "test all available members", + "When all members are available it should report all available", []healthCheck{ healthyMember(1), healthyMember(2), @@ -25,7 +25,7 @@ func TestMemberHealthStatus(t *testing.T) { "3 members are available", }, { - "test an unhealthy member", + "When one member is unhealthy it should report the unhealthy member", []healthCheck{ healthyMember(1), healthyMember(2), @@ -34,7 +34,7 @@ func TestMemberHealthStatus(t *testing.T) { "2 of 3 members are available, etcd-3 is unhealthy", }, { - "test an unstarted member", + "When one member is unstarted it should report the unstarted member", []healthCheck{ healthyMember(1), healthyMember(2), @@ -43,7 +43,7 @@ func TestMemberHealthStatus(t *testing.T) { "2 of 3 members are available, NAME-PENDING-10.0.0.3 has not started", }, { - "test an unstarted member and an unhealthy member", + "When one member is unstarted and one is unhealthy it should report both", []healthCheck{ healthyMember(1), unHealthyMember(2), @@ -52,7 +52,7 @@ func TestMemberHealthStatus(t *testing.T) { "1 of 3 members are available, etcd-2 is unhealthy, NAME-PENDING-10.0.0.3 has not started", }, { - "test two unhealthy members", + "When two members are unhealthy it should report both unhealthy members", []healthCheck{ healthyMember(1), unHealthyMember(2), @@ -61,7 +61,7 @@ func TestMemberHealthStatus(t *testing.T) { "1 of 3 members are available, etcd-2 is unhealthy, etcd-3 is unhealthy", }, { - "test two unstarted members", + "When two members are unstarted it should report both unstarted members", []healthCheck{ healthyMember(1), unstartedMember(2), @@ -86,7 +86,7 @@ func TestGetUnstartedMemberNames(t *testing.T) { want []string }{ { - "test all available members", + "When all members are available it should return empty list", []healthCheck{ healthyMember(1), healthyMember(2), @@ -95,7 +95,7 @@ func TestGetUnstartedMemberNames(t *testing.T) { []string{}, }, { - "test an unhealthy members", + "When one member is unhealthy it should return empty list", []healthCheck{ healthyMember(1), healthyMember(2), @@ -104,7 +104,7 @@ func TestGetUnstartedMemberNames(t *testing.T) { []string{}, }, { - "test an unstarted and an unhealthy member", + "When one member is unstarted and one is unhealthy it should return unstarted member name", []healthCheck{ unHealthyMember(1), unstartedMember(2), @@ -130,7 +130,7 @@ func TestGetUnhealthyMemberNames(t *testing.T) { want []string }{ { - "test all available members", + "When all members are available it should return empty list", []healthCheck{ healthyMember(1), healthyMember(2), @@ -139,7 +139,7 @@ func TestGetUnhealthyMemberNames(t *testing.T) { []string{}, }, { - "test an unhealthy members", + "When one member is unhealthy it should return unhealthy member name", []healthCheck{ healthyMember(1), healthyMember(2), @@ -148,7 +148,7 @@ func TestGetUnhealthyMemberNames(t *testing.T) { []string{"etcd-3"}, }, { - "test an unstarted member", + "When one member is unstarted it should return unstarted member name", []healthCheck{ healthyMember(1), unstartedMember(2), @@ -157,7 +157,7 @@ func TestGetUnhealthyMemberNames(t *testing.T) { []string{"NAME-PENDING-10.0.0.2"}, }, { - "test an unstarted and an unhealthy member", + "When one member is unstarted and one is unhealthy it should return both names", []healthCheck{ unHealthyMember(1), unstartedMember(2), @@ -183,7 +183,7 @@ func TestIsQuorumFaultTolerant(t *testing.T) { want bool }{ { - "test all available members", + "When all members are available it should return true", []healthCheck{ healthyMember(1), healthyMember(2), @@ -192,7 +192,7 @@ func TestIsQuorumFaultTolerant(t *testing.T) { true, }, { - "test an unhealthy members", + "When one member is unhealthy it should return false", []healthCheck{ healthyMember(1), healthyMember(2), @@ -201,7 +201,7 @@ func TestIsQuorumFaultTolerant(t *testing.T) { false, }, { - "test an unstarted member", + "When one member is unstarted it should return false", []healthCheck{ healthyMember(1), unstartedMember(2), @@ -210,7 +210,7 @@ func TestIsQuorumFaultTolerant(t *testing.T) { false, }, { - "test an unstarted and an unhealthy member", + "When one member is unstarted and one is unhealthy it should return false", []healthCheck{ unHealthyMember(1), unstartedMember(2), @@ -219,7 +219,7 @@ func TestIsQuorumFaultTolerant(t *testing.T) { false, }, { - "test etcd cluster with less than 3 members", + "When cluster has less than 3 members it should return false", []healthCheck{ healthyMember(1), healthyMember(2), @@ -227,7 +227,7 @@ func TestIsQuorumFaultTolerant(t *testing.T) { false, }, { - "test empty health check", + "When health check is empty it should return false", []healthCheck{}, false, }, @@ -270,25 +270,25 @@ func TestMinimumTolerableQuorum(t *testing.T) { exp int }{ { - name: "valid input `3`", + name: "When input is 3, it should return 2", input: 3, expErr: nil, exp: 2, }, { - name: "valid input `5`", + name: "When input is 5, it should return 3", input: 5, expErr: nil, exp: 3, }, { - name: "invalid input `0`", + name: "When input is 0, it should return error", input: 0, expErr: fmt.Errorf("invalid etcd member length: %v", 0), exp: 0, }, { - name: "invalid input `-10`", + name: "When input is -10, it should return error", input: -10, expErr: fmt.Errorf("invalid etcd member length: %v", -10), exp: 0, diff --git a/pkg/featuregates/featuregates_test.go b/pkg/featuregates/featuregates_test.go index 16b4e619e012..da0a7e58add5 100644 --- a/pkg/featuregates/featuregates_test.go +++ b/pkg/featuregates/featuregates_test.go @@ -22,7 +22,7 @@ func TestCreatingFeatureGates(t *testing.T) { testcases := []testcase{ { - name: "configuring a feature gate with no featureset, should never be enabled", + name: "When a feature gate has no featureset, it should never be enabled", features: []*featuregates.Feature{ featuregates.NewFeature("Foo"), }, @@ -39,7 +39,7 @@ func TestCreatingFeatureGates(t *testing.T) { }, }, { - name: "configuring featuregates with specific featureset enablement, should only be enabled in featuresets it is explicitly enabled in", + name: "When featuregates have specific featureset enablement, it should only enable in explicitly enabled featuresets", features: []*featuregates.Feature{ featuregates.NewFeature("Foo", featuregates.WithEnableForFeatureSets(configv1.AllFixedFeatureSets...)), featuregates.NewFeature("Bar", featuregates.WithEnableForFeatureSets(configv1.Default)), // enabling only in default should generally never be done, but theoretically possible @@ -93,7 +93,9 @@ func TestCreatingFeatureGates(t *testing.T) { } func TestConfiguringUnknownFeatureSetErrors(t *testing.T) { - features := featuregates.NewFeatureSetAwareFeatures() - _, err := features.FeatureGatesForFeatureSet("FooBar") - assert.Error(t, err, "configuring an unknown featureset should result in an error") + t.Run("When an unknown featureset is configured it should return an error", func(t *testing.T) { + features := featuregates.NewFeatureSetAwareFeatures() + _, err := features.FeatureGatesForFeatureSet("FooBar") + assert.Error(t, err, "configuring an unknown featureset should result in an error") + }) } diff --git a/support/azureutil/azureutil_test.go b/support/azureutil/azureutil_test.go index 33edfdc6b23d..edf403339a59 100644 --- a/support/azureutil/azureutil_test.go +++ b/support/azureutil/azureutil_test.go @@ -31,19 +31,19 @@ func TestGetSubnetNameFromSubnetID(t *testing.T) { expectedErr bool }{ { - testCaseName: "empty subnet ID", + testCaseName: "When subnet ID is empty it should return an error", subnetID: "", expectedSubnetName: "", expectedErr: true, }, { - testCaseName: "improperly formed subnet ID", + testCaseName: "When subnet ID is improperly formed it should return an error", subnetID: "/subscriptions/mySubscriptionID/resourceGroups/myResourceGroupName/providers/Microsoft.Network/virtualNetworks/myVnetName/subnets", expectedSubnetName: "", expectedErr: true, }, { - testCaseName: "properly formed subnet ID", + testCaseName: "When subnet ID is properly formed it should return the subnet name", subnetID: "/subscriptions/mySubscriptionID/resourceGroups/myResourceGroupName/providers/Microsoft.Network/virtualNetworks/myVnetName/subnets/mySubnetName", expectedSubnetName: "mySubnetName", expectedErr: false, @@ -73,21 +73,21 @@ func TestGetNetworkSecurityGroupNameFromNetworkSecurityGroupID(t *testing.T) { expectedErr bool }{ { - testCaseName: "empty NSG ID", + testCaseName: "When NSG ID is empty it should return an error", nsgID: "", expectedNSGName: "", expectedNSGRG: "", expectedErr: true, }, { - testCaseName: "improperly formed nsg ID", + testCaseName: "When nsg ID is improperly formed it should return an error", nsgID: "/subscriptions/mySubscriptionID/resourceGroups/myResourceGroupName/providers/Microsoft.Network/networkSecurityGroups", expectedNSGName: "", expectedNSGRG: "", expectedErr: true, }, { - testCaseName: "properly formed nsg ID", + testCaseName: "When nsg ID is properly formed it should return NSG name and resource group", nsgID: "/subscriptions/mySubscriptionID/resourceGroups/myResourceGroupName/providers/Microsoft.Network/networkSecurityGroups/myNSGName", expectedNSGName: "myNSGName", expectedNSGRG: "myResourceGroupName", @@ -119,21 +119,21 @@ func TestGetVnetNameAndResourceGroupFromVnetID(t *testing.T) { expectedErr bool }{ { - testCaseName: "empty VNET ID", + testCaseName: "When VNET ID is empty it should return an error", vnetID: "", expectedVnetName: "", expectedVnetRG: "", expectedErr: true, }, { - testCaseName: "improperly formed VNET ID", + testCaseName: "When VNET ID is improperly formed it should return an error", vnetID: "/subscriptions/mySubscriptionID/resourceGroups/myResourceGroupName/providers/Microsoft.Network/virtualNetworks/", expectedVnetName: "", expectedVnetRG: "", expectedErr: true, }, { - testCaseName: "properly formed VNET ID", + testCaseName: "When VNET ID is properly formed it should return VNET name and resource group", vnetID: "/subscriptions/mySubscriptionID/resourceGroups/myResourceGroupName/providers/Microsoft.Network/virtualNetworks/myVnetName", expectedVnetName: "myVnetName", expectedVnetRG: "myResourceGroupName", @@ -163,17 +163,17 @@ func TestIsAroHCP(t *testing.T) { expectedValue bool }{ { - name: "Sets the managed service env var to hyperv1.AroHCP so the function should return true", + name: "When the managed service env var is set to AroHCP it should return true", envVarValue: hyperv1.AroHCP, expectedValue: true, }, { - name: "Sets the managed service env var to nothing so the function should return false", + name: "When the managed service env var is set to nothing it should return false", envVarValue: "", expectedValue: false, }, { - name: "Sets the managed service env var to 'asdf' so the function should return false", + name: "When the managed service env var is set to an invalid value it should return false", envVarValue: "asdf", expectedValue: false, }, @@ -196,7 +196,7 @@ func TestIsAroHCPByHCP(t *testing.T) { expected bool }{ { - name: "When AzureAuthenticationConfigType is ManagedIdentities it should return true", + name: "When AzureAuthenticationConfigType is ManagedIdentities, it should return true", hcp: &hyperv1.HostedControlPlane{ Spec: hyperv1.HostedControlPlaneSpec{ Platform: hyperv1.PlatformSpec{ @@ -212,7 +212,7 @@ func TestIsAroHCPByHCP(t *testing.T) { expected: true, }, { - name: "When AzureAuthenticationConfigType is WorkloadIdentities it should return false", + name: "When AzureAuthenticationConfigType is WorkloadIdentities, it should return false", hcp: &hyperv1.HostedControlPlane{ Spec: hyperv1.HostedControlPlaneSpec{ Platform: hyperv1.PlatformSpec{ @@ -228,7 +228,7 @@ func TestIsAroHCPByHCP(t *testing.T) { expected: false, }, { - name: "When platform is not Azure it should return false", + name: "When platform is not Azure, it should return false", hcp: &hyperv1.HostedControlPlane{ Spec: hyperv1.HostedControlPlaneSpec{ Platform: hyperv1.PlatformSpec{ @@ -239,7 +239,7 @@ func TestIsAroHCPByHCP(t *testing.T) { expected: false, }, { - name: "When Azure spec is nil it should fall back to env var", + name: "When Azure spec is nil, it should fall back to env var", hcp: &hyperv1.HostedControlPlane{ Spec: hyperv1.HostedControlPlaneSpec{ Platform: hyperv1.PlatformSpec{ @@ -251,7 +251,7 @@ func TestIsAroHCPByHCP(t *testing.T) { expected: true, }, { - name: "When Azure spec is nil and env var is not set it should return false", + name: "When Azure spec is nil and env var is not set, it should return false", hcp: &hyperv1.HostedControlPlane{ Spec: hyperv1.HostedControlPlaneSpec{ Platform: hyperv1.PlatformSpec{ @@ -262,7 +262,7 @@ func TestIsAroHCPByHCP(t *testing.T) { expected: false, }, { - name: "When WorkloadIdentities with ARO HCP env var it should return false because API takes precedence", + name: "When WorkloadIdentities with ARO HCP env var, it should return false because API takes precedence", hcp: &hyperv1.HostedControlPlane{ Spec: hyperv1.HostedControlPlaneSpec{ Platform: hyperv1.PlatformSpec{ @@ -298,7 +298,7 @@ func TestIsAroHCPByHC(t *testing.T) { expected bool }{ { - name: "When AzureAuthenticationConfigType is ManagedIdentities it should return true", + name: "When AzureAuthenticationConfigType is ManagedIdentities, it should return true", hc: &hyperv1.HostedCluster{ Spec: hyperv1.HostedClusterSpec{ Platform: hyperv1.PlatformSpec{ @@ -314,7 +314,7 @@ func TestIsAroHCPByHC(t *testing.T) { expected: true, }, { - name: "When AzureAuthenticationConfigType is WorkloadIdentities it should return false", + name: "When AzureAuthenticationConfigType is WorkloadIdentities, it should return false", hc: &hyperv1.HostedCluster{ Spec: hyperv1.HostedClusterSpec{ Platform: hyperv1.PlatformSpec{ @@ -330,7 +330,7 @@ func TestIsAroHCPByHC(t *testing.T) { expected: false, }, { - name: "When platform is not Azure it should return false", + name: "When platform is not Azure, it should return false", hc: &hyperv1.HostedCluster{ Spec: hyperv1.HostedClusterSpec{ Platform: hyperv1.PlatformSpec{ @@ -341,7 +341,7 @@ func TestIsAroHCPByHC(t *testing.T) { expected: false, }, { - name: "When Azure spec is nil it should fall back to env var", + name: "When Azure spec is nil, it should fall back to env var", hc: &hyperv1.HostedCluster{ Spec: hyperv1.HostedClusterSpec{ Platform: hyperv1.PlatformSpec{ @@ -353,7 +353,7 @@ func TestIsAroHCPByHC(t *testing.T) { expected: true, }, { - name: "When Azure spec is nil and env var is not set it should return false", + name: "When Azure spec is nil and env var is not set, it should return false", hc: &hyperv1.HostedCluster{ Spec: hyperv1.HostedClusterSpec{ Platform: hyperv1.PlatformSpec{ @@ -382,7 +382,7 @@ func TestIsPrivateKeyVault(t *testing.T) { expected bool }{ { - name: "When KeyVaultAccess is Private it should return true", + name: "When KeyVaultAccess is Private, it should return true", hcp: &hyperv1.HostedControlPlane{ Spec: hyperv1.HostedControlPlaneSpec{ SecretEncryption: &hyperv1.SecretEncryptionSpec{ @@ -397,7 +397,7 @@ func TestIsPrivateKeyVault(t *testing.T) { expected: true, }, { - name: "When KeyVaultAccess is Public it should return false", + name: "When KeyVaultAccess is Public, it should return false", hcp: &hyperv1.HostedControlPlane{ Spec: hyperv1.HostedControlPlaneSpec{ SecretEncryption: &hyperv1.SecretEncryptionSpec{ @@ -412,7 +412,7 @@ func TestIsPrivateKeyVault(t *testing.T) { expected: false, }, { - name: "When KeyVaultAccess is empty it should return false", + name: "When KeyVaultAccess is empty, it should return false", hcp: &hyperv1.HostedControlPlane{ Spec: hyperv1.HostedControlPlaneSpec{ SecretEncryption: &hyperv1.SecretEncryptionSpec{ @@ -425,14 +425,14 @@ func TestIsPrivateKeyVault(t *testing.T) { expected: false, }, { - name: "When SecretEncryption is nil it should return false", + name: "When SecretEncryption is nil, it should return false", hcp: &hyperv1.HostedControlPlane{ Spec: hyperv1.HostedControlPlaneSpec{}, }, expected: false, }, { - name: "When KMS is nil it should return false", + name: "When KMS is nil, it should return false", hcp: &hyperv1.HostedControlPlane{ Spec: hyperv1.HostedControlPlaneSpec{ SecretEncryption: &hyperv1.SecretEncryptionSpec{}, @@ -441,7 +441,7 @@ func TestIsPrivateKeyVault(t *testing.T) { expected: false, }, { - name: "When Azure KMS is nil it should return false", + name: "When Azure KMS is nil, it should return false", hcp: &hyperv1.HostedControlPlane{ Spec: hyperv1.HostedControlPlaneSpec{ SecretEncryption: &hyperv1.SecretEncryptionSpec{ @@ -470,7 +470,7 @@ func TestCreateEnvVarsForAzureManagedIdentity(t *testing.T) { want []corev1.EnvVar }{ { - name: "returns a slice of environment variables with the azure creds", + name: "When azure credentials filepath is provided, it should return environment variables", args: args{ azureCredentialsFilepath: "my-credentials-file", }, @@ -498,7 +498,7 @@ func TestCreateVolumeMountForAzureSecretStoreProviderClass(t *testing.T) { want corev1.VolumeMount }{ { - name: "return a volume mount for a secret store provider", + name: "When secret store volume name is provided, it should return a volume mount", secretStoreVolumeName: "my-secret-store", want: corev1.VolumeMount{ Name: "my-secret-store", @@ -524,7 +524,7 @@ func TestCreateVolumeForAzureSecretStoreProviderClass(t *testing.T) { want corev1.Volume }{ { - name: "return a volume for a secret store provider", + name: "When secret store volume and provider class are provided, it should return a volume", secretStoreVolumeName: "my-secret-store", secretProviderClassName: "my-secret-provider-class", want: corev1.Volume{ @@ -602,7 +602,7 @@ func TestGetKeyVaultFQDN(t *testing.T) { wantFQDN: "gov-vault.vault.usgovcloudapi.net", }, { - name: "When SecretEncryption is nil it should return error", + name: "When SecretEncryption is nil, it should return error", hcp: &hyperv1.HostedControlPlane{ Spec: hyperv1.HostedControlPlaneSpec{ Platform: hyperv1.PlatformSpec{ @@ -615,7 +615,7 @@ func TestGetKeyVaultFQDN(t *testing.T) { wantErr: true, }, { - name: "When KMS Azure is nil it should return error", + name: "When KMS Azure is nil, it should return error", hcp: &hyperv1.HostedControlPlane{ Spec: hyperv1.HostedControlPlaneSpec{ Platform: hyperv1.PlatformSpec{ @@ -631,7 +631,7 @@ func TestGetKeyVaultFQDN(t *testing.T) { wantErr: true, }, { - name: "When KeyVaultName is empty it should return error", + name: "When KeyVaultName is empty, it should return error", hcp: &hyperv1.HostedControlPlane{ Spec: hyperv1.HostedControlPlaneSpec{ Platform: hyperv1.PlatformSpec{ @@ -678,7 +678,7 @@ func TestGetAzureEncryptionKeyInfo(t *testing.T) { wantErr bool }{ { - name: "When given a valid key id it should parse fields", + name: "When given a valid key id, it should parse fields", id: "https://example-kms.vault.azure.net/keys/example-key/1234abcd", wantVaultHost: "example-kms", wantKeyName: "example-key", @@ -686,22 +686,22 @@ func TestGetAzureEncryptionKeyInfo(t *testing.T) { wantErr: false, }, { - name: "When key id missing version it should error", + name: "When key id missing version, it should error", id: "https://example-kms.vault.azure.net/keys/example-key", wantErr: true, }, { - name: "When key id path not under /keys it should error", + name: "When key id path not under /keys, it should error", id: "https://example-kms.vault.azure.net/secrets/example-key/1234abcd", wantErr: true, }, { - name: "When key id has trailing slash it should error", + name: "When key id has trailing slash, it should error", id: "https://example-kms.vault.azure.net/keys/example-key/1234abcd/", wantErr: true, }, { - name: "Parses govcloud suffix correctly", + name: "When key id has govcloud suffix, it should parse correctly", id: "https://example-kms.vault.usgovcloudapi.net/keys/example-key/1234abcd", wantVaultHost: "example-kms", wantKeyName: "example-key", @@ -709,7 +709,7 @@ func TestGetAzureEncryptionKeyInfo(t *testing.T) { wantErr: false, }, { - name: "Missing scheme should error", + name: "When key id is missing scheme, it should error", id: "example-kms.vault.azure.net/keys/example-key/1234abcd", wantErr: true, }, @@ -763,7 +763,7 @@ func TestReconcileAzureCredentials(t *testing.T) { validateSecret func(secret *corev1.Secret, config AzureCredentialConfig) }{ { - name: "creates all secrets with correct client IDs when all capabilities enabled", + name: "When all capabilities are enabled it should create all secrets with correct client IDs", configs: []AzureCredentialConfig{ { Name: "ingress", @@ -791,7 +791,7 @@ func TestReconcileAzureCredentials(t *testing.T) { }, }, { - name: "skips secrets when capability is disabled", + name: "When capability is disabled it should skip creating secrets", configs: []AzureCredentialConfig{ { Name: "ingress", @@ -820,7 +820,7 @@ func TestReconcileAzureCredentials(t *testing.T) { }, }, { - name: "creates secrets without client ID when not provided", + name: "When client ID is not provided it should create secrets without client ID", configs: []AzureCredentialConfig{ { Name: "test-secret", @@ -840,7 +840,7 @@ func TestReconcileAzureCredentials(t *testing.T) { }, }, { - name: "handles nil manifest function gracefully", + name: "When manifest function returns nil it should handle gracefully", configs: []AzureCredentialConfig{ { Name: "broken-secret", @@ -937,7 +937,7 @@ func TestIsSelfManagedAzureWithWorkloadIdentity(t *testing.T) { expected bool }{ { - name: "When Azure platform with workload identities configured it should return true", + name: "When Azure platform with workload identities configured, it should return true", platformType: hyperv1.AzurePlatform, azure: &hyperv1.AzurePlatformSpec{ AzureAuthenticationConfig: hyperv1.AzureAuthenticationConfiguration{ @@ -947,7 +947,7 @@ func TestIsSelfManagedAzureWithWorkloadIdentity(t *testing.T) { expected: true, }, { - name: "When Azure platform with nil workload identities it should return false", + name: "When Azure platform with nil workload identities, it should return false", platformType: hyperv1.AzurePlatform, azure: &hyperv1.AzurePlatformSpec{ AzureAuthenticationConfig: hyperv1.AzureAuthenticationConfiguration{}, @@ -955,13 +955,13 @@ func TestIsSelfManagedAzureWithWorkloadIdentity(t *testing.T) { expected: false, }, { - name: "When Azure platform with nil azure spec it should return false", + name: "When Azure platform with nil azure spec, it should return false", platformType: hyperv1.AzurePlatform, azure: nil, expected: false, }, { - name: "When non-Azure platform with workload identities it should return false", + name: "When non-Azure platform with workload identities, it should return false", platformType: hyperv1.AWSPlatform, azure: &hyperv1.AzurePlatformSpec{ AzureAuthenticationConfig: hyperv1.AzureAuthenticationConfiguration{ @@ -971,7 +971,7 @@ func TestIsSelfManagedAzureWithWorkloadIdentity(t *testing.T) { expected: false, }, { - name: "When ARO-HCP managed service with workload identities it should return false", + name: "When ARO-HCP managed service with workload identities, it should return false", platformType: hyperv1.AzurePlatform, azure: &hyperv1.AzurePlatformSpec{ AzureAuthenticationConfig: hyperv1.AzureAuthenticationConfiguration{ @@ -1041,37 +1041,37 @@ func TestGetAzureCloudConfiguration(t *testing.T) { wantErr bool }{ { - name: "AzurePublicCloud returns public cloud configuration", + name: "When cloud name is AzurePublicCloud, it should return public cloud configuration", cloudName: "AzurePublicCloud", wantCloud: cloud.AzurePublic, wantErr: false, }, { - name: "Empty string defaults to public cloud configuration", + name: "When cloud name is empty, it should default to public cloud configuration", cloudName: "", wantCloud: cloud.AzurePublic, wantErr: false, }, { - name: "AzureUSGovernmentCloud returns government cloud configuration", + name: "When cloud name is AzureUSGovernmentCloud, it should return government cloud configuration", cloudName: "AzureUSGovernmentCloud", wantCloud: cloud.AzureGovernment, wantErr: false, }, { - name: "AzureChinaCloud returns China cloud configuration", + name: "When cloud name is AzureChinaCloud, it should return China cloud configuration", cloudName: "AzureChinaCloud", wantCloud: cloud.AzureChina, wantErr: false, }, { - name: "Invalid cloud name returns error", + name: "When cloud name is invalid, it should return an error", cloudName: "InvalidCloud", wantCloud: cloud.Configuration{}, wantErr: true, }, { - name: "Unknown cloud name returns error", + name: "When cloud name is unknown, it should return an error", cloudName: "AzureStackCloud", wantCloud: cloud.Configuration{}, wantErr: true, diff --git a/support/azureutil/validation_test.go b/support/azureutil/validation_test.go index fe1560ab3904..c24574d61bb5 100644 --- a/support/azureutil/validation_test.go +++ b/support/azureutil/validation_test.go @@ -17,19 +17,19 @@ func TestValidateAzureResourceName(t *testing.T) { expectErr bool }{ { - name: "When name is under 80 characters it should pass", + name: "When name is under 80 characters, it should pass", resourceName: "pls-my-cluster", resourceType: "Private Link Service", expectErr: false, }, { - name: "When name is exactly 80 characters it should pass", + name: "When name is exactly 80 characters, it should pass", resourceName: strings.Repeat("a", AzureResourceNameMaxLength), resourceType: "Private Endpoint", expectErr: false, }, { - name: "When name exceeds 80 characters it should return an error", + name: "When name exceeds 80 characters, it should return an error", resourceName: strings.Repeat("a", AzureResourceNameMaxLength+1), resourceType: "VNet Link", expectErr: true, diff --git a/support/backwardcompat/backwardcompat_test.go b/support/backwardcompat/backwardcompat_test.go index ad55673f0c45..d594f2a7ab22 100644 --- a/support/backwardcompat/backwardcompat_test.go +++ b/support/backwardcompat/backwardcompat_test.go @@ -16,7 +16,7 @@ func TestNormalizeV1Alpha1ClusterImagePolicy(t *testing.T) { expected string }{ { - name: "When manifest is a v1alpha1 ClusterImagePolicy it should rewrite apiVersion to v1", + name: "When manifest is a v1alpha1 ClusterImagePolicy, it should rewrite apiVersion to v1", input: `apiVersion: config.openshift.io/v1alpha1 kind: ClusterImagePolicy metadata: @@ -35,7 +35,7 @@ spec: `, }, { - name: "When manifest is already v1 ClusterImagePolicy it should return it unchanged", + name: "When manifest is already v1 ClusterImagePolicy, it should return it unchanged", input: `apiVersion: config.openshift.io/v1 kind: ClusterImagePolicy metadata: @@ -48,7 +48,7 @@ metadata: `, }, { - name: "When manifest is a v1alpha1 ImagePolicy it should return it unchanged", + name: "When manifest is a v1alpha1 ImagePolicy, it should return it unchanged", input: `apiVersion: config.openshift.io/v1alpha1 kind: ImagePolicy metadata: @@ -61,7 +61,7 @@ metadata: `, }, { - name: "When manifest is a different resource it should return it unchanged", + name: "When manifest is a different resource, it should return it unchanged", input: `apiVersion: v1 kind: ConfigMap metadata: @@ -74,17 +74,17 @@ metadata: `, }, { - name: "When manifest is invalid YAML it should return it unchanged", + name: "When manifest is invalid YAML, it should return it unchanged", input: `not: valid: yaml: [`, expected: `not: valid: yaml: [`, }, { - name: "When manifest is empty it should return it unchanged", + name: "When manifest is empty, it should return it unchanged", input: ``, expected: ``, }, { - name: "When manifest has v1alpha1 in a value it should only replace the apiVersion occurrence", + name: "When manifest has v1alpha1 in a value, it should only replace the apiVersion occurrence", input: `apiVersion: config.openshift.io/v1alpha1 kind: ClusterImagePolicy metadata: @@ -119,7 +119,7 @@ func TestGetBackwardCompatibleConfigHash(t *testing.T) { requiresBackwardCompat bool }{ { - name: "test config without an image", + name: "When config has no image, it should hash correctly", input: v1beta1.ClusterConfiguration{ Proxy: &v1.ProxySpec{ HTTPProxy: "http://proxy.example.com", @@ -128,7 +128,7 @@ func TestGetBackwardCompatibleConfigHash(t *testing.T) { expectedHashedJSONE: `{"proxy":{"httpProxy":"http://proxy.example.com"}}`, }, { - name: "test config with an image and no imageStreamImportMode", + name: "When config has image but no imageStreamImportMode, it should require backward compatibility", input: v1beta1.ClusterConfiguration{ Proxy: &v1.ProxySpec{ HTTPProxy: "http://proxy.example.com", @@ -143,7 +143,7 @@ func TestGetBackwardCompatibleConfigHash(t *testing.T) { requiresBackwardCompat: true, }, { - name: "test config with an image and imageStreamImportMode", + name: "When config has image with imageStreamImportMode, it should require backward compatibility", input: v1beta1.ClusterConfiguration{ Proxy: &v1.ProxySpec{ HTTPProxy: "http://proxy.example.com", diff --git a/support/catalogs/images_test.go b/support/catalogs/images_test.go index 683073d2df69..916d87210070 100644 --- a/support/catalogs/images_test.go +++ b/support/catalogs/images_test.go @@ -40,7 +40,7 @@ func TestComputeCatalogImages(t *testing.T) { expected map[string]string }{ { - name: "All current release images are available", + name: "When all current release images are available, it should use them", releaseVersion: semver.MustParse("4.19.2"), existingImages: []string{ "registry.redhat.io/redhat/certified-operator-index:v4.19", @@ -54,7 +54,7 @@ func TestComputeCatalogImages(t *testing.T) { }, }, { - name: "Some catalogs only have previous release images", + name: "When some catalogs only have previous release images, it should use them", releaseVersion: semver.MustParse("4.19.2"), existingImages: []string{ "registry.redhat.io/redhat/certified-operator-index:v4.19", @@ -68,7 +68,7 @@ func TestComputeCatalogImages(t *testing.T) { }, }, { - name: "image overrides are used if present", + name: "When image overrides are present, it should use them", releaseVersion: semver.MustParse("4.19.0"), existingImages: []string{ "example.org/test/certified-operator-index:v4.19", @@ -89,7 +89,7 @@ func TestComputeCatalogImages(t *testing.T) { }, }, { - name: "previous versions are used for overrides", + name: "When current version overrides are not available, it should use previous versions", releaseVersion: semver.MustParse("4.19.0"), existingImages: []string{ "example.org/test/certified-operator-index:v4.19", @@ -109,7 +109,7 @@ func TestComputeCatalogImages(t *testing.T) { }, }, { - name: "overrides with root registry and root registry with namespace mixed", + name: "When overrides mix root registry and root registry with namespace, it should resolve correctly", releaseVersion: semver.MustParse("4.19.0"), existingImages: []string{ "example.org/test/certified-operator-index:v4.19", @@ -186,7 +186,7 @@ func TestComputeCatalogImages(t *testing.T) { }, }, { - name: "overrides with root registry only", + name: "When overrides use root registry only, it should resolve correctly", releaseVersion: semver.MustParse("4.19.0"), existingImages: []string{ "example.org/test/certified-operator-index:v4.19", @@ -231,13 +231,13 @@ func TestImagesCacheGetImages(t *testing.T) { expected map[string]string }{ { - name: "cache empty", + name: "When cache is empty, it should return nil", cache: &imagesCache{}, inputHash: "1234", expected: nil, }, { - name: "valid entry", + name: "When cache has valid entry, it should return images", cache: &imagesCache{ timeStamp: time.Now(), hash: "4567", @@ -253,7 +253,7 @@ func TestImagesCacheGetImages(t *testing.T) { }, }, { - name: "hash doesn't match", + name: "When hash does not match, it should return nil", cache: &imagesCache{ timeStamp: time.Now(), hash: "4567", @@ -266,7 +266,7 @@ func TestImagesCacheGetImages(t *testing.T) { expected: nil, }, { - name: "cache expired", + name: "When cache is expired, it should return nil", cache: &imagesCache{ timeStamp: time.Now().Add(-30 * time.Minute), hash: "4567", diff --git a/support/config/resources_test.go b/support/config/resources_test.go index d35237d13337..7bff5e3d3450 100644 --- a/support/config/resources_test.go +++ b/support/config/resources_test.go @@ -78,7 +78,7 @@ func TestApplyResourceRequestOverrides(t *testing.T) { expected corev1.PodSpec }{ { - name: "simple memory override", + name: "When memory override is provided, it should apply it", input: corev1.PodSpec{ Containers: []corev1.Container{ { @@ -114,7 +114,7 @@ func TestApplyResourceRequestOverrides(t *testing.T) { }, }, { - name: "simple memory override, does not affect other settings", + name: "When memory override is provided, it should not affect other resource settings", input: corev1.PodSpec{ Containers: []corev1.Container{ { @@ -160,7 +160,7 @@ func TestApplyResourceRequestOverrides(t *testing.T) { }, }, { - name: "overrides to multiple containers", + name: "When overrides are provided for multiple containers, it should apply them all", input: corev1.PodSpec{ Containers: []corev1.Container{ { @@ -249,7 +249,7 @@ func TestApplyResourceRequestOverrides(t *testing.T) { }, }, { - name: "different deployment", + name: "When override is for different deployment, it should not apply", input: corev1.PodSpec{ Containers: []corev1.Container{ { diff --git a/support/etcd/shards_test.go b/support/etcd/shards_test.go index 7923f8d3a860..a475ae56e2c7 100644 --- a/support/etcd/shards_test.go +++ b/support/etcd/shards_test.go @@ -17,12 +17,12 @@ func TestEffectiveShards(t *testing.T) { wantShardNames []string }{ { - name: "nil managed returns nil", + name: "When managed etcd is nil, it should return nil", managed: nil, wantLen: 0, }, { - name: "no shards returns only default", + name: "When no shards are configured, it should return only default", managed: &hyperv1.ManagedEtcdSpec{ Storage: hyperv1.ManagedEtcdStorageSpec{ Type: hyperv1.PersistentVolumeEtcdStorage, @@ -33,7 +33,7 @@ func TestEffectiveShards(t *testing.T) { wantShardNames: []string{"etcd"}, }, { - name: "with shards returns default plus shards", + name: "When shards are configured, it should return default plus shards", managed: &hyperv1.ManagedEtcdSpec{ Storage: hyperv1.ManagedEtcdStorageSpec{ Type: hyperv1.PersistentVolumeEtcdStorage, @@ -89,12 +89,12 @@ func TestUnmanagedEffectiveShards(t *testing.T) { wantLen int }{ { - name: "nil returns nil", + name: "When unmanaged etcd is nil, it should return nil", unmanaged: nil, wantLen: 0, }, { - name: "no shards returns only default", + name: "When no shards are configured, it should return only default", unmanaged: &hyperv1.UnmanagedEtcdSpec{ Endpoint: "https://etcd:2379", TLS: hyperv1.EtcdTLSConfig{}, @@ -102,7 +102,7 @@ func TestUnmanagedEffectiveShards(t *testing.T) { wantLen: 1, }, { - name: "with shards", + name: "When shards are configured, it should return default plus shards", unmanaged: &hyperv1.UnmanagedEtcdSpec{ Endpoint: "https://etcd:2379", TLS: hyperv1.EtcdTLSConfig{}, @@ -137,17 +137,17 @@ func TestResourcePrefix(t *testing.T) { want string }{ { - name: "core group", + name: "When resource is in core group, it should use slash prefix", resource: hyperv1.EtcdShardResource{Resource: "events"}, want: "/events", }, { - name: "empty string apiGroup", + name: "When apiGroup is empty string, it should use slash prefix", resource: hyperv1.EtcdShardResource{APIGroup: ptr.To(""), Resource: "events"}, want: "/events", }, { - name: "non-core group", + name: "When resource is in non-core group, it should include group prefix", resource: hyperv1.EtcdShardResource{APIGroup: ptr.To("coordination.k8s.io"), Resource: "leases"}, want: "coordination.k8s.io/leases", }, diff --git a/support/events/message_test.go b/support/events/message_test.go index ff73514ffa46..690dcc122d69 100644 --- a/support/events/message_test.go +++ b/support/events/message_test.go @@ -44,17 +44,17 @@ func TestErrorMessages(t *testing.T) { expected []string }{ { - name: "single event", + name: "When a single warning event exists, it should return the message", events: evl(ev("msg1", corev1.EventTypeWarning, "r1")), expected: []string{"msg1"}, }, { - name: "no warning events", + name: "When no warning events exist, it should return empty list", events: evl(ev("msg1", corev1.EventTypeNormal, "r1")), expected: []string{}, }, { - name: "warning and info events", + name: "When both warning and info events exist, it should return only warnings", events: evl( ev("msg1", corev1.EventTypeNormal, "r1"), ev("msg2", corev1.EventTypeWarning, "r2"), @@ -62,7 +62,7 @@ func TestErrorMessages(t *testing.T) { expected: []string{"msg2"}, }, { - name: "multiple events with same reason", + name: "When multiple events with same reason exist, it should return the most recent", events: evl( ev("msg1", corev1.EventTypeWarning, "rr"), ev("msg2", corev1.EventTypeWarning, "rr"), @@ -72,7 +72,7 @@ func TestErrorMessages(t *testing.T) { expected: []string{"msg3"}, }, { - name: "multiple events with different reasons", + name: "When multiple events with different reasons exist, it should return the most recent per reason", events: evl( ev("msg1", corev1.EventTypeWarning, "r1"), ev("msg2", corev1.EventTypeWarning, "r1"), diff --git a/support/forwarder/forwarder_test.go b/support/forwarder/forwarder_test.go index ad8d4093d013..fb1f0b0f0d76 100644 --- a/support/forwarder/forwarder_test.go +++ b/support/forwarder/forwarder_test.go @@ -26,7 +26,7 @@ func TestGetRunningKubeAPIServerPod(t *testing.T) { errContains string }{ { - name: "successfully find running kube-apiserver pod", + name: "When a running kube-apiserver pod exists, it should return the pod", pods: []client.Object{ &corev1.Pod{ ObjectMeta: metav1.ObjectMeta{ @@ -46,7 +46,7 @@ func TestGetRunningKubeAPIServerPod(t *testing.T) { wantErr: false, }, { - name: "no running kube-apiserver pod found", + name: "When no running kube-apiserver pod exists, it should return an error", pods: []client.Object{ &corev1.Pod{ ObjectMeta: metav1.ObjectMeta{ @@ -67,7 +67,7 @@ func TestGetRunningKubeAPIServerPod(t *testing.T) { errContains: "did not find running kube-apiserver pod", }, { - name: "no kube-apiserver pods found", + name: "When no kube-apiserver pods exist, it should return an error", pods: []client.Object{ &corev1.Pod{ ObjectMeta: metav1.ObjectMeta{ diff --git a/support/k8sutil/annotations_test.go b/support/k8sutil/annotations_test.go index 9e5a75556ef8..878323f06e04 100644 --- a/support/k8sutil/annotations_test.go +++ b/support/k8sutil/annotations_test.go @@ -25,28 +25,28 @@ func TestHasAnnotationWithValue(t *testing.T) { want bool }{ { - name: "When annotation exists with matching value it should return true", + name: "When annotation exists with matching value, it should return true", annotations: map[string]string{"foo": "bar"}, key: "foo", value: "bar", want: true, }, { - name: "When annotation exists with different value it should return false", + name: "When annotation exists with different value, it should return false", annotations: map[string]string{"foo": "baz"}, key: "foo", value: "bar", want: false, }, { - name: "When annotation does not exist it should return false", + name: "When annotation does not exist, it should return false", annotations: map[string]string{"other": "value"}, key: "foo", value: "bar", want: false, }, { - name: "When annotations map is nil it should return false", + name: "When annotations map is nil, it should return false", annotations: nil, key: "foo", value: "bar", @@ -89,7 +89,7 @@ func TestHostedClusterFromAnnotation(t *testing.T) { errSubstr string }{ { - name: "When annotation is missing it should return an error", + name: "When annotation is missing, it should return an error", obj: &hyperv1.AzurePrivateLinkService{ ObjectMeta: metav1.ObjectMeta{ Name: "test-pls", @@ -100,7 +100,7 @@ func TestHostedClusterFromAnnotation(t *testing.T) { errSubstr: "missing", }, { - name: "When annotation value is empty it should return a format error", + name: "When annotation value is empty, it should return a format error", obj: &hyperv1.AzurePrivateLinkService{ ObjectMeta: metav1.ObjectMeta{ Name: "test-pls", @@ -114,7 +114,7 @@ func TestHostedClusterFromAnnotation(t *testing.T) { errSubstr: "invalid", }, { - name: "When annotation has no slash it should return a format error", + name: "When annotation has no slash, it should return a format error", obj: &hyperv1.AzurePrivateLinkService{ ObjectMeta: metav1.ObjectMeta{ Name: "test-pls", @@ -128,7 +128,7 @@ func TestHostedClusterFromAnnotation(t *testing.T) { errSubstr: "invalid", }, { - name: "When annotation has empty namespace it should return a format error", + name: "When annotation has empty namespace, it should return a format error", obj: &hyperv1.AzurePrivateLinkService{ ObjectMeta: metav1.ObjectMeta{ Name: "test-pls", @@ -142,7 +142,7 @@ func TestHostedClusterFromAnnotation(t *testing.T) { errSubstr: "invalid", }, { - name: "When annotation has empty name it should return a format error", + name: "When annotation has empty name, it should return a format error", obj: &hyperv1.AzurePrivateLinkService{ ObjectMeta: metav1.ObjectMeta{ Name: "test-pls", @@ -156,7 +156,7 @@ func TestHostedClusterFromAnnotation(t *testing.T) { errSubstr: "invalid", }, { - name: "When annotation is valid but HostedCluster does not exist it should return an error", + name: "When annotation is valid but HostedCluster does not exist, it should return an error", obj: &hyperv1.AzurePrivateLinkService{ ObjectMeta: metav1.ObjectMeta{ Name: "test-pls", diff --git a/support/k8sutil/object_test.go b/support/k8sutil/object_test.go index 81b87d4a84a6..18a83478dfc6 100644 --- a/support/k8sutil/object_test.go +++ b/support/k8sutil/object_test.go @@ -419,7 +419,7 @@ func TestParseNodeSelector(t *testing.T) { want map[string]string }{ { - name: "When input has multiple key=value pairs it should return all entries", + name: "When input has multiple key=value pairs, it should return all entries", str: "key1=value1,key2=value2,key3=value3", want: map[string]string{ "key1": "value1", @@ -428,26 +428,26 @@ func TestParseNodeSelector(t *testing.T) { }, }, { - name: "When entries have empty values it should skip them", + name: "When entries have empty values, it should skip them", str: "key1=,key2=value2,key3=", want: map[string]string{ "key2": "value2", }, }, { - name: "When entries have empty keys it should skip them", + name: "When entries have empty keys, it should skip them", str: "=value1,key2=value2,=value3", want: map[string]string{ "key2": "value2", }, }, { - name: "When input is empty it should return nil", + name: "When input is empty, it should return nil", str: "", want: nil, }, { - name: "When entries lack an = separator it should skip them", + name: "When entries lack an = separator, it should skip them", str: "key1=value1,key2,key3=value3", want: map[string]string{ "key1": "value1", @@ -455,7 +455,7 @@ func TestParseNodeSelector(t *testing.T) { }, }, { - name: "When values contain = characters it should preserve them", + name: "When values contain = characters, it should preserve them", str: "key1=value1=one,key2,key3=value3=three", want: map[string]string{ "key1": "value1=one", diff --git a/support/k8sutil/service_test.go b/support/k8sutil/service_test.go index 64cf78260b7c..bc9bff2bc6c6 100644 --- a/support/k8sutil/service_test.go +++ b/support/k8sutil/service_test.go @@ -104,7 +104,7 @@ func TestExtractHostedControlPlaneOwnerName(t *testing.T) { want string }{ { - name: "When HostedControlPlane owner ref exists it should return the name", + name: "When HostedControlPlane owner ref exists, it should return the name", ownerRefs: []metav1.OwnerReference{ { APIVersion: hyperv1.GroupVersion.String(), @@ -115,12 +115,12 @@ func TestExtractHostedControlPlaneOwnerName(t *testing.T) { want: "my-hcp", }, { - name: "When no owner refs exist it should return empty string", + name: "When no owner refs exist, it should return empty string", ownerRefs: []metav1.OwnerReference{}, want: "", }, { - name: "When owner refs exist but none is HostedControlPlane it should return empty string", + name: "When owner refs exist but none is HostedControlPlane, it should return empty string", ownerRefs: []metav1.OwnerReference{ { APIVersion: "apps/v1", @@ -136,7 +136,7 @@ func TestExtractHostedControlPlaneOwnerName(t *testing.T) { want: "", }, { - name: "When multiple owner refs exist it should return only the HCP one", + name: "When multiple owner refs exist, it should return only the HCP one", ownerRefs: []metav1.OwnerReference{ { APIVersion: "apps/v1", @@ -157,7 +157,7 @@ func TestExtractHostedControlPlaneOwnerName(t *testing.T) { want: "my-hcp", }, { - name: "When owner ref has wrong APIVersion it should return empty string", + name: "When owner ref has wrong APIVersion, it should return empty string", ownerRefs: []metav1.OwnerReference{ { APIVersion: "wrong.api/v1", diff --git a/support/karpenter/karpenter_test.go b/support/karpenter/karpenter_test.go index c4a2db3aca11..4c2e3f81f086 100644 --- a/support/karpenter/karpenter_test.go +++ b/support/karpenter/karpenter_test.go @@ -116,13 +116,13 @@ func TestSupportedArchitectures(t *testing.T) { expectedError error }{ { - name: "AWS", + name: "When platform is AWS, it should return AMD64 and ARM64 architectures", platform: hyperv1.AWSPlatform, expected: []string{hyperv1.ArchitectureAMD64, hyperv1.ArchitectureARM64}, expectedError: nil, }, { - name: "Azure", + name: "When platform is Azure, it should return unsupported platform error", platform: hyperv1.AzurePlatform, expected: nil, expectedError: fmt.Errorf("unsupported platform: Azure"), @@ -152,12 +152,12 @@ func TestArchToAMILabelKey(t *testing.T) { expected string }{ { - name: "AMD64", + name: "When architecture is AMD64, it should return the standard AMI label key", arch: hyperv1.ArchitectureAMD64, expected: "hypershift.openshift.io/ami", }, { - name: "ARM64", + name: "When architecture is ARM64, it should return the ARM64-specific AMI label key", arch: hyperv1.ArchitectureARM64, expected: "hypershift.openshift.io/ami-arm64", }, diff --git a/support/konnectivityproxy/dialer_test.go b/support/konnectivityproxy/dialer_test.go index ca327cad709c..790fa8717046 100644 --- a/support/konnectivityproxy/dialer_test.go +++ b/support/konnectivityproxy/dialer_test.go @@ -24,7 +24,7 @@ func TestValidate(t *testing.T) { expectValid bool }{ { - name: "valid options", + name: "When all required options are provided it should be valid", o: Options{ CAFile: "test-ca", ClientCertBytes: []byte("test-cert"), @@ -36,7 +36,7 @@ func TestValidate(t *testing.T) { expectValid: true, }, { - name: "missing CA", + name: "When CA is missing it should be invalid", o: Options{ ClientCertBytes: []byte("test-cert"), ClientKeyFile: "test-key-name", @@ -47,7 +47,7 @@ func TestValidate(t *testing.T) { expectValid: false, }, { - name: "missing KonnectivityPort", + name: "When KonnectivityPort is missing it should be invalid", o: Options{ CABytes: []byte("test-ca"), ClientCertBytes: []byte("test-cert"), @@ -58,7 +58,7 @@ func TestValidate(t *testing.T) { expectValid: false, }, { - name: "client cert file and bytes", + name: "When both client cert file and bytes are provided it should be invalid", o: Options{ CAFile: "test-ca", ClientCertFile: "test-cert-file", @@ -93,13 +93,13 @@ func TestKonnectivityHealth(t *testing.T) { expected bool }{ { - name: "When healthy it should allow retry", + name: "When healthy, it should allow retry", setup: func(kh *konnectivityHealth) {}, action: func(kh *konnectivityHealth) bool { return kh.beginRetry() }, expected: true, }, { - name: "When in fallback and too soon it should not retry", + name: "When in fallback and too soon, it should not retry", setup: func(kh *konnectivityHealth) { kh.markFailure() }, @@ -107,7 +107,7 @@ func TestKonnectivityHealth(t *testing.T) { expected: false, }, { - name: "When in fallback and enough time passed it should retry", + name: "When in fallback and enough time passed, it should retry", setup: func(kh *konnectivityHealth) { kh.markFailure() // Set lastRetryTime to past @@ -117,7 +117,7 @@ func TestKonnectivityHealth(t *testing.T) { expected: true, }, { - name: "When another retry is active it should not retry", + name: "When another retry is active, it should not retry", setup: func(kh *konnectivityHealth) { kh.markFailure() kh.lastRetryTime = time.Now().Add(-31 * time.Second) @@ -127,7 +127,7 @@ func TestKonnectivityHealth(t *testing.T) { expected: false, }, { - name: "After success it should be healthy", + name: "When the check succeeds, it should be healthy", setup: func(kh *konnectivityHealth) { kh.markFailure() kh.markSuccess() @@ -136,7 +136,7 @@ func TestKonnectivityHealth(t *testing.T) { expected: true, }, { - name: "After failure it should be unhealthy", + name: "When the check fails, it should be unhealthy", setup: func(kh *konnectivityHealth) { kh.markFailure() }, @@ -208,7 +208,7 @@ func TestKonnectivityHealthEndRetry(t *testing.T) { expectRetry bool }{ { - name: "When endRetry is called it should clear activeRetry flag", + name: "When endRetry is called, it should clear activeRetry flag", setup: func(kh *konnectivityHealth) { kh.markFailure() kh.lastRetryTime = time.Now().Add(-31 * time.Second) @@ -220,7 +220,7 @@ func TestKonnectivityHealthEndRetry(t *testing.T) { expectRetry: true, // Should allow retry since activeRetry was cleared }, { - name: "When endRetry is called after beginRetry it should allow subsequent retries", + name: "When endRetry is called after beginRetry, it should allow subsequent retries", setup: func(kh *konnectivityHealth) { kh.markFailure() kh.lastRetryTime = time.Now().Add(-31 * time.Second) @@ -232,7 +232,7 @@ func TestKonnectivityHealthEndRetry(t *testing.T) { expectRetry: true, // Should allow new retry after endRetry was called }, { - name: "When multiple endRetry calls it should remain safe", + name: "When multiple endRetry calls, it should remain safe", setup: func(kh *konnectivityHealth) { kh.markFailure() kh.lastRetryTime = time.Now().Add(-31 * time.Second) @@ -434,25 +434,25 @@ func TestIsCloudAPI(t *testing.T) { }{ // Valid cloud API hosts { - name: "When host is valid AWS API it should return true", + name: "When host is valid AWS API, it should return true", host: "ec2.amazonaws.com", expected: true, description: "AWS API endpoints should be detected", }, { - name: "When host is valid Azure API it should return true", + name: "When host is valid Azure API, it should return true", host: "management.azure.com", expected: true, description: "Azure API endpoints should be detected", }, { - name: "When host is valid Microsoft API it should return true", + name: "When host is valid Microsoft API, it should return true", host: "login.microsoftonline.com", expected: true, description: "Microsoft API endpoints should be detected", }, { - name: "When host is valid IBM API it should return true", + name: "When host is valid IBM API, it should return true", host: "iam.cloud.ibm.com", expected: true, description: "IBM Cloud API endpoints should be detected", @@ -460,19 +460,19 @@ func TestIsCloudAPI(t *testing.T) { // Valid AWS ISO cloud API hosts { - name: "When host is valid AWS ISO C2S API it should return true", + name: "When host is valid AWS ISO C2S API, it should return true", host: "s3.c2s.ic.gov", expected: true, description: "AWS ISO C2S endpoints should be detected", }, { - name: "When host is valid AWS ISO HCI API it should return true", + name: "When host is valid AWS ISO HCI API, it should return true", host: "iam.hci.ic.gov", expected: true, description: "AWS ISO HCI endpoints should be detected", }, { - name: "When host is valid AWS ISO-B SC2S API it should return true", + name: "When host is valid AWS ISO-B SC2S API, it should return true", host: "s3.sc2s.sgov.gov", expected: true, description: "AWS ISO-B SC2S endpoints should be detected", @@ -480,25 +480,25 @@ func TestIsCloudAPI(t *testing.T) { // False positive scenarios that were fixed { - name: "When host contains azure.com but is not azure.com it should return false", + name: "When host contains azure.com but is not azure.com, it should return false", host: "notazure.com", expected: false, description: "False positive: hosts ending with azure.com but not actually Azure", }, { - name: "When host contains cloud.ibm.com but is not IBM it should return false", + name: "When host contains cloud.ibm.com but is not IBM, it should return false", host: "fakecloud.ibm.com", expected: false, description: "False positive: hosts ending with cloud.ibm.com but not actually IBM", }, { - name: "When host is malicious azure lookalike it should return false", + name: "When host is malicious azure lookalike, it should return false", host: "evilazure.com", expected: false, description: "Malicious hosts trying to mimic Azure should not be detected as cloud API", }, { - name: "When host is malicious IBM lookalike it should return false", + name: "When host is malicious IBM lookalike, it should return false", host: "badcloud.ibm.com", expected: false, description: "Malicious hosts trying to mimic IBM should not be detected as cloud API", @@ -506,13 +506,13 @@ func TestIsCloudAPI(t *testing.T) { // Edge cases { - name: "When host is exactly azure.com it should return false", + name: "When host is exactly azure.com, it should return false", host: "azure.com", expected: false, description: "Bare azure.com without subdomain should not be cloud API", }, { - name: "When host is exactly cloud.ibm.com it should return false", + name: "When host is exactly cloud.ibm.com, it should return false", host: "cloud.ibm.com", expected: false, description: "Bare cloud.ibm.com without subdomain should not be cloud API", @@ -520,13 +520,13 @@ func TestIsCloudAPI(t *testing.T) { // Non-cloud hosts { - name: "When host is not cloud API it should return false", + name: "When host is not cloud API, it should return false", host: "example.com", expected: false, description: "Regular hosts should not be detected as cloud API", }, { - name: "When host is empty it should return false", + name: "When host is empty, it should return false", host: "", expected: false, description: "Empty host should not be detected as cloud API", diff --git a/support/metrics/sets_test.go b/support/metrics/sets_test.go index 0af839848a07..a7df4e4cfe6d 100644 --- a/support/metrics/sets_test.go +++ b/support/metrics/sets_test.go @@ -15,17 +15,17 @@ func TestSchedulerResourceRelabelConfigs(t *testing.T) { want int }{ { - name: "When using Telemetry metrics set it should return a drop-all relabel config", + name: "When using Telemetry metrics set, it should return a drop-all relabel config", set: MetricsSetTelemetry, want: 1, }, { - name: "When using SRE metrics set it should return SRE config", + name: "When using SRE metrics set, it should return SRE config", set: MetricsSetSRE, want: 0, }, { - name: "When using All metrics set it should return nil", + name: "When using All metrics set, it should return nil", set: MetricsSetAll, want: 0, }, diff --git a/support/netutil/iputil_test.go b/support/netutil/iputil_test.go index 601a70ca3e21..3612ce5ac448 100644 --- a/support/netutil/iputil_test.go +++ b/support/netutil/iputil_test.go @@ -14,25 +14,25 @@ func TestFirstUsableIP(t *testing.T) { wantErr bool }{ { - name: "Given IPv4 CIDR, it should return the first ip of the network range", + name: "When IPv4 CIDR is provided, it should return the first ip of the network range", cidr: "192.168.1.0/24", want: "192.168.1.1", wantErr: false, }, { - name: "Given IPv6 CIDR, it should return the first ip of the network range", + name: "When IPv6 CIDR is provided, it should return the first ip of the network range", cidr: "2000::/3", want: "2000::1", wantErr: false, }, { - name: "Given a malformed IPv4 CIDR, it should return empty string and err", + name: "When a malformed IPv4 CIDR is provided, it should return empty string and err", cidr: "192.168.1.35.53/24", want: "", wantErr: true, }, { - name: "Given a malformed IPv6 CIDR, it should return empty string and err", + name: "When a malformed IPv6 CIDR is provided, it should return empty string and err", cidr: "2001::44444444444444/17", want: "", wantErr: true, diff --git a/support/netutil/networking_test.go b/support/netutil/networking_test.go index 7061b1212dc8..8e876cedf5c3 100644 --- a/support/netutil/networking_test.go +++ b/support/netutil/networking_test.go @@ -22,7 +22,7 @@ func TestGetAdvertiseAddress(t *testing.T) { want string }{ { - name: "given an AdvertiseAddress in the HCP, it should return it", + name: "When an AdvertiseAddress is set in the HCP, it should return it", hcp: &hyperv1.HostedControlPlane{ Spec: hyperv1.HostedControlPlaneSpec{ Networking: hyperv1.ClusterNetworking{ @@ -38,7 +38,7 @@ func TestGetAdvertiseAddress(t *testing.T) { want: "192.168.1.1", }, { - name: "given no AdvertiseAddress/es in the HCP, it should return IPv4 based default address", + name: "When no AdvertiseAddress is set in the HCP, it should return IPv4 based default address", hcp: &hyperv1.HostedControlPlane{ Spec: hyperv1.HostedControlPlaneSpec{ Networking: hyperv1.ClusterNetworking{ @@ -51,7 +51,7 @@ func TestGetAdvertiseAddress(t *testing.T) { want: DefaultAdvertiseIPv4Address, }, { - name: "given no AdvertiseAddress/es in the HCP, it should return IPv6 based default address", + name: "When no AdvertiseAddress is set and ServiceNetwork is IPv6, it should return IPv6 based default address", hcp: &hyperv1.HostedControlPlane{ Spec: hyperv1.HostedControlPlaneSpec{ Networking: hyperv1.ClusterNetworking{ @@ -64,7 +64,7 @@ func TestGetAdvertiseAddress(t *testing.T) { want: DefaultAdvertiseIPv6Address, }, { - name: "given no ServiceNetwork CIDR in the HCP, it should return IPv4 based default address", + name: "When no ServiceNetwork CIDR is set in the HCP, it should return IPv4 based default address", hcp: &hyperv1.HostedControlPlane{ Spec: hyperv1.HostedControlPlaneSpec{ Networking: hyperv1.ClusterNetworking{ @@ -90,14 +90,14 @@ func TestMachineNetworksToList(t *testing.T) { want string }{ { - name: "single CIDR", + name: "When a single CIDR is provided, it should return comma-separated list", machineNetwork: []hyperv1.MachineNetworkEntry{ {CIDR: *ipnet.MustParseCIDR("192.168.1.0/24")}, }, want: "192.168.1.0/24", }, { - name: "multiple CIDRs", + name: "When multiple CIDRs are provided, it should return comma-separated list", machineNetwork: []hyperv1.MachineNetworkEntry{ {CIDR: *ipnet.MustParseCIDR("192.168.1.0/24")}, {CIDR: *ipnet.MustParseCIDR("10.0.0.0/8")}, @@ -105,7 +105,7 @@ func TestMachineNetworksToList(t *testing.T) { want: "192.168.1.0/24,10.0.0.0/8", }, { - name: "no CIDRs", + name: "When no CIDRs are provided, it should return empty string", machineNetwork: []hyperv1.MachineNetworkEntry{}, want: "", }, @@ -126,7 +126,7 @@ func TestIsMultusDisabled(t *testing.T) { expected bool }{ { - name: "DisableMultiNetwork is nil - defaults to false (multus enabled)", + name: "When DisableMultiNetwork is nil, it should default to false (multus enabled)", hcp: &hyperv1.HostedControlPlane{ Spec: hyperv1.HostedControlPlaneSpec{ OperatorConfiguration: &hyperv1.OperatorConfiguration{ @@ -137,7 +137,7 @@ func TestIsMultusDisabled(t *testing.T) { expected: false, }, { - name: "DisableMultiNetwork is explicitly false", + name: "When DisableMultiNetwork is explicitly false, it should return false", hcp: &hyperv1.HostedControlPlane{ Spec: hyperv1.HostedControlPlaneSpec{ OperatorConfiguration: &hyperv1.OperatorConfiguration{ @@ -150,7 +150,7 @@ func TestIsMultusDisabled(t *testing.T) { expected: false, }, { - name: "DisableMultiNetwork is explicitly true", + name: "When DisableMultiNetwork is explicitly true, it should return true", hcp: &hyperv1.HostedControlPlane{ Spec: hyperv1.HostedControlPlaneSpec{ OperatorConfiguration: &hyperv1.OperatorConfiguration{ @@ -163,14 +163,14 @@ func TestIsMultusDisabled(t *testing.T) { expected: true, }, { - name: "OperatorConfiguration is nil", + name: "When OperatorConfiguration is nil, it should default to false", hcp: &hyperv1.HostedControlPlane{ Spec: hyperv1.HostedControlPlaneSpec{}, }, expected: false, }, { - name: "ClusterNetworkOperator is nil", + name: "When ClusterNetworkOperator is nil, it should default to false", hcp: &hyperv1.HostedControlPlane{ Spec: hyperv1.HostedControlPlaneSpec{ OperatorConfiguration: &hyperv1.OperatorConfiguration{}, diff --git a/support/netutil/public_test.go b/support/netutil/public_test.go index 8de104b33a18..71981ba5a3ef 100644 --- a/support/netutil/public_test.go +++ b/support/netutil/public_test.go @@ -13,30 +13,30 @@ func TestConnectsThroughInternetToControlplane(t *testing.T) { expected bool }{ { - name: "Not aws always uses internet", + name: "When platform is not AWS, it should use internet", expected: true, }, { - name: "AWS public uses internet", + name: "When AWS endpoint access is public, it should use internet", platform: hyperv1.PlatformSpec{ AWS: &hyperv1.AWSPlatformSpec{EndpointAccess: hyperv1.Public}, }, expected: true, }, { - name: "AWS public/private doesn't use internet", + name: "When AWS endpoint access is public and private it should not use internet", platform: hyperv1.PlatformSpec{ AWS: &hyperv1.AWSPlatformSpec{EndpointAccess: hyperv1.PublicAndPrivate}, }, }, { - name: "AWS private doesn't use internet", + name: "When AWS endpoint access is private it should not use internet", platform: hyperv1.PlatformSpec{ AWS: &hyperv1.AWSPlatformSpec{EndpointAccess: hyperv1.Private}, }, }, { - name: "When Azure topology is Public it should use internet", + name: "When Azure topology is Public, it should use internet", platform: hyperv1.PlatformSpec{ Azure: &hyperv1.AzurePlatformSpec{Topology: hyperv1.AzureTopologyPublic}, }, @@ -55,14 +55,14 @@ func TestConnectsThroughInternetToControlplane(t *testing.T) { }, }, { - name: "When Azure topology is empty it should use internet", + name: "When Azure topology is empty, it should use internet", platform: hyperv1.PlatformSpec{ Azure: &hyperv1.AzurePlatformSpec{}, }, expected: true, }, { - name: "When Azure spec is nil it should use internet", + name: "When Azure spec is nil, it should use internet", expected: true, }, } diff --git a/support/netutil/visibility_test.go b/support/netutil/visibility_test.go index 32cfc020a07d..6d8943eded97 100644 --- a/support/netutil/visibility_test.go +++ b/support/netutil/visibility_test.go @@ -1054,7 +1054,7 @@ func TestUseSwiftNetworkingHCP(t *testing.T) { want bool }{ { - name: "When Azure platform with Private.Type=Swift it should return true", + name: "When Azure platform with Private.Type=Swift, it should return true", hcp: &hyperv1.HostedControlPlane{ Spec: hyperv1.HostedControlPlaneSpec{ Platform: hyperv1.PlatformSpec{ @@ -1073,7 +1073,7 @@ func TestUseSwiftNetworkingHCP(t *testing.T) { want: true, }, { - name: "When Azure platform with annotation fallback it should return true", + name: "When Azure platform with annotation fallback, it should return true", hcp: &hyperv1.HostedControlPlane{ ObjectMeta: metav1.ObjectMeta{ Annotations: map[string]string{ @@ -1092,7 +1092,7 @@ func TestUseSwiftNetworkingHCP(t *testing.T) { want: true, }, { - name: "When Azure platform with neither API field nor annotation it should return false", + name: "When Azure platform with neither API field nor annotation, it should return false", hcp: &hyperv1.HostedControlPlane{ Spec: hyperv1.HostedControlPlaneSpec{ Platform: hyperv1.PlatformSpec{ @@ -1104,7 +1104,7 @@ func TestUseSwiftNetworkingHCP(t *testing.T) { want: false, }, { - name: "When AWS platform it should return false", + name: "When AWS platform, it should return false", hcp: &hyperv1.HostedControlPlane{ Spec: hyperv1.HostedControlPlaneSpec{ Platform: hyperv1.PlatformSpec{ @@ -1116,7 +1116,7 @@ func TestUseSwiftNetworkingHCP(t *testing.T) { want: false, }, { - name: "When Azure platform with Private.Type=PrivateLink it should return false", + name: "When Azure platform with Private.Type=PrivateLink, it should return false", hcp: &hyperv1.HostedControlPlane{ Spec: hyperv1.HostedControlPlaneSpec{ Platform: hyperv1.PlatformSpec{ @@ -1152,7 +1152,7 @@ func TestUseSwiftNetworkingHC(t *testing.T) { want bool }{ { - name: "When Azure platform with Private.Type=Swift it should return true", + name: "When Azure platform with Private.Type=Swift, it should return true", hc: &hyperv1.HostedCluster{ Spec: hyperv1.HostedClusterSpec{ Platform: hyperv1.PlatformSpec{ @@ -1171,7 +1171,7 @@ func TestUseSwiftNetworkingHC(t *testing.T) { want: true, }, { - name: "When Azure platform with annotation fallback it should return true", + name: "When Azure platform with annotation fallback, it should return true", hc: &hyperv1.HostedCluster{ ObjectMeta: metav1.ObjectMeta{ Annotations: map[string]string{ @@ -1190,7 +1190,7 @@ func TestUseSwiftNetworkingHC(t *testing.T) { want: true, }, { - name: "When Azure platform with neither API field nor annotation it should return false", + name: "When Azure platform with neither API field nor annotation, it should return false", hc: &hyperv1.HostedCluster{ Spec: hyperv1.HostedClusterSpec{ Platform: hyperv1.PlatformSpec{ @@ -1202,7 +1202,7 @@ func TestUseSwiftNetworkingHC(t *testing.T) { want: false, }, { - name: "When AWS platform it should return false", + name: "When AWS platform, it should return false", hc: &hyperv1.HostedCluster{ Spec: hyperv1.HostedClusterSpec{ Platform: hyperv1.PlatformSpec{ @@ -1214,7 +1214,7 @@ func TestUseSwiftNetworkingHC(t *testing.T) { want: false, }, { - name: "When Azure platform with Private.Type=PrivateLink it should return false", + name: "When Azure platform with Private.Type=PrivateLink, it should return false", hc: &hyperv1.HostedCluster{ Spec: hyperv1.HostedClusterSpec{ Platform: hyperv1.PlatformSpec{ @@ -1249,7 +1249,7 @@ func TestUseSharedIngressHCP(t *testing.T) { want bool }{ { - name: "When Swift with PublicAndPrivate topology it should return true", + name: "When Swift with PublicAndPrivate topology, it should return true", hcp: &hyperv1.HostedControlPlane{ Spec: hyperv1.HostedControlPlaneSpec{ Platform: hyperv1.PlatformSpec{ @@ -1272,7 +1272,7 @@ func TestUseSharedIngressHCP(t *testing.T) { want: true, }, { - name: "When Swift with Private topology it should return false", + name: "When Swift with Private topology, it should return false", hcp: &hyperv1.HostedControlPlane{ Spec: hyperv1.HostedControlPlaneSpec{ Platform: hyperv1.PlatformSpec{ @@ -1295,7 +1295,7 @@ func TestUseSharedIngressHCP(t *testing.T) { want: false, }, { - name: "When Swift with empty topology it should return true", + name: "When Swift with empty topology, it should return true", hcp: &hyperv1.HostedControlPlane{ Spec: hyperv1.HostedControlPlaneSpec{ Platform: hyperv1.PlatformSpec{ @@ -1317,7 +1317,7 @@ func TestUseSharedIngressHCP(t *testing.T) { want: true, }, { - name: "When ManagedIdentities without Swift and empty topology it should return true", + name: "When ManagedIdentities without Swift and empty topology, it should return true", hcp: &hyperv1.HostedControlPlane{ Spec: hyperv1.HostedControlPlaneSpec{ Platform: hyperv1.PlatformSpec{ @@ -1333,7 +1333,7 @@ func TestUseSharedIngressHCP(t *testing.T) { want: true, }, { - name: "When non-Swift it should return false", + name: "When non-Swift, it should return false", hcp: &hyperv1.HostedControlPlane{ Spec: hyperv1.HostedControlPlaneSpec{ Platform: hyperv1.PlatformSpec{ @@ -1366,7 +1366,7 @@ func TestUseSharedIngressHC(t *testing.T) { want bool }{ { - name: "When Swift with PublicAndPrivate topology it should return true", + name: "When Swift with PublicAndPrivate topology, it should return true", hc: &hyperv1.HostedCluster{ Spec: hyperv1.HostedClusterSpec{ Platform: hyperv1.PlatformSpec{ @@ -1389,7 +1389,7 @@ func TestUseSharedIngressHC(t *testing.T) { want: true, }, { - name: "When Swift with Private topology it should return false", + name: "When Swift with Private topology, it should return false", hc: &hyperv1.HostedCluster{ Spec: hyperv1.HostedClusterSpec{ Platform: hyperv1.PlatformSpec{ @@ -1412,7 +1412,7 @@ func TestUseSharedIngressHC(t *testing.T) { want: false, }, { - name: "When Swift with empty topology it should return true", + name: "When Swift with empty topology, it should return true", hc: &hyperv1.HostedCluster{ Spec: hyperv1.HostedClusterSpec{ Platform: hyperv1.PlatformSpec{ @@ -1434,7 +1434,7 @@ func TestUseSharedIngressHC(t *testing.T) { want: true, }, { - name: "When ManagedIdentities without Swift and empty topology it should return true", + name: "When ManagedIdentities without Swift and empty topology, it should return true", hc: &hyperv1.HostedCluster{ Spec: hyperv1.HostedClusterSpec{ Platform: hyperv1.PlatformSpec{ @@ -1450,7 +1450,7 @@ func TestUseSharedIngressHC(t *testing.T) { want: true, }, { - name: "When non-Swift it should return false", + name: "When non-Swift, it should return false", hc: &hyperv1.HostedCluster{ Spec: hyperv1.HostedClusterSpec{ Platform: hyperv1.PlatformSpec{ @@ -1483,7 +1483,7 @@ func TestSwiftPodNetworkInstanceHCP(t *testing.T) { want string }{ { - name: "When Azure with Private.Type=Swift it should return PodNetworkInstance from API field", + name: "When Azure with Private.Type=Swift, it should return PodNetworkInstance from API field", hcp: &hyperv1.HostedControlPlane{ Spec: hyperv1.HostedControlPlaneSpec{ Platform: hyperv1.PlatformSpec{ @@ -1502,7 +1502,7 @@ func TestSwiftPodNetworkInstanceHCP(t *testing.T) { want: "test-pni", }, { - name: "When Azure with annotation fallback it should return value from annotation", + name: "When Azure with annotation fallback, it should return value from annotation", hcp: &hyperv1.HostedControlPlane{ ObjectMeta: metav1.ObjectMeta{ Annotations: map[string]string{ @@ -1519,7 +1519,7 @@ func TestSwiftPodNetworkInstanceHCP(t *testing.T) { want: "annotation-pni", }, { - name: "When Azure with neither API field nor annotation it should return empty string", + name: "When Azure with neither API field nor annotation, it should return empty string", hcp: &hyperv1.HostedControlPlane{ Spec: hyperv1.HostedControlPlaneSpec{ Platform: hyperv1.PlatformSpec{ @@ -1531,7 +1531,7 @@ func TestSwiftPodNetworkInstanceHCP(t *testing.T) { want: "", }, { - name: "When non-Azure platform it should return empty string", + name: "When non-Azure platform, it should return empty string", hcp: &hyperv1.HostedControlPlane{ Spec: hyperv1.HostedControlPlaneSpec{ Platform: hyperv1.PlatformSpec{ diff --git a/support/oadp/validate_test.go b/support/oadp/validate_test.go index 52c4fe51213d..186aa9793978 100644 --- a/support/oadp/validate_test.go +++ b/support/oadp/validate_test.go @@ -29,14 +29,14 @@ func TestValidateOADPComponents(t *testing.T) { errorMsg string }{ { - name: "OADP operator deployment not found", + name: "When OADP operator deployment does not exist, it should return an error", namespace: "openshift-adp", objects: []client.Object{}, expectError: true, errorMsg: "OADP operator deployment not found", }, { - name: "OADP operator deployment not ready", + name: "When OADP operator deployment is not ready, it should return an error", namespace: "openshift-adp", objects: []client.Object{ &appsv1.Deployment{ @@ -53,7 +53,7 @@ func TestValidateOADPComponents(t *testing.T) { errorMsg: "OADP operator deployment is not ready", }, { - name: "Velero deployment not found", + name: "When Velero deployment does not exist, it should return an error", namespace: "openshift-adp", objects: []client.Object{ &appsv1.Deployment{ @@ -70,7 +70,7 @@ func TestValidateOADPComponents(t *testing.T) { errorMsg: "velero deployment not found", }, { - name: "Velero deployment not ready", + name: "When Velero deployment is not ready, it should return an error", namespace: "openshift-adp", objects: []client.Object{ &appsv1.Deployment{ @@ -96,7 +96,7 @@ func TestValidateOADPComponents(t *testing.T) { errorMsg: "velero deployment is not ready", }, { - name: "All deployments ready", + name: "When all deployments are ready, it should succeed", namespace: "openshift-adp", objects: []client.Object{ &appsv1.Deployment{ @@ -158,14 +158,14 @@ func TestVerifyDPAStatus(t *testing.T) { errorMsg string }{ { - name: "No DPA resources found", + name: "When no DPA resources exist, it should return an error", namespace: "openshift-adp", objects: []client.Object{}, expectError: true, errorMsg: "no DataProtectionApplication resources found", }, { - name: "DPA with Reconciled=True condition", + name: "When DPA has Reconciled=True condition, it should succeed", namespace: "openshift-adp", objects: []client.Object{ createDPAWithCondition("test-dpa", "openshift-adp", "Reconciled", "True"), @@ -173,7 +173,7 @@ func TestVerifyDPAStatus(t *testing.T) { expectError: false, }, { - name: "DPA with Reconciled=False condition", + name: "When DPA has Reconciled=False condition, it should return an error", namespace: "openshift-adp", objects: []client.Object{ createDPAWithCondition("test-dpa", "openshift-adp", "Reconciled", "False"), @@ -182,7 +182,7 @@ func TestVerifyDPAStatus(t *testing.T) { errorMsg: "no ready DataProtectionApplication found", }, { - name: "DPA with different condition type", + name: "When DPA has a different condition type, it should return an error", namespace: "openshift-adp", objects: []client.Object{ createDPAWithCondition("test-dpa", "openshift-adp", "Available", "True"), @@ -191,7 +191,7 @@ func TestVerifyDPAStatus(t *testing.T) { errorMsg: "no ready DataProtectionApplication found", }, { - name: "Multiple DPAs, one ready", + name: "When multiple DPAs exist with one ready, it should succeed", namespace: "openshift-adp", objects: []client.Object{ createDPAWithCondition("test-dpa-1", "openshift-adp", "Reconciled", "False"), @@ -200,7 +200,7 @@ func TestVerifyDPAStatus(t *testing.T) { expectError: false, }, { - name: "DPA without status", + name: "When DPA has no status, it should return an error", namespace: "openshift-adp", objects: []client.Object{ createDPAWithoutStatus("test-dpa", "openshift-adp"), @@ -246,14 +246,14 @@ func TestCheckDPAHypershiftPlugin(t *testing.T) { errorMsg string }{ { - name: "No DPA resources found", + name: "When no DPA resources exist, it should return an error", namespace: "openshift-adp", objects: []client.Object{}, expectError: true, errorMsg: "no DataProtectionApplication resources found", }, { - name: "DPA with hypershift plugin", + name: "When DPA has hypershift plugin, it should succeed", namespace: "openshift-adp", objects: []client.Object{ createDPAWithPlugins("test-dpa", "openshift-adp", []string{"openshift", "aws", "hypershift"}), @@ -261,7 +261,7 @@ func TestCheckDPAHypershiftPlugin(t *testing.T) { expectError: false, }, { - name: "DPA without hypershift plugin", + name: "When DPA does not have hypershift plugin, it should return an error", namespace: "openshift-adp", objects: []client.Object{ createDPAWithPlugins("test-dpa", "openshift-adp", []string{"openshift", "aws"}), @@ -270,7 +270,7 @@ func TestCheckDPAHypershiftPlugin(t *testing.T) { errorMsg: "HyperShift plugin not found", }, { - name: "Multiple DPAs, one with hypershift plugin", + name: "When multiple DPAs exist with one having hypershift plugin, it should succeed", namespace: "openshift-adp", objects: []client.Object{ createDPAWithPlugins("test-dpa-1", "openshift-adp", []string{"openshift", "aws"}), @@ -319,7 +319,7 @@ func TestValidateAndGetHostedClusterPlatform(t *testing.T) { errorMsg string }{ { - name: "HostedCluster not found", + name: "When HostedCluster does not exist, it should return an error", hcName: "test-cluster", hcNamespace: "clusters", objects: []client.Object{}, @@ -327,7 +327,7 @@ func TestValidateAndGetHostedClusterPlatform(t *testing.T) { errorMsg: "not found", }, { - name: "AWS platform", + name: "When HostedCluster has AWS platform, it should return AWS", hcName: "test-cluster", hcNamespace: "clusters", objects: []client.Object{ @@ -337,7 +337,7 @@ func TestValidateAndGetHostedClusterPlatform(t *testing.T) { expectError: false, }, { - name: "Agent platform (lowercase)", + name: "When HostedCluster has Agent platform, it should return AGENT in uppercase", hcName: "test-cluster", hcNamespace: "clusters", objects: []client.Object{ @@ -347,7 +347,7 @@ func TestValidateAndGetHostedClusterPlatform(t *testing.T) { expectError: false, }, { - name: "KubeVirt platform", + name: "When HostedCluster has KubeVirt platform, it should return KUBEVIRT in uppercase", hcName: "test-cluster", hcNamespace: "clusters", objects: []client.Object{ @@ -357,7 +357,7 @@ func TestValidateAndGetHostedClusterPlatform(t *testing.T) { expectError: false, }, { - name: "HostedCluster without platform", + name: "When HostedCluster has no platform type, it should return an error", hcName: "test-cluster", hcNamespace: "clusters", objects: []client.Object{ diff --git a/support/openstackutil/conversion_test.go b/support/openstackutil/conversion_test.go index 9d0b9ba3e886..6170ac155921 100644 --- a/support/openstackutil/conversion_test.go +++ b/support/openstackutil/conversion_test.go @@ -16,15 +16,15 @@ func TestConvertHypershiftTagToCAPOTag(t *testing.T) { want []capo.NeutronTag }{ { - name: "empty tags", + name: "When tags are empty, it should return empty CAPO tags", }, { - name: "single tag", + name: "When a single tag is provided, it should convert to CAPO tag", tags: []hyperv1.NeutronTag{"tag1"}, want: []capo.NeutronTag{"tag1"}, }, { - name: "multiple tags", + name: "When multiple tags are provided, it should convert all to CAPO tags", tags: []hyperv1.NeutronTag{"tag1", "tag2"}, want: []capo.NeutronTag{"tag1", "tag2"}, }, @@ -49,7 +49,7 @@ func TestCreateCAPOFilterTags(t *testing.T) { want capo.FilterByNeutronTags }{ { - name: "empty tags", + name: "When all tag categories are empty, it should return empty filter", tags: []hyperv1.NeutronTag{}, tagsAny: []hyperv1.NeutronTag{}, NotTags: []hyperv1.NeutronTag{}, @@ -57,7 +57,7 @@ func TestCreateCAPOFilterTags(t *testing.T) { want: capo.FilterByNeutronTags{}, }, { - name: "single tag in each category", + name: "When each tag category has a single tag, it should convert all categories", tags: []hyperv1.NeutronTag{"tag1"}, tagsAny: []hyperv1.NeutronTag{"tag2"}, NotTags: []hyperv1.NeutronTag{"tag3"}, @@ -87,7 +87,7 @@ func TestCreateCAPONetworkFilter(t *testing.T) { want *capo.NetworkFilter }{ { - name: "filled filter", + name: "When filter has all fields populated, it should convert to CAPO network filter", filter: &hyperv1.NetworkFilter{ Name: "test-name", Description: "test-description", diff --git a/support/podspec/containers_test.go b/support/podspec/containers_test.go index 90d6163b1208..06748456ab53 100644 --- a/support/podspec/containers_test.go +++ b/support/podspec/containers_test.go @@ -132,12 +132,12 @@ func TestIsPodReady(t *testing.T) { expected bool }{ { - name: "When pod is nil it should return false", + name: "When pod is nil, it should return false", pod: nil, expected: false, }, { - name: "When pod has Ready=True it should return true", + name: "When pod has Ready=True, it should return true", pod: &corev1.Pod{ Status: corev1.PodStatus{ Conditions: []corev1.PodCondition{{ @@ -149,7 +149,7 @@ func TestIsPodReady(t *testing.T) { expected: true, }, { - name: "When pod has Ready=False it should return false", + name: "When pod has Ready=False, it should return false", pod: &corev1.Pod{ Status: corev1.PodStatus{ Conditions: []corev1.PodCondition{{ @@ -161,7 +161,7 @@ func TestIsPodReady(t *testing.T) { expected: false, }, { - name: "When pod has no Ready condition it should return false", + name: "When pod has no Ready condition, it should return false", pod: &corev1.Pod{ Status: corev1.PodStatus{ Conditions: []corev1.PodCondition{{ @@ -173,7 +173,7 @@ func TestIsPodReady(t *testing.T) { expected: false, }, { - name: "When pod has no conditions it should return false", + name: "When pod has no conditions, it should return false", pod: &corev1.Pod{ Status: corev1.PodStatus{}, }, @@ -284,7 +284,7 @@ func TestEnforceRestrictedSecurityContextToContainers(t *testing.T) { expected *corev1.PodSpec }{ { - name: "basic application with no exceptions", + name: "When container has no security context, it should apply restricted security context", podSpec: &corev1.PodSpec{ Containers: []corev1.Container{ { @@ -311,7 +311,7 @@ func TestEnforceRestrictedSecurityContextToContainers(t *testing.T) { }, }, { - name: "preserves capabilities from deployment template", + name: "When container has NET_BIND_SERVICE capability, it should preserve it while applying restricted context", podSpec: &corev1.PodSpec{ Containers: []corev1.Container{ { @@ -358,7 +358,7 @@ func TestEnforceRestrictedSecurityContextToContainers(t *testing.T) { }, }, { - name: "application with init containers", + name: "When pod has init containers, it should apply restricted security context to all containers", podSpec: &corev1.PodSpec{ InitContainers: []corev1.Container{ { @@ -404,7 +404,7 @@ func TestEnforceRestrictedSecurityContextToContainers(t *testing.T) { }, }, { - name: "preserves existing security context fields", + name: "When container has existing RunAsUser, it should preserve it while applying restricted context", podSpec: &corev1.PodSpec{ Containers: []corev1.Container{ { @@ -435,7 +435,7 @@ func TestEnforceRestrictedSecurityContextToContainers(t *testing.T) { }, }, { - name: "preserves different capabilities for multiple containers", + name: "When multiple containers have different capabilities, it should preserve each container's capabilities", podSpec: &corev1.PodSpec{ Containers: []corev1.Container{ { @@ -503,7 +503,7 @@ func TestEnforceRestrictedSecurityContextToContainers(t *testing.T) { }, }, { - name: "overrides insecure AllowPrivilegeEscalation", + name: "When AllowPrivilegeEscalation is true, it should override to false", podSpec: &corev1.PodSpec{ Containers: []corev1.Container{ { @@ -535,7 +535,7 @@ func TestEnforceRestrictedSecurityContextToContainers(t *testing.T) { }, }, { - name: "overrides insecure RunAsNonRoot", + name: "When RunAsNonRoot is false, it should override to true", podSpec: &corev1.PodSpec{ Containers: []corev1.Container{ { @@ -567,7 +567,7 @@ func TestEnforceRestrictedSecurityContextToContainers(t *testing.T) { }, }, { - name: "preserves existing add capabilities", + name: "When container has existing add capabilities and drop capabilities, it should preserve add and override drop to ALL", podSpec: &corev1.PodSpec{ Containers: []corev1.Container{ { @@ -601,7 +601,7 @@ func TestEnforceRestrictedSecurityContextToContainers(t *testing.T) { }, }, { - name: "empty pod spec", + name: "When pod spec has no containers, it should make no changes", podSpec: &corev1.PodSpec{ Containers: []corev1.Container{}, }, @@ -611,7 +611,7 @@ func TestEnforceRestrictedSecurityContextToContainers(t *testing.T) { }, }, { - name: "containers with explicitly nil security context", + name: "When container has nil security context, it should apply restricted security context", podSpec: &corev1.PodSpec{ Containers: []corev1.Container{ { @@ -660,7 +660,7 @@ func TestEnforceRestrictedSecurityContextToContainers_InvalidCapabilities(t *tes expectedError string }{ { - name: "rejects SYS_ADMIN capability", + name: "When container has SYS_ADMIN capability, it should return an error", podSpec: &corev1.PodSpec{ Containers: []corev1.Container{ { @@ -677,7 +677,7 @@ func TestEnforceRestrictedSecurityContextToContainers_InvalidCapabilities(t *tes expectedError: `container "bad-container": capability "SYS_ADMIN" is not allowed by restricted pod security standards (only NET_BIND_SERVICE is permitted)`, }, { - name: "rejects NET_ADMIN capability", + name: "When container has NET_ADMIN capability, it should return an error", podSpec: &corev1.PodSpec{ Containers: []corev1.Container{ { @@ -694,7 +694,7 @@ func TestEnforceRestrictedSecurityContextToContainers_InvalidCapabilities(t *tes expectedError: `container "network-container": capability "NET_ADMIN" is not allowed by restricted pod security standards (only NET_BIND_SERVICE is permitted)`, }, { - name: "rejects invalid capability in init container", + name: "When init container has SYS_MODULE capability, it should return an error", podSpec: &corev1.PodSpec{ InitContainers: []corev1.Container{ { @@ -711,7 +711,7 @@ func TestEnforceRestrictedSecurityContextToContainers_InvalidCapabilities(t *tes expectedError: `container "bad-init-container": capability "SYS_MODULE" is not allowed by restricted pod security standards (only NET_BIND_SERVICE is permitted)`, }, { - name: "rejects multiple invalid capabilities", + name: "When container has multiple capabilities including invalid ones, it should return an error", podSpec: &corev1.PodSpec{ Containers: []corev1.Container{ { diff --git a/support/proxy/proxy_test.go b/support/proxy/proxy_test.go index bcd9c6fe0ce1..def2f7613a4d 100644 --- a/support/proxy/proxy_test.go +++ b/support/proxy/proxy_test.go @@ -19,10 +19,10 @@ func TestSetEnvVars(t *testing.T) { expected []corev1.EnvVar }{ { - name: "No proxy configured and no proxy in env vars, no change", + name: "When no proxy is configured and no proxy env vars exist, it should make no changes", }, { - name: "No proxy configured, proxy gets removed from env vars", + name: "When no proxy is configured but proxy env vars exist, it should remove proxy env vars", currentEnvVars: []corev1.EnvVar{ {Name: "HTTP_PROXY", Value: "http://foo"}, {Name: "HTTPS_PROXY", Value: "http://foo"}, @@ -30,7 +30,7 @@ func TestSetEnvVars(t *testing.T) { }, }, { - name: "Proxy configured and gets added to env vars", + name: "When proxy is configured and no env vars exist, it should add proxy env vars", httpProxy: "http://foo", httpsProxy: "http://foo", noProxy: "kube-apiserver", expected: []corev1.EnvVar{ {Name: "HTTP_PROXY", Value: "http://foo"}, @@ -39,7 +39,7 @@ func TestSetEnvVars(t *testing.T) { }, }, { - name: "Proxy configured, env vars get changed", + name: "When proxy is configured and env vars have different values, it should update env vars", httpProxy: "http://foo", httpsProxy: "http://foo", noProxy: "kube-apiserver", currentEnvVars: []corev1.EnvVar{ {Name: "HTTP_PROXY", Value: "nope"}, @@ -53,7 +53,7 @@ func TestSetEnvVars(t *testing.T) { }, }, { - name: "kube-apiserver always gets included into NO_PROXY", + name: "When proxy is configured without NO_PROXY, it should include kube-apiserver in NO_PROXY", httpProxy: "http://foo", httpsProxy: "http://foo", expected: []corev1.EnvVar{ {Name: "HTTP_PROXY", Value: "http://foo"}, @@ -62,7 +62,7 @@ func TestSetEnvVars(t *testing.T) { }, }, { - name: "Additional no proxy is respected", + name: "When proxy is configured with additional no proxy entries, it should include them in NO_PROXY", httpProxy: "http://foo", httpsProxy: "http://foo", additionalNoProxy: []string{"dont-proxy-me"}, expected: []corev1.EnvVar{ @@ -72,7 +72,7 @@ func TestSetEnvVars(t *testing.T) { }, }, { - name: "Additional no proxy does nothing if no proxy is configured", + name: "When no proxy is configured, it should ignore additional no proxy entries", additionalNoProxy: []string{"dont-proxy-me"}, }, } diff --git a/support/releaseinfo/deserialize_test.go b/support/releaseinfo/deserialize_test.go index 7a127a1c137e..21c6c0db386f 100644 --- a/support/releaseinfo/deserialize_test.go +++ b/support/releaseinfo/deserialize_test.go @@ -58,37 +58,37 @@ func TestDeserializeImageMetadata(t *testing.T) { expectOSStream: true, }, { - name: "When ConfigMap is missing both stream and streams keys it should return an error", + name: "When ConfigMap is missing both stream and streams keys, it should return an error", data: testConfigMap(map[string]string{"releaseVersion": `"5.0.0"`}), expectError: true, }, { - name: "When stream JSON is invalid it should return an error", + name: "When stream JSON is invalid, it should return an error", data: testConfigMap(map[string]string{"stream": `"not valid json {"`}), expectError: true, }, { - name: "When streams JSON is invalid it should return an error", + name: "When streams JSON is invalid, it should return an error", data: testConfigMap(map[string]string{"streams": `"not valid json {"`}), expectError: true, }, { - name: "When input is empty it should return an error", + name: "When input is empty, it should return an error", data: []byte{}, expectError: true, }, { - name: "When input is not valid YAML it should return an error", + name: "When input is not valid YAML, it should return an error", data: []byte(`{not yaml at all`), expectError: true, }, { - name: "When streams map is empty it should return an error", + name: "When streams map is empty, it should return an error", data: testConfigMap(map[string]string{"streams": `"{}"`}), expectError: true, }, { - name: "When streams is valid but stream JSON is invalid it should return an error", + name: "When streams is valid but stream JSON is invalid, it should return an error", data: testConfigMap(map[string]string{ "streams": `'{"rhel-9":{"stream":"rhcos-4.21","architectures":{"x86_64":{"artifacts":{},"images":{}}}}}'`, "stream": `"not valid json {"`, @@ -195,7 +195,7 @@ func TestDeserializeImageMetadataMultiStreamContent(t *testing.T) { }, }, { - name: "When looking up streams both rhel-9 and rhel-10 should have ppc64le architecture", + name: "When looking up streams, it should include ppc64le architecture in both rhel-9 and rhel-10", assert: func(g Gomega) { _, rhel9HasPPC := osStreams["rhel-9"].Architectures["ppc64le"] _, rhel10HasPPC := osStreams["rhel-10"].Architectures["ppc64le"] @@ -236,7 +236,7 @@ func TestDeserializeImageMetadataMultiStreamContent(t *testing.T) { }, }, { - name: "When looking up Azure marketplace data rhel-10 should have no no-purchase-plan entries", + name: "When looking up Azure marketplace data, it should have no no-purchase-plan entries in rhel-10", assert: func(g Gomega) { rhel9Ext := osStreams["rhel-9"].Architectures["x86_64"].RHELCoreOSExtensions rhel10Ext := osStreams["rhel-10"].Architectures["x86_64"].RHELCoreOSExtensions diff --git a/support/releaseinfo/registryclient/client_test.go b/support/releaseinfo/registryclient/client_test.go index 16ff451eb120..6944ac6c23c2 100644 --- a/support/releaseinfo/registryclient/client_test.go +++ b/support/releaseinfo/registryclient/client_test.go @@ -170,7 +170,7 @@ func TestFindMatchingManifest(t *testing.T) { expectedImageRef string }{ { - testName: "Find linux/amd64 in multi-arch ReleaseImage1", + testName: "When searching for linux/amd64 in multi-arch ReleaseImage1 it should return the correct manifest", releaseImage: ReleaseImage1, deserializedManifestList: deserializedManifestList1, osToFind: LinuxOS, @@ -178,7 +178,7 @@ func TestFindMatchingManifest(t *testing.T) { expectedImageRef: "quay.io/openshift-release-dev/ocp-release@sha256:70fb4524d21e1b6c08477eb5d1ca2cf282b3270b1d008f70dd7e1cf13d8ba4ce", }, { - testName: "Find linux/arm64 in multi-arch ReleaseImage1", + testName: "When searching for linux/arm64 in multi-arch ReleaseImage1 it should return the correct manifest", releaseImage: ReleaseImage1, deserializedManifestList: deserializedManifestList1, osToFind: LinuxOS, @@ -186,7 +186,7 @@ func TestFindMatchingManifest(t *testing.T) { expectedImageRef: "quay.io/openshift-release-dev/ocp-release@sha256:4fe15a54f144d0200a39a93e2dc97b8b0e989e95cc076acbe2dfe129d0c04831", }, { - testName: "Find linux/ppc64le in multi-arch ReleaseImage1", + testName: "When searching for linux/ppc64le in multi-arch ReleaseImage1 it should return the correct manifest", releaseImage: ReleaseImage1, deserializedManifestList: deserializedManifestList1, osToFind: LinuxOS, @@ -194,7 +194,7 @@ func TestFindMatchingManifest(t *testing.T) { expectedImageRef: "quay.io/openshift-release-dev/ocp-release@sha256:a46358bdcf31d39c23e7389e8b75d1e5efa7181cca8832e51697b6bb3470e4a5", }, { - testName: "Find linux/s390x in multi-arch ReleaseImage1", + testName: "When searching for linux/s390x in multi-arch ReleaseImage1 it should return the correct manifest", releaseImage: ReleaseImage1, deserializedManifestList: deserializedManifestList1, osToFind: LinuxOS, @@ -202,7 +202,7 @@ func TestFindMatchingManifest(t *testing.T) { expectedImageRef: "quay.io/openshift-release-dev/ocp-release@sha256:f8dcd1dadc68b85ccf8737067f73fc03b0f6a1d81633fbdcdde2e3b5bc804d6a", }, { - testName: "Find linux/amd64 in multi-arch ReleaseImage2", + testName: "When searching for linux/amd64 in multi-arch ReleaseImage2 it should return the correct manifest", releaseImage: ReleaseImage2, deserializedManifestList: deserializedManifestList2, osToFind: LinuxOS, @@ -210,7 +210,7 @@ func TestFindMatchingManifest(t *testing.T) { expectedImageRef: "quay.io/openshift-release-dev/ocp-release@sha256:b593c6882f9c8d9d75f3d200fa3e02f7f8caa99cea595fd70bbdd495613fd23f", }, { - testName: "Find linux/arm64 in multi-arch ReleaseImage2", + testName: "When searching for linux/arm64 in multi-arch ReleaseImage2 it should return the correct manifest", releaseImage: ReleaseImage2, deserializedManifestList: deserializedManifestList2, osToFind: LinuxOS, @@ -218,7 +218,7 @@ func TestFindMatchingManifest(t *testing.T) { expectedImageRef: "quay.io/openshift-release-dev/ocp-release@sha256:f1c97cf57c57757fcd6d4314ff4b4cc792b27b904e949b840f902c104f1acf38", }, { - testName: "Find linux/ppc64le in multi-arch ReleaseImage2", + testName: "When searching for linux/ppc64le in multi-arch ReleaseImage2 it should return the correct manifest", releaseImage: ReleaseImage2, deserializedManifestList: deserializedManifestList2, osToFind: LinuxOS, @@ -226,7 +226,7 @@ func TestFindMatchingManifest(t *testing.T) { expectedImageRef: "quay.io/openshift-release-dev/ocp-release@sha256:a0f3d715a8947e45bdc9c9d2c1fcdccf8da6b216cb6efc38d75cec49a56f074b", }, { - testName: "Find linux/s390x in multi-arch ReleaseImage2", + testName: "When searching for linux/s390x in multi-arch ReleaseImage2 it should return the correct manifest", releaseImage: ReleaseImage2, deserializedManifestList: deserializedManifestList2, osToFind: LinuxOS, @@ -258,7 +258,7 @@ func TestIsMultiArchManifestList(t *testing.T) { expectErr bool }{ { - name: "Check an amd64 image; no err", + name: "When checking an amd64 image, it should return false for multi-arch", image: "quay.io/openshift-release-dev/ocp-release:4.16.10-x86_64", mediaType: ManifestMediaType, pullSecretBytes: pullSecretBytes, @@ -278,7 +278,7 @@ func TestIsMultiArchManifestList(t *testing.T) { }, }, { - name: "Check a ppc64le image; no err", + name: "When checking a ppc64le image, it should return false for multi-arch", image: "quay.io/openshift-release-dev/ocp-release:4.16.11-ppc64le", mediaType: ManifestMediaType, pullSecretBytes: pullSecretBytes, @@ -298,7 +298,7 @@ func TestIsMultiArchManifestList(t *testing.T) { }, }, { - name: "Check a multi-arch image; no err", + name: "When checking a multi-arch image, it should return true", image: "quay.io/openshift-release-dev/ocp-release:4.16.11-multi", mediaType: ManifestListMediaType, pullSecretBytes: pullSecretBytes, @@ -328,7 +328,7 @@ func TestIsMultiArchManifestList(t *testing.T) { }, }, { - name: "Bad pull secret; err", + name: "When pull secret is empty, it should return an error", image: "quay.io/openshift-release-dev/ocp-release:4.16.11-ppc64le", mediaType: ManifestMediaType, pullSecretBytes: []byte(""), diff --git a/support/releaseinfo/releaseinfo_test.go b/support/releaseinfo/releaseinfo_test.go index a826add9fa1f..ed91c21e7e07 100644 --- a/support/releaseinfo/releaseinfo_test.go +++ b/support/releaseinfo/releaseinfo_test.go @@ -43,13 +43,13 @@ func TestParseComponentVersionsLabel(t *testing.T) { expectName: "My Component (v1.0): Beta", }, { - name: "When display name contains invalid characters it should return an error", + name: "When display name contains invalid characters, it should return an error", label: "mycomponent=1.0.0", displayNames: "mycomponent=Invalid ", expectError: true, }, { - name: "When version is not valid semver it should return an error", + name: "When version is not valid semver, it should return an error", label: "mycomponent=not-a-version", expectError: true, }, @@ -125,7 +125,7 @@ func TestReadComponentVersions(t *testing.T) { expectKey: "component", }, { - name: "When multiple non-machine-os versions exist it should return an error", + name: "When multiple non-machine-os versions exist, it should return an error", tags: []imageapi.TagReference{ { Name: "component-a", @@ -250,7 +250,7 @@ func TestStreamForName(t *testing.T) { expectStream: "rhcos-5.0", }, { - name: "When name does not match any stream it should return an error listing available streams", + name: "When name does not match any stream, it should return an error listing available streams", releaseImage: &ReleaseImage{ ImageStream: &imageapi.ImageStream{}, StreamMetadata: &stream.Stream{ @@ -279,7 +279,7 @@ func TestStreamForName(t *testing.T) { expectStream: "rhcos-4.10", }, { - name: "When StreamMetadata is nil and name is empty it should return an error", + name: "When StreamMetadata is nil and name is empty, it should return an error", releaseImage: &ReleaseImage{ ImageStream: &imageapi.ImageStream{}, }, @@ -287,7 +287,7 @@ func TestStreamForName(t *testing.T) { expectError: true, }, { - name: "When StreamMetadata is nil and OSStreams has entries it should return an error for empty name", + name: "When StreamMetadata is nil and OSStreams has entries, it should return an error for empty name", releaseImage: &ReleaseImage{ ImageStream: &imageapi.ImageStream{}, OSStreams: map[string]*stream.Stream{ @@ -309,7 +309,7 @@ func TestStreamForName(t *testing.T) { expectStream: "rhcos-4.21", }, { - name: "When StreamMetadata is nil and OSStreams has no matching entry it should return an error", + name: "When StreamMetadata is nil and OSStreams has no matching entry, it should return an error", releaseImage: &ReleaseImage{ ImageStream: &imageapi.ImageStream{}, OSStreams: map[string]*stream.Stream{ @@ -321,7 +321,7 @@ func TestStreamForName(t *testing.T) { expectContains: "rhel-10", }, { - name: "When both StreamMetadata and OSStreams are nil it should return an error for non-empty name", + name: "When both StreamMetadata and OSStreams are nil, it should return an error for non-empty name", releaseImage: &ReleaseImage{ ImageStream: &imageapi.ImageStream{}, }, @@ -329,7 +329,7 @@ func TestStreamForName(t *testing.T) { expectError: true, }, { - name: "When OSStreams is an empty map it should return an error", + name: "When OSStreams is an empty map, it should return an error", releaseImage: &ReleaseImage{ ImageStream: &imageapi.ImageStream{}, StreamMetadata: &stream.Stream{ @@ -341,7 +341,7 @@ func TestStreamForName(t *testing.T) { expectError: true, }, { - name: "When OSStreams entry has nil value it should return an error listing available streams", + name: "When OSStreams entry has nil value, it should return an error listing available streams", releaseImage: &ReleaseImage{ ImageStream: &imageapi.ImageStream{}, StreamMetadata: &stream.Stream{ diff --git a/support/secretencryption/encryptionconfig_test.go b/support/secretencryption/encryptionconfig_test.go index 60a79169c317..28b21ef7eed6 100644 --- a/support/secretencryption/encryptionconfig_test.go +++ b/support/secretencryption/encryptionconfig_test.go @@ -220,84 +220,84 @@ func TestFindKeyRole(t *testing.T) { expected TargetKeyRole }{ { - name: "When config is nil it should return TargetKeyAbsent", + name: "When config is nil, it should return TargetKeyAbsent", cfg: nil, targetName: "target", encType: hyperv1.KMS, expected: TargetKeyAbsent, }, { - name: "When config has no resources it should return TargetKeyAbsent", + name: "When config has no resources, it should return TargetKeyAbsent", cfg: &apiserverv1.EncryptionConfiguration{}, targetName: "target", encType: hyperv1.KMS, expected: TargetKeyAbsent, }, { - name: "When KMS target key is the first provider it should return TargetKeyWrite", + name: "When KMS target key is the first provider, it should return TargetKeyWrite", cfg: kmsConfig(kmsProvider("target-key"), kmsProvider("old-key"), identityProvider()), targetName: "target-key", encType: hyperv1.KMS, expected: TargetKeyWrite, }, { - name: "When KMS target key is the second provider it should return TargetKeyReadOnly", + name: "When KMS target key is the second provider, it should return TargetKeyReadOnly", cfg: kmsConfig(kmsProvider("old-key"), kmsProvider("target-key"), identityProvider()), targetName: "target-key", encType: hyperv1.KMS, expected: TargetKeyReadOnly, }, { - name: "When KMS target key is not in config it should return TargetKeyAbsent", + name: "When KMS target key is not in config, it should return TargetKeyAbsent", cfg: kmsConfig(kmsProvider("old-key"), identityProvider()), targetName: "target-key", encType: hyperv1.KMS, expected: TargetKeyAbsent, }, { - name: "When KMS target key is the only provider it should return TargetKeyWrite", + name: "When KMS target key is the only provider, it should return TargetKeyWrite", cfg: kmsConfig(kmsProvider("target-key"), identityProvider()), targetName: "target-key", encType: hyperv1.KMS, expected: TargetKeyWrite, }, { - name: "When KMS has identity before KMS providers it should still find write correctly", + name: "When KMS has identity before KMS providers, it should still find write correctly", cfg: kmsConfig(identityProvider(), kmsProvider("target-key"), kmsProvider("old-key")), targetName: "target-key", encType: hyperv1.KMS, expected: TargetKeyWrite, }, { - name: "When AESCBC target key is the first key it should return TargetKeyWrite", + name: "When AESCBC target key is the first key, it should return TargetKeyWrite", cfg: kmsConfig(aescbcProvider(aescbcKey("target-key"), aescbcKey("old-key")), identityProvider()), targetName: "target-key", encType: hyperv1.AESCBC, expected: TargetKeyWrite, }, { - name: "When AESCBC target key is the second key it should return TargetKeyReadOnly", + name: "When AESCBC target key is the second key, it should return TargetKeyReadOnly", cfg: kmsConfig(aescbcProvider(aescbcKey("old-key"), aescbcKey("target-key")), identityProvider()), targetName: "target-key", encType: hyperv1.AESCBC, expected: TargetKeyReadOnly, }, { - name: "When AESCBC target key is not present it should return TargetKeyAbsent", + name: "When AESCBC target key is not present, it should return TargetKeyAbsent", cfg: kmsConfig(aescbcProvider(aescbcKey("old-key")), identityProvider()), targetName: "target-key", encType: hyperv1.AESCBC, expected: TargetKeyAbsent, }, { - name: "When AESCBC target key is the only key it should return TargetKeyWrite", + name: "When AESCBC target key is the only key, it should return TargetKeyWrite", cfg: kmsConfig(aescbcProvider(aescbcKey("target-key")), identityProvider()), targetName: "target-key", encType: hyperv1.AESCBC, expected: TargetKeyWrite, }, { - name: "When encryption type is unrecognized it should return TargetKeyAbsent", + name: "When encryption type is unrecognized, it should return TargetKeyAbsent", cfg: kmsConfig(kmsProvider("target-key")), targetName: "target-key", encType: hyperv1.SecretEncryptionType("unknown"), @@ -326,7 +326,7 @@ func TestShouldPromoteTargetKey(t *testing.T) { expected bool }{ { - name: "When target key is absent it should not promote", + name: "When target key is absent, it should not promote", cfg: kmsConfig(kmsProvider("old-key"), identityProvider()), targetName: "target-key", encType: hyperv1.KMS, @@ -334,7 +334,7 @@ func TestShouldPromoteTargetKey(t *testing.T) { expected: false, }, { - name: "When target key is already write it should promote regardless of convergence", + name: "When target key is already write, it should promote regardless of convergence", cfg: kmsConfig(kmsProvider("target-key"), kmsProvider("old-key"), identityProvider()), targetName: "target-key", encType: hyperv1.KMS, @@ -342,7 +342,7 @@ func TestShouldPromoteTargetKey(t *testing.T) { expected: true, }, { - name: "When target key is read-only and KAS is converged it should promote", + name: "When target key is read-only and KAS is converged, it should promote", cfg: kmsConfig(kmsProvider("old-key"), kmsProvider("target-key"), identityProvider()), targetName: "target-key", encType: hyperv1.KMS, @@ -350,7 +350,7 @@ func TestShouldPromoteTargetKey(t *testing.T) { expected: true, }, { - name: "When target key is read-only and KAS is not converged it should not promote", + name: "When target key is read-only and KAS is not converged, it should not promote", cfg: kmsConfig(kmsProvider("old-key"), kmsProvider("target-key"), identityProvider()), targetName: "target-key", encType: hyperv1.KMS, @@ -358,7 +358,7 @@ func TestShouldPromoteTargetKey(t *testing.T) { expected: false, }, { - name: "When config is nil it should not promote", + name: "When config is nil, it should not promote", cfg: nil, targetName: "target-key", encType: hyperv1.KMS, @@ -366,7 +366,7 @@ func TestShouldPromoteTargetKey(t *testing.T) { expected: false, }, { - name: "When AESCBC target key is write it should promote", + name: "When AESCBC target key is write, it should promote", cfg: kmsConfig(aescbcProvider(aescbcKey("target-key"), aescbcKey("old-key")), identityProvider()), targetName: "target-key", encType: hyperv1.AESCBC, @@ -374,7 +374,7 @@ func TestShouldPromoteTargetKey(t *testing.T) { expected: true, }, { - name: "When AESCBC target key is read-only and KAS converged it should promote", + name: "When AESCBC target key is read-only and KAS converged, it should promote", cfg: kmsConfig(aescbcProvider(aescbcKey("old-key"), aescbcKey("target-key")), identityProvider()), targetName: "target-key", encType: hyperv1.AESCBC, @@ -382,7 +382,7 @@ func TestShouldPromoteTargetKey(t *testing.T) { expected: true, }, { - name: "When AESCBC target key is read-only and KAS not converged it should not promote", + name: "When AESCBC target key is read-only and KAS not converged, it should not promote", cfg: kmsConfig(aescbcProvider(aescbcKey("old-key"), aescbcKey("target-key")), identityProvider()), targetName: "target-key", encType: hyperv1.AESCBC, diff --git a/support/secretproviderclass/secretproviderclass_test.go b/support/secretproviderclass/secretproviderclass_test.go index b35dd82ac0f4..b63182af4649 100644 --- a/support/secretproviderclass/secretproviderclass_test.go +++ b/support/secretproviderclass/secretproviderclass_test.go @@ -19,7 +19,7 @@ func TestFormatSecretProviderClassObject(t *testing.T) { expected string }{ { - name: "default", + name: "When objectEncoding is base64, it should format correctly", certName: "cert", objectEncoding: "base64", expected: ` @@ -31,7 +31,7 @@ array: `, }, { - name: "default", + name: "When objectEncoding is utf-8, it should format correctly", certName: "cert", objectEncoding: "utf-8", expected: ` @@ -86,7 +86,7 @@ func TestReconcileManagedAzureSecretProviderClass(t *testing.T) { expected *secretsstorev1.SecretProviderClass }{ { - name: "expect the objects field to contain the CredentialsSecretName value", + name: "When reconciling, it should populate objects field with CredentialsSecretName", secretProviderClass: &secretsstorev1.SecretProviderClass{ Spec: secretsstorev1.SecretProviderClassSpec{ Provider: "azure", diff --git a/support/supportedversion/version_test.go b/support/supportedversion/version_test.go index 920c162c06f7..919851d6d5e1 100644 --- a/support/supportedversion/version_test.go +++ b/support/supportedversion/version_test.go @@ -77,7 +77,7 @@ func TestGetKubeVersionForSupportedVersion(t *testing.T) { expectedKubeVer: "1.37.0", }, { - name: "When an unmapped OCP version is provided it should return an error", + name: "When an unmapped OCP version is provided, it should return an error", ocpVersion: "4.99.0", expectErr: true, }, @@ -115,7 +115,7 @@ func TestIsValidReleaseVersion(t *testing.T) { platform hyperv1.PlatformType }{ { - name: "Releases before 4.14 are not supported", + name: "When release is before 4.14, it should not be supported", currentVersion: v("4.8.0"), nextVersion: v("4.7.0"), latestVersionSupported: v("4.12.0"), @@ -124,7 +124,7 @@ func TestIsValidReleaseVersion(t *testing.T) { platform: hyperv1.NonePlatform, }, { - name: "versions > LatestSupportedVersion are not supported", + name: "When version is greater than LatestSupportedVersion, it should not be supported", currentVersion: v("4.15.0"), nextVersion: &semver.Version{ Major: LatestSupportedVersion.Major, @@ -137,7 +137,7 @@ func TestIsValidReleaseVersion(t *testing.T) { platform: hyperv1.NonePlatform, }, { - name: "y-stream downgrade is not supported", + name: "When doing y-stream downgrade, it should not be supported", currentVersion: v("4.10.0"), nextVersion: v("4.9.0"), latestVersionSupported: v("4.12.0"), @@ -146,7 +146,7 @@ func TestIsValidReleaseVersion(t *testing.T) { platform: hyperv1.NonePlatform, }, { - name: "y-stream upgrade is not for OpenShiftSDN", + name: "When doing y-stream upgrade with OpenShiftSDN, it should not be supported", currentVersion: v("4.10.0"), nextVersion: v("4.11.0"), latestVersionSupported: v("4.12.0"), @@ -156,7 +156,7 @@ func TestIsValidReleaseVersion(t *testing.T) { platform: hyperv1.NonePlatform, }, { - name: "the latest HostedCluster version supported by this Operator is 4.12.0", + name: "When version exceeds latest supported by operator, it should return error", currentVersion: v("4.12.0"), nextVersion: v("4.14.0"), latestVersionSupported: v("4.12.0"), @@ -165,7 +165,7 @@ func TestIsValidReleaseVersion(t *testing.T) { platform: hyperv1.NonePlatform, }, { - name: "the minimum HostedCluster version supported by this Operator is 4.10.0", + name: "When version is below minimum supported by operator, it should return error", currentVersion: v("4.9.0"), nextVersion: v("4.9.0"), latestVersionSupported: v("4.12.0"), @@ -175,7 +175,7 @@ func TestIsValidReleaseVersion(t *testing.T) { platform: hyperv1.NonePlatform, }, { - name: "Valid", + name: "When version is valid, it should succeed", currentVersion: v("4.11.0"), nextVersion: v("4.11.1"), latestVersionSupported: v("4.12.0"), @@ -184,7 +184,7 @@ func TestIsValidReleaseVersion(t *testing.T) { platform: hyperv1.NonePlatform, }, { - name: "When going to minimum should be valid", + name: "When going to minimum version, it should be valid", currentVersion: v("4.9.0"), nextVersion: v("4.10.0"), latestVersionSupported: v("4.12.0"), @@ -193,7 +193,7 @@ func TestIsValidReleaseVersion(t *testing.T) { platform: hyperv1.NonePlatform, }, { - name: "Valid when going to minimum with a dev tag", + name: "When going to minimum with a dev tag, it should be valid", currentVersion: v("4.9.0"), nextVersion: v("4.10.0-nightly-something"), latestVersionSupported: v("4.12.0"), @@ -202,7 +202,7 @@ func TestIsValidReleaseVersion(t *testing.T) { platform: hyperv1.NonePlatform, }, { - name: "Invalid when installing with OpenShiftSDN and version > 4.10", + name: "When installing with OpenShiftSDN and version > 4.10, it should be invalid", currentVersion: nil, nextVersion: v("4.11.5"), latestVersionSupported: v("4.12.0"), @@ -212,7 +212,7 @@ func TestIsValidReleaseVersion(t *testing.T) { platform: hyperv1.NonePlatform, }, { - name: "Valid when installing with OpenShift SDN and version <= 4.10", + name: "When installing with OpenShift SDN and version <= 4.10, it should be valid", currentVersion: nil, nextVersion: v("4.10.3"), latestVersionSupported: v("4.12.0"), @@ -222,7 +222,7 @@ func TestIsValidReleaseVersion(t *testing.T) { platform: hyperv1.NonePlatform, }, { - name: "Invalid when installing with OVNKubernetes and version < 4.11", + name: "When installing with OVNKubernetes and version < 4.11, it should be invalid", currentVersion: nil, nextVersion: v("4.10.5"), latestVersionSupported: v("4.12.0"), @@ -232,7 +232,7 @@ func TestIsValidReleaseVersion(t *testing.T) { platform: hyperv1.NonePlatform, }, { - name: "Valid when installing with OVNKubernetes and version >= 4.11", + name: "When installing with OVNKubernetes and version >= 4.11, it should be valid", currentVersion: nil, nextVersion: v("4.11.1"), latestVersionSupported: v("4.12.0"), @@ -242,7 +242,7 @@ func TestIsValidReleaseVersion(t *testing.T) { platform: hyperv1.NonePlatform, }, { - name: "Valid when installing with OpenShift SDN and version >= 4.11 with PowerVS platform", + name: "When installing with OpenShift SDN and version >= 4.11 with PowerVS platform, it should be valid", currentVersion: nil, nextVersion: v("4.11.0"), latestVersionSupported: v("4.12.0"), @@ -404,7 +404,7 @@ func TestGetSupportedOCPVersions(t *testing.T) { expectedServerVersion string }{ { - name: "When the ConfigMap is valid, expect versions to be returned successfully", + name: "When the ConfigMap is valid, it should return versions successfully", cm: &corev1.ConfigMap{ ObjectMeta: baseCM.ObjectMeta, Data: map[string]string{ @@ -417,13 +417,13 @@ func TestGetSupportedOCPVersions(t *testing.T) { expectedServerVersion: "test-server-version", }, { - name: "When the ConfigMap is not found, expect an error", + name: "When the ConfigMap is not found, it should return an error", cm: nil, // No configmap will be added to the client expectErr: true, expectedErrMsg: "failed to find supported versions on the server", }, { - name: "When the server-version key is missing, expect an error", + name: "When the server-version key is missing, it should return an error", cm: &corev1.ConfigMap{ ObjectMeta: baseCM.ObjectMeta, Data: map[string]string{config.ConfigMapVersionsKey: string(validVersionsJSON)}, @@ -432,7 +432,7 @@ func TestGetSupportedOCPVersions(t *testing.T) { expectedErrMsg: "the server did not advertise its HyperShift version", }, { - name: "When the supported-versions key is missing, expect an error", + name: "When the supported-versions key is missing, it should return an error", cm: &corev1.ConfigMap{ ObjectMeta: baseCM.ObjectMeta, Data: map[string]string{config.ConfigMapServerVersionKey: "test-server-version"}, @@ -441,7 +441,7 @@ func TestGetSupportedOCPVersions(t *testing.T) { expectedErrMsg: "the server did not advertise supported OCP versions", }, { - name: "When the supported-versions JSON is malformed, expect an error", + name: "When the supported-versions JSON is malformed, it should return an error", cm: &corev1.ConfigMap{ ObjectMeta: baseCM.ObjectMeta, Data: map[string]string{ @@ -607,14 +607,14 @@ func TestPreviousMinorVersion(t *testing.T) { errSubstr string }{ { - name: "When subtracting within 4.x, it should return the correct 4.x version", + name: "When subtracting within 4.x it should return the correct 4.x version", version: semver.MustParse("4.20.0"), n: 2, expectedMajor: 4, expectedMinor: 18, }, { - name: "When crossing the 5.x to 4.x bridge, it should denormalize correctly", + name: "When crossing the 5.x to 4.x bridge it should denormalize correctly", version: semver.MustParse("5.0.0"), n: 2, expectedMajor: 4, @@ -628,14 +628,14 @@ func TestPreviousMinorVersion(t *testing.T) { expectedMinor: 22, }, { - name: "When staying within 5.x, it should return the correct 5.x version", + name: "When staying within 5.x it should return the correct 5.x version", version: semver.MustParse("5.2.0"), n: 1, expectedMajor: 5, expectedMinor: 1, }, { - name: "When n is 0, it should return the same version", + name: "When n is 0 it should return the same version", version: semver.MustParse("4.18.0"), n: 0, expectedMajor: 4, @@ -917,7 +917,7 @@ func TestRetrieveSupportedOCPVersion(t *testing.T) { expectedOCPVersion ocpVersion }{ { - name: "When latest stable release is supported, expect it to be returned", + name: "When latest stable release is supported, it should be returned", cm: supportedVersionsCM, releaseURL: mockServer.URL + "/api/v1/releasestream/4-stable-multi/tags", expectErr: false, @@ -927,28 +927,28 @@ func TestRetrieveSupportedOCPVersion(t *testing.T) { }, }, { - name: "When no supported release versions match, expect an error", + name: "When no supported release versions match, it should return an error", cm: unsupportedVersionsCM, releaseURL: mockServer.URL + "/api/v1/releasestream/4-stable-multi/tags", expectErr: true, expectedErrMsg: "failed to find the latest supported OCP version", }, { - name: "When the ConfigMap is missing, expect an error", + name: "When the ConfigMap is missing, it should return an error", cm: nil, releaseURL: mockServer.URL + "/api/v1/releasestream/4-stable-multi/tags", expectErr: true, expectedErrMsg: "failed to get supported OCP versions", }, { - name: "When the release URL is invalid, expect a request creation error", + name: "When the release URL is invalid, it should return a request creation error", cm: supportedVersionsCM, releaseURL: "://invalid-url", expectErr: true, expectedErrMsg: "parse", }, { - name: "When the ConfigMap supports older versions, expect the latest older version to be returned", + name: "When the ConfigMap supports older versions, it should return the latest older version", cm: olderSupportedVersionsCM, releaseURL: mockServer.URL + "/api/v1/releasestream/4-stable-multi/tags", expectErr: false, @@ -1226,7 +1226,7 @@ func TestRetrieveSupportedOCPVersionWithRCFiltering(t *testing.T) { expectedOCPVersion ocpVersion }{ { - name: "When multi-arch stream has RC versions, expect latest non-RC supported version", + name: "When multi-arch stream has RC versions, it should return latest non-RC supported version", cm: supportedVersionsCM, releaseURL: mockServerWithRC.URL, expectErr: false, @@ -1236,7 +1236,7 @@ func TestRetrieveSupportedOCPVersionWithRCFiltering(t *testing.T) { }, }, { - name: "When amd64 stream has RC versions, expect latest non-RC supported version", + name: "When amd64 stream has RC versions, it should return latest non-RC supported version", cm: supportedVersionsCM, releaseURL: mockServerAmd64WithRC.URL, expectErr: false, @@ -1246,7 +1246,7 @@ func TestRetrieveSupportedOCPVersionWithRCFiltering(t *testing.T) { }, }, { - name: "When arm64 stream has RC versions, expect latest non-RC supported version", + name: "When arm64 stream has RC versions, it should return latest non-RC supported version", cm: supportedVersionsCM, releaseURL: mockServerArm64WithRC.URL, expectErr: false, @@ -1256,7 +1256,7 @@ func TestRetrieveSupportedOCPVersionWithRCFiltering(t *testing.T) { }, }, { - name: "When stream has only RC versions, expect error", + name: "When stream has only RC versions, it should return error", cm: supportedVersionsCM, releaseURL: mockServerOnlyRC.URL, expectErr: true, @@ -1314,7 +1314,7 @@ func TestFindLatestSupportedVersionWithSorting(t *testing.T) { expectedErrMsg string }{ { - name: "When tags are in random order with oldest first, expect NEWEST supported version", + name: "When tags are in random order with oldest first it should return NEWEST supported version", tags: `[ {"name": "4.14.21", "pullSpec": "quay.io/openshift-release-dev/ocp-release:4.14.21-multi", "downloadURL": "https://example.com/4.14.21"}, {"name": "4.19.5", "pullSpec": "quay.io/openshift-release-dev/ocp-release:4.19.5-multi", "downloadURL": "https://example.com/4.19.5"}, @@ -1325,7 +1325,7 @@ func TestFindLatestSupportedVersionWithSorting(t *testing.T) { expectedPullSpec: "quay.io/openshift-release-dev/ocp-release:4.19.5-multi", }, { - name: "When tags include RC versions, expect latest non-RC supported version", + name: "When tags include RC versions it should return latest non-RC supported version", tags: `[ {"name": "4.20.0-rc.5", "pullSpec": "quay.io/openshift-release-dev/ocp-release:4.20.0-rc.5-multi", "downloadURL": "https://example.com/4.20.0-rc.5"}, {"name": "4.19.5", "pullSpec": "quay.io/openshift-release-dev/ocp-release:4.19.5-multi", "downloadURL": "https://example.com/4.19.5"}, @@ -1336,7 +1336,7 @@ func TestFindLatestSupportedVersionWithSorting(t *testing.T) { expectedPullSpec: "quay.io/openshift-release-dev/ocp-release:4.19.5-multi", }, { - name: "When tags are in ascending order, expect NEWEST supported version", + name: "When tags are in ascending order it should return NEWEST supported version", tags: `[ {"name": "4.14.21", "pullSpec": "quay.io/openshift-release-dev/ocp-release:4.14.21-multi", "downloadURL": "https://example.com/4.14.21"}, {"name": "4.15.10", "pullSpec": "quay.io/openshift-release-dev/ocp-release:4.15.10-multi", "downloadURL": "https://example.com/4.15.10"}, @@ -1349,7 +1349,7 @@ func TestFindLatestSupportedVersionWithSorting(t *testing.T) { expectedPullSpec: "quay.io/openshift-release-dev/ocp-release:4.19.1-multi", }, { - name: "When tags are in descending order, expect NEWEST supported version", + name: "When tags are in descending order it should return NEWEST supported version", tags: `[ {"name": "4.19.1", "pullSpec": "quay.io/openshift-release-dev/ocp-release:4.19.1-multi", "downloadURL": "https://example.com/4.19.1"}, {"name": "4.18.2", "pullSpec": "quay.io/openshift-release-dev/ocp-release:4.18.2-multi", "downloadURL": "https://example.com/4.18.2"}, @@ -1360,7 +1360,7 @@ func TestFindLatestSupportedVersionWithSorting(t *testing.T) { expectedPullSpec: "quay.io/openshift-release-dev/ocp-release:4.19.1-multi", }, { - name: "When all versions are RC, expect error", + name: "When all versions are RC, it should return error", tags: `[ {"name": "4.20.0-rc.5", "pullSpec": "quay.io/openshift-release-dev/ocp-release:4.20.0-rc.5-multi", "downloadURL": "https://example.com/4.20.0-rc.5"}, {"name": "4.20.0-rc.4", "pullSpec": "quay.io/openshift-release-dev/ocp-release:4.20.0-rc.4-multi", "downloadURL": "https://example.com/4.20.0-rc.4"}, @@ -1370,7 +1370,7 @@ func TestFindLatestSupportedVersionWithSorting(t *testing.T) { expectedErrMsg: "failed to find the latest supported OCP version", }, { - name: "When RC versions are mixed throughout list, expect latest non-RC supported version", + name: "When RC versions are mixed throughout list it should return latest non-RC supported version", tags: `[ {"name": "4.18.1", "pullSpec": "quay.io/openshift-release-dev/ocp-release:4.18.1-multi", "downloadURL": "https://example.com/4.18.1"}, {"name": "4.20.0-rc.3", "pullSpec": "quay.io/openshift-release-dev/ocp-release:4.20.0-rc.3-multi", "downloadURL": "https://example.com/4.20.0-rc.3"}, @@ -1454,19 +1454,19 @@ func TestGetLatestSupportedOCPVersion(t *testing.T) { expectedVersion: "4.22.0", }, { - name: "When the ConfigMap is in a non-default namespace it should return an error", + name: "When the ConfigMap is in a non-default namespace, it should return an error", objects: []client.Object{validCM("custom-namespace")}, expectErr: true, expectedErrMsg: "failed to find supported versions on the server", }, { - name: "When no ConfigMap exists it should return an error", + name: "When no ConfigMap exists, it should return an error", objects: []client.Object{}, expectErr: true, expectedErrMsg: "failed to find supported versions on the server", }, { - name: "When the versions list is empty it should return an error", + name: "When the versions list is empty, it should return an error", objects: []client.Object{ &corev1.ConfigMap{ ObjectMeta: metav1.ObjectMeta{ @@ -1484,7 +1484,7 @@ func TestGetLatestSupportedOCPVersion(t *testing.T) { expectedErrMsg: "no supported OCP versions found", }, { - name: "When the version string is unparsable it should return an error", + name: "When the version string is unparsable, it should return an error", objects: []client.Object{ &corev1.ConfigMap{ ObjectMeta: metav1.ObjectMeta{ diff --git a/support/util/cleanup_tracker_test.go b/support/util/cleanup_tracker_test.go index 0b82f0726d86..c8bb3a9d5c9f 100644 --- a/support/util/cleanup_tracker_test.go +++ b/support/util/cleanup_tracker_test.go @@ -308,7 +308,7 @@ func TestIsKubeAPIServerAvailable(t *testing.T) { expectError bool }{ { - name: "KubeAPIServer exists", + name: "When KubeAPIServer exists, it should return true", deployment: &appsv1.Deployment{ ObjectMeta: metav1.ObjectMeta{ Name: "kube-apiserver", @@ -319,7 +319,7 @@ func TestIsKubeAPIServerAvailable(t *testing.T) { expectError: false, }, { - name: "KubeAPIServer does not exist", + name: "When KubeAPIServer does not exist, it should return false", deployment: nil, expected: false, expectError: false, diff --git a/support/util/maps_test.go b/support/util/maps_test.go index 1a6ad1ff311e..35595a67ec5a 100644 --- a/support/util/maps_test.go +++ b/support/util/maps_test.go @@ -17,7 +17,7 @@ func TestMapsDiff(t *testing.T) { expectedDifferent bool }{ { - name: "Nil maps", + name: "When both maps are nil, it should return empty changes and no difference", current: nil, input: nil, expectedChanged: map[string]string{}, @@ -25,7 +25,7 @@ func TestMapsDiff(t *testing.T) { expectedDifferent: false, }, { - name: "Nil current, non-empty input", + name: "When current is nil and input is non-empty, it should return all input as changed", current: nil, input: map[string]string{"x": "y"}, expectedChanged: map[string]string{"x": "y"}, @@ -33,7 +33,7 @@ func TestMapsDiff(t *testing.T) { expectedDifferent: true, }, { - name: "Nil input, non-empty current", + name: "When input is nil and current is non-empty, it should return all current as deleted", current: map[string]string{"x": "y"}, input: nil, expectedChanged: map[string]string{}, @@ -41,7 +41,7 @@ func TestMapsDiff(t *testing.T) { expectedDifferent: true, }, { - name: "Multiple changes and deletions", + name: "When maps have multiple changes and deletions, it should detect all differences", current: map[string]string{"a": "1", "b": "2", "c": "3"}, input: map[string]string{"a": "2", "d": "4"}, expectedChanged: map[string]string{"a": "2", "d": "4"}, @@ -49,7 +49,7 @@ func TestMapsDiff(t *testing.T) { expectedDifferent: true, }, { - name: "Empty string values", + name: "When maps have empty string values, it should handle them correctly", current: map[string]string{"a": "", "b": "2"}, input: map[string]string{"a": "", "b": ""}, expectedChanged: map[string]string{"b": ""}, @@ -57,7 +57,7 @@ func TestMapsDiff(t *testing.T) { expectedDifferent: true, }, { - name: "Same keys, different order", + name: "When maps have same keys in different order, it should return no difference", current: map[string]string{"a": "1", "b": "2"}, input: map[string]string{"b": "2", "a": "1"}, expectedChanged: map[string]string{}, diff --git a/support/util/registryoverride/registryoverride_test.go b/support/util/registryoverride/registryoverride_test.go index 1212c8ae9b74..a35b778aeb34 100644 --- a/support/util/registryoverride/registryoverride_test.go +++ b/support/util/registryoverride/registryoverride_test.go @@ -15,49 +15,49 @@ func TestReplace(t *testing.T) { want string }{ { - name: "nil overrides returns input unchanged", + name: "When nil overrides are provided, it should return input unchanged", image: "quay.io/openshift-release-dev/ocp-release@sha256:abc", overrides: nil, want: "quay.io/openshift-release-dev/ocp-release@sha256:abc", }, { - name: "empty overrides returns input unchanged", + name: "When empty overrides are provided, it should return input unchanged", image: "quay.io/openshift-release-dev/ocp-release@sha256:abc", overrides: map[string]string{}, want: "quay.io/openshift-release-dev/ocp-release@sha256:abc", }, { - name: "no matching override returns input unchanged", + name: "When no matching override exists, it should return input unchanged", image: "quay.io/openshift-release-dev/ocp-release@sha256:abc", overrides: map[string]string{"registry.redhat.io": "mirror.example.com"}, want: "quay.io/openshift-release-dev/ocp-release@sha256:abc", }, { - name: "exact-match key replaces image", + name: "When exact-match key is found, it should replace image", image: "quay.io", overrides: map[string]string{"quay.io": "mirror.example.com"}, want: "mirror.example.com", }, { - name: "slash-boundary prefix match preserves path and digest", + name: "When slash-boundary prefix matches, it should preserve path and digest", image: "quay.io/openshift-release-dev/ocp-release@sha256:abc", overrides: map[string]string{"quay.io": "mirror.example.com"}, want: "mirror.example.com/openshift-release-dev/ocp-release@sha256:abc", }, { - name: "subdomain does not match (no false positive)", + name: "When subdomain looks similar, it should not match", image: "quay.io.example.com/foo/bar:latest", overrides: map[string]string{"quay.io": "mirror.example.com"}, want: "quay.io.example.com/foo/bar:latest", }, { - name: "trailing path component does not match (no false positive)", + name: "When trailing path component looks similar, it should not match", image: "quay.io-evil/foo:latest", overrides: map[string]string{"quay.io": "mirror.example.com"}, want: "quay.io-evil/foo:latest", }, { - name: "longest matching prefix wins", + name: "When multiple prefixes match, it should use longest matching prefix", image: "quay.io/openshift-release-dev/ocp-release@sha256:abc", overrides: map[string]string{ "quay.io": "broad.example.com", @@ -66,7 +66,7 @@ func TestReplace(t *testing.T) { want: "narrow.example.com/mirror/ocp-release@sha256:abc", }, { - name: "shorter prefix used when longer prefix does not match", + name: "When longer prefix does not match, it should use shorter prefix", image: "quay.io/some-other-org/image:tag", overrides: map[string]string{ "quay.io": "broad.example.com", @@ -75,7 +75,7 @@ func TestReplace(t *testing.T) { want: "broad.example.com/some-other-org/image:tag", }, { - name: "empty source key is skipped", + name: "When empty source key exists, it should skip it", image: "quay.io/foo/bar:latest", overrides: map[string]string{ "": "should-never-be-used", @@ -84,25 +84,25 @@ func TestReplace(t *testing.T) { want: "mirror.example.com/foo/bar:latest", }, { - name: "tag is preserved", + name: "When image has tag, it should preserve tag", image: "quay.io/foo/bar:v1.2.3", overrides: map[string]string{"quay.io": "mirror.example.com"}, want: "mirror.example.com/foo/bar:v1.2.3", }, { - name: "When source matches full repository with digest separator it should replace prefix", + name: "When source matches full repository with digest separator, it should replace prefix", image: "quay.io/openshift-release-dev/ocp-v4.0-art-dev@sha256:abc123", overrides: map[string]string{"quay.io/openshift-release-dev/ocp-v4.0-art-dev": "mirror.example.com/art-dev"}, want: "mirror.example.com/art-dev@sha256:abc123", }, { - name: "When source matches full repository with tag separator it should replace prefix", + name: "When source matches full repository with tag separator, it should replace prefix", image: "quay.io/openshift-release-dev/ocp-v4.0-art-dev:latest", overrides: map[string]string{"quay.io/openshift-release-dev/ocp-v4.0-art-dev": "mirror.example.com/art-dev"}, want: "mirror.example.com/art-dev:latest", }, { - name: "When multiple overrides match with digest it should pick longest prefix", + name: "When multiple overrides match with digest, it should pick longest prefix", image: "quay.io/openshift-release-dev/ocp-v4.0-art-dev@sha256:abc123", overrides: map[string]string{ "quay.io": "broad.example.com", @@ -111,25 +111,25 @@ func TestReplace(t *testing.T) { want: "narrow.example.com/art-dev@sha256:abc123", }, { - name: "When source has trailing dash it should not match similar prefix (no false positive)", + name: "When source has trailing dash, it should not match similar prefix (no false positive)", image: "quay.io/openshift-release-dev/ocp-v4.0-art-dev-extra@sha256:abc", overrides: map[string]string{"quay.io/openshift-release-dev/ocp-v4.0-art-dev": "mirror/art-dev"}, want: "quay.io/openshift-release-dev/ocp-v4.0-art-dev-extra@sha256:abc", }, { - name: "When host-only source matches host:port image it should not match (port is not a tag)", + name: "When host-only source matches host:port image, it should not match (port is not a tag)", image: "quay.io:5000/org/repo@sha256:abc", overrides: map[string]string{"quay.io": "mirror.example.com"}, want: "quay.io:5000/org/repo@sha256:abc", }, { - name: "When host:port source matches host:port image it should match via slash", + name: "When host:port source matches host:port image, it should match via slash", image: "myregistry:5000/org/repo@sha256:abc", overrides: map[string]string{"myregistry:5000": "mirror.example.com"}, want: "mirror.example.com/org/repo@sha256:abc", }, { - name: "empty image returns empty", + name: "When image is empty, it should return empty", image: "", overrides: map[string]string{"quay.io": "mirror.example.com"}, want: "", diff --git a/support/util/util_test.go b/support/util/util_test.go index 549cbefaf8ba..3308de6d187f 100644 --- a/support/util/util_test.go +++ b/support/util/util_test.go @@ -31,17 +31,17 @@ func TestCompressDecompress(t *testing.T) { compressed []byte }{ { - name: "Text", + name: "When compressing text data, it should encode it correctly", payload: []byte("The quick brown fox jumps over the lazy dog."), compressed: []byte("H4sIAAAAAAAC/wrJSFUoLM1MzlZIKsovz1NIy69QyCrNLShWyC9LLVIoyUhVyEmsqlRIyU/XAwQAAP//6SWQUSwAAAA="), }, { - name: "Empty", + name: "When compressing empty data, it should return empty data", payload: []byte{}, compressed: []byte{}, }, { - name: "Nil", + name: "When compressing nil data, it should return nil", payload: nil, compressed: nil, }, @@ -73,11 +73,11 @@ func TestConvertRegistryOverridesToCommandLineFlag(t *testing.T) { expectedFlag string }{ { - name: "No registry overrides", + name: "When there are no registry overrides it should return empty flag", expectedFlag: "=", }, { - name: "Registry overrides with single mirrors", + name: "When registry overrides have single mirrors it should return correct flag", registryOverrides: map[string]string{ "registry1": "mirror1.1", "registry2": "mirror2.1", @@ -106,11 +106,11 @@ func TestConvertOpenShiftImageRegistryOverridesToCommandLineFlag(t *testing.T) { expectedFlag string }{ { - name: "No registry overrides", + name: "When there are no registry overrides it should return empty flag", expectedFlag: "=", }, { - name: "Registry overrides with single mirrors", + name: "When registry overrides have single mirrors it should return correct flag", registryOverrides: map[string][]string{ "registry1": { "mirror1.1", @@ -125,7 +125,7 @@ func TestConvertOpenShiftImageRegistryOverridesToCommandLineFlag(t *testing.T) { expectedFlag: "registry1=mirror1.1,registry2=mirror2.1,registry3=mirror3.1", }, { - name: "Registry overrides with multiple mirrors", + name: "When registry overrides have multiple mirrors it should return correct flag", registryOverrides: map[string][]string{ "registry1": { "mirror1.1", @@ -163,16 +163,16 @@ func TestConvertImageRegistryOverrideStringToMap(t *testing.T) { input string }{ { - name: "Empty string", + name: "When input is empty string, it should return nil", input: "", }, { - name: "No registry overrides", + name: "When input has no registry overrides, it should return nil", input: "=", //expectedOutput: make(map[string][]string), }, { - name: "Registry overrides with single mirrors", + name: "When input has single mirrors, it should return correct map", expectedOutput: map[string][]string{ "registry1": { "mirror1.1", @@ -188,7 +188,7 @@ func TestConvertImageRegistryOverrideStringToMap(t *testing.T) { input: "registry1=mirror1.1,registry2=mirror2.1,registry3=mirror3.1", }, { - name: "Registry overrides with multiple mirrors", + name: "When input has multiple mirrors, it should return correct map", expectedOutput: map[string][]string{ "registry1": { "mirror1.1", @@ -273,27 +273,27 @@ func TestSanitizeIgnitionPayload(t *testing.T) { wantErr bool }{ { - name: "Simple valid Ignition payload", + name: "When payload is a simple valid Ignition config, it should not return error", payload: []byte(`{"ignition": {"version": "3.0.0"}}`), wantErr: false, }, { - name: "More complex valid Ignition payload", + name: "When payload is a complex valid Ignition config, it should not return error", payload: []byte(`{"ignition":{"version":"3.0.0"},"storage":{"files":[{"path":"/etc/someconfig","mode":420,"contents":{"source":"data:,example%20file%0A"}}]}}`), wantErr: false, }, { - name: "Simple invalid Ignition payload (missing closing brace)", + name: "When payload is missing a closing brace, it should return error", payload: []byte(`{"ignition": {"version": "3.0.0"`), wantErr: true, }, { - name: "Empty payload", + name: "When payload is empty, it should return error", payload: []byte(``), wantErr: true, }, { - name: "Nil payload", + name: "When payload is nil, it should return error", payload: nil, wantErr: true, }, @@ -362,7 +362,7 @@ func TestGetPullSecretBytes(t *testing.T) { expectErr bool }{ { - name: "HC has right pull secret info; no err", + name: "When HC has right pull secret info, it should not return error", hc: &hyperv1.HostedCluster{ TypeMeta: metav1.TypeMeta{}, ObjectMeta: metav1.ObjectMeta{ @@ -385,7 +385,7 @@ func TestGetPullSecretBytes(t *testing.T) { expectErr: false, }, { - name: "HC has wrong pull secret name; err", + name: "When HC has wrong pull secret name, it should return error", hc: &hyperv1.HostedCluster{ TypeMeta: metav1.TypeMeta{}, ObjectMeta: metav1.ObjectMeta{ @@ -408,7 +408,7 @@ func TestGetPullSecretBytes(t *testing.T) { expectErr: true, }, { - name: "HC has right pull secret name; pull secret missing key; err", + name: "When HC has right pull secret name but pull secret is missing key, it should return error", hc: &hyperv1.HostedCluster{ TypeMeta: metav1.TypeMeta{}, ObjectMeta: metav1.ObjectMeta{ @@ -463,7 +463,7 @@ func TestGetImageArchitecture(t *testing.T) { expectErr bool }{ { - name: "When providing an empty pull secret it should return an error", + name: "When providing an empty pull secret, it should return an error", image: "quay.io/openshift-release-dev/ocp-release:4.16.11-ppc64le", pullSecretBytes: []byte(""), imageMetadataProvider: &fakeimagemetadataprovider.FakeRegistryClientImageMetadataProvider{ @@ -473,7 +473,7 @@ func TestGetImageArchitecture(t *testing.T) { expectErr: true, }, { - name: "When resolving an amd64 image it should return AMD64", + name: "When resolving an amd64 image, it should return AMD64", image: "quay.io/openshift-release-dev/ocp-release:4.16.10-x86_64", pullSecretBytes: pullSecretBytes, imageMetadataProvider: &fakeimagemetadataprovider.FakeRegistryClientImageMetadataProvider{ @@ -483,7 +483,7 @@ func TestGetImageArchitecture(t *testing.T) { expectErr: false, }, { - name: "When resolving a ppc64le image it should return PPC64LE", + name: "When resolving a ppc64le image, it should return PPC64LE", image: "quay.io/openshift-release-dev/ocp-release:4.16.11-ppc64le", pullSecretBytes: pullSecretBytes, imageMetadataProvider: &fakeimagemetadataprovider.FakeRegistryClientImageMetadataProvider{ @@ -520,7 +520,7 @@ func TestDetermineHostedClusterPayloadArch(t *testing.T) { expectErr bool }{ { - name: "When resolving an amd64 image it should return AMD64", + name: "When resolving an amd64 image, it should return AMD64", hc: &hyperv1.HostedCluster{ TypeMeta: metav1.TypeMeta{}, ObjectMeta: metav1.ObjectMeta{ @@ -551,7 +551,7 @@ func TestDetermineHostedClusterPayloadArch(t *testing.T) { expectErr: false, }, { - name: "When resolving a multi-arch image it should return Multi", + name: "When resolving a multi-arch image, it should return Multi", hc: &hyperv1.HostedCluster{ TypeMeta: metav1.TypeMeta{}, ObjectMeta: metav1.ObjectMeta{ @@ -610,74 +610,74 @@ func TestRemoveEmptyJSONField(t *testing.T) { expected string }{ { - name: "Remove empty field from JSON - at the end", + name: "When empty field is at the end, it should remove it", input: `{"field1": "value1", "field2": ""}`, field: "field2", expected: `{"field1": "value1"}`, }, { - name: "Remove empty field from JSON - at the beginning", + name: "When empty field is at the beginning, it should remove it", input: `{"field1": "", "field2": "value2"}`, field: "field1", expected: `{"field2": "value2"}`, }, { - name: "Remove empty field from JSON - in the middle", + name: "When empty field is in the middle, it should remove it", input: `{"field1": "value1", "field2": "", "field3": "value3"}`, field: "field2", expected: `{"field1": "value1", "field3": "value3"}`, }, { - name: "Remove empty field from JSON - without spaces - at the beginning", + name: "When empty field without spaces is at the beginning, it should remove it", input: `{"field1":"","field2":"value2"}`, field: "field1", expected: `{"field2":"value2"}`, }, { - name: "Remove empty field from JSON - without spaces - in the middle", + name: "When empty field without spaces is in the middle, it should remove it", input: `{"field1":"value1","field2":"","field3":"value3"}`, field: "field2", expected: `{"field1":"value1","field3":"value3"}`, }, { - name: "Remove empty field from JSON - without spaces - at the end", + name: "When empty field without spaces is at the end, it should remove it", input: `{"field1":"value1","field2":""}`, field: "field2", expected: `{"field1":"value1"}`, }, { - name: "Keep non-empty field from JSON", + name: "When field is non-empty, it should keep it", input: `{"field1": "value1", "field2": "value2"}`, field: "field2", expected: `{"field1": "value1", "field2": "value2"}`, }, { - name: "Remove non-existent field from JSON returns the same JSON", + name: "When field does not exist, it should return the same JSON", input: `{"field1": "value1"}`, field: "field2", expected: `{"field1": "value1"}`, }, { - name: "Empty JSON returns empty JSON", + name: "When JSON is empty, it should return empty JSON", input: `{}`, field: "field1", expected: `{}`, }, { - name: "Empty JSON returns empty JSON - empty field", + name: "When JSON is empty and field is empty, it should return empty JSON", input: `{}`, field: "", expected: `{}`, }, { - name: "Remove nested empty field from JSON", + name: "When nested field is empty, it should remove it", input: `{"field1": "value1", "field2": {"field3": ""}}`, field: "field3", expected: `{"field1": "value1", "field2": {}}`, }, { - name: "Remove nested empty field from JSON - in the middle", + name: "When nested empty field is in the middle, it should remove it", input: `{"field1": "value1", "field2": {"field3": "value3", "field4": "value4", "field5": ""}}`, field: "field5", expected: `{"field1": "value1", "field2": {"field3": "value3", "field4": "value4"}}`, @@ -704,7 +704,7 @@ func TestCountAvailableNodes(t *testing.T) { expectErr bool }{ { - name: "all nodes ready and schedulable", + name: "When all nodes are ready and schedulable, it should count all of them", nodes: []corev1.Node{ { ObjectMeta: metav1.ObjectMeta{Name: "node1"}, @@ -728,7 +728,7 @@ func TestCountAvailableNodes(t *testing.T) { expected: 2, }, { - name: "one node cordoned", + name: "When one node is cordoned, it should exclude it from the count", nodes: []corev1.Node{ { ObjectMeta: metav1.ObjectMeta{Name: "node1"}, @@ -752,7 +752,7 @@ func TestCountAvailableNodes(t *testing.T) { expected: 1, }, { - name: "one node not ready", + name: "When one node is not ready, it should exclude it from the count", nodes: []corev1.Node{ { ObjectMeta: metav1.ObjectMeta{Name: "node1"}, @@ -776,7 +776,7 @@ func TestCountAvailableNodes(t *testing.T) { expected: 1, }, { - name: "no nodes", + name: "When there are no nodes, it should return zero", nodes: []corev1.Node{}, expected: 0, }, @@ -814,11 +814,11 @@ func TestHashConfigMapData(t *testing.T) { data map[string]string }{ { - name: "When data is nil it should return empty string", + name: "When data is nil, it should return empty string", data: nil, }, { - name: "When data is empty it should return empty string", + name: "When data is empty, it should return empty string", data: map[string]string{}, }, } @@ -829,27 +829,27 @@ func TestHashConfigMapData(t *testing.T) { }) } - t.Run("When data has entries it should return a non-empty hash", func(t *testing.T) { + t.Run("When data has entries, it should return a non-empty hash", func(t *testing.T) { g := NewWithT(t) hash := HashConfigMapData(map[string]string{"key": "value"}) g.Expect(hash).NotTo(BeEmpty()) }) - t.Run("When same keys are inserted in different order it should return the same hash", func(t *testing.T) { + t.Run("When same keys are inserted in different order, it should return the same hash", func(t *testing.T) { g := NewWithT(t) h1 := HashConfigMapData(map[string]string{"a": "1", "b": "2", "c": "3"}) h2 := HashConfigMapData(map[string]string{"c": "3", "a": "1", "b": "2"}) g.Expect(h1).To(Equal(h2)) }) - t.Run("When keys and values could collide without delimiters it should produce different hashes", func(t *testing.T) { + t.Run("When keys and values could collide without delimiters, it should produce different hashes", func(t *testing.T) { g := NewWithT(t) h1 := HashConfigMapData(map[string]string{"ab": "c"}) h2 := HashConfigMapData(map[string]string{"a": "bc"}) g.Expect(h1).NotTo(Equal(h2)) }) - t.Run("When data differs it should return different hashes", func(t *testing.T) { + t.Run("When data differs, it should return different hashes", func(t *testing.T) { g := NewWithT(t) h1 := HashConfigMapData(map[string]string{"key": "value1"}) h2 := HashConfigMapData(map[string]string{"key": "value2"}) diff --git a/sync-global-pullsecret/sync-global-pullsecret_test.go b/sync-global-pullsecret/sync-global-pullsecret_test.go index 7655a0f6096c..d9edee43f8f3 100644 --- a/sync-global-pullsecret/sync-global-pullsecret_test.go +++ b/sync-global-pullsecret/sync-global-pullsecret_test.go @@ -25,7 +25,7 @@ func TestCheckAndFixFile(t *testing.T) { description string }{ { - name: "When file does not exist and kubelet restart succeeds it should create file with new content", + name: "When file does not exist and kubelet restart succeeds, it should create file with new content", description: "file does not exist, kubelet restart succeeds, file is created", initialContent: "", secretContent: `{"auths":{"test.registry.com":{"auth":"dGVzdDp0ZXN0"}}}`, @@ -37,7 +37,7 @@ func TestCheckAndFixFile(t *testing.T) { expectError: false, }, { - name: "When file does not exist and kubelet restart fails it should rollback", + name: "When file does not exist and kubelet restart fails, it should rollback", description: "file does not exist, kubelet restart fails, rollback succeeds", initialContent: "", secretContent: `{"auths":{"test.registry.com":{"auth":"dGVzdDp0ZXN0"}}}`, @@ -53,7 +53,7 @@ func TestCheckAndFixFile(t *testing.T) { expectError: true, }, { - name: "When file exists with different content and kubelet restart succeeds it should update file", + name: "When file exists with different content and kubelet restart succeeds, it should update file", description: "file exists with different content, kubelet restart succeeds", initialContent: `{"auths":{"old.registry.com":{"auth":"b2xkOnRlc3Q="}}}`, secretContent: `{"auths":{"test.registry.com":{"auth":"dGVzdDp0ZXN0"}}}`, @@ -65,7 +65,7 @@ func TestCheckAndFixFile(t *testing.T) { expectError: false, }, { - name: "When file exists with different content and kubelet restart fails it should rollback", + name: "When file exists with different content and kubelet restart fails, it should rollback", description: "file exists with different content, kubelet restart fails, rollback succeeds", initialContent: `{"auths":{"old.registry.com":{"auth":"b2xkOnRlc3Q="}}}`, secretContent: `{"auths":{"test.registry.com":{"auth":"dGVzdDp0ZXN0"}}}`, @@ -81,7 +81,7 @@ func TestCheckAndFixFile(t *testing.T) { expectError: true, }, { - name: "When file exists with same content it should not restart kubelet", + name: "When file exists with same content, it should not restart kubelet", description: "file exists with same content, no changes needed", initialContent: `{"auths":{"test.registry.com":{"auth":"dGVzdDp0ZXN0"}}}`, secretContent: `{"auths":{"test.registry.com":{"auth":"dGVzdDp0ZXN0"}}}`, @@ -92,7 +92,7 @@ func TestCheckAndFixFile(t *testing.T) { expectError: false, }, { - name: "When kubelet restart fails it should rollback to original content", + name: "When kubelet restart fails, it should rollback to original content", description: "kubelet restart fails but rollback succeeds, file should be restored to original content", initialContent: `{"auths":{"old.registry.com":{"auth":"b2xkOnRlc3Q="}}}`, secretContent: `{"auths":{"test.registry.com":{"auth":"dGVzdDp0ZXN0"}}}`, @@ -108,7 +108,7 @@ func TestCheckAndFixFile(t *testing.T) { expectError: true, }, { - name: "When both kubelet restart and rollback fail it should return combined error", + name: "When both kubelet restart and rollback fail, it should return combined error", description: "both kubelet restart and rollback fail, file should remain with new content", initialContent: `{"auths":{"old.registry.com":{"auth":"b2xkOnRlc3Q="}}}`, secretContent: `{"auths":{"test.registry.com":{"auth":"dGVzdDp0ZXN0"}}}`, @@ -125,7 +125,7 @@ func TestCheckAndFixFile(t *testing.T) { expectError: true, }, { - name: "When only trailing newline differs it should not restart kubelet", + name: "When only trailing newline differs, it should not restart kubelet", description: "file has trailing newline, new content doesn't, should not trigger restart", initialContent: "{\"auths\":{\"test.registry.com\":{\"auth\":\"dGVzdDp0ZXN0\"}}}\n", secretContent: `{"auths":{"test.registry.com":{"auth":"dGVzdDp0ZXN0"}}}`, @@ -135,7 +135,7 @@ func TestCheckAndFixFile(t *testing.T) { expectError: false, }, { - name: "When content differs and both have newlines it should update and restart", + name: "When content differs and both have newlines, it should update and restart", description: "both original file and new content have trailing newlines, different content", initialContent: "{\"auths\":{\"old.registry.com\":{\"auth\":\"b2xkOnRlc3Q=\"}}}\n", secretContent: "{\"auths\":{\"test.registry.com\":{\"auth\":\"dGVzdDp0ZXN0\"}}}\n", @@ -147,7 +147,7 @@ func TestCheckAndFixFile(t *testing.T) { expectError: false, }, { - name: "When content differs with newline in secret it should write exact secret content", + name: "When content differs with newline in secret, it should write exact secret content", description: "original file has no newline, new content has newline, should write new content exactly", initialContent: `{"auths":{"old.registry.com":{"auth":"b2xkOnRlc3Q="}}}`, secretContent: "{\"auths\":{\"test.registry.com\":{\"auth\":\"dGVzdDp0ZXN0\"}}}\n", @@ -159,7 +159,7 @@ func TestCheckAndFixFile(t *testing.T) { expectError: false, }, { - name: "When content differs without newlines it should update and restart", + name: "When content differs without newlines, it should update and restart", description: "neither original file nor new content have newlines, should update", initialContent: `{"auths":{"old.registry.com":{"auth":"b2xkOnRlc3Q="}}}`, secretContent: `{"auths":{"test.registry.com":{"auth":"dGVzdDp0ZXN0"}}}`, @@ -171,7 +171,7 @@ func TestCheckAndFixFile(t *testing.T) { expectError: false, }, { - name: "When file has newline and secret does not but content is same it should not restart", + name: "When file has newline and secret does not but content is same, it should not restart", description: "file content is identical ignoring newline, no restart should be attempted", initialContent: "{\"auths\":{\"test.registry.com\":{\"auth\":\"dGVzdDp0ZXN0\"}}}\n", secretContent: `{"auths":{"test.registry.com":{"auth":"dGVzdDp0ZXN0"}}}`, @@ -272,7 +272,7 @@ func TestRestartKubelet(t *testing.T) { description string }{ { - name: "Success", + name: "When systemd job completes successfully it should return no error", setupMock: func(mock *MockdbusConn) { mock.EXPECT(). RestartUnit(gomock.Any(), gomock.Any(), gomock.Any()). @@ -285,7 +285,7 @@ func TestRestartKubelet(t *testing.T) { description: "systemd job completed successfully", }, { - name: "RestartUnit returns an error", + name: "When RestartUnit returns an error it should propagate the error", setupMock: func(mock *MockdbusConn) { mock.EXPECT(). RestartUnit(gomock.Any(), gomock.Any(), gomock.Any()). @@ -295,7 +295,7 @@ func TestRestartKubelet(t *testing.T) { description: "dbus call itself failed", }, { - name: "Job failed", + name: "When systemd job fails it should return failure error", setupMock: func(mock *MockdbusConn) { mock.EXPECT(). RestartUnit(gomock.Any(), gomock.Any(), gomock.Any()). @@ -308,7 +308,7 @@ func TestRestartKubelet(t *testing.T) { description: "systemd job failed", }, { - name: "Job timeout", + name: "When systemd job times out it should return timeout error", setupMock: func(mock *MockdbusConn) { mock.EXPECT(). RestartUnit(gomock.Any(), gomock.Any(), gomock.Any()). @@ -321,7 +321,7 @@ func TestRestartKubelet(t *testing.T) { description: "systemd job timed out", }, { - name: "Job canceled", + name: "When systemd job is canceled it should return canceled error", setupMock: func(mock *MockdbusConn) { mock.EXPECT(). RestartUnit(gomock.Any(), gomock.Any(), gomock.Any()). @@ -334,7 +334,7 @@ func TestRestartKubelet(t *testing.T) { description: "systemd job was canceled", }, { - name: "Job dependency failed", + name: "When systemd job dependency fails it should return dependency error", setupMock: func(mock *MockdbusConn) { mock.EXPECT(). RestartUnit(gomock.Any(), gomock.Any(), gomock.Any()). @@ -347,7 +347,7 @@ func TestRestartKubelet(t *testing.T) { description: "systemd job dependency failed", }, { - name: "Job skipped", + name: "When systemd job is skipped it should return skipped error", setupMock: func(mock *MockdbusConn) { mock.EXPECT(). RestartUnit(gomock.Any(), gomock.Any(), gomock.Any()). @@ -391,121 +391,121 @@ func TestValidateDockerConfigJSON(t *testing.T) { description string }{ { - name: "valid docker config with single auth", + name: "When docker config has single auth, it should validate successfully", input: []byte(`{"auths":{"test.registry.com":{"auth":"dGVzdDp0ZXN0"}}}`), expectError: false, description: "valid JSON with auths key containing single registry", }, { - name: "valid docker config with multiple auths", + name: "When docker config has multiple auths, it should validate successfully", input: []byte(`{"auths":{"registry1.com":{"auth":"dGVzdDp0ZXN0"},"registry2.com":{"auth":"YW5vdGhlcjphdXRo"}}}`), expectError: false, description: "valid JSON with auths key containing multiple registries", }, { - name: "valid docker config with empty auths", + name: "When docker config has empty auths, it should validate successfully", input: []byte(`{"auths":{}}`), expectError: false, description: "valid JSON with empty auths object", }, { - name: "valid docker config with additional fields", + name: "When docker config has additional fields, it should validate successfully", input: []byte(`{"auths":{"test.registry.com":{"auth":"dGVzdDp0ZXN0"}},"credsStore":"desktop","credHelpers":{"registry.com":"registry-helper"}}`), expectError: false, description: "valid JSON with auths key and additional docker config fields", }, { - name: "invalid JSON - malformed", + name: "When JSON is malformed, it should return validation error", input: []byte(`{"auths":{"test.registry.com":{"auth":"dGVzdDp0ZXN0"}`), expectError: true, description: "malformed JSON missing closing brace", }, { - name: "invalid JSON - trailing comma", + name: "When JSON has trailing comma, it should return validation error", input: []byte(`{"auths":{"test.registry.com":{"auth":"dGVzdDp0ZXN0"}},}`), expectError: true, description: "malformed JSON with trailing comma", }, { - name: "invalid JSON - unquoted key", + name: "When JSON has unquoted key, it should return validation error", input: []byte(`{auths:{"test.registry.com":{"auth":"dGVzdDp0ZXN0"}}}`), expectError: true, description: "malformed JSON with unquoted key", }, { - name: "missing auths key", + name: "When auths key is missing, it should return validation error", input: []byte(`{"registries":{"test.registry.com":{"auth":"dGVzdDp0ZXN0"}}}`), expectError: true, description: "valid JSON but missing required auths key", }, { - name: "empty input", + name: "When input is empty, it should return validation error", input: []byte(``), expectError: true, description: "empty byte slice should fail JSON parsing", }, { - name: "null input", + name: "When input is null, it should return validation error", input: []byte(`null`), expectError: true, description: "null JSON value should fail validation", }, { - name: "string input", + name: "When input is a string, it should return validation error", input: []byte(`"some string"`), expectError: true, description: "string JSON value should fail validation", }, { - name: "array input", + name: "When input is an array, it should return validation error", input: []byte(`[{"auths":{"test.registry.com":{"auth":"dGVzdDp0ZXN0"}}}]`), expectError: true, description: "array JSON value should fail validation", }, { - name: "number input", + name: "When input is a number, it should return validation error", input: []byte(`123`), expectError: true, description: "number JSON value should fail validation", }, { - name: "boolean input", + name: "When input is a boolean, it should return validation error", input: []byte(`true`), expectError: true, description: "boolean JSON value should fail validation", }, { - name: "auths key with null value", + name: "When auths key has null value, it should validate successfully", input: []byte(`{"auths":null}`), expectError: false, description: "auths key with null value should be valid (auths key exists)", }, { - name: "auths key with string value", + name: "When auths key has string value, it should validate successfully", input: []byte(`{"auths":"not an object"}`), expectError: false, description: "auths key with non-object value should be valid (auths key exists)", }, { - name: "auths key with array value", + name: "When auths key has array value, it should validate successfully", input: []byte(`{"auths":[]}`), expectError: false, description: "auths key with array value should be valid (auths key exists)", }, { - name: "whitespace only", + name: "When input is whitespace only, it should return validation error", input: []byte(` `), expectError: true, description: "whitespace only input should fail JSON parsing", }, { - name: "empty object", + name: "When input is empty object, it should return validation error", input: []byte(`{}`), expectError: true, description: "empty object should fail validation (missing auths key)", }, { - name: "nested auths key", + name: "When auths key is nested, it should return validation error", input: []byte(`{"config":{"auths":{"test.registry.com":{"auth":"dGVzdDp0ZXN0"}}}}`), expectError: true, description: "auths key nested inside another object should fail validation", diff --git a/test/e2e/v2/lifecycle/manifest_test.go b/test/e2e/v2/lifecycle/manifest_test.go index 39934568417d..25d80877bc73 100644 --- a/test/e2e/v2/lifecycle/manifest_test.go +++ b/test/e2e/v2/lifecycle/manifest_test.go @@ -13,7 +13,7 @@ func TestManifestRoundTrip(t *testing.T) { want *ClusterManifest }{ { - name: "when written with a single cluster should deserialize identically", + name: "When written with a single cluster, it should deserialize identically", want: &ClusterManifest{ Clusters: []ClusterEntry{ {Variant: "public", Name: "public-abc1234567", InfraID: "public-abc1234567", Namespace: "clusters"}, @@ -21,7 +21,7 @@ func TestManifestRoundTrip(t *testing.T) { }, }, { - name: "when written with multiple clusters should deserialize identically", + name: "When written with multiple clusters, it should deserialize identically", want: &ClusterManifest{ Clusters: []ClusterEntry{ {Variant: "public", Name: "public-abc1234567", InfraID: "public-abc1234567", Namespace: "clusters"}, @@ -64,7 +64,7 @@ func TestResolveVariants(t *testing.T) { wantError bool }{ { - name: "when all parallel variants exist should return resolved map", + name: "When all parallel variants exist, it should return resolved map", matrix: TestMatrix{ Parallel: []TestGroup{ {Variant: "public"}, @@ -77,7 +77,7 @@ func TestResolveVariants(t *testing.T) { }, }, { - name: "when sequential variants exist should return resolved map", + name: "When sequential variants exist, it should return resolved map", matrix: TestMatrix{ Sequential: []SequentialGroup{ {Steps: []TestGroup{{Variant: "public"}, {Variant: "private"}}}, @@ -89,7 +89,7 @@ func TestResolveVariants(t *testing.T) { }, }, { - name: "when a parallel variant is missing should return an error", + name: "When a parallel variant is missing, it should return an error", matrix: TestMatrix{ Parallel: []TestGroup{ {Variant: "public"}, @@ -99,7 +99,7 @@ func TestResolveVariants(t *testing.T) { wantError: true, }, { - name: "when a sequential variant is missing should return an error", + name: "When a sequential variant is missing, it should return an error", matrix: TestMatrix{ Sequential: []SequentialGroup{ {Steps: []TestGroup{{Variant: "nonexistent"}}}, @@ -108,7 +108,7 @@ func TestResolveVariants(t *testing.T) { wantError: true, }, { - name: "when duplicate variants exist across parallel and sequential should deduplicate", + name: "When duplicate variants exist across parallel and sequential, it should deduplicate", matrix: TestMatrix{ Parallel: []TestGroup{{Variant: "public"}}, Sequential: []SequentialGroup{{Steps: []TestGroup{{Variant: "public"}}}}, diff --git a/test/util/pki_test.go b/test/util/pki_test.go index 2d1eda012e50..b3c5f8c15764 100644 --- a/test/util/pki_test.go +++ b/test/util/pki_test.go @@ -25,7 +25,7 @@ func TestGenerateTestCertificate(t *testing.T) { expectedCN string }{ { - name: "When generating a certificate with DNS names it should succeed", + name: "When generating a certificate with DNS names, it should succeed", dnsNames: []string{"example.com", "test.example.com"}, ipAddresses: []string{"192.168.1.1"}, duration: 24 * time.Hour, @@ -33,7 +33,7 @@ func TestGenerateTestCertificate(t *testing.T) { expectedCN: "example.com", }, { - name: "When generating a certificate with IP addresses only it should succeed", + name: "When generating a certificate with IP addresses only, it should succeed", dnsNames: []string{}, ipAddresses: []string{"192.168.1.1", "10.0.0.1"}, duration: 24 * time.Hour, @@ -41,21 +41,21 @@ func TestGenerateTestCertificate(t *testing.T) { expectedCN: "192.168.1.1", }, { - name: "When generating a certificate with no DNS names or IP addresses it should fail", + name: "When generating a certificate with no DNS names or IP addresses, it should fail", dnsNames: []string{}, ipAddresses: []string{}, duration: 24 * time.Hour, wantErr: true, }, { - name: "When generating a certificate with invalid IP address it should fail", + name: "When generating a certificate with invalid IP address, it should fail", dnsNames: []string{}, ipAddresses: []string{"invalid.ip.address"}, duration: 24 * time.Hour, wantErr: true, }, { - name: "When generating a certificate with zero duration it should succeed", + name: "When generating a certificate with zero duration, it should succeed", dnsNames: []string{"example.com"}, ipAddresses: []string{"192.168.1.1"}, duration: 0,