Repository navigation
feat(charges): apply namespace default tax codes on charge create - #4396
Conversation
📝 WalkthroughWalkthroughThis PR wires taxcode.Service into the charges stack, adds ChargeIntent helpers, applies organization-default TaxCodeIDs to intents missing TaxConfig.TaxCodeID during charge Create, and updates test infra plus many tests to provision and assert these defaults. ChangesTax Code Defaulting in Charges Service
Estimated code review effort🎯 3 (Moderate) | ⏱️ ~25 minutes Possibly related PRs
Suggested reviewers
🚥 Pre-merge checks | ✅ 4 | ❌ 1❌ Failed checks (1 warning)
✅ Passed checks (4 passed)
✏️ Tip: You can configure your own custom pre-merge checks in the settings. ✨ Finishing Touches📝 Generate docstrings
🧪 Generate unit tests (beta)
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. Comment |
There was a problem hiding this comment.
Actionable comments posted: 1
🧹 Nitpick comments (2)
openmeter/billing/charges/service/create.go (1)
54-62: ⚡ Quick winUse defensive copies instead of mutating the config in place.
The function stamps a tax code ID onto the config by mutating it directly—which feels a bit risky. If callers are passing around shallow copies of intents that share the same underlying
TaxConfigpointer, you could end up accidentally modifying the original intent's tax setup. Not great for predictability.A safer pattern is to always return a fresh struct with the new values:
♻️ Suggested refactor
func stampTaxCodeID(cfg *productcatalog.TaxCodeConfig, id string) *productcatalog.TaxCodeConfig { if cfg == nil { return &productcatalog.TaxCodeConfig{TaxCodeID: &id} } - cfg.TaxCodeID = &id - - return cfg + return &productcatalog.TaxCodeConfig{ + TaxCodeID: &id, + Behavior: cfg.Behavior, + } }🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@openmeter/billing/charges/service/create.go` around lines 54 - 62, The helper stampTaxCodeID currently mutates the passed productcatalog.TaxCodeConfig in-place; change it to always return a new productcatalog.TaxCodeConfig copy with TaxCodeID set to the provided id (and copying any other fields from cfg when cfg != nil) so callers receive a defensive copy instead of having their original config mutated; update stampTaxCodeID to construct and return a fresh struct (not modify cfg) and ensure the returned TaxCodeID uses a newly allocated string pointer for id.openmeter/billing/charges/service/taxcode_test.go (1)
33-1410: 💤 Low valueNice work on the comprehensive test coverage! 🎉
The test suite thoroughly verifies the new default tax code stamping behavior across all charge types, propagation paths, and edge cases. The distinction between invoicing defaults (flat-fee/usage-based) and credit-grant defaults (credit purchase) is correctly tested throughout.
Optional refinement: The most complex multi-step scenarios—like
TestCreditPurchaseInvoiceSettlementPropagatesTaxConfigToGatheringLine(lines 347-471)—might benefit from brief given/when/then comments at the start to orient readers. But the existing inline comments already make the tests reasonably clear, so this is just a nice-to-have for those really gnarly integration flows. As per coding guidelines, adding concise intent comments when scenarios are non-trivial can help future maintainers quickly grok the test structure.Overall, the tests are solid, well-structured, and correctly verify the PR objectives! ✨
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@openmeter/billing/charges/service/taxcode_test.go` around lines 33 - 1410, Add a short given/when/then comment header to the complex multi-step test TestCreditPurchaseInvoiceSettlementPropagatesTaxConfigToGatheringLine to improve readability: locate the test function by name and at its start (before setting up ctx/ns/defaults/customInvoicing) insert a 2–3 line comment briefly stating the initial state (given), the action under test (when), and the expected outcome (then); keep the comments concise and focused so they complement existing inline comments without duplicating them.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
Inline comments:
In `@openmeter/billing/charges/service/create.go`:
- Around line 64-72: The code calls GetOrganizationDefaultTaxCodes and then uses
the returned defaults in defaultTaxCodeIDFor without validating them; call
defaults.Validate() (the OrganizationDefaultTaxCodes.Validate method)
immediately after retrieving defaults in the code path that invokes
GetOrganizationDefaultTaxCodes (before passing to defaultTaxCodeIDFor) and
handle the validation error (return or propagate it) so empty
InvoicingTaxCodeID/CreditGrantTaxCodeID are rejected; alternatively, add
.NotEmpty() constraints to the Ent schema for those fields to enforce non-empty
values at the DB level—apply one of these fixes and ensure any error is
logged/returned where GetOrganizationDefaultTaxCodes is called.
---
Nitpick comments:
In `@openmeter/billing/charges/service/create.go`:
- Around line 54-62: The helper stampTaxCodeID currently mutates the passed
productcatalog.TaxCodeConfig in-place; change it to always return a new
productcatalog.TaxCodeConfig copy with TaxCodeID set to the provided id (and
copying any other fields from cfg when cfg != nil) so callers receive a
defensive copy instead of having their original config mutated; update
stampTaxCodeID to construct and return a fresh struct (not modify cfg) and
ensure the returned TaxCodeID uses a newly allocated string pointer for id.
In `@openmeter/billing/charges/service/taxcode_test.go`:
- Around line 33-1410: Add a short given/when/then comment header to the complex
multi-step test
TestCreditPurchaseInvoiceSettlementPropagatesTaxConfigToGatheringLine to improve
readability: locate the test function by name and at its start (before setting
up ctx/ns/defaults/customInvoicing) insert a 2–3 line comment briefly stating
the initial state (given), the action under test (when), and the expected
outcome (then); keep the comments concise and focused so they complement
existing inline comments without duplicating them.
🪄 Autofix (Beta)
Fix all unresolved CodeRabbit comments on this PR:
- Push a commit to this branch (recommended)
- Create a new PR with the fixes
ℹ️ Review info
⚙️ Run configuration
Configuration used: Path: .coderabbit.yaml
Review profile: CHILL
Plan: Pro
Run ID: c5503afe-9f66-419e-87c4-c390e5140bb9
📒 Files selected for processing (13)
app/common/billing.goapp/common/charges.goopenmeter/billing/charges/service/advance_test.goopenmeter/billing/charges/service/base_test.goopenmeter/billing/charges/service/create.goopenmeter/billing/charges/service/creditpurchase_test.goopenmeter/billing/charges/service/featureid_test.goopenmeter/billing/charges/service/invoicable_test.goopenmeter/billing/charges/service/lineage_test.goopenmeter/billing/charges/service/service.goopenmeter/billing/charges/service/taxcode_test.goopenmeter/billing/charges/service/truncation_test.goopenmeter/billing/charges/service/usagebased_test.go
| // defaultTaxCodeIDFor picks which namespace default applies to the given charge type. | ||
| // Credit purchases use the credit-grant default; invoicing charges (flat-fee, usage-based) use the invoicing default. | ||
| func defaultTaxCodeIDFor(t meta.ChargeType, defaults taxcode.OrganizationDefaultTaxCodes) string { | ||
| if t == meta.ChargeTypeCreditPurchase { | ||
| return defaults.CreditGrantTaxCodeID | ||
| } | ||
|
|
||
| return defaults.InvoicingTaxCodeID | ||
| } |
There was a problem hiding this comment.
🧩 Analysis chain
🏁 Script executed:
#!/bin/bash
# Check how GetOrganizationDefaultTaxCodes handles missing defaults
rg -nA 20 'func.*GetOrganizationDefaultTaxCodes' --type goRepository: openmeterio/openmeter
Length of output: 15165
🏁 Script executed:
# Get the full adapter implementation
cat -n openmeter/taxcode/adapter/organizationdefaulttaxcodes.go | head -60Repository: openmeterio/openmeter
Length of output: 2716
🏁 Script executed:
# Check the OrganizationDefaultTaxCodes type definition
rg -nA 15 'type OrganizationDefaultTaxCodes struct' --type goRepository: openmeterio/openmeter
Length of output: 5031
🏁 Script executed:
# Look at the create.go file to see how defaultTaxCodeIDFor is used
cat -n openmeter/billing/charges/service/create.go | head -100Repository: openmeterio/openmeter
Length of output: 3811
🏁 Script executed:
# Get the complete Validate() method for OrganizationDefaultTaxCodes
rg -nA 20 'func \(o OrganizationDefaultTaxCodes\) Validate' --type goRepository: openmeterio/openmeter
Length of output: 1328
🏁 Script executed:
# Check the Ent schema fields for the tax code IDs
sed -n '26,60p' openmeter/ent/schema/organizationdefaulttaxcodes.goRepository: openmeterio/openmeter
Length of output: 1165
🏁 Script executed:
# Also check where defaultTaxCodeIDFor is called and how the result is used
rg -nB 5 -A 5 'defaultTaxCodeIDFor' openmeter/billing/charges/service/create.goRepository: openmeterio/openmeter
Length of output: 848
🏁 Script executed:
# Let's see the context around where GetOrganizationDefaultTaxCodes is called in create.go
rg -nB 10 -A 15 'GetOrganizationDefaultTaxCodes' openmeter/billing/charges/service/create.goRepository: openmeterio/openmeter
Length of output: 756
🏁 Script executed:
# Check if Validate() is called on the returned defaults anywhere
rg -n 'defaults\.Validate\|GetOrganizationDefaultTaxCodes.*\.Validate' openmeter/billing/charges/service/Repository: openmeterio/openmeter
Length of output: 47
Add validation of returned defaults before use.
The returned defaults from GetOrganizationDefaultTaxCodes (line 131) is used directly without validation. While OrganizationDefaultTaxCodes.Validate() does check for empty InvoicingTaxCodeID and CreditGrantTaxCodeID, the validation is never called here. The Ent schema also lacks .NotEmpty() constraints on those fields, so the database can return empty strings. This means defaultTaxCodeIDFor could propagate empty IDs onto charge intents.
Either call defaults.Validate() after retrieving them (line 136), or add .NotEmpty() constraints to the Ent schema fields to prevent this at the database level.
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
In `@openmeter/billing/charges/service/create.go` around lines 64 - 72, The code
calls GetOrganizationDefaultTaxCodes and then uses the returned defaults in
defaultTaxCodeIDFor without validating them; call defaults.Validate() (the
OrganizationDefaultTaxCodes.Validate method) immediately after retrieving
defaults in the code path that invokes GetOrganizationDefaultTaxCodes (before
passing to defaultTaxCodeIDFor) and handle the validation error (return or
propagate it) so empty InvoicingTaxCodeID/CreditGrantTaxCodeID are rejected;
alternatively, add .NotEmpty() constraints to the Ent schema for those fields to
enforce non-empty values at the DB level—apply one of these fixes and ensure any
error is logged/returned where GetOrganizationDefaultTaxCodes is called.
There was a problem hiding this comment.
Actionable comments posted: 1
🧹 Nitpick comments (1)
test/credits/creditgrant_test.go (1)
90-93: ⚡ Quick winUse
s.T().Context()instead ofcontext.Background()in these tests.Lines 90, 147, 186, and 244 all create a background context directly, but since you have access to
testing.Tthrough the suite (vias.T()), it's better to uses.T().Context()to keep the context lifecycle tied to the test harness.🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@test/credits/creditgrant_test.go` around lines 90 - 93, Replace the use of context.Background() with the test-scoped context s.T().Context() where the tests create ctx (e.g., the lines that set ctx := context.Background() before calling s.GetUniqueNamespace and s.ProvisionDefaultTaxCodes); update all occurrences in this test (the four places creating ctx) so the context lifecycle is tied to the testing.T via s.T().Context().
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
Inline comments:
In `@test/credits/creditgrant_test.go`:
- Around line 360-362: The test currently compares defaults.CreditGrantTaxCodeID
for equality but doesn't guard against it being empty; add an explicit non-empty
assertion before the equality check to avoid false positives. Locate the call to
s.TaxCodeService.GetOrganizationDefaultTaxCodes
(taxcode.GetOrganizationDefaultTaxCodesInput) and after s.Require().NoError(err)
add s.Require().NotEmpty(defaults.CreditGrantTaxCodeID) (or s.Assert().NotEmpty
if non-fatal preferred), then perform the existing equality assertion against
the expected ID; make the same change at the other occurrence around lines
390-392 to harden both assertions.
---
Nitpick comments:
In `@test/credits/creditgrant_test.go`:
- Around line 90-93: Replace the use of context.Background() with the
test-scoped context s.T().Context() where the tests create ctx (e.g., the lines
that set ctx := context.Background() before calling s.GetUniqueNamespace and
s.ProvisionDefaultTaxCodes); update all occurrences in this test (the four
places creating ctx) so the context lifecycle is tied to the testing.T via
s.T().Context().
🪄 Autofix (Beta)
Fix all unresolved CodeRabbit comments on this PR:
- Push a commit to this branch (recommended)
- Create a new PR with the fixes
ℹ️ Review info
⚙️ Run configuration
Configuration used: Path: .coderabbit.yaml
Review profile: CHILL
Plan: Pro
Run ID: a151a8af-d741-443c-afa9-e8e840f5cc7a
📒 Files selected for processing (15)
openmeter/billing/charges/charge.goopenmeter/billing/charges/service/create.goopenmeter/billing/charges/testutils/service.goopenmeter/billing/worker/subscriptionsync/service/base_test.goopenmeter/billing/worker/subscriptionsync/service/creditsonly_test.goopenmeter/billing/worker/subscriptionsync/service/sync_credittheninvoice_test.gotest/app/stripe/invoice_credits_test.gotest/app/stripe/invoice_test.gotest/billing/suite.gotest/credits/base.gotest/credits/credit_then_invoice_test.gotest/credits/creditgrant_test.gotest/credits/rating_test.gotest/credits/sanity_lifecycle_test.gotest/credits/sanity_test.go
| defaults, err := s.TaxCodeService.GetOrganizationDefaultTaxCodes(ctx, taxcode.GetOrganizationDefaultTaxCodesInput{Namespace: ns}) | ||
| s.Require().NoError(err) | ||
|
|
There was a problem hiding this comment.
Harden the default-tax assertion against empty-ID false positives.
Nice coverage update. One small gap: if defaults.CreditGrantTaxCodeID were unexpectedly empty, the equality check could still pass without validating real propagation.
Suggested tweak
defaults, err := s.TaxCodeService.GetOrganizationDefaultTaxCodes(ctx, taxcode.GetOrganizationDefaultTaxCodesInput{Namespace: ns})
s.Require().NoError(err)
+s.Require().NotEmpty(defaults.CreditGrantTaxCodeID)
...
s.Require().NotNil(lines[0].TaxConfig.TaxCodeID)
+s.Require().NotEmpty(*lines[0].TaxConfig.TaxCodeID)
s.Equal(defaults.CreditGrantTaxCodeID, *lines[0].TaxConfig.TaxCodeID, "standard invoice line must reference the namespace default credit-grant tax code")Also applies to: 390-392
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
In `@test/credits/creditgrant_test.go` around lines 360 - 362, The test currently
compares defaults.CreditGrantTaxCodeID for equality but doesn't guard against it
being empty; add an explicit non-empty assertion before the equality check to
avoid false positives. Locate the call to
s.TaxCodeService.GetOrganizationDefaultTaxCodes
(taxcode.GetOrganizationDefaultTaxCodesInput) and after s.Require().NoError(err)
add s.Require().NotEmpty(defaults.CreditGrantTaxCodeID) (or s.Assert().NotEmpty
if non-fatal preferred), then perform the existing equality assertion against
the expected ID; make the same change at the other occurrence around lines
390-392 to harden both assertions.
71880f4 to
0e5d202
Compare
9e51b15 to
5e607cb
Compare
There was a problem hiding this comment.
Actionable comments posted: 1
Caution
Some comments are outside the diff and can’t be posted inline due to platform limitations.
⚠️ Outside diff range comments (1)
openmeter/billing/worker/subscriptionsync/service/base_test.go (1)
47-54:⚠️ Potential issue | 🟠 Major | ⚡ Quick win
SuiteBase.Ledgerlooks unwired in this file’s setup path.Nice addition overall, but this new field is read by
assertLedgerTransactionGroupBookedAtand I can’t see it being initialized inSetupSuite/setupChargesServicehere. That can make the new ledger assertions fail withledger servicenil checks. Please wires.Ledgerduring suite setup (or use the already-wired embedded dependency directly instead of shadowing it).Also applies to: 60-80, 82-101
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@openmeter/billing/worker/subscriptionsync/service/base_test.go` around lines 47 - 54, SuiteBase.Ledger is declared but never initialized, causing nil ledger failures in assertLedgerTransactionGroupBookedAt; initialize or wire it in the suite setup. In SetupSuite (or setupChargesService) assign s.Ledger to the already-wired ledger from the embedded billingtest.BaseSuite (or whichever field holds the initialized ledger) or remove the shadowing field and use the embedded ledger directly; ensure any uses in assertLedgerTransactionGroupBookedAt reference the initialized s.Ledger (or the embedded ledger) so ledger service nil checks pass.
🧹 Nitpick comments (2)
openmeter/billing/charges/service/service.go (1)
57-101: ⚡ Quick winWrap joined validation errors with the repository validation error type.
Validate()aggregates errors but returns rawerrors.Join(errs...). Please wrap it withmodels.NewNillableGenericValidationError(...)for consistent validation semantics.Suggested patch
import ( "errors" "fmt" "log/slog" "slices" @@ "github.com/openmeterio/openmeter/openmeter/productcatalog/feature" "github.com/openmeterio/openmeter/openmeter/taxcode" + "github.com/openmeterio/openmeter/pkg/models" ) @@ - return errors.Join(errs...) + return models.NewNillableGenericValidationError(errors.Join(errs...)) }As per coding guidelines:
openmeter/**/*.go: ForValidate() errormethods, collect all validation issues intovar errs []errorand returnmodels.NewNillableGenericValidationError(errors.Join(errs...)).🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@openmeter/billing/charges/service/service.go` around lines 57 - 101, The Validate method on Config currently returns raw errors.Join(errs...), so change the return to wrap the joined errors with models.NewNillableGenericValidationError(errors.Join(errs...)) to follow repo validation semantics; keep collecting errs as-is and at the end return models.NewNillableGenericValidationError(errors.Join(errs...)) from Config.Validate so callers receive the standardized validation error type.test/credits/creditgrant_test.go (1)
95-95: ⚡ Quick winPrefer
s.T().Context()overcontext.Background()in these tests.Since
testing.Tis available, this should use the test-scoped context for lifecycle/cancellation consistency.As per coding guidelines:
**/*_test.go: Uset.Context()in tests when atesting.Tortesting.TBis available instead of introducingcontext.Background()to keep cancellation and lifecycle tied to the test harness.Also applies to: 152-152, 191-191, 249-249
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@test/credits/creditgrant_test.go` at line 95, Replace test-local uses of context.Background() with the test-scoped context from the test harness (e.g., s.T().Context() or t.Context()) so cancellation/lifecycle are tied to the test; search for the assignments to ctx (currently "ctx := context.Background()") in creditgrant_test.go (occurrences at the shown lines and the other mentioned instances) and change them to obtain the context from the test runner (use s.T().Context() if this is a testify suite method or t.Context() if inside a plain test) ensuring the rest of the test uses the same ctx variable.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
Inline comments:
In `@openmeter/billing/charges/service/truncation_test.go`:
- Around line 41-43: Replace the use of context.Background() in
truncation_test.go with the test-scoped context from the test harness: call
s.T().Context() when creating ctx in the test setup (the ctx variable created
near the top of the file where ns is assigned and ProvisionDefaultTaxCodes is
called) and in the later test section around the second occurrence (lines around
the code that provisions tax codes and other test actions, currently using
context.Background()); this ties cancellation and lifecycle to the testing.T
instance instead of using a global background context.
---
Outside diff comments:
In `@openmeter/billing/worker/subscriptionsync/service/base_test.go`:
- Around line 47-54: SuiteBase.Ledger is declared but never initialized, causing
nil ledger failures in assertLedgerTransactionGroupBookedAt; initialize or wire
it in the suite setup. In SetupSuite (or setupChargesService) assign s.Ledger to
the already-wired ledger from the embedded billingtest.BaseSuite (or whichever
field holds the initialized ledger) or remove the shadowing field and use the
embedded ledger directly; ensure any uses in
assertLedgerTransactionGroupBookedAt reference the initialized s.Ledger (or the
embedded ledger) so ledger service nil checks pass.
---
Nitpick comments:
In `@openmeter/billing/charges/service/service.go`:
- Around line 57-101: The Validate method on Config currently returns raw
errors.Join(errs...), so change the return to wrap the joined errors with
models.NewNillableGenericValidationError(errors.Join(errs...)) to follow repo
validation semantics; keep collecting errs as-is and at the end return
models.NewNillableGenericValidationError(errors.Join(errs...)) from
Config.Validate so callers receive the standardized validation error type.
In `@test/credits/creditgrant_test.go`:
- Line 95: Replace test-local uses of context.Background() with the test-scoped
context from the test harness (e.g., s.T().Context() or t.Context()) so
cancellation/lifecycle are tied to the test; search for the assignments to ctx
(currently "ctx := context.Background()") in creditgrant_test.go (occurrences at
the shown lines and the other mentioned instances) and change them to obtain the
context from the test runner (use s.T().Context() if this is a testify suite
method or t.Context() if inside a plain test) ensuring the rest of the test uses
the same ctx variable.
🪄 Autofix (Beta)
Fix all unresolved CodeRabbit comments on this PR:
- Push a commit to this branch (recommended)
- Create a new PR with the fixes
ℹ️ Review info
⚙️ Run configuration
Configuration used: Path: .coderabbit.yaml
Review profile: CHILL
Plan: Pro
Run ID: 17ea07c0-78e2-4652-b6e2-04f9a565a3ad
📒 Files selected for processing (27)
app/common/billing.goapp/common/charges.goopenmeter/billing/charges/charge.goopenmeter/billing/charges/service/advance_test.goopenmeter/billing/charges/service/base_test.goopenmeter/billing/charges/service/create.goopenmeter/billing/charges/service/creditpurchase_test.goopenmeter/billing/charges/service/featureid_test.goopenmeter/billing/charges/service/invoicable_test.goopenmeter/billing/charges/service/lineage_test.goopenmeter/billing/charges/service/service.goopenmeter/billing/charges/service/taxcode_test.goopenmeter/billing/charges/service/truncation_test.goopenmeter/billing/charges/service/usagebased_test.goopenmeter/billing/charges/testutils/service.goopenmeter/billing/worker/subscriptionsync/service/base_test.goopenmeter/billing/worker/subscriptionsync/service/creditsonly_test.goopenmeter/billing/worker/subscriptionsync/service/sync_credittheninvoice_test.gotest/app/stripe/invoice_credits_test.gotest/app/stripe/invoice_test.gotest/billing/suite.gotest/credits/base.gotest/credits/credit_then_invoice_test.gotest/credits/creditgrant_test.gotest/credits/rating_test.gotest/credits/sanity_lifecycle_test.gotest/credits/sanity_test.go
✅ Files skipped from review due to trivial changes (1)
- openmeter/billing/charges/service/base_test.go
| ctx := context.Background() | ||
| ns := s.GetUniqueNamespace("charges-service-truncation-flatfee") | ||
| s.ProvisionDefaultTaxCodes(ctx, ns) |
There was a problem hiding this comment.
Use test-scoped context instead of context.Background() in these tests.
Line 41 and Line 99 should use s.T().Context() so cancellation/lifecycle stays tied to the test harness.
Suggested patch
func (s *ChargeTimestampTruncationTestSuite) TestCreateTruncatesFlatFeeIntentAndProrationInputs() {
- ctx := context.Background()
+ ctx := s.T().Context()
ns := s.GetUniqueNamespace("charges-service-truncation-flatfee")
s.ProvisionDefaultTaxCodes(ctx, ns)
@@
func (s *ChargeTimestampTruncationTestSuite) TestUsageBasedAdvanceTruncatesPersistedCalculationTimestamps() {
- ctx := context.Background()
+ ctx := s.T().Context()
ns := s.GetUniqueNamespace("charges-service-truncation-usagebased")
s.ProvisionDefaultTaxCodes(ctx, ns)As per coding guidelines: **/*_test.go: Use t.Context() in tests when a testing.T or testing.TB is available instead of introducing context.Background() to keep cancellation and lifecycle tied to the test harness.
Also applies to: 99-102
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
In `@openmeter/billing/charges/service/truncation_test.go` around lines 41 - 43,
Replace the use of context.Background() in truncation_test.go with the
test-scoped context from the test harness: call s.T().Context() when creating
ctx in the test setup (the ctx variable created near the top of the file where
ns is assigned and ProvisionDefaultTaxCodes is called) and in the later test
section around the second occurrence (lines around the code that provisions tax
codes and other test actions, currently using context.Background()); this ties
cancellation and lifecycle to the testing.T instance instead of using a global
background context.
Summary by CodeRabbit
New Features
Tests