public async Task DestinationThrows_Reported(bool isRequest)
        {
            var events = TestEventListener.Collect();

            const int SourceSize   = 10;
            const int BytesPerRead = 3;

            var clock               = new ManualClock();
            var sourceWaitTime      = TimeSpan.FromMilliseconds(12345);
            var destinationWaitTime = TimeSpan.FromMilliseconds(42);
            var source              = new SlowStream(new MemoryStream(new byte[SourceSize]), clock, sourceWaitTime)
            {
                MaxBytesPerRead = BytesPerRead
            };
            var destination = new SlowStream(new ThrowStream(), clock, destinationWaitTime);

            var(result, error) = await StreamCopier.CopyAsync(isRequest, source, destination, clock, CancellationToken.None);

            Assert.Equal(StreamCopyResult.OutputError, result);
            Assert.IsAssignableFrom <IOException>(error);

            AssertContentTransferred(events, isRequest,
                                     contentLength: BytesPerRead,
                                     iops: 1,
                                     firstReadTime: sourceWaitTime,
                                     readTime: sourceWaitTime,
                                     writeTime: destinationWaitTime);
        }
Exemple #2
0
        public async Task VerifyTimeoutOnReadAsync(Func <Stream, Task <string> > readAsync)
        {
            // Arrange
            var expectedDownload     = "download";
            var expectedMilliseconds = 25;
            var memoryStream         = GetStream("foobar");
            var slowStream           = new SlowStream(memoryStream)
            {
                DelayPerByte = TimeSpan.FromMilliseconds(expectedMilliseconds * 2)
            };
            var timeoutStream = new DownloadTimeoutStream(
                expectedDownload,
                slowStream,
                TimeSpan.FromMilliseconds(expectedMilliseconds));

            // Act & Assert
            var exception = await Assert.ThrowsAsync <IOException>(() =>
                                                                   readAsync(timeoutStream));

            Assert.Equal(
                $"The download of '{expectedDownload}' timed out because " +
                $"no data was received for {expectedMilliseconds}ms.",
                exception.Message);
            Assert.IsType <TimeoutException>(exception.InnerException);
        }
Exemple #3
0
        public void ReadExactlyArray()
        {
            byte[] abySource = new byte[] { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };

            using (Stream streamSource = new MemoryStream(abySource))
                using (Stream stream = new SlowStream(streamSource))
                {
                    byte[] buffer = new byte[20];
                    stream.ReadExactly(buffer, 3, 8);
                    CollectionAssert.AreEqual(new byte[3].Concat(abySource.Take(8)).Concat(new byte[9]), buffer);
                }

            using (Stream streamSource = new MemoryStream(abySource))
                using (Stream stream = new SlowStream(streamSource))
                {
                    byte[] buffer = new byte[20];
                    stream.ReadExactly(buffer, 5, 11);
                    CollectionAssert.AreEqual(new byte[5].Concat(abySource).Concat(new byte[4]), buffer);
                }

            using (Stream streamSource = new MemoryStream(abySource))
                using (Stream stream = new SlowStream(streamSource))
                {
                    byte[] buffer = new byte[20];
                    Assert.Throws <EndOfStreamException>(() => stream.ReadExactly(buffer, 5, 12));
                }
        }
Exemple #4
0
        public async Task VerifyTimeoutOnReadAsync(Func <Stream, Task <string> > readAsync)
        {
            // Arrange
            var expectedDownload = "download";
            var timeout          = TimeSpan.FromMilliseconds(25);
            var memoryStream     = GetStream("foobar");

            using (var cancellationTokenSource = new CancellationTokenSource())
            {
                var slowStream = new SlowStream(memoryStream, cancellationTokenSource.Token)
                {
                    DelayPerByte = TimeSpan.FromSeconds(10)
                };
                var timeoutStream = new DownloadTimeoutStream(
                    expectedDownload,
                    slowStream,
                    timeout);

                // Act & Assert
                var exception = await Assert.ThrowsAsync <IOException>(() =>
                                                                       readAsync(timeoutStream));

                Assert.Equal(
                    $"The download of '{expectedDownload}' timed out because " +
                    $"no data was received for {timeout.TotalMilliseconds}ms.",
                    exception.Message);
                Assert.IsType <TimeoutException>(exception.InnerException);

                cancellationTokenSource.Cancel();
            }
        }
