public void TryChangingPositionCombinedWithWritingAndReading()
        {
            DataStreamReadableWritable dataStream = TestCollaboratorsFactory.CreateEmptyDataStream();

            byte[] bytes = ByteBufferFactory.CreateByteBufferWithAllBytesSet(123, 123);

            dataStream.Write(bytes, 0, bytes.Length);

            dataStream.SetPosition(0);

            byte[] bytes2 = ByteBufferFactory.CreateByteBufferWithAllBytesSet(14, 77);

            dataStream.Write(bytes2, 0, bytes2.Length);

            var bytesRead = new byte[dataStream.Length];

            dataStream.SetPosition(0);

            dataStream.Read(bytesRead, 0, dataStream.Length);

            for (int i = 0; i < dataStream.Length; i++)
            {
                if (i <= 13)
                {
                    Assert.AreEqual(77, bytesRead[i]);
                }
                else
                {
                    Assert.AreEqual(123, bytesRead[i]);
                }
            }
        }
        public void TryExpandingTheStreamViaSetLengthAndThenWritingReadingFromIt()
        {
            DataStreamReadableWritable dataStream = TestCollaboratorsFactory.CreateEmptyDataStream();

            const int testArrayLength = 500000;

            dataStream.SetLength(testArrayLength);

            Assert.AreEqual(testArrayLength, dataStream.Length);
            Assert.AreEqual(0, dataStream.Position);

            const int halfTestArray = testArrayLength / 2; //на половине пути запишем что-нибудь интересное.

            dataStream.SetPosition(halfTestArray);

            var bytesToWrite = new byte[halfTestArray];

            for (int i = 0; i < bytesToWrite.Length; i++)
            {
                bytesToWrite[i] = 231;
            }

            dataStream.Write(bytesToWrite, 0, bytesToWrite.Length);

            dataStream.SetPosition(halfTestArray);

            var bytesRead = new byte[bytesToWrite.Length];

            dataStream.Read(bytesRead, 0, bytesRead.Length);

            MakeSureEachByteInArrayIsRight(bytesRead, 231); // и проверим, что записалось что нужно, - новый объем как будто проработан.
        }
        /// <summary>
        /// Записывает в поток указанное число байт из массива. Если поток недостаточного размера, он увеличивается.
        /// Запись производится, начиная с текущей позиции в потоке.
        /// </summary>
        /// <param name="bytesToWrite">Массив байт, данные из которого следует записать в поток.</param>
        /// <param name="arrayOffset">Указывает начальную позицию в массиве (<paramref name="bytesToWrite"/>), с которой нужно брать байты для записи.</param>
        /// <param name="count">Количество байт, которые, начиная с <paramref name="arrayOffset"/>, следует записать в поток.</param>
        /// <exception cref="InsufficientSpaceException"></exception>
        /// <exception cref="ObjectDisposedException"></exception>
        /// <exception cref="ArgumentNullException"></exception>
        /// <exception cref="ArgumentException"></exception>
        /// <exception cref="MaximumFileSizeReachedException"></exception>
        public override void Write(byte[] bytesToWrite, int arrayOffset, int count)
        {
            var oldLength = _dataStream.Length;

            _dataStream.Write(bytesToWrite, arrayOffset, count);

            var newLength = _dataStream.Length;

            if (newLength != oldLength)
            {
                this.PersistOwningNode();
            }
        }
        public void MakeSureReadDoesNotThrowIfReadingBeyondTheStream()
        {
            DataStreamReadableWritable dataStream = TestCollaboratorsFactory.CreateEmptyDataStream();

            byte[] bytes = ByteBufferFactory.CreateByteBufferWithAllBytesSet(55000, 123);

            dataStream.Write(bytes, 0, bytes.Length);

            dataStream.SetPosition(55000 - 35);

            var largeArray = new byte[2000];

            Assert.AreEqual(35, dataStream.Read(largeArray, 0, 2000));
        }
        public void TryPushingAFileToItsLimitSize()
        {
            var testCollaborators = TestCollaboratorsFactory.CreateCollaboratorsForTestingDataStreamsOneGigabyteDrive();

            DataStreamReadableWritable stream =
                testCollaborators.VirtualFileSystem.OpenFileForWriting(testCollaborators.FileInfo.FullPath);

            var zeroes = new byte[testCollaborators.Disk.BlockSizeInBytes * 1000];

            ExceptionAssert.MakeSureExceptionIsRaisedBy <MaximumFileSizeReachedException>(
                delegate
            {
                while (stream.Length != Int32.MaxValue)
                {
                    stream.Write(zeroes, 0, zeroes.Length);
                }
            });
        }
        public void MakeSureShrinkingFreesDiskSpace()
        {
            var testCollaborators = TestCollaboratorsFactory.CreateCollaboratorsForTestingDataStreams();

            DataStreamReadableWritable dataStream =
                testCollaborators.VirtualFileSystem.OpenFileForWriting(testCollaborators.FileInfo.FullPath);

            int valueCloseToDiskSize = (int)testCollaborators.Disk.DiskSizeInBytes - 25 * testCollaborators.Disk.BlockSizeInBytes;

            dataStream.SetLength(valueCloseToDiskSize);

            var fileSystem = testCollaborators.VirtualFileSystem;

            FileInfo newFileNode = fileSystem.CreateFile(@"\testFile2");

            DataStreamReadableWritable newFileNodeStream = fileSystem.OpenFileForWriting(newFileNode.FullPath);

            ExceptionAssert.MakeSureExceptionIsRaisedBy <InsufficientSpaceException>(
                delegate
            {
                newFileNodeStream.SetLength(valueCloseToDiskSize);
            });

            dataStream.SetLength(0);

            newFileNodeStream.SetLength(valueCloseToDiskSize);
            dataStream.SetPosition(0);

            const int answeringToAllQuestionsByte = 42;

            byte[] bytesToWrite = ByteBufferFactory.CreateByteBufferWithAllBytesSet(valueCloseToDiskSize, answeringToAllQuestionsByte);

            newFileNodeStream.Write(bytesToWrite, 0, bytesToWrite.Length);

            newFileNodeStream.SetPosition(0);

            var buffer = new byte[valueCloseToDiskSize];

            newFileNodeStream.Read(buffer, 0, buffer.Length);

            MakeSureEachByteInArrayIsRight(buffer, answeringToAllQuestionsByte);
        }
        private void TryWritingAndReadingBackSpecifiedByteArrays(byte[] testArray)
        {
            DataStreamReadableWritable dataStream = TestCollaboratorsFactory.CreateEmptyDataStream();

            Assert.AreEqual(0, dataStream.Position);
            Assert.AreEqual(0, dataStream.Length);

            dataStream.Write(testArray, 0, testArray.Length);

            Assert.AreEqual(testArray.Length, dataStream.Position);
            Assert.AreEqual(testArray.Length, dataStream.Length);

            var bytesRead = new byte[testArray.Length];

            Assert.AreEqual(0, dataStream.Read(bytesRead, 0, testArray.Length)); // позиция в DataStream = testArray.Length; Прочитать ничего не получится.

            dataStream.SetPosition(0);

            dataStream.Read(bytesRead, 0, testArray.Length);

            CollectionAssert.AreEqual(testArray, bytesRead);
        }
        public void TryReadingAndWritingPortionsOfDataByteByByte()
        {
            DataStreamReadableWritable dataStream = TestCollaboratorsFactory.CreateEmptyDataStream();

            var stream       = new MemoryStream();
            var binaryWriter = new BinaryWriter(stream);

            const int numberOfIntegersToTest = 2561;

            for (int i = 0; i < numberOfIntegersToTest; i++)
            {
                binaryWriter.Write(i);
            }

            byte[] bytes = stream.ToArray();

            for (int i = 0; i < bytes.Length; i++)
            {
                dataStream.Write(new byte[] { bytes[i] }, 0, 1);
            }

            dataStream.SetPosition(0);

            var bytesRead = new byte[dataStream.Length];

            dataStream.Read(bytesRead, 0, dataStream.Length);

            var readingStream = new MemoryStream(bytesRead, false);
            var reader        = new BinaryReader(readingStream);

            for (int i = 0; i < numberOfIntegersToTest; i++)
            {
                int number = reader.ReadInt32();

                Assert.AreEqual(i, number);
            }
        }
        public void TryWritingABigFileReadingItAfterSystemReload()
        {
            var testCollaborators = TestCollaboratorsFactory.CreateAllCollaborators(50000, false);

            byte[] interestingBytes = ByteBufferFactory.BuildSomeGuidsIntoByteArray(5000);

            int streamLength;

            const int numberOfGuidPortionsToReadAndWrite = 500;

            using (DataStreamReadableWritable stream = testCollaborators.VirtualFileSystem.CreateAndOpenFileForWriting(@"\hey"))
            {
                for (int i = 0; i < numberOfGuidPortionsToReadAndWrite; i++)
                {
                    stream.Write(interestingBytes, 0, interestingBytes.Length);
                }

                streamLength = stream.Length;
            }

            VirtualFileSystem fileSystemReloaded =
                TestCollaboratorsFactory.CreateFileSystemFromExistingStream(testCollaborators.Stream);

            using (DataStreamReadable stream = fileSystemReloaded.OpenFileForReading(@"\hey"))
            {
                Assert.AreEqual(streamLength, stream.Length);

                var bytesRead = new byte[interestingBytes.Length];

                for (int i = 0; i < numberOfGuidPortionsToReadAndWrite; i++)
                {
                    int numberOfBytesRead = stream.Read(bytesRead, 0, interestingBytes.Length);
                    CollectionAssert.AreEqual(interestingBytes, bytesRead);
                }
            }
        }
        public void TryShrinkingTheStreamAndThenWritingReadingFromIt()
        {
            DataStreamReadableWritable dataStream = TestCollaboratorsFactory.CreateEmptyDataStream();

            const int testArrayLength = 50000;

            dataStream.SetLength(testArrayLength);

            byte[] bytesToWrite = new byte[testArrayLength];

            for (int i = 0; i < bytesToWrite.Length; i++)
            {
                bytesToWrite[i] = (byte)(i / 10000);
            }

            dataStream.Write(bytesToWrite, 0, bytesToWrite.Length);

            ShrinkAndMakeSureDataIsIntact(dataStream, 40000);
            ShrinkAndMakeSureDataIsIntact(dataStream, 34567);
            ShrinkAndMakeSureDataIsIntact(dataStream, 25000);
            ShrinkAndMakeSureDataIsIntact(dataStream, 9999);
            ShrinkAndMakeSureDataIsIntact(dataStream, 24);
            ShrinkAndMakeSureDataIsIntact(dataStream, 1);
        }
