public async Task ReadAsStreamAsync_InvalidArgs_Throw()
        {
            var mc = new MultipartContent();

            using (Stream s = await mc.ReadAsStreamAsync())
            {
                Assert.True(s.CanRead);
                Assert.Equal(PlatformDetection.IsFullFramework, s.CanWrite);
                Assert.True(s.CanSeek);

                AssertExtensions.Throws <ArgumentNullException>("buffer", null, () => s.Read(null, 0, 0));
                AssertExtensions.Throws <ArgumentOutOfRangeException>("offset", () => s.Read(new byte[1], -1, 0));
                AssertExtensions.Throws <ArgumentOutOfRangeException>("count", () => s.Read(new byte[1], 0, -1));
                AssertExtensions.Throws <ArgumentException>("buffer", null, () => s.Read(new byte[1], 1, 1));

                AssertExtensions.Throws <ArgumentNullException>("buffer", null, () => { s.ReadAsync(null, 0, 0); });
                AssertExtensions.Throws <ArgumentOutOfRangeException>("offset", () => { s.ReadAsync(new byte[1], -1, 0); });
                AssertExtensions.Throws <ArgumentOutOfRangeException>("count", () => { s.ReadAsync(new byte[1], 0, -1); });
                AssertExtensions.Throws <ArgumentException>("buffer", null, () => { s.ReadAsync(new byte[1], 1, 1); });

                AssertExtensions.Throws <ArgumentOutOfRangeException>("value", () => s.Position = -1);

                // NETFX is not throwing exceptions but probably should since the stream should be considered read-only.
                if (!PlatformDetection.IsFullFramework)
                {
                    AssertExtensions.Throws <ArgumentOutOfRangeException>("value", () => s.Seek(-1, SeekOrigin.Begin));
                    AssertExtensions.Throws <ArgumentOutOfRangeException>("origin", () => s.Seek(0, (SeekOrigin)42));
                    Assert.Throws <NotSupportedException>(() => s.Write(new byte[1], 0, 0));
                    Assert.Throws <NotSupportedException>(() => s.Write(new Span <byte>(new byte[1], 0, 0)));
                    Assert.Throws <NotSupportedException>(() => { s.WriteAsync(new byte[1], 0, 0); });
                    Assert.Throws <NotSupportedException>(() => s.SetLength(1));
                }
            }
        }
Exemplo n.º 2
0
        public async Task ReadAsStreamAsync_InvalidArgs_Throw(bool readStreamAsync)
        {
            var mc = new MultipartContent();

            using (Stream s = await mc.ReadAsStreamAsync(readStreamAsync))
            {
                Assert.True(s.CanRead);
                Assert.False(s.CanWrite);
                Assert.True(s.CanSeek);

                AssertExtensions.Throws <ArgumentNullException>("buffer", null, () => s.Read(null, 0, 0));
                AssertExtensions.Throws <ArgumentOutOfRangeException>("offset", () => s.Read(new byte[1], -1, 0));
                AssertExtensions.Throws <ArgumentOutOfRangeException>("count", () => s.Read(new byte[1], 0, -1));
                AssertExtensions.Throws <ArgumentException>("buffer", null, () => s.Read(new byte[1], 1, 1));

                AssertExtensions.Throws <ArgumentNullException>("buffer", null, () => { s.ReadAsync(null, 0, 0); });
                AssertExtensions.Throws <ArgumentOutOfRangeException>("offset", () => { s.ReadAsync(new byte[1], -1, 0); });
                AssertExtensions.Throws <ArgumentOutOfRangeException>("count", () => { s.ReadAsync(new byte[1], 0, -1); });
                AssertExtensions.Throws <ArgumentException>("buffer", null, () => { s.ReadAsync(new byte[1], 1, 1); });

                AssertExtensions.Throws <ArgumentOutOfRangeException>("value", () => s.Position = -1);
                AssertExtensions.Throws <ArgumentOutOfRangeException>("value", () => s.Seek(-1, SeekOrigin.Begin));
                AssertExtensions.Throws <ArgumentOutOfRangeException>("origin", () => s.Seek(0, (SeekOrigin)42));
                Assert.Throws <NotSupportedException>(() => s.Write(new byte[1], 0, 0));
                Assert.Throws <NotSupportedException>(() => s.Write(new Span <byte>(new byte[1], 0, 0)));
                Assert.Throws <NotSupportedException>(() => { s.WriteAsync(new byte[1], 0, 0); });
                Assert.Throws <NotSupportedException>(() => s.SetLength(1));
            }
        }
Exemplo n.º 3
0
        public async Task ImportStream(string aggregateType, long recordCount)
        {
            var moqRepo = new Mock <IRebalanceRepository>();

            moqRepo.Setup((lst, id) =>
            {
                Assert.Equal(recordCount, lst.Count);
                return(Task.FromResult(recordCount));
            });
            using var modelContent   = new MultipartContent("mixed", "++++++++");
            using var templateStream = await $"{aggregateType}.xml".AsStreamContent();
            using var dataStream     = await $"{aggregateType}.txt".AsStreamContent();
            modelContent.AddContent(
                aggregateType,
                templateStream,
                dataStream);

            var section = new MultipartSection
            {
                Body = await modelContent.ReadAsStreamAsync()
            };

            var sut = new ImportController(_loggerFactory.CreateLogger <ImportController>(), moqRepo.Object);
            await sut.ImportStream(section);
        }
Exemplo n.º 4
0
        public async Task Import(string correlationKey)
        {
            var factory = new WebApplicationFactory <Startup>();
            var moqRepo = new Mock <IRebalanceRepository>();
            var client  = factory.WithWebHostBuilder(bldr =>
            {
                bldr.ConfigureServices(services =>
                {
                    services.AddSingleton(moqRepo.Object)
                    .AddTransient(provider => moqRepo.Object);
                });
            }).CreateClient();

            using var content = new MultipartContent("mixed", "========");
            content.Headers.Add("correlationKey", correlationKey);

            using var portfolioContent = new MultipartContent("mixed", "++++++++");
            using var templateStream   = await "Household.xml".AsStreamContent();
            using var dataStream       = await "Household.txt".AsStreamContent();
            portfolioContent.AddContent(
                "Household",
                templateStream,
                dataStream);

            using var streamContent           = new StreamContent(await portfolioContent.ReadAsStreamAsync());
            streamContent.Headers.ContentType = MediaTypeHeaderValue.Parse("multipart/mixed");
            streamContent.Headers.Add("AggregateType", "Portfolio");
            content.Add(streamContent);
            moqRepo.Setup((lst, id) => Task.FromResult((long)lst.Count));
            var response = await client.PostAsync("/api/Import", content);

            Assert.True(response.IsSuccessStatusCode);
            moqRepo.Verify <Portfolio>();
        }
Exemplo n.º 5
0
        private static async Task <string> MultipartContentToStringAsync(MultipartContent content, MultipartContentToStringMode mode, bool async)
        {
            Stream stream;

            switch (mode)
            {
            case MultipartContentToStringMode.ReadAsStreamAsync:
                stream = await content.ReadAsStreamAsync(async);

                break;

            default:
                stream = new MemoryStream();
                if (async)
                {
                    await content.CopyToAsync(stream);
                }
                else
                {
                    content.CopyTo(stream, null, default);
                }
                stream.Position = 0;
                break;
            }

            using (var reader = new StreamReader(stream))
            {
                return(await reader.ReadToEndAsync());
            }
        }
Exemplo n.º 6
0
        public async Task ReadAsStreamAsync_CreateContentReadStreamAsyncThrows_ExceptionStoredInTask()
        {
            var mc = new MultipartContent();

            mc.Add(new MockContent());
            Task t = mc.ReadAsStreamAsync();
            await Assert.ThrowsAsync <NotImplementedException>(() => t);
        }
Exemplo n.º 7
0
        public async Task ReadAsStreamAsync_Seek_JumpsToSpecifiedPosition(bool nestedContent, bool readStreamAsync)
        {
            var mc = new MultipartContent();

            if (nestedContent)
            {
                mc.Add(new ByteArrayContent(Encoding.UTF8.GetBytes("This is a ByteArrayContent")));
                mc.Add(new StringContent("This is a StringContent"));
                mc.Add(new ByteArrayContent(Encoding.UTF8.GetBytes("Another ByteArrayContent :-)")));
            }

            var memStream = new MemoryStream();
            await mc.CopyToAsync(memStream);

            byte[] buf1 = new byte[1], buf2 = new byte[1];
            using (Stream s = await mc.ReadAsStreamAsync(readStreamAsync))
            {
                var targets = new[]
                {
                    new { Origin = SeekOrigin.Begin, Offset = memStream.Length / 2 },
                    new { Origin = SeekOrigin.Begin, Offset = memStream.Length - 1 },
                    new { Origin = SeekOrigin.Begin, Offset = memStream.Length },
                    new { Origin = SeekOrigin.Begin, Offset = memStream.Length + 1 },
                    new { Origin = SeekOrigin.Begin, Offset = 0L },
                    new { Origin = SeekOrigin.Begin, Offset = 1L },

                    new { Origin = SeekOrigin.Current, Offset = 1L },
                    new { Origin = SeekOrigin.Current, Offset = 2L },
                    new { Origin = SeekOrigin.Current, Offset = -2L },
                    new { Origin = SeekOrigin.Current, Offset = 0L },
                    new { Origin = SeekOrigin.Current, Offset = 1000L },

                    new { Origin = SeekOrigin.End, Offset = 0L },
                    new { Origin = SeekOrigin.End, Offset = memStream.Length },
                    new { Origin = SeekOrigin.End, Offset = memStream.Length / 2 },
                };
                foreach (var target in targets)
                {
                    memStream.Seek(target.Offset, target.Origin);
                    s.Seek(target.Offset, target.Origin);
                    Assert.Equal(memStream.Position, s.Position);

                    Assert.Equal(memStream.Read(buf1, 0, 1), s.Read(buf2, 0, 1));
                    Assert.Equal(buf1[0], buf2[0]);
                }
            }
        }
Exemplo n.º 8
0
        public async Task ReadAsStreamAsync_CustomEncodingSelector_SelectorIsCalledWithCustomState(bool async)
        {
            var mc = new MultipartContent();

            var stringContent = new StringContent("foo");

            stringContent.Headers.Add("StringContent", "foo");
            mc.Add(stringContent);

            var byteArrayContent = new ByteArrayContent(Encoding.ASCII.GetBytes("foo"));

            byteArrayContent.Headers.Add("ByteArrayContent", "foo");
            mc.Add(byteArrayContent);

            bool seenStringContent = false, seenByteArrayContent = false;

            mc.HeaderEncodingSelector = (name, content) =>
            {
                if (ReferenceEquals(content, stringContent) && name == "StringContent")
                {
                    seenStringContent = true;
                }

                if (ReferenceEquals(content, byteArrayContent) && name == "ByteArrayContent")
                {
                    seenByteArrayContent = true;
                }

                return(null);
            };

            var dummy = new MemoryStream();

            if (async)
            {
                await(await mc.ReadAsStreamAsync()).CopyToAsync(dummy);
            }
            else
            {
                mc.ReadAsStream().CopyTo(dummy);
            }

            Assert.True(seenStringContent);
            Assert.True(seenByteArrayContent);
        }
Exemplo n.º 9
0
        public async Task ReadAsStreamAsync_CanSeekEvenIfAllStreamsNotSeekale(bool firstContentSeekable, bool secondContentSeekable, bool readStreamAsync)
        {
            var c = new MultipartContent();

            c.Add(new StreamContent(firstContentSeekable ? new MemoryStream(new byte[42]) : new NonSeekableMemoryStream(new byte[42])));
            c.Add(new StreamContent(secondContentSeekable ? new MemoryStream(new byte[42]) : new NonSeekableMemoryStream(new byte[1])));
            using (Stream s = await c.ReadAsStreamAsync(readStreamAsync))
            {
                Assert.True(s.CanSeek);
                Assert.InRange(s.Length, 43, int.MaxValue);

                s.Position = 1;
                Assert.Equal(1, s.Position);

                s.Seek(20, SeekOrigin.Current);
                Assert.Equal(21, s.Position);
            }
        }
Exemplo n.º 10
0
        public async Task ReadAsStreamAsync_OperationsThatDontChangePosition()
        {
            var mc = new MultipartContent();

            using (Stream s = await mc.ReadAsStreamAsync())
            {
                Assert.Equal(0, s.Read(new byte[1], 0, 0));
                Assert.Equal(0, s.Position);

                Assert.Equal(0, await s.ReadAsync(new byte[1], 0, 0));
                Assert.Equal(0, s.Position);

                s.Flush();
                Assert.Equal(0, s.Position);

                await s.FlushAsync();

                Assert.Equal(0, s.Position);
            }
        }
Exemplo n.º 11
0
        public async Task ThrowFromImportStreamWhenRecordTypeIsNotADomainObject()
        {
            var moqRepo = new Mock <IRebalanceRepository>();

            moqRepo.Setup((lst, id) => Task.FromResult((long)lst.Count));
            using var modelContent   = new MultipartContent("mixed", "++++++++");
            using var templateStream = await $"Model.Bad.xml".AsStreamContent();
            using var dataStream     = await $"Model.txt".AsStreamContent();
            modelContent.AddContent(
                "Model",
                templateStream,
                dataStream);

            var section = new MultipartSection
            {
                Body = await modelContent.ReadAsStreamAsync()
            };

            var sut = new ImportController(_loggerFactory.CreateLogger <ImportController>(), moqRepo.Object);
            var ex  = await Assert.ThrowsAsync <InvalidOperationException>(async() => await sut.ImportStream(section));

            Assert.Equal("Cannot import records into object of type BadModel", ex.Message);
        }
Exemplo n.º 12
0
        public async Task ReadAsStreamAsync_Seek_JumpsToSpecifiedPosition(bool nestedContent)
        {
            var mc = new MultipartContent();
            if (nestedContent)
            {
                mc.Add(new ByteArrayContent(Encoding.UTF8.GetBytes("This is a ByteArrayContent")));
                mc.Add(new StringContent("This is a StringContent"));
                mc.Add(new ByteArrayContent(Encoding.UTF8.GetBytes("Another ByteArrayContent :-)")));
            }

            var memStream = new MemoryStream();
            await mc.CopyToAsync(memStream);

            byte[] buf1 = new byte[1], buf2 = new byte[1];
            using (Stream s = await mc.ReadAsStreamAsync())
            {
                var targets = new[]
                {
                    new { Origin = SeekOrigin.Begin, Offset = memStream.Length / 2 },
                    new { Origin = SeekOrigin.Begin, Offset = memStream.Length - 1 },
                    new { Origin = SeekOrigin.Begin, Offset = memStream.Length },
                    new { Origin = SeekOrigin.Begin, Offset = memStream.Length + 1 },
                    new { Origin = SeekOrigin.Begin, Offset = 0L },
                    new { Origin = SeekOrigin.Begin, Offset = 1L },

                    new { Origin = SeekOrigin.Current, Offset = 1L },
                    new { Origin = SeekOrigin.Current, Offset = 2L },
                    new { Origin = SeekOrigin.Current, Offset = -2L },
                    new { Origin = SeekOrigin.Current, Offset = 0L },
                    new { Origin = SeekOrigin.Current, Offset = 1000L },

                    new { Origin = SeekOrigin.End, Offset = 0L },
                    new { Origin = SeekOrigin.End, Offset = memStream.Length },
                    new { Origin = SeekOrigin.End, Offset = memStream.Length / 2 },
                };
                foreach (var target in targets)
                {
                    memStream.Seek(target.Offset, target.Origin);
                    s.Seek(target.Offset, target.Origin);
                    Assert.Equal(memStream.Position, s.Position);

                    Assert.Equal(memStream.Read(buf1, 0, 1), s.Read(buf2, 0, 1));
                    Assert.Equal(buf1[0], buf2[0]);
                }
            }
        }
