public void EnumerateFilesOperation_EnumerateFiles_FilterCaseSensitive_ReturnsNoFiles()
        {
            var mockFileSystem = new MockFileSystem();
            var txFileSystem   = new TxFileSystem(mockFileSystem);

            txFileSystem.Directory.CreateDirectory("/var/dirtoenum/");

            for (var i = 1; i <= 3; i++)
            {
                txFileSystem.File.Create("/var/dirtoenum/file_" + i + ".txt");
                txFileSystem.Directory.CreateDirectory("/var/dirtoenum/subdir_" + i);

                for (var j = 1; j <= 6; j++)
                {
                    txFileSystem.File.Create("/var/dirtoenum/subdir_" + i + "/subfile_" + j + ".txt");
                }
            }

            var files = txFileSystem.Directory.EnumerateFiles("/var/dirtoenum/", "subFile_*",
                                                              new EnumerationOptions()
            {
                MatchCasing = MatchCasing.CaseSensitive
            });

            Assert.Empty(files);
        }
        public void AppendAllLinesOperation_Transactional_ContainsAllLines()
        {
            var mockFileSystem = new MockFileSystem();
            var txFileSystem   = new TxFileSystem(mockFileSystem);

            txFileSystem.Directory.CreateDirectory("/tmp");

            var initialLine = new string[] { "Initial contents" };
            var lines       = new string[] { "line one", "line two", "line three" };

            var textFileStream = txFileSystem.File.CreateText("/tmp/filetoappendto.txt");

            textFileStream.WriteLine(initialLine[0]);
            textFileStream.Flush();
            textFileStream.Close();

            Assert.Equal("Initial contents" + Environment.NewLine,
                         txFileSystem.File.ReadAllText("/tmp/filetoappendto.txt"));

            using (var transactionScope = new TransactionScope())
            {
                txFileSystem = new TxFileSystem(mockFileSystem);
                txFileSystem.File.AppendAllLines("/tmp/filetoappendto.txt", lines.ToList());
                transactionScope.Complete();
            }

            lines = new[] { "Initial contents" }.Concat(lines).ToArray();

            Assert.Equal(lines, txFileSystem.File.ReadAllLines("/tmp/filetoappendto.txt"));
        }
        public void DeleteOperation_Recursive_Delete_ReturnsExistsFalse_ParentExistsFalse()
        {
            TxFileSystem txFileSystem = null;

            void CreateAndDeleteDirectories()
            {
                #region CodeExample_DeleteDirectory_Recursive

                var mockFileSystem = new MockFileSystem();
                using (var transactionScope = new TransactionScope())
                {
                    txFileSystem = new TxFileSystem(mockFileSystem);
                    txFileSystem.Directory.CreateDirectory("/var/tobedeleted");
                    txFileSystem.Directory.Delete("/var", recursive: true);
                    transactionScope.Complete();
                }

                #endregion
            }

            CreateAndDeleteDirectories();

            var txJournal = txFileSystem.Journal;

            Assert.Equal(JournalState.Committed, txJournal.State);
            Assert.False(txJournal.IsRolledBack);
            Assert.False(txFileSystem.Directory.Exists("/var/tobedeleted"));
            Assert.False(txFileSystem.Directory.Exists("/var"));
        }
Пример #4
0
        public void MoveOperation_OverwriteFalse_ThrowsIOException()
        {
            var mockFileSystem = new MockFileSystem();
            var txFileSystem   = new TxFileSystem(mockFileSystem);

            txFileSystem.Directory.CreateDirectory("/tmp");

            var sourceFile = txFileSystem.File.CreateText("/tmp/sourcefile.txt");

            sourceFile.Write("Source file");
            sourceFile.Flush();
            sourceFile.Close();

            var destFile = txFileSystem.File.CreateText("/tmp/destfile.txt");

            destFile.Write("Dest file");
            destFile.Flush();
            destFile.Close();

            Assert.Throws <IOException>(() =>
            {
                using var transactionScope = new TransactionScope();

                txFileSystem = new TxFileSystem(mockFileSystem);
                txFileSystem.File.Move("/tmp/sourcefile.txt", "/tmp/destfile.txt", overwrite: false);

                transactionScope.Complete();
            });

            Assert.True(txFileSystem.File.Exists("/tmp/sourcefile.txt"));
            Assert.Equal("Source file", txFileSystem.File.ReadAllText("/tmp/sourcefile.txt"));

            Assert.True(txFileSystem.File.Exists("/tmp/destfile.txt"));
            Assert.Equal("Dest file", txFileSystem.File.ReadAllText("/tmp/destfile.txt"));
        }
