Exemple #1
0
 public OpenApiSteps(
     ScenarioContext scenarioContext,
     FeatureContext featureContext)
 {
     this.scenarioContext = scenarioContext;
     this.serviceProvider = ContainerBindings.GetServiceProvider(featureContext);
 }
        public async Task WhenIUseTheOperationsControlClientToCreateAnOperation(Table table)
        {
            string idName           = table.Rows[0]["IdName"];
            Guid   id               = this.ScenarioContext.Get <Guid>(idName);
            string resourceLocation = table.Rows[0]["ResourceLocation"];
            long   expireAfter      = long.Parse(table.Rows[0]["ExpireAfter"]);
            string body             = table.Rows[0]["Body"];

            IServiceProvider         serviceProvider = ContainerBindings.GetServiceProvider(this.FeatureContext);
            IMarainOperationsControl client          = serviceProvider.GetRequiredService <IMarainOperationsControl>();
            var transientTenantManager = TransientTenantManager.GetInstance(this.FeatureContext);

            await Exceptions.ExecuteAndStoreExceptionAsync(
                this.ScenarioContext,
                async() =>
            {
                CreateOperationHeaders result = await client.CreateOperationAsync(
                    transientTenantManager.PrimaryTransientClient.Id,
                    id,
                    resourceLocation,
                    expireAfter,
                    body).ConfigureAwait(false);

                this.ScenarioContext.Set(result);
            }).ConfigureAwait(false);
        }
Exemple #3
0
        private static EnrollmentConfigurationItem[] GetClaimsConfig(FeatureContext featureContext)
        {
            IConfiguration configuration = ContainerBindings
                                           .GetServiceProvider(featureContext)
                                           .GetRequiredService <IConfiguration>();

            // Load the config items we need:
            BlobStorageConfiguration claimPermissionsStoreStorageConfiguration =
                configuration.GetSection("TestBlobStorageConfiguration").Get <BlobStorageConfiguration>()
                ?? new BlobStorageConfiguration();

            claimPermissionsStoreStorageConfiguration.Container = "claimpermissions";

            BlobStorageConfiguration resourceAccessRuleSetsStoreStorageConfiguration =
                configuration.GetSection("TestBlobStorageConfiguration").Get <BlobStorageConfiguration>()
                ?? new BlobStorageConfiguration();

            resourceAccessRuleSetsStoreStorageConfiguration.Container = "resourceaccessrulesets";

            return(new EnrollmentConfigurationItem[]
            {
                new EnrollmentBlobStorageConfigurationItem
                {
                    Key = "claimPermissionsStore",
                    Configuration = claimPermissionsStoreStorageConfiguration,
                },
                new EnrollmentBlobStorageConfigurationItem
                {
                    Key = "resourceAccessRuleSetsStore",
                    Configuration = resourceAccessRuleSetsStoreStorageConfiguration,
                },
            });
        }
        public static async Task SetupCosmosDbAccountKeys(FeatureContext featureContext)
        {
            IServiceProvider   serviceProvider = ContainerBindings.GetServiceProvider(featureContext);
            IConfigurationRoot configRoot      = serviceProvider.GetRequiredService <IConfigurationRoot>();

            CosmosDbSettings settings = configRoot.Get <CosmosDbSettings>();

            if (settings.CosmosDbKeySecretName == null)
            {
                throw new NullReferenceException("CosmosDbKeySecretName must be set in config.");
            }

            string keyVaultName = configRoot["KeyVaultName"];

            string secret = await SecretHelper.GetSecretFromConfigurationOrKeyVaultAsync(
                configRoot,
                "kv:" + settings.CosmosDbKeySecretName,
                keyVaultName,
                settings.CosmosDbKeySecretName).ConfigureAwait(false);

            string partitionKeyPath = configRoot["CosmosDbPartitionKeyPath"];

            featureContext.Set(partitionKeyPath, CosmosDbContextKeys.PartitionKeyPath);
            featureContext.Set(settings);
            featureContext.Set(secret, CosmosDbContextKeys.AccountKey);
        }
