Beispiel #1
0
        public void CorruptFile()
        {
            // Write out some garbage to create a corrupt file
            File.WriteAllText(m_path, "1Cleanasldkjf09234,kns90j23lk4n2309u4");

            FakeFile f1 = CreateFakeFile(R("foo", "bar1.txt"), "bar1.txt");

            // Try to use it
            using (FileCombiner combiner = CreateFileCombiner(m_loggingContext, m_path))
            {
                XAssert.IsNull(combiner.RequestFile(f1.Path, f1.Hash));
                AddFile(combiner, f1);
            }

            // Reload and consume the added file
            using (FileCombiner combiner = CreateFileCombiner(m_loggingContext, m_path))
            {
                using (MemoryStream ms = combiner.RequestFile(f1.Path, f1.Hash))
                {
                    XAssert.IsNotNull(ms);
                }
            }

            AssertWarningEventLogged(EventId.FileCombinerVersionIncremented);
        }
Beispiel #2
0
        public void FileGetsUpdated()
        {
            FakeFile initial = CreateFakeFile(R("foo", "bar1.txt"), "BeginningContent");

            // Create a combiner and add some files
            using (FileCombiner combiner = CreateFileCombiner(m_loggingContext, m_path, 1))
            {
                AddFile(combiner, initial);
            }

            FakeFile updated = CreateFakeFile(R("foo", "bar1.txt"), "UpdatedContent");

            using (FileCombiner combiner = CreateFileCombiner(m_loggingContext, m_path, 1))
            {
                AddFile(combiner, updated);
            }

            using (FileCombiner combiner = CreateFileCombiner(m_loggingContext, m_path, 1))
            {
                using (MemoryStream ms = combiner.RequestFile(initial.Path, initial.Hash))
                {
                    XAssert.IsNull(ms);
                }

                using (MemoryStream ms = combiner.RequestFile(updated.Path, updated.Hash))
                {
                    XAssert.IsNotNull(ms);
                    AssertContentMatches(ms, updated);
                }
            }
        }
Beispiel #3
0
        public void AddTextFile(string path, string content)
        {
            var d = PathUtils.SplitDirAndFile(path, out var ff).ToString();
            var f = ff.ToString();

            if (_content.TryGetValue(new KeyValuePair <string, string>(d, f), out var file))
            {
                if (file == null)
                {
                    throw new Exception("Cannot add file because it is already dir " + path);
                }
                file._lastWriteTimeUtc = DateTime.UtcNow;
                file._content          = content;
                file._length           = (ulong)Encoding.UTF8.GetByteCount(content);
                return;
            }

            CreateDir(d);
            _content[new KeyValuePair <string, string>(d, f)] = new FakeFile
            {
                _content          = content,
                _length           = (ulong)Encoding.UTF8.GetByteCount(content),
                _lastWriteTimeUtc = DateTime.UtcNow
            };
            OnFileChange?.Invoke(path);
        }
Beispiel #4
0
        private FakeFile InternalGetFile(string path, MissingFileStrategy missingFileStrategy)
        {
            var file = _files.FirstOrDefault(x => x.FullName.Equals(path, StringComparison.CurrentCultureIgnoreCase));

            if (file == null)
            {
                switch (missingFileStrategy)
                {
                case MissingFileStrategy.ReturnNull:
                    break;

                case MissingFileStrategy.CreateNew:
                    file = new FakeFile(path, _dateTimeProvider);
                    _files.Add(file);
                    break;

                case MissingFileStrategy.ThrowException:
                    throw new FileNotFoundException();

                default:
                    throw new ArgumentOutOfRangeException(nameof(missingFileStrategy), missingFileStrategy, null);
                }
            }

            return(file);
        }
Beispiel #5
0
        public async Task ProcessFileLogicVid()
        {
            var file = new FakeFile {
                ContentType = "video", FileName = "vid.mp4"
            };

            var data  = new FakeApiDataEntityHandler <VisibleFile>();
            var logic = new CoreApiLogicHandler();
            var cloud = new FakeCloudHandler();

            var command = new ProcessFile
            {
                DataHandler  = data,
                Source       = file,
                CloudHandler = cloud,
                LogicHandler = logic,
                CurrentUser  = StandardUser
            };

            await command.Execute();

            cloud.HasExecuted.Should().BeFalse();
            logic.HasExecuted.Should().BeFalse();

            data.HasExecuted.Should().BeFalse();
            data.HasCommitted.Should().BeFalse();
            logic.Result.Verify(s => s.Execute(It.IsAny <ProcessImage>()), Times.Never());
        }
