private static Mock <ILanguageServerFacade> CreateMockLanguageServer(Action <ShowDocumentParams, CancellationToken> callback, ShowDocumentResult result, Container <WorkspaceFolder>?workspaceFolders = null)
        {
            var window = StrictMock.Of <IWindowLanguageServer>();

            window
            .Setup(m => m.SendNotification(It.IsAny <LogMessageParams>()));
            window
            .Setup(m => m.SendRequest <ShowDocumentResult>(It.IsAny <ShowDocumentParams>(), It.IsAny <CancellationToken>()))
            .Callback((IRequest <ShowDocumentResult> request, CancellationToken token) =>
            {
                var @params = (ShowDocumentParams)request;
                callback(@params, token);
            })
            .ReturnsAsync(() => result);

            var workspace = StrictMock.Of <IWorkspaceLanguageServer>();

            workspace
            .Setup(m => m.SendRequest <Container <WorkspaceFolder>?>(It.IsAny <WorkspaceFolderParams>(), It.IsAny <CancellationToken>()))
            .ReturnsAsync(() => workspaceFolders);

            var server = StrictMock.Of <ILanguageServerFacade>();

            server
            .Setup(m => m.Window)
            .Returns(window.Object);
            server
            .Setup(m => m.Workspace)
            .Returns(workspace.Object);

            return(server);
        }
Exemple #2
0
        public async Task WaitForDeploymentCompletionAsync_WithStatusMessage200Or201_ReturnsDeploymentSucceededMessage(int status)
        {
            var responseMessage = "sample response";

            var armDeploymentResourceResponse = StrictMock.Of <Response <ArmDeploymentResource> >();

            armDeploymentResourceResponse.Setup(m => m.GetRawResponse().Status).Returns(status);
            armDeploymentResourceResponse.Setup(m => m.ToString()).Returns(responseMessage);

            var armDeploymentResourceOperation = StrictMock.Of <ArmOperation <ArmDeploymentResource> >();

            armDeploymentResourceOperation.Setup(m => m.WaitForCompletionAsync(CancellationToken.None)).Returns(ValueTask.FromResult(armDeploymentResourceResponse.Object));
            armDeploymentResourceOperation.Setup(m => m.HasValue).Returns(true);

            var documentPath = "some_path";
            var deploymentId = "bicep_deployment";
            var deploymentOperationsCache = new DeploymentOperationsCache();

            deploymentOperationsCache.CacheDeploymentOperation(deploymentId, armDeploymentResourceOperation.Object);

            var bicepDeployWaitForCompletionResponse = await DeploymentHelper.WaitForDeploymentCompletionAsync(
                deploymentId,
                documentPath,
                deploymentOperationsCache);

            var expectedDeploymentOutputMessage = string.Format(LangServerResources.DeploymentSucceededMessage, documentPath);

            bicepDeployWaitForCompletionResponse.isSuccess.Should().BeTrue();
            bicepDeployWaitForCompletionResponse.outputMessage.Should().Be(expectedDeploymentOutputMessage);
        }
        public async Task CreateDeployment_WithExceptionWhileFetchingDeploymentCollection_ReturnsDeploymentFailedMessage()
        {
            var template = @"{
  ""$schema"": ""https://schema.management.azure.com/schemas/2019-04-01/deploymentTemplate.json#"",
  ""resources"": [
    {
      ""type"": ""Microsoft.Storage/storageAccounts"",
      ""apiVersion"": ""2021-06-01"",
      ""name"": ""storageaccount"",
      ""location"": ""[resourceGroup().location]"",
      ""properties"": {}
    }
  ]
}";
            var deploymentCollectionProvider = StrictMock.Of <IDeploymentCollectionProvider>();
            var errorMessage = "Encountered error while fetching deployments";

            deploymentCollectionProvider
            .Setup(m => m.GetDeploymentCollection(It.IsAny <ArmClient>(), It.IsAny <ResourceIdentifier>(), LanguageConstants.TargetScopeTypeResourceGroup))
            .Throws(new Exception(errorMessage));
            var documentPath = "some_path";

            var result = await DeploymentHelper.CreateDeployment(
                deploymentCollectionProvider.Object,
                CreateMockArmClient(),
                documentPath,
                template,
                string.Empty,
                "/subscriptions/07268dd7-4c50-434b-b1ff-67b8164edb41/resourceGroups/bhavyatest",
                LanguageConstants.TargetScopeTypeResourceGroup,
                "");

            result.Should().Be(string.Format(LangServerResources.DeploymentFailedWithExceptionMessage, documentPath, errorMessage));
        }
