Skip to content

fix: Support key-value pair enumerables in the reuse hash - #1824

Closed
vengut wants to merge 1 commit into
testcontainers:developfrom
vengut:fix/reuse-hash-enumerable-key-value-pairs
Closed

vengut wants to merge 1 commit into
testcontainers:developfrom
vengut:fix/reuse-hash-enumerable-key-value-pairs

Conversation

@vengut

@vengut vengut commented Nov 17, 2026 •

Copy link
Copy Markdown

What does this PR do?

Changes JsonOrderedKeysConverter (and the derived JsonIgnoreRuntimeResourceLabels) from JsonConverter<IReadOnlyDictionary<string, string>> to JsonConverter<IEnumerable<KeyValuePair<string, string>>>.

CanConvert already claims every IEnumerable<KeyValuePair<string, string>>, but because the converter was typed for IReadOnlyDictionary<string, string>, System.Text.Json casts the value to IReadOnlyDictionary<string, string> before calling Write. Any configuration property that is a key-value pair enumerable but not a dictionary (e.g. a KeyValuePair<string, string>[]) throws during GetReuseHash().

The JSON written for dictionaries is unchanged, so existing reuse hashes stay the same (ForKnownConfiguration still passes with the hard-coded hash).

Why is it important?

The MongoDB Atlas Local module (#1780) added MongoDbAtlasLocalConfiguration.InitScriptContents (IEnumerable<KeyValuePair<string, string>>). BuildConfiguration.Combine always populates it with an array (Array.Empty<T>() when no init scripts are configured), so enabling reuse on that module always fails:

await new MongoDbAtlasLocalBuilder("mongodb/mongodb-atlas-local:8.0")
    .WithReuse(true)
    .Build()
    .StartAsync();
System.InvalidCastException: Unable to cast object of type 'System.Collections.Generic.KeyValuePair`2[System.String,System.String][]' to type 'System.Collections.Generic.IReadOnlyDictionary`2[System.String,System.String]'.
   at System.Text.Json.JsonSerializer.UnboxOnWrite[T](Object value)
   ...
   at DotNet.Testcontainers.Configurations.ResourceConfiguration`1.GetReuseHash()
   at DotNet.Testcontainers.Clients.FilterByReuseHash..ctor(IContainerConfiguration resourceConfiguration)
   at DotNet.Testcontainers.Containers.DockerContainer.UnsafeCreateAsync(CancellationToken ct)
   at DotNet.Testcontainers.Containers.DockerContainer.StartAsync(CancellationToken ct)

Fixing the converter (rather than adding [JsonIgnore] to InitScriptContents, as done for #1643 / #1644) keeps the init scripts part of the reuse hash, so containers with different init scripts are not reused for each other, and it covers any future module with a similar property.

Related issues

How to test this PR

Added two tests to ReusableResourceTest.ReuseHashTest using a configuration with an IEnumerable<KeyValuePair<string, string>> property backed by an array:

  • EqualTest.ForSameKeyValuePairsInDifferentOrder
  • NotEqualTest.ForDifferentKeyValuePairs

Both fail with the InvalidCastException above without the converter change and pass with it.

dotnet test tests/Testcontainers.Platform.Linux.Tests

🤖 Generated with Claude Code

Summary by CodeRabbit

  • Bug Fixes
    • Configurations containing the same key-value pairs now produce consistent reuse hashes even when the pairs are provided in a different order.
    • Configurations with the same keys but different values continue to produce distinct hashes.
    • Key-value entries are written in key order for consistent serialization.

@vengut
vengut requested a review from HofmeisterAn as a code owner November 17, 2026 13:32
@netlify

netlify Bot commented Nov 17, 2026

Copy link
Copy Markdown

👷 Deploy request for testcontainers-dotnet pending review.

Visit the deploys page to approve it

Name Link
🔨 Latest commit 8cbf384

@coderabbitai

coderabbitai Bot commented Nov 17, 2026 •

Copy link
Copy Markdown

Explain Change →

No actionable comments were generated in the recent review.

Walkthrough

The JSON converter and runtime-label writer now accept enumerable key-value pairs. Linux tests check reuse hashes for reordered pairs and for pairs with different values.

Changes

Reuse Hash Serialization

Layer / File(s) Summary
Enumerable serialization contract
src/Testcontainers/Configurations/Commons/JsonOrderedKeysConverter.cs, src/Testcontainers/Configurations/Commons/JsonIgnoreRuntimeResourceLabels.cs
The converter and runtime-label writer accept IEnumerable<KeyValuePair<string, string>>. The converter still orders entries by key when writing and deserializes an IReadOnlyDictionary.
Reuse-hash comparisons
tests/Testcontainers.Platform.Linux.Tests/ReusableResourceTest.cs
Linux tests verify that reversing the same key-value pairs produces an equal reuse hash, while changing a value produces a different hash. A test helper exposes supplied pairs as an enumerable.

Estimated code review effort: 2 (Simple) | ~10 minutes

Change: Bug fix

Suggested reviewers: 0xced

Merge Risk: Minimal · up to 8cbf3

This change lets reuse hashing handle key-value pair enumerables such as arrays without throwing. Dictionary behavior is unchanged, and new tests cover ordering and value differences. No merge-blocking risk was found.

Pre-merge checks: Passed 4

Check name Status Explanation
Title check Passed The title names the main change: key-value pair enumerables are now supported in the reuse hash. The PR changes JsonOrderedKeysConverter and JsonIgnoreRuntimeResourceLabels from a dictionary-typed con…
Description check Passed The description follows the repository template. It covers What does this PR do (the converter type change and why CanConvert mismatch causes the InvalidCastException), Why is it important (MongoDB At…
Linked Issues check Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check Passed Check skipped because no linked issues were found for this pull request.
Full details: Title check

Explanation

The title names the main change: key-value pair enumerables are now supported in the reuse hash. The PR changes JsonOrderedKeysConverter and JsonIgnoreRuntimeResourceLabels from a dictionary-typed converter to an IEnumerable<KeyValuePair<string, string>> converter, and adds tests for that case. The title uses the conventional 'fix:' prefix and stays under the length target.

Full details: Description check

Explanation

The description follows the repository template. It covers What does this PR do (the converter type change and why CanConvert mismatch causes the InvalidCastException), Why is it important (MongoDB Atlas Local init scripts, the reuse hash rationale, and the alternative of JsonIgnore), Related issues (Relates #1780), and How to test (two named tests and the dotnet test command). The Follow-ups section is optional and absent, which is acceptable.

Finishing Touches

Generate unit tests (beta)

  • Create a new PR
  • Autofix · Keep fixing CodeRabbit findings and required CI, and resolving merge conflicts

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

A rabbit checks the pairs in line,
Then sorts the keys to make them shine.
Swap their order; hashes stay the same,
Change a value; results change.
I thump my paws and hop away,
With tidy keys to greet the day.

Recent review info

Run configuration

  • Source mode: Auto
  • Repository: Unavailable
  • Branch: Unavailable
  • File: No configuration file from this repository applied
  • Commit: Unavailable
  • Layers: Repository UI
  • Review profile: CHILL
  • Plan: Advanced
  • Run ID: 64e58afa-f071-4ece-8f53-8adf393f3dd0
Commits

Reviewing files that changed from the base of the PR and between 5edbe99 and 8cbf384.

Files selected for processing: 3

  • src/Testcontainers/Configurations/Commons/JsonIgnoreRuntimeResourceLabels.cs
  • src/Testcontainers/Configurations/Commons/JsonOrderedKeysConverter.cs
  • tests/Testcontainers.Platform.Linux.Tests/ReusableResourceTest.cs

Included review availability: This review used your included allowance. Your plan provides up to 8 included reviews per hour; 7 remain after this review.

@vengut vengut closed this Nov 18, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant