Exemplo n.º 1
0
        public void CreateRowViewModel()
        {
            const string file1Name = "File1";
            const string file2Name = "File2";

            using (var leftDirectory = new Infrastructure.TestDirectory())
                using (var rightDirectory = new Infrastructure.TestDirectory())
                {
                    leftDirectory.CreateFiles(new Dictionary <string, DateTime>
                    {
                        { file1Name, DateTime.Now },
                        { file2Name, DateTime.Now }
                    });
                    rightDirectory.CreateFiles(new Dictionary <string, DateTime>
                    {
                        { file1Name, DateTime.Now },
                        { file2Name, DateTime.Now }
                    });
                    bool useAddRowEvent = false;

                    var synchronizedDirectories = GetSynchronizedDirectories(leftDirectory.FullPath, rightDirectory.FullPath);
                    var factory = new RowViewModelFactory();
                    factory.AddRowEvent += (IRowViewModel parent, IRowViewModel child) => { useAddRowEvent = true; };
                    var rowViewModel = factory.CreateRowViewModel(synchronizedDirectories);

                    // Пока не выполнялась загрузка, события добавления записи происходить не должны.
                    Assert.False(useAddRowEvent);

                    Assert.Empty(rowViewModel.ChildRows);
                }
        }
Exemplo n.º 2
0
        public async Task DeleteDirectoryRowEvent()
        {
            IRowViewModel deleteRowEventParent = null, deleteRowEventChild = null;

            using (var testDirectory = new Infrastructure.TestDirectory())
            {
                Infrastructure.TestDirectory.CreateFiles(testDirectory.CreateDirectory("Dir"), new Dictionary <string, DateTime>
                {
                    { "File", DateTime.Now }
                });

                var synchronizedDirectories = new TestSynchronizedItems(new Directory(testDirectory.FullPath, null, new ItemFactory()));
                var factory = new RowViewModelFactory();
                factory.DeleteRowEvent += (IRowViewModel parent, IRowViewModel child) =>
                {
                    deleteRowEventParent = parent;
                    deleteRowEventChild  = child;
                };

                var rowViewModel = factory.CreateRowViewModel(synchronizedDirectories);

                await synchronizedDirectories.Load();

                var level1Child = synchronizedDirectories.ChildItems[0];
                var level2Child = level1Child.ChildItems[0];

                ((TestSynchronizedItems)level1Child).IsDeleted();

                Assert.NotNull(deleteRowEventParent);
                Assert.NotNull(deleteRowEventChild);
                Assert.Equal(synchronizedDirectories.LeftItem.Name, deleteRowEventParent.LeftItem.Name);
                Assert.Equal(level1Child.LeftItem.Name, deleteRowEventChild.LeftItem.Name);
            }
        }
        public async void LoadChildItems_RefreshStatusAndCommandsFromChilds()
        {
            const string dir1Name   = "Dir1";
            const string dir2Name   = "Dir2";
            const string file1Name  = "File1";
            const string file2Name  = "File2";
            const string file3Name  = "File3";
            var          updateDate = DateTime.Now;

            using (var leftDirectory = new Infrastructure.TestDirectory())
                using (var rightDirectory = new Infrastructure.TestDirectory())
                {
                    Infrastructure.TestDirectory.CreateFiles(leftDirectory.CreateDirectory(dir1Name),
                                                             new Dictionary <string, DateTime> {
                        { file1Name, updateDate }
                    });
                    Infrastructure.TestDirectory.CreateFiles(leftDirectory.CreateDirectory(dir2Name),
                                                             new Dictionary <string, DateTime> {
                        { file2Name, updateDate }, { file3Name, updateDate }
                    });

                    Infrastructure.TestDirectory.CreateFiles(rightDirectory.CreateDirectory(dir1Name),
                                                             new Dictionary <string, DateTime> {
                        { file1Name, updateDate }
                    });
                    Infrastructure.TestDirectory.CreateFiles(rightDirectory.CreateDirectory(dir2Name),
                                                             new Dictionary <string, DateTime> {
                        { file2Name, updateDate }, { file3Name, updateDate }
                    });

                    var settingsRow = new TestSettingsRow
                    {
                        LeftDirectory  = new SettingsDirectory(leftDirectory.FullPath),
                        RightDirectory = new SettingsDirectory(rightDirectory.FullPath)
                    };

                    var testSynchronizedItemsStatusAndCommandsUpdater = new TestSynchronizedItemsStatusAndCommandsUpdater();
                    var synchronizedItems = new SynchronizedItems(settingsRow, new SynchronizedItemFactory(new ItemFactory()),
                                                                  testSynchronizedItemsStatusAndCommandsUpdater);

                    await Task.WhenAll(synchronizedItems.LeftDirectory.Load(), synchronizedItems.RightDirectory.Load());

                    synchronizedItems.LoadChildItems();

                    var refreshedLeftItemSynchronizedItemsList  = testSynchronizedItemsStatusAndCommandsUpdater.RefreshedLeftItemSynchronizedItemsList;
                    var refreshedRightItemSynchronizedItemsList = testSynchronizedItemsStatusAndCommandsUpdater.RefreshedRightItemSynchronizedItemsList;

                    // Каждая директория должна была обновить свои статусы и команды.
                    Assert.Equal(3, refreshedLeftItemSynchronizedItemsList.Count);
                    Assert.Equal(3, refreshedRightItemSynchronizedItemsList.Count);

                    // В таком порядке должны были обновляться статусы элементов.
                    Assert.Equal(refreshedLeftItemSynchronizedItemsList[0], synchronizedItems.ChildItems[0]);
                    Assert.Equal(refreshedLeftItemSynchronizedItemsList[1], synchronizedItems.ChildItems[1]);
                    Assert.Equal(refreshedLeftItemSynchronizedItemsList[2], synchronizedItems);
                    Assert.Equal(refreshedRightItemSynchronizedItemsList[0], synchronizedItems.ChildItems[0]);
                    Assert.Equal(refreshedRightItemSynchronizedItemsList[1], synchronizedItems.ChildItems[1]);
                    Assert.Equal(refreshedRightItemSynchronizedItemsList[2], synchronizedItems);
                }
        }
Exemplo n.º 4
0
        public void CopyTo()
        {
            using (var testDirectory = new Infrastructure.TestDirectory())
            {
                var sourceFile      = Path.Combine(testDirectory.FullPath, Guid.NewGuid().ToString());
                var destinationFile = Path.Combine(testDirectory.FullPath, Guid.NewGuid().ToString());
                var fileText        = Guid.NewGuid().ToString();

                File.WriteAllText(sourceFile, fileText);

                IItem  destinationCopyFile = null;
                string destinationCopyPath = null;

                var file = new DirectorySync.Models.File(sourceFile);
                file.CopiedFromToEvent += (IItem destinationItem, string destinationPath) =>
                {
                    destinationCopyFile = destinationItem;
                    destinationCopyPath = destinationPath;
                };
                file.CopyTo(destinationFile).Wait();

                Assert.True(File.Exists(sourceFile));
                Assert.True(File.Exists(destinationFile));
                Assert.Equal(fileText, File.ReadAllText(destinationFile));
                Assert.NotNull(destinationCopyFile);
                Assert.Equal(destinationFile, destinationCopyFile.FullPath);
                Assert.Equal(destinationFile, destinationCopyPath);
            }
        }
        public async Task RemoveEmptySynchronizedDirectoriesAfterDeleteItem()
        {
            const string directoryName = "Dir1";

            using (var leftDirectory = new Infrastructure.TestDirectory())
                using (var rightDirectory = new Infrastructure.TestDirectory())
                {
                    Infrastructure.TestDirectory.CreateDirectory(leftDirectory.CreateDirectory(directoryName), directoryName);
                    Infrastructure.TestDirectory.CreateFiles(
                        Infrastructure.TestDirectory.CreateDirectory(rightDirectory.CreateDirectory(directoryName), directoryName),
                        new Dictionary <string, DateTime> {
                        { "File1", DateTime.Now }
                    });

                    var synchronizedDirectories = GetSynchronizedDirectories(leftDirectory.FullPath, rightDirectory.FullPath);
                    await synchronizedDirectories.Load();

                    await synchronizedDirectories.LeftItem.SyncCommand.Process(); // Эта команда должна выполнить удаление файла справа.

                    // Корневые элементы должны по прежнему остваться директориями.
                    Assert.NotNull(synchronizedDirectories.LeftDirectory);
                    Assert.NotNull(synchronizedDirectories.RightDirectory);

                    await Task.Delay(20); // Подождём, чтобы успела обновиться коллекция дочерних элементов.

                    // Но синхронизируемых элементов в них быть не должно, так как никаких файлов не осталось.
                    Assert.Empty(synchronizedDirectories.ChildItems);
                }
        }
        public async Task SynchronizedDirectoriesAfterDeleteItem_ThroughRightChild(string childItemName)
        {
            const string directoryName  = "Dir1";
            const string fileName       = "File1";
            var          fileUpdateDate = DateTime.Now;

            using (var leftDirectory = new Infrastructure.TestDirectory())
                using (var rightDirectory = new Infrastructure.TestDirectory())
                {
                    Infrastructure.TestDirectory.CreateFiles(leftDirectory.CreateDirectory(directoryName),
                                                             new Dictionary <string, DateTime> {
                        { fileName, fileUpdateDate }, { "File2", fileUpdateDate }
                    });
                    Infrastructure.TestDirectory.CreateFiles(rightDirectory.CreateDirectory(directoryName),
                                                             new Dictionary <string, DateTime> {
                        { fileName, fileUpdateDate }
                    });

                    var synchronizedDirectories = GetSynchronizedDirectories(leftDirectory.FullPath, rightDirectory.FullPath);
                    await synchronizedDirectories.Load();

                    // Эта команда должна выполнить удаление файла "File2" слева.
                    await GetChildItemByName(synchronizedDirectories, false, childItemName).SyncCommand.Process();

                    // По прежнему должна остваться одна дочерняя запись на директории.
                    Assert.Single(synchronizedDirectories.ChildItems);

                    await Task.Delay(20); // Чтобы успели обновиться статусы и команды.

                    // Дочерние элементы теперь должны быть идентичные и команды синхронизации им не нужны.
                    var childItem = synchronizedDirectories.ChildItems[0];
                    Assert.Equal(ItemStatusEnum.Equally, childItem.LeftItem.Status.StatusEnum);
                    Assert.Equal(ItemStatusEnum.Equally, childItem.RightItem.Status.StatusEnum);
                    Assert.Null(childItem.LeftItem.SyncCommand.CommandAction);
                    Assert.Null(childItem.RightItem.SyncCommand.CommandAction);

                    // И в ней одна запись на оставшуюся пару файлов.
                    Assert.Single(childItem.ChildItems);

                    // Эти тоже теперь должны быть идентичные и команды синхронизации им не нужны.
                    childItem = childItem.ChildItems[0];
                    Assert.Equal(ItemStatusEnum.Equally, childItem.LeftItem.Status.StatusEnum);
                    Assert.Equal(ItemStatusEnum.Equally, childItem.RightItem.Status.StatusEnum);
                    Assert.Null(childItem.LeftItem.SyncCommand.CommandAction);
                    Assert.Null(childItem.RightItem.SyncCommand.CommandAction);

                    // И корневые элементы теперь должны быть идентичные и команды синхронизации им тоже не нужны.
                    Assert.Equal(ItemStatusEnum.Equally, synchronizedDirectories.LeftItem.Status.StatusEnum);
                    Assert.Equal(ItemStatusEnum.Equally, synchronizedDirectories.RightItem.Status.StatusEnum);
                    Assert.Null(synchronizedDirectories.LeftItem.SyncCommand.CommandAction);
                    Assert.Null(synchronizedDirectories.RightItem.SyncCommand.CommandAction);
                }
        }
        public async Task LoadDirectoryAndFile()
        {
            const string directoryAndFileName = "Item";

            using (var leftDirectory = new Infrastructure.TestDirectory())
                using (var rightDirectory = new Infrastructure.TestDirectory())
                {
                    var updateDate = DateTime.Now;

                    leftDirectory.CreateFiles(new Dictionary <string, DateTime>
                    {
                        { directoryAndFileName, updateDate }
                    });

                    // В директорию надо поместить хотя бы один файл, чтобы она была видна.
                    Infrastructure.TestDirectory.CreateFiles(rightDirectory.CreateDirectory(directoryAndFileName),
                                                             new Dictionary <string, DateTime> {
                        { "1", updateDate }
                    });

                    var settingsRow = new TestSettingsRow
                    {
                        LeftDirectory  = new SettingsDirectory(leftDirectory.FullPath),
                        RightDirectory = new SettingsDirectory(rightDirectory.FullPath)
                    };
                    var testSynchronizedItemsStatusAndCommandsUpdater = new TestSynchronizedItemsStatusAndCommandsUpdater();
                    var synchronizedDirectories = new SynchronizedItems(settingsRow, new SynchronizedItemFactory(new ItemFactory()),
                                                                        testSynchronizedItemsStatusAndCommandsUpdater);

                    await synchronizedDirectories.Load();

                    Assert.Equal(2, synchronizedDirectories.ChildItemsCount); // Одна модель на директории, одна модель на файлы.

                    // Сначала директория, потом файл.
                    var childDirectories1 = synchronizedDirectories.ChildItems[0];
                    Assert.Equal(directoryAndFileName, childDirectories1.LeftItem.Name);
                    Assert.Equal(directoryAndFileName, childDirectories1.RightItem.Name);
                    Assert.NotNull(childDirectories1.RightItem.Directory);
                    Assert.True(childDirectories1.RightItem.IsDirectory);

                    // Даже если элемент отсутствует, а присутствующий является директорией, то и этот должен быть директорией.
                    Assert.Null(childDirectories1.LeftItem.Directory);
                    Assert.True(childDirectories1.LeftItem.IsDirectory);

                    var childDirectories2 = synchronizedDirectories.ChildItems[1];
                    Assert.Equal(directoryAndFileName, childDirectories2.LeftItem.Name);
                    Assert.Equal(directoryAndFileName, childDirectories2.RightItem.Name);
                    Assert.Null(childDirectories2.LeftItem.Directory);
                    Assert.False(childDirectories2.LeftItem.IsDirectory);
                    Assert.Null(childDirectories2.RightItem.Directory);
                    Assert.False(childDirectories2.RightItem.IsDirectory);
                }
        }
