public void NewDriveAsync_WhereGatewayIsExported_PerformsComposition()
        {
            var gatewayMock = new Mock<IAsyncCloudGateway>(MockBehavior.Strict).Object;

            compositionFixture.ExportAsyncGateway(gatewayMock);

            var pipelineFixture = new PipelineFixture();
            pipelineFixture.Invoke(string.Format(CultureInfo.InvariantCulture,
                "New-PSDrive -PSProvider {0} -Name X -Root '{1}' -Description '{2}' -ApiKey {3} -EncryptionKey {4}",
                CloudProvider.PROVIDER_NAME, CompositionFixture.MOCKGATEWAY_NAME + "|" + root, description, apiKey, encryptionKey)
            );
        }
        public void GetChildItem_WherePathIsRoot_CallsGatewayCorrectly()
        {
            var rootName = FileSystemFixture.GetRootName();
            var rootDirectoryItems = fileSystemFixture.RootDirectoryItems;

            var gatewayMock = mockingFixture.InitializeGetChildItems(rootName, @"\", rootDirectoryItems);
            compositionFixture.ExportGateway(gatewayMock.Object);

            var result = new PipelineFixture().Invoke(
                FileSystemFixture.NewDriveCommand,
                @"Get-ChildItem -Path X:\"
            );

            Assert.AreEqual(rootDirectoryItems.Length, result.Count, "Unexpected number of results");
            CollectionAssert.AreEquivalent(rootDirectoryItems, result.Select(p => p.BaseObject).Cast<FileSystemInfoContract>().ToList());
        }
        public void ResolvePath_WhereBasePathIsRoot_CallsGatewayCorrectly()
        {
            var rootName = FileSystemFixture.GetRootName();
            var rootDirectoryItems = fileSystemFixture.RootDirectoryItems;

            var gatewayMock = mockingFixture.InitializeGetChildItemsAsync(rootName, @"\", rootDirectoryItems);
            compositionFixture.ExportAsyncGateway(gatewayMock.Object);

            var result = new PipelineFixture().Invoke(new string[] {
                FileSystemFixture.NewDriveCommand,
                @"Resolve-Path X:\*"
            });

            Assert.AreEqual(rootDirectoryItems.Length, result.Count, "Unexpected number of results");
            CollectionAssert.AllItemsAreInstancesOfType(result.Select(i => i.BaseObject).ToList(), typeof(PathInfo), "Result is not of type PathInfo");
        }
        public void RemoveDriveAsync_RemovesDrive()
        {
            var gatewayMock = new Mock<IAsyncCloudGateway>(MockBehavior.Strict).Object;

            compositionFixture.ExportAsyncGateway(gatewayMock);

            var pipelineFixture = new PipelineFixture();
            var result = pipelineFixture.Invoke(new string[] {
                string.Format(CultureInfo.InvariantCulture,
                    "New-PSDrive -PSProvider {0} -Name X -Root '{1}' -Description '{2}' -ApiKey {3} -EncryptionKey {4}",
                    CloudProvider.PROVIDER_NAME, CompositionFixture.MOCKGATEWAY_NAME + "|" + root, description, apiKey, encryptionKey),
                "Remove-PSDrive -Name X",
                string.Format(CultureInfo.InvariantCulture,
                    "Get-PSDrive -PSProvider {0}", CloudProvider.PROVIDER_NAME)
            });

            Assert.AreEqual(0, result.Count, "Unexpected number of results");
        }
        public void GetContentAsync_WhereNodeIsFileAndEncodingIsByte_ReturnsContent()
        {
            var rootName = FileSystemFixture.GetRootName();
            var rootDirectoryItems = fileSystemFixture.RootDirectoryItems;
            var content = new MemoryStream(TestContent.MultiLineTestContent.Select(c => Convert.ToByte(c)).ToArray());

            var gatewayMock = mockingFixture.InitializeGetChildItemsAsync(rootName, @"\", rootDirectoryItems);
            gatewayMock.SetupSequence(g => g.GetContentAsync(rootName, new FileId(@"\File.ext")))
                .ReturnsAsync(content)
                .ThrowsAsync(new InvalidOperationException(@"Redundant access to \File.ext"));
            compositionFixture.ExportAsyncGateway(gatewayMock.Object);

            var result = new PipelineFixture().Invoke(
                FileSystemFixture.NewDriveCommand,
                @"Get-Content -Path X:\File.ext -Encoding Byte"
            );

            CollectionAssert.AreEqual(content.ToArray(), result.Select(p => p.BaseObject).ToArray(), "Mismatching content");
        }
        public void ClearContent_WhereNodeIsFile_ClearsContent()
        {
            var rootName = FileSystemFixture.GetRootName();
            var rootDirectoryItems = fileSystemFixture.RootDirectoryItems;
            var content = TestContent.MultiLineTestContent.Select(c => Convert.ToByte(c)).ToArray();

            var gatewayMock = mockingFixture.InitializeGetChildItems(rootName, @"\", rootDirectoryItems);
            gatewayMock.Setup(g => g.ClearContent(rootName, new FileId(@"\File.ext"))).Verifiable();
            compositionFixture.ExportGateway(gatewayMock.Object);

            var pipelineFixture = new PipelineFixture();
            pipelineFixture.SetVariable("value", content);
            pipelineFixture.Invoke(
                FileSystemFixture.NewDriveCommand,
                @"Clear-Content -Path X:\File.ext"
            );

            gatewayMock.VerifyAll();
        }
        public void NewDrive_WhereCredentialsAreEmpty_CreatesDrive()
        {
            var gatewayMock = new Mock<ICloudGateway>(MockBehavior.Strict).Object;

            compositionFixture.ExportGateway(gatewayMock);

            var result = new PipelineFixture().Invoke(new string[] {
                string.Format(CultureInfo.InvariantCulture,
                    "New-PSDrive -PSProvider {0} -Name X -Root '{1}' -Description '{2}' -ApiKey {3} -EncryptionKey {4}",
                    CloudProvider.PROVIDER_NAME, CompositionFixture.MOCKGATEWAY_NAME + "|" + root, description, apiKey, encryptionKey),
                string.Format(CultureInfo.InvariantCulture,
                    "Get-PSDrive -PSProvider {0}", CloudProvider.PROVIDER_NAME)
            });

            Assert.AreEqual(1, result.Count, "Unexpected number of results");
            Assert.IsInstanceOfType(result[0].BaseObject, typeof(PSDriveInfo), "Result is not of type PSDriveInfo");

            var driveInfo = result[0].BaseObject as PSDriveInfo;
            Assert.AreEqual("X:", driveInfo.Root, "Unexpected root");
            Assert.AreEqual(CompositionFixture.MOCKGATEWAY_NAME, ((CloudDrive)driveInfo).DisplayRoot, "Unexpected display root");
            Assert.AreEqual(description, driveInfo.Description, "Unexpected description");
        }
        public void NewItem_WherePathIsRootAndItemTypeIsDirectory_CallsGatewayCorrectly()
        {
            var rootName = FileSystemFixture.GetRootName();
            var rootDirectoryItems = fileSystemFixture.RootDirectoryItems;
            var newItem = new DirectoryInfoContract(@"\SubDir", "SubDir", DateTime.Now, DateTime.Now);

            var gatewayMock = mockingFixture.InitializeGetChildItems(rootName, @"\", rootDirectoryItems);
            gatewayMock.Setup(g => g.NewDirectoryItem(rootName, new DirectoryId(@"\"), "NewSubDir"))
                .Returns(newItem)
                .Verifiable();
            compositionFixture.ExportGateway(gatewayMock.Object);

            var result = new PipelineFixture().Invoke(
                FileSystemFixture.NewDriveCommand,
                @"New-Item -Type Directory -Path X:\ -Name NewSubDir"
            );

            Assert.AreEqual(1, result.Count, "Unexpected number of results");
            Assert.AreEqual(newItem, result[0].BaseObject, "Mismatching result");

            gatewayMock.VerifyAll();
        }
        public void SetContentAsync_WhereNodeIsFileAndEncodingIsByte_AcceptsContent()
        {
            var rootName = FileSystemFixture.GetRootName();
            var rootDirectoryItems = fileSystemFixture.RootDirectoryItems;
            var content = TestContent.MultiLineTestContent.Select(c => Convert.ToByte(c)).ToArray();

            var gatewayMock = mockingFixture.InitializeGetChildItemsAsync(rootName, @"\", rootDirectoryItems);
            gatewayMock.Setup(g => g.ClearContentAsync(rootName, new FileId(@"\File.ext"), It.IsAny<Func<FileSystemInfoLocator>>()))
                .ReturnsAsync(true)
                .Verifiable();
            gatewayMock.Setup(g => g.SetContentAsync(rootName, new FileId(@"\File.ext"), It.Is<Stream>(s => new BinaryReader(s, System.Text.Encoding.Default, true).ReadBytes((int)s.Length).SequenceEqual(content)), It.Is<IProgress<ProgressValue>>(p => true), It.IsAny<Func<FileSystemInfoLocator>>()))
                .ReturnsAsync(true)
                .Verifiable();
            compositionFixture.ExportAsyncGateway(gatewayMock.Object);

            var pipelineFixture = new PipelineFixture();
            pipelineFixture.SetVariable("value", content);
            pipelineFixture.Invoke(
                FileSystemFixture.NewDriveCommand,
                @"Set-Content -Path X:\File.ext $value -Encoding Byte"
            );

            gatewayMock.VerifyAll();
        }
        public void GetChildItem_WherePathIsRootAndCredentialsAreSpecified_CallsGatewayCorrectly()
        {
            var rootName = FileSystemFixture.GetRootName("@TestUser");
            var rootDirectoryItems = fileSystemFixture.RootDirectoryItems;

            var gatewayMock = mockingFixture.InitializeGetChildItems(rootName, @"\", rootDirectoryItems);
            compositionFixture.ExportGateway(gatewayMock.Object);

            var pipelineFixture = new PipelineFixture();
            pipelineFixture.SetVariable("credential", PipelineFixture.GetCredential("TestUser", "TestPassword"));
            var result = pipelineFixture.Invoke(
                FileSystemFixture.NewDriveCommandWithCredential,
                @"Get-ChildItem -Path Y:\"
            );

            Assert.AreEqual(rootDirectoryItems.Length, result.Count, "Unexpected number of results");
            CollectionAssert.AreEquivalent(rootDirectoryItems, result.Select(p => p.BaseObject).Cast<FileSystemInfoContract>().ToList());
        }
        public void GetChildItem_WherePathIsRootAndFilterIsSpecified_CallsGatewayCorrectly()
        {
            var rootName = FileSystemFixture.GetRootName();
            var rootDirectoryItems = fileSystemFixture.RootDirectoryItems;

            var gatewayMock = mockingFixture.InitializeGetChildItemsWithFilter(rootName, @"\", "*File.ext", rootDirectoryItems);
            compositionFixture.ExportGateway(gatewayMock.Object);

            var result = new PipelineFixture().Invoke(
                FileSystemFixture.NewDriveCommand,
                @"Get-ChildItem -Path X:\ -Filter *File.ext"
            );

            Assert.AreEqual(rootDirectoryItems.Count(i => i.Name.EndsWith("File.ext", StringComparison.Ordinal)), result.Count, "Unexpected number of results");
            CollectionAssert.AllItemsAreInstancesOfType(result.Select(i => i.BaseObject).ToList(), typeof(FileInfoContract), "Results are not of type FileInfoContract");
            CollectionAssert.AreEqual(rootDirectoryItems.Where(i => i.Name.EndsWith("File.ext", StringComparison.Ordinal)).ToList(), result.Select(i => i.BaseObject).ToList(), "Mismatched result");
        }
        public void GetChildItem_WherePathIsSubDirectoryAndForceIsSpecified_RefreshesResult()
        {
            var rootName = FileSystemFixture.GetRootName();
            var rootDirectoryItems = fileSystemFixture.RootDirectoryItems;
            var subDirectoryItems = fileSystemFixture.SubDirectoryItems;
            var subDirectoryItemsRefreshed = fileSystemFixture.SubDirectoryItems
                .Select(f => f is FileInfoContract
                    ? new FileInfoContract(f.Id.Value.Insert(f.Id.Value.IndexOf(".ext", StringComparison.Ordinal), "Refreshed"), f.Name.Insert(f.Name.IndexOf(".ext", StringComparison.Ordinal), "Refreshed"), f.Created, f.Updated, ((FileInfoContract)f).Size, ((FileInfoContract)f).Hash) as FileSystemInfoContract
                    : new DirectoryInfoContract(f.Id + "Refreshed", f.Name + "Refreshed", f.Created, f.Updated) as FileSystemInfoContract)
                .ToArray();

            var gatewayMock = new MockingFixture().InitializeGetChildItems(rootName, string.Empty, rootDirectoryItems);
            gatewayMock.SetupSequence(g => g.GetChildItem(rootName, new DirectoryId(@"\SubDir")))
                .Returns(subDirectoryItems)
                .Returns(subDirectoryItemsRefreshed)
                .Throws(new InvalidOperationException(string.Format(CultureInfo.CurrentCulture, @"Redundant access to \SubDir")));
            compositionFixture.ExportGateway(gatewayMock.Object);

            var result = new PipelineFixture().Invoke(
                FileSystemFixture.NewDriveCommand,
                @"Get-ChildItem -Path X:\SubDir",
                @"Get-ChildItem -Path X:\SubDir -Force"
            );

            Assert.AreEqual(subDirectoryItemsRefreshed.Length, result.Count, "Unexpected number of results");
            CollectionAssert.AreEquivalent(subDirectoryItemsRefreshed, result.Select(p => p.BaseObject).Cast<FileSystemInfoContract>().ToList());
        }
        public void CopyItem_WherePathIsDirectoryAndDestinationDirectoryIsDifferent_CopiesDirectory()
        {
            var rootName = FileSystemFixture.GetRootName();
            var rootDirectoryItems = fileSystemFixture.RootDirectoryItems;
            var subDirectoryItems = fileSystemFixture.SubDirectoryItems;

            var original = (DirectoryInfoContract)rootDirectoryItems.Single(i => i.Name == "SubDir");
            var copy = default(DirectoryInfoContract);

            var gatewayMock = mockingFixture.InitializeGetChildItems(rootName, @"\SubDir", rootDirectoryItems, subDirectoryItems);
            gatewayMock.Setup(g => g.CopyItem(rootName, new DirectoryId(@"\SubDir"), @"SubDirCopy", new DirectoryId(@"\SubDir"), false))
                .Returns(copy = new DirectoryInfoContract(original.Id.Value.Replace("SubDir", "SubDirCopy"), original.Name.Replace("SubDir", "SubDirCopy"), original.Created, original.Updated))
                .Verifiable();
            compositionFixture.ExportGateway(gatewayMock.Object);

            var result = new PipelineFixture().Invoke(
                FileSystemFixture.NewDriveCommand,
                @"Copy-Item -Path X:\SubDir -Destination X:\SubDir\SubDirCopy",
                @"Get-ChildItem -Path X:\SubDir"
            );

            Assert.AreEqual(subDirectoryItems.Count() + 1, result.Count, "Unexpected number of results");
            CollectionAssert.Contains(result.Select(p => p.BaseObject).ToArray(), copy, "Copied item is missing");

            gatewayMock.VerifyAll();
        }
        public void GetContentAsync_WhereNodeIsFileAndEncodingIsByteAndReadCountIsZero_ReturnsContent()
        {
            var rootName = FileSystemFixture.GetRootName();
            var rootDirectoryItems = fileSystemFixture.RootDirectoryItems;
            var content = new MemoryStream(TestContent.MultiLineTestContent.Select(c => Convert.ToByte(c)).ToArray());

            var gatewayMock = mockingFixture.InitializeGetChildItemsAsync(rootName, @"\", rootDirectoryItems);
            gatewayMock.SetupSequence(g => g.GetContentAsync(rootName, new FileId(@"\File.ext")))
                .ReturnsAsync(content)
                .ThrowsAsync(new InvalidOperationException(@"Redundant access to \File.ext"));
            compositionFixture.ExportAsyncGateway(gatewayMock.Object);

            var result = new PipelineFixture().Invoke(
                FileSystemFixture.NewDriveCommand,
                @"Get-Content -Path X:\File.ext -Encoding Byte -ReadCount 0"
            );

            Assert.AreEqual(1, result.Count, "Unexpected number of results");
            Assert.IsInstanceOfType(result[0].BaseObject, typeof(byte[]), "Results is not of type byte[]");
            CollectionAssert.AreEqual(content.ToArray(), result[0].BaseObject as byte[], "Mismatching content");
        }
        public void GetChildItem_WherePathIsRootAndExcludeIsSpecified_CallsGatewayCorrectly()
        {
            var rootName = FileSystemFixture.GetRootName();
            var rootDirectoryItems = fileSystemFixture.RootDirectoryItems;
            var subDirectoryItems = fileSystemFixture.SubDirectoryItems;
            var subSubDirectoryItems = fileSystemFixture.SubSubDirectoryItems;

            var gatewayMock = mockingFixture.InitializeGetChildItems(rootName, @"\SubDir\SubSubDir", rootDirectoryItems, subDirectoryItems, subSubDirectoryItems);
            compositionFixture.ExportGateway(gatewayMock.Object);

            var result = new PipelineFixture().Invoke(
                FileSystemFixture.NewDriveCommand,
                @"Get-ChildItem -Path X:\ -Exclude *File.ext"
            );

            Assert.AreEqual(2, result.Count, "Unexpected number of results");
            CollectionAssert.AreEquivalent(rootDirectoryItems.Where(i => !i.Name.EndsWith("File.ext", StringComparison.Ordinal)).ToList(), result.Select(i => i.BaseObject).ToList(), "Mismatched result");
        }
        public void NewItem_WherePathIsSubDirAndItemTypeIsFile_CanRemoveNewFile()
        {
            var rootName = FileSystemFixture.GetRootName();
            var rootDirectoryItems = fileSystemFixture.RootDirectoryItems;
            var subDirectoryItems = fileSystemFixture.SubDirectoryItems;
            var newItem = new FileInfoContract(@"\SubDir\NewSubFile", "NewSubFile", DateTime.Now, DateTime.Now, 0, null);

            var gatewayMock = mockingFixture.InitializeGetChildItems(rootName, @"\SubDir", rootDirectoryItems, subDirectoryItems);
            gatewayMock.Setup(g => g.NewFileItem(rootName, new DirectoryId(@"\SubDir"), "NewSubFile", null, It.Is<IProgress<ProgressValue>>(p => true)))
                .Returns(newItem)
                .Verifiable();
            gatewayMock.Setup(g => g.RemoveItem(rootName, new FileId(@"\SubDir\NewSubFile"), false)).Verifiable();
            compositionFixture.ExportGateway(gatewayMock.Object);

            var result = new PipelineFixture().Invoke(
                FileSystemFixture.NewDriveCommand,
                @"New-Item -Type File -Path X:\SubDir -Name NewSubFile",
                @"Remove-Item -Path X:\SubDir\NewSubFile",
                @"Get-ChildItem -Path X:\SubDir"
            );

            Assert.AreEqual(subDirectoryItems.Length, result.Count, "Unexpected number of results");
            CollectionAssert.DoesNotContain(result.Select(p => p.BaseObject).ToArray(), newItem, "Excessive result");

            gatewayMock.VerifyAll();
        }
        public void NewItem_WhereEncryptionKeyIsSpecifiedAndItemTypeIsFile_PassesEncryptedValue()
        {
            var rootName = FileSystemFixture.GetRootName();
            var rootDirectoryItems = fileSystemFixture.RootDirectoryItems;
            var content = TestContent.SingleLineTestContent;
            var newItem = new FileInfoContract(@"\NewFile", "NewFile", DateTime.Now, DateTime.Now, content.Length, FileSystemFixture.GetHash(content));

            var gatewayMock = mockingFixture.InitializeGetChildItems(rootName, @"\", rootDirectoryItems);
            gatewayMock.Setup(g => g.NewFileItem(rootName, new DirectoryId(@"\"), "NewFile", It.Is<Stream>(s => EncryptionFixture.GetDecryptingReader(s, FileSystemFixture.EncryptionKey).ReadToEnd() == content), It.Is<IProgress<ProgressValue>>(p => true)))
                .Returns(newItem)
                .Verifiable();
            compositionFixture.ExportGateway(gatewayMock.Object);

            var pipelineFixture = new PipelineFixture();
            pipelineFixture.SetVariable("value", content);
            var result = pipelineFixture.Invoke(
                FileSystemFixture.NewDriveCommandWithEncryptionKey,
                @"New-Item -Type File -Path X:\ -Name NewFile -Value $value"
            );

            Assert.AreEqual(1, result.Count, "Unexpected number of results");
            Assert.AreEqual(newItem, result[0].BaseObject, "Mismatching result");

            gatewayMock.VerifyAll();
        }
        public void SetContentAsync_WhereNodeIsFileAndEncodingIsUnknown_AcceptsContent()
        {
            var rootName = FileSystemFixture.GetRootName();
            var rootDirectoryItems = fileSystemFixture.RootDirectoryItems;
            var content = TestContent.MultiLineTestContent.Split(new char[] { '\r', '\n' }, StringSplitOptions.RemoveEmptyEntries);

            var gatewayMock = mockingFixture.InitializeGetChildItemsAsync(rootName, @"\", rootDirectoryItems);
            gatewayMock.Setup(g => g.ClearContentAsync(rootName, new FileId(@"\File.ext"), It.IsAny<Func<FileSystemInfoLocator>>()))
                .ReturnsAsync(true)
                .Verifiable();
            gatewayMock.Setup(g => g.SetContentAsync(rootName, new FileId(@"\File.ext"), It.Is<Stream>(s => new StreamReader(s, System.Text.Encoding.Default, true, 1024, true).ReadToEnd().TrimEnd('\r', '\n') == string.Join("\r\n", content)), It.Is<IProgress<ProgressValue>>(p => true), It.IsAny<Func<FileSystemInfoLocator>>()))
                .ReturnsAsync(true)
                .Verifiable();
            compositionFixture.ExportAsyncGateway(gatewayMock.Object);

            var pipelineFixture = new PipelineFixture();
            pipelineFixture.SetVariable("value", content);
            pipelineFixture.Invoke(
                FileSystemFixture.NewDriveCommand,
                @"Set-Content -Path X:\File.ext $value"
            );

            gatewayMock.VerifyAll();
        }
        public void SetContentAsync_WherePathIsUnknownFile_Throws()
        {
            var rootName = FileSystemFixture.GetRootName();
            var rootDirectoryItems = fileSystemFixture.RootDirectoryItems;
            var content = TestContent.MultiLineTestContent.Split(new char[] { '\r', '\n' }, StringSplitOptions.RemoveEmptyEntries);

            var gatewayMock = mockingFixture.InitializeGetChildItemsAsync(rootName, @"\", rootDirectoryItems);
            compositionFixture.ExportAsyncGateway(gatewayMock.Object);

            try {
                var pipelineFixture = new PipelineFixture();
                pipelineFixture.SetVariable("value", content);
                pipelineFixture.Invoke(
                    FileSystemFixture.NewDriveCommand,
                    @"Set-Content -Path X:\FileUnknown $value"
                );

                throw new InvalidOperationException("Expected Exception was not thrown");
            } catch (AssertFailedException ex) {
                Assert.IsTrue(ex.Message.EndsWith(@"ObjectNotFound: (X:\FileUnknown:String) [Set-Content], ItemNotFoundException", StringComparison.Ordinal));
            }

            gatewayMock.VerifyAll();
        }
        public void RenameItem_WherePathIsFile_RenamesFile()
        {
            var rootName = FileSystemFixture.GetRootName();
            var rootDirectoryItems = fileSystemFixture.RootDirectoryItems;

            var original = (FileInfoContract)rootDirectoryItems.Single(i => i.Name == "File.ext");
            var renamed = default(FileInfoContract);

            var gatewayMock = mockingFixture.InitializeGetChildItems(rootName, @"\", rootDirectoryItems);
            gatewayMock.Setup(g => g.RenameItem(rootName, new FileId(@"\File.ext"), "FileRenamed.ext"))
                .Returns(renamed = new FileInfoContract(original.Id.Value.Replace("File", "FileRenamed"), original.Name.Replace("File", "FileRenamed"), original.Created, original.Updated, original.Size, original.Hash))
                .Verifiable();
            compositionFixture.ExportGateway(gatewayMock.Object);

            var result = new PipelineFixture().Invoke(
                FileSystemFixture.NewDriveCommand,
                @"Rename-Item -Path X:\File.ext -NewName FileRenamed.ext",
                @"Get-ChildItem -Path X:\"
            );

            Assert.AreEqual(rootDirectoryItems.Count(), result.Count, "Unexpected number of results");
            CollectionAssert.DoesNotContain(result.Select(p => p.BaseObject).ToArray(), original, "Unrenamed original remains");
            CollectionAssert.Contains(result.Select(p => p.BaseObject).ToArray(), renamed, "Renamed item is missing");

            gatewayMock.VerifyAll();
        }
        public void MoveItemAsync_WherePathIsFile_MovesFile()
        {
            var rootName = FileSystemFixture.GetRootName();
            var rootDirectoryItems = fileSystemFixture.RootDirectoryItems;

            var original = (FileInfoContract)rootDirectoryItems.Single(i => i.Name == "File.ext");
            var moved = default(FileInfoContract);

            var gatewayMock = mockingFixture.InitializeGetChildItemsAsync(rootName, @"\", rootDirectoryItems);
            gatewayMock.Setup(g => g.MoveItemAsync(rootName, new FileId(@"\File.ext"), @"FileMove.ext", new DirectoryId(@"\"), It.IsAny<Func<FileSystemInfoLocator>>()))
                .ReturnsAsync(moved = new FileInfoContract(original.Id.Value.Replace("File", "FileMove"), original.Name.Replace("File", "FileMove"), original.Created, original.Updated, original.Size, original.Hash))
                .Verifiable();
            compositionFixture.ExportAsyncGateway(gatewayMock.Object);

            var result = new PipelineFixture().Invoke(
                FileSystemFixture.NewDriveCommand,
                @"Move-Item -Path X:\File.ext -Destination X:\FileMove.ext",
                @"Get-ChildItem -Path X:\"
            );

            Assert.AreEqual(rootDirectoryItems.Count(), result.Count, "Unexpected number of results");
            CollectionAssert.DoesNotContain(result.Select(p => p.BaseObject).ToArray(), original, "Original item remains");
            CollectionAssert.Contains(result.Select(p => p.BaseObject).ToArray(), moved, "Copied item is missing");

            gatewayMock.VerifyAll();
        }
        public void MoveItemAsync_WherePathIsDirectoryAndDestinationDirectoryIsDifferent_MovesDirectory()
        {
            var rootName = FileSystemFixture.GetRootName();
            var rootDirectoryItems = fileSystemFixture.RootDirectoryItems;
            var subDirectory2Items = fileSystemFixture.SubDirectory2Items;

            var original = (DirectoryInfoContract)rootDirectoryItems.Single(i => i.Name == "SubDir");
            var moved = default(DirectoryInfoContract);

            var gatewayMock = mockingFixture.InitializeGetChildItemsAsync(rootName, @"\SubDir2", rootDirectoryItems, subDirectory2Items);
            gatewayMock.Setup(g => g.MoveItemAsync(rootName, new DirectoryId(@"\SubDir"), @"SubDirMove", new DirectoryId(@"\SubDir2"), It.IsAny<Func<FileSystemInfoLocator>>()))
                .ReturnsAsync(moved = new DirectoryInfoContract(original.Id.Value.Replace("SubDir", "SubDirMove"), original.Name.Replace("SubDir", "SubDirMove"), original.Created, original.Updated))
                .Verifiable();
            compositionFixture.ExportAsyncGateway(gatewayMock.Object);

            var result = new PipelineFixture().Invoke(
                FileSystemFixture.NewDriveCommand,
                @"Move-Item -Path X:\SubDir -Destination X:\SubDir2\SubDirMove",
                @"Get-ChildItem -Path X:\SubDir2"
            );

            Assert.AreEqual(subDirectory2Items.Count() + 1, result.Count, "Unexpected number of results");
            CollectionAssert.Contains(result.Select(p => p.BaseObject).ToArray(), moved, "Copied item is missing");

            gatewayMock.VerifyAll();
        }
        public void SetContentAsync_WhereNodeIsFileAndPassThruIsSet_ReturnsContent()
        {
            var rootName = FileSystemFixture.GetRootName();
            var rootDirectoryItems = fileSystemFixture.RootDirectoryItems;
            var content = TestContent.MultiLineTestContent.Split(new char[] { '\r', '\n' }, StringSplitOptions.RemoveEmptyEntries);

            var gatewayMock = mockingFixture.InitializeGetChildItemsAsync(rootName, @"\", rootDirectoryItems);
            gatewayMock.Setup(g => g.ClearContentAsync(rootName, new FileId(@"\File.ext"), It.IsAny<Func<FileSystemInfoLocator>>()))
                .ReturnsAsync(true)
                .Verifiable();
            gatewayMock.Setup(g => g.SetContentAsync(rootName, new FileId(@"\File.ext"), It.Is<Stream>(s => new StreamReader(s, System.Text.Encoding.Default, true, 1024, true).ReadToEnd().TrimEnd('\r', '\n') == string.Join("\r\n", content)), It.Is<IProgress<ProgressValue>>(p => true), It.IsAny<Func<FileSystemInfoLocator>>()))
                .ReturnsAsync(true)
                .Verifiable();
            compositionFixture.ExportAsyncGateway(gatewayMock.Object);

            var pipelineFixture = new PipelineFixture();
            pipelineFixture.SetVariable("value", content);
            var result = pipelineFixture.Invoke(
                FileSystemFixture.NewDriveCommand,
                @"Set-Content -Path X:\File.ext $value -PassThru"
            );

            Assert.AreEqual(1, result.Count, "Unexpected number of results");
            Assert.IsInstanceOfType(result[0].BaseObject, typeof(string[]), "Results is not of type string[]");
            CollectionAssert.AreEqual(content, (string[])result[0].BaseObject, "Mismatching content");

            gatewayMock.VerifyAll();
        }
        public void NewItem_WhereItemIsAlreadyPresent_Throws()
        {
            var rootName = FileSystemFixture.GetRootName();
            var rootDirectoryItems = fileSystemFixture.RootDirectoryItems;
            var content = TestContent.SingleLineTestContent;

            var gatewayMock = mockingFixture.InitializeGetChildItems(rootName, @"\", rootDirectoryItems);
            compositionFixture.ExportGateway(gatewayMock.Object);

            try {
                var pipelineFixture = new PipelineFixture();
                pipelineFixture.SetVariable("value", content);
                pipelineFixture.Invoke(
                    FileSystemFixture.NewDriveCommand,
                    @"New-Item -Type File -Path X:\ -Name File.ext -Value $value"
                );

                throw new InvalidOperationException("Expected Exception was not thrown");
            } catch (AssertFailedException ex) {
                Assert.IsTrue(ex.Message.EndsWith("NotSpecified: (X:\\File.ext:String) [New-Item], NotSupportedException", StringComparison.Ordinal));
            }

            gatewayMock.VerifyAll();
        }
        public void SetContentAsync_WhereNodeIsDirectory_Throws()
        {
            var rootName = FileSystemFixture.GetRootName();
            var rootDirectoryItems = fileSystemFixture.RootDirectoryItems;
            var content = TestContent.MultiLineTestContent.Select(c => Convert.ToByte(c)).ToArray();

            var gatewayMock = mockingFixture.InitializeGetChildItemsAsync(rootName, @"\", rootDirectoryItems);
            gatewayMock.Setup(g => g.SetContentAsync(rootName, new FileId(@"\SubDir"), It.Is<Stream>(s => new BinaryReader(s, System.Text.Encoding.Default, true).ReadBytes((int)s.Length).SequenceEqual(content)), null, It.IsAny<Func<FileSystemInfoLocator>>()))
                .ThrowsAsync(new NotSupportedException(@"Access to path \SubDir is denied"));
            compositionFixture.ExportAsyncGateway(gatewayMock.Object);

            try {
                var pipelineFixture = new PipelineFixture();
                pipelineFixture.SetVariable("value", content);
                pipelineFixture.Invoke(
                    FileSystemFixture.NewDriveCommand,
                    @"Set-Content -Path X:\SubDir $value"
                );
            } catch (CmdletInvocationException ex) {
                throw ex.InnerException;
            }
        }
        public void NewItem_WherePathIsIncompleteAndItemTypeIsFile_CreatesNewFile()
        {
            var rootName = FileSystemFixture.GetRootName();
            var rootDirectoryItems = fileSystemFixture.RootDirectoryItems;
            var newIntermediateDirectory = new DirectoryInfoContract(@"\NewSubDir", "NewSubDir", DateTime.Now, DateTime.Now);
            var newItem = new FileInfoContract(@"\NewSubDir\NewSubFile", "NewSubFile", DateTime.Now, DateTime.Now, 0, null);

            var gatewayMock = mockingFixture.InitializeGetChildItems(rootName, @"\", rootDirectoryItems);
            gatewayMock.Setup(g => g.NewDirectoryItem(rootName, new DirectoryId(@"\"), "NewSubDir"))
                .Returns(newIntermediateDirectory)
                .Verifiable();
            gatewayMock.Setup(g => g.NewFileItem(rootName, new DirectoryId(@"\NewSubDir"), "NewSubFile", null, It.Is<IProgress<ProgressValue>>(p => true)))
                .Returns(newItem)
                .Verifiable();
            var subDirs = new Queue<string>(new[] { @"\", @"\NewSubDir" });
            var predicateIterator = new Func<string, bool>(s => s == subDirs.Dequeue());
            gatewayMock.SetupSequence(g => g.GetChildItem(rootName, It.Is<DirectoryId>(d => predicateIterator(d.Value))))
                .Returns(new FileSystemInfoContract[0])
                .Returns(new FileSystemInfoContract[0])
                .Throws(new InvalidOperationException(@"Redundant access to directory"));
            compositionFixture.ExportGateway(gatewayMock.Object);

            var result = new PipelineFixture().Invoke(
                FileSystemFixture.NewDriveCommand,
                @"New-Item -Type File -Path X:\NewSubDir -Name NewSubFile -Force",
                @"Get-ChildItem -Path X:\ -Filter 'NewSub*' -Recurse"
            );

            Assert.AreEqual(2, result.Count, "Unexpected number of results");
            CollectionAssert.AreEqual(result.Select(i => i.BaseObject).ToArray(), new FileSystemInfoContract[] { newIntermediateDirectory, newItem }, "Unexpected result");

            gatewayMock.VerifyAll();
        }
        public void GetContentAsync_WhereNodeIsFileAndEncryptionKeyIsSpecified_ReturnsDecryptedContent()
        {
            var rootName = FileSystemFixture.GetRootName();
            var rootDirectoryItems = fileSystemFixture.RootDirectoryItems;
            var content = new MemoryStream(TestContent.MultiLineTestContent.Select(c => Convert.ToByte(c)).ToArray());

            var gatewayMock = mockingFixture.InitializeGetChildItemsAsync(rootName, @"\", rootDirectoryItems);
            gatewayMock.SetupSequence(g => g.GetContentAsync(rootName, new FileId(@"\File.ext")))
                .ReturnsAsync(content.Encrypt(FileSystemFixture.EncryptionKey))
                .ThrowsAsync(new InvalidOperationException(@"Redundant access to \File.ext"));
            compositionFixture.ExportAsyncGateway(gatewayMock.Object);

            var result = new PipelineFixture().Invoke(
                FileSystemFixture.NewDriveCommandWithEncryptionKey,
                @"Get-Content -Path X:\File.ext -ReadCount 0"
            );

            Assert.AreEqual(1, result.Count, "Unexpected number of results");
            Assert.IsInstanceOfType(result[0].BaseObject, typeof(string[]), "Results is not of type string[]");
            CollectionAssert.AreEqual(TestContent.MultiLineTestContent.Split(new char[] { '\r', '\n' }, StringSplitOptions.RemoveEmptyEntries), (string[])result[0].BaseObject, "Mismatching content");
        }
        public void NewItem_WherePathIsSubDirAndItemTypeIsDirectory_CreatesNewDirectory()
        {
            var rootName = FileSystemFixture.GetRootName();
            var rootDirectoryItems = fileSystemFixture.RootDirectoryItems;
            var subDirectoryItems = fileSystemFixture.SubDirectoryItems;
            var newItem = new DirectoryInfoContract(@"\SubDir\NewSubSubDir", "NewSubSubDir", DateTime.Now, DateTime.Now);

            var gatewayMock = mockingFixture.InitializeGetChildItems(rootName, @"\SubDir", rootDirectoryItems, subDirectoryItems);
            gatewayMock.Setup(g => g.NewDirectoryItem(rootName, new DirectoryId(@"\SubDir"), "NewSubSubDir"))
                .Returns(newItem)
                .Verifiable();
            compositionFixture.ExportGateway(gatewayMock.Object);

            var result = new PipelineFixture().Invoke(
                FileSystemFixture.NewDriveCommand,
                @"New-Item -Type Directory -Path X:\SubDir -Name NewSubSubDir",
                @"Get-ChildItem -Path X:\SubDir"
            );

            Assert.AreEqual(subDirectoryItems.Length + 1, result.Count, "Unexpected number of results");
            CollectionAssert.Contains(result.Select(p => p.BaseObject).ToArray(), newItem, "Missing result");

            gatewayMock.VerifyAll();
        }
        public void RemoveItemAsync_WherePathIsFile_RemovesFile()
        {
            var rootName = FileSystemFixture.GetRootName();
            var rootDirectoryItems = fileSystemFixture.RootDirectoryItems;

            var gatewayMock = mockingFixture.InitializeGetChildItemsAsync(rootName, @"\", rootDirectoryItems);
            gatewayMock.Setup(g => g.RemoveItemAsync(rootName, new FileId(@"\File.ext"), false))
                .ReturnsAsync(true)
                .Verifiable();
            compositionFixture.ExportAsyncGateway(gatewayMock.Object);

            var result = new PipelineFixture().Invoke(
                FileSystemFixture.NewDriveCommand,
                @"Remove-Item -Path X:\File.ext",
                @"Get-ChildItem -Path X:\"
            );

            Assert.AreEqual(rootDirectoryItems.Length - 1, result.Count, "Unexpected number of results");
            CollectionAssert.AreEquivalent(rootDirectoryItems.Where(f => f.Name != "File.ext").ToList(), result.Select(p => p.BaseObject).Cast<FileSystemInfoContract>().ToList());

            gatewayMock.VerifyAll();
        }
        public void ResolvePath_WhereBasePathIsSubDirectoryAndPatternContainsPrefix_CallsGatewayCorrectly()
        {
            var rootName = FileSystemFixture.GetRootName();
            var rootDirectoryItems = fileSystemFixture.RootDirectoryItems;
            var subDirectoryItems = fileSystemFixture.SubDirectoryItems;

            var gatewayMock = mockingFixture.InitializeGetChildItemsAsync(rootName, @"\SubDir", rootDirectoryItems, subDirectoryItems);
            compositionFixture.ExportAsyncGateway(gatewayMock.Object);

            var result = new PipelineFixture().Invoke(new string[] {
                FileSystemFixture.NewDriveCommand,
                @"Resolve-Path X:\SubDir\Sub*"
            });

            Assert.AreEqual(subDirectoryItems.Count(i => i.Name.StartsWith("Sub", StringComparison.Ordinal)), result.Count, "Unexpected number of results");
            CollectionAssert.AllItemsAreInstancesOfType(result.Select(i => i.BaseObject).ToList(), typeof(PathInfo), "Result is not of type PathInfo");
            CollectionAssert.AreEqual(subDirectoryItems.Where(i => i.Name.StartsWith("Sub", StringComparison.Ordinal)).Select(i => @"X:" + i.Id).ToList(), result.Select(i => ((PathInfo)i.BaseObject).Path).ToList());
        }