|
| 1 | +using System.IO.Compression; |
| 2 | +using System.Runtime.CompilerServices; |
| 3 | +using System.Text; |
| 4 | +using System.Text.Json; |
| 5 | +using Cosmos.DataTransfer.Common.UnitTests; |
| 6 | +using Cosmos.DataTransfer.Interfaces; |
| 7 | +using Microsoft.Extensions.Configuration; |
| 8 | +using Microsoft.Extensions.Logging; |
| 9 | +using Microsoft.Extensions.Logging.Abstractions; |
| 10 | +using Moq; |
| 11 | + |
| 12 | +namespace Cosmos.DataTransfer.JsonExtension.UnitTests; |
| 13 | + |
| 14 | +[TestClass] |
| 15 | +public class JsonFormatReaderTests |
| 16 | +{ |
| 17 | + private static readonly IConfiguration Config = TestHelpers.CreateConfig(new()); |
| 18 | + |
| 19 | + [DataTestMethod] |
| 20 | + [DataRow(false, false)] |
| 21 | + [DataRow(false, true)] |
| 22 | + [DataRow(true, false)] |
| 23 | + [DataRow(true, true)] |
| 24 | + public async Task ParseDataAsync_InvalidJson_PreservesOriginalLocation(bool array, bool nonSeekable) |
| 25 | + { |
| 26 | + var json = (array ? "[" : "") + "{\n \"id\": \"private-value\",\n \"name\": }\n" + (array ? "]" : ""); |
| 27 | + var bytes = Encoding.UTF8.GetBytes(json); |
| 28 | + JsonException expected; |
| 29 | + if (array) |
| 30 | + { |
| 31 | + expected = Assert.ThrowsException<JsonException>(() => JsonSerializer.Deserialize<Dictionary<string, object?>[]>(bytes)); |
| 32 | + } |
| 33 | + else |
| 34 | + { |
| 35 | + expected = Assert.ThrowsException<JsonException>(() => JsonSerializer.Deserialize<Dictionary<string, object?>>(bytes)); |
| 36 | + } |
| 37 | + |
| 38 | + var stream = new TestStream(bytes, nonSeekable, maxReadSize: 1); |
| 39 | + var logger = new Mock<ILogger>(); |
| 40 | + var error = await Assert.ThrowsExceptionAsync<JsonException>(async () => |
| 41 | + await ReadAsync(stream, logger.Object).ToListAsync()); |
| 42 | + |
| 43 | + Assert.AreEqual(expected.Path, error.Path); |
| 44 | + Assert.AreEqual(expected.LineNumber, error.LineNumber); |
| 45 | + Assert.AreEqual(expected.BytePositionInLine, error.BytePositionInLine); |
| 46 | + StringAssert.Contains(error.Message, "invalid start of a value"); |
| 47 | + logger.Verify(l => l.Log(LogLevel.Error, It.IsAny<EventId>(), |
| 48 | + It.Is<It.IsAnyType>((state, _) => state.ToString()!.Contains("stream 1") && !state.ToString()!.Contains("private-value")), |
| 49 | + error, It.IsAny<Func<It.IsAnyType, Exception?, string>>()), Times.Once); |
| 50 | + Assert.IsTrue(stream.Disposed); |
| 51 | + } |
| 52 | + |
| 53 | + [DataTestMethod] |
| 54 | + [DataRow("{}")] |
| 55 | + [DataRow("[{}]")] |
| 56 | + [DataRow("[]")] |
| 57 | + [DataRow("[null]")] |
| 58 | + [DataRow("null")] |
| 59 | + public async Task ParseDataAsync_ValidJson_WithBomWhitespaceAndShortReads(string json) |
| 60 | + { |
| 61 | + var bytes = Encoding.UTF8.GetPreamble().Concat(Encoding.UTF8.GetBytes(new string(' ', 20000) + "\r\n\t" + json)).ToArray(); |
| 62 | + var stream = new TestStream(bytes, nonSeekable: true, maxReadSize: 2); |
| 63 | + var items = await ReadAsync(stream).ToListAsync(); |
| 64 | + Assert.AreEqual(json is "[]" or "[null]" or "null" ? 0 : 1, items.Count); |
| 65 | + Assert.IsTrue(stream.Disposed); |
| 66 | + } |
| 67 | + |
| 68 | + [DataTestMethod] |
| 69 | + [DataRow("")] |
| 70 | + [DataRow(" \r\n\t")] |
| 71 | + [DataRow("{\"id\":1,}")] |
| 72 | + [DataRow("[{\"id\":1,}]")] |
| 73 | + [DataRow("{/*comment*/\"id\":1}")] |
| 74 | + [DataRow("{} {}")] |
| 75 | + [DataRow("[] []")] |
| 76 | + [DataRow("42")] |
| 77 | + public async Task ParseDataAsync_InvalidOrUnsupportedJson_Throws(string json) |
| 78 | + { |
| 79 | + var stream = new TestStream(Encoding.UTF8.GetBytes(json), nonSeekable: true); |
| 80 | + await Assert.ThrowsExceptionAsync<JsonException>(async () => await ReadAsync(stream).ToListAsync()); |
| 81 | + Assert.IsTrue(stream.Disposed); |
| 82 | + } |
| 83 | + |
| 84 | + [TestMethod] |
| 85 | + public async Task ParseDataAsync_LargeObject_PreservesNumericValues() |
| 86 | + { |
| 87 | + var json = "{\"value\":638676324052177500,\"text\":\"" + new string('a', 1500000) + "\"}"; |
| 88 | + var items = await ReadAsync(new TestStream(Encoding.UTF8.GetBytes(json), nonSeekable: true)).ToListAsync(); |
| 89 | + Assert.AreEqual(1, items.Count); |
| 90 | + Assert.AreEqual(638676324052177500L, items[0].GetValue("value")); |
| 91 | + Assert.AreEqual(1500000, ((string)items[0].GetValue("text")!).Length); |
| 92 | + } |
| 93 | + |
| 94 | + [TestMethod] |
| 95 | + public async Task ParseDataAsync_LargeArray_IsStreamedAndDisposedOnEarlyExit() |
| 96 | + { |
| 97 | + var bytes = Encoding.UTF8.GetBytes("[" + string.Join(",", Enumerable.Repeat("{\"id\":1}", 100000)) + "]"); |
| 98 | + var stream = new TestStream(bytes, nonSeekable: true); |
| 99 | + await using (var enumerator = ReadAsync(stream).GetAsyncEnumerator()) |
| 100 | + { |
| 101 | + Assert.IsTrue(await enumerator.MoveNextAsync()); |
| 102 | + Assert.AreEqual(1, enumerator.Current.GetValue("id")); |
| 103 | + Assert.IsTrue(stream.BytesRead < bytes.Length / 2, $"Read {stream.BytesRead} of {bytes.Length} bytes before first item"); |
| 104 | + } |
| 105 | + Assert.IsTrue(stream.Disposed); |
| 106 | + } |
| 107 | + |
| 108 | + [TestMethod] |
| 109 | + public async Task ParseDataAsync_LateArrayError_IsLoggedAndPropagated() |
| 110 | + { |
| 111 | + var json = "[" + string.Join(",", Enumerable.Repeat("{\"id\":1}", 10000)) + ",{\"name\":}]"; |
| 112 | + var stream = new TestStream(Encoding.UTF8.GetBytes(json), nonSeekable: true); |
| 113 | + var logger = new Mock<ILogger>(); |
| 114 | + int count = 0; |
| 115 | + var error = await Assert.ThrowsExceptionAsync<JsonException>(async () => |
| 116 | + { |
| 117 | + await foreach (var item in ReadAsync(stream, logger.Object)) |
| 118 | + count++; |
| 119 | + }); |
| 120 | + Assert.IsTrue(count > 0); |
| 121 | + Assert.IsTrue(error.Path!.EndsWith(".name", StringComparison.Ordinal)); |
| 122 | + Assert.AreEqual(0L, error.LineNumber); |
| 123 | + Assert.AreEqual((long)json.Length - 2, error.BytePositionInLine); |
| 124 | + logger.Verify(l => l.Log(LogLevel.Error, It.IsAny<EventId>(), It.IsAny<It.IsAnyType>(), |
| 125 | + error, It.IsAny<Func<It.IsAnyType, Exception?, string>>()), Times.Once); |
| 126 | + } |
| 127 | + |
| 128 | + [DataTestMethod] |
| 129 | + [DataRow(0)] |
| 130 | + [DataRow(20000)] |
| 131 | + public async Task ParseDataAsync_ReadFailure_IsNotSwallowed(int failAfter) |
| 132 | + { |
| 133 | + var bytes = Encoding.UTF8.GetBytes("{\"text\":\"" + new string('a', 50000) + "\"}"); |
| 134 | + var failure = new IOException("Synthetic read failure"); |
| 135 | + var stream = new TestStream(bytes, nonSeekable: false, failAfter: failAfter, failure: failure); |
| 136 | + var error = await Assert.ThrowsExceptionAsync<IOException>(async () => await ReadAsync(stream).ToListAsync()); |
| 137 | + Assert.AreSame(failure, error); |
| 138 | + Assert.IsTrue(stream.Disposed); |
| 139 | + } |
| 140 | + |
| 141 | + [TestMethod] |
| 142 | + public async Task ParseDataAsync_CanceledRead_IsNotSwallowed() |
| 143 | + { |
| 144 | + using var cancellation = new CancellationTokenSource(); |
| 145 | + cancellation.Cancel(); |
| 146 | + var stream = new TestStream(Encoding.UTF8.GetBytes("{}"), nonSeekable: true); |
| 147 | + await Assert.ThrowsExceptionAsync<OperationCanceledException>(async () => |
| 148 | + await ReadAsync(stream, cancellationToken: cancellation.Token).ToListAsync()); |
| 149 | + Assert.IsTrue(stream.Disposed); |
| 150 | + } |
| 151 | + |
| 152 | + [DataTestMethod] |
| 153 | + [DataRow("gz", false)] |
| 154 | + [DataRow("br", false)] |
| 155 | + [DataRow("zz", false)] |
| 156 | + [DataRow("gz", true)] |
| 157 | + [DataRow("br", true)] |
| 158 | + [DataRow("zz", true)] |
| 159 | + public async Task ParseDataAsync_CompressedSingleObject_IsSupported(string compression, bool longPrefix) |
| 160 | + { |
| 161 | + using var data = new MemoryStream(); |
| 162 | + using (Stream writer = compression switch |
| 163 | + { |
| 164 | + "gz" => new GZipStream(data, CompressionMode.Compress, leaveOpen: true), |
| 165 | + "br" => new BrotliStream(data, CompressionMode.Compress, leaveOpen: true), |
| 166 | + _ => new DeflateStream(data, CompressionMode.Compress, leaveOpen: true) |
| 167 | + }) |
| 168 | + { |
| 169 | + writer.Write(Encoding.UTF8.GetBytes((longPrefix ? new string(' ', 128 * 1024) + "\r\n\t" : "") + "{\"id\":1}")); |
| 170 | + } |
| 171 | + data.Position = 0; |
| 172 | + Stream stream = compression switch |
| 173 | + { |
| 174 | + "gz" => new GZipStream(data, CompressionMode.Decompress), |
| 175 | + "br" => new BrotliStream(data, CompressionMode.Decompress), |
| 176 | + _ => new DeflateStream(data, CompressionMode.Decompress) |
| 177 | + }; |
| 178 | + var items = await ReadAsync(stream).ToListAsync(); |
| 179 | + Assert.AreEqual(1, items.Count); |
| 180 | + Assert.AreEqual(1, items[0].GetValue("id")); |
| 181 | + } |
| 182 | + |
| 183 | + private static IAsyncEnumerable<IDataItem> ReadAsync(Stream stream, ILogger? logger = null, CancellationToken cancellationToken = default) |
| 184 | + { |
| 185 | + return new JsonFormatReader().ParseDataAsync(new StreamSource(stream), Config, logger ?? NullLogger.Instance, cancellationToken); |
| 186 | + } |
| 187 | + |
| 188 | + private sealed class StreamSource(Stream stream) : IComposableDataSource |
| 189 | + { |
| 190 | + public IEnumerable<IDataExtensionSettings> GetSettings() => Array.Empty<IDataExtensionSettings>(); |
| 191 | + |
| 192 | + public async IAsyncEnumerable<Stream?> ReadSourceAsync(IConfiguration config, ILogger logger, [EnumeratorCancellation] CancellationToken cancellationToken = default) |
| 193 | + { |
| 194 | + await Task.CompletedTask; |
| 195 | + yield return stream; |
| 196 | + } |
| 197 | + } |
| 198 | + |
| 199 | + private sealed class TestStream(byte[] bytes, bool nonSeekable, int maxReadSize = int.MaxValue, |
| 200 | + int failAfter = int.MaxValue, Exception? failure = null) : Stream |
| 201 | + { |
| 202 | + private readonly MemoryStream inner = new(bytes); |
| 203 | + public bool Disposed { get; private set; } |
| 204 | + public int BytesRead { get; private set; } |
| 205 | + public override bool CanSeek => !nonSeekable; |
| 206 | + public override bool CanRead => inner.CanRead; |
| 207 | + public override bool CanWrite => false; |
| 208 | + public override long Length => CanSeek ? inner.Length : throw new NotSupportedException(); |
| 209 | + public override long Position |
| 210 | + { |
| 211 | + get => CanSeek ? inner.Position : throw new NotSupportedException(); |
| 212 | + set => inner.Position = CanSeek ? value : throw new NotSupportedException(); |
| 213 | + } |
| 214 | + public override long Seek(long offset, SeekOrigin origin) => CanSeek ? inner.Seek(offset, origin) : throw new NotSupportedException(); |
| 215 | + public override void SetLength(long value) => throw new NotSupportedException(); |
| 216 | + public override void Write(byte[] buffer, int offset, int count) => throw new NotSupportedException(); |
| 217 | + public override void Flush() => throw new NotSupportedException(); |
| 218 | + |
| 219 | + public override int Read(byte[] buffer, int offset, int count) => Read(buffer.AsSpan(offset, count)); |
| 220 | + |
| 221 | + public override int Read(Span<byte> buffer) |
| 222 | + { |
| 223 | + if (BytesRead >= failAfter) |
| 224 | + throw failure ?? new IOException("Synthetic read failure"); |
| 225 | + int read = inner.Read(buffer[..Math.Min(buffer.Length, maxReadSize)]); |
| 226 | + BytesRead += read; |
| 227 | + return read; |
| 228 | + } |
| 229 | + |
| 230 | + public override ValueTask<int> ReadAsync(Memory<byte> buffer, CancellationToken cancellationToken = default) |
| 231 | + { |
| 232 | + cancellationToken.ThrowIfCancellationRequested(); |
| 233 | + return ValueTask.FromResult(Read(buffer.Span)); |
| 234 | + } |
| 235 | + |
| 236 | + protected override void Dispose(bool disposing) |
| 237 | + { |
| 238 | + Disposed = true; |
| 239 | + if (disposing) |
| 240 | + inner.Dispose(); |
| 241 | + base.Dispose(disposing); |
| 242 | + } |
| 243 | + } |
| 244 | +} |
0 commit comments