Exemplo n.º 8
0
        public void DeleteWithError()
        {
            using (var testDirectory = new Infrastructure.TestDirectory())
            {
                var sourceFile = Path.Combine(testDirectory.FullPath, Guid.NewGuid().ToString());
                File.WriteAllBytes(sourceFile, new byte[0]);
                var file = new DirectorySync.Models.File(sourceFile);

                string error = null;
                file.SyncErrorEvent += (string message) => { error = message; };

                using (var stream = File.Open(sourceFile, FileMode.Open))
                    file.Delete().Wait();

                Assert.NotNull(error);
            }
        }
        public async Task DirectoriesIsLoadedEvent()
        {
            List <ISynchronizedItems> loadedSynchronizedDirectoriesList = new List <ISynchronizedItems>();

            using (var leftDirectory = new Infrastructure.TestDirectory())
                using (var rightDirectory = new Infrastructure.TestDirectory())
                {
                    var synchronizedDirectories = GetSynchronizedDirectories(leftDirectory.FullPath, rightDirectory.FullPath);
                    synchronizedDirectories.DirectoriesIsLoadedEvent += (ISynchronizedItems loadedSynchronizedItems) =>
                    {
                        loadedSynchronizedDirectoriesList.Add(loadedSynchronizedItems);
                    };
                    await synchronizedDirectories.Load();

                    Assert.Single(loadedSynchronizedDirectoriesList);
                    Assert.Equal(synchronizedDirectories, loadedSynchronizedDirectoriesList[0]);
                }
        }