Exemple #5
0
        public async Task ReadExactlyAsync()
        {
            byte[] abySource = new byte[] { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };

            using (Stream streamSource = new MemoryStream(abySource))
                using (Stream stream = new SlowStream(streamSource))
                {
                    byte[] read = await stream.ReadExactlyAsync(5);

                    CollectionAssert.AreEqual(abySource.Take(5), read);

                    read = await stream.ReadExactlyAsync(6);

                    CollectionAssert.AreEqual(abySource.Skip(5), read);

                    Assert.ThrowsAsync <EndOfStreamException>(() => stream.ReadExactlyAsync(1));
                }

            using (Stream streamSource = new MemoryStream(abySource))
                using (Stream stream = new SlowStream(streamSource))
                {
                    byte[] read = await stream.ReadExactlyAsync(11);

                    CollectionAssert.AreEqual(abySource, read);
                }

            using (Stream streamSource = new MemoryStream(abySource))
                using (Stream stream = new SlowStream(streamSource))
                {
                    Assert.ThrowsAsync <EndOfStreamException>(() => stream.ReadExactlyAsync(12));
                }
        }
        public void TestPeekableStreamRead()
        {
            var inputStr = "← ↔ →";
            var buffer   = inputStr.ToUtf8();

            for (int i = 1; i <= buffer.Length; i++)
            {
                using (var mem = new MemoryStream(buffer))
                    using (var slow = new SlowStream(mem, i))
                        using (var peekable = new PeekableStream(slow))
                        {
                            using (var peek = peekable.GetPeekStream())
                            {
                                var buf = peek.Read(11);
                                Assert.AreEqual(inputStr, buf.FromUtf8());
                                Assert.AreEqual(0, peek.Read(buf, 0, 1));
                            }
                            var buf2 = peekable.Read(11);
                            Assert.AreEqual(inputStr, buf2.FromUtf8());
                            Assert.AreEqual(0, peekable.Read(buf2, 0, 1));
                            using (var peek = peekable.GetPeekStream())
                                Assert.AreEqual(0, peek.Read(buf2, 0, 1));
                        }
            }
        }
        public void ReadExactly()
        {
            var abySource = new byte[] { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };

            using (Stream streamSource = new MemoryStream(abySource))
                using (Stream stream = new SlowStream(streamSource))
                {
                    var read = stream.ReadExactly(5);
                    CollectionAssert.AreEqual(abySource.Take(5), read);

                    read = stream.ReadExactly(6);
                    CollectionAssert.AreEqual(abySource.Skip(5), read);

                    Assert.Throws <EndOfStreamException>(() => stream.ReadExactly(1));
                }

            using (Stream streamSource = new MemoryStream(abySource))
                using (Stream stream = new SlowStream(streamSource))
                {
                    var read = stream.ReadExactly(11);
                    CollectionAssert.AreEqual(abySource, read);
                }

            using (Stream streamSource = new MemoryStream(abySource))
                using (Stream stream = new SlowStream(streamSource))
                {
                    Assert.Throws <EndOfStreamException>(() => stream.ReadExactly(12));
                }
        }
Exemple #8
0
        public void TestControlCodedStream()
        {
            byte[] buffer;
            using (var memoryStream = new MemoryStream())
                using (var peekable = new PeekableStream(memoryStream))
                    using (var ccs = new ControlCodedStream(peekable))
                        using (var binary = new BinaryStream(ccs))
                        {
                            binary.WriteString("← ↔ →");
                            ccs.WriteControlCode(47);
                            binary.WriteChar((char)255);
                            ccs.WriteControlCode(48);
                            binary.WriteVarInt(0x1FF);
                            ccs.WriteControlCode(49);
                            binary.WriteFloat(float.NaN);
                            binary.WriteFloat(float.PositiveInfinity);
                            binary.WriteFloat(float.NegativeInfinity);
                            ccs.WriteControlCode(50);

                            Assert.Throws <ArgumentOutOfRangeException>(() => ccs.WriteControlCode(255));

                            binary.Close();
                            ccs.Close();
                            peekable.Close();
                            memoryStream.Close();
                            buffer = memoryStream.ToArray();
                        }

            for (int i = 1; i < buffer.Length; i++)
            {
                using (var memoryStream = new MemoryStream(buffer))
                    using (var slowStream = new SlowStream(memoryStream, i))
                        using (var peekable = new PeekableStream(slowStream))
                            using (var ccs = new ControlCodedStream(peekable))
                                using (var binary = new BinaryStream(ccs))
                                {
                                    Assert.AreEqual("← ↔ →", binary.ReadString());
                                    Assert.Throws <InvalidOperationException>(() => ccs.Read(new byte[1], 0, 1));
                                    Assert.AreEqual(47, ccs.ReadControlCode());
                                    Assert.AreEqual((char)255, binary.ReadChar());
                                    Assert.AreEqual(48, ccs.ReadControlCode());
                                    Assert.AreEqual(0x1FF, binary.ReadVarInt());
                                    Assert.AreEqual(49, ccs.ReadControlCode());
                                    Assert.IsNaN(binary.ReadFloat());
                                    Assert.AreEqual(-1, ccs.ReadControlCode());
                                    Assert.AreEqual(float.PositiveInfinity, binary.ReadFloat());
                                    Assert.AreEqual(float.NegativeInfinity, binary.ReadFloat());
                                    Assert.AreEqual(50, ccs.ReadControlCode());
                                    Assert.AreEqual(-1, ccs.ReadControlCode());
                                    Assert.AreEqual(0, ccs.Read(new byte[1], 0, 1));
                                }
            }
        }
