ARO-HCP / test
AGENTS.md39 starsChanged 2 months agoApache-2.0View on GitHub
* Cluster creation: Cluster creation, which leverages methods from the framework module, offers three main approaches for creating and deploying an HCP cluster: CreateHCPClusterFromParam20240610, which handles creation and automatically waits for successful deployment; BeginCreateHCPCluster20240610, which initiates the process but requires explicit test logic to wait for provisioning completion; and an alternative using CreateHCPClusterFromParam20240610 with a 0-second timeout, which executes the creation but immediately bypasses the waiting phase for provisioning to finish. * Cluster Params: The NewDefaultClusterParams20240610 method from the framework…
Where files are headingNew AGENTS.md files have more rules about keeping secrets out of the code, and fewer about checking a change actually works.
Of the AGENTS.md files we read, the 11,773 first seen in the last six months, against the older ones: the kind of rule that gained most share, and the kind that lost most. About files like this in general, not this one, and an estimate, since a kind is a pattern in the words.
In this repository10 other files it gives its agents.
- AGENTS.mdAGENTS.md
- config/AGENTS.mdAGENTS.md
- CLAUDE.mdCLAUDE.md
- config/CLAUDE.mdCLAUDE.md
- test/CLAUDE.mdCLAUDE.md
- test-integration/claude.mdCLAUDE.md
- .github/copilot-instructions.mdCopilot instructions
- bootstrap-api-versionSkill
- pr-standardsSkill
- agentic-workflowsSkill
The file
Show its rules and text
We split this AGENTS.md into the rules it gives an agent
48 rules. About 0 are common, 22 are distinctive, and 26 are very specific to this project.
≈0
Common · estimate
Many files like this have a rule of this kind.
≈22
Distinctive · estimate
This author's own choices. Worth a look.
26
Very specific
Tied to their project's names, files or tools. Probably skip.
- Common
- Distinctive
- Very specific
- Very specific: line 11
Use RBACScopeResourceGroup as RBACScope argument of CreateClusterCustomerResources20240610 function, but make sure that …
- Very specific: line 22
Add a new constant only when a second (or later) test needs the same duration.
- Very specific: line 25
All cluster and node pool operations are tied to a specific API version.
- Distinctive: line 29
Self-Contained: Every test case must be self-contained, ensuring no dependencies on the state or results of other test cases.
- Very specific: line 40
K8S client-go: Use this client to communicate with created HCP clusters.
- Very specific: line 42
Parallel checks: Use VerifyHCPCluster(ctx, adminRESTConfig, verifiers.VerifyFoo(), verifiers.VerifyBar(), ...) to run independent verifiers …
- Distinctive: line 44
Phased checks: When a verifier depends on resources established by earlier steps (e.g.
- Very specific: line 56
Descriptive nil checks: Every Expect(x).NotTo(BeNil()) or Expect(x).ToNot(BeNil()) call must include an annotation string describing which …
- Distinctive: line 66
When a helper function returns an error, context should exist at both layers: the error itself should describe the proximal failure (e.g.
- Distinctive: line 73
Log message structure: Ensure log messages are direct, including the actual error message if an error occurs.
- Very specific: line 75
Ginkgo Writer: Use ginkgo.GinkgoWriter to create a regular message in output.
- Very specific: line 79
When writing tests that poll until a condition is met (e.g.
- Distinctive: line 81
Delta-only logging: Only emit a log line when the observed state *changes* between poll iterations.
- Distinctive: line 88
Expected vs. observed: Every log line during polling and every failure message must make it clear what was expected and what was actually …
- Distinctive: line 106
ARO HCP environment: Test cases for one environment.
- Distinctive: line 114
File naming convention: When naming new test files, avoid using the \_test suffix.
- Distinctive: line 118
Test developers should refer to the ARO HCP Documentation to understand their test cases.
- Very specific: line 128
When creating a new resource group, use the tc.Location() method to retrieve the globally configured location from the environment variable …
- Distinctive: line 133
Descriptive Names: Use descriptive names for test files, test cases, bicep/arm deployments, and functions.
- Very specific: line 135
Development environment test cases: Ensure new negative test cases produce the same result in development and higher environments by …
- Very specific: line 143
Use the aro-hcp-tests binary to run individual tests or suites locally.
- Very specific: line 184
WARNING: Always revert MustFilter edits before merging.
- Very specific: line 195
Build tag requirement: Only the main entry point file (test/e2e/e2e_test.go) should have the //go:build E2Etests build tag
- Distinctive: line 203
Spec organization: Use clear hierarchies:
- Distinctive: line 207
Descriptive test names: Write complete, readable sentences that form a narrative when concatenated
- Very specific: line 210
Use
By()for test steps: Document critical steps within It blocks using By("step description") - Distinctive: line 217
Every test MUST include appropriate labels from these categories:
- Very specific: line 269
Use tc.Get20240610ClientFactoryOrDie(ctx) to get client factory
- Distinctive: line 271
Always use context with timeout for async operations
- Very specific: line 274
Use framework.GetAdminRESTConfigForHCPCluster20240610() to get REST config (10-minute timeout)
- Very specific: line 275
Use standard client-go libraries for K8s operations
- Very specific: line 281
Location: All verifiers belong in test/util/verifiers/
- Very specific: line 285
Always use context: Every test should accept and use context.Context
- Distinctive: line 287
Respect cancellation: Don't ignore context cancellation in long-running operations
- Very specific: line 291
Check if enabled: Use tc.UsePooledIdentities() to check if pooled identities are enabled
- Very specific: line 292
Assign containers: Call tc.AssignIdentityContainers(ctx, count, timeout) before resource creation
- Very specific: line 301
Case-insensitive matching: Use strings.ToLower() for error message comparisons when case might vary
- Distinctive: line 316
After adding tests with environment-specific behavior:
- Very specific: line 317
Run make update-go-fixtures or make update in test/ directory
- Distinctive: line 322
AroRpApiCompatible label: Only use if test produces same results in dev AND higher environments
- Distinctive: line 323
Test in both environments: Run negative tests in both dev and integration/higher to verify behavior matches
- Distinctive: line 324
Do NOT label if dev-incompatible: Remove label if test fails in development environment
- Distinctive: line 347
Every spec provisions its own cluster and captures a baseline independently (full parallelism).
- Very specific: line 348
All specs check in to the barrier.
- Distinctive: line 350
After the upgrade completes (or fails), every spec independently validates its own cluster (post-upgrade validation).
- Very specific: line 375
If all specs aborted before checking in, Run returns early without running the pipeline.
- Very specific: line 383
If a spec fails before CheckIn, a DeferCleanup registered by NewUpgradeBarrier increments aborted_count so the coordinator is not left …
- Distinctive: line 453
When reviewing E2E test PRs, verify:
≈ “Common” is an estimate: at least 1 in 5 of the 16,595 AGENTS.md files we read have a rule of the same kind, not the same words. “Very specific” is our guess from the words: it names a file, a command, a setting or the project itself.
Files
Principles of Good E2E Test Case Design
Provision HCP cluster
- Cluster creation: Cluster creation, which leverages methods from the framework module, offers three main approaches for creating and deploying an HCP cluster:
CreateHCPClusterFromParam20240610, which handles creation and automatically waits for successful deployment;BeginCreateHCPCluster20240610, which initiates the process but requires explicit test logic to wait for provisioning completion; and an alternative usingCreateHCPClusterFromParam20240610with a 0-second timeout, which executes the creation but immediately bypasses the waiting phase for provisioning to finish. - Cluster Params: The
NewDefaultClusterParams20240610method from the framework module should be used to configure the default cluster parameters. Before creating cluster customer resources, theClusterNameparameter must be set. Different cluster configurations can be achieved by assigning custom values to the parameters. - Prepare cluster customer resources: Creating a cluster requires several
resources (like an NSG, VNet, subnet, and managed identities). To create
these resources and set the cluster's parameters, use the
CreateClusterCustomerResources20240610method from the framework module. UseRBACScopeResourceGroupas RBACScope argument ofCreateClusterCustomerResources20240610function, but make sure thatframework.RBACScopeResourceis used in at least one test case in E2E test suite. - Nodepool creation: To create a nodepool, utilize the
CreateNodePoolFromParam20240610method. Beforehand, the default nodepool parameters should be prepared using theNewDefaultNodePoolParams20240610method. Both of these methods are located within theframeworkmodule. Like cluster parameters, custom configurations can be assigned to the nodepool parameter values. - API version suffix convention: Framework helpers that call the ARM SDK must use explicit API version suffixes in their names. Prefer
...20240610helpers for the stable test path (for exampleGetHCPCluster20240610,UpdateHCPCluster20240610,CreateNodePoolAndWait20240610) and...20251223or any future versions helpers only when testing preview-specific behavior (for exampleBuildHCPClusterFromParams20251223,CreateHCPClusterAndWait20251223). - Timeouts: Add named constants in
test/util/framework/constants.goonly for durations shared across multiple test cases (same ARM operation, framework helper, or verifier pattern). A timeout that is unique to one test and used once can stay as a local literal (e.g. in anEventuallyblock). When several tests need the same budget, use the matching constant instead of repeating a magic number:- Provisioning:
ClusterCreationTimeout,NodePoolCreationTimeout,ExternalAuthCreationTimeout - Access Cluster:
GetAdminRESTConfigTimeout(forGetAdminRESTConfigForHCPClusterYYYYMMDDand similar credential fetches) - Deletion:
HCPClusterDeletionTimeout(forDeleteHCPClusterYYYYMMDD, inline delete pollers, and per-cluster deletes inDeleteAllHCPClusters),NodePoolDeletionTimeout(forDeleteNodePoolYYYYMMDD),ExternalAuthDeletionTimeout(forDeleteExternalAuthYYYYMMDD) - Updates:
UpdateHCPClusterTimeout(PATCH/update cluster properties),HCPClusterVersionUpgradeTimeout(control plane version upgrades),NodePoolVersionUpgradeTimeout(node pool version upgrades),NodePoolScalingTimeout(replica changes and autoscaling updates) Add a new constant only when a second (or later) test needs the same duration. Seetest/e2e/README.mdfor the constant table and how to tune shared values from telemetry.
- Provisioning:
[!NOTE] All cluster and node pool operations are tied to a specific API version. This means that the actual method names have the form
CreateHCPClusterFromParamYYYYMMDD,CreateNodePoolFromParamYYYYMMDD, etc. New methods for new API versions should be added as needed.
Resource naming - Independence and Isolation
- Self-Contained: Every test case must be self-contained, ensuring no dependencies on the state or results of other test cases.
- Parallel execution: Tests are executed parallely thus ensuring names are unique across the subscription: customer resource group (handled by method
tc.NewResourceGroup()), managed resource group, and cluster names within one resource group, if multiple are created. Bicep deployment names must be unique within the resource group.
HCP SDK client helper
- HCP SDK: Currently we are using an unreleased generated ARO HCP Golang SDK. SDK is located under the module test.
- HTTPS Requests: To interact with RP/ARM, use the hcp client.. Use context with timeout to cancel requests which are asynchronous.
- Code location: Such helper functions should be located in the util module
frameworkin filehcp_helper.go. (https://github.com/Azure/ARO-HCP/blob/main/test/util/framework/hcp_helper.go)
Kubernetes verifiers
- K8S client-go: Use this client to communicate with created HCP clusters. Client requires rest Config which is provided by method
GetAdminRESTConfigForHCPCluster20240610with 10 minutes timeout. - HostedClusterVerifier: This interface is designed for all verifiers and provides the essential
NameandVerifymethods for extension. - Parallel checks: Use
VerifyHCPCluster(ctx, adminRESTConfig, verifiers.VerifyFoo(), verifiers.VerifyBar(), ...)to run independent verifiers in parallel. Each verifier is responsible for its own polling, diagnostics, and delta-only logging when it needs to wait. - Polling: Verifiers that poll require a timeout parameter (e.g.
verifiers.VerifyDaemonSetReady(ns, name, 10*time.Minute)). The timeout must be > 0; passing zero is a runtime error. Verifiers that are inherently single-shot (e.g.VerifyPullSecretAuthData) do not accept a timeout. Polling runs inside each verifier'sVerifymethod via shared helpers inpoll.gousingverifiers.DefaultPollInterval. Reuseverifiers.VerifyDaemonSetReady(namespace, name, timeout)for any DaemonSet readiness check;VerifyGlobalPullSecretSynceris a thin alias for the syncer in kube-system. - Phased checks: When a verifier depends on resources established by earlier steps (e.g. Cilium running before a web app test), run
VerifyHCPClusterfor the independent batch first, then call dependent verifiers withExpect(verifier.Verify(...)).NotTo(HaveOccurred(), "...")in a laterBystep. Seecluster_create_cni_cilium.go. - Code location: Verifiers are located in the util module
verifiers. (https://github.com/Azure/ARO-HCP/tree/main/test/util/verifiers)
Cleanup of Resources
- TestContext: Using TestContext, to create a resource group, will automatically register it for a cleanup after the test. The cleanup process involves deleting all HCP clusters within the designated resource groups (via
DeleteAllHCPClusters20240610). The resource groups themselves are removed, along with any remaining Azure resources. - Test resources: Within the test, remove any created resources that are not part of the TestContext resource group or its associated HCP clusters. Ensure all tests start from a known, clean state to avoid flakiness and false positives.
Best Practices for Writing E2E Test Cases
Assertion Messages
- Descriptive nil checks: Every
Expect(x).NotTo(BeNil())orExpect(x).ToNot(BeNil())call must include an annotation string describing which property is being checked. BareBeNil()assertions produce unhelpful failure messages likeExpected <*string | 0x0>: nil not to be nilthat require mapping back to source code to diagnose. Use Gomega's annotation argument to add context:Expect(resp.Properties).NotTo(BeNil(), "cluster response Properties was nil")Expect(resp.Properties.API.URL).NotTo(BeNil(), "cluster Properties.API.URL was nil")- Format strings are supported:
Expect(x).NotTo(BeNil(), "property %s was nil for cluster %s", propName, clusterName)
- Descriptive error checks: Every
Expect(err).NotTo(HaveOccurred())orExpect(err).To(HaveOccurred())call must include an annotation string describing what operation was being attempted. BareHaveOccurred()assertions produce failure messages likeUnexpected error: <raw error>that give no indication of what the test was trying to do when it failed. A reader should be able to understand the failure without consulting the source code. Use Gomega's annotation argument to add context:Expect(err).NotTo(HaveOccurred(), "failed to create HCP cluster")Expect(err).NotTo(HaveOccurred(), "failed to verify a simple web app can run on the cluster")Expect(err).To(HaveOccurred(), "expected error when requesting serial console logs for non-existent VM")- Format strings are supported:
Expect(err).NotTo(HaveOccurred(), "failed to create node pool %q", nodePoolName) - The message should describe the intent (what we were trying to achieve), not merely restate the function name. For example, prefer
"failed to verify the cluster is healthy"over"VerifyHCPCluster returned error". - When a helper function returns an error, context should exist at both layers: the error itself should describe the proximal failure (e.g.
"route never returned a successful response: TLS error..."), and the gomega annotation should describe the higher-level intent (e.g."failed to verify a simple web app can run on the cluster").
- General assertion clarity: For any assertion where the failure message would be ambiguous (e.g. checking pointer values, map entries, or deeply nested fields), include an annotation string that identifies the value being checked and the expected condition.
- Struct comparisons: Use Gomega's
BeComparableTo(expected)instead ofEqual(expected)orBeEquivalentTo(expected)for structs, pointers to structs, and arrays, slices, or maps containing structs. It already usescmp.Equaland reportscmp.Diffon failure, so noWithTransform(cmp.Diff, BeEmpty())helper is needed. Keep a descriptive annotation, for exampleExpect(got).To(BeComparableTo(want), "get and list should agree"). Supply explicitcmpoptions when needed for unexported fields or custom equality; unlikeBeEquivalentTo, this matcher does not convert between types. - Static enforcement:
make verify-gomega-cmpdifftype-checkstest/e2eandtest/util/..., including unit tests and theE2Etestsentry point. It checks Gomega matcher calls even when nested or imported with aliases or dot imports. Scalar enums and collections of scalars may still useEqual/BeEquivalentTo. The check uses the expected argument's static type: interfaces can hide structs at runtime, so reviewers must still enforce this guidance for interface-typed values.
Logging
- Log message structure: Ensure log messages are direct, including the actual error message if an error occurs.
- Preferred Logger: For logging, use
ginkgo.GinkgoLogrto generate info or error entries in the output. This is the preferred logger. Alternatively, you can use theklogfrom thek8s.iomodule. To measure the execution time of a specific method, utilize theRecordTestStepfunction as adefercall within that method. - Ginkgo Writer: Use
ginkgo.GinkgoWriterto create a regular message in output.
Logging in Eventually/Polling Tests
When writing tests that poll until a condition is met (e.g. Eventually(...), wait.PollUntilContextTimeout, or any retry loop), follow these rules to produce output that is actionable when failures occur:
- Delta-only logging: Only emit a log line when the observed state changes between poll iterations. Logging the same message every 15 seconds creates noise and hides real transitions. Track the previous error/state string and compare before logging.
- Minimal state representation: Find the most compact way to represent what you observed. Prefer a single structured line over multi-line dumps during polling. For example:
found 2/3 nodes upgraded to release image v4.16.1; 1 node still on v4.15.8: [worker-2] - Expected vs. observed: Every log line during polling and every failure message must make it clear what was expected and what was actually seen. A reader who has never seen the test code should be able to understand the problem from the output alone.
- Consider dumping targeted state on failure: When a polling loop times out, it is strongly recommended to dump the status of the specific resources you were directly polling — e.g. if you were waiting for Machines to upgrade, dump those Machine statuses. Keep this narrowly scoped to avoid log clutter; broad cluster diagnostics should be left to
oc adm inspector equivalent artifact collection. The goal is that the most immediately relevant context appears inline next to the failure message. - Polling inside verifiers: Verifiers that poll require a timeout parameter (e.g.
verifiers.VerifyDaemonSetReady(ns, name, 10*time.Minute)); the timeout must be > 0. Verifiers that are inherently single-shot (e.g.VerifyPullSecretAuthData) do not accept a timeout. Each verifier runs polling inside its ownVerifymethod using shared helpers intest/util/verifiers/poll.go(delta-only logging, elapsed-time reporting, optional diagnostics). When polling completes, verifiers log actual wall-clock duration (success and timeout) viaGinkgoLogr(elapsedfield) andGinkgoWriter([VerifierName] succeeded after 1m23s). Tests should callExpect(verifier.Verify(ctx, cfg)).NotTo(HaveOccurred(), "intent message")— the annotation describes what the test was trying to do; the returned error carries the proximal failure (see Descriptive error checks above). Do not add test-levelEventuallyVerify-style wrappers or wrapper verifiers that rerun another verifier'sVerify. Verifiers with bespoke polling needs (e.g. exponential backoff or multi-phase waits) implement that logic directly inVerify, asVerifyAllClusterOperatorsAvailabledoes. - Think about failure before writing the test: Test authors must consider what happens when the test fails. Before submitting a test, intentionally trigger a failure and verify that the error output answers: what went wrong, what was expected, and what information does someone need to debug it? CI log readers and agentic debug flows should not need to open test source to understand intent.
Labels
- Importance:
- Critical: blockers for rollout
- High: significant problems affecting a feature
- Medium: less frequent scenarios
- Low: very specific scenarios or enhancements to user experience
- Positivity: Positive/negative test scenarios.
- Positive
- Negative
- ARO HCP environment: Test cases for one environment.
- IntegrationOnly
- StageOnly
- API compatibility:
- AroRpApiCompatible: This label indicates tests that are compatible with both the development environment (directly against ARO HCP RP without ARM) and higher environments (with ARM).
File Structure
- File naming convention: When naming new test files, avoid using the _test suffix. The Ginkgo OpenShift test extension specifically excludes files with this suffix during direct test imports.
ARO HCP Documentation
- Test developers should refer to the ARO HCP Documentation to understand their test cases.
Linting and go workspace
- Go Workspace: Module tests are managed within a Go workspace, which means that the
go.sumandgo.modfiles for all modules in the workspace maintain synchronized versions of their shared imported modules. The modules included in the Go Workspace are specified in thego.workfile. - Linting: The ARO HCP project utilizes
golangci-lintfor linting. This is executed for Pull Requests via theci-goGitHub workflow'slintstep. To perform local linting, run make lint from the repository's root directory. - Makefile: The
Makefilein the repository's root directory includes anall-tidyrule. This rule guarantees the correct implementation of the golang mechanisms and enforces the license header.
Azure Location
- When creating a new resource group, use the
tc.Location()method to retrieve the globally configured location from the environment variable instead of hardcoding Azure location names.
Tips and Tricks for Effective E2E Testing
- Randomize strings: To create unique resource names, use the
rand.String(n int)function from thek8s.io/apimachinery/pkg/util/randlibrary to generate random strings. A length of 6 characters is typically sufficient. - Descriptive Names: Use descriptive names for test files, test cases, bicep/arm deployments, and functions.
- Test case description: Maintain descriptions of specifications and tests as informative and comprehensive complete sentences.
- Development environment test cases: Ensure new negative test cases produce the same result in development and higher environments by running them in both. Do not use the label
AroRpApiCompatibleif the test case fails in the development environment.
Running or Filtering Specific E2E Tests
This project does NOT use Ginkgo's Focus (FDescribe, FIt, FEntry) to select tests.
Local: CLI-based filtering
Use the aro-hcp-tests binary to run individual tests or suites locally.
Build it first with make -C test, then:
# List available tests
./test/aro-hcp-tests list | jq '.[].name'
# Run a single test by name
./test/aro-hcp-tests run-test "Customer should be able to create an HCP cluster using bicep templates"
# Run a test suite
./test/aro-hcp-tests run-suite "integration/parallel"See test/e2e/README.md for full details on environment setup and available suites.
CI / PR validation: MustFilter in main.go
To run specific tests in a PR against Int, Stage, or Prod environments, use
specs.MustFilter() in test/cmd/aro-hcp-tests/main.go with CEL expressions.
This is the only way to select tests for CI runs in higher environments.
Locate the commented line and uncomment/modify it:
// specs = specs.MustFilter([]string{`name.contains("filter")`})Filter examples:
// Filter by name
specs = specs.MustFilter([]string{`name.contains("z-stream upgrade")`})
// Filter by label
specs = specs.MustFilter([]string{`labels.exists(l, l=="Positivity:Positive")`})
// Combine filters (name AND label)
specs = specs.MustFilter([]string{`name.contains("Cluster") && labels.exists(l, l=="Importance:Critical")`})WARNING: Always revert MustFilter edits before merging. Leaving a filter
in place silently skips tests in CI.
E2E Test Code Review Standards
This section defines the standards for reviewing E2E test code changes. These rules supplement the general project PR standards with E2E-specific requirements.
Build Tags and File Naming
- Build tag requirement: Only the main entry point file (
test/e2e/e2e_test.go) should have the//go:build E2Etestsbuild tag - File naming: E2E test files should NOT use the
_test.gosuffix (except for framework unit tests intest/util/framework/*_test.goand the entry pointtest/e2e/e2e_test.go)- ✅ Good:
cluster_create.go,admin_api.go,cluster_pullsecret.go - ❌ Bad:
cluster_create_test.go(Ginkgo OpenShift extension excludes these during imports) - Exception: Framework helper unit tests like
per_test_framework_test.goshould use_test.gosuffix
- ✅ Good:
Test Structure (Ginkgo/Gomega)
- Spec organization: Use clear hierarchies:
Describe→It(simple tests)Describe→Context→It(grouped scenarios)- Multiple nested
Describeblocks for complex organization
- Descriptive test names: Write complete, readable sentences that form a narrative when concatenated
- Example: "Get HCPOpenShiftCluster" → "Fails to get a nonexistent cluster with a Not Found error"
- Reads as: "Get HCPOpenShiftCluster fails to get a nonexistent cluster with a Not Found error"
- Use
By()for test steps: Document critical steps withinItblocks usingBy("step description") - Context parameter: All
Itblocks must acceptcontext.Contextas their first parameter- ✅ Good:
It("should create cluster", func(ctx context.Context) { ... }) - ❌ Bad:
It("should create cluster", func() { ctx := context.Background(); ... })
- ✅ Good:
Required Test Labels
Every test MUST include appropriate labels from these categories:
Test Environment Labels (MANDATORY - exactly one):
labels.RequireNothing: Per-test cluster tests (creates own cluster) — preferred approachlabels.RequireHappyPathInfra: Per-run cluster tests (uses pre-created cluster)labels.UpgradeInPlace: End-to-end in-place upgrade tests — exclusively selected by theupgrade/in-placesuite and automatically excluded from all other suites. Use for tests that invoke the Region entrypoint pipeline against pre-provisioned regional infrastructure and must only run in dev environments. See Upgrade Barrier for the parallel coordination pattern.
Importance Labels (MANDATORY - exactly one):
labels.Critical: Blockers for rolloutlabels.High: Significant problems affecting a featurelabels.Medium: Less frequent scenarioslabels.Low: Very specific scenarios or enhancements
Positivity Labels (MANDATORY - exactly one):
labels.Positive: Happy path test scenarioslabels.Negative: Error/failure test scenarios
Optional Usage Labels:
labels.CreateCluster: Cluster creation related testslabels.SetupValidation: Pre-test validationlabels.TeardownValidation: Post-test validationlabels.CoreInfraService: Gates rollout of ARO-HCP componentslabels.AroRpApiCompatible: Can run against both ARO HCP RP and ARM endpoint (dev environment compatible)labels.AllowRetry: Marks a test as safe to auto-retry during an EV2 Stage/Prod gating run when it fails due to a known, actively tracked issue. Temporary by design (tracked in AROSLSRE-1721): every use must have an owner and a tracking issue in an inline comment, and must be removed once the underlying issue is fixed.
Optional Environment Labels:
labels.DevelopmentOnlylabels.IntegrationOnlylabels.StageAndProdOnly
Resource Demand Labels (required on every spec):
labels.MIContainers(N): Declares how many managed identity containers the test needs (0 for tests that don't use MI containers). Enforced byverify-mi-containersCI check and runtime scheduler.
Speed Labels (when applicable):
labels.Slow: For tests that take significantly longer than average
Example:
It("should create cluster successfully",
labels.RequireNothing,
labels.Critical,
labels.Positive,
labels.CreateCluster,
labels.MIContainers(1),
func(ctx context.Context) {
// test code
})Client Usage Patterns
HCP SDK Client:
- Use
tc.Get20240610ClientFactoryOrDie(ctx)to get client factory - Chain to specific clients:
.NewHcpOpenShiftClustersClient(),.NewHcpOpenShiftClusterNodePoolsClient() - Always use context with timeout for async operations
Kubernetes Client:
- Use
framework.GetAdminRESTConfigForHCPCluster20240610()to get REST config (10-minute timeout) - Use standard
client-golibraries for K8s operations - Verifiers are in
test/util/verifiers/and implementHostedClusterVerifierinterface
Verifier Patterns
- Interface: Implement
HostedClusterVerifierinterface withName()andVerify()methods - Location: All verifiers belong in
test/util/verifiers/
Context and Cancellation
- Always use context: Every test should accept and use
context.Context - Propagate context: Pass context to all SDK calls, framework helpers, and verifiers
- Respect cancellation: Don't ignore context cancellation in long-running operations
Pooled Identities
- Check if enabled: Use
tc.UsePooledIdentities()to check if pooled identities are enabled - Assign containers: Call
tc.AssignIdentityContainers(ctx, count, timeout)before resource creation- Example:
tc.AssignIdentityContainers(ctx, 1, framework.IdentityContainerAssignmentRetryInterval)
- Example:
- Error handling: Expect assignment to succeed:
Expect(err).NotTo(HaveOccurred(), "failed to assign pooled identity containers")
Error Handling in Negative Tests
- Explicit error expectations: Negative tests must assert on specific error messages
- ✅ Good:
Expect(err.Error()).To(ContainSubstring("The location property is required")) - ❌ Bad:
Expect(err).ToNot(BeNil())(too vague)
- ✅ Good:
- Case-insensitive matching: Use
strings.ToLower()for error message comparisons when case might vary
Code Organization
Helper functions should be placed in appropriate test/util/ modules:
test/util/framework/: HCP client helpers, cluster operationstest/util/verifiers/: Kubernetes verifierstest/util/labels/: Label definitionstest/util/timing/: Timing utilitiestest/util/cleanup/: Cleanup helpers
Shared test artifacts should use //go:embed test-artifacts pattern and embed.FS for embedded resources.
Test Fixtures
After adding tests with environment-specific behavior:
- Run
make update-go-fixturesormake updateintest/directory - Required to ensure test environment detection works correctly
Development Environment Compatibility
- AroRpApiCompatible label: Only use if test produces same results in dev AND higher environments
- Test in both environments: Run negative tests in both dev and integration/higher to verify behavior matches
- Do NOT label if dev-incompatible: Remove label if test fails in development environment
Common Anti-Patterns to Reject
The following patterns should be rejected in code review:
❌ Missing assertion messages: Bare Expect().NotTo(BeNil()) or Expect(err).To(HaveOccurred())
❌ Hardcoded timeouts: Using literals instead of named constants from constants.go (except for test-specific timeouts used only once)
❌ Missing labels: Tests without environment, importance, or positivity labels
❌ Hardcoded locations: "eastus" instead of tc.Location()
❌ Non-unique names: Static resource names that will collide in parallel runs
❌ Focused tests: Using FIt, FDescribe, or FEntry
❌ Noisy polling: Logging same message every iteration of Eventually()
❌ Vague error assertions: Checking err != nil without validating error content in negative tests
❌ Missing context: It() blocks without context.Context parameter
❌ Wrong file suffix: Using _test.go for E2E test files (except framework unit tests)
❌ Missing By() steps: Complex tests without documented steps
❌ Abandoned resources: Creating resources outside TestContext without explicit cleanup
Upgrade Barrier and Coordinator
framework.UpgradeBarrier and framework.UpgradeCoordinator work together to coordinate parallel UpgradeInPlace specs so that:
- Every spec provisions its own cluster and captures a baseline independently (full parallelism).
- All specs check in to the barrier. The UpgradeCoordinator — running in the long-lived parent
run-suiteprocess — waits for all specs to check in, then invokes the Region entrypoint pipeline viarun.RunPipeline. - While the upgrade runs, every spec can independently validate its own cluster (during-upgrade validation).
- After the upgrade completes (or fails), every spec independently validates its own cluster (post-upgrade validation).
Architecture
Parent process (run-suite)
└─ BeforeAll ──► NewUpgradeCoordinator() ──► go coord.Run(ctx)
│
├─ waitSettled (polls state file)
├─ run.RunPipeline (Region entrypoint)
└─ markUpgradeDone → state file
Worker process per spec (run-test)
└─ Spec A ──► provision ──► CheckIn() ──► Consistently(validate, upgradeDoneCtx) ──► WaitForUpgrade() ──► post-upgrade validate
└─ Spec B ──► provision ──► CheckIn() ──► Consistently(validate, upgradeDoneCtx) ──► WaitForUpgrade() ──► post-upgrade validate
└─ Spec C ──► FAIL ──────── DeferCleanup abort (increments aborted_count; coordinator unblocks)There is no runner election — all specs are identical. The upgrade runs in the parent process and is completely independent of individual spec success or failure.
How it works
UpgradeCoordinator (parent process):
- Created synchronously in
BeforeAll(guarded to the parentrun-suiteprocess only) viaNewUpgradeCoordinator(), which writes the initial state file before any worker is dispatched. Run(ctx)is launched in a goroutine. It polls untilchecked_in + aborted_count >= total(settlement), then callsrunRegionEntrypoint, then writesUpgradeDone+ any error to the state file.- If all specs aborted before checking in,
Runreturns early without running the pipeline. - Logs go to
os.Stderrvia alogr/stdrlogger (set viaSetUpgradeCoordinatorLoggerinmain.go) — never to Ginkgo's captured output.
UpgradeBarrier (worker processes):
- Created per-spec via
NewUpgradeBarrier(). All instances share the same lock file (os.TempDir()/upgrade-barrier.lock) and state file (underARTIFACT_DIRoros.TempDir()). CheckIn(ctx)atomically incrementschecked_inand returns immediately — it does not wait for settlement. It also starts a background goroutine that polls forUpgradeDoneand cancels the returnedupgradeDoneCtxwhen the coordinator signals completion.WaitForUpgrade(ctx)blocks untilUpgradeDone=trueand returns the coordinator's upgrade error (if any).CheckInAndWait(ctx)is a convenience wrapper combiningCheckIn+WaitForUpgradefor specs that do not need during-upgrade validation.- If a spec fails before
CheckIn, aDeferCleanupregistered byNewUpgradeBarrierincrementsaborted_countso the coordinator is not left waiting for a participant that will never arrive.
Timing
| Timeout | Value | Meaning |
defaultSettleTimeout | 45 min | How long the coordinator waits for all specs to check in or abort |
defaultUpgradeRunTimeout | 50 min | Budget for the Region entrypoint pipeline itself |
defaultUpgradeTimeout | 60 min | How long specs wait in WaitForUpgrade for the coordinator's signal (10 min buffer over run timeout) |
Stale state detection
The state file carries the parent PID of the suite runner as run_id. All parallel workers in the same invocation share the same parent PID, so they recognise the existing state file as their own. A new suite invocation gets a different PID:
- The coordinator resets any stale file with a different
run_idininitState(). - A worker (barrier) errors loudly if it finds a mismatched
run_id— this signals that the coordinator did not initialise the state before the worker was dispatched, which should never happen in a correct setup.
In Prow each job runs in a fresh pod, so there is no leakage between runs. For local runs os.TempDir() is a fixed path, but local runs are always single-spec (no parallelism), which further narrows the risk.
CI setup
ARTIFACT_DIR is optional. When set, the state file is written there and collected as a CI artifact. When absent (local runs), it falls back to os.TempDir().
Required environment variables for local runs (in addition to the usual AROHCP_ENV, LOCATION, DEPLOY_ENV, KUBECONFIG):
export GITHUB_ACTIONS=true # makes templatize's cmdutils.GetAzureTokenCredentials use az CLI credentials
# instead of workload-identity tokens (which are only available in CI)AROHCP_ENV=development controls the test framework's own Azure credential (subscription/resource-group
lookups done by the test helpers). GITHUB_ACTIONS controls the credential used by the templatize pipeline
when it performs its own subscription lookup. Both must be set for a fully local run of upgrade/in-place.
The total number of UpgradeInPlace specs is computed dynamically in main.go's setupCli() — after BuildExtensionTestSpecsFromOpenShiftGinkgoSuite() builds the spec list, the code counts specs with labels.UpgradeInPlace and calls framework.SetUpgradeInPlaceSpecCount(n). The same count drives both the suite Parallelism and NewUpgradeBarrier(). No constant to maintain — adding a new UpgradeInPlace spec automatically updates both.
Invocation
run-test is not supported for upgrade specs. The UpgradeCoordinator only starts in the long-lived run-suite process; a direct run-test invocation will fail immediately with a RunID mismatch error. Always use run-suite or CI to execute upgrade specs.
Typical It-block skeleton
tc := framework.NewTestContext()
// NewUpgradeBarrier must be called after NewTestContext so its abort DeferCleanup
// runs before tc teardown in FILO order, unblocking other specs before resource cleanup.
// The total spec count was set by main.go's setupCli() via SetUpgradeInPlaceSpecCount.
barrier, err := framework.NewUpgradeBarrier()
Expect(err).NotTo(HaveOccurred(), "failed to create upgrade barrier")
// ... provision cluster, capture baseline ...
// Option A: no during-upgrade validation — one call handles check-in and waiting.
err = barrier.CheckInAndWait(ctx)
Expect(err).NotTo(HaveOccurred(), "upgrade phase failed")
// Option B: during-upgrade validation — use CheckIn + WaitForUpgrade separately.
upgradeDoneCtx, err := barrier.CheckIn(ctx)
Expect(err).NotTo(HaveOccurred(), "failed to check in to upgrade barrier")
Consistently(func(g Gomega) {
// validate cluster is stable while upgrade runs
}, upgradeDoneCtx, rolloutPollInterval).Should(Succeed(), "cluster unstable during upgrade")
err = barrier.WaitForUpgrade(ctx)
Expect(err).NotTo(HaveOccurred(), "upgrade phase failed")
// ... post-upgrade validation ...Code Review Checklist
When reviewing E2E test PRs, verify:
- All base PR standards from
../CONTRIBUTING.mdare met - Test files use correct naming convention (no
_test.gosuffix for E2E tests) - All tests have required labels (environment, importance, positivity)
- All assertions include descriptive messages
- Timeouts use named constants from
constants.go(for shared durations) or are local literals (for test-specific timeouts) - Resource names are unique (using
rand.String()or framework helpers) - TestContext is used for resource group creation (auto-cleanup)
- No hardcoded Azure locations (use
tc.Location()) - API version suffixes are explicit in framework helper names
- Context is properly propagated through all operations
- Polling/Eventually blocks use delta-only logging
- Negative tests assert on specific error messages
- No Focus helpers (
FIt,FDescribe, etc.) are used - Test fixtures updated if needed (
make update-go-fixtures) - Tests are self-contained and don't depend on other test state
By()statements document critical test steps- Cleanup is properly handled (automatic via TestContext or explicit)
Does it work?
Reviews from people and from AI agents that ran it: what they used it for, and whether it worked.
No reviews yet
People and AI agents can review whether this works in practice. Say what you used it for, and whether it worked.
- It worked
- Partly
- It didn't
Using an agent? It can post a review for you after it has run the file: the MCP tool registry_write, action report. How to connect one.
Your trail
Files you open will collect here, so you can find them again.
Open two or more, and you can remix the rules you like from each into one list. Kept in this browser only.
Now do this for your own.
Bring your CLAUDE.md, AGENTS.md or skills. agentleFS shows which of your rules are common, which are yours and which only fit one project, and keeps one version your agents read everywhere.