Beispiel #6
0
        public async Task ProcessFileLogicImgNoTag()
        {
            var file = new FakeFile {
                ContentType = string.Empty
            };

            var data  = new FakeApiDataEntityHandler <VisibleFile>();
            var logic = new CoreApiLogicHandler();
            var cloud = new FakeCloudHandler();

            logic.Result.Setup(m => m.Execute(It.IsAny <ProcessImage>()))
            .Returns(ActionConfirm.CreateSuccess("File Processed"));

            var command = new ProcessFile
            {
                DataHandler  = data,
                Source       = file,
                CloudHandler = cloud,
                LogicHandler = logic,
                CurrentUser  = StandardUser
            };

            await command.Execute();

            cloud.HasExecuted.Should().BeFalse();
            logic.HasExecuted.Should().BeTrue();

            data.HasExecuted.Should().BeFalse();
            data.HasCommitted.Should().BeFalse();
            logic.Result.Verify(s => s.Execute(It.IsAny <ProcessImage>()), Times.Once());
        }
        public void MoveFile(FakeFile fakeFile, FilePath destination)
        {
            // Copy the file to the new location.
            CopyFile(fakeFile, destination, false);

            // Delete the original file.
            fakeFile.Delete();
        }
Beispiel #8
0
        void IFileSystem.DeleteFile(string path)
        {
            VerboseDebugLog($"{nameof(IFileSystem.DeleteFile)}(\"{path}\")");

            FakeFile file = InternalGetFile(path, MissingFileStrategy.ThrowException);

            InternalDeleteFile(file);
        }
        /// <summary>
        /// Initializes a new instance of the <see cref="PaketPusherFixture" /> class.
        /// </summary>
        internal PaketPusherFixture()
            : base("paket.exe")
        {
            FakeFile fakeFile = FileSystem.CreateFile("NuGet/foo.nupkg");

            FilePath      = fakeFile.Path;
            FakeArguments = Substitute.For <ICakeArguments>();
        }
Beispiel #10
0
 static LogUtil_iOS()
 {
     LogFile            = new FakeFile_iOS(FileUtil_iOS.GetPath(FileUtil_iOS.cachePath, "AppLog.log"));
     logStream          = new FileStream(LogFile.path, FileMode.OpenOrCreate);
     logStream.Position = logStream.Length;
     logWriter          = new StreamWriter(logStream);
     TryLog("Init Logger");
 }
        public void UserFeedback_ValidStringReturned()
        {
            FakeFile linkTo   = new FakeFile("linkTo");
            FakeFile linkFrom = new FakeFile("linkFrom");

            ICommand linkFileCommand = new CreateFileLinkCommand(linkTo, linkFrom);

            Assert.IsFalse(String.IsNullOrEmpty(linkFileCommand.UserFeedback));
        }