Exemplo n.º 10
0
        public async Task LoadDirectories_OneEmptyDirectory()
        {
            const string directoryName = "Directory";
            const string fileName      = "File";

            var newerDate = new DateTime(2019, 1, 1);
            var olderDate = new DateTime(2018, 1, 1);

            using (var leftDirectory = new Infrastructure.TestDirectory())
                using (var rightDirectory = new Infrastructure.TestDirectory())
                {
                    var childLeftDirectoryPath = leftDirectory.CreateDirectory(directoryName, newerDate);
                    Infrastructure.TestDirectory.CreateFiles(childLeftDirectoryPath, new Dictionary <string, DateTime> {
                        { fileName, DateTime.Now }
                    });

                    rightDirectory.CreateDirectory(directoryName, olderDate);

                    var settingsRow = new TestSettingsRow
                    {
                        LeftDirectory  = new SettingsDirectory(leftDirectory.FullPath),
                        RightDirectory = new SettingsDirectory(rightDirectory.FullPath)
                    };

                    var testSynchronizedItemsStatusAndCommandsUpdater = new TestSynchronizedItemsStatusAndCommandsUpdater();
                    var synchronizedDirectories = new SynchronizedItems(settingsRow, new SynchronizedItemFactory(new ItemFactory()),
                                                                        testSynchronizedItemsStatusAndCommandsUpdater);

                    await synchronizedDirectories.Load();

                    Assert.Single(synchronizedDirectories.ChildItems);

                    var childDirectories = synchronizedDirectories.ChildItems[0];
                    Assert.Equal(directoryName, childDirectories.LeftItem.Name);
                    Assert.Equal(directoryName, childDirectories.RightItem.Name);
                    Assert.NotNull(childDirectories.LeftItem.Directory);

                    // Справа реально директории нет, потому что пустые директории не учитываются, но элемент помечен как директория.
                    Assert.Null(childDirectories.RightItem.Directory);
                    Assert.True(childDirectories.RightItem.IsDirectory);

                    Assert.Empty(childDirectories.ChildItems);
                }
        }
