using System; using System.Collections.Generic; using System.Linq; using System.Text; using NUnit.Framework; using System.IO; using Developpez.Dotnet.IO; namespace Developpez.Dotnet.Tests.IO { [TestFixture] public class StreamExtensionsTests { [Test] public void Check_CopyToStream() { byte[] data = new byte[10000]; Random rnd = new Random(); rnd.NextBytes(data); using(MemoryStream input = new MemoryStream(data)) using (MemoryStream output = new MemoryStream()) { input.CopyToStream(output); byte[] copy = output.ToArray(); Assert.That(copy.SequenceEqual(data)); } } [Test] public void Check_CopyToFile() { string path = Path.GetTempFileName(); byte[] data = new byte[10000]; Random rnd = new Random(); rnd.NextBytes(data); using (MemoryStream input = new MemoryStream(data)) { input.CopyToFile(path); byte[] copy = File.ReadAllBytes(path); Assert.That(copy.SequenceEqual(data)); } } [Test] public void Test_AsNonClosing() { string expected = "Hello world !"; using (MemoryStream ms = new MemoryStream()) { using (StreamWriter wr = new StreamWriter(ms.AsNonClosing())) { wr.WriteLine(expected); } try { // Planterait sans le PreventClose ms.Position = 0; using (StreamReader rd = new StreamReader(ms.AsNonClosing())) { string actual = rd.ReadLine(); Assert.AreEqual(expected, actual); } // Planterait sans le PreventClose ms.Position = 0; } catch(ObjectDisposedException) { Assert.Fail("Le stream a été disposé prématurément"); } } } [Test] public void Test_AsByteEnumerable() { byte[] data = new byte[10000]; Random rnd = new Random(); rnd.NextBytes(data); using (MemoryStream input = new MemoryStream(data)) { int i = 0; foreach (var b in input.AsByteEnumerable()) { Assert.AreEqual(data[i], b); i++; } } } [Test] public void Test_AsBlockEnumerable() { byte[] data = new byte[10000]; Random rnd = new Random(); rnd.NextBytes(data); using (MemoryStream input = new MemoryStream(data)) { int blockSize = 512; int p = 0; foreach (var block in input.AsBlockEnumerable(blockSize)) { Assert.IsTrue(block.SequenceEqual(data.Skip(p).Take(blockSize))); p += blockSize; } } } } }