Beispiel #12
0
        public void CompactFile()
        {
            using (FileCombiner combiner = CreateFileCombiner(m_loggingContext, m_path, 1))
            {
                for (int i = 0; i < 10; i++)
                {
                    FakeFile f = CreateFakeFile(R("foo", "bar") + i, i.ToString());
                    AddFile(combiner, f);
                }
            }

            FileInfo fileInfo      = new FileInfo(m_path);
            long     initialLength = fileInfo.Length;

            // File shouldn't shrink
            using (FileCombiner combiner = CreateFileCombiner(m_loggingContext, m_path, .9))
            {
                for (int i = 0; i < 2; i++)
                {
                    FakeFile f = CreateFakeFile(R("foo", "bar") + i, i.ToString());
                    combiner.RequestFile(f.Path, f.Hash);
                }
            }

            fileInfo = new FileInfo(m_path);
            XAssert.AreEqual(initialLength, fileInfo.Length);

            // File shouldn't shrink since no new content was added. Delay the shrink for a future run.
            using (FileCombiner combiner = CreateFileCombiner(m_loggingContext, m_path, .2))
            {
                combiner.RequestFile(R("foo", "bar1"), null);
                combiner.RequestFile(R("foo", "bar8"), null);
            }

            fileInfo = new FileInfo(m_path);
            XAssert.AreEqual(initialLength, fileInfo.Length);

            // File should shrink
            using (FileCombiner combiner = CreateFileCombiner(m_loggingContext, m_path, .2))
            {
                combiner.RequestFile(R("foo", "bar1"), null);
                combiner.RequestFile(R("foo", "bar8"), null);
                FakeFile f = CreateFakeFile(R("foo", "bar10"), "10");
                AddFile(combiner, f);
            }

            fileInfo = new FileInfo(m_path);
            XAssert.IsTrue(initialLength > fileInfo.Length);

            // Request files from before, inbetween, and after the ones that got removed
            using (FileCombiner combiner = CreateFileCombiner(m_loggingContext, m_path, .2))
            {
                AssertContentMatches(combiner.RequestFile(R("foo", "bar1"), null), "1");
                AssertContentMatches(combiner.RequestFile(R("foo", "bar8"), null), "8");
                AssertContentMatches(combiner.RequestFile(R("foo", "bar10"), null), "10");
            }
        }
        public void Undo_NoExceptionThrown()
        {
            FakeFile linkTo   = new FakeFile("linkTo");
            FakeFile linkFrom = new FakeFile("linkFrom");

            ICommand linkFileCommand = new CreateFileLinkCommand(linkTo, linkFrom);

            Assert.DoesNotThrow(() => linkFileCommand.Undo());
        }
Beispiel #14
0
        public static unsafe SoundEffect Decode(byte *start, byte *end)
        {
            FakeFile file = new FakeFile {
                start = start, position = start, end = end
            };

            int sampleCount = *(int *)file.position; // <- We encoded this, before the packets start, because Vorbis doesn't know [not sure if this is still true for Ogg, haven't checked -AR]

            file.position += 4;
            int loopStart = *(int *)file.position;

            file.position += 4;
            int loopLength = *(int *)file.position;

            file.position += 4;

            // TODO: Consider modifying vorbisfile binding so we can stackalloc `vf`
            IntPtr vf;

            Vorbisfile.ov_open_callbacks((IntPtr)(&file), out vf, IntPtr.Zero, IntPtr.Zero, staticCallbacks);

            Vorbisfile.vorbis_info info = Vorbisfile.ov_info(vf, 0);

            byte[] audioData = new byte[sampleCount * info.channels * 2]; // *2 for 16-bit audio (as required by XNA)

            fixed(byte *writeStart = audioData)
            {
                byte *writePosition = writeStart;
                byte *writeEnd      = writePosition + audioData.Length;

                while (true)
                {
                    int currentSection;
                    int result = (int)Vorbisfile.ov_read(vf, (IntPtr)writePosition, (int)(writeEnd - writePosition), 0, 2, 1, out currentSection);

                    if (result == 0) // End of file
                    {
                        break;
                    }
                    else if (result > 0)
                    {
                        writePosition += result;
                    }
                    if (writePosition >= writeEnd)
                    {
                        break;
                    }
                }

                Debug.Assert(writePosition == writeEnd); // <- If this fires, something went terribly wrong. (TODO: Throw exception?)
            }

            Vorbisfile.ov_clear(ref vf);

            return(new SoundEffect(audioData, 0, audioData.Length, (int)info.rate, (AudioChannels)info.channels, loopStart, loopLength));
        }
        public void Undo_DoesNothing()
        {
            var fileToDelete = new FakeFile("fileToDelete");

            fileToDelete.Attributes = FileAttributes.ReadOnly;

            var deleteCommand = new DeleteFileCommand(fileToDelete);

            Assert.DoesNotThrow(() => deleteCommand.Undo());
        }
Beispiel #16
0
        private void InternalDeleteFile(FakeFile file)
        {
            if (file == null)
            {
                return;
            }

            file.ValidateAccess(FileShare.Delete);
            _files.Remove(file);
        }
Beispiel #17
0
        private void AssertContentMatches(MemoryStream ms, FakeFile info)
        {
            using (StreamReader reader = new StreamReader(ms))
            {
                string read     = reader.ReadToEnd();
                string original = Encoding.UTF8.GetString(info.Content);

                XAssert.AreEqual(original, read);
            }
        }
