| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140 |
- using System.Net;
- using System.Text;
- using System.Text.Json;
- using Admin.NET.Plugin.AiDOP.DataPlatform.Core;
- using Admin.NET.Plugin.AiDOP.DataPlatform.UnifiedIngress;
- using Xunit;
- namespace Admin.NET.Plugin.AiDOP.Tests.DataPlatform;
- public sealed class MdpApiPullTests
- {
- [Fact]
- public void MalformedApiPageHasAnImmutableRawCaptureBeforeParsing()
- {
- var body = Encoding.UTF8.GetBytes("{\"orders\":[");
- var identity = new IngestDatasetIdentity(1, 2, 3, 4, "LAB", PurchaseOrderSchemaRegistry.DatasetKey);
- var preparer = new IngestBatchPreparer(new PurchaseOrderSchemaRegistry());
- var raw = preparer.CaptureApiPage(identity, PurchaseOrderSchemaRegistry.SourceVersion, body, new(1024, 100, 16));
- Assert.Equal(body, raw.Payload.ToArray());
- Assert.Equal(0, raw.AcceptedRowCount);
- Assert.Equal("MDP-PO-001@1.0.0", raw.Versions.HandoffSchema.Version);
- Assert.Equal(IngestContractError.InvalidJson, Assert.Throws<IngestContractException>(() =>
- preparer.PrepareApiPage(identity, PurchaseOrderSchemaRegistry.SourceVersion, body, new(1024, 100, 16), ["orders"])).Code);
- body[0] = 0;
- Assert.Equal((byte)'{', raw.Payload.Span[0]);
- }
- [Fact]
- public void ConfiguredArrayPreservesSourceBytesAndOffsets()
- {
- var body = Encoding.UTF8.GetBytes("""{"提示":"采购单","result":{"orders":[{"PoNo":"A","PoLine":"1"}]}}""");
- var identity = new IngestDatasetIdentity(1, 2, 3, 4, "LAB", PurchaseOrderSchemaRegistry.DatasetKey);
- var prepared = new IngestBatchPreparer(new PurchaseOrderSchemaRegistry()).PrepareApiPage(identity,
- PurchaseOrderSchemaRegistry.SourceVersion, body, new(1024, 100, 16), ["result", "orders"]);
- Assert.Equal(body, prepared.Batch.Payload.ToArray());
- var item = Assert.Single(prepared.Events);
- Assert.Equal("/result/orders/0", item.SourcePosition);
- Assert.Equal("""{"PoNo":"A","PoLine":"1"}""", Encoding.UTF8.GetString(body, item.PayloadOffset, item.PayloadLength));
- }
- [Theory]
- [InlineData("127.0.0.1", false)]
- [InlineData("169.254.169.254", false)]
- [InlineData("::ffff:127.0.0.1", false)]
- [InlineData("10.6.1.4", true)]
- [InlineData("10.6.1.5", false)]
- [InlineData("8.8.8.8", false)]
- public void TargetRequiresMatchingApprovedAddressAndRejectsProtectedRanges(string address, bool allowed)
- {
- var rule = new MdpApiPullTarget("supplier.example", 443, ["10.6.1.4"]);
- Assert.Equal(allowed, rule.AllowsAddress(IPAddress.Parse(address)));
- }
- [Theory]
- [InlineData("page", "page=2")]
- [InlineData("offset", "offset=2")]
- [InlineData("cursor", "cursor=opaque%2B2")]
- [InlineData("link", "page=3")]
- public void PageModesAdvanceUsingSourcePosition(string mode, string expected)
- {
- var plan = new MdpApiPullPlan("https://supplier.example/orders", Mode: mode, PositionParameter: mode,
- PageSize: 2, FirstPosition: mode == "offset" ? 0 : 1, NextCursorPath: "next", StableWindow: true);
- plan.Validate();
- var position = plan.Begin(DateTimeOffset.UtcNow, null);
- using var page = JsonDocument.Parse("""{"next":"opaque+2","orders":[{},{}]}""");
- var next = plan.Next(position, page.RootElement, 2, plan.Endpoint,
- MdpApiPullClient.ParseNext(["</orders?page=3>; rel=\"next\""]));
- Assert.Contains(expected, plan.RequestUri(next!).Query);
- }
- [Fact]
- public void TimePositionIncludesStableTieBreakAndRejectsUnsortedRows()
- {
- var plan = new MdpApiPullPlan("https://supplier.example/orders", Mode: "time", ResponsePath: "orders",
- PageSize: 2, SourceTimePath: "time", BusinessKeyPath: "key",
- InitialFromUtc: DateTimeOffset.Parse("2026-01-01T00:00:00Z"), StableWindow: true);
- var position = plan.Begin(DateTimeOffset.Parse("2026-01-03T00:00:00Z"), null);
- using var ok = JsonDocument.Parse("""{"orders":[{"time":"2026-01-02T00:00:00Z","key":"A"},{"time":"2026-01-02T00:00:00Z","key":"B"}]}""");
- var next = plan.Next(position, ok.RootElement, 2, plan.Endpoint, null)!;
- Assert.Equal("B", next.AfterKey);
- Assert.Contains("afterKey=B", plan.RequestUri(next).Query);
- Assert.Equal("PULL_WATERMARK_NOT_ORDERED", Assert.Throws<MdpApiPullException>(() =>
- plan.Next(next, ok.RootElement, 2, plan.Endpoint, null)).Code);
- }
- [Fact]
- public void FollowedLinkRequiresConfiguredOriginAndCursorCannotStall()
- {
- var link = new MdpApiPullPlan("https://supplier.example/orders", Mode: "link");
- var initial = link.Begin(DateTimeOffset.UtcNow, null);
- using var page = JsonDocument.Parse("""{"next":"first"}""");
- Assert.Equal("PULL_LINK_FORBIDDEN", Assert.Throws<MdpApiPullException>(() =>
- link.Next(initial, page.RootElement, 1, link.Endpoint, "https://other.example/orders")).Code);
- var cursor = link with { Mode = "cursor", NextCursorPath = "next" };
- Assert.Equal("PULL_POSITION_STALLED", Assert.Throws<MdpApiPullException>(() =>
- cursor.Next(initial with { Cursor = "first" }, page.RootElement, 1, cursor.Endpoint, null)).Code);
- }
- [Theory]
- [InlineData("curl", """curl --header "X-API-Key: secret-value" "https://supplier.example/orders?token=secret-value" """)]
- [InlineData("postman", """{"request":{"method":"GET","url":"https://supplier.example/orders?token=secret-value","auth":{"type":"apikey"}}}""")]
- [InlineData("openapi", """{"servers":[{"url":"https://supplier.example"}],"paths":{"/orders":{"get":{"security":[{"key":[]}]}}},"components":{"securitySchemes":{"key":{"type":"apiKey"}}}}""")]
- public void ImportCreatesDraftAndDoesNotReturnCredentials(string kind, string source)
- {
- var draft = MdpApiPullImport.Read(kind, source, null);
- Assert.Equal("https://supplier.example/orders", draft.Url);
- Assert.Equal("apiKey", draft.Auth);
- Assert.Null(draft.CredentialRef);
- Assert.DoesNotContain("secret-value", JsonSerializer.Serialize(draft));
- }
- [Fact]
- public void OpenApiSuggestsInlineResponseArrayAndKeepsExplicitNoAuth()
- {
- var draft = MdpApiPullImport.Read("openapi", """
- {"servers":[{"url":"https://supplier.example"}],"security":[{"key":[]}],
- "paths":{"/orders":{"get":{"security":[],"responses":{"200":{"content":{"application/json":{"schema":{
- "type":"object","properties":{"result":{"type":"object","properties":{"orders":{"type":"array"}}}}
- }}}}}}}},"components":{"securitySchemes":{"key":{"type":"apiKey"}}}}
- """, null);
- Assert.Equal("result.orders", draft.ResponsePath);
- Assert.Equal("none", draft.Auth);
- }
- [Fact]
- public void FixedQueryFiltersAreEncodedAndCannotOverridePositionOrCarryCredentials()
- {
- var filters = new Dictionary<string, string> { ["status"] = "paid & open" };
- var plan = new MdpApiPullPlan("https://supplier.example/orders", StableWindow: true, Query: filters);
- plan.Validate();
- var uri = plan.RequestUri(plan.Begin(DateTimeOffset.UtcNow, null));
- Assert.Contains("status=paid%20%26%20open", uri.AbsoluteUri);
- Assert.Contains("page=1", uri.Query);
- filters["Page"] = "9";
- Assert.Equal("PULL_CONFIG_INVALID", Assert.Throws<MdpApiPullException>(plan.Validate).Code);
- filters.Remove("Page");
- filters["X-API-Key"] = "secret";
- Assert.Equal("PULL_CONFIG_INVALID", Assert.Throws<MdpApiPullException>(plan.Validate).Code);
- }
- }
|