From 68a6833f3f27344baa13e2c38ddd0e3c02ae00f8 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Mike=20Kr=C3=BCger?= Date: Mon, 30 Nov 2026 14:12:16 +0100 Subject: [PATCH 1/4] Expose container unique-key policies in info output Refs #310 --- .../CommandTests/InfoCommandTests.cs | 119 ++++++++++++++++++ .../InfoCommand.cs | 3 + .../ArmCosmosResourceOperations.cs | 4 +- .../ContainerSettingsView.cs | 3 +- .../ContainerUniqueKeyPolicyView.cs | 32 +++++ .../ContainerUniqueKeyView.cs | 7 ++ .../DataPlaneCosmosResourceOperations.cs | 25 +++- docs/commands.md | 6 +- docs/mcp.md | 2 + 9 files changed, 193 insertions(+), 8 deletions(-) create mode 100644 CosmosDBShell/Azure.Data.Cosmos.Shell.Core/ContainerUniqueKeyPolicyView.cs create mode 100644 CosmosDBShell/Azure.Data.Cosmos.Shell.Core/ContainerUniqueKeyView.cs diff --git a/CosmosDBShell.Tests/CommandTests/InfoCommandTests.cs b/CosmosDBShell.Tests/CommandTests/InfoCommandTests.cs index 3e8ab943..34678ae5 100644 --- a/CosmosDBShell.Tests/CommandTests/InfoCommandTests.cs +++ b/CosmosDBShell.Tests/CommandTests/InfoCommandTests.cs @@ -4,13 +4,22 @@ namespace CosmosShell.Tests.CommandTests; +using System.Net; +using System.Text; using System.Text.Json; +using Azure; +using Azure.Core; using Azure.Data.Cosmos.Shell.Commands; using Azure.Data.Cosmos.Shell.Core; +using Azure.Data.Cosmos.Shell.Mcp; using Azure.Data.Cosmos.Shell.Parser; using Azure.Data.Cosmos.Shell.States; using Azure.Data.Cosmos.Shell.Util; +using Azure.ResourceManager; +using Azure.ResourceManager.CosmosDB; using Microsoft.Azure.Cosmos; +using ModelContextProtocol.Protocol; +using NSubstitute; /// /// Offline unit tests for . These cover the @@ -20,6 +29,116 @@ namespace CosmosShell.Tests.CommandTests; /// public class InfoCommandTests { + private const string GroupedUniqueKeys = """{"uniqueKeys":[{"paths":["/sku"]},{"paths":["/supplierId","/supplierProductCode"]}]}"""; + private const string EmptyUniqueKeys = """{"uniqueKeys":[]}"""; + + [Theory] + [InlineData(false, GroupedUniqueKeys)] + [InlineData(false, EmptyUniqueKeys)] + [InlineData(false, null)] + [InlineData(false, "{}")] + [InlineData(true, GroupedUniqueKeys)] + [InlineData(true, EmptyUniqueKeys)] + [InlineData(true, null)] + [InlineData(true, "{}")] + public async Task Info_ProjectsObservedUniqueKeyPolicyToCliAndMcp(bool useArm, string? policy) + { + const string databaseName = "shop"; + const string containerName = "products"; + var client = Substitute.For(); + var database = Substitute.For(); + var container = Substitute.For(); + client.GetDatabase(databaseName).Returns(database); + database.GetContainer(containerName).Returns(container); + var databaseRead = Substitute.For(); + databaseRead.StatusCode.Returns(HttpStatusCode.OK); + database.ReadAsync(cancellationToken: Arg.Any()).Returns(databaseRead); + var containerRead = Substitute.For(); + containerRead.StatusCode.Returns(HttpStatusCode.OK); + containerRead.Headers.Returns(new Headers { ["x-ms-resource-usage"] = "documentsCount=42" }); + container.ReadContainerAsync(Arg.Any(), Arg.Any()).Returns(containerRead); + + var resource = """{"id":"products","partitionKey":{"paths":["/tenant"],"kind":"Hash"},"analyticalStorageTtl":3600"""; + resource += policy is null ? "}" : $",\"uniqueKeyPolicy\":{policy}}}"; + ArmCosmosContext? context = null; + if (useArm) + { + var account = Substitute.For(); + var databases = Substitute.For(); + var armDatabase = Substitute.For(); + var containers = Substitute.For(); + var armContainer = Substitute.For(); + account.GetCosmosDBSqlDatabases().Returns(databases); + databases.GetIfExistsAsync(databaseName, Arg.Any()) + .Returns((NullableResponse)Response.FromValue(armDatabase, Substitute.For())); + armDatabase.GetCosmosDBSqlContainers().Returns(containers); + containers.GetIfExistsAsync(containerName, Arg.Any()) + .Returns((NullableResponse)Response.FromValue(armContainer, Substitute.For())); + armContainer.Data.Returns(CosmosArmResourceProvider.ReadArmModel( + """{"properties":{"resource":""" + resource + "}}")); + var throughput = Substitute.For(); + throughput.GetAsync(Arg.Any()) + .Returns(Task.FromException>(new RequestFailedException(404, "No dedicated throughput"))); + armContainer.GetCosmosDBSqlContainerThroughputSetting().Returns(throughput); + var id = new ResourceIdentifier("/subscriptions/s/resourceGroups/rg/providers/Microsoft.DocumentDB/databaseAccounts/a"); + context = new ArmCosmosContext(Substitute.For(), id, "s", "rg", "a", new Uri("https://a.documents.azure.com"), account); + } + else + { + container.ReadContainerStreamAsync(cancellationToken: Arg.Any()) + .Returns(_ => new ResponseMessage(HttpStatusCode.OK) { Content = new MemoryStream(Encoding.UTF8.GetBytes(resource)) }); + container.ReadThroughputAsync(Arg.Any(), Arg.Any()) + .Returns(Task.FromException(ScriptMocks.NotFound())); + } + + using var shell = ShellInterpreter.CreateInstance(); + shell.State = new ConnectedState(client, context); + var command = new InfoCommand { Database = databaseName, Container = containerName, Format = "json" }; + var result = await command.ExecuteAsync(shell, new CommandState(), "info", TestContext.Current.CancellationToken); + + using var cli = JsonDocument.Parse(result.GenerateOutputText()); + var mcpResult = McpResponseFactory.CreateSuccess(result, shell.State); + using var mcp = JsonDocument.Parse(Assert.IsType(Assert.Single(mcpResult.Content)).Text); + AssertPolicy(cli.RootElement); + AssertPolicy(mcp.RootElement.GetProperty("result")); + + void AssertPolicy(JsonElement output) + { + Assert.Equal(containerName, output.GetProperty("id").GetString()); + Assert.Equal("/tenant", Assert.Single(output.GetProperty("partitionKey").EnumerateArray()).GetString()); + Assert.Equal(3600, output.GetProperty("analyticalTTL").GetInt64()); + Assert.Equal(42, output.GetProperty("documentCount").GetInt64()); + var actual = output.GetProperty("uniqueKeyPolicy"); + if (policy is null or "{}") + { + Assert.Equal(JsonValueKind.Null, actual.ValueKind); + } + else + { + using var expected = JsonDocument.Parse(policy); + Assert.True(JsonElement.DeepEquals(expected.RootElement, actual)); + } + } + } + + [Fact] + public async Task ContainerSettings_FailedReadIsNotReportedAsAnEmptyPolicy() + { + var client = Substitute.For(); + var database = Substitute.For(); + var container = Substitute.For(); + client.GetDatabase("shop").Returns(database); + database.GetContainer("products").Returns(container); + container.ReadContainerStreamAsync(cancellationToken: Arg.Any()) + .Returns(_ => new ResponseMessage(HttpStatusCode.Forbidden)); + var operations = new DataPlaneCosmosResourceOperations(client); + + var exception = await Assert.ThrowsAsync(() => + operations.GetContainerSettingsAsync("shop", "products", TestContext.Current.CancellationToken)); + + Assert.Equal(HttpStatusCode.Forbidden, exception.StatusCode); + } + [Fact] public async Task Info_Disconnected_ThrowsNotConnected() { diff --git a/CosmosDBShell/Azure.Data.Cosmos.Shell.Commands/InfoCommand.cs b/CosmosDBShell/Azure.Data.Cosmos.Shell.Commands/InfoCommand.cs index 7493feab..a5f66c50 100644 --- a/CosmosDBShell/Azure.Data.Cosmos.Shell.Commands/InfoCommand.cs +++ b/CosmosDBShell/Azure.Data.Cosmos.Shell.Commands/InfoCommand.cs @@ -782,6 +782,9 @@ private async Task ShowContainerSettingsAsync(ShellInterpreter she mcpTable["id"] = view.ContainerName; mcpTable["partitionKey"] = view.PartitionKeyPaths; mcpTable["analyticalTTL"] = view.AnalyticalStorageTtl; + mcpTable["uniqueKeyPolicy"] = view.UniqueKeyPolicy is { } uniqueKeyPolicy + ? new { uniqueKeys = uniqueKeyPolicy.UniqueKeys.Select(key => new { paths = key.Paths }).ToArray() } + : null; string ttl; if (view.AnalyticalStorageTtl == null || diff --git a/CosmosDBShell/Azure.Data.Cosmos.Shell.Core/ArmCosmosResourceOperations.cs b/CosmosDBShell/Azure.Data.Cosmos.Shell.Core/ArmCosmosResourceOperations.cs index 988125cf..902396e9 100644 --- a/CosmosDBShell/Azure.Data.Cosmos.Shell.Core/ArmCosmosResourceOperations.cs +++ b/CosmosDBShell/Azure.Data.Cosmos.Shell.Core/ArmCosmosResourceOperations.cs @@ -9,6 +9,7 @@ namespace Azure.Data.Cosmos.Shell.Core; using System.Runtime.CompilerServices; using global::Azure; using global::Azure.ResourceManager.CosmosDB.Models; +using Newtonsoft.Json.Linq; internal sealed class ArmCosmosResourceOperations(ArmCosmosContext context) : ICosmosResourceOperations { @@ -157,7 +158,8 @@ public async Task GetContainerSettingsAsync(string databa throughputError, GeospatialType: null, FullTextPolicy: null, - IndexingPolicy: indexingView); + IndexingPolicy: indexingView, + UniqueKeyPolicy: ContainerUniqueKeyPolicyView.FromResource(JObject.Parse(CosmosArmResourceProvider.WriteArmModel(armResource)))); } public async Task GetIndexingPolicyJsonAsync(string databaseName, string containerName, CancellationToken token) diff --git a/CosmosDBShell/Azure.Data.Cosmos.Shell.Core/ContainerSettingsView.cs b/CosmosDBShell/Azure.Data.Cosmos.Shell.Core/ContainerSettingsView.cs index 62b667f0..9f41ce93 100644 --- a/CosmosDBShell/Azure.Data.Cosmos.Shell.Core/ContainerSettingsView.cs +++ b/CosmosDBShell/Azure.Data.Cosmos.Shell.Core/ContainerSettingsView.cs @@ -14,4 +14,5 @@ internal sealed record ContainerSettingsView( string? ThroughputErrorMessage, string? GeospatialType, ContainerFullTextPolicyView? FullTextPolicy, - ContainerIndexingPolicyView? IndexingPolicy); + ContainerIndexingPolicyView? IndexingPolicy, + ContainerUniqueKeyPolicyView? UniqueKeyPolicy); diff --git a/CosmosDBShell/Azure.Data.Cosmos.Shell.Core/ContainerUniqueKeyPolicyView.cs b/CosmosDBShell/Azure.Data.Cosmos.Shell.Core/ContainerUniqueKeyPolicyView.cs new file mode 100644 index 00000000..78cfad75 --- /dev/null +++ b/CosmosDBShell/Azure.Data.Cosmos.Shell.Core/ContainerUniqueKeyPolicyView.cs @@ -0,0 +1,32 @@ +// ------------------------------------------------------------ +// Copyright (c) Microsoft Corporation. All rights reserved. +// ------------------------------------------------------------ + +namespace Azure.Data.Cosmos.Shell.Core; + +using Newtonsoft.Json.Linq; + +internal sealed record ContainerUniqueKeyPolicyView(IReadOnlyList UniqueKeys) +{ + public static ContainerUniqueKeyPolicyView? FromResource(JObject resource) + { + if (resource["uniqueKeyPolicy"] is not JObject policy || policy["uniqueKeys"] is not JArray keys) + { + return null; + } + + var constraints = new List(keys.Count); + foreach (var key in keys) + { + if (key is not JObject constraint || constraint["paths"] is not JArray paths + || paths.Count == 0 || paths.Any(path => path.Type != JTokenType.String)) + { + return null; + } + + constraints.Add(new ContainerUniqueKeyView(paths.Values().Select(path => path!).ToArray())); + } + + return new ContainerUniqueKeyPolicyView(constraints); + } +} diff --git a/CosmosDBShell/Azure.Data.Cosmos.Shell.Core/ContainerUniqueKeyView.cs b/CosmosDBShell/Azure.Data.Cosmos.Shell.Core/ContainerUniqueKeyView.cs new file mode 100644 index 00000000..795507cf --- /dev/null +++ b/CosmosDBShell/Azure.Data.Cosmos.Shell.Core/ContainerUniqueKeyView.cs @@ -0,0 +1,7 @@ +// ------------------------------------------------------------ +// Copyright (c) Microsoft Corporation. All rights reserved. +// ------------------------------------------------------------ + +namespace Azure.Data.Cosmos.Shell.Core; + +internal sealed record ContainerUniqueKeyView(IReadOnlyList Paths); diff --git a/CosmosDBShell/Azure.Data.Cosmos.Shell.Core/DataPlaneCosmosResourceOperations.cs b/CosmosDBShell/Azure.Data.Cosmos.Shell.Core/DataPlaneCosmosResourceOperations.cs index cf7aa04a..4d2a331a 100644 --- a/CosmosDBShell/Azure.Data.Cosmos.Shell.Core/DataPlaneCosmosResourceOperations.cs +++ b/CosmosDBShell/Azure.Data.Cosmos.Shell.Core/DataPlaneCosmosResourceOperations.cs @@ -9,6 +9,7 @@ namespace Azure.Data.Cosmos.Shell.Core; using Azure.Data.Cosmos.Shell.Util; using Microsoft.Azure.Cosmos; using Newtonsoft.Json; +using Newtonsoft.Json.Linq; internal sealed class DataPlaneCosmosResourceOperations(CosmosClient client) : ICosmosResourceOperations { @@ -166,16 +167,27 @@ public async Task> GetPartitionKeyPathsAsync(string databa public async Task GetContainerSettingsAsync(string databaseName, string containerName, CancellationToken token) { - var dpResponse = await client.GetDatabase(databaseName).GetContainer(containerName).ReadContainerAsync(cancellationToken: token); - RequestChargeContext.Record(dpResponse.RequestCharge); - var properties = GetContainerPropertiesOrThrow(dpResponse); + var container = client.GetDatabase(databaseName).GetContainer(containerName); + using var dpResponse = await container.ReadContainerStreamAsync(cancellationToken: token); + dpResponse.EnsureSuccessStatusCode(); + RequestChargeContext.Record(dpResponse.Headers.RequestCharge); + if (dpResponse.Content is null) + { + throw new ShellException(MessageService.GetString("error-unable_to_read_container")); + } + + using var streamReader = new StreamReader(dpResponse.Content); + using var jsonReader = new JsonTextReader(streamReader) { DateParseHandling = DateParseHandling.None }; + var resource = await JObject.LoadAsync(jsonReader, token); + var properties = resource.ToObject() + ?? throw new ShellException(MessageService.GetString("error-unable_to_read_container")); int? dpMin = null; int? dpMax = null; ThroughputAvailability dpAvailability = ThroughputAvailability.Available; string? dpError = null; try { - var throughputResponse = await client.GetDatabase(databaseName).GetContainer(containerName).ReadThroughputAsync(new RequestOptions(), token); + var throughputResponse = await container.ReadThroughputAsync(new RequestOptions(), token); RequestChargeContext.Record(throughputResponse.RequestCharge); dpMin = throughputResponse.MinThroughput; dpMax = throughputResponse.Resource?.AutoscaleMaxThroughput ?? throughputResponse.Resource?.Throughput ?? dpMin; @@ -226,6 +238,8 @@ public async Task GetContainerSettingsAsync(string databa indexingPolicy.VectorIndexes?.Count ?? 0); } + // The SDK getter creates an empty policy if the service omitted it. + var uniqueKeyPolicy = ContainerUniqueKeyPolicyView.FromResource(resource); return new ContainerSettingsView( properties.Id, properties.PartitionKeyPaths?.ToArray() ?? (properties.PartitionKeyPath != null ? [properties.PartitionKeyPath] : []), @@ -236,7 +250,8 @@ public async Task GetContainerSettingsAsync(string databa dpError, geospatialType, fullTextView, - indexingView); + indexingView, + uniqueKeyPolicy); } public async Task GetIndexingPolicyJsonAsync(string databaseName, string containerName, CancellationToken token) diff --git a/docs/commands.md b/docs/commands.md index 7c10ac44..cbf8d0f5 100644 --- a/docs/commands.md +++ b/docs/commands.md @@ -1877,7 +1877,11 @@ Options: The default interactive report is rendered as tables. Use `--format json` for a machine-readable JSON object; redirecting `info` output to a file also writes JSON -so CI and scripts can parse the result directly. When `--format table` is combined +so CI and scripts can parse the result directly. Container JSON includes the +observed `uniqueKeyPolicy` on data-plane and Azure Resource Manager connections. +Each entry in `uniqueKeys` contains the `paths` of one constraint. An empty +`uniqueKeys` array means the service reported no constraints; `uniqueKeyPolicy: null` +means no policy could be observed from the response. When `--format table` is combined with redirection, the report is written to the file as a plain-text grid instead of the rich console layout. The `--partitions` and `--detailed` options issue queries against the data and therefore consume diff --git a/docs/mcp.md b/docs/mcp.md index 5f8f523c..f977a7f8 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -150,6 +150,8 @@ For single-item deletions, prefer `rm` with `key: "id"`, `partition-key`, and `d Database and container resource actions are executed through Azure Resource Manager when an ARM context is attached (Entra ID connections). MCP sessions connected with account keys, emulator credentials, or static data-plane tokens fall back to the Cosmos DB data plane for these actions. +Container `info` results include the observed [`uniqueKeyPolicy`](commands.md#info) on both routes, preserving the grouping of paths into constraints. A `null` policy means it was unavailable in the response, not that the container has no constraints. + On serverless accounts, `mkdb`, `mkcon`, and their `create` aliases omit throughput when neither `--scale` nor `--ru` is supplied. Explicit throughput options are rejected on serverless accounts for both ARM and data-plane connections. See [database and container creation](commands.md#mkdb). For deterministic ARM routing in multi-subscription environments, start the shell with `--connect-subscription` and `--connect-resource-group`. From 847072eabe81d6a0a1e46ed4ab5738b47a2cd88c Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Mike=20Kr=C3=BCger?= Date: Tue, 1 Dec 2026 10:51:27 +0100 Subject: [PATCH 2/4] Test rejection of incomplete unique-key constraints --- CosmosDBShell.Tests/CommandTests/InfoCommandTests.cs | 8 +++++++- 1 file changed, 7 insertions(+), 1 deletion(-) diff --git a/CosmosDBShell.Tests/CommandTests/InfoCommandTests.cs b/CosmosDBShell.Tests/CommandTests/InfoCommandTests.cs index 34678ae5..8ab6d454 100644 --- a/CosmosDBShell.Tests/CommandTests/InfoCommandTests.cs +++ b/CosmosDBShell.Tests/CommandTests/InfoCommandTests.cs @@ -31,16 +31,22 @@ public class InfoCommandTests { private const string GroupedUniqueKeys = """{"uniqueKeys":[{"paths":["/sku"]},{"paths":["/supplierId","/supplierProductCode"]}]}"""; private const string EmptyUniqueKeys = """{"uniqueKeys":[]}"""; + private const string MissingConstraintPaths = """{"uniqueKeys":[{"paths":["/sku"]},{}]}"""; + private const string EmptyConstraintPaths = """{"uniqueKeys":[{"paths":["/sku"]},{"paths":[]}]}"""; [Theory] [InlineData(false, GroupedUniqueKeys)] [InlineData(false, EmptyUniqueKeys)] [InlineData(false, null)] [InlineData(false, "{}")] + [InlineData(false, MissingConstraintPaths)] + [InlineData(false, EmptyConstraintPaths)] [InlineData(true, GroupedUniqueKeys)] [InlineData(true, EmptyUniqueKeys)] [InlineData(true, null)] [InlineData(true, "{}")] + [InlineData(true, MissingConstraintPaths)] + [InlineData(true, EmptyConstraintPaths)] public async Task Info_ProjectsObservedUniqueKeyPolicyToCliAndMcp(bool useArm, string? policy) { const string databaseName = "shop"; @@ -109,7 +115,7 @@ void AssertPolicy(JsonElement output) Assert.Equal(3600, output.GetProperty("analyticalTTL").GetInt64()); Assert.Equal(42, output.GetProperty("documentCount").GetInt64()); var actual = output.GetProperty("uniqueKeyPolicy"); - if (policy is null or "{}") + if (policy is null or "{}" or MissingConstraintPaths or EmptyConstraintPaths) { Assert.Equal(JsonValueKind.Null, actual.ValueKind); } From 89ac8f4e7a746ae21e1bca5fe78b3bcdf34a315a Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Mike=20Kr=C3=BCger?= Date: Thu, 3 Dec 2026 14:24:46 +0100 Subject: [PATCH 3/4] Register throughput status tests in migration inventory Fix portable contract inventory validation for #319. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- tests/cli-contracts/migration-map.json | 1 + 1 file changed, 1 insertion(+) diff --git a/tests/cli-contracts/migration-map.json b/tests/cli-contracts/migration-map.json index 94a7034d..84754d7a 100644 --- a/tests/cli-contracts/migration-map.json +++ b/tests/cli-contracts/migration-map.json @@ -121,6 +121,7 @@ "CosmosDBShell.Tests/CommandTests/SprocCommandExecutionTests.cs", "CosmosDBShell.Tests/CommandTests/SprocCommandTests.cs", "CosmosDBShell.Tests/CommandTests/ThroughputCommandTests.cs", + "CosmosDBShell.Tests/CommandTests/ThroughputReplacementStatusTests.cs", "CosmosDBShell.Tests/CommandTests/TriggerCommandExecutionTests.cs", "CosmosDBShell.Tests/CommandTests/TriggerCommandTests.cs", "CosmosDBShell.Tests/CommandTests/TtlCommandTests.cs", From ce0e1641cfab0d9548f57239e1bc8f7cd2220d94 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Mike=20Kr=C3=BCger?= Date: Thu, 3 Dec 2026 15:46:59 +0100 Subject: [PATCH 4/4] Align emulator contracts with container metadata output Require unavailable unique-key policy and throughput replacement status fields in the Windows emulator contract. Add regression checks for missing or fabricated metadata. Fix #319 CI. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- .../cases/emulator/command-smoke.json | 3 +- .../test_reviewed_expectations.py | 36 +++++++++++++++++++ 2 files changed, 38 insertions(+), 1 deletion(-) diff --git a/tests/cli-contracts/cases/emulator/command-smoke.json b/tests/cli-contracts/cases/emulator/command-smoke.json index 65eee340..43c89984 100644 --- a/tests/cli-contracts/cases/emulator/command-smoke.json +++ b/tests/cli-contracts/cases/emulator/command-smoke.json @@ -69,6 +69,7 @@ "minThroughput": 400, "maxThroughput": 400, "analyticalTTL": null, + "uniqueKeyPolicy": null, "geospatialType": "Geography", "documentCount": 1, "dataSizeKb": null, @@ -83,7 +84,7 @@ "/session/chargedOperationCount": {"type": "integer", "minimum": 1} } }, - "throughput.json": {"mode": "json", "expected": {"scope": "container", "resource": "items", "mode": "manual", "throughput": 400, "autoscaleMaxThroughput": null, "minThroughput": 400}}, + "throughput.json": {"mode": "json", "expected": {"scope": "container", "resource": "items", "mode": "manual", "throughput": 400, "autoscaleMaxThroughput": null, "minThroughput": 400, "isReplacePending": null}}, "stderr.txt": {"mode": "empty"} } }, diff --git a/tests/cli-contracts/test_reviewed_expectations.py b/tests/cli-contracts/test_reviewed_expectations.py index 87847f43..9cb53765 100644 --- a/tests/cli-contracts/test_reviewed_expectations.py +++ b/tests/cli-contracts/test_reviewed_expectations.py @@ -52,3 +52,39 @@ def test_user_redirect_contract_rejects_json_with_whitespace(tmp_path): result.write_text(f'{{"status": "error", "error": "{message}"}}', encoding="utf-8") with pytest.raises(AssertionError, match="unexpected"): compare_file(result, spec) + + +@pytest.mark.parametrize( + "filename,field,invalid_values", + [ + ("info.json", "uniqueKeyPolicy", [{}, {"uniqueKeys": []}]), + ("throughput.json", "isReplacePending", [False, True]), + ], +) +def test_emulator_metadata_contract_preserves_unavailable_values(tmp_path, filename, field, invalid_values): + cases = parse_json( + (CASES.parent / "emulator" / "command-smoke.json").read_text(encoding="utf-8") + )["cases"] + spec = next( + case for case in cases if case["id"] == "emulator-info-and-throughput-at-container-scope" + )["files"][filename] + payload = {**spec["expected"], field: None} + if filename == "info.json": + payload.update( + dataSizeKb=0, + totalSizeKb=1, + session={"requestCharge": 1, "chargedOperationCount": 1}, + ) + result = tmp_path / filename + result.write_text(json_text(payload), encoding="utf-8") + compare_file(result, spec) + + for value in invalid_values: + result.write_text(json_text({**payload, field: value}), encoding="utf-8") + with pytest.raises(AssertionError): + compare_file(result, spec) + + del payload[field] + result.write_text(json_text(payload), encoding="utf-8") + with pytest.raises(AssertionError): + compare_file(result, spec)