Exemplo n.º 13
0
        private static async Task<string> MultipartContentToStringAsync(MultipartContent content, MultipartContentToStringMode mode)
        {
            Stream stream;

            switch (mode)
            {
                case MultipartContentToStringMode.ReadAsStreamAsync:
                    stream = await content.ReadAsStreamAsync();
                    break;

                default:
                    stream = new MemoryStream();
                    await content.CopyToAsync(stream);
                    stream.Position = 0;
                    break;
            }

            using (var reader = new StreamReader(stream))
            {
                return await reader.ReadToEndAsync();
            }
        }
Exemplo n.º 14
0
 public async Task ReadAsStreamAsync_CreateContentReadStreamAsyncThrows_ExceptionStoredInTask()
 {
     var mc = new MultipartContent();
     mc.Add(new MockContent());
     Task t = mc.ReadAsStreamAsync();
     await Assert.ThrowsAsync<NotImplementedException>(() => t);
 }
Exemplo n.º 15
0
        public async Task ReadAsStreamAsync_OperationsThatDontChangePosition()
        {
            var mc = new MultipartContent();
            using (Stream s = await mc.ReadAsStreamAsync())
            {
                Assert.Equal(0, s.Read(new byte[1], 0, 0));
                Assert.Equal(0, s.Position);

                Assert.Equal(0, await s.ReadAsync(new byte[1], 0, 0));
                Assert.Equal(0, s.Position);

                s.Flush();
                Assert.Equal(0, s.Position);

                await s.FlushAsync();
                Assert.Equal(0, s.Position);
            }
        }
Exemplo n.º 16
0
        public async Task ReadAsStreamAsync_InvalidArgs_Throw()
        {
            var mc = new MultipartContent();
            using (Stream s = await mc.ReadAsStreamAsync())
            {
                Assert.True(s.CanRead);
                Assert.False(s.CanWrite);
                Assert.True(s.CanSeek);

                Assert.Throws<ArgumentNullException>("buffer", () => s.Read(null, 0, 0));
                Assert.Throws<ArgumentOutOfRangeException>("offset", () => s.Read(new byte[1], -1, 0));
                Assert.Throws<ArgumentOutOfRangeException>("count", () => s.Read(new byte[1], 0, -1));
                Assert.Throws<ArgumentException>("buffer", () => s.Read(new byte[1], 1, 1));

                Assert.Throws<ArgumentNullException>("buffer", () => { s.ReadAsync(null, 0, 0); });
                Assert.Throws<ArgumentOutOfRangeException>("offset", () => { s.ReadAsync(new byte[1], -1, 0); });
                Assert.Throws<ArgumentOutOfRangeException>("count", () => { s.ReadAsync(new byte[1], 0, -1); });
                Assert.Throws<ArgumentException>("buffer", () => { s.ReadAsync(new byte[1], 1, 1); });

                Assert.Throws<ArgumentOutOfRangeException>("value", () => s.Position = -1);
                Assert.Throws<ArgumentOutOfRangeException>("value", () => s.Seek(-1, SeekOrigin.Begin));
                Assert.Throws<ArgumentOutOfRangeException>("origin", () => s.Seek(0, (SeekOrigin)42));

                Assert.Throws<NotSupportedException>(() => s.Write(new byte[1], 0, 0));
                Assert.Throws<NotSupportedException>(() => { s.WriteAsync(new byte[1], 0, 0); });
                Assert.Throws<NotSupportedException>(() => s.SetLength(1));
            }
        }