Exemplo n.º 11
0
        public async Task Load_RefreshStatusAndCommandsFromChilds()
        {
            const string directoryName = "Directory";
            const string fileName      = "File";
            var          updateDate    = DateTime.Now;

            using (var leftDirectory = new Infrastructure.TestDirectory())
                using (var rightDirectory = new Infrastructure.TestDirectory())
                {
                    var childLeftDirectoryPath  = leftDirectory.CreateDirectory(directoryName, updateDate);
                    var childRightDirectoryPath = rightDirectory.CreateDirectory(directoryName, updateDate);

                    Infrastructure.TestDirectory.CreateFiles(childLeftDirectoryPath, new Dictionary <string, DateTime> {
                        { fileName, updateDate }
                    });
                    Infrastructure.TestDirectory.CreateFiles(childRightDirectoryPath, new Dictionary <string, DateTime> {
                        { fileName, updateDate }
                    });

                    var settingsRow = new TestSettingsRow
                    {
                        LeftDirectory  = new SettingsDirectory(leftDirectory.FullPath),
                        RightDirectory = new SettingsDirectory(rightDirectory.FullPath)
                    };

                    var testSynchronizedItemsStatusAndCommandsUpdater = new TestSynchronizedItemsStatusAndCommandsUpdater();
                    var synchronizedDirectories = new SynchronizedItems(settingsRow, new SynchronizedItemFactory(new ItemFactory()),
                                                                        testSynchronizedItemsStatusAndCommandsUpdater);
                    await synchronizedDirectories.Load();

                    Assert.Single(synchronizedDirectories.ChildItems);

                    var childDirectories = synchronizedDirectories.ChildItems[0];

                    var refreshedLeftItemSynchronizedItemsList  = testSynchronizedItemsStatusAndCommandsUpdater.RefreshedLeftItemSynchronizedItemsList;
                    var refreshedRightItemSynchronizedItemsList = testSynchronizedItemsStatusAndCommandsUpdater.RefreshedRightItemSynchronizedItemsList;
                    Assert.Equal(2, refreshedLeftItemSynchronizedItemsList.Count);
                    Assert.Equal(2, refreshedRightItemSynchronizedItemsList.Count);
                    Assert.Equal(childDirectories, refreshedLeftItemSynchronizedItemsList[0]);
                    Assert.Equal(childDirectories, refreshedRightItemSynchronizedItemsList[0]);
                    Assert.Equal(synchronizedDirectories, refreshedLeftItemSynchronizedItemsList[1]);
                    Assert.Equal(synchronizedDirectories, refreshedRightItemSynchronizedItemsList[1]);
                }
        }