Exemple #9
0
        public void Slow_stream_is_parsed_correctly()
        {
            var buffer = new MemoryStream();

            Yaml.StreamFrom("04-scalars-in-multi-docs.yaml").CopyTo(buffer);

            var slowStream = new SlowStream(buffer.ToArray());

            var scanner = new Scanner(new StreamReader(slowStream));

            scanner.MoveNext();

            // Should not fail
            scanner.MoveNext();
        }
Exemple #10
0
        public async Task VerifyFailureOnReadAsync(Func <Stream, Task <string> > readAsync)
        {
            // Arrange
            var expected     = new IOException();
            var memoryStream = GetStream("foobar");
            var slowStream   = new SlowStream(memoryStream)
            {
                OnRead = (buffer, offset, count) => { throw expected; }
            };
            var timeoutStream = new DownloadTimeoutStream(
                "download",
                slowStream,
                TimeSpan.FromSeconds(10));

            // Act & Assert
            var actual = await Assert.ThrowsAsync <IOException>(() =>
                                                                readAsync(timeoutStream));

            Assert.Same(expected, actual);
        }
Exemple #11
0
        private void PerformTestAtRate(int rateInKBs, string tempFileToUse)
        {
            timing.Restart();
            int bytesRead = 0;

            using (var file = new SlowStream(new FileStream(tempFileToUse, FileMode.Open, FileAccess.Read), rateInKBs))
            {
                var buffer = new byte[4096];
                do
                {
                    bytesRead += file.Read(buffer, 0, buffer.Length);
                } while (file.CanRead && file.Position != file.Length && bytesRead < file.Length);
            }
            var time    = timing.ElapsedMilliseconds;
            var kbBytes = bytesRead / 1024.0;
            var msTime  = time / 1000.0;

            System.Console.WriteLine("{0}kb in {1:0.00}s == {2:0.00} kb/s", kbBytes, msTime, kbBytes / msTime);
            Thread.Sleep(1000);
        }
        public async Task SourceThrows_Reported(bool isRequest)
        {
            var events = TestEventListener.Collect();

            var clock          = new ManualClock();
            var sourceWaitTime = TimeSpan.FromMilliseconds(12345);
            var source         = new SlowStream(new ThrowStream(), clock, sourceWaitTime);
            var destination    = new MemoryStream();

            using var cts      = new CancellationTokenSource();
            var(result, error) = await StreamCopier.CopyAsync(isRequest, source, destination, clock, cts, TimeSpan.FromSeconds(10));

            Assert.Equal(StreamCopyResult.InputError, result);
            Assert.IsAssignableFrom <IOException>(error);

            AssertContentTransferred(events, isRequest,
                                     contentLength: 0,
                                     iops: 1,
                                     firstReadTime: sourceWaitTime,
                                     readTime: sourceWaitTime,
                                     writeTime: TimeSpan.Zero);
        }