Exemple #4
0
        public async Task Publish_AggregateExceptionWithInnerRequestFailedExceptions_ShouldFail()
        {
            var dataSet          = DataSets.Empty;
            var outputDirectory  = dataSet.SaveFilesToTestDirectory(TestContext);
            var compiledFilePath = Path.Combine(outputDirectory, DataSet.TestFileMainCompiled);

            var client = StrictMock.Of <ContainerRegistryBlobClient>();

            client
            .Setup(m => m.UploadBlobAsync(It.IsAny <Stream>(), It.IsAny <CancellationToken>()))
            .ThrowsAsync(new AggregateException(new RequestFailedException("Mock registry request failure 1."), new RequestFailedException("Mock registry request failure 2.")));

            var clientFactory = StrictMock.Of <IContainerRegistryClientFactory>();

            clientFactory
            .Setup(m => m.CreateAuthenticatedBlobClient(It.IsAny <RootConfiguration>(), new Uri("https://fake"), "fake"))
            .Returns(client.Object);

            var templateSpecRepositoryFactory = StrictMock.Of <ITemplateSpecRepositoryFactory>();

            var settings = new InvocationSettings(BicepTestConstants.CreateFeaturesProvider(TestContext, registryEnabled: true), clientFactory.Object, templateSpecRepositoryFactory.Object);

            var(output, error, result) = await Bicep(settings, "publish", compiledFilePath, "--target", "br:fake/fake:v1");

            using (new AssertionScope())
            {
                error.Should().StartWith("Unable to publish module \"br:fake/fake:v1\": One or more errors occurred. (Mock registry request failure 1.) (Mock registry request failure 2.)");
                output.Should().BeEmpty();
                result.Should().Be(1);
            }
        }
        public async Task CreateDeployment_WithValidScopeAndInput_ReturnsDeploymentSucceededMessage(string scope, string location)
        {
            var template                     = @"{
  ""$schema"": ""https://schema.management.azure.com/schemas/2019-04-01/deploymentTemplate.json#"",
  ""resources"": [
    {
      ""type"": ""Microsoft.Storage/storageAccounts"",
      ""apiVersion"": ""2021-06-01"",
      ""name"": ""storageaccount"",
      ""location"": ""[resourceGroup().location]"",
      ""properties"": {}
    }
  ]
}";
            var deploymentCollection         = CreateDeploymentCollection(scope);
            var deploymentCollectionProvider = StrictMock.Of <IDeploymentCollectionProvider>();

            deploymentCollectionProvider
            .Setup(m => m.GetDeploymentCollection(It.IsAny <ArmClient>(), It.IsAny <ResourceIdentifier>(), scope))
            .Returns(deploymentCollection);
            var documentPath = "some_path";

            var result = await DeploymentHelper.CreateDeployment(
                deploymentCollectionProvider.Object,
                CreateMockArmClient(),
                documentPath,
                template,
                string.Empty,
                "/subscriptions/07268dd7-4c50-434b-b1ff-67b8164edb41/resourceGroups/bhavyatest",
                scope,
                location);

            result.Should().Be(string.Format(LangServerResources.DeploymentSucceededMessage, documentPath));
        }
Exemple #6
0
        public async Task LocalModuleReferenceShouldThrow()
        {
            var dispatcher = StrictMock.Of <IModuleDispatcher>();

            DiagnosticBuilder.ErrorBuilderDelegate?failureBuilder = null;

            const string ModuleRefStr = "./hello.bicep";
            var          localRef     = LocalModuleReference.TryParse(ModuleRefStr, out _);

            localRef.Should().NotBeNull();

            dispatcher.Setup(m => m.TryGetModuleReference(ModuleRefStr, It.IsAny <RootConfiguration>(), out failureBuilder)).Returns(localRef);

            var resolver = StrictMock.Of <IFileResolver>();

            var handler = new BicepRegistryCacheRequestHandler(dispatcher.Object, resolver.Object, ConfigurationManager);

            var @params = new BicepRegistryCacheParams("/foo/bar/main.bicep", ModuleRefStr);

            (await FluentActions
             .Awaiting(() => handler.Handle(@params, default))
             .Should()
             .ThrowAsync <InvalidOperationException>())
            .WithMessage($"The specified module reference '{ModuleRefStr}' refers to a local module which is not supported by textDocument/bicepCache requests.");
        }
Exemple #7
0
        public async Task GetModuleRestoreStatus_ConfigurationChanges_ReturnsCachedStatusWhenChangeIsIrrelevant(RootConfiguration changedConfiguration, ModuleRestoreStatus expectedStatus)
        {
            // Arrange.
            var badReference = new MockModuleReference("bad");

            var registryMock = StrictMock.Of <IModuleRegistry>();

            registryMock.SetupGet(x => x.Scheme).Returns("mock");
            registryMock.Setup(x => x.RestoreModules(It.IsAny <RootConfiguration>(), It.IsAny <IEnumerable <ModuleReference> >()))
            .ReturnsAsync(new Dictionary <ModuleReference, ErrorBuilderDelegate>
            {
                [badReference] = x => new ErrorDiagnostic(x.TextSpan, "RestoreFailure", "Failed to restore module.")
            });
            registryMock.Setup(x => x.IsModuleRestoreRequired(badReference))
            .Returns(true);

            var dispatcher    = CreateDispatcher(registryMock.Object);
            var configuration = BicepTestConstants.CreateMockConfiguration();

            await dispatcher.RestoreModules(configuration, new[] { badReference });

            // Act.
            var status = dispatcher.GetModuleRestoreStatus(badReference, changedConfiguration, out _);

            // Assert.
            status.Should().Be(expectedStatus);
        }