Exemplo n.º 12
0
        public void Delete(bool isReadOnly)
        {
            IItem deletedFile = null;

            using (var testDirectory = new Infrastructure.TestDirectory())
            {
                var sourceFile = Path.Combine(testDirectory.FullPath, Guid.NewGuid().ToString());
                File.WriteAllBytes(sourceFile, new byte[0]);
                new FileInfo(sourceFile).IsReadOnly = isReadOnly;

                var file = new DirectorySync.Models.File(sourceFile);
                file.DeletedEvent += (IItem item) => { deletedFile = item; };

                file.Delete().Wait();

                Assert.Equal(file, deletedFile);
                Assert.False(File.Exists(sourceFile));
            }
        }
Exemplo n.º 13
0
        public void CopyToWithError()
        {
            using (var testDirectory = new Infrastructure.TestDirectory())
            {
                var sourceFile      = Path.Combine(testDirectory.FullPath, Guid.NewGuid().ToString());
                var destinationFile = Path.Combine(testDirectory.FullPath, Guid.NewGuid().ToString());
                var fileText        = Guid.NewGuid().ToString();

                File.WriteAllText(sourceFile, fileText);
                var file = new DirectorySync.Models.File(sourceFile);

                string error = null;
                file.SyncErrorEvent += (string message) => { error = message; };
                using (var stream = File.Create(destinationFile))
                    file.CopyTo(destinationFile).Wait();

                Assert.NotNull(error);
            }
        }
Exemplo n.º 14
0
        public async Task CreateRowViewModel_Tree()
        {
            const string name1           = "1";
            const string name2           = "2";
            byte         useAddRowsCount = 0;

            using (var leftDirectory = new Infrastructure.TestDirectory())
                using (var rightDirectory = new Infrastructure.TestDirectory())
                {
                    Infrastructure.TestDirectory.CreateFiles(leftDirectory.CreateDirectory(name1), new Dictionary <string, DateTime>
                    {
                        { name1, DateTime.Now }
                    });
                    Infrastructure.TestDirectory.CreateFiles(rightDirectory.CreateDirectory(name1), new Dictionary <string, DateTime>
                    {
                        { name1, DateTime.Now }
                    });

                    Infrastructure.TestDirectory.CreateFiles(leftDirectory.CreateDirectory(name2), new Dictionary <string, DateTime>
                    {
                        { name1, DateTime.Now }
                    });
                    Infrastructure.TestDirectory.CreateFiles(rightDirectory.CreateDirectory(name2), new Dictionary <string, DateTime>
                    {
                        { name1, DateTime.Now }
                    });

                    var synchronizedDirectories = GetSynchronizedDirectories(leftDirectory.FullPath, rightDirectory.FullPath);
                    var factory = new RowViewModelFactory();
                    factory.AddRowEvent += (IRowViewModel parent, IRowViewModel child) => { useAddRowsCount++; };
                    var rowViewModel = factory.CreateRowViewModel(synchronizedDirectories);

                    await synchronizedDirectories.Load();

                    Assert.Equal(4, useAddRowsCount);     // Две директории, в каждой директории по одному файлу.

                    Assert.Empty(rowViewModel.ChildRows); // А записей не прибавилось, потому что фабрика их не прибавляет.
                }
        }