Exemplo n.º 11
0
        public void MakeSureYouReadSameStuffFromTwoStreamsLinkingToTheSameFile()
        {
            VirtualFileSystem fileSystem = VirtualFileSystemFactory.CreateDefaultFileSystem();

            FolderInfo folder1Node = fileSystem.CreateFolder(@"\folder1");
            FileInfo   newFile     = fileSystem.CreateFile(@"\folder1\file1");

            var relativelyInterestingData = new List <byte>();

            for (int i = 0; i < 1000; i++)
            {
                relativelyInterestingData.AddRange(Guid.NewGuid().ToByteArray());
            }

            using (DataStreamReadableWritable dataStream = fileSystem.OpenFileForWriting(newFile.FullPath))
            {
                dataStream.Write(relativelyInterestingData.ToArray(), 0, relativelyInterestingData.Count);
            }

            DataStreamReadable dataStream1 = fileSystem.OpenFileForReading(newFile.FullPath);
            DataStreamReadable dataStream2 = fileSystem.OpenFileForReading(newFile.FullPath);

            Exception anyThreadException = null;

            var bytesReadByThreadOne = new List <byte>();

            var thread1 = new Thread(delegate()
            {
                try
                {
                    var buffer = new byte[1];

                    while (dataStream1.Read(buffer, 0, 1) == 1)
                    {
                        bytesReadByThreadOne.Add(buffer[0]);
                    }
                }
                catch (Exception exception)
                {
                    anyThreadException = new InvalidOperationException("", exception);
                }
            });

            var bytesReadByThreadTwo = new List <byte>();

            var thread2 = new Thread(delegate()
            {
                try
                {
                    while (dataStream2.Position != dataStream2.Length)
                    {
                        var buffer = new byte[1];
                        dataStream2.Read(buffer, 0, 1);
                        bytesReadByThreadTwo.Add(buffer[0]);
                    }
                }
                catch (Exception exception)
                {
                    anyThreadException = new InvalidOperationException("Возникло исключение в одном из тестовых потоков. Детали и стэк вызова - в обернутом исключении.", exception);
                }
            });

            thread1.Start();
            thread2.Start();

            thread2.Join();
            thread1.Join();

            if (anyThreadException != null)
            {
                throw anyThreadException;
            }

            CollectionAssert.AreEqual(relativelyInterestingData, bytesReadByThreadOne);
            CollectionAssert.AreEqual(relativelyInterestingData, bytesReadByThreadTwo);
        }