Exemple #8
0
        public async Task ExternalModuleFailedEntryPointShouldThrow()
        {
            var dispatcher = StrictMock.Of <IModuleDispatcher>();

            DiagnosticBuilder.ErrorBuilderDelegate?failureBuilder = null;
            const string UnqualifiedModuleRefStr = "example.azurecr.invalid/foo/bar:v3";
            const string ModuleRefStr            = "br:" + UnqualifiedModuleRefStr;

            var configuration   = ConfigurationManager.GetBuiltInConfiguration();
            var moduleReference = OciArtifactModuleReference.TryParse(null, UnqualifiedModuleRefStr, configuration, out _) !;

            moduleReference.Should().NotBeNull();

            dispatcher.Setup(m => m.TryGetModuleReference(ModuleRefStr, It.IsAny <RootConfiguration>(), out failureBuilder)).Returns(moduleReference);
            dispatcher.Setup(m => m.GetModuleRestoreStatus(moduleReference, configuration, out failureBuilder)).Returns(ModuleRestoreStatus.Succeeded);
            dispatcher.Setup(m => m.TryGetLocalModuleEntryPointUri(null, moduleReference, configuration, out failureBuilder)).Returns <Uri?>(null);

            var resolver = StrictMock.Of <IFileResolver>();

            var handler = new BicepRegistryCacheRequestHandler(dispatcher.Object, resolver.Object, ConfigurationManager);

            var @params = new BicepRegistryCacheParams("/main.bicep", ModuleRefStr);

            (await FluentActions
             .Awaiting(() => handler.Handle(@params, default))
             .Should()
             .ThrowAsync <InvalidOperationException>())
            .WithMessage($"Unable to obtain the entry point URI for module '{ModuleRefStr}'.");
        }
Exemple #9
0
        public async Task CreateDeployment_WithInvalidValidParameterFilePath_ReturnsDeploymentFailedMessage()
        {
            var template                     = @"{
  ""$schema"": ""https://schema.management.azure.com/schemas/2019-04-01/deploymentTemplate.json#"",
  ""resources"": [
    {
      ""type"": ""Microsoft.Storage/storageAccounts"",
      ""apiVersion"": ""2021-06-01"",
      ""name"": ""storageaccount"",
      ""location"": ""[resourceGroup().location]"",
      ""properties"": {}
    }
  ]
}";
            var deploymentCollection         = CreateDeploymentCollection(LanguageConstants.TargetScopeTypeSubscription);
            var deploymentCollectionProvider = StrictMock.Of <IDeploymentCollectionProvider>();

            deploymentCollectionProvider
            .Setup(m => m.GetDeploymentCollection(It.IsAny <ArmClient>(), It.IsAny <ResourceIdentifier>(), LanguageConstants.TargetScopeTypeSubscription))
            .Returns(deploymentCollection);

            var result = await DeploymentHelper.CreateDeployment(
                deploymentCollectionProvider.Object,
                CreateMockArmClient(),
                template,
                @"c:\parameter.json",
                "/subscriptions/07268dd7-4c50-434b-b1ff-67b8164edb41/resourceGroups/bhavyatest",
                LanguageConstants.TargetScopeTypeSubscription,
                "eastus");

            result.Should().Contain(string.Format(LangServerResources.InvalidParameterFileDeploymentFailedMessage, @"Could not find file"));
        }
        public async Task IfConfigExists_AndContainsRuleButNotLevel_ThenJustAddLevelAndSelect()
        {
            string bicepConfig = @"{
              ""analyzers"": {
                ""core"": {
                  ""verbose"": false,
                  ""enabled"": true,
                  ""rules"": {
                    ""no-unused-params"": {
                    }
                  }
                }
              }
            }";

            var(bicepPath, configPath) = CreateFiles(bicepConfig);

            string?selectedText = null;
            var    server       = CreateMockLanguageServer(
                (ShowDocumentParams @params, CancellationToken token) =>
            {
                @params.Uri.GetFileSystemPath().ToLowerInvariant().Should().Be(configPath.ToLowerInvariant());
                selectedText = GetSelectedTextFromFile(@params.Uri, @params.Selection);
            },
                new ShowDocumentResult()
            {
                Success = true
            });

            var telemetryProvider = BicepTestConstants.CreateMockTelemetryProvider();
            BicepEditLinterRuleCommandHandler bicepEditLinterRuleHandler = new(StrictMock.Of <ISerializer>().Object, server.Object, telemetryProvider.Object);
            await bicepEditLinterRuleHandler.Handle(new Uri(bicepPath), "no-unused-params", configPath, CancellationToken.None);

            selectedText.Should().Be("warning", "rule's current level value should be selected when the config file is opened");
        }
        public async Task CreateDeployment_WithInvalidScope_ReturnsDeploymentFailedMessage(string scope)
        {
            var armClient = CreateMockArmClient();
            var deploymentCollectionProvider = StrictMock.Of <IDeploymentCollectionProvider>();

            deploymentCollectionProvider
            .Setup(m => m.GetDeploymentCollection(It.IsAny <ArmClient>(), It.IsAny <ResourceIdentifier>(), scope))
            .Throws(new Exception(string.Format(LangServerResources.UnsupportedTargetScopeMessage, scope)));
            var documentPath = "some_path";

            var result = await DeploymentHelper.CreateDeployment(
                deploymentCollectionProvider.Object,
                armClient,
                documentPath,
                string.Empty,
                string.Empty,
                "/subscriptions/07268dd7-4c50-434b-b1ff-67b8164edb41",
                scope,
                string.Empty);

            var expectedDeploymentOutputMessage = string.Format(LangServerResources.DeploymentFailedWithExceptionMessage, documentPath,
                                                                string.Format(LangServerResources.UnsupportedTargetScopeMessage, scope));

            result.Should().Be(expectedDeploymentOutputMessage);
        }
        public async Task CreateDeployment_WithInvalidValidParameterFileContents_ReturnsDeploymentFailesMessage()
        {
            var template                     = @"{
  ""$schema"": ""https://schema.management.azure.com/schemas/2019-04-01/deploymentTemplate.json#"",
  ""resources"": [
    {
      ""type"": ""Microsoft.Storage/storageAccounts"",
      ""apiVersion"": ""2021-06-01"",
      ""name"": ""storageaccount"",
      ""location"": ""[resourceGroup().location]"",
      ""properties"": {}
    }
  ]
}";
            var deploymentCollection         = CreateDeploymentCollection(LanguageConstants.TargetScopeTypeSubscription);
            var deploymentCollectionProvider = StrictMock.Of <IDeploymentCollectionProvider>();

            deploymentCollectionProvider
            .Setup(m => m.GetDeploymentCollection(It.IsAny <ArmClient>(), It.IsAny <ResourceIdentifier>(), LanguageConstants.TargetScopeTypeSubscription))
            .Returns(deploymentCollection);
            string parametersFilePath = FileHelper.SaveResultFile(TestContext, "parameters.json", "invalid_parameters_file");
            var    documentPath       = "some_path";

            var result = await DeploymentHelper.CreateDeployment(
                deploymentCollectionProvider.Object,
                CreateMockArmClient(),
                documentPath,
                template,
                parametersFilePath,
                "/subscriptions/07268dd7-4c50-434b-b1ff-67b8164edb41/resourceGroups/bhavyatest",
                LanguageConstants.TargetScopeTypeSubscription,
                "eastus");

            result.Should().Be(string.Format(LangServerResources.InvalidParameterFileDeploymentFailedMessage, documentPath, @"'i' is an invalid start of a value. LineNumber: 0 | BytePositionInLine: 0."));
        }