Exemplo n.º 15
0
        public async Task AddCommandsAfterSyncProcess()
        {
            const string directory1Name = "Dir1";
            const string directory2Name = "Dir2";
            const string file1Name      = "File1";
            var          updateDate     = DateTime.Now;

            using (var leftDirectory = new Infrastructure.TestDirectory())
                using (var rightDirectory = new Infrastructure.TestDirectory())
                {
                    leftDirectory.CreateDirectory(directory1Name);
                    Infrastructure.TestDirectory.CreateFiles(rightDirectory.CreateDirectory(directory1Name),
                                                             new Dictionary <string, DateTime> {
                        { file1Name, updateDate }
                    });

                    Infrastructure.TestDirectory.CreateFiles(leftDirectory.CreateDirectory(directory2Name),
                                                             new Dictionary <string, DateTime> {
                        { file1Name, updateDate }, { "File2", updateDate }
                    });
                    Infrastructure.TestDirectory.CreateFiles(rightDirectory.CreateDirectory(directory2Name),
                                                             new Dictionary <string, DateTime> {
                        { file1Name, updateDate }
                    });

                    var synchronizedDirectories = GetSynchronizedDirectories(leftDirectory.FullPath, rightDirectory.FullPath);
                    await synchronizedDirectories.Load();

                    // После того, как Dir2 слева начнёт соответствовать Dir2 справа,
                    // у корневой строки должны появиться команды для синхронизации Dir1.
                    await synchronizedDirectories.ChildItems[1].LeftItem.SyncCommand.Process();
                    await Task.Delay(20); // Чтобы успели обновиться статусы и команды.

                    Assert.NotNull(synchronizedDirectories.LeftItem.SyncCommand.CommandAction);
                    Assert.NotNull(synchronizedDirectories.RightItem.SyncCommand.CommandAction);
                }
        }
Exemplo n.º 16
0
        public async Task LoadFiles()
        {
            const string file1Name           = "File1";
            const string file2Name           = "File2";
            const string file3Name           = "File3";
            var          updateFileDate      = DateTime.Now;
            var          filesDirectoinaries = new Dictionary <string, DateTime>
            {
                { file1Name, updateFileDate },
                { file2Name, updateFileDate },
                { file3Name, updateFileDate }
            };

            using (var leftDirectory = new Infrastructure.TestDirectory())
                using (var rightDirectory = new Infrastructure.TestDirectory())
                {
                    leftDirectory.CreateFiles(filesDirectoinaries);
                    rightDirectory.CreateFiles(filesDirectoinaries);

                    var settingsRow = new TestSettingsRow
                    {
                        LeftDirectory  = new SettingsDirectory(leftDirectory.FullPath),
                        RightDirectory = new SettingsDirectory(rightDirectory.FullPath)
                    };
                    var testSynchronizedItemsStatusAndCommandsUpdater = new TestSynchronizedItemsStatusAndCommandsUpdater();
                    var synchronizedDirectories = new SynchronizedItems(settingsRow, new SynchronizedItemFactory(new ItemFactory()),
                                                                        testSynchronizedItemsStatusAndCommandsUpdater);

                    await synchronizedDirectories.Load();

                    Assert.Equal(3, synchronizedDirectories.ChildItemsCount);

                    var directories = synchronizedDirectories.ChildItems[0];
                    Assert.Equal(file1Name, directories.LeftItem.Name);
                    Assert.Equal(file1Name, directories.RightItem.Name);

                    // Это файлы.
                    Assert.False(directories.LeftItem.IsDirectory);
                    Assert.Null(directories.LeftItem.Directory);
                    Assert.False(directories.RightItem.IsDirectory);
                    Assert.Null(directories.RightItem.Directory);

                    directories = synchronizedDirectories.ChildItems[1];
                    Assert.Equal(file2Name, directories.LeftItem.Name);
                    Assert.Equal(file2Name, directories.RightItem.Name);

                    // Это файлы.
                    Assert.False(directories.LeftItem.IsDirectory);
                    Assert.Null(directories.LeftItem.Directory);
                    Assert.False(directories.RightItem.IsDirectory);
                    Assert.Null(directories.RightItem.Directory);

                    directories = synchronizedDirectories.ChildItems[2];
                    Assert.Equal(file3Name, directories.LeftItem.Name);
                    Assert.Equal(file3Name, directories.RightItem.Name);

                    // Это файлы.
                    Assert.False(directories.LeftItem.IsDirectory);
                    Assert.Null(directories.LeftItem.Directory);
                    Assert.False(directories.RightItem.IsDirectory);
                    Assert.Null(directories.RightItem.Directory);
                }
        }
