Repository navigation
refactor: use testutils in productcatalog - #2699
Conversation
📝 WalkthroughWalkthroughThis change refactors test files for the product catalog's addon and planaddon modules. It replaces specialized, local test utility packages and manual test environment setups with a centralized, shared test utilities package ( Changes
Possibly related PRs
Warning There were issues while running some tools. Please review the errors and either fix the tool's configuration or disable the tool if it's a critical failure. 🔧 golangci-lint (1.64.8)Error: you are using a configuration file for golangci-lint v2 with golangci-lint v1: please use golangci-lint v2 ✨ Finishing Touches
Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out. 🪧 TipsChatThere are 3 ways to chat with CodeRabbit:
Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments. CodeRabbit Commands (Invoked using PR comments)
Other keywords and placeholders
CodeRabbit Configuration File (
|
There was a problem hiding this comment.
Actionable comments posted: 4
🔭 Outside diff range comments (1)
openmeter/productcatalog/planaddon/service/service_test.go (1)
308-317:⚠️ Potential issueWrong variable checked – the test never asserts the value just fetched
require.NotNilfvalidatesaddonV1, but the value that was just retrieved isgetPlanAddon.
As written, the assertion is meaningless becauseaddonV1was already verified earlier.- require.NotNilf(t, addonV1, "plan add-on assignment must not be nil") + require.NotNilf(t, getPlanAddon, "plan add-on assignment must not be nil")Make the same replacement for the
ByKeysub‑test below.
🧹 Nitpick comments (6)
openmeter/productcatalog/testutils/addon.go (1)
14-34: Accepting variadicRateCardis a good improvement, consider guarding against an empty sliceThe new signature is flexible, but a
CreateAddonInputwithRateCards == nil(or an empty slice) will pass compilation and could surface as a validation error deeper in the stack.
If “no rate‑cards” is invalid for an addon, add a quick guard:func NewTestAddon(t *testing.T, namespace string, rateCards ...productcatalog.RateCard) addon.CreateAddonInput { t.Helper() + require.Greater(t, len(rateCards), 0, "a test addon should contain at least one rate‑card")(or
assert, depending on your conventions).
This keeps the helper honest and prevents silently creating unusable fixtures.openmeter/productcatalog/addon/service/service_test.go (5)
24-25: Avoid scattering “magic” cadence constants – reuse test‑wide helpers
MonthPeriodis already declared inproductcatalog/testutils/date.go(or can easily live there). Duplicating it here risks the inevitable “29/30/31‑day month” drift between tests.- var MonthPeriod = isodate.FromDuration(30 * 24 * time.Hour) +// testutils.DateMonthPeriod provides a canonical 30‑day month for tests +var MonthPeriod = pctestutils.DateMonthPeriod
26-34: Make the top‑level test concurrently friendly & self‑cleaning
- Add
t.Parallel()at the start of every sub‑test to improve CI throughput.env.Close(t)is great, but thecontext.WithCancelcreated above is never propagated to the env; prefercontext.Background()or passctxintoNewTestEnvso that the DB/containers also respect the cancellation.-func TestAddonService(t *testing.T) { +func TestAddonService(t *testing.T) { + t.Parallel() ctx, cancel := context.WithCancel(context.Background()) - defer cancel() + defer cancel() - env := pctestutils.NewTestEnv(t) + env := pctestutils.NewTestEnv(t, pctestutils.WithContext(ctx))
46-57: Simplify meter listing – no need for manual pagination in tests
All meters are written in a singleReplaceMeterscall, and the test never exercises paging logic. CallingListMeterswith an artificially large page size is noisy and future‑fragile. Prefer eitherenv.Meter.ListAllMeters(ctx, namespace)helper or a direct repository call without pagination.
70-115: Inline monster literals hamper readability – extract to helper
The 40‑lineUsageBasedRateCardliteral obscures test intent (“create addon V1”). Moving it to a named helper (e.g.pctestutils.NewRateCardForFeature(t, feature, MonthPeriod)) would shrink this test body and improve maintainability.
254-264: Assert the exact failure when publishing mis‑aligned rate cards
The test only checks that an error occurred. To guard against unrelated regressions, assert the specific sentinel (productcatalog.ErrRateCardCadenceMismatch?) or at least the error message substring.require.ErrorIs(t, err, productcatalog.ErrRateCardCadenceMismatch)
📜 Review details
Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro
📒 Files selected for processing (11)
openmeter/productcatalog/addon/adapter/adapter_test.go(1 hunks)openmeter/productcatalog/addon/service/service_test.go(6 hunks)openmeter/productcatalog/planaddon/adapter/adapter_test.go(9 hunks)openmeter/productcatalog/planaddon/service/service_test.go(10 hunks)openmeter/productcatalog/planaddon/testutils/addon.go(0 hunks)openmeter/productcatalog/planaddon/testutils/env.go(0 hunks)openmeter/productcatalog/planaddon/testutils/feature.go(0 hunks)openmeter/productcatalog/planaddon/testutils/meters.go(0 hunks)openmeter/productcatalog/planaddon/testutils/namespace.go(0 hunks)openmeter/productcatalog/planaddon/testutils/plan.go(0 hunks)openmeter/productcatalog/testutils/addon.go(2 hunks)
💤 Files with no reviewable changes (6)
- openmeter/productcatalog/planaddon/testutils/plan.go
- openmeter/productcatalog/planaddon/testutils/addon.go
- openmeter/productcatalog/planaddon/testutils/feature.go
- openmeter/productcatalog/planaddon/testutils/meters.go
- openmeter/productcatalog/planaddon/testutils/env.go
- openmeter/productcatalog/planaddon/testutils/namespace.go
🧰 Additional context used
🧬 Code Graph Analysis (2)
openmeter/productcatalog/testutils/addon.go (1)
openmeter/productcatalog/addon/service.go (1)
CreateAddonInput(98-101)
openmeter/productcatalog/addon/service/service_test.go (10)
pkg/isodate/date.go (1)
FromDuration(120-122)openmeter/productcatalog/testutils/namespace.go (1)
NewTestNamespace(17-17)openmeter/productcatalog/testutils/meters.go (1)
NewTestMeters(13-81)openmeter/productcatalog/testutils/feature.go (1)
NewTestFeatureFromMeter(22-33)openmeter/productcatalog/testutils/addon.go (1)
NewTestAddon(14-34)openmeter/productcatalog/ratecard.go (3)
RateCards(472-472)UsageBasedRateCard(347-353)RateCardMeta(52-83)openmeter/productcatalog/entitlement.go (3)
EntitlementTemplate(34-39)NewEntitlementTemplateFrom(230-246)BooleanEntitlementTemplate(393-396)openmeter/productcatalog/addon/addon.go (1)
Addon(12-20)openmeter/productcatalog/addon/assert.go (1)
AssertAddonCreateInputEqual(13-25)openmeter/productcatalog/addon/service.go (5)
GetAddonInput(227-240)UpdateAddonInput(122-145)PublishAddonInput(274-279)ArchiveAddonInput(317-323)DeleteAddonInput(260-262)
⏰ Context from checks skipped due to timeout of 90000ms (6)
- GitHub Check: Lint
- GitHub Check: E2E
- GitHub Check: Developer environment
- GitHub Check: CI
- GitHub Check: Test
- GitHub Check: Analyze (go)
🔇 Additional comments (3)
openmeter/productcatalog/addon/adapter/adapter_test.go (1)
378-384: Use an explicit enum to represent “Scheduled” status
productcatalog.AddonStatusInvalidis passed when the intent appears to be “Scheduled”.
If a properAddonStatusScheduled(or similar) exists, prefer that to avoid semantic drift; otherwise create one.- productcatalog.AddonStatusInvalid, + productcatalog.AddonStatusScheduled,Tests relying on status filters will be clearer and less fragile.
openmeter/productcatalog/addon/service/service_test.go (2)
58-69: Potential goroutine leak in feature creation loop
The loop re‑uses the outerctx; if a future refactor adds goroutines insideCreateFeature, the parent test may exit before the goroutines finish. Wrap each iteration with its own derived context or at least callt.Parallel()inside the loop body (table‑driven style).Please confirm whether
env.Feature.CreateFeaturespawns goroutines; if so I can draft a safe pattern.
333-340: Post‑deletion behaviour – should we expect “not found” instead of a soft‑deleted record?
Currently the repository still returns the deleted add‑on and the test only checksDeletedAt != nil. If the public API contract is “deleted resources are no longer retrievable”, this assertion lets a regression slip through. Consider asserting thatenv.Addon.GetAddonreturnsErrNotFoundinstead.Would you like a follow‑up patch that switches the expectation and updates the repository mock?
e222980 to
2896a0b
Compare
2896a0b to
19738b1
Compare
There was a problem hiding this comment.
Actionable comments posted: 0
🧹 Nitpick comments (1)
openmeter/productcatalog/addon/service/service_test.go (1)
117-119: Consider combining variable declaration and assignmentThe variable declaration and assignment could be combined for slightly cleaner code.
-var addonV1 *addon.Addon - -addonV1, err = env.Addon.CreateAddon(ctx, addonV1Input) +addonV1, err := env.Addon.CreateAddon(ctx, addonV1Input)
📜 Review details
Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro
📒 Files selected for processing (11)
openmeter/productcatalog/addon/adapter/adapter_test.go(1 hunks)openmeter/productcatalog/addon/service/service_test.go(6 hunks)openmeter/productcatalog/planaddon/adapter/adapter_test.go(9 hunks)openmeter/productcatalog/planaddon/service/service_test.go(10 hunks)openmeter/productcatalog/planaddon/testutils/addon.go(0 hunks)openmeter/productcatalog/planaddon/testutils/env.go(0 hunks)openmeter/productcatalog/planaddon/testutils/feature.go(0 hunks)openmeter/productcatalog/planaddon/testutils/meters.go(0 hunks)openmeter/productcatalog/planaddon/testutils/namespace.go(0 hunks)openmeter/productcatalog/planaddon/testutils/plan.go(0 hunks)openmeter/productcatalog/testutils/addon.go(2 hunks)
💤 Files with no reviewable changes (6)
- openmeter/productcatalog/planaddon/testutils/plan.go
- openmeter/productcatalog/planaddon/testutils/feature.go
- openmeter/productcatalog/planaddon/testutils/addon.go
- openmeter/productcatalog/planaddon/testutils/meters.go
- openmeter/productcatalog/planaddon/testutils/namespace.go
- openmeter/productcatalog/planaddon/testutils/env.go
🚧 Files skipped from review as they are similar to previous changes (4)
- openmeter/productcatalog/testutils/addon.go
- openmeter/productcatalog/planaddon/adapter/adapter_test.go
- openmeter/productcatalog/planaddon/service/service_test.go
- openmeter/productcatalog/addon/adapter/adapter_test.go
⏰ Context from checks skipped due to timeout of 90000ms (7)
- GitHub Check: E2E
- GitHub Check: CI
- GitHub Check: Test
- GitHub Check: Lint
- GitHub Check: Developer environment
- GitHub Check: Commit hooks
- GitHub Check: Analyze (go)
🔇 Additional comments (14)
openmeter/productcatalog/addon/service/service_test.go (14)
1-1: Good change to improve test isolation!Moving from
package servicetopackage service_testforces the test to only use exported members of the package, improving encapsulation and ensuring the tests validate the public API rather than implementation details.
17-17: Well-aligned with refactoring goalsThe addition of the centralized
pctestutilspackage aligns perfectly with the PR objective of refactoring to use shared test utilities for integration testing.
24-25: Good simplificationReplacing multiple period constants with a single
MonthPeriodconstant reduces code clutter and improves consistency with other test files in the codebase.
30-33: Great use of shared test environmentUsing
pctestutils.NewTestEnv(t)instead of direct initialization reduces code duplication and ensures consistent setup across tests. The proper cleanup handling is also important for resource management.
37-57: Well-structured test organizationThe nested test structure with descriptive names improves clarity and organization. Using utilities for creating test data (
NewTestNamespace,NewTestMeters) reduces code duplication and improves maintainability.
58-69: Good approach for feature creationCreating features from meters using the utility function is consistent with the refactoring approach and produces cleaner, more maintainable test code.
70-116: Thorough test data setupThe detailed setup of the rate cards with proper references to features makes the test comprehensive and realistic. This is important for testing the integration between different components.
125-126: Improved variable namingUsing
addonV1instead of more generic variable names likedraftAddonmakes the code more readable, especially in longer tests where multiple versions are being manipulated.
165-188: Good variable declaration for clarityUsing a dedicated variable
publishedAddonV1for the published version makes the test flow clearer, as we can see at a glance what state each object represents.
202-212: Well-structured versioning testsThe versioning section is well-structured and validates both the creation of a new version and the proper versioning relationship between the old and new versions.
213-271: Thorough error case testingTesting the failure case with misaligned billing cadences and then the recovery path is important for ensuring robust error handling, especially in a financial system where billing consistency is critical.
295-303: Important state verificationChecking that the previous version is automatically archived when a new version is published validates a critical business rule for versioning.
304-322: Complete lifecycle testingThe tests cover the complete lifecycle of an addon including archiving, ensuring that all state transitions work correctly.
325-340: Good deletion verificationTesting both the deletion operation and the resulting state of the deleted addon ensures that deletion behaves as expected (soft delete with
DeletedAtfield set).
Overview
Use
testutilspkg for integrations testing of service/adapters in productcatalog.Summary by CodeRabbit
Refactor
Chores
Tests