Пример #5
0
        public void MoveOperation_ExceptionThrown_SourceFileAndDestFile_SameAsBefore()
        {
            var mockFileSystem = new MockFileSystem();
            var txFileSystem   = new TxFileSystem(mockFileSystem);

            txFileSystem.Directory.CreateDirectory("/tmp");

            var sourceFile = txFileSystem.File.CreateText("/tmp/sourcefile.txt");

            sourceFile.Write("Source file");
            sourceFile.Flush();
            sourceFile.Close();

            var destFile = txFileSystem.File.CreateText("/tmp/destfile.txt");

            destFile.Write("Dest file");
            destFile.Flush();
            destFile.Close();

            Assert.ThrowsAsync <Exception>(() =>
            {
                using var transactionScope = new TransactionScope();

                var txFileSystem = new TxFileSystem(mockFileSystem);
                txFileSystem.File.Move("/tmp/sourcefile.txt", "/tmp/destfile.txt", overwrite: true);

                throw new Exception("Error occurred right after moving file");
            });

            Assert.True(txFileSystem.File.Exists("/tmp/sourcefile.txt"));
            Assert.Equal("Source file", txFileSystem.File.ReadAllText("/tmp/sourcefile.txt"));

            Assert.True(txFileSystem.File.Exists("/tmp/destfile.txt"));
            Assert.Equal("Dest file", txFileSystem.File.ReadAllText("/tmp/destfile.txt"));
        }
Пример #6
0
        public void CreateTextOperation_ExceptionThrown_NoFileCreated()
        {
            var fileName = "/tmp/generatedfile.txt";

            var mockFileSystem = new MockFileSystem();
            var txFileSystem   = new TxFileSystem(mockFileSystem);

            txFileSystem.Directory.CreateDirectory("/tmp");

            Assert.ThrowsAsync <Exception>(() =>
            {
                using (var transactionScope = new TransactionScope())
                {
                    txFileSystem = new TxFileSystem(mockFileSystem);

                    var streamWriter = txFileSystem.File.CreateText(fileName);
                    streamWriter.Write(GetLoremIpsumText());
                    streamWriter.Flush();
                    streamWriter.Close();

                    throw new Exception("Error right after writing to stream");
                }
            });

            Assert.False(txFileSystem.File.Exists(fileName));
        }
        public void SetAccessControlOperation_ExceptionThrown_AccessControlUnchanged()
        {
            var fileName = "/tmp/filetochangeaccesscontrolof.txt";

            var mockFileSystem = new MockFileSystem();
            var txFileSystem   = new TxFileSystem(mockFileSystem);

            txFileSystem.Directory.CreateDirectory("/tmp");
            txFileSystem.File.Create(fileName);

            var originalAccessControl = txFileSystem.File.GetAccessControl(fileName);
            var modifiedAccessControl = new FileSecurity();

            Assert.ThrowsAsync <Exception>(() =>
            {
                using (var transactionScope = new TransactionScope())
                {
                    txFileSystem = new TxFileSystem(mockFileSystem);
                    txFileSystem.File.SetAccessControl(fileName, modifiedAccessControl);

                    throw new Exception("Error occurred right after changing accesscontrol");
                }
            });

            Assert.NotEqual(modifiedAccessControl, txFileSystem.File.GetAccessControl(fileName));
            Assert.Equal(originalAccessControl, txFileSystem.File.GetAccessControl(fileName));
        }