Exemple #5
0
        public static void WriteOutput(FeatureContext featureContext)
        {
            ILogger <FunctionsController> logger = ContainerBindings.GetServiceProvider(featureContext).GetRequiredService <ILogger <FunctionsController> >();
            FunctionsController           functionsController = FunctionsBindings.GetFunctionsController(featureContext);

            logger.LogAllAndClear(functionsController.GetFunctionsOutput());
        }
Exemple #6
0
        public async Task WhenIAcquireTheLease()
        {
            var policy = this.scenarioContext.Get <LeasePolicy>();

            Lease lease         = null;
            var   leaseProvider = ContainerBindings.GetServiceProvider(this.featureContext).GetRequiredService <ILeaseProvider>();

            try
            {
                if (!this.scenarioContext.TryGetValue(out lease))
                {
                    lease = await leaseProvider.AcquireAsync(policy);

                    this.scenarioContext.Set(lease);
                }
                else
                {
                    lease = await leaseProvider.AcquireAsync(policy);
                }
            }
            catch (AggregateException ex)
            {
                this.scenarioContext.Add("AggregateException", ex);
            }
            catch (Exception ex)
            {
                this.scenarioContext.Add("Exception", ex);
            }

            this.scenarioContext.Set(lease);
        }
        public ApiSteps(FeatureContext featureContext, ScenarioContext scenarioContext)
        {
            this.featureContext  = featureContext;
            this.scenarioContext = scenarioContext;

            this.serviceProvider = ContainerBindings.GetServiceProvider(this.featureContext);
        }
        public static async Task ClearDownTransientTenantContentStore(FeatureContext context)
        {
            ITenant          transientTenant = TransientTenantManager.GetInstance(context).PrimaryTransientClient;
            IServiceProvider serviceProvider = ContainerBindings.GetServiceProvider(context);

            if (transientTenant != null && serviceProvider != null)
            {
                await context.RunAndStoreExceptionsAsync(async() =>
                {
                    ITenantedWorkflowStoreFactory workflowStoreFactory = serviceProvider.GetRequiredService <ITenantedWorkflowStoreFactory>();
                    IWorkflowStore workflowStore = await workflowStoreFactory.GetWorkflowStoreForTenantAsync(transientTenant).ConfigureAwait(false);
                    if (workflowStore is CosmosWorkflowStore cosmosWorkflowStore)
                    {
                        await cosmosWorkflowStore.Container.DeleteContainerAsync().ConfigureAwait(false);
                    }
                }).ConfigureAwait(false);

                await context.RunAndStoreExceptionsAsync(async() =>
                {
                    ITenantedWorkflowInstanceStoreFactory workflowInstanceStoreFactory = serviceProvider.GetRequiredService <ITenantedWorkflowInstanceStoreFactory>();
                    var workflowInstanceStore = (CosmosWorkflowInstanceStore)await workflowInstanceStoreFactory.GetWorkflowInstanceStoreForTenantAsync(transientTenant).ConfigureAwait(false);
                    await workflowInstanceStore.Container.DeleteContainerAsync().ConfigureAwait(false);
                }).ConfigureAwait(false);
            }
        }
        public static async Task SetupCosmosDbDatabaseForFeature(FeatureContext featureContext)
        {
            CosmosDbSettings settings = featureContext.Get <CosmosDbSettings>();

            if (settings.CosmosDbAccountUri == null)
            {
                throw new NullReferenceException("CosmosDbAccountUri must be set in config.");
            }

            ICosmosClientBuilderFactory clientBuilderFactory = ContainerBindings.GetServiceProvider(featureContext).GetRequiredService <ICosmosClientBuilderFactory>();

            string accountKey = featureContext.Get <string>(CosmosDbContextKeys.AccountKey);

            CosmosClientBuilder builder;

            if (clientBuilderFactory is null)
            {
                builder = new CosmosClientBuilder(settings.CosmosDbAccountUri, accountKey);
            }
            else
            {
                builder = clientBuilderFactory.CreateCosmosClientBuilder(settings.CosmosDbAccountUri, accountKey);
            }

            builder = builder
                      .WithConnectionModeDirect();

            CosmosClient client   = builder.Build();
            Database     database = await client.CreateDatabaseIfNotExistsAsync(settings.CosmosDbDatabaseName, settings.CosmosDbDefaultOfferThroughput).ConfigureAwait(false);

            featureContext.Set(client, CosmosDbContextKeys.CosmosDbClient);
            featureContext.Set(database, CosmosDbContextKeys.CosmosDbDatabase);
        }
        public async Task ThenTheWorkflowInstanceWithIdShouldContainContextItems(string instanceId, Table expectedContextItems)
        {
            ITenantedWorkflowInstanceStoreFactory instanceStoreFactory = ContainerBindings.GetServiceProvider(this.featureContext)
                                                                         .GetService <ITenantedWorkflowInstanceStoreFactory>();

            ITenantProvider tenantProvider = ContainerBindings.GetServiceProvider(this.featureContext)
                                             .GetService <ITenantProvider>();

            IWorkflowInstanceStore instanceStore = await instanceStoreFactory.GetWorkflowInstanceStoreForTenantAsync(tenantProvider.Root).ConfigureAwait(false);

            WorkflowInstance instance = await WorkflowRetryHelper.ExecuteWithStandardTestRetryRulesAsync(
                () => instanceStore.GetWorkflowInstanceAsync(instanceId)).ConfigureAwait(false);

            Assert.AreEqual(
                expectedContextItems.Rows.Count,
                instance.Context.Count,
                "The number of context items in the workflow instance is different to the number of items in the specified list");

            foreach (TableRow current in expectedContextItems.Rows)
            {
                Assert.IsTrue(
                    instance.Context.TryGetValue(current[0], out string actualValue),
                    $"The instance context does not contain expected item with key '{current[0]}'");

                Assert.AreEqual(current[1], actualValue, $"The instance context does not contain the expected value for key '{current[0]}'");
            }
        }
        public async Task GivenIHaveCreatedAndPersistedANewInstanceOfTheDataCatalogWorkflowWithId(string workflowId)
        {
            IWorkflowMessageQueue workflowMessageQueue =
                ContainerBindings.GetServiceProvider(this.featureContext).GetService <IWorkflowMessageQueue>();
            Workflow workflow = DataCatalogWorkflowFactory.Create(workflowId, workflowMessageQueue);

            ITenantedWorkflowStoreFactory storeFactory =
                ContainerBindings.GetServiceProvider(this.featureContext).GetService <ITenantedWorkflowStoreFactory>();
            ITenantProvider tenantProvider =
                ContainerBindings.GetServiceProvider(this.featureContext).GetService <ITenantProvider>();

            IWorkflowStore store = await storeFactory.GetWorkflowStoreForTenantAsync(tenantProvider.Root).ConfigureAwait(false);

            await WorkflowRetryHelper.ExecuteWithStandardTestRetryRulesAsync(async() =>
            {
                try
                {
                    Workflow oldWorkflow = await store.GetWorkflowAsync(workflowId).ConfigureAwait(false);
                    workflow.ETag        = oldWorkflow.ETag;
                }
                catch (WorkflowNotFoundException)
                {
                    // Don't care if there is no old workflow.
                }

                await store.UpsertWorkflowAsync(workflow).ConfigureAwait(false);
            }).ConfigureAwait(false);
        }
        public static async Task CreateContentStateTestData(FeatureContext featureContext)
        {
            ITenantedContentStoreFactory contentStoreFactory = ContainerBindings.GetServiceProvider(featureContext).GetRequiredService <ITenantedContentStoreFactory>();
            IContentStore store = await contentStoreFactory.GetContentStoreForTenantAsync(featureContext.GetCurrentTenantId()).ConfigureAwait(false);

            for (int i = 0; i < 30; i++)
            {
                var state = new ContentState
                {
                    Id         = Guid.NewGuid().ToString(),
                    ContentId  = SpecHelpers.ParseSpecValue <string>(featureContext, $"{{Content{i}.Id}}"),
                    Slug       = SpecHelpers.ParseSpecValue <string>(featureContext, $"{{Content{i}.Slug}}"),
                    WorkflowId = "workflow1id",
                    ChangedBy  = new CmsIdentity(Guid.NewGuid().ToString(), Guid.NewGuid().ToString()),
                };

                if (i < 4)
                {
                    state.StateName = "draft";
                }
                else if (i < 29)
                {
                    state.StateName = "published";
                }
                else
                {
                    state.StateName = "archived";
                }

                ContentState storedContentState = await store.SetContentWorkflowStateAsync(state.Slug, state.ContentId, state.WorkflowId, state.StateName, state.ChangedBy).ConfigureAwait(false);

                featureContext.Set(storedContentState, $"Content{i}-State");
            }
        }
        public static async Task CreateContentTestData(FeatureContext featureContext)
        {
            ITenantedContentStoreFactory contentStoreFactory = ContainerBindings.GetServiceProvider(featureContext).GetRequiredService <ITenantedContentStoreFactory>();
            IContentStore store = await contentStoreFactory.GetContentStoreForTenantAsync(featureContext.GetCurrentTenantId()).ConfigureAwait(false);

            for (int i = 0; i < 30; i++)
            {
                var content = new Content
                {
                    Id   = Guid.NewGuid().ToString(),
                    Slug = "slug",
                    Tags = new List <string> {
                        "First tag", "Second tag"
                    },
                    CategoryPaths = new List <string> {
                        "/standard/content;", "/books/hobbit;", "/books/lotr"
                    },
                    Author      = new CmsIdentity(Guid.NewGuid().ToString(), "Bilbo Baggins"),
                    Title       = "This is the title",
                    Description = "A description of the content",
                    Culture     = CultureInfo.GetCultureInfo("en-GB"),
                };

                Content storedContent = await store.StoreContentAsync(content).ConfigureAwait(false);

                featureContext.Set(storedContent, "Content" + i);
            }
        }