Exemple #13
0
        public async Task WaitForDeploymentCompletionAsync_WhenCalled_RemovesDeployIdFromDeploymentOperationsCache()
        {
            var responseMessage = "sample response";

            var armDeploymentResourceResponse = StrictMock.Of <Response <ArmDeploymentResource> >();

            armDeploymentResourceResponse.Setup(m => m.GetRawResponse().Status).Returns(It.IsAny <int>);
            armDeploymentResourceResponse.Setup(m => m.ToString()).Returns(responseMessage);

            var armDeploymentResourceOperation = StrictMock.Of <ArmOperation <ArmDeploymentResource> >();

            armDeploymentResourceOperation.Setup(m => m.WaitForCompletionAsync(CancellationToken.None)).Returns(ValueTask.FromResult(armDeploymentResourceResponse.Object));
            armDeploymentResourceOperation.Setup(m => m.HasValue).Returns(true);

            var documentPath              = "some_path";
            var deploymentId1             = "bicep_deployment_1";
            var deploymentId2             = "bicep_deployment_2";
            var deploymentOperationsCache = new DeploymentOperationsCache();

            deploymentOperationsCache.CacheDeploymentOperation(deploymentId1, armDeploymentResourceOperation.Object);
            deploymentOperationsCache.CacheDeploymentOperation(deploymentId2, armDeploymentResourceOperation.Object);

            await DeploymentHelper.WaitForDeploymentCompletionAsync(
                deploymentId1,
                documentPath,
                deploymentOperationsCache);

            deploymentOperationsCache.FindAndRemoveDeploymentOperation(deploymentId1).Should().BeNull();
            deploymentOperationsCache.FindAndRemoveDeploymentOperation(deploymentId2).Should().NotBeNull();
        }