Пример #8
0
        public void CreateDirectoryOperation_WithDirectorySecurity_ReturnsSameFileAccessRule()
        {
            var fileSystemAccessRule = new FileSystemAccessRule(
                Environment.UserName, FileSystemRights.Read, AccessControlType.Allow);

            var directorySecurity = new DirectorySecurity();

            directorySecurity.AddAccessRule(fileSystemAccessRule);

            var mockFileSystem = new MockFileSystem();
            var txFileSystem   = new TxFileSystem(mockFileSystem);
            var directoryInfo  = txFileSystem.Directory.CreateDirectory("/temp/dirwithaccessrestriction",
                                                                        directorySecurity);
            var authorizationRule = directoryInfo.GetAccessControl()
                                    .GetAccessRules(true, true, typeof(NTAccount))[0] as FileSystemAccessRule;

            Assert.IsType <FileSystemAccessRule>(authorizationRule);
            Assert.True(authorizationRule.FileSystemRights.HasFlag(FileSystemRights.Read));

            var identityUserName = authorizationRule.IdentityReference.Value;

            if (identityUserName.Contains(@"\"))
            {
                var startPos = identityUserName.LastIndexOf(@"\") + 1;
                identityUserName = identityUserName.Substring(startPos, identityUserName.Length - startPos);
            }

            Assert.Equal(Environment.UserName, identityUserName);
        }
Пример #9
0
        public void CreateDirectoryOperation_Fails_ResultsInExists_ReturnsFalse()
        {
            var fileSystemMock = new Mock <IFileSystem>();

            fileSystemMock.Setup(f => f.Directory.CreateDirectory(
                                     It.Is <string>(s => s == "/var/failingdirectory"))
                                 )
            .Throws(new Exception("Failed to create failing directory"));

            TxFileSystem txFileSystem = null;

            Assert.Throws <Exception>(() =>
            {
                using (var transactionScope = new TransactionScope())
                {
                    txFileSystem = new TxFileSystem(fileSystemMock.Object);
                    txFileSystem.Directory.CreateDirectory("/var/www");
                    txFileSystem.Directory.CreateDirectory("/var/failingdirectory");
                    transactionScope.Complete();
                }
            });

            Assert.True(txFileSystem.Journal.IsRolledBack);
            Assert.False(txFileSystem.Directory.Exists("/var/www"));
            Assert.False(txFileSystem.Directory.Exists("/var/failingdirectory"));
        }
Пример #10
0
        public void GetDirectoriesOperation_TopDirs_ReturnsThreeDirNames()
        {
            var mockFileSystem = new MockFileSystem();
            var txFileSystem   = new TxFileSystem(mockFileSystem);

            txFileSystem.Directory.CreateDirectory("/var/dirsdir");

            for (var i = 1; i <= 3; i++)
            {
                txFileSystem.File.Create("/var/dirsdir/file_" + i + ".txt");
                txFileSystem.Directory.CreateDirectory("/var/dirsdir/subdir_" + i);

                for (var j = 1; j <= 6; j++)
                {
                    txFileSystem.Directory.CreateDirectory("/var/dirsdir/subdir_" + i + "/subsubdir_" + j);
                    txFileSystem.File.Create("/var/dirsdir/subdir_" + i + "/subfile_" + j + ".txt");
                }
            }

            var directories = txFileSystem.Directory.GetDirectories("/var/dirsdir",
                                                                    "*", System.IO.SearchOption.TopDirectoryOnly);

            Assert.NotEmpty(directories);
            Assert.True(directories.Count() == 3);
        }
        public void TxFileSystem_FileSystemPassed_Path_FileSystem_ReturnsParentTxFileSystem()
        {
            var txFileSystem = new TxFileSystem(new FileSystem());

            Assert.IsType <TxFileSystem>(txFileSystem.Path.FileSystem);
            Assert.Equal(txFileSystem, txFileSystem.Path.FileSystem);
        }
Пример #12
0
        public void GetDirectoriesOperation_FilterTwo_ReturnsOneDirName()
        {
            var mockFileSystem = new MockFileSystem();
            var txFileSystem   = new TxFileSystem(mockFileSystem);

            txFileSystem.Directory.CreateDirectory("/var/dirsdir");

            for (var i = 1; i <= 3; i++)
            {
                txFileSystem.File.Create("/var/dirsdir/file_" + i + ".txt");
                txFileSystem.Directory.CreateDirectory("/var/dirsdir/subdir_" + i);

                for (var j = 1; j <= 6; j++)
                {
                    txFileSystem.Directory.CreateDirectory("/var/dirsdir/subdir_" + i + "/subsubdir_" + j);
                    txFileSystem.File.Create("/var/dirsdir/subdir_" + i + "/subfile_" + j + ".txt");
                }
            }

            var directories = txFileSystem.Directory.GetDirectories("/var/dirsdir",
                                                                    "*_2");

            Assert.NotEmpty(directories);
            Assert.True(directories.Count() == 1);
        }
        public void DirectoryBackupOperation_Backup_BackupPath_SubDirectoriesExist()
        {
            var mockFileSystem = new MockFileSystem();

            TxFileSystem txFileSystem = null;

            using (var transactionScope = new TransactionScope())
            {
                txFileSystem = new TxFileSystem(mockFileSystem);
                txFileSystem.Directory.CreateDirectory("/tmp/directorytobackupped");
                for (var i = 1; i <= 3; i++)
                {
                    txFileSystem.Directory.CreateDirectory("/tmp/directorytobackupped/subdir_" + i.ToString());
                }

                var unitTestOperation = new UnitTestDirectoryOperation(txFileSystem.Directory,
                                                                       "/tmp/directorytobackupped");
                unitTestOperation.Backup();

                var directories = txFileSystem.Directory.EnumerateDirectories(unitTestOperation.BackupPath);

                Assert.NotEmpty(directories);
                Assert.Equal(3, directories.Count());
            }
        }
        public void EnumerateFilesOperation_EnumerateFiles_FilterPlusRecurseSubdirectories_ReturnsThreeFiles()
        {
            var mockFileSystem = new MockFileSystem();
            var txFileSystem   = new TxFileSystem(mockFileSystem);

            txFileSystem.Directory.CreateDirectory("/var/dirtoenum/");

            for (var i = 1; i <= 3; i++)
            {
                txFileSystem.File.Create("/var/dirtoenum/file_" + i + ".txt");
                txFileSystem.Directory.CreateDirectory("/var/dirtoenum/subdir_" + i);

                for (var j = 1; j <= 6; j++)
                {
                    txFileSystem.File.Create("/var/dirtoenum/subdir_" + i + "/subfile_" + j + ".txt");
                }
            }

            var files = txFileSystem.Directory.EnumerateFiles("/var/dirtoenum/", "*",
                                                              new EnumerationOptions()
            {
                RecurseSubdirectories = false
            });

            Assert.NotEmpty(files);
            Assert.True(files.Count() == 3);
        }
Пример #15
0
        public void TxDriveInfo_GetDrives_CalledOnce_ReturnsDriveInfoArray()
        {
            var attr = (FsFactAttribute)Attribute.GetCustomAttribute(MethodBase.GetCurrentMethod(),
                                                                     typeof(FsFactAttribute));
            var fileSystemMock = attr.GetMock <IFileSystem>();

            var drives = new string[] { @"C:\", @"D:\", @"E:\" };

            var cDriveInfoMock = new Mock <IDriveInfo>();

            cDriveInfoMock.SetupGet(d => d.VolumeLabel)
            .Returns(drives[0]);
            var dDriveInfoMock = new Mock <IDriveInfo>();

            dDriveInfoMock.SetupGet(d => d.VolumeLabel)
            .Returns(drives[1]);
            var eDriveInfoMock = new Mock <IDriveInfo>();

            eDriveInfoMock.SetupGet(d => d.VolumeLabel)
            .Returns(drives[2]);

            var drivesInfos = new IDriveInfo[] { cDriveInfoMock.Object, dDriveInfoMock.Object, eDriveInfoMock.Object };

            fileSystemMock.Setup(f => f.DriveInfo.GetDrives())
            .Returns(drivesInfos);

            var txFileSystem       = new TxFileSystem(fileSystemMock.Object);
            var driveInfosReturned = txFileSystem.DriveInfo.GetDrives();

            fileSystemMock.Verify(f => f.DriveInfo.GetDrives(), Times.Once);

            Assert.IsAssignableFrom <IDriveInfo[]>(driveInfosReturned);
            Assert.Equal(drivesInfos, driveInfosReturned);
        }
Пример #16
0
        public void CreateDirectoryOperation_ResultsInExists_ReturnsTrue()
        {
            TxFileSystem txFileSystem = null;

            void CreateDirectories()
            {
                #region CodeExample_CreateDirectory

                var mockFileSystem = new MockFileSystem();
                using (var transactionScope = new TransactionScope())
                {
                    txFileSystem = new TxFileSystem(mockFileSystem);
                    txFileSystem.Directory.CreateDirectory("/var/www");
                    txFileSystem.Directory.CreateDirectory("/var/nonfailingdirectory");
                    transactionScope.Complete();
                }

                #endregion
            }

            CreateDirectories();

            var txJournal = txFileSystem.Journal;

            Assert.Equal(JournalState.Committed, txJournal.State);
            Assert.False(txJournal.IsRolledBack);
            Assert.True(txFileSystem.Directory.Exists("/var/www"));
            Assert.True(txFileSystem.Directory.Exists("/var/nonfailingdirectory"));
        }
        public void ReadLinesOperation_CalledOnce_ReturnsLines()
        {
            var attr = (FsFactAttribute)Attribute.GetCustomAttribute(MethodBase.GetCurrentMethod(),
                                                                     typeof(FsFactAttribute));
            var fileSystemMock = attr.GetMock <IFileSystem>();

            var fileName = "/tmp/filetoreadlinesfrom.txt";
            var encoding = Encoding.UTF8;
            var lines    = new string[] { "Line one", "Line two", "Line three" };

            fileSystemMock.Setup(fs => fs.File.ReadLines(It.Is <string>((s) => s == fileName),
                                                         It.Is <Encoding>((e) => e == encoding)))
            .Returns(lines);

            using (var transactionScope = new TransactionScope())
            {
                var txFileSystem  = new TxFileSystem(fileSystemMock.Object);
                var linesReturned = txFileSystem.File.ReadLines(fileName, encoding);

                transactionScope.Complete();

                fileSystemMock.Verify(fs => fs.File.ReadLines(It.Is <string>((s) => s == fileName),
                                                              It.Is <Encoding>((e) => e == encoding)), Times.Once);

                Assert.IsAssignableFrom <IEnumerable <string> >(linesReturned);
                Assert.Equal(lines, linesReturned);
            }
        }
        public void ExistsOperation_ReturnsFalse()
        {
            var mockFileSystem = new MockFileSystem();
            var txFileSystem   = new TxFileSystem(mockFileSystem);

            Assert.False(txFileSystem.Directory.Exists("/var/nonexistant"));
        }
        public void CreateFromFileHandleOperation_OwnsHandle_CalledOnce()
        {
            if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
            {
                var attr = (FsFactAttribute)Attribute.GetCustomAttribute(MethodBase.GetCurrentMethod(),
                                                                         typeof(FsFactAttribute));
                var fileSystemMock = attr.GetMock <IFileSystem>();
                var txFileSystem   = new TxFileSystem(fileSystemMock.Object);

                string fileName   = UnitTestUtils.GetTempFileName(txFileSystem);
                var    fileAccess = FileAccess.ReadWrite;
                var    filePtr    = NativeMethods.CreateFile(fileName, fileAccess, FileShare.ReadWrite, IntPtr.Zero,
                                                             FileMode.OpenOrCreate, FileAttributes.Normal, IntPtr.Zero);
                var ownsHandle = false;

                var fileStreamMock = new Mock <FileStream>(MockBehavior.Loose, filePtr, fileAccess, ownsHandle);

                fileSystemMock.Setup(f => f.FileStream.Create(It.Is <IntPtr>((p) => p == filePtr),
                                                              It.Is <FileAccess>((a) => a == fileAccess), It.Is <bool>((o) => o == ownsHandle)))
                .Returns(fileStreamMock.Object);

                var fileStreamReturned = txFileSystem.FileStream.Create(filePtr, fileAccess, ownsHandle);

                fileSystemMock.Verify(f => f.FileStream.Create(It.Is <IntPtr>((p) => p == filePtr),
                                                               It.Is <FileAccess>((a) => a == fileAccess), It.Is <bool>((o) => o == ownsHandle)), Times.Once);

                Assert.Equal(fileStreamMock.Object, fileStreamReturned);

                NativeMethods.CloseHandle(filePtr);

                new FileSystem().File.Delete(fileName);
            }
        }
        public void ReadAllTextOperationAsync_CalledOnce_ReturnsSameStringTask()
        {
            var attr = (FsFactAttribute)Attribute.GetCustomAttribute(MethodBase.GetCurrentMethod(),
                                                                     typeof(FsFactAttribute));
            var fileSystemMock = attr.GetMock <IFileSystem>();

            var fileName = "/tmp/textfile.txt";
            var lines    = new string[] { "Line one", "Line two", "Line three" };
            var text     = string.Join(Environment.NewLine, lines);
            var task     = Task.FromResult(text);

            fileSystemMock.Setup(f => f.File.ReadAllTextAsync(It.Is <string>((s) => s == fileName),
                                                              It.IsAny <CancellationToken>()))
            .Returns(task);

            var cancellationTokenSource = new CancellationTokenSource();

            var txFileSystem = new TxFileSystem(fileSystemMock.Object);
            var taskReturned = txFileSystem.File.ReadAllTextAsync(fileName, cancellationTokenSource.Token);

            fileSystemMock.Verify(f => f.File.ReadAllTextAsync(It.Is <string>((s) => s == fileName),
                                                               It.IsAny <CancellationToken>()), Times.Once);

            Assert.IsAssignableFrom <Task <string> >(taskReturned);
            Assert.Equal(task, taskReturned);
        }
        public void SetLastAccessTimeOperation_ExceptionThrown_ResultsTimeNotChanged()
        {
            var fileName = "/tmp/filetochangeaccesstimeof.txt";

            var mockFileSystem = new MockFileSystem();
            var txFileSystem   = new TxFileSystem(mockFileSystem);

            txFileSystem.Directory.CreateDirectory("/tmp");
            txFileSystem.File.Create(fileName);
            var originalAccessTime = txFileSystem.File.GetLastAccessTime(fileName);
            var modifiedAccessTime = DateTime.Now.AddDays(-7);

            Assert.ThrowsAsync <Exception>(() =>
            {
                using (var transactionScope = new TransactionScope())
                {
                    txFileSystem = new TxFileSystem(mockFileSystem);

                    txFileSystem.File.SetLastAccessTime(fileName, modifiedAccessTime);

                    throw new Exception("Exception occurred right after modifying write time");
                }
            });

            Assert.Equal(originalAccessTime, txFileSystem.File.GetLastAccessTime(fileName));
            Assert.NotEqual(modifiedAccessTime, txFileSystem.File.GetLastAccessTime(fileName));
        }
Пример #22
0
        public void SetCreationTimeOperation_CreationTimeChanged()
        {
            #region CodeExample_Directory_SetCreationTime_Changed

            var dirName = "/tmp/dirtochangecreationtimeof";

            var mockFileSystem = new MockFileSystem();
            var txFileSystem   = new TxFileSystem(mockFileSystem);
            txFileSystem.Directory.CreateDirectory(dirName);

            var originalCreationTime = txFileSystem.Directory.GetCreationTime(dirName);
            var modifiedCreationTime = originalCreationTime.AddDays(-7);

            using (var transactionScope = new TransactionScope())
            {
                txFileSystem = new TxFileSystem(mockFileSystem);
                txFileSystem.Directory.SetCreationTime(dirName, modifiedCreationTime);

                transactionScope.Complete();

                Assert.Equal(modifiedCreationTime, txFileSystem.Directory.GetCreationTime(dirName));
            }

            #endregion
        }
Пример #23
0
        public void MoveOperation_ExceptionThrown_SourceFile_RestoredProperly()
        {
            var mockFileSystem = new MockFileSystem();
            var txFileSystem   = new TxFileSystem(mockFileSystem);

            txFileSystem.Directory.CreateDirectory("/tmp");

            var textStream = txFileSystem.File.CreateText("/tmp/sourcefile.txt");

            textStream.Write("Source file contents");
            textStream.Flush();
            textStream.Close();

            Assert.ThrowsAsync <Exception>(() =>
            {
                using (var transactionScope = new TransactionScope())
                {
                    txFileSystem = new TxFileSystem(mockFileSystem);
                    txFileSystem.File.Move("/tmp/sourcefile.txt", "/tmp/destfile.txt");

                    throw new Exception("Error occurred right after moving file");
                }
            });

            Assert.True(txFileSystem.File.Exists("/tmp/sourcefile.txt"));
            Assert.Equal("Source file contents", txFileSystem.File.ReadAllText("/tmp/sourcefile.txt"));
        }
Пример #24
0
        public void SetCreationTimeOperation_ExceptionThrown_CreationTimeUnchanged()
        {
            #region CodeExample_Directory_SetCreationTime_Unchanged

            var dirName = "/tmp/dirtochangecreationtimeof";

            var mockFileSystem = new MockFileSystem();
            var txFileSystem   = new TxFileSystem(mockFileSystem);
            txFileSystem.Directory.CreateDirectory(dirName);

            var originalCreationTime = txFileSystem.Directory.GetCreationTime(dirName);
            var modifiedCreationTime = originalCreationTime.AddDays(-7);

            Assert.ThrowsAsync <Exception>(() =>
            {
                using (var transactionScope = new TransactionScope())
                {
                    txFileSystem = new TxFileSystem(mockFileSystem);
                    txFileSystem.Directory.SetCreationTime(dirName, modifiedCreationTime);

                    throw new Exception("Error occurred right after changing creation time");
                }
            });

            Assert.NotEqual(modifiedCreationTime, txFileSystem.Directory.GetCreationTime(dirName));
            Assert.Equal(originalCreationTime, txFileSystem.Directory.GetCreationTime(dirName));

            #endregion
        }
        public void AppendAllLinesOperation_ThrownException_ContainsInitiallyWrittenLines()
        {
            var mockFileSystem = new MockFileSystem();
            var txFileSystem   = new TxFileSystem(mockFileSystem);

            txFileSystem.Directory.CreateDirectory("/tmp");

            var initialLine = new string[] { "Initial contents" };
            var lines       = new string[] { "line one", "line two", "line three" };

            var textFileStream = txFileSystem.File.CreateText("/tmp/filetoappendto.txt");

            textFileStream.WriteLine(initialLine[0]);
            textFileStream.Flush();
            textFileStream.Close();

            Assert.Equal("Initial contents" + Environment.NewLine,
                         txFileSystem.File.ReadAllText("/tmp/filetoappendto.txt"));

            Assert.ThrowsAsync <Exception>(() =>
            {
                using (var transactionScope = new TransactionScope())
                {
                    txFileSystem = new TxFileSystem(mockFileSystem);
                    txFileSystem.File.AppendAllLines("/tmp/filetoappendto.txt", lines.ToList());

                    throw new Exception("Error occurred right after appending lines");
                }
            });

            Assert.True(txFileSystem.Journal.IsRolledBack);
            Assert.Equal(initialLine, txFileSystem.File.ReadAllLines("/tmp/filetoappendto.txt"));
        }
        public void EnumerateFileSystemEntriesOperation_RecurseSubDirs_ReturnsTwentyFourEntries()
        {
            var mockFileSystem = new MockFileSystem();
            var txFileSystem   = new TxFileSystem(mockFileSystem);

            txFileSystem.Directory.CreateDirectory("/var/filesysentriesdir");

            for (var i = 1; i <= 3; i++)
            {
                txFileSystem.File.Create("/var/filesysentriesdir/file_" + i + ".txt");
                txFileSystem.Directory.CreateDirectory("/var/filesysentriesdir/subdir_" + i);

                for (var j = 1; j <= 6; j++)
                {
                    txFileSystem.File.Create("/var/filesysentriesdir/subdir_" + i + "/subfile_" + j + ".txt");
                }
            }

            var entries = txFileSystem.Directory.EnumerateFileSystemEntries("/var/filesysentriesdir",
                                                                            "*", new EnumerationOptions()
            {
                RecurseSubdirectories = true
            });

            Assert.NotEmpty(entries);
            Assert.True(entries.Count() == 24);
        }
Пример #27
0
        public static string GetTempFileName(TxFileSystem txFileSystem)
        {
            var tempPath = txFileSystem.Path.GetTempPath();
            var fileName = tempPath + "filetocreatefilestreamfor-" + Guid.NewGuid().ToString() + ".txt";

            return(fileName);
        }
Пример #28
0
        public void TxDriveInfo_FromDriveName_CalledOnce_ReturnsDriveInfo()
        {
            var attr = (FsFactAttribute)Attribute.GetCustomAttribute(MethodBase.GetCurrentMethod(),
                                                                     typeof(FsFactAttribute));
            var fileSystemMock = attr.GetMock <IFileSystem>();

            var driveName  = @"C:\";
            var driveLabel = "MOCK_DRIVE";

            var driveInfoMock = new Mock <IDriveInfo>();

            driveInfoMock.SetupGet(d => d.VolumeLabel)
            .Returns(driveLabel);

            fileSystemMock.Setup(f => f.DriveInfo.FromDriveName(It.Is <string>((s) => s == driveName)))
            .Returns(driveInfoMock.Object);

            var txFileSystem      = new TxFileSystem(fileSystemMock.Object);
            var driveInfoReturned = txFileSystem.DriveInfo.FromDriveName(driveName);

            fileSystemMock.Verify(f => f.DriveInfo.FromDriveName(It.Is <string>((s) => s == driveName)),
                                  Times.Once);

            Assert.IsAssignableFrom <IDriveInfo>(driveInfoReturned);
            Assert.Equal(driveLabel, driveInfoReturned.VolumeLabel);
        }
Пример #29
0
        public void ReadAllLinesOperationAsync_Encoding_CalledOnce_ReturnsStringArrayTask()
        {
            var attr = (FsFactAttribute)Attribute.GetCustomAttribute(MethodBase.GetCurrentMethod(),
                                                                     typeof(FsFactAttribute));
            var fileSystemMock = attr.GetMock <IFileSystem>();

            var fileName = "/tmp/textfile.txt";
            var lines    = new string[] { "Line one", "Line two", "Line three" };
            var task     = Task.FromResult(lines);

            fileSystemMock.Setup(f => f.File.ReadAllLinesAsync(It.Is <string>((s) => s == fileName),
                                                               It.Is <Encoding>((e) => e == Encoding.UTF8), It.IsAny <CancellationToken>()))
            .Returns(task);

            var cancellationTokenSource = new CancellationTokenSource();

            var txFileSystem = new TxFileSystem(fileSystemMock.Object);
            var taskReturned = txFileSystem.File.ReadAllLinesAsync(fileName, Encoding.UTF8, cancellationTokenSource.Token);

            fileSystemMock.Verify(f => f.File.ReadAllLinesAsync(It.Is <string>((s) => s == fileName),
                                                                It.Is <Encoding>((e) => e == Encoding.UTF8), It.IsAny <CancellationToken>()), Times.Once);

            Assert.IsType <Task <string[]> >(taskReturned);
            Assert.NotEmpty(taskReturned.Result);
            Assert.Equal(task, taskReturned);
        }
        public void ReplaceOperation_ProperlyExecuted()
        {
            var mockFileSystem = new MockFileSystem();
            var txFileSystem   = new TxFileSystem(mockFileSystem);

            using (var transactionScope = new TransactionScope())
            {
                txFileSystem.Directory.CreateDirectory("/tmp");

                var sourceTextStream = txFileSystem.File.CreateText("/tmp/sourcefile.txt");
                sourceTextStream.Write("Source file contents");
                sourceTextStream.Flush();
                sourceTextStream.Close();

                var destTextStream = txFileSystem.File.CreateText("/tmp/destfile.txt");
                destTextStream.Write("Dest file contents");
                destTextStream.Flush();
                destTextStream.Close();

                txFileSystem.File.Replace("/tmp/sourcefile.txt", "/tmp/destfile.txt", "/tmp/destbackupfile.txt");

                transactionScope.Complete();
            }

            Assert.False(txFileSystem.File.Exists("/tmp/sourcefile.txt"));
            Assert.True(txFileSystem.File.Exists("/tmp/destfile.txt"));
            Assert.True(txFileSystem.File.Exists("/tmp/destbackupfile.txt"));
            Assert.Equal("Source file contents", txFileSystem.File.ReadAllText("/tmp/destfile.txt"));
            Assert.Equal("Dest file contents", txFileSystem.File.ReadAllText("/tmp/destbackupfile.txt"));
        }