Exemple #14
0
        public void GivenIAddAnEmbeddedResourceToTheHalDocumentT()
        {
            HalDocument         document           = this.scenarioContext.Get <HalDocument>();
            IHalDocumentFactory halDocumentFactory = ContainerBindings.GetServiceProvider(this.scenarioContext).GetService <IHalDocumentFactory>();

            document.AddEmbeddedResource("somerel", halDocumentFactory.CreateHalDocument());
        }
Exemple #15
0
        public void GivenIHaveCreatedAnInstanceOfHalDocumentFromTheDomainClass()
        {
            IHalDocumentFactory halDocumentFactory = ContainerBindings.GetServiceProvider(this.scenarioContext).GetService <IHalDocumentFactory>();
            HalDocument         halDocument        = halDocumentFactory.CreateHalDocumentFrom(this.scenarioContext.Get <TestDomainClass>());

            this.scenarioContext.Set(halDocument);
        }
Exemple #16
0
        public void WhenISerializeTheContentObjectCalled(string instanceName, string resultName)
        {
            object instance        = this.scenarioContext.Get <object>(instanceName);
            string serializedValue = JsonConvert.SerializeObject(instance, ContainerBindings.GetServiceProvider(this.featureContext).GetRequiredService <IJsonSerializerSettingsProvider>().Instance);

            this.scenarioContext.Set(serializedValue, resultName);
        }
        public void GivenIDraftTheContentCalled(string contentName)
        {
            Content          content          = this.scenarioContext.Get <Content>(contentName);
            FakeContentStore fakeContentStore = ContainerBindings.GetServiceProvider(this.featureContext).GetService <FakeContentStore>();

            fakeContentStore.SetContentState(content, ContentPublicationContentState.Draft);
        }
        public static async Task SetupTransientTenant(FeatureContext featureContext)
        {
            ITenantProvider tenantProvider         = ContainerBindings.GetServiceProvider(featureContext).GetRequiredService <ITenantProvider>();
            var             transientTenantManager = TransientTenantManager.GetInstance(featureContext);
            await transientTenantManager.EnsureInitialised().ConfigureAwait(false);

            // Create a transient service tenant for testing purposes.
            ITenant transientServiceTenant = await transientTenantManager.CreateTransientServiceTenantFromEmbeddedResourceAsync(
                typeof(TransientTenantBindings).Assembly,
                "Marain.UserNotifications.Specs.ServiceManifests.UserNotificationsServiceManifest.jsonc").ConfigureAwait(false);

            // Now update the service Id in our configuration and in the function configuration
            UpdateServiceConfigurationWithTransientTenantId(featureContext, transientServiceTenant);

            // Now we need to construct a transient client tenant for the test, and enroll it in the new
            // transient service.
            ITenant transientClientTenant = await transientTenantManager.CreateTransientClientTenantAsync().ConfigureAwait(false);

            await transientTenantManager.AddEnrollmentAsync(
                transientClientTenant.Id,
                transientServiceTenant.Id,
                GetUserNotificationsConfig(featureContext)).ConfigureAwait(false);

            // TODO: Temporary hack to work around the fact that the transient tenant manager no longer holds the latest
            // version of the tenants it's tracking; see https://github.com/marain-dotnet/Marain.TenantManagement/issues/28
            transientTenantManager.PrimaryTransientClient = await tenantProvider.GetTenantAsync(transientClientTenant.Id).ConfigureAwait(false);
        }
        private static EnrollmentConfigurationItem[] GetOperationsConfig(FeatureContext featureContext)
        {
            IConfiguration configuration = ContainerBindings
                                           .GetServiceProvider(featureContext)
                                           .GetRequiredService <IConfiguration>();

            // Can't create a logger using the generic type of this class because it's static, so we'll do it using
            // the feature context instead.
            ILogger <FeatureContext> logger = ContainerBindings
                                              .GetServiceProvider(featureContext)
                                              .GetRequiredService <ILogger <FeatureContext> >();

            BlobStorageConfiguration blobStorageConfiguration =
                configuration.GetSection("TestBlobStorageConfiguration").Get <BlobStorageConfiguration>()
                ?? new BlobStorageConfiguration();

            if (string.IsNullOrEmpty(blobStorageConfiguration.AccountName))
            {
                logger.LogDebug("No configuration value 'TestBlobStorageConfiguration:AccountName' provided; using local storage emulator.");
            }

            return(new EnrollmentConfigurationItem[]
            {
                new EnrollmentBlobStorageConfigurationItem
                {
                    Key = "operationsStore",
                    Configuration = blobStorageConfiguration,
                },
            });
        }
Exemple #20
0
        public async Task GivenIHaveUsedTheTenantStoreToCreateANewClientTenantCalled(string clientName)
        {
            ITenantStore service   = ContainerBindings.GetServiceProvider(this.scenarioContext).GetRequiredService <ITenantStore>();
            ITenant      newTenant = await service.CreateClientTenantAsync(clientName).ConfigureAwait(false);

            this.scenarioContext.Set(newTenant.Id, clientName);
        }
        private async Task EnrollTenantForService(
            string enrollingTenantName,
            string serviceTenantName,
            string?enrollmentConfigurationName = null)
        {
            ITenantStore managementService =
                ContainerBindings.GetServiceProvider(this.scenarioContext).GetRequiredService <ITenantStore>();
            ITenantProvider tenantProvider = ContainerBindings.GetServiceProvider(this.scenarioContext).GetRequiredService <ITenantProvider>();

            ITenant enrollingTenant = await tenantProvider.GetTenantAsync(this.scenarioContext.Get <string>(enrollingTenantName)).ConfigureAwait(false);

            ITenant serviceTenant = await tenantProvider.GetTenantAsync(this.scenarioContext.Get <string>(serviceTenantName)).ConfigureAwait(false);

            List <EnrollmentConfigurationItem> enrollmentConfiguration =
                string.IsNullOrEmpty(enrollmentConfigurationName)
                ? new List <EnrollmentConfigurationItem>()
                : this.scenarioContext.Get <List <EnrollmentConfigurationItem> >(enrollmentConfigurationName);

            await CatchException.AndStoreInScenarioContextAsync(
                this.scenarioContext,
                () => managementService.EnrollInServiceAsync(
                    enrollingTenant,
                    serviceTenant,
                    enrollmentConfiguration.ToArray())).ConfigureAwait(false);
        }
Exemple #22
0
        public async Task ThenThereIsAServiceTenantWithId(string expectedServiceTenantId)
        {
            ITenantProvider tenantProvider = ContainerBindings.GetServiceProvider(this.scenarioContext).GetRequiredService <ITenantProvider>();
            ITenant         tenant         = await tenantProvider.GetTenantAsync(expectedServiceTenantId).ConfigureAwait(false);

            Assert.AreEqual(WellKnownTenantIds.ServiceTenantParentId, tenant.GetRequiredParentId());
        }
Exemple #23
0
        public async Task ThenTheTenantWithIdIsCalled(string tenantId, string expectedTenantName)
        {
            ITenantProvider tenantProvider = ContainerBindings.GetServiceProvider(this.scenarioContext).GetRequiredService <ITenantProvider>();
            ITenant         tenant         = await tenantProvider.GetTenantAsync(tenantId).ConfigureAwait(false);

            Assert.AreEqual(expectedTenantName, tenant.Name);
        }
Exemple #24
0
        public async Task ThenTheTenancyProviderContainsTenantsAsChildrenOfTheRootTenant(int expectedTenantCount)
        {
            ITenantStore           tenantStore        = ContainerBindings.GetServiceProvider(this.scenarioContext).GetRequiredService <ITenantStore>();
            TenantCollectionResult rootTenantChildren = await tenantStore.GetChildrenAsync(tenantStore.Root.Id).ConfigureAwait(false);

            Assert.AreEqual(expectedTenantCount, rootTenantChildren.Tenants.Count);
        }
Exemple #25
0
        public Task WhenIUseTheTenantStoreToInitialiseTheTenancyProviderUsingTheForceOption()
        {
            ITenantStore service = ContainerBindings.GetServiceProvider(this.scenarioContext).GetRequiredService <ITenantStore>();

            return(CatchException.AndStoreInScenarioContextAsync(
                       this.scenarioContext,
                       () => service.InitialiseTenancyProviderAsync(true)));
        }
Exemple #26
0
        public static void InitializeMocksToEnableInvocation(ScenarioContext scenarioContext)
        {
            OperationInvokerTestContext invokerContext = ContainerBindings.GetServiceProvider(scenarioContext).GetRequiredService <OperationInvokerTestContext>();

            invokerContext.ParameterBuilder
            .Setup(pb => pb.BuildParametersAsync(It.IsAny <object>(), It.IsAny <OpenApiOperationPathTemplate>()))
            .ReturnsAsync(new Dictionary <string, object>());
        }
Exemple #27
0
        public void GivenIDetokenizeTheLease()
        {
            var   leaseToken    = this.scenarioContext.Get <string>("LeaseToken");
            var   leaseProvider = ContainerBindings.GetServiceProvider(this.featureContext).GetRequiredService <ILeaseProvider>();
            Lease lease         = leaseProvider.FromLeaseToken(leaseToken);

            this.scenarioContext.Set <Lease>(lease);
        }
        public void GivenISerializeThePropertyBag()
        {
            IJsonSerializerOptionsProvider settingsProvider = ContainerBindings.GetServiceProvider(this.featureContext).GetService <IJsonSerializerOptionsProvider>();

            PropertyBag propertyBag = this.scenarioContext.Get <PropertyBag>();

            this.scenarioContext.Set(JsonSerializer.Serialize(propertyBag, settingsProvider.Instance), "Result");
        }
Exemple #29
0
        public async Task GivenIHaveAlreadyAcquiredTheLease()
        {
            var leaseProvider = ContainerBindings.GetServiceProvider(this.featureContext).GetRequiredService <ILeaseProvider>();
            var policy        = this.scenarioContext.Get <LeasePolicy>();
            var lease         = await leaseProvider.AcquireAsync(policy);

            this.scenarioContext.Set(lease);
        }
Exemple #30
0
        public void GivenIHaveAnInstanceOfAContentObjectCalled(string instanceName, string contentType, Table table)
        {
            Assert.AreEqual(1, table.RowCount);

            object instance = table.CreateInstance(() => ContainerBindings.GetServiceProvider(this.featureContext).GetContent(contentType));

            this.scenarioContext.Set(instance, instanceName);
        }