Skip to content

Commit ce52d8e

Browse files
committed
refactor(e2e): prepare independent component step extractions
Extract port-forward and metrics helpers before moving catalogd steps. Make recording hooks explicit in platform and legacy suites, and document the incremental ownership boundary. Keep cross-component object lookups shared so component branches can build and land independently. Refs: OPRUN-4784 Signed-off-by: Fabricio Aguiar <fabricio.aguiar@gmail.com> rh-pre-commit.version: 2.3.2 rh-pre-commit.check-secrets: ENABLED
1 parent 348df94 commit ce52d8e

8 files changed

Lines changed: 167 additions & 132 deletions

File tree

‎test/e2e/README.md‎

Lines changed: 43 additions & 21 deletions
Original file line numberDiff line numberDiff line change
@@ -19,6 +19,9 @@ non-technical stakeholders.
1919

2020
## Project Structure
2121

22+
Component step packages are introduced incrementally. The layout below shows
23+
their intended ownership after all component extractions land.
24+
2225
```
2326
test/
2427
├── e2e/
@@ -33,8 +36,12 @@ test/
3336
└── internal/
3437
├── e2e/
3538
│ ├── runner.go # Godog options, scenario selection, summary wiring
36-
│ ├── steps/ # All existing step definitions and hooks
39+
│ ├── steps/ # Shared world, hooks, catalog, resource, RBAC, and condition helpers
3740
│ │ └── testdata/ # RBAC and resource templates
41+
│ ├── operator-controller/steps/ # ClusterExtension lifecycle and integration assertions
42+
│ ├── catalogd/steps/ # HA/proxy/TLS steps and restoration hooks
43+
│ ├── object-controller/steps/ # ClusterObjectSet/Deployment assertions
44+
│ ├── platform/steps/ # Demo steps and recording
3845
│ └── support-bundle.yaml # Shared diagnostics
3946
└── summary/ # Summary generation and embedded templates
4047
```
@@ -43,7 +50,7 @@ test/
4350

4451
### 1. Test Runner (`operator-controller/suite_test.go`)
4552

46-
The component entry point registers the full shared step set and hooks, then calls
53+
The component entry point registers shared steps, hooks, and its component steps, then calls
4754
`e2e.Run` from `test/internal/e2e` with its feature directory. The shared runner configures Godog options,
4855
scenario selection, and summary generation.
4956

@@ -53,10 +60,22 @@ controller unit tests live under `internal/testutil`, which is accessible throug
5360
the repository.
5461

5562
Features follow the ownership in the [per-component suite design](../../docs/designs/e2e-per-component.md).
56-
Each component has a thin entry point that still registers the full shared step set;
57-
step ownership is separated in the next stage. The newer `cos_*`, `cod_*`, and
58-
`group` features belong to object-controller. Feature contents and step behavior
59-
are unchanged, including ClusterExtension integration assertions in object features.
63+
The newer `cos_*`, `cod_*`, and `group` features belong to object-controller.
64+
Suites register additional component steps when existing features contain integration
65+
assertions: operator-controller uses object assertions, object-controller retains
66+
ClusterExtension integration coverage, and catalogd proxy tests use ClusterExtension
67+
steps. Platform registers ClusterExtension steps for demos. Feature contents,
68+
scenario names, tags, and assertions are unchanged.
69+
70+
`test/internal/e2e/steps` owns `World` and the `Scenario(ctx)` accessor, generic resource and
71+
condition helpers, catalog/registry prerequisites, RBAC templates, and cleanup.
72+
`ListClusterObjectSetsInGroup` and `ResolveObjectRef` remain shared because
73+
both ClusterExtension and ClusterObjectSet assertions consume them.
74+
Catalogd owns deployment restoration and proxy state. Platform owns recording;
75+
shared helpers observe commands through an optional `CommandRecorder` interface.
76+
Pass extra lifecycle registration to `sharedsteps.RegisterHooks` to keep suite hooks
77+
between shared scenario setup and cleanup. The upgrade helpers remain shared because
78+
catalogd HA scenarios also consume component readiness and catalog reconciliation steps.
6079

