MdpApiPullTests.cs 7.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140
  1. using System.Net;
  2. using System.Text;
  3. using System.Text.Json;
  4. using Admin.NET.Plugin.AiDOP.DataPlatform.Core;
  5. using Admin.NET.Plugin.AiDOP.DataPlatform.UnifiedIngress;
  6. using Xunit;
  7. namespace Admin.NET.Plugin.AiDOP.Tests.DataPlatform;
  8. public sealed class MdpApiPullTests
  9. {
  10. [Fact]
  11. public void MalformedApiPageHasAnImmutableRawCaptureBeforeParsing()
  12. {
  13. var body = Encoding.UTF8.GetBytes("{\"orders\":[");
  14. var identity = new IngestDatasetIdentity(1, 2, 3, 4, "LAB", PurchaseOrderSchemaRegistry.DatasetKey);
  15. var preparer = new IngestBatchPreparer(new PurchaseOrderSchemaRegistry());
  16. var raw = preparer.CaptureApiPage(identity, PurchaseOrderSchemaRegistry.SourceVersion, body, new(1024, 100, 16));
  17. Assert.Equal(body, raw.Payload.ToArray());
  18. Assert.Equal(0, raw.AcceptedRowCount);
  19. Assert.Equal("MDP-PO-001@1.0.0", raw.Versions.HandoffSchema.Version);
  20. Assert.Equal(IngestContractError.InvalidJson, Assert.Throws<IngestContractException>(() =>
  21. preparer.PrepareApiPage(identity, PurchaseOrderSchemaRegistry.SourceVersion, body, new(1024, 100, 16), ["orders"])).Code);
  22. body[0] = 0;
  23. Assert.Equal((byte)'{', raw.Payload.Span[0]);
  24. }
  25. [Fact]
  26. public void ConfiguredArrayPreservesSourceBytesAndOffsets()
  27. {
  28. var body = Encoding.UTF8.GetBytes("""{"提示":"采购单","result":{"orders":[{"PoNo":"A","PoLine":"1"}]}}""");
  29. var identity = new IngestDatasetIdentity(1, 2, 3, 4, "LAB", PurchaseOrderSchemaRegistry.DatasetKey);
  30. var prepared = new IngestBatchPreparer(new PurchaseOrderSchemaRegistry()).PrepareApiPage(identity,
  31. PurchaseOrderSchemaRegistry.SourceVersion, body, new(1024, 100, 16), ["result", "orders"]);
  32. Assert.Equal(body, prepared.Batch.Payload.ToArray());
  33. var item = Assert.Single(prepared.Events);
  34. Assert.Equal("/result/orders/0", item.SourcePosition);
  35. Assert.Equal("""{"PoNo":"A","PoLine":"1"}""", Encoding.UTF8.GetString(body, item.PayloadOffset, item.PayloadLength));
  36. }
  37. [Theory]
  38. [InlineData("127.0.0.1", false)]
  39. [InlineData("169.254.169.254", false)]
  40. [InlineData("::ffff:127.0.0.1", false)]
  41. [InlineData("10.6.1.4", true)]
  42. [InlineData("10.6.1.5", false)]
  43. [InlineData("8.8.8.8", false)]
  44. public void TargetRequiresMatchingApprovedAddressAndRejectsProtectedRanges(string address, bool allowed)
  45. {
  46. var rule = new MdpApiPullTarget("supplier.example", 443, ["10.6.1.4"]);
  47. Assert.Equal(allowed, rule.AllowsAddress(IPAddress.Parse(address)));
  48. }
  49. [Theory]
  50. [InlineData("page", "page=2")]
  51. [InlineData("offset", "offset=2")]
  52. [InlineData("cursor", "cursor=opaque%2B2")]
  53. [InlineData("link", "page=3")]
  54. public void PageModesAdvanceUsingSourcePosition(string mode, string expected)
  55. {
  56. var plan = new MdpApiPullPlan("https://supplier.example/orders", Mode: mode, PositionParameter: mode,
  57. PageSize: 2, FirstPosition: mode == "offset" ? 0 : 1, NextCursorPath: "next", StableWindow: true);
  58. plan.Validate();
  59. var position = plan.Begin(DateTimeOffset.UtcNow, null);
  60. using var page = JsonDocument.Parse("""{"next":"opaque+2","orders":[{},{}]}""");
  61. var next = plan.Next(position, page.RootElement, 2, plan.Endpoint,
  62. MdpApiPullClient.ParseNext(["</orders?page=3>; rel=\"next\""]));
  63. Assert.Contains(expected, plan.RequestUri(next!).Query);
  64. }
  65. [Fact]
  66. public void TimePositionIncludesStableTieBreakAndRejectsUnsortedRows()
  67. {
  68. var plan = new MdpApiPullPlan("https://supplier.example/orders", Mode: "time", ResponsePath: "orders",
  69. PageSize: 2, SourceTimePath: "time", BusinessKeyPath: "key",
  70. InitialFromUtc: DateTimeOffset.Parse("2026-01-01T00:00:00Z"), StableWindow: true);
  71. var position = plan.Begin(DateTimeOffset.Parse("2026-01-03T00:00:00Z"), null);
  72. using var ok = JsonDocument.Parse("""{"orders":[{"time":"2026-01-02T00:00:00Z","key":"A"},{"time":"2026-01-02T00:00:00Z","key":"B"}]}""");
  73. var next = plan.Next(position, ok.RootElement, 2, plan.Endpoint, null)!;
  74. Assert.Equal("B", next.AfterKey);
  75. Assert.Contains("afterKey=B", plan.RequestUri(next).Query);
  76. Assert.Equal("PULL_WATERMARK_NOT_ORDERED", Assert.Throws<MdpApiPullException>(() =>
  77. plan.Next(next, ok.RootElement, 2, plan.Endpoint, null)).Code);
  78. }
  79. [Fact]
  80. public void FollowedLinkRequiresConfiguredOriginAndCursorCannotStall()
  81. {
  82. var link = new MdpApiPullPlan("https://supplier.example/orders", Mode: "link");
  83. var initial = link.Begin(DateTimeOffset.UtcNow, null);
  84. using var page = JsonDocument.Parse("""{"next":"first"}""");
  85. Assert.Equal("PULL_LINK_FORBIDDEN", Assert.Throws<MdpApiPullException>(() =>
  86. link.Next(initial, page.RootElement, 1, link.Endpoint, "https://other.example/orders")).Code);
  87. var cursor = link with { Mode = "cursor", NextCursorPath = "next" };
  88. Assert.Equal("PULL_POSITION_STALLED", Assert.Throws<MdpApiPullException>(() =>
  89. cursor.Next(initial with { Cursor = "first" }, page.RootElement, 1, cursor.Endpoint, null)).Code);
  90. }
  91. [Theory]
  92. [InlineData("curl", """curl --header "X-API-Key: secret-value" "https://supplier.example/orders?token=secret-value" """)]
  93. [InlineData("postman", """{"request":{"method":"GET","url":"https://supplier.example/orders?token=secret-value","auth":{"type":"apikey"}}}""")]
  94. [InlineData("openapi", """{"servers":[{"url":"https://supplier.example"}],"paths":{"/orders":{"get":{"security":[{"key":[]}]}}},"components":{"securitySchemes":{"key":{"type":"apiKey"}}}}""")]
  95. public void ImportCreatesDraftAndDoesNotReturnCredentials(string kind, string source)
  96. {
  97. var draft = MdpApiPullImport.Read(kind, source, null);
  98. Assert.Equal("https://supplier.example/orders", draft.Url);
  99. Assert.Equal("apiKey", draft.Auth);
  100. Assert.Null(draft.CredentialRef);
  101. Assert.DoesNotContain("secret-value", JsonSerializer.Serialize(draft));
  102. }
  103. [Fact]
  104. public void OpenApiSuggestsInlineResponseArrayAndKeepsExplicitNoAuth()
  105. {
  106. var draft = MdpApiPullImport.Read("openapi", """
  107. {"servers":[{"url":"https://supplier.example"}],"security":[{"key":[]}],
  108. "paths":{"/orders":{"get":{"security":[],"responses":{"200":{"content":{"application/json":{"schema":{
  109. "type":"object","properties":{"result":{"type":"object","properties":{"orders":{"type":"array"}}}}
  110. }}}}}}}},"components":{"securitySchemes":{"key":{"type":"apiKey"}}}}
  111. """, null);
  112. Assert.Equal("result.orders", draft.ResponsePath);
  113. Assert.Equal("none", draft.Auth);
  114. }
  115. [Fact]
  116. public void FixedQueryFiltersAreEncodedAndCannotOverridePositionOrCarryCredentials()
  117. {
  118. var filters = new Dictionary<string, string> { ["status"] = "paid & open" };
  119. var plan = new MdpApiPullPlan("https://supplier.example/orders", StableWindow: true, Query: filters);
  120. plan.Validate();
  121. var uri = plan.RequestUri(plan.Begin(DateTimeOffset.UtcNow, null));
  122. Assert.Contains("status=paid%20%26%20open", uri.AbsoluteUri);
  123. Assert.Contains("page=1", uri.Query);
  124. filters["Page"] = "9";
  125. Assert.Equal("PULL_CONFIG_INVALID", Assert.Throws<MdpApiPullException>(plan.Validate).Code);
  126. filters.Remove("Page");
  127. filters["X-API-Key"] = "secret";
  128. Assert.Equal("PULL_CONFIG_INVALID", Assert.Throws<MdpApiPullException>(plan.Validate).Code);
  129. }
  130. }