Beispiel #18
0
        void IFileSystem.ReplaceFile(string sourcePath, string destPath, string destBackupPath)
        {
            VerboseDebugLog($"{nameof(IFileSystem.ReplaceFile)}(\"{sourcePath}\", \"{destPath}\", \"{destBackupPath}\")");

            FakeFile sourceFile = InternalGetFile(sourcePath, MissingFileStrategy.ThrowException);

            this.CopyAsync(destPath, destBackupPath, true).SafeWait();
            this.CopyAsync(sourcePath, destPath, true).SafeWait();
            InternalDeleteFile(sourceFile);
        }
        public void UserFeedback_ReturnsStringWithContent()
        {
            var fileToDelete = new FakeFile("fileToDelete");

            fileToDelete.Attributes = FileAttributes.ReadOnly;

            var deleteCommand = new DeleteFileCommand(fileToDelete);

            Assert.IsFalse(String.IsNullOrEmpty(deleteCommand.UserFeedback));
        }
        public void Execute_FileIsNotReadOnly_FileDeleted()
        {
            var fileToDelete = new FakeFile("fileToDelete");

            fileToDelete.ExistsReturnValue = true;
            var deleteCommand = new DeleteFileCommand(fileToDelete);

            deleteCommand.Execute();

            Assert.IsTrue(fileToDelete.DeleteCalled);
        }
Beispiel #21
0
        public static async void Init()
        {
            LogFile = new FakeFile_UWP(FileUtil_UWP.GetPath(FileUtil_UWP.cacheFolder, "AppLog.log"));
            var file = await StorageFile.GetFileFromPathAsync(LogFile.path);

            logStream = await file.OpenStreamForWriteAsync();

            logStream.Position = logStream.Length;
            logWriter          = new StreamWriter(logStream);
            TryLog("Init Logger");
        }
        public void Execute_ValidPaths_PassedToCommandCorrectly()
        {
            FakeFile linkTo   = new FakeFile("linkTo");
            FakeFile linkFrom = new FakeFile("linkFrom");

            ICommand linkFileCommand = new CreateFileLinkCommand(linkTo, linkFrom);

            linkFileCommand.Execute();

            Assert.AreSame("linkTo", linkFrom.FileLinkCreatedAt);
        }
Beispiel #23
0
        public void CreateAndReloadCombinedFile()
        {
            int maxBackingBufferBytes = 3; // let's make sure we are going to span multiple chunks...

            FakeFile f1 = CreateFakeFile(R("foo", "bar1.txt"), "bar1.txt");
            FakeFile f2 = CreateFakeFile(R("foo", "bar2.txt"), "bar2.txt");
            FakeFile f3 = CreateFakeFile(R("foo", "bar3.txt"), "bar3.txt");

            XAssert.IsTrue(f1.Content.Length > maxBackingBufferBytes * 3);
            XAssert.IsTrue(f2.Content.Length > maxBackingBufferBytes * 3);
            XAssert.IsTrue(f3.Content.Length > maxBackingBufferBytes * 3);

            Logger.FileCombinerStats stats = new Logger.FileCombinerStats();

            // Create a combiner and add some files
            using (FileCombiner combiner = CreateFileCombiner(m_loggingContext, m_path, 1))
            {
                combiner.GetStatsRefForTest(ref stats);
                AddFile(combiner, f3);
                AddFile(combiner, f2);
                AddFile(combiner, f1);
            }

            XAssert.AreEqual(3, stats.EndCount);
            XAssert.AreEqual(0, stats.CompactingTimeMs, "FileCombiner should not have been compacted");

            // Make sure the file is longer than the max backing buffer so we can test data being split across buffers
            FileInfo info = new FileInfo(m_path);

            XAssert.IsTrue(info.Length > maxBackingBufferBytes);

            // reload the combiner
            using (FileCombiner combiner = CreateFileCombiner(m_loggingContext, m_path, 1, maxBackingBufferBytes))
            {
                // fetch a file that exists and verify the correct data is returned
                using (MemoryStream ms = combiner.RequestFile(f1.Path, f1.Hash))
                {
                    XAssert.IsNotNull(ms);
                    AssertContentMatches(ms, f1);
                }

                // Fetch a file with the wrong hash. Make sure no content is returned
                using (MemoryStream ms = combiner.RequestFile(f1.Path, f2.Hash))
                {
                    XAssert.IsNull(ms);
                }

                // Fetch a file that doesn't exist. Make sure no content is returned
                using (MemoryStream ms = combiner.RequestFile(R("foo", "bar4"), f2.Hash))
                {
                    XAssert.IsNull(ms);
                }
            }
        }