Exemplo n.º 17
0
        public async Task ReadAsStreamAsync_CustomEncodingSelector_CustomEncodingIsUsed(bool async)
        {
            var mc = new MultipartContent("subtype", "fooBoundary");

            var stringContent = new StringContent("bar1");

            stringContent.Headers.Add("latin1", "\uD83D\uDE00");
            mc.Add(stringContent);

            var byteArrayContent = new ByteArrayContent(Encoding.ASCII.GetBytes("bar2"));

            byteArrayContent.Headers.Add("utf8", "\uD83D\uDE00");
            mc.Add(byteArrayContent);

            byteArrayContent = new ByteArrayContent(Encoding.ASCII.GetBytes("bar3"));
            byteArrayContent.Headers.Add("ascii", "\uD83D\uDE00");
            mc.Add(byteArrayContent);

            byteArrayContent = new ByteArrayContent(Encoding.ASCII.GetBytes("bar4"));
            byteArrayContent.Headers.Add("default", "\uD83D\uDE00");
            mc.Add(byteArrayContent);

            mc.HeaderEncodingSelector = (name, _) => name switch
            {
                "latin1" => Encoding.Latin1,
                "utf8" => Encoding.UTF8,
                "ascii" => Encoding.ASCII,
                _ => null
            };

            var ms = new MemoryStream();

            if (async)
            {
                await(await mc.ReadAsStreamAsync()).CopyToAsync(ms);
            }
            else
            {
                mc.ReadAsStream().CopyTo(ms);
            }

            byte[] expected = Concat(
                Encoding.Latin1.GetBytes("--fooBoundary\r\n"),
                Encoding.Latin1.GetBytes("Content-Type: text/plain; charset=utf-8\r\n"),
                Encoding.Latin1.GetBytes("latin1: "),
                Encoding.Latin1.GetBytes("\uD83D\uDE00"),
                Encoding.Latin1.GetBytes("\r\n\r\n"),
                Encoding.Latin1.GetBytes("bar1"),
                Encoding.Latin1.GetBytes("\r\n--fooBoundary\r\n"),
                Encoding.Latin1.GetBytes("utf8: "),
                Encoding.UTF8.GetBytes("\uD83D\uDE00"),
                Encoding.Latin1.GetBytes("\r\n\r\n"),
                Encoding.Latin1.GetBytes("bar2"),
                Encoding.Latin1.GetBytes("\r\n--fooBoundary\r\n"),
                Encoding.Latin1.GetBytes("ascii: "),
                Encoding.ASCII.GetBytes("\uD83D\uDE00"),
                Encoding.Latin1.GetBytes("\r\n\r\n"),
                Encoding.Latin1.GetBytes("bar3"),
                Encoding.Latin1.GetBytes("\r\n--fooBoundary\r\n"),
                Encoding.Latin1.GetBytes("default: "),
                Encoding.Latin1.GetBytes("\uD83D\uDE00"),
                Encoding.Latin1.GetBytes("\r\n\r\n"),
                Encoding.Latin1.GetBytes("bar4"),
                Encoding.Latin1.GetBytes("\r\n--fooBoundary--\r\n"));

            Assert.Equal(expected, ms.ToArray());
Exemplo n.º 18
0
        public async Task ReadAsStreamAsync_CanSeekEvenIfAllStreamsNotSeekale(bool firstContentSeekable, bool secondContentSeekable)
        {
            var c = new MultipartContent();
            c.Add(new StreamContent(firstContentSeekable ? new MemoryStream(new byte[42]) : new NonSeekableMemoryStream(new byte[42])));
            c.Add(new StreamContent(secondContentSeekable ? new MemoryStream(new byte[42]) : new NonSeekableMemoryStream(new byte[1])));
            using (Stream s = await c.ReadAsStreamAsync())
            {
                Assert.True(s.CanSeek);
                Assert.InRange(s.Length, 43, int.MaxValue);

                s.Position = 1;
                Assert.Equal(1, s.Position);

                s.Seek(20, SeekOrigin.Current);
                Assert.Equal(21, s.Position);
            }
        }