6180
### 2. Feature Files (`operator-controller/features/*.feature`)
6281

@@ -112,7 +131,7 @@ Feature: Install ClusterExtension
112131
And ClusterExtension is available
113132
```
114133

115-
### 3. Step Definitions (`test/internal/e2e/steps/steps.go`)
134+
### 3. Step Definitions (`test/internal/e2e/<component>/steps/steps.go`)
116135

117136
Go functions that implement the steps defined in feature files. Each step is registered with a regex pattern that
118137
matches the Gherkin text.
@@ -121,9 +140,8 @@ matches the Gherkin text.
121140

122141
```go
123142
func RegisterSteps(sc *godog.ScenarioContext) {
124-
sc.Step(`^OLM is available$`, OLMisAvailable)
125143
sc.Step(`^bundle "([^"]+)" is installed in version "([^"]+)"$`, BundleInstalled)
126-
sc.Step(`^ClusterExtension is applied$`, ResourceIsApplied)
144+
sc.Step(`^ClusterExtension is applied$`, shared.ResourceIsApplied)
127145
// ... more steps
128146
}
129147
```
@@ -132,7 +150,7 @@ sc.Step(`^ClusterExtension is applied$`, ResourceIsApplied)
132150

133151
Status assertions must read metadata and status from the same API response and
134152
require the asserted condition's `observedGeneration` to equal `metadata.generation`.
135-
Use `waitForCondition` for condition checks. Bundle metadata uses the `Installed`
153+
Use `shared.WaitForCondition` for condition checks. Bundle metadata uses the `Installed`
136154
condition, and COS phase digests and object counts use the `Ready` condition to
137155
verify that the status reflects the current spec. Deployments instead expose
138156
`status.observedGeneration` at the resource level.
@@ -146,18 +164,18 @@ That step accepts any current-generation `Progressing` status or reason, whereas
146164

147165
```go
148166
func BundleInstalled(ctx context.Context, name, version string) error {
149-
sc := scenarioCtx(ctx)
150-
waitFor(ctx, func() bool {
151-
v, err := k8sClient(ctx, "get", "clusterextension", sc.clusterExtensionName, "-o", "json")
167+
sc := shared.Scenario(ctx)
168+
shared.WaitFor(ctx, func() bool {
169+
v, err := shared.K8sClient(ctx, "get", "clusterextension", sc.ClusterExtensionName, "-o", "json")
152170
if err != nil {
153171
return false
154172
}
155173
var ext ocv1.ClusterExtension
156174
if err := json.Unmarshal([]byte(v), &ext); err != nil {
157175
return false
158176
}
159-
installed := currentCondition(ext.Generation, ext.Status.Conditions, ocv1.TypeInstalled)
160-
return conditionMatches(installed, metav1.ConditionTrue, nil, nil) &&
177+
installed := shared.CurrentCondition(ext.Generation, ext.Status.Conditions, ocv1.TypeInstalled)
178+
return shared.ConditionMatches(installed, metav1.ConditionTrue, nil, nil) &&
161179
ext.Status.Install.Bundle.Name == name && ext.Status.Install.Bundle.Version == version
162180
})
163181
return nil
@@ -199,7 +217,7 @@ Feature: Your Feature Name
199217

200218
### 2. Implement Step Definitions
201219

202-
Add step implementations in `test/internal/e2e/steps/steps.go`:
220+
Add component assertions in `test/internal/e2e/<component>/steps/`; add reusable prerequisites and helpers in `test/internal/e2e/steps/`:
203221

204222
```go
205223
func RegisterSteps(sc *godog.ScenarioContext) {
@@ -208,7 +226,7 @@ func RegisterSteps(sc *godog.ScenarioContext) {
208226
}
209227

210228
func YourStepFunction(ctx context.Context, param string) error {
211-
sc := scenarioCtx(ctx)
229+
sc := shared.Scenario(ctx)
212230
// Implementation
213231
return nil
214232
}
@@ -230,7 +248,7 @@ Use these variables in YAML templates:
230248
- `${NAME}`: Scenario-specific ClusterExtension name (e.g., `ce-123`)
231249
- `${COS_NAME}`: Scenario-specific ClusterObjectSet name (e.g., `cos-123`; for applying ClusterObjectSets directly)
232250
- `${TEST_NAMESPACE}`: Scenario-specific namespace (e.g., `ns-123`)
233-
- `${SCENARIO_ID}`: Unique scenario identifier used for resource name isolation
251+
- `${SCENARIO_ID}`: Feature-scoped scenario identifier used for resource isolation across concurrent Go suites
234252
- `${PACKAGE:<name>}`: Parameterized package name (e.g., `${PACKAGE:test}` expands to `test-<scenario-id>`)
235253
- `${CATALOG:<name>}`: Catalog resource name (e.g., `${CATALOG:test}` expands to `test-catalog-<scenario-id>`)
236254

@@ -427,8 +445,12 @@ go test -count=1 ./test/e2e/operator-controller/... -args --log.debug --k8s.cli=
427445

428446
Each scenario runs in its own namespace with unique resource names, ensuring complete isolation:
429447

430-
- Namespace: `ns-{scenario-id}`
431-
- ClusterExtension: `ce-{scenario-id}`
448+
- Namespace: `ns-{feature-hash}-{godog-id}`
449+
- ClusterExtension: `ce-{feature-hash}-{godog-id}`
450+
451+
Godog restarts numeric IDs in each process. The feature hash prevents collisions
452+
between concurrent component suites and stays stable when a feature moves. Feature
453+
and scenario annotations retain their existing values.
432454

433455
### 2. Test-Identifying Annotations
434456

@@ -476,7 +498,7 @@ When ClusterExtension is applied
476498
All asynchronous operations use `waitFor` with consistent timeout (300s) and tick (1s):
477499

478500
```go
479-
waitFor(ctx, func() bool {
501+
shared.WaitFor(ctx, func() bool {
480502
// Check condition
481503
return conditionMet
482504
})

‎test/e2e/features_test.go‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -42,6 +42,6 @@ func TestMain(m *testing.M) {
4242
}, func(sc *godog.ScenarioContext) {
4343
steps.RegisterSteps(sc)
4444
steps.RegisterDemoSteps(sc)
45-
steps.RegisterHooks(sc)
45+
steps.RegisterHooks(sc, steps.RegisterAsciiCastHooks)
4646
}))
4747
}

‎test/e2e/platform/suite_test.go‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -16,6 +16,6 @@ func TestMain(m *testing.M) {
1616
}, func(sc *godog.ScenarioContext) {
1717
steps.RegisterSteps(sc)
1818
steps.RegisterDemoSteps(sc)
19-
steps.RegisterHooks(sc)
19+
steps.RegisterHooks(sc, steps.RegisterAsciiCastHooks)
2020
}))
2121
}