Exemple #14
0
        public async Task StartDeploymentAsync_WithInvalidScope_ReturnsDeploymentFailedMessage(string scope)
        {
            var armClient = CreateMockArmClient();
            var deploymentCollectionProvider = StrictMock.Of <IDeploymentCollectionProvider>();

            deploymentCollectionProvider
            .Setup(m => m.GetDeploymentCollection(It.IsAny <ArmClient>(), It.IsAny <ResourceIdentifier>(), scope))
            .Throws(new Exception(string.Format(LangServerResources.UnsupportedTargetScopeMessage, scope)));
            var documentPath = "some_path";

            var bicepDeployStartResponse = await DeploymentHelper.StartDeploymentAsync(
                deploymentCollectionProvider.Object,
                armClient,
                documentPath,
                string.Empty,
                string.Empty,
                "/subscriptions/07268dd7-4c50-434b-b1ff-67b8164edb41",
                scope,
                string.Empty,
                string.Empty,
                string.Empty,
                ParametersFileUpdateOption.None,
                new List <BicepUpdatedDeploymentParameter>(),
                "https://portal.azure.com",
                "bicep_deployment",
                new DeploymentOperationsCache());

            var expectedDeploymentOutputMessage = string.Format(LangServerResources.DeploymentFailedWithExceptionMessage, documentPath,
                                                                string.Format(LangServerResources.UnsupportedTargetScopeMessage, scope));

            bicepDeployStartResponse.isSuccess.Should().BeFalse();
            bicepDeployStartResponse.outputMessage.Should().Be(expectedDeploymentOutputMessage);
            bicepDeployStartResponse.viewDeploymentInPortalMessage.Should().BeNull();
        }
Exemple #15
0
        public void GetConfiguration_ConfigurationFileNotReadable_ThrowsCouldNotLoadConfigurationException()
        {
            // Arrange.
            var configurataionPath = CreatePath("path/to/bicepconfig.json");
            var fileSystem         = new MockFileSystem(new Dictionary <string, MockFileData>
            {
                [configurataionPath] = "",
            });

            var fileSystemMock = StrictMock.Of <IFileSystem>();

            fileSystemMock.SetupGet(x => x.Path).Returns(fileSystem.Path);
            fileSystemMock.SetupGet(x => x.Directory).Returns(fileSystem.Directory);
            fileSystemMock.SetupGet(x => x.File).Returns(fileSystem.File);
            fileSystemMock.Setup(x => x.FileStream.Create(It.IsAny <string>(), It.IsAny <FileMode>(), It.IsAny <FileAccess>()))
            .Throws(new UnauthorizedAccessException("Not allowed."));

            var sut           = new ConfigurationManager(fileSystemMock.Object);
            var sourceFileUri = new Uri(CreatePath("path/to/main.bicep"));

            // Act & Assert.
            FluentActions.Invoking(() => sut.GetConfiguration(sourceFileUri)).Should()
            .Throw <ConfigurationException>()
            .WithMessage($"Could not load the Bicep configuration file \"{configurataionPath}\": \"Not allowed.\".");
        }
Exemple #16
0
        public async Task RestoredValidModuleShouldReturnSuccessfully()
        {
            var dispatcher = StrictMock.Of <IModuleDispatcher>();

            // needed for mocking out parameters
            DiagnosticBuilder.ErrorBuilderDelegate?nullBuilder        = null;
            DiagnosticBuilder.ErrorBuilderDelegate?readFailureBuilder = x => x.ErrorOccurredReadingFile("Mock file read failure.");
            string?fileContents = "mock file contents";

            const string UnqualifiedModuleRefStr = "example.azurecr.invalid/foo/bar:v3";
            const string ModuleRefStr            = "br:" + UnqualifiedModuleRefStr;

            var moduleReference = OciArtifactModuleReference.TryParse(null, UnqualifiedModuleRefStr, ConfigurationManager.GetBuiltInConfiguration(), out _) !;

            moduleReference.Should().NotBeNull();

            var fileUri = new Uri("file:///main.bicep");

            dispatcher.Setup(m => m.TryGetModuleReference(ModuleRefStr, It.IsAny <RootConfiguration>(), out nullBuilder)).Returns(moduleReference);
            dispatcher.Setup(m => m.GetModuleRestoreStatus(moduleReference, out nullBuilder)).Returns(ModuleRestoreStatus.Succeeded);
            dispatcher.Setup(m => m.TryGetLocalModuleEntryPointUri(null, moduleReference, out nullBuilder)).Returns(fileUri);

            var resolver = StrictMock.Of <IFileResolver>();

            resolver.Setup(m => m.TryRead(fileUri, out fileContents, out nullBuilder)).Returns(true);

            var handler = new BicepRegistryCacheRequestHandler(dispatcher.Object, resolver.Object, ConfigurationManager);

            var @params  = new BicepRegistryCacheParams(ModuleRefStr);
            var response = await handler.Handle(@params, default);

            response.Should().NotBeNull();
            response.Content.Should().Be(fileContents);
        }
Exemple #17
0
        public async Task ExternalModuleNotInCacheShouldThrow()
        {
            var dispatcher = StrictMock.Of <IModuleDispatcher>();

            DiagnosticBuilder.ErrorBuilderDelegate?failureBuilder = null;
            const string UnqualifiedModuleRefStr = "example.azurecr.invalid/foo/bar:v3";
            const string ModuleRefStr            = "br:" + UnqualifiedModuleRefStr;

            var moduleReference = OciArtifactModuleReference.TryParse(null, UnqualifiedModuleRefStr, ConfigurationManager.GetBuiltInConfiguration(), out _) !;

            moduleReference.Should().NotBeNull();

            dispatcher.Setup(m => m.TryGetModuleReference(ModuleRefStr, It.IsAny <RootConfiguration>(), out failureBuilder)).Returns(moduleReference);
            dispatcher.Setup(m => m.GetModuleRestoreStatus(moduleReference, out failureBuilder)).Returns(ModuleRestoreStatus.Unknown);

            var resolver = StrictMock.Of <IFileResolver>();

            var handler = new BicepRegistryCacheRequestHandler(dispatcher.Object, resolver.Object, ConfigurationManager);

            var @params = new BicepRegistryCacheParams(ModuleRefStr);

            (await FluentActions
             .Awaiting(() => handler.Handle(@params, default))
             .Should()
             .ThrowAsync <InvalidOperationException>())
            .WithMessage($"The module '{ModuleRefStr}' has not yet been successfully restored.");
        }
