Skip to content

refactor: use testutils in productcatalog - #2699

Merged
chrisgacsal merged 2 commits into
mainfrom
refactor/productcatalog
Apr 21, 2025
Merged

chrisgacsal merged 2 commits into
mainfrom
refactor/productcatalog

Conversation

@chrisgacsal

@chrisgacsal chrisgacsal commented Apr 21, 2025 •

Copy link
Copy Markdown
Collaborator

Overview

Use testutils pkg for integrations testing of service/adapters in productcatalog.

Summary by CodeRabbit

  • Refactor

    • Streamlined and reorganized test files for add-on and plan add-on features, improving modularity, clarity, and test environment setup.
    • Consolidated and standardized test utility usage across test suites.
    • Updated variable names and test flows for better readability and maintainability.
  • Chores

    • Removed redundant and specialized test utility files in favor of shared, centralized test utilities.
    • Updated test helper functions to support more flexible test data creation.
  • Tests

    • Maintained and improved test coverage for add-on and plan add-on creation, retrieval, updating, deletion, and status filtering scenarios.

@chrisgacsal chrisgacsal added the release-note/ignore Ignore this change when generating release notes label Apr 21, 2025
@chrisgacsal chrisgacsal self-assigned this Apr 21, 2025
@chrisgacsal
chrisgacsal requested a review from a team as a code owner April 21, 2025 08:15
@coderabbitai

coderabbitai Bot commented Apr 21, 2025 •

Copy link
Copy Markdown
Contributor
📝 Walkthrough

Walkthrough

This 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 (pctestutils). Test files are updated to use external test environments, improved variable naming, and more modular, inline test data creation. Several planaddon-specific test utility files are deleted, with their logic consolidated into the shared utilities. The test logic and coverage remain consistent, but the structure is streamlined for maintainability and clarity. No exported or public API changes are made outside of test code.

Changes

Files/Paths Change Summary
openmeter/productcatalog/addon/adapter/adapter_test.go Refactored to use shared test environment (pctestutils.NewTestEnv), dynamic namespace/meters/features setup, improved modularity, and inline logic for addon creation, updating, deletion, and status filtering; package renamed to adapter_test.
openmeter/productcatalog/addon/service/service_test.go Moved from internal to external test package (service_test), replaced local helpers with shared test utilities, improved variable naming and test flow, removed direct DB/adapter setup in favor of external test environment.
openmeter/productcatalog/planaddon/adapter/adapter_test.go Refactored to use pctestutils for environment and data setup, used t.Cleanup for cleanup, nested tests for modularity, consolidated test data creation, and standardized repository usage; removed redundancy.
openmeter/productcatalog/planaddon/service/service_test.go Refactored to use pctestutils, changed to external test package, simplified environment setup, consolidated data creation, removed planaddon-specific service/adapter layers, and streamlined test logic.
openmeter/productcatalog/planaddon/testutils/addon.go
openmeter/productcatalog/planaddon/testutils/env.go
openmeter/productcatalog/planaddon/testutils/feature.go
openmeter/productcatalog/planaddon/testutils/meters.go
openmeter/productcatalog/planaddon/testutils/namespace.go
openmeter/productcatalog/planaddon/testutils/plan.go
Deleted planaddon-specific test utility files and functions for environment, addon, feature, meter, namespace, and plan creation; their logic is now handled by shared utilities.
openmeter/productcatalog/testutils/addon.go Updated NewTestAddon to accept variadic rateCards parameter for dynamic rate card assignment; updated field values for key, name, description, and metadata to use "test-addon".

Possibly related PRs

  • openmeterio/openmeter#2623: Refactors addon adapter tests to use a new test environment and utilities; related as both PRs restructure addon test setups, though this one focuses on service transaction handling and ratecard method renaming.

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
Failed executing command with error: you are using a configuration file for golangci-lint v2 with golangci-lint v1: please use golangci-lint v2

✨ Finishing Touches
  • 📝 Generate Docstrings

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.

❤️ Share
🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Generate unit testing code for this file.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai generate unit testing code for this file.
    • @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read src/utils.ts and generate unit testing code.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

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)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai generate docstrings to generate docstrings for this PR.
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