Exemplo n.º 17
0
        public async Task InProcess_SyncCommand(bool left)
        {
            using (var leftDirectory = new Infrastructure.TestDirectory())
                using (var rightDirectory = new Infrastructure.TestDirectory())
                {
                    Infrastructure.TestDirectory.CreateDirectory(leftDirectory.CreateDirectory("Dir1"), "Dir2");
                    Infrastructure.TestDirectory.CreateDirectory(rightDirectory.CreateDirectory("Dir1"), "Dir2");
                    leftDirectory.CreateDirectory("Dir3");
                    rightDirectory.CreateDirectory("Dir3");

                    var containerBuilder = new ContainerBuilder();
                    containerBuilder.RegisterModule <TestAutofacRegisterModule>();
                    containerBuilder.RegisterType <SettingsRow>().As <ISettingsRow>();
                    containerBuilder.RegisterType <SynchronizedItems>().As <ISynchronizedItems>();

                    using (var fake = new AutoFake(builder: containerBuilder))
                    {
                        var fakeItemFactory = A.Fake <IItemFactory>();
                        A.CallTo(() => fakeItemFactory.CreateDirectory(A <string> .Ignored, A <string[]> .Ignored))
                        .ReturnsLazily((string directoryPath, string[] excludedExtensions) =>
                        {
                            return(new TestDirectory(directoryPath, fakeItemFactory, 1));
                        });

                        var fakeSettingsRow = A.Fake <ISettingsRow>();
                        A.CallTo(() => fakeSettingsRow.LeftDirectory).Returns(new SettingsDirectory(leftDirectory.FullPath));
                        A.CallTo(() => fakeSettingsRow.RightDirectory).Returns(new SettingsDirectory(rightDirectory.FullPath));

                        var fakeSynchronizedItemsStatusAndCommandsUpdater = A.Fake <ISynchronizedItemsStatusAndCommandsUpdater>();
                        A.CallTo(() => fakeSynchronizedItemsStatusAndCommandsUpdater
                                 .UpdateStatusesAndCommands(A <ISynchronizedItem> .Ignored, A <ISynchronizedItem> .Ignored))
                        .Invokes((ISynchronizedItem item1, ISynchronizedItem item2) =>
                        {
                            item1.UpdateStatus(ItemStatusEnum.Equally);
                            item2.UpdateStatus(ItemStatusEnum.Equally);
                        });

                        fake.Provide(fakeSettingsRow);
                        fake.Provide(fakeItemFactory);
                        fake.Provide(fakeSynchronizedItemsStatusAndCommandsUpdater);

                        var synchronizedItems = fake.Resolve <ISynchronizedItems>();
                        await synchronizedItems.Load(); // Загрузим, чтобы построилось дерево элементов.

                        // А теперь запустим синхронизацию одного из элементов и проверим изменение признака InProcess.
                        var childLevel1SynchronizedItems1 = synchronizedItems.ChildItems[0];
                        var processItem = left ? childLevel1SynchronizedItems1.LeftItem : childLevel1SynchronizedItems1.RightItem;
                        processItem.SyncCommand.SetCommandAction(() =>
                                                                 Task.Delay(4));
                        var syncTask = Task.Run(() => processItem.SyncCommand.Process());

                        await Task.Delay(2); // Чтобы признаки успели поменять значения.

                        Assert.True(childLevel1SynchronizedItems1.InProcess);
                        Assert.True(synchronizedItems.InProcess);                           // И процесс родителя должен обозначиться.
                        Assert.True(childLevel1SynchronizedItems1.ChildItems[0].InProcess); // И процесс дочерних элементом.

                        Assert.False(synchronizedItems.ChildItems[1].InProcess);            // А эти элементы не при чём.

                        syncTask.Wait();                                                    // Ждём, пока завершится синхронизация.

                        // А теперь всё обратно в false.
                        Assert.False(childLevel1SynchronizedItems1.InProcess);
                        Assert.False(synchronizedItems.InProcess);
                        Assert.False(childLevel1SynchronizedItems1.ChildItems[0].InProcess);
                    }
                }
        }