‎test/internal/e2e/steps/demo_steps.go‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -104,7 +104,7 @@ func ensureCatalogPortForward(ctx context.Context) (string, error) {
104104
port = 8443
105105
}
106106

107-
addr, cleanup, err := portForward(ctx, ns, target, port)
107+
addr, cleanup, err := PortForward(ctx, ns, target, port)
108108
if err != nil {
109109
return "", fmt.Errorf("failed to start catalog port-forward to %s: %w", target, err)
110110
}

‎test/internal/e2e/steps/hooks.go‎

Lines changed: 5 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -110,10 +110,13 @@ func init() {
110110
flagSet.BoolVar(&devMode, "log.debug", false, "print debug log level")
111111
}
112112

113-
func RegisterHooks(sc *godog.ScenarioContext) {
113+
// RegisterHooks installs shared lifecycle hooks, with optional suite hooks between setup and cleanup.
114+
func RegisterHooks(sc *godog.ScenarioContext, hooks ...func(*godog.ScenarioContext)) {
114115
sc.Before(CheckFeatureTags)
115116
sc.Before(CreateScenarioContext)
116-
RegisterAsciiCastHooks(sc)
117+
for _, register := range hooks {
118+
register(sc)
119+
}
117120

118121
sc.After(ScenarioCleanup)
119122
}
Lines changed: 91 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,91 @@
1+
package steps
2+
3+
import (
4+
"context"
5+
"encoding/json"
6+
"fmt"
7+
"net"
8+
"os"
9+
"os/exec"
10+
"strings"
11+
12+
corev1 "k8s.io/api/core/v1"
13+
)
14+
15+
func randomAvailablePort() (int, error) {
16+
l, err := net.Listen("tcp", "127.0.0.1:0")
17+
if err != nil {
18+
return 0, err
19+
}
20+
defer l.Close()
21+
return l.Addr().(*net.TCPAddr).Port, nil
22+
}
23+
24+
// portForward starts a kubectl port-forward to target (e.g. "service/foo" or "pod/bar")
25+
// in the given Namespace, mapping a random local port to remotePort. It returns the
26+
// local address and a cleanup function. The caller is responsible for calling cleanup.
27+
func PortForward(ctx context.Context, ns, target string, remotePort int32) (string, func(), error) {
28+
localPort, err := randomAvailablePort()
29+
if err != nil {
30+
return "", nil, fmt.Errorf("failed to find a free local port: %w", err)
31+
}
32+
33+
pfCmd := exec.Command(K8sCLI, "port-forward", "-n", ns, //nolint:gosec
34+
target, fmt.Sprintf("%d:%d", localPort, remotePort))
35+
pfCmd.Env = append(os.Environ(), fmt.Sprintf("KUBECONFIG=%s", KubeconfigPath))
36+
if err := pfCmd.Start(); err != nil {
37+
return "", nil, fmt.Errorf("failed to start port-forward to %s: %w", target, err)
38+
}
39+
40+
cleanup := func() {
41+
if p := pfCmd.Process; p != nil {
42+
_ = p.Kill()
43+
_ = pfCmd.Wait()
44+
}
45+
}
46+
47+
if rec := CommandRecorderFromContext(ctx); rec != nil {
48+
rec.RecordCustom(
49+
fmt.Sprintf("%s port-forward -n %s %s %d:%d &", K8sCLI, ns, target, localPort, remotePort),
50+
"", "",
51+
)
52+
}
53+
54+
addr := fmt.Sprintf("127.0.0.1:%d", localPort)
55+
return addr, cleanup, nil
56+
}
57+
58+
// getMetricsService returns the full Service object for the named component's metrics service.
59+
// The Namespace is available via svc.Namespace.
60+
func GetMetricsService(component string) (*corev1.Service, error) {
61+
serviceName := fmt.Sprintf("%s-service", component)
62+
serviceNs, err := K8sClient(context.Background(), "get", "service", "-A", "-o",
63+
fmt.Sprintf(`jsonpath={.items[?(@.metadata.name=="%s")].metadata.namespace}`, serviceName))
64+
if err != nil {
65+
return nil, fmt.Errorf("failed to find namespace for service %s: %w", serviceName, err)
66+
}
67+
serviceNs = strings.TrimSpace(serviceNs)
68+
if serviceNs == "" {
69+
return nil, fmt.Errorf("service %s not found in any namespace", serviceName)
70+
}
71+
72+
raw, err := K8sClient(context.Background(), "get", "service", "-n", serviceNs, serviceName, "-o", "json")
73+
if err != nil {
74+
return nil, fmt.Errorf("failed to get service %s: %w", serviceName, err)
75+
}
76+
var svc corev1.Service
77+
if err := json.Unmarshal([]byte(raw), &svc); err != nil {
78+
return nil, fmt.Errorf("failed to unmarshal service %s: %w", serviceName, err)
79+
}
80+
return &svc, nil
81+
}
82+
83+
// metricsPort returns the port number of the port named "metrics" on the given service.
84+
func MetricsPort(svc *corev1.Service) (int32, error) {
85+
for _, p := range svc.Spec.Ports {
86+
if p.Name == "metrics" {
87+
return p.Port, nil
88+
}
89+
}
90+
return 0, fmt.Errorf("no port named 'metrics' found on service %s", svc.Name)
91+
}

0 commit comments

Comments
 (0)