Exemple #18
0
    public static Mock <T> StrictMock <T>(this IServiceCollection services) where T : class
    {
        var mock = new StrictMock <T>();

        services.AddSingleton <Mock <T> >(mock);
        services.AddSingleton(mock.Object);
        return(mock);
    }
Exemple #19
0
        public static IProcessProxy CreateProcessProxy(int exitCode = 0, string standardOutput = "", string standardError = "")
        {
            var proxyMock      = StrictMock.Of <IProcessProxy>();
            var proxyMockSetup = proxyMock.Setup(x => x.Start(It.IsAny <string>(), It.IsAny <string>()))
                                 .Returns((exitCode, standardOutput, standardError));

            return(proxyMock.Object);
        }
        private static IModuleDispatcher CreateDispatcher(params IModuleRegistry[] registries)
        {
            var provider = StrictMock.Of <IModuleRegistryProvider>();

            provider.Setup(m => m.Registries).Returns(registries.ToImmutableArray());

            return(new ModuleDispatcher(provider.Object));
        }
Exemple #21
0
        public async Task Restore_ByDigest_ShouldSucceed()
        {
            var registry    = "example.com";
            var registryUri = new Uri("https://" + registry);
            var repository  = "hello/there";

            var client = new MockRegistryBlobClient();

            var clientFactory = StrictMock.Of <IContainerRegistryClientFactory>();

            clientFactory.Setup(m => m.CreateAuthenticatedBlobClient(It.IsAny <RootConfiguration>(), registryUri, repository)).Returns(client);

            var templateSpecRepositoryFactory = BicepTestConstants.TemplateSpecRepositoryFactory;

            var settings = new InvocationSettings(BicepTestConstants.CreateFeaturesProvider(TestContext, registryEnabled: true), clientFactory.Object, BicepTestConstants.TemplateSpecRepositoryFactory);

            var tempDirectory = FileHelper.GetUniqueTestOutputPath(TestContext);

            Directory.CreateDirectory(tempDirectory);

            var publishedBicepFilePath = Path.Combine(tempDirectory, "published.bicep");

            File.WriteAllText(publishedBicepFilePath, string.Empty);

            var(publishOutput, publishError, publishResult) = await Bicep(settings, "publish", publishedBicepFilePath, "--target", $"br:{registry}/{repository}:v1");

            using (new AssertionScope())
            {
                publishResult.Should().Be(0);
                publishOutput.Should().BeEmpty();
                publishError.Should().BeEmpty();
            }

            client.Blobs.Should().HaveCount(2);
            client.Manifests.Should().HaveCount(1);
            client.ManifestTags.Should().HaveCount(1);

            string digest = client.Manifests.Single().Key;

            var bicep = $@"
module empty 'br:{registry}/{repository}@{digest}' = {{
  name: 'empty'
}}
";

            var restoreBicepFilePath = Path.Combine(tempDirectory, "restored.bicep");

            File.WriteAllText(restoreBicepFilePath, bicep);

            var(output, error, result) = await Bicep(settings, "restore", restoreBicepFilePath);

            using (new AssertionScope())
            {
                result.Should().Be(0);
                output.Should().BeEmpty();
                error.Should().BeEmpty();
            }
        }
        private static Response <T> CreateMockResponse <T>(T value)
        {
            var responseMock = StrictMock.Of <Response <T> >();

            responseMock.SetupGet(m => m.Value).Returns(value);
            responseMock.Setup(m => m.GetRawResponse()).Returns(StrictMock.Of <Response>().Object);

            return(responseMock.Object);
        }
Exemple #23
0
        private static ArmClient CreateMockClient(TemplateSpecVersionResource resource)
        {
            var clientMock = StrictMock.Of <ArmClient>();

            clientMock.Setup(x => x.GetResourceClient(It.IsAny <Func <TemplateSpecVersionResource> >()))
            .Returns(resource);

            return(clientMock.Object);
        }
Exemple #24
0
        public static IProcessProxy CreateProcessProxy(Action?onSuccess)
        {
            var proxyMock      = StrictMock.Of <IProcessProxy>();
            var proxyMockSetup = proxyMock.Setup(x => x.Start(It.IsAny <string>(), It.IsAny <string>()))
                                 .Returns((0, "", ""))
                                 .Callback(onSuccess);

            return(proxyMock.Object);
        }
        public async Task IfConfigExists_AndContainsRuleAlready_ThenJustShowAndSelect()
        {
            string bicepConfig = @"{
              ""analyzers"": {
                ""core"": {
                  ""verbose"": false,
                  ""enabled"": true,
                  ""rules"": {
                    ""whatever"": {
                      ""level"": ""error""
                    },
                    ""no-unused-params"": {
                      ""level"": ""no-unused-params-current-level""
                    }
                  }
                }
              }
            }";

            var(bicepPath, configPath) = CreateFiles(bicepConfig);

            string?selectedText = null;
            var    server       = CreateMockLanguageServer(
                (ShowDocumentParams @params, CancellationToken token) =>
            {
                @params.Uri.GetFileSystemPath().ToLowerInvariant().Should().Be(configPath.ToLowerInvariant());
                selectedText = GetSelectedTextFromFile(@params.Uri, @params.Selection);
            },
                new ShowDocumentResult()
            {
                Success = true
            });

            var telemetryProvider  = StrictMock.Of <ITelemetryProvider>();
            BicepTelemetryEvent?ev = null;

            telemetryProvider.Setup(x => x.PostEvent(It.IsAny <BicepTelemetryEvent>()))
            .Callback((BicepTelemetryEvent e) =>
            {
                ev = e;
            });

            BicepEditLinterRuleCommandHandler bicepEditLinterRuleHandler = new(StrictMock.Of <ISerializer>().Object, server.Object, telemetryProvider.Object);
            await bicepEditLinterRuleHandler.Handle(new Uri(bicepPath), "no-unused-params", configPath, CancellationToken.None);

            selectedText.Should().Be("no-unused-params-current-level", "rule's current level value should be selected when the config file is opened");
            ev.Should().NotBeNull();
            ev !.EventName.Should().Be(TelemetryConstants.EventNames.EditLinterRule);
            ev.Properties.Should().Contain(new Dictionary <string, string> {
                { "code", "no-unused-params" },
                { "newConfigFile", "false" },
                { "newRuleAdded", "false" },
                { "error", string.Empty },
                { "result", Result.Succeeded },
            });
        }
Exemple #26
0
        private static TemplateSpecVersionResource CreateMockTemplateSpecVersionResource(params Action <Mock <TemplateSpecVersionResource> >[] setUpTemplateSpecVersionMockActions)
        {
            var templateSpecVersionMock = StrictMock.Of <TemplateSpecVersionResource>();

            foreach (var action in setUpTemplateSpecVersionMockActions)
            {
                action.Invoke(templateSpecVersionMock);
            }

            return(templateSpecVersionMock.Object);
        }
        public async Task CreateDeployment_WithStatusMessageOtherThan200Or201_ReturnsDeploymentFailedMessage()
        {
            var template = @"{
  ""$schema"": ""https://schema.management.azure.com/schemas/2019-04-01/deploymentTemplate.json#"",
  ""resources"": [
    {
      ""type"": ""Microsoft.Storage/storageAccounts"",
      ""apiVersion"": ""2021-06-01"",
      ""name"": ""storageaccount"",
      ""location"": ""[resourceGroup().location]"",
      ""properties"": {}
    }
  ]
}";
            var response = StrictMock.Of <Response>();

            response.Setup(m => m.Status).Returns(502);
            var responseMessage = "sample response";

            response.Setup(m => m.ToString()).Returns(responseMessage);

            var deploymentCreateOrUpdateOperation = StrictMock.Of <DeploymentCreateOrUpdateOperation>();

            deploymentCreateOrUpdateOperation.Setup(m => m.HasValue).Returns(true);
            deploymentCreateOrUpdateOperation.Setup(m => m.GetRawResponse()).Returns(response.Object);

            var deploymentCollection = StrictMock.Of <DeploymentCollection>();

            deploymentCollection
            .Setup(m => m.CreateOrUpdateAsync(
                       It.IsAny <bool>(),
                       It.IsAny <string>(),
                       It.IsAny <DeploymentInput>(),
                       It.IsAny <CancellationToken>())).Returns(Task.FromResult(deploymentCreateOrUpdateOperation.Object));

            var deploymentCollectionProvider = StrictMock.Of <IDeploymentCollectionProvider>();

            deploymentCollectionProvider
            .Setup(m => m.GetDeploymentCollection(It.IsAny <ArmClient>(), It.IsAny <ResourceIdentifier>(), LanguageConstants.TargetScopeTypeResourceGroup))
            .Returns(deploymentCollection.Object);
            var documentPath = "some_path";

            var result = await DeploymentHelper.CreateDeployment(
                deploymentCollectionProvider.Object,
                CreateMockArmClient(),
                documentPath,
                template,
                string.Empty,
                "/subscriptions/07268dd7-4c50-434b-b1ff-67b8164edb41/resourceGroups/bhavyatest",
                LanguageConstants.TargetScopeTypeResourceGroup,
                "");

            result.Should().Be(string.Format(LangServerResources.DeploymentFailedWithExceptionMessage, documentPath, responseMessage));
        }
Exemple #28
0
        public async Task StartDeploymentAsync_WithExceptionWhileCreatingDeployment_ReturnsDeploymentFailedMessage()
        {
            var template             = @"{
  ""$schema"": ""https://schema.management.azure.com/schemas/2019-04-01/deploymentTemplate.json#"",
  ""resources"": [
    {
      ""type"": ""Microsoft.Storage/storageAccounts"",
      ""apiVersion"": ""2021-06-01"",
      ""name"": ""storageaccount"",
      ""location"": ""[resourceGroup().location]"",
      ""properties"": {}
    }
  ]
}";
            var deploymentCollection = StrictMock.Of <ArmDeploymentCollection>();
            var errorMessage         = "Encountered error while creating deployment";

            deploymentCollection
            .Setup(m => m.CreateOrUpdateAsync(
                       It.IsAny <WaitUntil>(),
                       It.IsAny <string>(),
                       It.IsAny <ArmDeploymentContent>(),
                       It.IsAny <CancellationToken>()))
            .Throws(new Exception(errorMessage));
            var deploymentCollectionProvider = StrictMock.Of <IDeploymentCollectionProvider>();

            deploymentCollectionProvider
            .Setup(m => m.GetDeploymentCollection(It.IsAny <ArmClient>(), It.IsAny <ResourceIdentifier>(), LanguageConstants.TargetScopeTypeResourceGroup))
            .Returns(deploymentCollection.Object);
            var documentPath = "some_path";

            var bicepDeployStartResponse = await DeploymentHelper.StartDeploymentAsync(
                deploymentCollectionProvider.Object,
                CreateMockArmClient(),
                documentPath,
                template,
                string.Empty,
                "/subscriptions/07268dd7-4c50-434b-b1ff-67b8164edb41/resourceGroups/bhavyatest",
                LanguageConstants.TargetScopeTypeResourceGroup,
                "",
                string.Empty,
                string.Empty,
                ParametersFileUpdateOption.None,
                new List <BicepUpdatedDeploymentParameter>(),
                "https://portal.azure.com",
                "bicep_deployment",
                new DeploymentOperationsCache());

            var expectedDeploymentOutputMessage = string.Format(LangServerResources.DeploymentFailedWithExceptionMessage, documentPath, errorMessage);

            bicepDeployStartResponse.isSuccess.Should().BeFalse();
            bicepDeployStartResponse.outputMessage.Should().Be(expectedDeploymentOutputMessage);
            bicepDeployStartResponse.viewDeploymentInPortalMessage.Should().BeNull();
        }
Exemple #29
0
        private static Response <TemplateSpecVersionResource> CreateMockResponse(string content)
        {
            var rawResponseMock = StrictMock.Of <Response>();

            rawResponseMock.SetupGet(x => x.Content).Returns(BinaryData.FromString(content));

            var responseMock = StrictMock.Of <Response <TemplateSpecVersionResource> >();

            responseMock.Setup(m => m.GetRawResponse()).Returns(rawResponseMock.Object);

            return(responseMock.Object);
        }
Exemple #30
0
        public async Task StartDeploymentAsync_WithValidScopeAndInput_ShouldUpdateDeploymentOperationsCache()
        {
            var template = @"{
  ""$schema"": ""https://schema.management.azure.com/schemas/2019-04-01/deploymentTemplate.json#"",
  ""resources"": [
    {
      ""type"": ""Microsoft.Storage/storageAccounts"",
      ""apiVersion"": ""2021-06-01"",
      ""name"": ""storageaccount"",
      ""location"": ""[resourceGroup().location]"",
      ""properties"": {}
    }
  ]
}";

            var armDeploymentResourceOperation = StrictMock.Of <ArmOperation <ArmDeploymentResource> >().Object;
            var deploymentCollection           = StrictMock.Of <ArmDeploymentCollection>();

            deploymentCollection
            .Setup(m => m.CreateOrUpdateAsync(
                       It.IsAny <WaitUntil>(),
                       It.IsAny <string>(),
                       It.IsAny <ArmDeploymentContent>(),
                       It.IsAny <CancellationToken>())).Returns(Task.FromResult(armDeploymentResourceOperation));

            var deploymentCollectionProvider = StrictMock.Of <IDeploymentCollectionProvider>();

            deploymentCollectionProvider
            .Setup(m => m.GetDeploymentCollection(It.IsAny <ArmClient>(), It.IsAny <ResourceIdentifier>(), LanguageConstants.TargetScopeTypeSubscription))
            .Returns(deploymentCollection.Object);

            var deploymentOperationsCache = new DeploymentOperationsCache();
            var deployId = "bicep_deployment1";

            var bicepDeployStartResponse = await DeploymentHelper.StartDeploymentAsync(
                deploymentCollectionProvider.Object,
                CreateMockArmClient(),
                "some_path",
                template,
                string.Empty,
                "/subscriptions/07268dd7-4c50-434b-b1ff-67b8164edb41/resourceGroups/bhavyatest",
                LanguageConstants.TargetScopeTypeSubscription,
                "eastus",
                deployId,
                string.Empty,
                ParametersFileUpdateOption.None,
                new List <BicepUpdatedDeploymentParameter>(),
                "https://portal.azure.com",
                "deployment_name",
                deploymentOperationsCache);

            deploymentOperationsCache.FindAndRemoveDeploymentOperation(deployId).Should().NotBeNull();
        }