Exemple #13
0
        public void TestParsePost()
        {
            string inputStr = @"-----------------------------265001916915724
Content-Disposition: form-data; name=""y""

This is what should be found in ""y"" at the end of the test.
-----------------------------265001916915724
Content-Disposition: form-data; name=""What a wonderful day it is today; so wonderful in fact, that I'm inclined to go out and meet friends""


<CRLF>(this)<CRLF>

-----------------------------265001916915724
Content-Disposition: form-data; name=""documentfile""; filename=""temp.htm""
Content-Type: text/html

<html>
    <head>
    </head>
    <body>
        <form action='http://*****:*****@"C:\serverstests";
            int i = 1;

            while (Directory.Exists(directoryNotToBeCreated))
            {
                i++;
                directoryNotToBeCreated = @"C:\serverstests_" + i;
            }

            for (int cs = 1; cs < testCase.Length; cs++)
            {
                HttpRequest r = new HttpRequest
                {
                    Url     = new HttpUrl("example.com", "/"),
                    Headers = new HttpRequestHeaders
                    {
                        ContentLength            = inputStr.Length,
                        ContentMultipartBoundary = "---------------------------265001916915724",
                        ContentType = HttpPostContentType.MultipartFormData
                    },
                    Method = HttpMethod.Post
                };

                using (Stream f = new SlowStream(new MemoryStream(testCase), cs))
                {
                    r.ParsePostBody(f, directoryNotToBeCreated);
                    var gets  = r.Url.Query.ToList();
                    var posts = r.Post;
                    var files = r.FileUploads;

                    Assert.IsTrue(files.ContainsKey("documentfile"));
                    Assert.AreEqual("temp.htm", files["documentfile"].Filename);
                    Assert.AreEqual("text/html", files["documentfile"].ContentType);

                    using (var stream = files["documentfile"].GetStream())
                    {
                        string fileContent = Encoding.UTF8.GetString(stream.ReadAllBytes());
                        Assert.AreEqual(@"<html>
    <head>
    </head>
    <body>
        <form action='http://*****:*****@"This is what should be found in ""y"" at the end of the test.", posts["y"].Value);
                    Assert.IsTrue(posts.ContainsKey("What a wonderful day it is today; so wonderful in fact, that I'm inclined to go out and meet friends"));
                    Assert.AreEqual("\r\n<CRLF>(this)<CRLF>\r\n",
                                    posts["What a wonderful day it is today; so wonderful in fact, that I'm inclined to go out and meet friends"].Value);
                }
            }

            Assert.IsFalse(Directory.Exists(directoryNotToBeCreated));
        }
    public void Read_IntegrationTest ()
    {
      var stream = new SlowStream (TimeSpan.FromMilliseconds (200));
      stream.ReadTimeout = 50;
      stream.WriteTimeout = 5000;

      var decoratedStream = new StreamWithTimeoutDecorator (stream);

      Assert.That (
          () => decoratedStream.Read (new byte[10], 22, 33),
          Throws.InstanceOf<TimeoutException>());
    }
		public void ReadExactly()
		{
			byte[] abySource = new byte[] { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };

			using (Stream streamSource = new MemoryStream(abySource))
			using (Stream stream = new SlowStream(streamSource))
			{
				byte[] read = stream.ReadExactly(5);
				CollectionAssert.AreEqual(abySource.Take(5), read);

				read = stream.ReadExactly(6);
				CollectionAssert.AreEqual(abySource.Skip(5), read);

				Assert.Throws<EndOfStreamException>(() => stream.ReadExactly(1));
			}

			using (Stream streamSource = new MemoryStream(abySource))
			using (Stream stream = new SlowStream(streamSource))
			{
				byte[] read = stream.ReadExactly(11);
				CollectionAssert.AreEqual(abySource, read);
			}

			using (Stream streamSource = new MemoryStream(abySource))
			using (Stream stream = new SlowStream(streamSource))
			{
				Assert.Throws<EndOfStreamException>(() => stream.ReadExactly(12));
			}
		}
		public void ReadExactlyArray()
		{
			byte[] abySource = new byte[] { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };

			using (Stream streamSource = new MemoryStream(abySource))
			using (Stream stream = new SlowStream(streamSource))
			{
				byte[] buffer = new byte[20];
				stream.ReadExactly(buffer, 3, 8);
				CollectionAssert.AreEqual(new byte[3].Concat(abySource.Take(8)).Concat(new byte[9]), buffer);
			}

			using (Stream streamSource = new MemoryStream(abySource))
			using (Stream stream = new SlowStream(streamSource))
			{
				byte[] buffer = new byte[20];
				stream.ReadExactly(buffer, 5, 11);
				CollectionAssert.AreEqual(new byte[5].Concat(abySource).Concat(new byte[4]), buffer);
			}

			using (Stream streamSource = new MemoryStream(abySource))
			using (Stream stream = new SlowStream(streamSource))
			{
				byte[] buffer = new byte[20];
				Assert.Throws<EndOfStreamException>(() => stream.ReadExactly(buffer, 5, 12));
			}
		}