Beispiel #24
0
        public void Status_should_return_status_with_both_filenames_in()
        {
            FakeFile sourceFile = new FakeFile("file1");
            FakeFile targetFile = new FakeFile("file2");

            MoveFileCommand testCopyCommand = new MoveFileCommand(sourceFile, targetFile, false);
            String          status          = testCopyCommand.UserFeedback;

            Assert.That(status.Contains("file1"));
            Assert.That(status.Contains("file2"));
        }
Beispiel #25
0
                    public IFile Create(PathPart name)
                    {
                        FakeFile file;

                        if (!this.fakeFiles.TryGetValue(name, out file))
                        {
                            file = new FakeFile(this.root.Combine(name));
                            this.fakeFiles.Add(name, file);
                        }

                        return(file);
                    }
        public void CheckNameOrGetValidFileThatNotExists()
        {
            TestWithShims(() =>
            {
                var fakeFile = new FakeFile();

                ShimFile.ExistsString = s => false;
                var result = SetupClass().CheckNameOrGetValid(fakeFile);

                Assert.AreEqual(fakeFile.FullName, result);
            });
        }
Beispiel #27
0
        private FakeFile CreateFakeFile(string path, string content)
        {
            FakeFile file = default(FakeFile);

            file.Path = path;

            // Make the content have a reasonable size so we can test getting split into multiple buffers when the backing
            // file is read into memory
            file.Content = Encoding.UTF8.GetBytes(Padding + content);
            file.Hash    = ContentHashingUtilities.HashBytes(file.Content);

            return(file);
        }
Beispiel #28
0
        private IFileFactoryForPath GetFileFactoryThatReturnsExistsFor(String fileToReturnTrueFor)
        {
            IFileFactoryForPath fileFactory = (f) =>
            {
                var fileToReturn = new FakeFile(f);

                fileToReturn.ExistsReturnValue = f.Equals(fileToReturnTrueFor);

                return(fileToReturn);
            };

            return(fileFactory);
        }
        public void Execute_FileIsReadOnly_ReadonlyCleared()
        {
            var fileToDelete = new FakeFile("fileToDelete");

            fileToDelete.ExistsReturnValue = true;
            fileToDelete.Attributes        = FileAttributes.ReadOnly;

            var deleteCommand = new DeleteFileCommand(fileToDelete);

            deleteCommand.Execute();

            Assert.AreEqual(FileAttributes.Normal, fileToDelete.Attributes);
        }
        public void Execute_FileDoesNotExist_NoFileDeleteIsCalled()
        {
            var fileToDelete = new FakeFile("fileToDelete");

            fileToDelete.ExistsReturnValue = false;
            fileToDelete.Attributes        = FileAttributes.ReadOnly;

            var deleteCommand = new DeleteFileCommand(fileToDelete);

            deleteCommand.Execute();

            Assert.IsFalse(fileToDelete.DeleteCalled);
        }
Beispiel #31
0
        public void GetCommandListForFileTask_LinkToDoesntExist_CreateLinkOnly()
        {
            FakeFile linkTo   = new FakeFile("LinkTo");
            FakeFile linkFrom = new FakeFile("LinkFrom");

            var commandFactory = MockRepository.GenerateMock <ICommandFactory>();

            var commandDiscovery = new CommandDiscovery(commandFactory, f => new FakeFile(f), f => new FakeFolder(f));
            var commandList      = commandDiscovery.GetCommandListForFileTask(linkTo, linkFrom, false, false);

            Assert.AreEqual(1, commandList.Count);
            commandFactory.AssertWasCalled(cf => cf.CreateFileLinkCommand(Arg <IFile> .Is.Equal(linkTo),
                                                                          Arg <IFile> .Is.Equal(linkFrom)));
        }
        public void CheckNameOrGetValidFile()
        {
            TestWithShims(() =>
            {
                var fakeFile = new FakeFile();

                ShimFile.ExistsString = s =>
                {
                    if (s == "C:\\Test.fake")
                    {
                        return true;
                    }
                    return s == "C:\\Test (1).fake";
                };

                var result = SetupClass().CheckNameOrGetValid(fakeFile);

                Assert.AreEqual("Test (2).fake", result);
            });
        }