@chrisgacsal
chrisgacsal requested a review from turip April 21, 2025 08:16

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 4

🔭 Outside diff range comments (1)
openmeter/productcatalog/planaddon/service/service_test.go (1)

308-317: ⚠️ Potential issue

Wrong variable checked – the test never asserts the value just fetched

require.NotNilf validates addonV1, but the value that was just retrieved is getPlanAddon.
As written, the assertion is meaningless because addonV1 was 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 ByKey sub‑test below.

🧹 Nitpick comments (6)
openmeter/productcatalog/testutils/addon.go (1)

14-34: Accepting variadic RateCard is a good improvement, consider guarding against an empty slice

The new signature is flexible, but a CreateAddonInput with RateCards == 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
MonthPeriod is already declared in productcatalog/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

  1. Add t.Parallel() at the start of every sub‑test to improve CI throughput.
  2. env.Close(t) is great, but the context.WithCancel created above is never propagated to the env; prefer context.Background() or pass ctx into NewTestEnv so 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 single ReplaceMeters call, and the test never exercises paging logic. Calling ListMeters with an artificially large page size is noisy and future‑fragile. Prefer either env.Meter.ListAllMeters(ctx, namespace) helper or a direct repository call without pagination.


70-115: Inline monster literals hamper readability – extract to helper
The 40‑line UsageBasedRateCard literal 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

📥 Commits

Reviewing files that changed from the base of the PR and between 2458b32 and e222980.

📒 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.AddonStatusInvalid is passed when the intent appears to be “Scheduled”.
If a proper AddonStatusScheduled (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 outer ctx; if a future refactor adds goroutines inside CreateFeature, the parent test may exit before the goroutines finish. Wrap each iteration with its own derived context or at least call t.Parallel() inside the loop body (table‑driven style).

Please confirm whether env.Feature.CreateFeature spawns 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 checks DeletedAt != nil. If the public API contract is “deleted resources are no longer retrievable”, this assertion lets a regression slip through. Consider asserting that env.Addon.GetAddon returns ErrNotFound instead.

Would you like a follow‑up patch that switches the expectation and updates the repository mock?

@chrisgacsal
chrisgacsal force-pushed the refactor/productcatalog branch from e222980 to 2896a0b Compare April 21, 2025 08:34
@chrisgacsal
chrisgacsal force-pushed the refactor/productcatalog branch from 2896a0b to 19738b1 Compare April 21, 2025 08:34
@chrisgacsal
chrisgacsal enabled auto-merge (squash) April 21, 2025 08:36

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 0

🧹 Nitpick comments (1)
openmeter/productcatalog/addon/service/service_test.go (1)

117-119: Consider combining variable declaration and assignment

The 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

📥 Commits

Reviewing files that changed from the base of the PR and between e222980 and 19738b1.

📒 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 service to package service_test forces 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 goals

The addition of the centralized pctestutils package aligns perfectly with the PR objective of refactoring to use shared test utilities for integration testing.


24-25: Good simplification

Replacing multiple period constants with a single MonthPeriod constant reduces code clutter and improves consistency with other test files in the codebase.


30-33: Great use of shared test environment

Using 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 organization

The 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 creation

Creating 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 setup

The 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 naming

Using addonV1 instead of more generic variable names like draftAddon makes the code more readable, especially in longer tests where multiple versions are being manipulated.


165-188: Good variable declaration for clarity

Using a dedicated variable publishedAddonV1 for 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 tests

The 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 testing

Testing 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 verification

Checking that the previous version is automatically archived when a new version is published validates a critical business rule for versioning.


304-322: Complete lifecycle testing

The tests cover the complete lifecycle of an addon including archiving, ensuring that all state transitions work correctly.


325-340: Good deletion verification

Testing both the deletion operation and the resulting state of the deleted addon ensures that deletion behaves as expected (soft delete with DeletedAt field set).

@coderabbitai coderabbitai Bot mentioned this pull request Jul 30, 2025
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

release-note/ignore Ignore this change when generating release notes

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants