diff options
author | Matt Cohn <macohn@microsoft.com> | 2015-07-08 04:31:10 +0300 |
---|---|---|
committer | stephentoub <stoub@microsoft.com> | 2015-08-11 01:29:24 +0300 |
commit | 381785c196c573fe4ee7b36eaf4c53f4f5526ca0 (patch) | |
tree | 192dca265c9cde48137c8ca1fa098aa7fc3137d1 | |
parent | b0d0470b9a6387a08bf05d22c6d1e713865ce0b6 (diff) |
Port additional System.IO tests from ToF
Port additional System.IO tests from ToF for
System.IO.BinaryWriter
System.IO.MemoryStream
System.IO.Stream
System.IO.StreamReader
System.IO.StreamWriter
System.IO.StringReader
System.IO.StringWriter
22 files changed, 3479 insertions, 3 deletions
diff --git a/src/System.IO/tests/BinaryWriter/BinaryWriterTests.cs b/src/System.IO/tests/BinaryWriter/BinaryWriterTests.cs new file mode 100644 index 0000000000..2bc27b55dc --- /dev/null +++ b/src/System.IO/tests/BinaryWriter/BinaryWriterTests.cs @@ -0,0 +1,352 @@ +using Xunit; +using System; +using System.IO; +using System.Text; + +namespace Tests +{ + public class BinaryWriterTests + { + + [Fact] + public static void BinaryWriter_CtorAndWriteTests1() + { + // [] Smoke test to ensure that we can write with the constructed writer + using (MemoryStream mstr = new MemoryStream()) + using (BinaryWriter dw2 = new BinaryWriter(mstr)) + using (BinaryReader dr2 = new BinaryReader(mstr)) + { + dw2.Write(true); + dw2.Flush(); + mstr.Position = 0; + + Assert.True(dr2.ReadBoolean()); + } + } + + [Fact] + public static void BinaryWriter_CtorAndWriteTests1_Negative() + { + // [] Should throw ArgumentNullException for null argument + Assert.Throws<ArgumentNullException>(() => { BinaryWriter writer = new BinaryWriter(null); }); + + // [] Can't construct a BinaryWriter on a readonly stream + using (MemoryStream memStream = new MemoryStream(new byte[10], false)) + { + Assert.Throws<ArgumentException>(() => { BinaryWriter writer = new BinaryWriter(memStream); }); + } + + // [] Can't construct a BinaryWriter with a closed stream + { + MemoryStream memStream = new MemoryStream(); + memStream.Dispose(); + Assert.Throws<ArgumentException>(() => { BinaryWriter dw2 = new BinaryWriter(memStream); }); + } + } + + [Fact] + public static void BinaryWriter_EncodingCtorAndWriteTests_UTF8() + { + BinaryWriter_EncodingCtorAndWriteTests(Encoding.UTF8, "This is UTF8\u00FF"); + } + + [Fact] + public static void BinaryWriter_EncodingCtorAndWriteTests_BigEndianUnicode() + { + BinaryWriter_EncodingCtorAndWriteTests(Encoding.BigEndianUnicode, "This is BigEndianUnicode\u00FF"); + } + + [Fact] + public static void BinaryWriter_EncodingCtorAndWriteTests_Unicode() + { + BinaryWriter_EncodingCtorAndWriteTests(Encoding.Unicode, "This is Unicode\u00FF"); + } + + private static void BinaryWriter_EncodingCtorAndWriteTests(Encoding encoding, string testString) + { + using (MemoryStream memStream = new MemoryStream()) + using (BinaryWriter writer = new BinaryWriter(memStream, encoding)) + using (BinaryReader reader = new BinaryReader(memStream, encoding)) + { + writer.Write(testString); + writer.Flush(); + memStream.Position = 0; + + Assert.Equal(testString, reader.ReadString()); + } + } + + [Fact] + public static void BinaryWriter_EncodingCtorAndWriteTests_Negative() + { + // [] Check for ArgumentNullException on null stream + Assert.Throws<ArgumentNullException>( + () => { new BinaryReader((Stream)null, Encoding.UTF8); }); + + // [] Check for ArgumentNullException on null encoding + Assert.Throws<ArgumentNullException>( + () => { new BinaryReader(new MemoryStream(), null); }); + } + + [Fact] + public static void BinaryWriter_SeekTests() + { + int[] iArrLargeValues = new Int32[] { 10000, 100000, Int32.MaxValue / 200, Int32.MaxValue / 1000, Int16.MaxValue, Int32.MaxValue, Int32.MaxValue - 1, Int32.MaxValue / 2, Int32.MaxValue / 10, Int32.MaxValue / 100 }; + + BinaryWriter dw2 = null; + MemoryStream mstr = null; + Byte[] bArr = null; + StringBuilder sb = new StringBuilder(); + Int64 lReturn = 0; + + mstr = new MemoryStream(); + dw2 = new BinaryWriter(mstr); + dw2.Write("Hello, this is my string".ToCharArray()); + for (int iLoop = 0; iLoop < iArrLargeValues.Length; iLoop++) + { + lReturn = dw2.Seek(iArrLargeValues[iLoop], SeekOrigin.Begin); + + Assert.Equal(lReturn, iArrLargeValues[iLoop]); + } + dw2.Dispose(); + mstr.Dispose(); + + // [] Seek from start of stream + mstr = new MemoryStream(); + dw2 = new BinaryWriter(mstr); + dw2.Write("0123456789".ToCharArray()); + lReturn = dw2.Seek(0, SeekOrigin.Begin); + + Assert.Equal(lReturn, 0); + + dw2.Write("lki".ToCharArray()); + dw2.Flush(); + bArr = mstr.ToArray(); + sb = new StringBuilder(); + for (int i = 0; i < bArr.Length; i++) + sb.Append((Char)bArr[i]); + + Assert.Equal(sb.ToString(), "lki3456789"); + + dw2.Dispose(); + mstr.Dispose(); + + // [] Seek into stream from start + mstr = new MemoryStream(); + dw2 = new BinaryWriter(mstr); + dw2.Write("0123456789".ToCharArray()); + lReturn = dw2.Seek(3, SeekOrigin.Begin); + + Assert.Equal(lReturn, 3); + + dw2.Write("lk".ToCharArray()); + dw2.Flush(); + bArr = mstr.ToArray(); + sb = new StringBuilder(); + for (int i = 0; i < bArr.Length; i++) + sb.Append((Char)bArr[i]); + + Assert.Equal(sb.ToString(), "012lk56789"); + + dw2.Dispose(); + mstr.Dispose(); + + // [] Seek from end of stream + mstr = new MemoryStream(); + dw2 = new BinaryWriter(mstr); + dw2.Write("0123456789".ToCharArray()); + lReturn = dw2.Seek(-3, SeekOrigin.End); + + Assert.Equal(lReturn, 7); + + dw2.Write("ll".ToCharArray()); + dw2.Flush(); + bArr = mstr.ToArray(); + sb = new StringBuilder(); + for (int i = 0; i < bArr.Length; i++) + sb.Append((Char)bArr[i]); + + Assert.Equal(sb.ToString(), "0123456ll9"); + + dw2.Dispose(); + mstr.Dispose(); + + // [] Seeking from current position + mstr = new MemoryStream(); + dw2 = new BinaryWriter(mstr); + dw2.Write("0123456789".ToCharArray()); + mstr.Position = 2; + lReturn = dw2.Seek(2, SeekOrigin.Current); + + Assert.Equal(lReturn, 4); + + dw2.Write("ll".ToCharArray()); + dw2.Flush(); + bArr = mstr.ToArray(); + sb = new StringBuilder(); + for (int i = 0; i < bArr.Length; i++) + sb.Append((Char)bArr[i]); + + Assert.Equal(sb.ToString(), "0123ll6789"); + + dw2.Dispose(); + mstr.Dispose(); + + // [] Seeking past the end from middle + mstr = new MemoryStream(); + dw2 = new BinaryWriter(mstr); + dw2.Write("0123456789".ToCharArray()); + lReturn = dw2.Seek(4, SeekOrigin.End); //This wont throw any exception now. + + Assert.Equal(mstr.Position, 14); + + + dw2.Dispose(); + mstr.Dispose(); + + // [] Seek past the end from beginning + mstr = new MemoryStream(); + dw2 = new BinaryWriter(mstr); + dw2.Write("0123456789".ToCharArray()); + lReturn = dw2.Seek(11, SeekOrigin.Begin); //This wont throw any exception now. + + Assert.Equal(mstr.Position, 11); + + dw2.Dispose(); + mstr.Dispose(); + + // [] Seek to the end + mstr = new MemoryStream(); + dw2 = new BinaryWriter(mstr); + dw2.Write("0123456789".ToCharArray()); + lReturn = dw2.Seek(10, SeekOrigin.Begin); + + Assert.Equal(lReturn, 10); + + dw2.Write("ll".ToCharArray()); + bArr = mstr.ToArray(); + sb = new StringBuilder(); + for (int i = 0; i < bArr.Length; i++) + sb.Append((Char)bArr[i]); + + Assert.Equal(sb.ToString(), "0123456789ll"); + + dw2.Dispose(); + mstr.Dispose(); + } + + [Fact] + public static void BinaryWriter_SeekTests_NegativeOffset() + { + int[] invalidValues = new Int32[] { -1, -2, -100, -1000, -10000, -100000, -1000000, -10000000, -100000000, -1000000000, Int32.MinValue, Int16.MinValue }; + + // [] ArgumentOutOfRangeException if offset is negative + using (MemoryStream memStream = new MemoryStream()) + using (BinaryWriter writer = new BinaryWriter(memStream)) + { + writer.Write("Hello, this is my string".ToCharArray()); + + foreach (int invalidValue in invalidValues) + { + Assert.Throws<IOException>(() => + { + writer.Seek(invalidValue, SeekOrigin.Begin); + }); + } + } + } + + [Fact] + public static void BinaryWriter_SeekTests_InvalidSeekOrigin() + { + // [] ArgumentException for invalid seekOrigin + using (MemoryStream memStream = new MemoryStream()) + using (BinaryWriter writer = new BinaryWriter(memStream)) + { + writer.Write("012345789".ToCharArray()); + + Assert.Throws<ArgumentException>(() => + { + writer.Seek(3, ~SeekOrigin.Begin); + }); + } + } + + [Fact] + public static void BinaryWriter_BaseStreamTests() + { + // [] Get the base stream for MemoryStream + using (MemoryStream ms2 = new MemoryStream()) + using (BinaryWriter sr2 = new BinaryWriter(ms2)) + { + Assert.Equal(ms2, sr2.BaseStream); + } + } + + [Fact] + public static void BinaryWriter_FlushTests() + { + // [] Check that flush updates the underlying stream + using (MemoryStream memstr2 = new MemoryStream()) + using (BinaryWriter bw2 = new BinaryWriter(memstr2)) + { + bw2.Write("HelloWorld"); + //TODO:: Ckeck with dev why it's 11 bytes. + Assert.Equal(11, memstr2.Length); + bw2.Flush(); + Assert.Equal(11, memstr2.Length); + } + + // [] Flushing closed writer should not throw an exception. + using (MemoryStream memstr2 = new MemoryStream()) + { + BinaryWriter bw2 = new BinaryWriter(memstr2); + bw2.Dispose(); + bw2.Flush(); + } + } + + [Fact] + public static void BinaryWriter_DisposeTests() + { + // Disposing multiple times should not throw an exception + using (MemoryStream memStream = new MemoryStream()) + using (BinaryWriter binaryWriter = new BinaryWriter(memStream)) + { + binaryWriter.Dispose(); + binaryWriter.Dispose(); + binaryWriter.Dispose(); + } + } + + [Fact] + public static void BinaryWriter_DisposeTests_Negative() + { + using (MemoryStream memStream = new MemoryStream()) + { + BinaryWriter binaryWriter = new BinaryWriter(memStream); + binaryWriter.Dispose(); + + Assert.Throws<ObjectDisposedException>(() => binaryWriter.Seek(1, SeekOrigin.Begin)); + Assert.Throws<ObjectDisposedException>(() => binaryWriter.Write(new Byte[2], 0, 2)); + Assert.Throws<ObjectDisposedException>(() => binaryWriter.Write(new Char[2], 0, 2)); + Assert.Throws<ObjectDisposedException>(() => binaryWriter.Write(true)); + Assert.Throws<ObjectDisposedException>(() => binaryWriter.Write((Byte)4)); + Assert.Throws<ObjectDisposedException>(() => binaryWriter.Write(new Byte[] { 1, 2 })); + Assert.Throws<ObjectDisposedException>(() => binaryWriter.Write('a')); + Assert.Throws<ObjectDisposedException>(() => binaryWriter.Write(new Char[] { 'a', 'b' })); + Assert.Throws<ObjectDisposedException>(() => binaryWriter.Write(5.3)); + Assert.Throws<ObjectDisposedException>(() => binaryWriter.Write((Int16)3)); + Assert.Throws<ObjectDisposedException>(() => binaryWriter.Write(33)); + Assert.Throws<ObjectDisposedException>(() => binaryWriter.Write((Int64)42)); + Assert.Throws<ObjectDisposedException>(() => binaryWriter.Write((SByte)4)); + Assert.Throws<ObjectDisposedException>(() => binaryWriter.Write("Hello There")); + Assert.Throws<ObjectDisposedException>(() => binaryWriter.Write((Single)4.3)); + Assert.Throws<ObjectDisposedException>(() => binaryWriter.Write((UInt16)3)); + Assert.Throws<ObjectDisposedException>(() => binaryWriter.Write((UInt32)4)); + Assert.Throws<ObjectDisposedException>(() => binaryWriter.Write((UInt64)5)); + Assert.Throws<ObjectDisposedException>(() => binaryWriter.Write("Bah")); + } + } + } +} diff --git a/src/System.IO/tests/BinaryWriter/BinaryWriter_WriteByteCharTests.cs b/src/System.IO/tests/BinaryWriter/BinaryWriter_WriteByteCharTests.cs new file mode 100644 index 0000000000..4e464040e7 --- /dev/null +++ b/src/System.IO/tests/BinaryWriter/BinaryWriter_WriteByteCharTests.cs @@ -0,0 +1,573 @@ +using Xunit; +using System; +using System.IO; +using System.Text; + +namespace BinaryWriterTests +{ + public class BinaryWriter_WriteByteCharTests + { + + /// <summary> + /// Cases Tested: + /// 1) Tests that BinaryWriter properly writes chars into a stream. + /// 2) Tests that if someone writes surrogate characters, an argument exception is thrown + /// 3) Casting an int to char and writing it, works. + /// </summary> + [Fact] + public static void BinaryWriter_WriteCharTest() + { + MemoryStream mstr = new MemoryStream(); + BinaryWriter dw2 = new BinaryWriter(mstr); + BinaryReader dr2 = new BinaryReader(mstr); + + Char[] chArr = new Char[0]; + int ii = 0; + + // [] Write a series of characters to a Memorystream and read them back + chArr = new Char[] { 'A', 'c', '\0', '\u2701', '$', '.', '1', 'l', '\u00FF', '\n', '\t', '\v' }; + for (ii = 0; ii < chArr.Length; ii++) + dw2.Write(chArr[ii]); + + dw2.Flush(); + mstr.Position = 0; + try + { + for (ii = 0; ; ii++) + { + Assert.Equal(dr2.ReadChar(), chArr[ii]); + } + } + catch (EndOfStreamException) + { + } + + Assert.Equal(ii, chArr.Length); + + dw2.Dispose(); + dr2.Dispose(); + mstr.Dispose(); + + //VSWhidbey #273805 + //If someone writes out characters using BinaryWriter's Write(char[]) method, they must use something like BinaryReader's ReadChars(int) method to read it back in. + //They cannot use BinaryReader's ReadChar(). Similarly, data written using Write(char) can't be read back using ReadChars(int). + + //A high-surrogate is a Unicode code point in the range U+D800 through U+DBFF and a low-surrogate is a Unicode code point in the range U+DC00 through U+DFFF + Char ch; + MemoryStream mem = new MemoryStream(); + BinaryWriter writer = new BinaryWriter(mem, Encoding.Unicode); + + //between 1 <= x < 255 + int[] randomNumbers = new int[] { 1, 254, 210, 200, 105, 135, 98, 54 }; + for (int i = 0; i < randomNumbers.Length; i++) + { + ch = (Char)randomNumbers[i]; + writer.Write(ch); + } + + mem.Position = 0; + writer.Dispose(); + mem.Dispose(); + } + + [Fact] + public static void BinaryWriter_WriteCharTest_Negative() + { + //VSWhidbey #273805 + //If someone writes out characters using BinaryWriter's Write(char[]) method, they must use something like BinaryReader's ReadChars(int) method to read it back in. + //They cannot use BinaryReader's ReadChar(). Similarly, data written using Write(char) can't be read back using ReadChars(int). + + //A high-surrogate is a Unicode code point in the range U+D800 through U+DBFF and a low-surrogate is a Unicode code point in the range U+DC00 through U+DFFF + Char ch; + MemoryStream mem = new MemoryStream(); + BinaryWriter writer = new BinaryWriter(mem, Encoding.Unicode); + // between 55296 <= x < 56319 + int[] randomNumbers = new int[] { 55296, 56318, 55305, 56019, 55888, 55900, 56251 }; + for (int i = 0; i < randomNumbers.Length; i++) + { + ch = (Char)randomNumbers[i]; + Assert.Throws<ArgumentException>(delegate { writer.Write(ch); }); + } + // between 56320 <= x < 57343 + randomNumbers = new int[] { 56320, 57342, 56431, 57001, 56453, 57245, 57111 }; + for (int i = 0; i < randomNumbers.Length; i++) + { + ch = (Char)randomNumbers[i]; + Assert.Throws<ArgumentException>(delegate { writer.Write(ch); }); + } + + writer.Dispose(); + mem.Dispose(); + } + + /// <summary> + /// Cases Tested: + /// Writing bytes casted to chars and using a different encoding; iso-2022-jp. + /// </summary> + [Fact] + public static void BinaryWriter_WriteCharTest2() + { + //VSWhidbey #275448 - BinaryReader/BinaryWriter don't do well when mixing char or char[] data and binary data. + //The bug was Wont Fix for compatibility reasons + Encoding.RegisterProvider(CodePagesEncodingProvider.Instance); + + Stream stream = new MemoryStream(); + // string name = iso-2022-jp, codepage = 50220 (original test used a code page number). + // taken from http://msdn.microsoft.com/en-us/library/windows/desktop/dd317756(v=vs.85).aspx + string codepageName = "iso-2022-jp"; + BinaryWriter writer = new BinaryWriter(stream, Encoding.GetEncoding(codepageName)); + + byte[] bytes = { 0x01, 0x02, 0x03, 0x04, 0x05 }; + + writer.Write((char)0x30ca); + writer.Write(bytes); + writer.Flush(); + writer.Write('\0'); + + stream.Seek(0, SeekOrigin.Begin); + BinaryReader reader = new BinaryReader(stream, Encoding.GetEncoding(codepageName)); + char japanese = reader.ReadChar(); + Assert.True((int)japanese == 0x30ca); + byte[] readBytes = reader.ReadBytes(5); + for (int i = 0; i < 5; i++) + { + //We pretty much dont expect this to work + Assert.NotEqual(readBytes[i], bytes[i]); + } + + stream.Dispose(); + writer.Dispose(); + reader.Dispose(); + } + + /// <summary> + /// Testing that bytes can be written to a stream with BinaryWriter. + /// </summary> + [Fact] + public static void BinaryWriter_WriteByteTest() + { + int ii = 0; + Byte[] bytArr = new Byte[] { Byte.MinValue, Byte.MaxValue, 100, 1, 10, Byte.MaxValue / 2, Byte.MaxValue - 100 }; + + // [] read/Write with Memorystream + MemoryStream mstr = new MemoryStream(); + BinaryWriter dw2 = new BinaryWriter(mstr); + + for (ii = 0; ii < bytArr.Length; ii++) + dw2.Write(bytArr[ii]); + + dw2.Flush(); + mstr.Position = 0; + BinaryReader dr2 = new BinaryReader(mstr); + + for (ii = 0; ii < bytArr.Length; ii++) + { + Assert.Equal(dr2.ReadByte(), bytArr[ii]); + } + + // [] Check End Of Stream + Assert.Throws<EndOfStreamException>(() => dr2.ReadByte()); + + dr2.Dispose(); + dw2.Dispose(); + mstr.Dispose(); + } + + /// <summary> + /// Testing that SBytes can be written to a stream with BinaryWriter. + /// </summary> + [Fact] + public static void BinaryWriter_WriteSByteTest() + { + int ii = 0; + SByte[] sbArr = new SByte[] { + SByte.MinValue, SByte.MaxValue, -100, 100, 0, SByte.MinValue / 2, SByte.MaxValue / 2, + 10, 20, 30, -10, -20, -30, SByte.MaxValue - 100 }; + + // [] read/Write with Memorystream + MemoryStream mstr = new MemoryStream(); + BinaryWriter dw2 = new BinaryWriter(mstr); + + for (ii = 0; ii < sbArr.Length; ii++) + dw2.Write(sbArr[ii]); + + dw2.Flush(); + mstr.Position = 0; + BinaryReader dr2 = new BinaryReader(mstr); + + for (ii = 0; ii < sbArr.Length; ii++) + { + Assert.Equal(dr2.ReadSByte(), sbArr[ii]); + } + + dr2.Dispose(); + dw2.Dispose(); + mstr.Dispose(); + } + + /// <summary> + /// Testing that an ArgumentException is thrown when Sbytes are written to a stream + /// and read past the end of that stream. + /// </summary> + [Fact] + public static void BinaryWriter_WriteSByteTest_NegativeCase() + { + int ii = 0; + SByte[] sbArr = new SByte[] { + SByte.MinValue, SByte.MaxValue, -100, 100, 0, SByte.MinValue / 2, SByte.MaxValue / 2, + 10, 20, 30, -10, -20, -30, SByte.MaxValue - 100 }; + + MemoryStream mstr = new MemoryStream(); + BinaryWriter dw2 = new BinaryWriter(mstr); + + for (ii = 0; ii < sbArr.Length; ii++) + dw2.Write(sbArr[ii]); + + dw2.Flush(); + + BinaryReader dr2 = new BinaryReader(mstr); + // [] Check End Of Stream + Assert.Throws<EndOfStreamException>(() => dr2.ReadSByte()); + + dr2.Dispose(); + dw2.Dispose(); + mstr.Dispose(); + } + + /// <summary> + /// Testing that a byte[] can be written to a stream with BinaryWriter. + /// </summary> + [Fact] + public static void BinaryWriter_WriteBArrayTest() + { + int ii = 0; + Byte[] bytArr = new Byte[] { Byte.MinValue, Byte.MaxValue, 1, 5, 10, 100, 200 }; + + // [] read/Write with Memorystream + MemoryStream mstr = new MemoryStream(); + BinaryWriter dw2 = new BinaryWriter(mstr); + + dw2.Write(bytArr); + dw2.Flush(); + mstr.Position = 0; + + BinaryReader dr2 = new BinaryReader(mstr); + + for (ii = 0; ii < bytArr.Length; ii++) + { + Assert.Equal(dr2.ReadByte(), bytArr[ii]); + } + + // [] Check End Of Stream + Assert.Throws<EndOfStreamException>(() => dr2.ReadByte()); + + mstr.Dispose(); + dw2.Dispose(); + dr2.Dispose(); + } + + [Fact] + public static void BinaryWriter_WriteBArrayTest_Negative() + { + int[] iArrInvalidValues = new Int32[] { -1, -2, -100, -1000, -10000, -100000, -1000000, -10000000, -100000000, -1000000000, Int32.MinValue, Int16.MinValue }; + int[] iArrLargeValues = new Int32[] { Int32.MaxValue, Int32.MaxValue - 1, Int32.MaxValue / 2, Int32.MaxValue / 10, Int32.MaxValue / 100 }; + Byte[] bArr = new Byte[0]; + // [] ArgumentNullException for null argument + MemoryStream mstr = new MemoryStream(); + BinaryWriter dw2 = new BinaryWriter(mstr); + + Assert.Throws<ArgumentNullException>(() => dw2.Write((Byte[])null)); + mstr.Dispose(); + dw2.Dispose(); + + // [] ArgumentNullException for null argument + mstr = new MemoryStream(); + dw2 = new BinaryWriter(mstr); + Assert.Throws<ArgumentNullException>(() => dw2.Write((Byte[])null, 0, 0)); + + dw2.Dispose(); + mstr.Dispose(); + + mstr = new MemoryStream(); + dw2 = new BinaryWriter(mstr); + for (int iLoop = 0; iLoop < iArrInvalidValues.Length; iLoop++) + { + // [] ArgumentOutOfRange for negative offset + Assert.Throws<ArgumentOutOfRangeException>(() => dw2.Write(bArr, iArrInvalidValues[iLoop], 0)); + // [] ArgumentOutOfRangeException for negative count + Assert.Throws<ArgumentOutOfRangeException>(() => dw2.Write(bArr, 0, iArrInvalidValues[iLoop])); + } + dw2.Dispose(); + mstr.Dispose(); + + mstr = new MemoryStream(); + dw2 = new BinaryWriter(mstr); + for (int iLoop = 0; iLoop < iArrLargeValues.Length; iLoop++) + { + // [] Offset out of range + Assert.Throws<ArgumentException>(() => dw2.Write(bArr, iArrLargeValues[iLoop], 0)); + // [] Invalid count value + Assert.Throws<ArgumentException>(() => dw2.Write(bArr, 0, iArrLargeValues[iLoop])); + } + dw2.Dispose(); + mstr.Dispose(); + } + + /// <summary> + /// Cases Tested: + /// 1) Testing that bytes can be written to a stream with BinaryWriter. + /// 2) Tests exceptional scenarios. + /// </summary> + [Fact] + public static void BinaryWriter_WriteBArrayTest2() + { + BinaryWriter dw2 = null; + BinaryReader dr2 = null; + MemoryStream mstr = null; + Byte[] bArr = new Byte[0]; + int ii = 0; + Byte[] bReadArr = new Byte[0]; + Int32 ReturnValue; + + bArr = new Byte[1000]; + bArr[0] = Byte.MinValue; + bArr[1] = Byte.MaxValue; + + for (ii = 2; ii < 1000; ii++) + bArr[ii] = (Byte)(ii % 255); + + // []read/ Write character values 0-1000 with Memorystream + mstr = new MemoryStream(); + dw2 = new BinaryWriter(mstr); + + dw2.Write(bArr, 0, bArr.Length); + dw2.Flush(); + mstr.Position = 0; + + dr2 = new BinaryReader(mstr); + bReadArr = new Byte[bArr.Length]; + ReturnValue = dr2.Read(bReadArr, 0, bArr.Length); + + Assert.Equal(ReturnValue, bArr.Length); + + for (ii = 0; ii < bArr.Length; ii++) + { + Assert.Equal(bReadArr[ii], bArr[ii]); + } + + dw2.Dispose(); + dr2.Dispose(); + mstr.Dispose(); + } + + /// <summary> + /// Cases Tested: + /// 1) Testing that char[] can be written to a stream with BinaryWriter. + /// 2) Tests exceptional scenarios. + /// </summary> + [Fact] + public static void BinaryWriter_WriteCharArrayTest() + { + int ii = 0; + Char[] chArr = new Char[1000]; + chArr[0] = Char.MinValue; + chArr[1] = Char.MaxValue; + chArr[2] = '1'; + chArr[3] = 'A'; + chArr[4] = '\0'; + chArr[5] = '#'; + chArr[6] = '\t'; + + for (ii = 7; ii < 1000; ii++) + chArr[ii] = (Char)ii; + + // [] read/Write with Memorystream + MemoryStream mstr = new MemoryStream(); + BinaryWriter dw2 = new BinaryWriter(mstr); + + dw2.Write(chArr); + dw2.Flush(); + mstr.Position = 0; + + BinaryReader dr2 = new BinaryReader(mstr); + + for (ii = 0; ii < chArr.Length; ii++) + { + Assert.Equal(dr2.ReadChar(), chArr[ii]); + } + + // [] Check End Of Stream + Assert.Throws<EndOfStreamException>(() => dr2.ReadChar()); + + dw2.Dispose(); + dr2.Dispose(); + mstr.Dispose(); + } + + [Fact] + public static void BinaryWriter_WriteCharArrayTest_Negative() + { + int[] iArrInvalidValues = new Int32[] { -1, -2, -100, -1000, -10000, -100000, -1000000, -10000000, -100000000, -1000000000, Int32.MinValue, Int16.MinValue }; + int[] iArrLargeValues = new Int32[] { Int32.MaxValue, Int32.MaxValue - 1, Int32.MaxValue / 2, Int32.MaxValue / 10, Int32.MaxValue / 100 }; + Char[] chArr = new Char[1000]; + + // [] ArgumentNullException for null argument + MemoryStream mstr = new MemoryStream(); + BinaryWriter dw2 = new BinaryWriter(mstr); + Assert.Throws<ArgumentNullException>(() => dw2.Write((Char[])null)); + dw2.Dispose(); + mstr.Dispose(); + + + // [] ArgumentNullException for null argument + mstr = new MemoryStream(); + dw2 = new BinaryWriter(mstr); + Assert.Throws<ArgumentNullException>(() => dw2.Write((Char[])null, 0, 0)); + + mstr.Dispose(); + dw2.Dispose(); + + mstr = new MemoryStream(); + dw2 = new BinaryWriter(mstr); + + for (int iLoop = 0; iLoop < iArrInvalidValues.Length; iLoop++) + { + // [] ArgumentOutOfRange for negative offset + Assert.Throws<ArgumentOutOfRangeException>(() => dw2.Write(chArr, iArrInvalidValues[iLoop], 0)); + // [] negative count. + Assert.Throws<ArgumentOutOfRangeException>(() => dw2.Write(chArr, 0, iArrInvalidValues[iLoop])); + } + mstr.Dispose(); + dw2.Dispose(); + + mstr = new MemoryStream(); + dw2 = new BinaryWriter(mstr); + for (int iLoop = 0; iLoop < iArrLargeValues.Length; iLoop++) + { + // [] Offset out of range + Assert.Throws<ArgumentOutOfRangeException>(() => dw2.Write(chArr, iArrLargeValues[iLoop], 0)); + // [] Invalid count value + Assert.Throws<ArgumentOutOfRangeException>(() => dw2.Write(chArr, 0, iArrLargeValues[iLoop])); + } + mstr.Dispose(); + dw2.Dispose(); + } + + /// <summary> + /// Cases Tested: + ///VSWhidbey #273805 + ///If someone writes out characters using BinaryWriter's Write(char[]) method, they must use something like BinaryReader's ReadChars(int) method to read it back in. + ///They cannot use BinaryReader's ReadChar(). Similarly, data written using Write(char) can't be read back using ReadChars(int). + /// + ///A high-surrogate is a Unicode code point in the range U+D800 through U+DBFF and a low-surrogate is a Unicode code point in the range U+DC00 through U+DFFF + /// + ///UPDATE: 9/21/2006: We dont throw on the second read but then throws continuously - note the loop count difference in the 2 loops + ///See VSWhdibey 598304 + ///From [KimHamil] + ///BinaryReader was reverting to its original location instead of advancing. This was changed to skip past the char in the surrogate range. + ///The affected method is InternalReadOneChar (IROC). Note that the work here is slightly complicated by the way surrogates are handled by + ///the decoding classes. When IROC calls decoder.GetChars(), if the bytes passed in are surrogates, UnicodeEncoding doesn't report it. + ///charsRead would end up being one value, and since BinaryReader doesn't have the logic telling it exactly how many bytes total to expect, + ///it calls GetChars in a second loop. In that loop, UnicodeEncoding matches up a surrogate pair. If it realizes it's too big for the encoding, + ///then it throws an ArgumentException (chars overflow). This meant that BinaryReader.IROC is advancing past two chars in the surrogate + ///range, which is why the position actually needs to be moved back (but not past the first surrogate char). + + ///Note that UnicodeEncoding doesn't always throw when it encounters two successive chars in the surrogate range. The exception + ///encountered here happens if it finds a valid pair but then determines it's too long. If the pair isn't valid (a low then a high), + ///then it returns 0xfffd, which is why BinaryReader.ReadChar needs to do an explicit check. (It always throws when it encounters a surrogate) + /// </summary> + [Fact] + public static void BinaryWriter_WriteCharArrayTest2() + { + + MemoryStream mem = new MemoryStream(); + BinaryWriter writer = new BinaryWriter(mem, Encoding.Unicode); + + // between 55296 <= x < 56319 + + // between 56320 <= x < 57343 + Char[] randomChars = new Char[] { + (Char)55296, (Char)57297, (Char)55513, (Char)56624, (Char)55334, (Char)56957, (Char)55857, + (Char)56355, (Char)56095, (Char)56887, (Char) 56126, (Char) 56735, (Char)55748, (Char)56405, + (Char)55787, (Char)56707, (Char) 56300, (Char)56417, (Char)55465, (Char)56944 + }; + + writer.Write(randomChars); + mem.Position = 0; + BinaryReader reader = new BinaryReader(mem, Encoding.Unicode); + + for (int i = 0; i < 50; i++) + { + try + { + reader.ReadChar(); + + Assert.Equal(i, 1); + } + catch (ArgumentException) + { + // I guess sometimes it throws and othertimes, it doesn't? + // Based on the comments above. + } + } + + Char[] chars = reader.ReadChars(randomChars.Length); + for (int i = 0; i < randomChars.Length; i++) + Assert.Equal(chars[i], randomChars[i]); + + reader.Dispose(); + writer.Dispose(); + } + + /// <summary> + /// Cases Tested: + /// 1) Tests that char[] can be written to a stream with BinaryWriter. + /// 2) Tests Exceptional cases. + /// </summary> + [Fact] + public static void BinaryWriter_WriteCharArrayTest3() + { + BinaryWriter dw2 = null; + BinaryReader dr2 = null; + MemoryStream mstr = null; + Char[] chArr = new Char[0]; + int ii = 0; + Char[] chReadArr = new Char[0]; + Int32 ReturnValue; + + chArr = new Char[1000]; + chArr[0] = Char.MinValue; + chArr[1] = Char.MaxValue; + chArr[2] = '1'; + chArr[3] = 'A'; + chArr[4] = '\0'; + chArr[5] = '#'; + chArr[6] = '\t'; + + for (ii = 7; ii < 1000; ii++) + chArr[ii] = (Char)ii; + + // []read/ Write character values 0-1000 with Memorystream + + mstr = new MemoryStream(); + dw2 = new BinaryWriter(mstr); + + dw2.Write(chArr, 0, chArr.Length); + dw2.Flush(); + mstr.Position = 0; + + dr2 = new BinaryReader(mstr); + chReadArr = new Char[chArr.Length]; + ReturnValue = dr2.Read(chReadArr, 0, chArr.Length); + Assert.Equal(ReturnValue, chArr.Length); + + for (ii = 0; ii < chArr.Length; ii++) + { + Assert.Equal(chReadArr[ii], chArr[ii]); + } + + mstr.Dispose(); + dw2.Dispose(); + } + } +} diff --git a/src/System.IO/tests/BinaryWriter/BinaryWriter_WriteTests.cs b/src/System.IO/tests/BinaryWriter/BinaryWriter_WriteTests.cs new file mode 100644 index 0000000000..448e77085e --- /dev/null +++ b/src/System.IO/tests/BinaryWriter/BinaryWriter_WriteTests.cs @@ -0,0 +1,163 @@ +using Xunit; +using System; +using System.IO; +using System.Text; + +namespace BinaryWriterTests +{ + public class BinaryWriter_WriteTests + { + + [Fact] + public static void BinaryWriter_WriteBoolTest() + { + // [] Write a series of booleans to a stream + using(MemoryStream mstr = new MemoryStream()) + using(BinaryWriter dw2 = new BinaryWriter(mstr)) + using(BinaryReader dr2 = new BinaryReader(mstr)) + { + dw2.Write(false); + dw2.Write(false); + dw2.Write(true); + dw2.Write(false); + dw2.Write(true); + dw2.Write(5); + dw2.Write(0); + + dw2.Flush(); + mstr.Position = 0; + + Assert.False(dr2.ReadBoolean()); //false + Assert.False(dr2.ReadBoolean()); //false + Assert.True(dr2.ReadBoolean()); //true + Assert.False(dr2.ReadBoolean()); //false + Assert.True(dr2.ReadBoolean()); //true + Assert.True(dr2.ReadBoolean()); //5 + Assert.False(dr2.ReadBoolean()); //0 + } + } + + [Fact] + public static void BinaryWriter_WriteSingleTest() + { + Single[] sglArr = new Single[] { + Single.MinValue, Single.MaxValue, Single.Epsilon, Single.PositiveInfinity, Single.NegativeInfinity, new Single(), + 0, (Single)(-1E20), (Single)(-3.5E-20), (Single)(1.4E-10), (Single)10000.2, (Single)2.3E30 + }; + + WriteTest<Single>(sglArr, (bw, s) => bw.Write(s), (br) => br.ReadSingle()); + } + + [Fact] + public static void BinaryWriter_WriteDecimalTest() + { + Decimal[] decArr = new Decimal[] { + Decimal.One, Decimal.Zero, Decimal.MinusOne, Decimal.MinValue, Decimal.MaxValue, + new Decimal(-1000.5), new Decimal(-10.0E-40), new Decimal(3.4E-40898), new Decimal(3.4E-28), + new Decimal(3.4E+28), new Decimal(0.45), new Decimal(5.55), new Decimal(3.4899E23) + }; + + WriteTest<Decimal>(decArr, (bw, s) => bw.Write(s), (br) => br.ReadDecimal()); + } + + [Fact] + public static void BinaryWriter_WriteDoubleTest() + { + Double[] dblArr = new Double[] { + Double.NegativeInfinity, Double.PositiveInfinity, Double.Epsilon, Double.MinValue, Double.MaxValue, + -3E59, -1000.5, -1E-40, 3.4E-37, 0.45, 5.55, 3.4899E233 + }; + + WriteTest<Double>(dblArr, (bw, s) => bw.Write(s), (br) => br.ReadDouble()); + } + + [Fact] + public static void BinaryWriter_WriteInt16Test() + { + Int16[] i16Arr = new Int16[] { Int16.MinValue, Int16.MaxValue, 0, -10000, 10000, -50, 50 }; + + WriteTest<Int16>(i16Arr, (bw, s) => bw.Write(s), (br) => br.ReadInt16()); + } + + [Fact] + public static void BinaryWriter_WriteInt32Test() + { + Int32[] i32arr = new Int32[] { Int32.MinValue, Int32.MaxValue, 0, -10000, 10000, -50, 50 }; + + WriteTest<Int32>(i32arr, (bw, s) => bw.Write(s), (br) => br.ReadInt32()); + } + + [Fact] + public static void BinaryWriter_WriteInt64Test() + { + Int64[] i64arr = new Int64[] { Int64.MinValue, Int64.MaxValue, 0, -10000, 10000, -50, 50 }; + + WriteTest<Int64>(i64arr, (bw, s) => bw.Write(s), (br) => br.ReadInt64()); + } + + [Fact] + public static void BinaryWriter_WriteUInt16Test() + { + UInt16[] ui16Arr = new UInt16[] { UInt16.MinValue, UInt16.MaxValue, 0, 100, 1000, 10000, UInt16.MaxValue - 100 }; + + WriteTest<UInt16>(ui16Arr, (bw, s) => bw.Write(s), (br) => br.ReadUInt16()); + } + + [Fact] + public static void BinaryWriter_WriteUInt32Test() + { + UInt32[] ui32Arr = new UInt32[] { UInt32.MinValue, UInt32.MaxValue, 0, 100, 1000, 10000, UInt32.MaxValue - 100 }; + + WriteTest<UInt32>(ui32Arr, (bw, s) => bw.Write(s), (br) => br.ReadUInt32()); + } + + [Fact] + public static void BinaryWriter_WriteUInt64Test() + { + UInt64[] ui64Arr = new UInt64[] { UInt64.MinValue, UInt64.MaxValue, 0, 100, 1000, 10000, UInt64.MaxValue - 100 }; + + WriteTest<UInt64>(ui64Arr, (bw, s) => bw.Write(s), (br) => br.ReadUInt64()); + } + + [Fact] + public static void BinaryWriter_WriteStringTest() + { + StringBuilder sb = new StringBuilder(); + String str1; + for (int ii = 0; ii < 5; ii++) + sb.Append("abc"); + str1 = sb.ToString(); + + String[] strArr = new String[] { + "ABC", "\t\t\n\n\n\0\r\r\v\v\t\0\rHello", "This is a normal string", "12345667789!@#$%^&&())_+_)@#", + "ABSDAFJPIRUETROPEWTGRUOGHJDOLJHLDHWEROTYIETYWsdifhsiudyoweurscnkjhdfusiyugjlskdjfoiwueriye", " ", + "\0\0\0\t\t\tHey\"\"", "\u0022\u0011", str1, String.Empty }; + + WriteTest<String>(strArr, (bw, s) => bw.Write(s), (br) => br.ReadString()); + } + + private static void WriteTest<T>(T[] testElements, Action<BinaryWriter, T> write, Func<BinaryReader, T> read) + { + using (MemoryStream memStream = new MemoryStream()) + using (BinaryWriter writer = new BinaryWriter(memStream)) + using (BinaryReader reader = new BinaryReader(memStream)) + { + for (int i = 0; i < testElements.Length; i++) + { + write(writer, testElements[i]); + } + + writer.Flush(); + memStream.Position = 0; + + for (int i = 0; i < testElements.Length; i++) + { + Assert.Equal(testElements[i], read(reader)); + } + + // We've reached the end of the stream. Check for expected EndOfStreamException + Assert.Throws<EndOfStreamException>(() => read(reader)); + } + } + } +} diff --git a/src/System.IO/tests/System/IO/InvalidDataExceptionTests.cs b/src/System.IO/tests/InvalidDataException/InvalidDataExceptionTests.cs index 693561f1ae..693561f1ae 100644 --- a/src/System.IO/tests/System/IO/InvalidDataExceptionTests.cs +++ b/src/System.IO/tests/InvalidDataException/InvalidDataExceptionTests.cs diff --git a/src/System.IO/tests/MemoryStream/Inputs.cs b/src/System.IO/tests/MemoryStream/Inputs.cs new file mode 100644 index 0000000000..413c927554 --- /dev/null +++ b/src/System.IO/tests/MemoryStream/Inputs.cs @@ -0,0 +1,45 @@ +using System; +using System.Collections.Generic; + +internal static class Inputs +{ + public static IEnumerable<ArraySegment<byte>> GetArraysVariedByOffsetAndLength() + { + yield return new ArraySegment<byte>(new byte[512], 0, 512); + yield return new ArraySegment<byte>(new byte[512], 1, 511); + yield return new ArraySegment<byte>(new byte[512], 2, 510); + yield return new ArraySegment<byte>(new byte[512], 256, 256); + yield return new ArraySegment<byte>(new byte[512], 512, 0); + yield return new ArraySegment<byte>(new byte[512], 511, 1); + yield return new ArraySegment<byte>(new byte[512], 510, 2); + } + + public static IEnumerable<byte[]> GetArraysVariedBySize() + { + yield return FillWithData(new byte[0]); + yield return FillWithData(new byte[1]); + yield return FillWithData(new byte[2]); + yield return FillWithData(new byte[254]); + yield return FillWithData(new byte[255]); + yield return FillWithData(new byte[256]); + yield return FillWithData(new byte[511]); + yield return FillWithData(new byte[512]); + yield return FillWithData(new byte[513]); + yield return FillWithData(new byte[1023]); + yield return FillWithData(new byte[1024]); + yield return FillWithData(new byte[1025]); + yield return FillWithData(new byte[2047]); + yield return FillWithData(new byte[2048]); + yield return FillWithData(new byte[2049]); + } + + private static byte[] FillWithData(byte[] buffer) + { + for (int i = 0; i < buffer.Length;i ++) + { + buffer[i] = (byte)i; + } + + return buffer; + } +} diff --git a/src/System.IO/tests/MemoryStream/MemoryStream_TryGetBufferTests.cs b/src/System.IO/tests/MemoryStream/MemoryStream_TryGetBufferTests.cs new file mode 100644 index 0000000000..2488ae0855 --- /dev/null +++ b/src/System.IO/tests/MemoryStream/MemoryStream_TryGetBufferTests.cs @@ -0,0 +1,428 @@ +using Xunit; +using System; +using System.IO; +using System.Collections.Generic; + +public class MemoryStream_TryGetBufferTests +{ + [Fact] + public static void TryGetBuffer_Constructor_AlwaysReturnsTrue() + { + var stream = new MemoryStream(); + + ArraySegment<byte> _; + bool result = stream.TryGetBuffer(out _); + + Assert.True(result); + } + + [Fact] + public static void TryGetBuffer_Constructor_Int32_AlwaysReturnsTrue() + { + var stream = new MemoryStream(512); + + ArraySegment<byte> _; + bool result = stream.TryGetBuffer(out _); + + Assert.True(result); + } + + [Fact] + public static void TryGetBuffer_Constructor_ByteArray_AlwaysReturnsFalse() + { + var stream = new MemoryStream(new byte[512]); + + ArraySegment<byte> _; + bool result = stream.TryGetBuffer(out _); + + Assert.False(result); + } + + [Fact] + public static void TryGetBuffer_Constructor_ByteArray_Bool_AlwaysReturnsFalse() + { + var stream = new MemoryStream(new byte[512], writable: true); + + ArraySegment<byte> _; + bool result = stream.TryGetBuffer(out _); + + Assert.False(result); + } + + [Fact] + public static void TryGetBuffer_Constructor_ByteArray_Int32_Int32_AlwaysReturnsFalse() + { + var stream = new MemoryStream(new byte[512], index: 0, count: 512); + + ArraySegment<byte> _; + bool result = stream.TryGetBuffer(out _); + + Assert.False(result); + } + + [Fact] + public static void TryGetBuffer_Constructor_ByteArray_Int32_Int32_Bool_AlwaysReturnsFalse() + { + var stream = new MemoryStream(new byte[512], index: 0, count: 512, writable: true); + + ArraySegment<byte> _; + bool result = stream.TryGetBuffer(out _); + + Assert.False(result); + } + + [Fact] + public static void TryGetBuffer_Constructor_ByteArray_Int32_Int32_Bool_Bool_FalseAsPubliclyVisible_ReturnsFalse() + { + var stream = new MemoryStream(new byte[512], index: 0, count: 512, writable: true, publiclyVisible: false); + + ArraySegment<byte> _; + bool result = stream.TryGetBuffer(out _); + + Assert.False(result); + } + + [Fact] + public static void TryGetBuffer_Constructor_ByteArray_Int32_Int32_Bool_Bool_TrueAsPubliclyVisible_ReturnsTrue() + { + var stream = new MemoryStream(new byte[512], index: 0, count: 512, writable: true, publiclyVisible: true); + + ArraySegment<byte> _; + bool result = stream.TryGetBuffer(out _); + + Assert.True(result); + } + + [Fact] + public static void TryGetBuffer_Constructor_ByteArray_AlwaysReturnsEmptyArraySegment() + { + var arrays = Inputs.GetArraysVariedBySize(); + + foreach (byte[] array in arrays) + { + var stream = new MemoryStream(array); + + ArraySegment<byte> result; + stream.TryGetBuffer(out result); + + // publiclyVisible = false; + Assert.True(default(ArraySegment<byte>).Equals(result)); + } + } + + [Fact] + public static void TryGetBuffer_Constructor_ByteArray_Bool_AlwaysReturnsEmptyArraySegment() + { + var arrays = Inputs.GetArraysVariedBySize(); + + foreach (byte[] array in arrays) + { + var stream = new MemoryStream(array, writable: true); + + ArraySegment<byte> result; + stream.TryGetBuffer(out result); + + // publiclyVisible = false; + Assert.True(default(ArraySegment<byte>).Equals(result)); + } + } + + [Fact] + public static void TryGetBuffer_Constructor_ByteArray_Int32_Int32_AlwaysReturnsEmptyArraySegment() + { + var arrays = Inputs.GetArraysVariedByOffsetAndLength(); + + foreach (var array in arrays) + { + var stream = new MemoryStream(array.Array, index: array.Offset, count: array.Count); + + ArraySegment<byte> result; + stream.TryGetBuffer(out result); + + // publiclyVisible = false; + Assert.True(default(ArraySegment<byte>).Equals(result)); + } + } + + [Fact] + public static void TryGetBuffer_Constructor_ByteArray_Int32_Int32_Bool_AlwaysReturnsEmptyArraySegment() + { + var arrays = Inputs.GetArraysVariedByOffsetAndLength(); + + foreach (var array in arrays) + { + var stream = new MemoryStream(array.Array, index: array.Offset, count: array.Count, writable: true); + + ArraySegment<byte> result; + stream.TryGetBuffer(out result); + + // publiclyVisible = false; + Assert.True(default(ArraySegment<byte>).Equals(result)); + } + } + + [Fact] + public static void TryGetBuffer_Constructor_ByteArray_Int32_Int32_Bool_Bool_FalseAsPubliclyVisible_ReturnsEmptyArraySegment() + { + var arrays = Inputs.GetArraysVariedByOffsetAndLength(); + + foreach (var array in arrays) + { + var stream = new MemoryStream(array.Array, index: array.Offset, count: array.Count, writable: true, publiclyVisible: false); + + ArraySegment<byte> result; + stream.TryGetBuffer(out result); + + // publiclyVisible = false; + Assert.True(default(ArraySegment<byte>).Equals(result)); + } + } + + [Fact] + public static void TryGetBuffer_Constructor_AlwaysReturnsOffsetSetToZero() + { + var stream = new MemoryStream(); + + ArraySegment<byte> result; + stream.TryGetBuffer(out result); + + Assert.Equal(0, result.Offset); + + } + + [Fact] + public static void TryGetBuffer_Constructor_Int32_AlwaysReturnsOffsetSetToZero() + { + var stream = new MemoryStream(512); + + ArraySegment<byte> result; + stream.TryGetBuffer(out result); + + Assert.Equal(0, result.Offset); + } + + [Fact] + public static void TryGetBuffer_Constructor_ByteArray_Int32_Int32_Bool_Bool_ValueAsIndexAndTrueAsPubliclyVisible_AlwaysReturnsOffsetSetToIndex() + { + var arrays = Inputs.GetArraysVariedByOffsetAndLength(); + + foreach (var array in arrays) + { + var stream = new MemoryStream(array.Array, index: array.Offset, count: array.Count, writable: true, publiclyVisible: true); + + ArraySegment<byte> result; + stream.TryGetBuffer(out result); + + Assert.Equal(array.Offset, result.Offset); + } + } + + [Fact] + public static void TryGetBuffer_Constructor_ByDefaultReturnsCountSetToZero() + { + var stream = new MemoryStream(); + + ArraySegment<byte> result; + stream.TryGetBuffer(out result); + + Assert.Equal(0, result.Count); + } + + [Fact] + public static void TryGetBuffer_Constructor_ReturnsCountSetToWrittenLength() + { + var arrays = Inputs.GetArraysVariedBySize(); + foreach (var array in arrays) + { + var stream = new MemoryStream(); + stream.Write(array, 0, array.Length); + + ArraySegment<byte> result; + stream.TryGetBuffer(out result); + + Assert.Equal(array.Length, result.Count); + } + } + + [Fact] + public static void TryGetBuffer_Constructor_Int32_ByDefaultReturnsCountSetToZero() + { + var stream = new MemoryStream(512); + + ArraySegment<byte> result; + stream.TryGetBuffer(out result); + + Assert.Equal(0, result.Offset); + } + + [Fact] + public static void TryGetBuffer_Constructor_Int32_ReturnsCountSetToWrittenLength() + { + var arrays = Inputs.GetArraysVariedBySize(); + foreach (var array in arrays) + { + var stream = new MemoryStream(512); + stream.Write(array, 0, array.Length); + + ArraySegment<byte> result; + stream.TryGetBuffer(out result); + + Assert.Equal(array.Length, result.Count); + } + } + + [Fact] + public static void TryGetBuffer_Constructor_ByteArray_Int32_Int32_Bool_Bool_ValueAsCountAndTrueAsPubliclyVisible_AlwaysReturnsCountSetToCount() + { + var arrays = Inputs.GetArraysVariedByOffsetAndLength(); + + foreach (var array in arrays) + { + var stream = new MemoryStream(array.Array, index: array.Offset, count: array.Count, writable: true, publiclyVisible: true); + + ArraySegment<byte> result; + stream.TryGetBuffer(out result); + + Assert.Equal(array.Count, result.Count); + } + } + + [Fact] + public static void TryGetBuffer_Constructor_ReturnsArray() + { + var stream = new MemoryStream(); + + ArraySegment<byte> result; + stream.TryGetBuffer(out result); + + Assert.NotNull(result.Array); + } + + [Fact] + public static void TryGetBuffer_Constructor_MultipleCallsReturnsSameArray() + { + var stream = new MemoryStream(); + + ArraySegment<byte> result1; + ArraySegment<byte> result2; + stream.TryGetBuffer(out result1); + stream.TryGetBuffer(out result2); + + Assert.Same(result1.Array, result2.Array); + } + + [Fact] + public static void TryGetBuffer_Constructor_Int32_MultipleCallsReturnSameArray() + { + var stream = new MemoryStream(512); + + ArraySegment<byte> result1; + ArraySegment<byte> result2; + stream.TryGetBuffer(out result1); + stream.TryGetBuffer(out result2); + + Assert.Same(result1.Array, result2.Array); + } + + [Fact] + public static void TryGetBuffer_Constructor_Int32_WhenWritingPastCapacity_ReturnsDifferentArrays() + { + var stream = new MemoryStream(512); + + ArraySegment<byte> result1; + stream.TryGetBuffer(out result1); + + // Force the stream to resize the underlying array + stream.Write(new byte[1024], 0, 1024); + + ArraySegment<byte> result2; + stream.TryGetBuffer(out result2); + + Assert.NotSame(result1.Array, result2.Array); + } + + [Fact] + public static void TryGetBuffer_Constructor_ByteArray_Int32_Int32_Bool_Bool_ValueAsBufferAndTrueAsPubliclyVisible_AlwaysReturnsArraySetToBuffer() + { + var arrays = Inputs.GetArraysVariedByOffsetAndLength(); + + foreach (var array in arrays) + { + var stream = new MemoryStream(array.Array, index: array.Offset, count: array.Count, writable: true, publiclyVisible: true); + + ArraySegment<byte> result; + stream.TryGetBuffer(out result); + + Assert.Same(array.Array, result.Array); + } + } + + [Fact] + public static void TryGetBuffer_WhenDisposed_ReturnsTrue() + { + var arrays = Inputs.GetArraysVariedByOffsetAndLength(); + + foreach (var array in arrays) + { + var stream = new MemoryStream(array.Array, index: array.Offset, count: array.Count, writable: true, publiclyVisible: true); + stream.Dispose(); + + ArraySegment<byte> _; + bool result = stream.TryGetBuffer(out _); + + Assert.True(result); + } + } + + [Fact] + public static void TryGetBuffer_WhenDisposed_ReturnsOffsetSetToIndex() + { + var arrays = Inputs.GetArraysVariedByOffsetAndLength(); + + foreach (var array in arrays) + { + var stream = new MemoryStream(array.Array, index: array.Offset, count: array.Count, writable: true, publiclyVisible: true); + stream.Dispose(); + + ArraySegment<byte> result; + stream.TryGetBuffer(out result); + + Assert.Equal(array.Offset, result.Offset); + } + } + + + [Fact] + public static void TryGetBuffer_WhenDisposed_ReturnsCountSetToCount() + { + var arrays = Inputs.GetArraysVariedByOffsetAndLength(); + + foreach (var array in arrays) + { + var stream = new MemoryStream(array.Array, index: array.Offset, count: array.Count, writable: true, publiclyVisible: true); + stream.Dispose(); + + ArraySegment<byte> result; + stream.TryGetBuffer(out result); + + Assert.Equal(array.Count, result.Count); + } + } + + [Fact] + public static void TryGetBuffer_WhenDisposed_ReturnsArraySetToBuffer() + { + var arrays = Inputs.GetArraysVariedByOffsetAndLength(); + + foreach (var array in arrays) + { + var stream = new MemoryStream(array.Array, index: array.Offset, count: array.Count, writable: true, publiclyVisible: true); + stream.Dispose(); + + ArraySegment<byte> result; + stream.TryGetBuffer(out result); + + Assert.Same(array.Array, result.Array); + } + } +}
\ No newline at end of file diff --git a/src/System.IO/tests/Stream/NullTests.cs b/src/System.IO/tests/Stream/NullTests.cs new file mode 100644 index 0000000000..57b4288216 --- /dev/null +++ b/src/System.IO/tests/Stream/NullTests.cs @@ -0,0 +1,104 @@ +using System; +using System.IO; +using System.Threading.Tasks; +using Xunit; + +namespace StreamTests +{ + public class NullCtorTests + { + [Fact] + public static void TestNullStream() + { + var t = TestNullStream(Stream.Null); + t.Wait(); + } + + [Fact] + public static void TestNullTextReader() + { + TestTextReader(TextReader.Null); + } + + [Fact] + public static void TestNullStreamReader() + { + TestTextReader(StreamReader.Null); + } + + [Fact] + public static void TestNullStringReader() + { + TestTextReader(StringReader.Null); + } + + [Fact] + public static void TestNullTextWriter() + { + TestTextWriter(TextWriter.Null); + + } + + [Fact] + public static void TestNullStreamWriter() + { + TestTextWriter(StreamWriter.Null); + } + + [Fact] + public static void TestNullStringWriter() + { + TestTextWriter(StringWriter.Null); + } + + static async Task TestNullStream(Stream s) + { + int n; + + s.Flush(); + + Assert.Equal(-1, s.ReadByte()); + + s.WriteByte(5); + n = s.Read(new byte[2], 0, 2); + Assert.Equal(0, n); + s.Write(new byte[2], 0, 2); + + Assert.Equal(0, await s.ReadAsync(new byte[2], 0, 2)); + + s.Flush(); + s.Dispose(); + } + + static void TestTextReader(TextReader input) + { + StreamReader sr = input as StreamReader; + + if (sr != null) + Assert.True(sr.EndOfStream, "EndOfStream property didn't return true"); + input.ReadLine(); + input.Dispose(); + + input.ReadLine(); + if (sr != null) + Assert.True(sr.EndOfStream, "EndOfStream property didn't return true"); + input.Read(); + input.Peek(); + input.Read(new char[2], 0, 2); + input.ReadToEnd(); + input.Dispose(); + } + + static void TestTextWriter(TextWriter output) + { + output.Flush(); + output.Dispose(); + + output.WriteLine(Decimal.MinValue); + output.WriteLine(Math.PI); + output.WriteLine(); + output.Flush(); + output.Dispose(); + } + } +} diff --git a/src/System.IO/tests/Stream/StreamAsyncTests.cs b/src/System.IO/tests/Stream/StreamAsyncTests.cs new file mode 100644 index 0000000000..434bca3307 --- /dev/null +++ b/src/System.IO/tests/Stream/StreamAsyncTests.cs @@ -0,0 +1,30 @@ +using System; +using System.IO; +using System.Threading.Tasks; +using Xunit; + +namespace StreamReaderTests +{ + public class AsyncStream + { + [Fact] + public static async Task CopyToTest() { + var ms = new MemoryStream(); + for (int i = 0; i < 1000; i++) + { + ms.WriteByte((byte)(i % 256)); + } + ms.Position = 0; + + var ms2 = new MemoryStream(); + await ms.CopyToAsync(ms2); + + var buffer = ms2.ToArray(); + for (int i = 0; i < 1000; i++) + { + Assert.Equal(i % 256, buffer[i]); + } + + } + } +} diff --git a/src/System.IO/tests/Stream/StreamMethods.cs b/src/System.IO/tests/Stream/StreamMethods.cs new file mode 100644 index 0000000000..412d647847 --- /dev/null +++ b/src/System.IO/tests/Stream/StreamMethods.cs @@ -0,0 +1,237 @@ +using System; +using System.IO; +using System.Threading.Tasks; +using Xunit; + +namespace StreamTests +{ + public class StreamMethods + { + [Fact] + public static void MemoryStreamSeekStress() + { + //MemoryStream + var ms1 = new MemoryStream(); + SeekTest(ms1, false); + } + [Fact] + public static void MemoryStreamSeekStressWithInitialBuffer() + { + //MemoryStream + var ms1 = new MemoryStream(new Byte[1024], false); + SeekTest(ms1, false); + } + + [Fact] + public static async Task MemoryStreamStress() + { + var ms1 = new MemoryStream(); + await StreamTest(ms1, false); + } + + static private void SeekTest(Stream stream, Boolean fSuppres) + { + long lngPos; + Byte btValue; + + stream.Position = 0; + + Assert.Equal(0, stream.Position); + + Int32 length = 1 << 10; //fancy way of writing 2 to the pow 10 + Byte[] btArr = new Byte[length]; + for (int i = 0; i < btArr.Length; i++) + btArr[i] = (byte)i; + + if (stream.CanWrite) + stream.Write(btArr, 0, btArr.Length); + else + stream.Position = btArr.Length; + + Assert.Equal(stream.Position, btArr.Length); + + lngPos = stream.Seek(0, SeekOrigin.Begin); + Assert.Equal(0, lngPos); + + Assert.Equal(0, stream.Position); + + for (int i = 0; i < btArr.Length; i++) + { + if (stream.CanWrite) + { + btValue = (Byte)stream.ReadByte(); + Assert.Equal(btArr[i], btValue); + } + else + { + stream.Seek(1, SeekOrigin.Current); + } + Assert.Equal(i + 1, stream.Position); + } + + Assert.Throws<IOException>( () => {lngPos = stream.Seek(-5, SeekOrigin.Begin); }); + + lngPos = stream.Seek(5, SeekOrigin.Begin); + Assert.Equal(5, lngPos); + Assert.Equal(5, stream.Position); + + lngPos = stream.Seek(5, SeekOrigin.End); + Assert.Equal(length + 5, lngPos); + Assert.Throws<IOException>( () => { lngPos = stream.Seek(-(btArr.Length + 1), SeekOrigin.End); }); + + lngPos = stream.Seek(-5, SeekOrigin.End); + Assert.Equal(btArr.Length - 5, lngPos); + Assert.Equal(btArr.Length - 5, stream.Position); + + lngPos = stream.Seek(0, SeekOrigin.End); + Assert.Equal(btArr.Length, stream.Position); + + for (int i = btArr.Length; i > 0; i--) + { + stream.Seek(-1, SeekOrigin.Current); + Assert.Equal(i - 1, stream.Position); + } + + Assert.Throws<IOException>( () => {lngPos = stream.Seek(-1, SeekOrigin.Current); }); + } + + private static async Task StreamTest(Stream stream, Boolean fSuppress) + { + + String strValue; + Int32 iValue; + + //[] We will first use the stream's 2 writing methods + Int32 iLength = 1 << 10; + stream.Seek(0, SeekOrigin.Begin); + + for (int i = 0; i < iLength; i++) + stream.WriteByte((Byte)i); + + Byte[] btArr = new Byte[iLength]; + for (int i = 0; i < iLength; i++) + btArr[i] = (Byte)i; + stream.Write(btArr, 0, iLength); + + //we will write many things here using a binary writer + BinaryWriter bw1 = new BinaryWriter(stream); + bw1.Write(false); + bw1.Write(true); + + for (int i = 0; i < 10; i++) + { + bw1.Write((Byte)i); + bw1.Write((SByte)i); + bw1.Write((Int16)i); + bw1.Write((Char)i); + bw1.Write((UInt16)i); + bw1.Write(i); + bw1.Write((UInt32)i); + bw1.Write((Int64)i); + bw1.Write((UInt64)i); + bw1.Write((Single)i); + bw1.Write((Double)i); + } + + //Some strings, chars and Bytes + Char[] chArr = new Char[iLength]; + for (int i = 0; i < iLength; i++) + chArr[i] = (Char)i; + + bw1.Write(chArr); + bw1.Write(chArr, 512, 512); + + bw1.Write(new String(chArr)); + bw1.Write(new String(chArr)); + + //[] we will now read + stream.Seek(0, SeekOrigin.Begin); + for (int i = 0; i < iLength; i++) + { + Assert.Equal(i % 256, stream.ReadByte()); + } + + + btArr = new Byte[iLength]; + stream.Read(btArr, 0, iLength); + for (int i = 0; i < iLength; i++) + { + Assert.Equal((byte)i, btArr[i]); + } + + //Now, for the binary reader + BinaryReader br1 = new BinaryReader(stream); + + Assert.False(br1.ReadBoolean()); + Assert.True(br1.ReadBoolean()); + + for (int i = 0; i < 10; i++) + { + Assert.Equal( (Byte)i, br1.ReadByte()); + Assert.Equal((SByte)i, br1.ReadSByte()); + Assert.Equal((Int16)i, br1.ReadInt16()); + Assert.Equal((Char)i, br1.ReadChar()); + Assert.Equal((UInt16)i, br1.ReadUInt16()); + Assert.Equal(i, br1.ReadInt32()); + Assert.Equal((UInt32)i, br1.ReadUInt32()); + Assert.Equal((Int64)i, br1.ReadInt64()); + Assert.Equal((UInt64)i, br1.ReadUInt64()); + Assert.Equal((Single)i, br1.ReadSingle()); + Assert.Equal((Double)i, br1.ReadDouble()); + } + + chArr = br1.ReadChars(iLength); + for (int i = 0; i < iLength; i++) + { + Assert.Equal((char)i, chArr[i]); + } + + chArr = new Char[512]; + chArr = br1.ReadChars(iLength / 2); + for (int i = 0; i < iLength / 2; i++) + { + Assert.Equal((char)(iLength / 2 + i), chArr[i]); + } + + chArr = new Char[iLength]; + for (int i = 0; i < iLength; i++) + chArr[i] = (Char)i; + strValue = br1.ReadString(); + Assert.Equal(new String(chArr), strValue); + + strValue = br1.ReadString(); + Assert.Equal(new String(chArr), strValue); + + stream.Seek(1, SeekOrigin.Current); // In the original test, success here would end the test + + //[] we will do some async tests here now + stream.Position = 0; + + btArr = new Byte[iLength]; + for (int i = 0; i < iLength; i++) + btArr[i] = (Byte)(i + 5); + + await stream.WriteAsync(btArr, 0, btArr.Length); + + stream.Position = 0; + for (int i = 0; i < iLength; i++) + { + Assert.Equal((byte)(i + 5), stream.ReadByte()); + } + + //we will read asynchronously + stream.Position = 0; + + Byte[] compArr = new Byte[iLength]; + + iValue = await stream.ReadAsync(compArr, 0, compArr.Length); + + Assert.Equal(btArr.Length, iValue); + + for (int i = 0; i < iLength; i++) + { + Assert.Equal(compArr[i], btArr[i]); + } + } + } +} diff --git a/src/System.IO/tests/Stream/TestLeaveOpen.cs b/src/System.IO/tests/Stream/TestLeaveOpen.cs new file mode 100644 index 0000000000..32c6c1aded --- /dev/null +++ b/src/System.IO/tests/Stream/TestLeaveOpen.cs @@ -0,0 +1,107 @@ +using System; +using System.IO; +using System.Threading.Tasks; +using Xunit; + +namespace StreamTests +{ + public class TestLeaveOpen + { + [Fact] + public static void StreamReaderTest() + { + MemoryStream ms = new MemoryStream(); + ms.WriteByte((byte)'a'); + ms.Position = 0; + Assert.True(ms.CanRead, "ERROR: Before testing, MemoryStream's CanRead property was false! What?"); + + // Test leaveOpen. + StreamReader sr = new StreamReader(ms, System.Text.Encoding.UTF8, true, 1000, true); + sr.Dispose(); + Assert.True(ms.CanRead, "ERROR: After closing a StreamReader with leaveOpen bool set, MemoryStream's CanRead property was false!"); + + // Test not leaving open + sr = new StreamReader(ms, System.Text.Encoding.UTF8, true, 1000, false); + sr.Dispose(); + Assert.False(ms.CanRead, "ERROR: After closing a StreamReader with leaveOpen bool not set, MemoryStream's CanRead property was true!"); + + // Test default + ms = new MemoryStream(); + sr = new StreamReader(ms); + sr.Dispose(); + Assert.False(ms.CanRead, "ERROR: After closing a StreamReader with the default value for leaveOpen, MemoryStream's CanRead property was true!"); + } + + [Fact] + public static void BinaryReaderTest() + { + MemoryStream ms = new MemoryStream(); + ms.WriteByte((byte)'a'); + ms.Position = 0; + Assert.True(ms.CanRead, "ERROR: Before testing, MemoryStream's CanRead property was false! What?"); + + // Test leaveOpen. + BinaryReader br = new BinaryReader(ms, System.Text.Encoding.UTF8, true); + br.Dispose(); + Assert.True(ms.CanRead, "ERROR: After closing a BinaryReader with leaveOpen bool set, MemoryStream's CanRead property was false!"); + + // Test not leaving open + br = new BinaryReader(ms, System.Text.Encoding.UTF8, false); + br.Dispose(); + Assert.False(ms.CanRead, "ERROR: After closing a BinaryReader with leaveOpen bool not set, MemoryStream's CanRead property was true!"); + + // Test default + ms = new MemoryStream(); + br = new BinaryReader(ms); + br.Dispose(); + Assert.False(ms.CanRead, "ERROR: After closing a BinaryReader with the default value for leaveOpen, MemoryStream's CanRead property was true!"); + } + + [Fact] + public static void StreamWriterTest() + { + MemoryStream ms = new MemoryStream(); + Assert.True(ms.CanWrite, "ERROR: Before testing, MemoryStream's CanWrite property was false! What?"); + + // Test leaveOpen. + StreamWriter sw = new StreamWriter(ms, System.Text.Encoding.UTF8, 1000, true); + sw.Dispose(); + Assert.True(ms.CanWrite, "ERROR: After closing a StreamWriter with leaveOpen bool set, MemoryStream's CanWrite property was false!"); + + // Test not leaving open + sw = new StreamWriter(ms, System.Text.Encoding.UTF8, 1000, false); + sw.Dispose(); + Assert.False(ms.CanWrite, "ERROR: After closing a StreamWriter with leaveOpen bool not set, MemoryStream's CanWrite property was true!"); + + // Test default + ms = new MemoryStream(); + sw = new StreamWriter(ms); + sw.Dispose(); + Assert.False( ms.CanWrite, "ERROR: After closing a StreamWriter with the default value for leaveOpen, MemoryStream's CanWrite property was true!"); + } + + [Fact] + public static void BinaryWriterTest() + { + + MemoryStream ms = new MemoryStream(); + Assert.True(ms.CanWrite, "ERROR: Before testing, MemoryStream's CanWrite property was false! What?"); + + // Test leaveOpen. + BinaryWriter bw = new BinaryWriter(ms, System.Text.Encoding.UTF8, true); + bw.Dispose(); + Assert.True(ms.CanWrite, "ERROR: After closing a BinaryWriterwith leaveOpen bool set, MemoryStream's CanWrite property was false!"); + + // Test not leaving open + bw = new BinaryWriter(ms, System.Text.Encoding.UTF8, false); + bw.Dispose(); + Assert.False(ms.CanWrite, "ERROR: After closing a BinaryWriterwith leaveOpen bool not set, MemoryStream's CanWrite property was true!"); + + // Test default + ms = new MemoryStream(); + bw = new BinaryWriter(ms); + bw.Dispose(); + Assert.False(ms.CanWrite, "ERROR: After closing a BinaryWriterwith the default value for leaveOpen, MemoryStream's CanWrite property was true!"); + } + } +} diff --git a/src/System.IO/tests/Stream/TimeoutTests.cs b/src/System.IO/tests/Stream/TimeoutTests.cs new file mode 100644 index 0000000000..710a93e9f4 --- /dev/null +++ b/src/System.IO/tests/Stream/TimeoutTests.cs @@ -0,0 +1,100 @@ +using System; +using System.IO; +using Xunit; + +namespace StreamTests +{ + public class MyStream : Stream + { + public override bool CanRead + { + get { return false; } + } + + public override bool CanSeek + { + get { return false; } + } + + + public override bool CanWrite + { + get { return false; } + } + + public override long Length + { + get { throw new NotSupportedException(); } + } + + + public override long Position + { + get { throw new NotSupportedException(); } + set { throw new NotSupportedException(); } + } + + public override void Flush() { } + public override long Seek(long offset, SeekOrigin origin) { throw new NotSupportedException(); } + public override void SetLength(long value) { throw new NotSupportedException(); } + public override int Read(byte[] buffer, int offset, int count) { return 0; } + public override void Write(byte[] buffer, int offset, int count) { } + + } + + public class TimeoutTests + { + [Fact] + public static void TestReadTimeoutCustomStream() + { + TestReadTimeout(new MyStream()); + } + [Fact] + public static void TestReadTimeoutMemoryStream() + { + TestReadTimeout(new MemoryStream()); + } + + + private static void TestReadTimeout(Stream stream) + { + Assert.Throws<InvalidOperationException>(() => { int readTimeout = stream.ReadTimeout; }); + + Assert.Throws<InvalidOperationException>(() => { stream.ReadTimeout = 500; }); + } + [Fact] + public static void TestWriteTimeoutCustomStream() + { + TestWriteTimeout(new MyStream()); + } + [Fact] + public static void TestWriteTimeoutMemoryStream() + { + TestWriteTimeout(new MemoryStream()); + } + + private static void TestWriteTimeout(Stream stream) + { + Assert.Throws<InvalidOperationException>(() => { int WriteTimeout = stream.WriteTimeout; }); + Assert.Throws<InvalidOperationException>(() => { stream.WriteTimeout = 500; }); + } + + [Fact] + public static void TestCanTimeoutCustomStream() + { + TestCanTimeout(new MyStream()); + } + + [Fact] + public static void TestCanTimeoutMemoryStream() + { + TestCanTimeout(new MemoryStream()); + } + + private static void TestCanTimeout(System.IO.Stream stream) + { + Assert.False(stream.CanTimeout, "Expected CanTimeout to return false"); + } + } + +} diff --git a/src/System.IO/tests/StreamReader/StreamReaderCtorTests.cs b/src/System.IO/tests/StreamReader/StreamReaderCtorTests.cs new file mode 100644 index 0000000000..7b85f6eae2 --- /dev/null +++ b/src/System.IO/tests/StreamReader/StreamReaderCtorTests.cs @@ -0,0 +1,50 @@ +using System; +using System.IO; +using System.Text; +using Xunit; + +namespace StreamReaderTests +{ + public class StreamReader_ctorTests + { + [Fact] + public static void StreamReaderNullPath() + { + Assert.Throws<ArgumentNullException>( + () => { new StreamReader((Stream)null, true); }); + } + [Fact] + public static void InputStreamClosed() + { + var ms2 = new MemoryStream(); + ms2.Dispose(); + + Assert.Throws<ArgumentException>( + () => { new StreamReader(ms2, false); }); + } + + [Fact] + public static void CreationFromMemoryStreamWithEncodingFalse() + { + var ms2 = new MemoryStream(); + ms2.Write(new Byte[] { 65, 66, 67, 68 }, 0, 4); + ms2.Position = 0; + var sr2 = new StreamReader(ms2, false); + + Assert.Equal("ABCD", sr2.ReadToEnd()); + sr2.Dispose(); + } + + [Fact] + public static void CreationFromMemoryStreamWithEncodingTrue() + { + var ms2 = new MemoryStream(); + ms2.Write(new Byte[] { 65, 66, 67, 68 }, 0, 4); + ms2.Position = 0; + var sr2 = new StreamReader(ms2, false); + + Assert.Equal("ABCD", sr2.ReadToEnd()); + sr2.Dispose(); + } + } +} diff --git a/src/System.IO/tests/StreamReader/StreamReaderTests.cs b/src/System.IO/tests/StreamReader/StreamReaderTests.cs new file mode 100644 index 0000000000..37a49adc9a --- /dev/null +++ b/src/System.IO/tests/StreamReader/StreamReaderTests.cs @@ -0,0 +1,377 @@ +using System; +using System.Collections.Generic; +using System.IO; +using System.Text; +using System.Threading.Tasks; +using Xunit; + +namespace StreamReaderTests +{ + public class StreamReaderTests + { + static Tuple<char[], StreamReader> GetCharArrayStream() + { + var chArr = new char[]{ + Char.MinValue + ,Char.MaxValue + ,'\t' + ,' ' + ,'$' + ,'@' + ,'#' + ,'\0' + ,'\v' + ,'\'' + ,'\u3190' + ,'\uC3A0' + ,'A' + ,'5' + ,'\r' + ,'\uFE70' + ,'-' + ,';' + ,'\r' + ,'\n' + ,'T' + ,'3' + ,'\n' + ,'K' + ,'\u00E6' + }; + + + var ms = new MemoryStream(); + var sw = new StreamWriter(ms); + + for (int i = 0; i < chArr.Length; i++) + sw.Write(chArr[i]); + sw.Flush(); + ms.Position = 0; + + return new Tuple<char[], StreamReader>(chArr, new StreamReader(ms)); + } + + static MemoryStream GetSmallStream() + { + byte[] testData = new byte[] { 72, 69, 76, 76, 79 }; + return new System.IO.MemoryStream(testData); + } + + static MemoryStream GetLargeStream() + { + byte[] testData = new byte[] { 72, 69, 76, 76, 79 }; + // System.Collections.Generic. + + List<byte> data = new List<byte>(); + for (int i = 0; i < 1000; i++) + { + data.AddRange(testData); + } + + return new System.IO.MemoryStream(data.ToArray()); + } + + + [Fact] + public static void EndOfStream() + { + var sw = new StreamReader(GetSmallStream()); + + var result = sw.ReadToEnd(); + + Assert.Equal("HELLO", result); + + Assert.True(sw.EndOfStream, "End of Stream was not true after ReadToEnd"); + } + + [Fact] + public static void EndOfStreamSmallDataLargeBuffer() + { + var sw = new StreamReader(GetSmallStream(), Encoding.UTF8, true, 1024); + + var result = sw.ReadToEnd(); + + Assert.Equal("HELLO", result); + + Assert.True(sw.EndOfStream, "End of Stream was not true after ReadToEnd"); + } + + [Fact] + public static void EndOfStreamLargeDataSmallBuffer() + { + var sw = new StreamReader(GetLargeStream(), Encoding.UTF8, true, 1); + + var result = sw.ReadToEnd(); + + Assert.Equal(5000, result.Length); + + Assert.True(sw.EndOfStream, "End of Stream was not true after ReadToEnd"); + } + + [Fact] + public static void EndOfStreamLargeDataLargeBuffer() + { + var sw = new StreamReader(GetLargeStream(), Encoding.UTF8, true, 1 << 16); + + var result = sw.ReadToEnd(); + + Assert.Equal(5000, result.Length); + + Assert.True(sw.EndOfStream, "End of Stream was not true after ReadToEnd"); + } + + [Fact] + public static async Task ReadToEndAsync() + { + var sw = new StreamReader(GetLargeStream()); + var result = await sw.ReadToEndAsync(); + + Assert.Equal(5000, result.Length); + } + + [Fact] + public static void GetBaseStream() + { + var ms = GetSmallStream(); + var sw = new StreamReader(ms); + + Assert.Equal(sw.BaseStream, ms); + } + + [Fact] + public static void TestRead() + { + var baseInfo = GetCharArrayStream(); + var sr = baseInfo.Item2; + + + for (int i = 0; i < baseInfo.Item1.Length; i++) + { + int tmp = sr.Read(); + Assert.Equal(tmp, (int)baseInfo.Item1[i]); + } + + sr.Dispose(); + } + + [Fact] + public static void TestPeek() + { + var baseInfo = GetCharArrayStream(); + var sr = baseInfo.Item2; + + for (int i = 0; i < baseInfo.Item1.Length; i++) + { + var peek = sr.Peek(); + Assert.Equal((int)baseInfo.Item1[i], peek); + + sr.Read(); + } + } + [Fact] + public static void ArgumentNullOnNullArray() + { + var baseInfo = GetCharArrayStream(); + var sr = baseInfo.Item2; + + Assert.Throws<ArgumentNullException>(() => + { + sr.Read(null, 0, 0); + }); + } + [Fact] + public static void ArgumentOutOfRangeOnInvalidOffset() + { + var sr = GetCharArrayStream().Item2; + Assert.Throws<ArgumentOutOfRangeException>(() => + { + sr.Read(new char[0], -1, 0); + }); + } + [Fact] + public static void ArgumentOutOfRangeOnNegativCount() + { + var sr = GetCharArrayStream().Item2; + Assert.Throws<ArgumentException>(() => + { + sr.Read(new char[0], 0, 1); + }); + } + [Fact] + public static void ArgumentExceptionOffsetAndCount() + { + var sr = GetCharArrayStream().Item2; + Assert.Throws<ArgumentException>(() => + { + sr.Read(new Char[0], 2, 0); + }); + } + [Fact] + public static void ObjectDisposedExceptionDisposedStream() + { + var sr = GetCharArrayStream().Item2; + sr.Dispose(); + + Assert.Throws<ObjectDisposedException>(() => + { + char[] temp = new char[1]; + sr.Read(temp, 0, 1); + }); + } + [Fact] + public static void ObjectDisposedExceptionDisposedBaseStream() + { + var ms = GetSmallStream(); + var sr = new StreamReader(ms); + ms.Dispose(); + + Assert.Throws<ObjectDisposedException>(() => + { + char[] temp = new char[1]; + sr.Read(temp, 0, 1); + }); + } + + [Fact] + public static void EmptyStream() + { + var ms = new MemoryStream(); + var sr = new StreamReader(ms); + + var buffer = new char[10]; + int read = sr.Read(buffer, 0, 1); + Assert.Equal(0, read); + } + + [Fact] + public static void VanillaReads1() + { + var baseInfo = GetCharArrayStream(); + var sr = baseInfo.Item2; + + var chArr = new Char[baseInfo.Item1.Length]; + + var read = sr.Read(chArr, 0, chArr.Length); + + Assert.Equal(read, chArr.Length); + for (int i = 0; i < baseInfo.Item1.Length; i++) + { + Assert.Equal(chArr[i], baseInfo.Item1[i]); + } + } + + [Fact] + public static async Task VanillaReads2WithAsync() + { + var baseInfo = GetCharArrayStream(); + + var sr = baseInfo.Item2; + + var chArr = new Char[baseInfo.Item1.Length]; + + var read = await sr.ReadAsync(chArr, 4, 3); + + Assert.Equal(read, 3); + for (int i = 0; i < 3; i++) + { + Assert.Equal(chArr[i + 4], baseInfo.Item1[i]); + } + } + [Fact] + public static void ObjectDisposedReadLine() + { + var baseInfo = GetCharArrayStream(); + var sr = baseInfo.Item2; + + sr.Dispose(); + Assert.Throws<ObjectDisposedException>(() => + { + sr.ReadLine(); + }); + } + [Fact] + public static void ObjectDisposedReadLineBaseStream() + { + var ms = GetLargeStream(); + var sr = new StreamReader(ms); + + ms.Dispose(); + Assert.Throws<ObjectDisposedException>(() => + { + sr.ReadLine(); + }); + } + + [Fact] + public static void VanillaReadLines() + { + var baseInfo = GetCharArrayStream(); + var sr = baseInfo.Item2; + + String valueString = new String(baseInfo.Item1); + + + var data = sr.ReadLine(); + Assert.Equal(valueString.Substring(0, valueString.IndexOf('\r')), data); + + data = sr.ReadLine(); + Assert.Equal(valueString.Substring(valueString.IndexOf('\r') + 1, 3), data); + + data = sr.ReadLine(); + Assert.Equal(valueString.Substring(valueString.IndexOf('\n') + 1, 2), data); + + data = sr.ReadLine(); + Assert.Equal((valueString.Substring(valueString.LastIndexOf('\n') + 1)), data); + } + + [Fact] + public static void VanillaReadLines2() + { + var baseInfo = GetCharArrayStream(); + var sr = baseInfo.Item2; + + String valueString = new String(baseInfo.Item1); + + var temp = new char[10]; + sr.Read(temp, 0, 1); + var data = sr.ReadLine(); + Assert.Equal(valueString.Substring(1, valueString.IndexOf('\r') - 1), data); + } + + [Fact] + public static async Task ContinuousNewLinesAndTabsAsync() + { + var ms = new MemoryStream(); + // ms.Write( + var sw = new StreamWriter(ms); + sw.Write("\n\n\r\r\n"); + sw.Flush(); + + ms.Position = 0; + + var sr = new StreamReader(ms); + + for (int i = 0; i < 4; i++) + { + var data = await sr.ReadLineAsync(); + Assert.Equal(String.Empty, data); + } + + var eol = await sr.ReadLineAsync(); + Assert.Null(eol); + } + + [Fact] + public static void CurrentEncoding() + { + var ms = new MemoryStream(); + + var sr = new StreamReader(ms); + Assert.Equal(Encoding.UTF8, sr.CurrentEncoding); + + sr = new StreamReader(ms, Encoding.Unicode); + Assert.Equal(Encoding.Unicode, sr.CurrentEncoding); + + } + } +} diff --git a/src/System.IO/tests/StreamWriter/BaseStream.cs b/src/System.IO/tests/StreamWriter/BaseStream.cs new file mode 100644 index 0000000000..ed2233adc3 --- /dev/null +++ b/src/System.IO/tests/StreamWriter/BaseStream.cs @@ -0,0 +1,18 @@ +using System; +using System.IO; +using Xunit; + +namespace StreamWriterTests +{ + public class BaseStream + { + [Fact] + public static void GetBaseStream() + { + // [] Get an underlying memorystream + MemoryStream memstr2 = new MemoryStream(); + StreamWriter sw = new StreamWriter(memstr2); + Assert.Equal(sw.BaseStream, memstr2); + } + } +} diff --git a/src/System.IO/tests/StreamWriter/CloseTests.cs b/src/System.IO/tests/StreamWriter/CloseTests.cs new file mode 100644 index 0000000000..9d3b47923c --- /dev/null +++ b/src/System.IO/tests/StreamWriter/CloseTests.cs @@ -0,0 +1,56 @@ +using System; +using System.IO; +using Xunit; + +namespace StreamWriterTests +{ + public class CloseTests + { + [Fact] + public static void AfterDisposeThrows() + { + StreamWriter sw2; + + // [] Calling methods after closing the stream should throw + //----------------------------------------------------------------- + sw2 = new StreamWriter(new MemoryStream()); + sw2.Dispose(); + + Assert.Throws<ObjectDisposedException>(() => { sw2.Write('A'); }); + Assert.Throws<ObjectDisposedException>(() => { sw2.Write("hello"); }); + Assert.Throws<ObjectDisposedException>(() => { sw2.Flush(); }); + Assert.Null(sw2.BaseStream); + + Assert.Throws<ObjectDisposedException>(() => { sw2.AutoFlush = true; }); + } + + [Fact] + public static void CloseCausesFlush() { + StreamWriter sw2; + MemoryStream memstr2; + + // [] Check that flush updates the underlying stream + //----------------------------------------------------------------- + memstr2 = new MemoryStream(); + sw2 = new StreamWriter(memstr2); + + var strTemp = "HelloWorld" ; + sw2.Write( strTemp); + Assert.Equal(0, memstr2.Length); + + sw2.Flush(); + Assert.Equal(strTemp.Length, memstr2.Length); + } + [Fact] + public static void CantFlushAfterDispose() { + // [] Flushing closed writer should throw + //----------------------------------------------------------------- + + MemoryStream memstr2 = new MemoryStream(); + StreamWriter sw2 = new StreamWriter(memstr2); + + sw2.Dispose(); + Assert.Throws<ObjectDisposedException>(() => { sw2.Flush(); }); + } + } +} diff --git a/src/System.IO/tests/StreamWriter/CtorTests.cs b/src/System.IO/tests/StreamWriter/CtorTests.cs new file mode 100644 index 0000000000..66100b333f --- /dev/null +++ b/src/System.IO/tests/StreamWriter/CtorTests.cs @@ -0,0 +1,73 @@ +using System; +using System.IO; +using Xunit; + +namespace StreamWriterTests +{ + public class CtorTests + { + [Fact] + public static void CreateStreamWriter() + { + StreamWriter sw2; + StreamReader sr2; + String str2; + MemoryStream memstr2; + + // [] Construct writer with MemoryStream + //----------------------------------------------------------------- + + memstr2 = new MemoryStream(); + sw2 = new StreamWriter(memstr2); + sw2.Write("HelloWorld"); + sw2.Flush(); + sr2 = new StreamReader(memstr2); + memstr2.Position = 0; + str2 = sr2.ReadToEnd(); + Assert.Equal("HelloWorld", str2); + } + [Fact] + public static void NullEncodingThrows() + { + // [] Check for ArgumentNullException on null encoding + //----------------------------------------------------------------- + + Assert.Throws<ArgumentNullException>(() => { new StreamWriter(new MemoryStream(), null); }); + } + + [Fact] + public static void UTF8Encoding() + { + TestEnconding(System.Text.Encoding.UTF8, "This is UTF8\u00FF"); + } + + [Fact] + public static void BigEndianUnicodeEncoding() + { + TestEnconding(System.Text.Encoding.BigEndianUnicode, "This is BigEndianUnicode\u00FF"); + } + + [Fact] + public static void UnicodeEncoding() + { + TestEnconding(System.Text.Encoding.Unicode, "This is Unicode\u00FF"); + } + + private static void TestEnconding(System.Text.Encoding encoding, String testString) + { + StreamWriter sw2; + StreamReader sr2; + String str2; + + var ms = new MemoryStream(); + sw2 = new StreamWriter(ms, encoding); + sw2.Write(testString); + sw2.Dispose(); + + var ms2 = new MemoryStream(ms.ToArray()); + sr2 = new StreamReader(ms2, encoding); + str2 = sr2.ReadToEnd(); + Assert.Equal(testString, str2); + } + } +} diff --git a/src/System.IO/tests/StreamWriter/FlushTests.cs b/src/System.IO/tests/StreamWriter/FlushTests.cs new file mode 100644 index 0000000000..c30c0072b5 --- /dev/null +++ b/src/System.IO/tests/StreamWriter/FlushTests.cs @@ -0,0 +1,27 @@ +using System; +using System.IO; +using Xunit; + +namespace StreamWriterTests +{ + public class FlushTests + { + [Fact] + public static void AutoFlushSetTrue() + { + // [] Set the autoflush to true + var sw2 = new StreamWriter(new MemoryStream()); + sw2.AutoFlush = true; + Assert.True(sw2.AutoFlush); + } + + [Fact] + public static void AutoFlushSetFalse() + { + // [] Set autoflush to false + var sw2 = new StreamWriter(new MemoryStream()); + sw2.AutoFlush = false; + Assert.False(sw2.AutoFlush); + } + } +} diff --git a/src/System.IO/tests/StreamWriter/WriteTests.cs b/src/System.IO/tests/StreamWriter/WriteTests.cs new file mode 100644 index 0000000000..be9d1305e4 --- /dev/null +++ b/src/System.IO/tests/StreamWriter/WriteTests.cs @@ -0,0 +1,183 @@ +using System; +using System.IO; +using System.Text; +using Xunit; + +namespace StreamWriterTests +{ + public class Co5563Write_ch + { + [Fact] + public static void WriteChars() + { + char[] chArr = setupArray(); + + // [] Write a wide variety of characters and read them back + + MemoryStream ms = new MemoryStream(); + StreamWriter sw = new StreamWriter(ms); + StreamReader sr; + + for (int i = 0; i < chArr.Length; i++) + sw.Write(chArr[i]); + sw.Flush(); + ms.Position = 0; + sr = new StreamReader(ms); + + for (int i = 0; i < chArr.Length; i++) + { + Assert.Equal((Int32)chArr[i], sr.Read()); + } + } + + private static char[] setupArray() + { + return new Char[]{ + Char.MinValue + ,Char.MaxValue + ,'\t' + ,' ' + ,'$' + ,'@' + ,'#' + ,'\0' + ,'\v' + ,'\'' + ,'\u3190' + ,'\uC3A0' + ,'A' + ,'5' + ,'\uFE70' + ,'-' + ,';' + ,'\u00E6' + }; + } + [Fact] + public static void NullArray() + { + // [] Exception for null array + MemoryStream ms = new MemoryStream(); + StreamWriter sw = new StreamWriter(ms); + + Assert.Throws<ArgumentNullException>(() => { sw.Write(null, 0, 0); }); + sw.Dispose(); + } + [Fact] + public static void NegativeOffset() + { + char[] chArr = setupArray(); + + // [] Exception if offset is negative + MemoryStream ms = new MemoryStream(); + StreamWriter sw = new StreamWriter(ms); + + Assert.Throws<ArgumentOutOfRangeException>(() => { sw.Write(chArr, -1, 0); }); + sw.Dispose(); + } + [Fact] + public static void NegativeCount() + { + char[] chArr = setupArray(); + + // [] Exception if count is negative + MemoryStream ms = new MemoryStream(); + StreamWriter sw = new StreamWriter(ms); + + Assert.Throws<ArgumentOutOfRangeException>(() => { sw.Write(chArr, 0, -1); }); + sw.Dispose(); + } + + [Fact] + public static void WriteCustomLenghtStrings() + { + char[] chArr = setupArray(); + + // [] Write some custom length strings + MemoryStream ms = new MemoryStream(); + StreamWriter sw = new StreamWriter(ms); + StreamReader sr; + + sw.Write(chArr, 2, 5); + sw.Flush(); + ms.Position = 0; + sr = new StreamReader(ms); + Int32 tmp = 0; + for (int i = 2; i < 7; i++) + { + tmp = sr.Read(); + Assert.Equal((Int32)chArr[i], tmp); + } + ms.Dispose(); + } + + [Fact] + public static void WriteToStreamWriter() + { + char[] chArr = setupArray(); + // [] Just construct a streamwriter and write to it + //------------------------------------------------- + MemoryStream ms = new MemoryStream(); + StreamWriter sw = new StreamWriter(ms); + StreamReader sr; + + sw.Write(chArr, 0, chArr.Length); + sw.Flush(); + ms.Position = 0; + sr = new StreamReader(ms); + + for (int i = 0; i < chArr.Length; i++) + { + Assert.Equal((Int32)chArr[i], sr.Read()); + } + ms.Dispose(); + } + [Fact] + public static void TestWritingPastEndOfArray() + { + char[] chArr = setupArray(); + MemoryStream ms = new MemoryStream(); + StreamWriter sw = new StreamWriter(ms); + + Assert.Throws<ArgumentException>(() => { sw.Write(chArr, 1, chArr.Length); }); + sw.Dispose(); + } + + [Fact] + public static void VerifyWrittenString() + { + char[] chArr = setupArray(); + // [] Write string with wide selection of characters and read it back + + StringBuilder sb = new StringBuilder(40); + MemoryStream ms = new MemoryStream(); + StreamWriter sw = new StreamWriter(ms); + StreamReader sr; + + for (int i = 0; i < chArr.Length; i++) + sb.Append(chArr[i]); + + sw.Write(sb.ToString()); + sw.Flush(); + ms.Position = 0; + sr = new StreamReader(ms); + + for (int i = 0; i < chArr.Length; i++) + { + Assert.Equal((Int32)chArr[i], sr.Read()); + } + } + + [Fact] + public static void NullStreamThrows() + { + // [] Null string should write nothing + + MemoryStream ms = new MemoryStream(); + StreamWriter sw = new StreamWriter(ms); + sw.Write((String)null); + sw.Flush(); + Assert.Equal(0, ms.Length); + } + } +} diff --git a/src/System.IO/tests/StringReader/StringReaderCtorTests.cs b/src/System.IO/tests/StringReader/StringReaderCtorTests.cs new file mode 100644 index 0000000000..39d3f24bee --- /dev/null +++ b/src/System.IO/tests/StringReader/StringReaderCtorTests.cs @@ -0,0 +1,156 @@ +using System; +using System.IO; +using Xunit; + +namespace StringReaderTests +{ + public class ReaderTests + { + [Fact] + public static void StringReaderWithNullString() + { + // [] Null Argument should store null string + //----------------------------------------------------------- + + Assert.Throws<ArgumentNullException>(() => + { + StringReader sr = new StringReader(null); + String strTemp = sr.ReadToEnd(); + sr.ReadLine(); + sr.Peek(); + sr.Read(); + sr.Dispose(); + }); + + } + + [Fact] + public static void StringReaderWithEmptyString() + { + + // [] Check vanilla construction + //----------------------------------------------------------- + StringReader sr = new StringReader(String.Empty); + Assert.Equal(String.Empty, sr.ReadToEnd()); + } + + [Fact] + public static void StringReaderWithGenericString() + { + // [] Another vanilla construction + //----------------------------------------------------------- + + StringReader sr = new StringReader("Hello\0World"); + Assert.Equal("Hello\0World", sr.ReadToEnd()); + } + + [Fact] + public static void ReadEmtpyString() { + StringReader sr = new StringReader(String.Empty); + Assert.Equal(-1, sr.Read()); + + } + + [Fact] + public static void ReadString() { + String str1 = "Hello\0\t\v \\ World"; + StringReader sr = new StringReader(str1); + for (int i = 0; i < str1.Length; i++) + { + Assert.Equal((int)str1[i], sr.Read()); + } + + } + + [Fact] + public static void ReadPsudoRandomString() + { + String str1 = String.Empty; + Random r = new Random(-55); + for (int i = 0; i < 5000; i++) + str1 += (Char)r.Next(0, 255); + + StringReader sr = new StringReader(str1); + for (int i = 0; i < str1.Length; i++) + { + Assert.Equal((int)str1[i], sr.Read()); + } + } + + + + + + [Fact] + public static void PeedEmtpyString() + { + StringReader sr = new StringReader(String.Empty); + Assert.Equal(-1, sr.Peek()); + + } + + [Fact] + public static void PeekString() + { + String str1 = "Hello\0\t\v \\ World"; + StringReader sr = new StringReader(str1); + for (int i = 0; i < str1.Length; i++) + { + int test = sr.Peek(); + sr.Read(); + Assert.Equal((int)str1[i], test); + } + + } + + [Fact] + public static void PeekPsudoRandomString() + { + String str1 = String.Empty; + Random r = new Random(-55); + for (int i = 0; i < 5000; i++) + str1 += (Char)r.Next(0, 255); + + StringReader sr = new StringReader(str1); + for (int i = 0; i < str1.Length; i++) + { + int test = sr.Peek(); + sr.Read(); + Assert.Equal((int)str1[i], test); + } + } + + [Fact] + public static void ReadToEndEmptyString() + { + ///////////////////////// START TESTS //////////////////////////// + /////////////////////////////////////////////////////////////////// + + StringReader sr; + + sr = new StringReader(String.Empty); + Assert.Equal(String.Empty, sr.ReadToEnd()); + + } + + [Fact] + public static void ReadToEndString() { + String str1 = "Hello\0\t\v \\ World"; + StringReader sr = new StringReader(str1); + Assert.Equal(str1, sr.ReadToEnd()); + } + + [Fact] + public static void ReadToEndPsuedoRandom() { + // [] Try with large random strings + //----------------------------------------------------------- + String str1 = String.Empty; + Random r = new Random(-55); + for (int i = 0; i < 10000; i++) + str1 += (Char)r.Next(0, 255); + + StringReader sr = new StringReader(str1); + Assert.Equal(str1, sr.ReadToEnd()); + } + } +} diff --git a/src/System.IO/tests/StringWriter/StringWriterTests.cs b/src/System.IO/tests/StringWriter/StringWriterTests.cs new file mode 100644 index 0000000000..d11b609e0f --- /dev/null +++ b/src/System.IO/tests/StringWriter/StringWriterTests.cs @@ -0,0 +1,369 @@ +using Xunit; +using System; +using System.Globalization; +using System.IO; +using System.Text; +using System.Threading.Tasks; + +namespace StreamTests +{ + public class StringWriterTests + { + static int[] iArrInvalidValues = new Int32[] { -1, -2, -100, -1000, -10000, -100000, -1000000, -10000000, -100000000, -1000000000, Int32.MinValue, Int16.MinValue }; + static int[] iArrLargeValues = new Int32[] { Int32.MaxValue, Int32.MaxValue - 1, Int32.MaxValue / 2, Int32.MaxValue / 10, Int32.MaxValue / 100 }; + static int[] iArrValidValues = new Int32[] { 10000, 100000, Int32.MaxValue / 2000, Int32.MaxValue / 5000, Int16.MaxValue }; + + private static char[] getCharArray() + { + return new char[]{ + Char.MinValue + ,Char.MaxValue + ,'\t' + ,' ' + ,'$' + ,'@' + ,'#' + ,'\0' + ,'\v' + ,'\'' + ,'\u3190' + ,'\uC3A0' + ,'A' + ,'5' + ,'\uFE70' + ,'-' + ,';' + ,'\u00E6' + }; + } + + private static StringBuilder getSb() + { + var chArr = getCharArray(); + var sb = new StringBuilder(40); + for (int i = 0; i < chArr.Length; i++) + sb.Append(chArr[i]); + + return sb; + } + + [Fact] + public static void Ctor() + { + StringWriter sw = new StringWriter(); + Assert.NotNull(sw); + } + + [Fact] + public static void CtorWithStringBuilder() + { + var sb = getSb(); + StringWriter sw = new StringWriter(getSb()); + Assert.NotNull(sw); + Assert.Equal(sb.Length, sw.GetStringBuilder().Length); + } + + [Fact] + public static void CtorWithCultureInfo() + { + StringWriter sw = new StringWriter(new CultureInfo("en-gb")); + Assert.NotNull(sw); + + Assert.Equal(new CultureInfo("en-gb"), sw.FormatProvider); + } + + [Fact] + public static void SimpleWriter() + { + var sw = new StringWriter(); + sw.Write(4); + var sb = sw.GetStringBuilder(); + Assert.Equal("4", sb.ToString()); + } + + [Fact] + public static void WriteArray() + { + var chArr = getCharArray(); + StringBuilder sb = getSb(); + StringWriter sw = new StringWriter(sb); + + var sr = new StringReader(sw.GetStringBuilder().ToString()); + + for (int i = 0; i < chArr.Length; i++) + { + int tmp = sr.Read(); + Assert.Equal((int)chArr[i], tmp); + } + } + [Fact] + public static void CantWriteNullArray() + { + var sw = new StringWriter(); + Assert.Throws<ArgumentNullException>(() => + { + sw.Write(null, 0, 0); + }); + } + [Fact] + public static void CantWriteNegativeOffset() + { + var sw = new StringWriter(); + Assert.Throws<ArgumentOutOfRangeException>(() => + { + sw.Write(new char[0], -1, 0); + }); + } + [Fact] + public static void CantWriteNegativeCount() + { + var sw = new StringWriter(); + Assert.Throws<ArgumentOutOfRangeException>(() => + { + sw.Write(new char[0], 0, -1); + }); + } + [Fact] + public static void CantWriteIndexLargeValues() + { + var chArr = getCharArray(); + for (int i = 0; i < iArrLargeValues.Length; i++) + { + StringWriter sw = new StringWriter(); + Assert.Throws<ArgumentException>(() => + { + sw.Write(chArr, iArrLargeValues[i], chArr.Length); + }); + } + } + [Fact] + public static void CantWriteCountLargeValues() + { + var chArr = getCharArray(); + for (int i = 0; i < iArrLargeValues.Length; i++) + { + StringWriter sw = new StringWriter(); + Assert.Throws<ArgumentException>(() => + { + sw.Write(chArr, 0, iArrLargeValues[i]); + }); + } + } + + [Fact] + public static void WriteWithOffset() + { + StringWriter sw = new StringWriter(); + StringReader sr; + + var chArr = getCharArray(); + + sw.Write(chArr, 2, 5); + + sr = new StringReader(sw.ToString()); + for (int i = 2; i < 7; i++) + { + int tmp = sr.Read(); + Assert.Equal((int)chArr[i], tmp); + } + } + + [Fact] + public static void WriteWithLargeIndex() + { + for (int i = 0; i < iArrValidValues.Length; i++) + { + StringBuilder sb = new StringBuilder(Int32.MaxValue / 2000); + StringWriter sw = new StringWriter(sb); + + var chArr = new Char[Int32.MaxValue / 2000]; + for (int j = 0; j < chArr.Length; j++) + chArr[j] = (char)(j % 256); + sw.Write(chArr, iArrValidValues[i] - 1, 1); + + String strTemp = sw.GetStringBuilder().ToString(); + Assert.Equal(1, strTemp.Length); + } + } + + + [Fact] + public static void WriteWithLargeCount() + { + for (int i = 0; i < iArrValidValues.Length; i++) + { + StringBuilder sb = new StringBuilder(Int32.MaxValue / 2000); + StringWriter sw = new StringWriter(sb); + + var chArr = new Char[Int32.MaxValue / 2000]; + for (int j = 0; j < chArr.Length; j++) + chArr[j] = (char)(j % 256); + + sw.Write(chArr, 0, iArrValidValues[i]); + + String strTemp = sw.GetStringBuilder().ToString(); + Assert.Equal(iArrValidValues[i], strTemp.Length); + } + } + + [Fact] + public static void NewStringWriterIsEmpty() + { + var sw = new StringWriter(); + Assert.Equal(String.Empty, sw.ToString()); + } + + [Fact] + public static void NewStringWriterHasEmptyStringBuilder() + { + var sw = new StringWriter(); + Assert.Equal(String.Empty, sw.GetStringBuilder().ToString()); + } + + [Fact] + public static void ToStringReturnsWrittenData() + { + StringBuilder sb = getSb(); + StringWriter sw = new StringWriter(sb); + + sw.Write(sb.ToString()); + + Assert.Equal(sb.ToString(), sw.ToString()); + } + + [Fact] + public static void StringBuilderHasCorrectData() + { + StringBuilder sb = getSb(); + StringWriter sw = new StringWriter(sb); + + sw.Write(sb.ToString()); + + Assert.Equal(sb.ToString(), sw.GetStringBuilder().ToString()); + } + + [Fact] + public static void Disposed() + { + StringWriter sw = new StringWriter(); + sw.Dispose(); + } + + [Fact] + public static async Task FlushAsyncWorks() + { + StringBuilder sb = getSb(); + StringWriter sw = new StringWriter(sb); + + sw.Write(sb.ToString()); + + await sw.FlushAsync(); // I think this is a noop in this case + + Assert.Equal(sb.ToString(), sw.GetStringBuilder().ToString()); + } + + [Fact] + public static void MiscWrites() + { + var sw = new StringWriter(); + sw.Write('H'); + sw.Write("ello World!"); + + Assert.Equal("Hello World!", sw.ToString()); + } + + [Fact] + public static async Task MiscWritesAsync() + { + var sw = new StringWriter(); + await sw.WriteAsync('H'); + await sw.WriteAsync(new char[] { 'e', 'l', 'l', 'o', ' ' }); + await sw.WriteAsync("World!"); + + Assert.Equal("Hello World!", sw.ToString()); + } + + [Fact] + public static async Task MiscWriteLineAsync() + { + var sw = new StringWriter(); + await sw.WriteLineAsync('H'); + await sw.WriteLineAsync(new char[] { 'e', 'l', 'l', 'o' }); + await sw.WriteLineAsync("World!"); + + Assert.Equal("H\r\nello\r\nWorld!\r\n", sw.ToString()); + } + + [Fact] + public static void GetEncoding() + { + var sw = new StringWriter(); + Assert.Equal(Encoding.Unicode.WebName, sw.Encoding.WebName); + } + + [Fact] + public static void TestWriteMisc() + { + var sw = new StringWriter(); + + sw.Write(true); + sw.Write((char)'a'); + sw.Write(new Decimal(1234.01)); + sw.Write((double)3452342.01); + sw.Write((int)23456); + sw.Write((long)long.MinValue); + sw.Write((float)1234.50f); + sw.Write((UInt32)UInt32.MaxValue); + sw.Write((UInt64)UInt64.MaxValue); + + Assert.Equal("Truea1234.013452342.0123456-92233720368547758081234.5429496729518446744073709551615", sw.ToString()); + } + + [Fact] + public static void TestWriteObject() + { + var sw = new StringWriter(); + sw.Write(new Object()); + Assert.Equal("System.Object", sw.ToString()); + } + + [Fact] + public static void TestWriteLineMisc() + { + var sw = new StringWriter(); + sw.WriteLine((bool)false); + sw.WriteLine((char)'B'); + sw.WriteLine((int)987); + sw.WriteLine((long)875634); + sw.WriteLine((Single)1.23457f); + sw.WriteLine((UInt32)45634563); + sw.WriteLine((UInt64.MaxValue)); + + Assert.Equal(@"False +B +987 +875634 +1.23457 +45634563 +18446744073709551615 +", sw.ToString()); + } + + [Fact] + public static void TestWriteLineObject() + { + var sw = new StringWriter(); + sw.WriteLine(new Object()); + Assert.Equal("System.Object\r\n", sw.ToString()); + } + + [Fact] + public static void TestWriteLineAsyncCharArray() + { + StringWriter sw = new StringWriter(); + sw.WriteLineAsync(new char[] { 'H', 'e', 'l', 'l', 'o' }); + + Assert.Equal("Hello\r\n", sw.ToString()); + } + } +} diff --git a/src/System.IO/tests/System.IO.Tests.csproj b/src/System.IO/tests/System.IO.Tests.csproj index f5e50b67a9..d05d6b0c11 100644 --- a/src/System.IO/tests/System.IO.Tests.csproj +++ b/src/System.IO/tests/System.IO.Tests.csproj @@ -1,4 +1,4 @@ -<?xml version="1.0" encoding="utf-8"?> +<?xml version="1.0" encoding="utf-8"?> <Project ToolsVersion="12.0" DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003"> <Import Project="$([MSBuild]::GetDirectoryNameOfFileAbove($(MSBuildThisFileDirectory), dir.props))\dir.props" /> <PropertyGroup> @@ -14,7 +14,26 @@ <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' " /> <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' " /> <ItemGroup> - <Compile Include="System\IO\InvalidDataExceptionTests.cs" /> + <Compile Include="BinaryWriter\BinaryWriter_WriteByteCharTests.cs" /> + <Compile Include="BinaryWriter\BinaryWriter_WriteTests.cs" /> + <Compile Include="BinaryWriter\BinaryWriterTests.cs" /> + <Compile Include="InvalidDataException\InvalidDataExceptionTests.cs" /> + <Compile Include="MemoryStream\Inputs.cs" /> + <Compile Include="MemoryStream\MemoryStream_TryGetBufferTests.cs" /> + <Compile Include="StreamReader\StreamReaderCtorTests.cs" /> + <Compile Include="StreamReader\StreamReaderTests.cs" /> + <Compile Include="StreamWriter\BaseStream.cs" /> + <Compile Include="StreamWriter\CloseTests.cs" /> + <Compile Include="StreamWriter\CtorTests.cs" /> + <Compile Include="StreamWriter\FlushTests.cs" /> + <Compile Include="StreamWriter\WriteTests.cs" /> + <Compile Include="Stream\NullTests.cs" /> + <Compile Include="Stream\StreamAsyncTests.cs" /> + <Compile Include="Stream\StreamMethods.cs" /> + <Compile Include="Stream\TestLeaveOpen.cs" /> + <Compile Include="Stream\TimeoutTests.cs" /> + <Compile Include="StringReader\StringReaderCtorTests.cs" /> + <Compile Include="StringWriter\StringWriterTests.cs" /> </ItemGroup> <ItemGroup> <!-- Compile tests against the contract, but copy our local-built implementation for testing --> diff --git a/src/System.IO/tests/project.json b/src/System.IO/tests/project.json index e70e389d5f..4fe2b9533e 100644 --- a/src/System.IO/tests/project.json +++ b/src/System.IO/tests/project.json @@ -1,11 +1,20 @@ { "dependencies": { +<<<<<<< HEAD "System.Globalization": "4.0.10", "System.IO": "4.0.10", "xunit": "2.1.0-beta3-*", +======= + "System.Globalization": "4.0.0-beta-*", + "System.Text.Encoding.CodePages": "4.0.0-beta-*", + "xunit": "2.0.0-beta5-build2785", + "xunit.abstractions.netcore": "1.0.0-prerelease", + "xunit.assert": "2.0.0-beta5-build2785", + "xunit.core.netcore": "1.0.1-prerelease", +>>>>>>> Port additional System.IO tests from ToF "xunit.netcore.extensions": "1.0.0-prerelease-*" }, "frameworks": { "dnxcore50": {} } -}
\ No newline at end of file +} |