protected override void ConfigureWebHost(IWebHostBuilder builder) { SeedUsers(); builder.ConfigureTestServices(services => { services.AddMvc(options => { options.Filters.Add(new AllowAnonymousFilter()); options.Filters.Add(new FakeUserFilter()); }) .AddApplicationPart(typeof(Startup).Assembly); services.AddSingleton <IPolicyEvaluator, FakePolicyEvaluator>(); }); builder.ConfigureServices(services => { var descriptor = services.SingleOrDefault( d => d.ServiceType == typeof(DbContextOptions <ApplicationDbContext>)); var descriptorSecurityDb = services.SingleOrDefault( d => d.ServiceType == typeof(DbContextOptions <SecurityDbContext>)); services.Remove(descriptor); services.Remove(descriptorSecurityDb); var provider = services .AddEntityFrameworkInMemoryDatabase() .BuildServiceProvider(); services.AddDbContext <ApplicationDbContext>(options => { options.UseInMemoryDatabase("InMemoryDatadbForTesting"); options.UseInternalServiceProvider(provider); }); services.AddDbContext <SecurityDbContext>(options => { options.UseInMemoryDatabase("InMemoryDbForTesting"); options.UseInternalServiceProvider(provider); }); var sp = services.BuildServiceProvider(); using var scope = sp.CreateScope(); var scopedServices = scope.ServiceProvider; var securedb = scopedServices.GetRequiredService <SecurityDbContext>(); var db = scopedServices.GetRequiredService <ApplicationDbContext>(); var logger = scopedServices .GetRequiredService <ILogger <CustomWebApplicationFactory <TStartup> > >(); db.Database.EnsureCreated(); securedb.Database.EnsureCreated(); try { InitializeDbForTests(securedb, db); } catch (Exception ex) { logger.LogError(ex, "An error occurred seeding the " + "database with test messages. Error: {Message}", ex.Message); } }); }
private void CustomWebHostBuilder(IWebHostBuilder builder) { builder.ConfigureTestServices(ServicesConfiguration); }
protected override void ConfigureWebHost(IWebHostBuilder builder) { builder.ConfigureTestServices(collection => { collection.Remove(new ServiceDescriptor(typeof(IDynamoDBContext), a => a.GetService(typeof(IDynamoDBContext)), ServiceLifetime.Scoped)); AmazonDynamoDBConfig clientConfig = new AmazonDynamoDBConfig { RegionEndpoint = RegionEndpoint.EUCentral1, UseHttp = true, ServiceURL = DynamoDbServiceUrl }; var dynamoDbClient = new AmazonDynamoDBClient("123", "123", clientConfig); collection.AddScoped <IDynamoDBContext, DynamoDBContext>(opt => { AmazonDynamoDBClient client = new AmazonDynamoDBClient(); client = dynamoDbClient; var dynamoDbContext = new DynamoDBContext(client); return(dynamoDbContext); }); collection.Remove(new ServiceDescriptor(typeof(IAmazonDynamoDB), a => a.GetService(typeof(IAmazonDynamoDB)), ServiceLifetime.Scoped)); collection.AddAWSService <IAmazonDynamoDB>(options: new AWSOptions { Region = RegionEndpoint.EUCentral1, Credentials = new BasicAWSCredentials("123", "123"), }, ServiceLifetime.Scoped); collection.Remove(new ServiceDescriptor(typeof(IAmazonSQS), a => a.GetService(typeof(IAmazonSQS)), ServiceLifetime.Scoped)); AmazonSQSConfig sqsConfig = new AmazonSQSConfig { RegionEndpoint = RegionEndpoint.EUCentral1, UseHttp = true, ServiceURL = SqsServiceUrl, }; var sqsClient = new AmazonSQSClient("123", "123", sqsConfig); collection.AddScoped <IAmazonSQS, AmazonSQSClient>(opt => { AmazonSQSConfig localSqsConfig = new AmazonSQSConfig { RegionEndpoint = RegionEndpoint.EUCentral1, UseHttp = true, ServiceURL = SqsServiceUrl, }; var localSqsClient = new AmazonSQSClient("123", "123", localSqsConfig); return(localSqsClient); }); collection.RemoveAll(typeof(IHostedService)); DynamoDbSeeder.CreateTable(dynamoDbClient); DynamoDbSeeder.Seed(dynamoDbClient); SqsSeeder.CreateQueue(sqsClient); }); base.ConfigureWebHost(builder); }
protected override void ConfigureWebHost(IWebHostBuilder builder) { base.ConfigureWebHost(builder); builder.ConfigureTestServices(configureTestServices); }
/// <summary> /// Configura o Web Host que responderá as requisições nos testes de integração /// </summary> /// <param name="webHostBuilder">Construtor do web host</param> private void ConfigureTestWebHost(IWebHostBuilder webHostBuilder) { webHostBuilder.UseEnvironment(Domain.Constants.EnvironmentName.Testing); webHostBuilder.ConfigureTestServices(SwapOriginalServicesWithMock); }
protected override void ConfigureWebHost(IWebHostBuilder builder) { builder.ConfigureTestServices(services => { var patientService = new Mock <IPatientService>(); var patientNoteService = new Mock <IPatientNoteService>(); patientService.Setup(ps => ps.GetPatientAsync(1)).ReturnsAsync(new PatientModel { Id = 1, Family = "Test", Given = "TestNone", Dob = new DateTime(1967, 06, 22), Sex = "M", Address = "address", Phone = "111-222-3333" }); patientNoteService.Setup(pns => pns.GetNotesByPatientIdAsync(1)).ReturnsAsync(new List <string> { "No Trigger Terms" }); patientService.Setup(ps => ps.GetPatientAsync(2)).ReturnsAsync(new PatientModel { Id = 2, Family = "Test", Given = "TestBorderline", Dob = new DateTime(1946, 06, 22), Sex = "M", Address = "address", Phone = "111-222-3333" }); patientNoteService.Setup(pns => pns.GetNotesByPatientIdAsync(2)).ReturnsAsync(new List <string> { "Patient is a Smoker and his Body Weight is too high" }); patientService.Setup(ps => ps.GetPatientAsync(3)).ReturnsAsync(new PatientModel { Id = 3, Family = "Test", Given = "TestInDanger", Dob = new DateTime(2005, 06, 22), Sex = "F", Address = "address", Phone = "111-222-3333" }); patientNoteService.Setup(pns => pns.GetNotesByPatientIdAsync(3)).ReturnsAsync(new List <string> { "Relapse Relapse Relapse Relapse Dizziness Reaction Reaction Reaction Reaction Antibodies" }); patientService.Setup(ps => ps.GetPatientAsync(4)).ReturnsAsync(new PatientModel { Id = 4, Family = "Test", Given = "TestEarlyOnset", Dob = new DateTime(2003, 06, 22), Sex = "M", Address = "address", Phone = "111-222-3333" }); patientNoteService.Setup(pns => pns.GetNotesByPatientIdAsync(4)).ReturnsAsync(new List <string> { "Relapse Dizziness Reaction Antibodies Cholesterol" }); services.AddTransient <IPatientService>(_ => { return(patientService.Object); }); services.AddTransient <IPatientNoteService>(_ => { return(patientNoteService.Object); }); var dateTimeService = new Mock <IDateTimeService>(); dateTimeService.Setup(dt => dt.DateTimeNow()).Returns(new DateTime(2020, 02, 21)); services.AddTransient <IDateTimeService>(_ => { return(dateTimeService.Object); }); }).UseEnvironment("Test"); }
protected override void ConfigureWebHost(IWebHostBuilder builder) { builder .UseSolutionRelativeContentRoot("src/Eventuras.WebApi") .UseEnvironment("Development") .ConfigureAppConfiguration(app => app .AddInMemoryCollection(new Dictionary <string, string> { { "AppSettings:EmailProvider", "Mock" }, { "AppSettings:SmsProvider", "Mock" }, { "AppSettings:UsePowerOffice", "false" }, { "AppSettings:UseStripeInvoice", "false" }, { "SuperAdmin:Email", TestingConstants.SuperAdminEmail }, { "SuperAdmin:Password", TestingConstants.SuperAdminPassword } })) .ConfigureServices(services => { // Override already added email sender with the true mock services.AddSingleton(EmailSenderMock.Object); // Remove the app's ApplicationDbContext registration. var descriptor = services.SingleOrDefault( d => d.ServiceType == typeof(DbContextOptions <ApplicationDbContext>)); if (descriptor != null) { services.Remove(descriptor); } // Add ApplicationDbContext using an in-memory database for testing. services.AddDbContext <ApplicationDbContext>(options => { options.UseInMemoryDatabase("eventuras-web-api-tests"); }); services.AddScoped <IDbInitializer, TestDbInitializer>(); // Build the service provider. var sp = services.BuildServiceProvider(); // Create a scope to obtain a reference to the database // context (ApplicationDbContext). using var scope = sp.CreateScope(); var initializer = scope.ServiceProvider.GetRequiredService <IDbInitializer>(); initializer.SeedAsync().Wait(); }); builder.ConfigureTestServices(services => { services.PostConfigure <JwtBearerOptions>(JwtBearerDefaults.AuthenticationScheme, options => { options.TokenValidationParameters = new TokenValidationParameters { IssuerSigningKey = FakeJwtManager.SecurityKey, ValidIssuer = FakeJwtManager.Issuer, ValidAudience = FakeJwtManager.Audience }; }); services.PostConfigure <AuthorizationOptions>(options => { foreach (var scope in TestingConstants.DefaultScopes) // replace default scope policies having original auth0 Issuer { options.AddPolicy(scope, policy => { policy.Requirements.Add(new ScopeRequirement(FakeJwtManager.Issuer, scope)); }); } }); }); }
protected override void ConfigureWebHost(IWebHostBuilder builder) { builder.ConfigureTestServices(services => configure?.Invoke(services)); }
/// <summary> /// Configure the web host to use an EF in memory database /// </summary> protected override void ConfigureWebHost(IWebHostBuilder builder) { builder.ConfigureAppConfiguration(c => { c.AddInMemoryCollection(new Dictionary <string, string> { // Manually insert a EF provider so that ConfigureServices will add EF repositories but we will override // DbContextOptions to use an in memory database { "globalSettings:databaseProvider", "postgres" }, { "globalSettings:postgreSql:connectionString", "Host=localhost;Username=test;Password=test;Database=test" }, // Clear the redis connection string for distributed caching, forcing an in-memory implementation { "globalSettings:redis:connectionString", "" } }); }); builder.ConfigureTestServices(services => { var dbContextOptions = services.First(sd => sd.ServiceType == typeof(DbContextOptions <DatabaseContext>)); services.Remove(dbContextOptions); services.AddScoped(_ => { return(new DbContextOptionsBuilder <DatabaseContext>() .UseInMemoryDatabase(DatabaseName) .Options); }); // QUESTION: The normal licensing service should run fine on developer machines but not in CI // should we have a fork here to leave the normal service for developers? // TODO: Eventually add the license file to CI var licensingService = services.First(sd => sd.ServiceType == typeof(ILicensingService)); services.Remove(licensingService); services.AddSingleton <ILicensingService, NoopLicensingService>(); // FUTURE CONSIDERATION: Add way to run this self hosted/cloud, for now it is cloud only var pushRegistrationService = services.First(sd => sd.ServiceType == typeof(IPushRegistrationService)); services.Remove(pushRegistrationService); services.AddSingleton <IPushRegistrationService, NoopPushRegistrationService>(); // Even though we are cloud we currently set this up as cloud, we can use the EF/selfhosted service // instead of using Noop for this service // TODO: Install and use azurite in CI pipeline var eventWriteService = services.First(sd => sd.ServiceType == typeof(IEventWriteService)); services.Remove(eventWriteService); services.AddSingleton <IEventWriteService, RepositoryEventWriteService>(); var eventRepositoryService = services.First(sd => sd.ServiceType == typeof(IEventRepository)); services.Remove(eventRepositoryService); services.AddSingleton <IEventRepository, EventRepository>(); // Our Rate limiter works so well that it begins to fail tests unless we carve out // one whitelisted ip. We should still test the rate limiter though and they should change the Ip // to something that is NOT whitelisted services.Configure <IpRateLimitOptions>(options => { options.IpWhitelist = new List <string> { FactoryConstants.WhitelistedIp, }; }); }); }
protected override void ConfigureWebHost(IWebHostBuilder builder) { builder.ConfigureTestServices(MockServices); }
protected override void ConfigureWebHost(IWebHostBuilder builder) { builder.UseWebRoot(Path.GetFullPath("wwwroot")); builder.ConfigureAppConfiguration((context, b) => { b.SetBasePath(Path.GetFullPath("wwwroot")) .AddJsonFile("config.json", false, true); b.AddInMemoryCollection(new Dictionary <string, string> { { "AppSettings:SitecoreIdentityServerUrl", "http://localhost" }, { "Logging:LogLevel:Default", "Debug" }, { "Logging:PipelineTraceLoggingEnabled", "true" } }); }); base.ConfigureWebHost(builder); builder.UseSolutionRelativeContentRoot("") .UseStartup <Startup>(); builder.ConfigureLogging(c => { c.AddProvider(new XunitLoggerProvider(getTestOutputHelper())); }); builder.ConfigureServices(c => { c.Configure <IdentityServerAuthenticationOptions>("Bearer", options => { options.Authority = "http://localhost"; // This makes sure the commerce engine contacts the in memory identity server options.JwtBackChannelHandler = identityServerHandler; options.IntrospectionDiscoveryHandler = identityServerHandler; options.IntrospectionBackChannelHandler = identityServerHandler; }); }); builder.ConfigureTestServices(services => { services.AddTransient <GetDatabaseVersionCommand, DummyGetDatabaseVersionCommand>(); /************************************** Persistent ***********************************/ services.AddSingleton <IStore>(inMemoryStore); services.AddSingleton(inMemoryStore); services.AddSingleton <IListStore>(inMemoryListStore); services.AddSingleton(inMemoryListStore); Assembly assembly = Assembly.GetExecutingAssembly(); services.RegisterAllPipelineBlocks(assembly); services.Sitecore().Pipelines(config => config.ConfigurePipeline <IFindEntitiesInListPipeline>(c => { c.Clear(); c.Add <FindEntitiesInListBlock>(); }) .ConfigurePipeline <IFindEntityPipeline>(c => { c.Clear(); c.Add <FindEntityBlock>(); })); }); }
protected override void ConfigureWebHost(IWebHostBuilder builder) { builder .ConfigureTestServices(services => { services .AddAuthentication(options => { options.DefaultAuthenticateScheme = "Test"; options.DefaultChallengeScheme = "Test"; }) .AddScheme <AuthenticationSchemeOptions, TestAuthHandler>("Test", options => { }); }) .ConfigureServices(services => { // Remove the app's ApplicationDbContext registration. var descriptor = services.SingleOrDefault( d => d.ServiceType == typeof(DbContextOptions <ExpensesContext>)); if (descriptor != null) { services.Remove(descriptor); } // Replace RabbitMQ bus to InMemoryBus to test it locally. services.AddInMemoryMessageBus(); // Add ApplicationDbContext using an in-memory database for testing. services.AddEntityFrameworkSqlite(); services.AddDbContext <ExpensesContext>((context) => { context.UseSqlite(_connection) .UseQueryTrackingBehavior(QueryTrackingBehavior.NoTracking); }); // Build the service provider. var sp = services.BuildServiceProvider(); // Create a scope to obtain a reference to the database // context (ApplicationDbContext). using (var scope = sp.CreateScope()) { var scopedServices = scope.ServiceProvider; var db = scopedServices.GetRequiredService <ExpensesContext>(); var logger = scopedServices .GetRequiredService <ILogger <CustomWebApplicationFactorySqlite <TStartup> > >(); // Ensure the database is created. db.Database.EnsureCreated(); try { // Seed the database with test data. //Utilities.InitializeDbForTests(db); } catch (Exception ex) { logger.LogError(ex, "An error occurred seeding the " + "database with test messages. Error: {Message}", ex.Message); } } }); }
protected override void ConfigureWebHost(IWebHostBuilder builder) { builder.UseEnvironment("Testing"); builder.ConfigureTestServices(ConfigureServices); }
//Inspired by: https://docs.microsoft.com/en-us/aspnet/core/test/integration-tests?view=aspnetcore-3.0#customize-webapplicationfactory protected override void ConfigureWebHost(IWebHostBuilder builder) { builder.ConfigureTestServices(services => { var descriptor = services.SingleOrDefault( d => d.ServiceType == typeof(DbContextOptions <SepesDbContext>)); services.Remove(descriptor); services.AddSingleton <IContextUserService>(new ContextUserServiceMock(_isEmployee, _isAdmin, _isSponsor, _isDatasetAdmin)); services.AddScoped <IAzureUserService, AzureUserServiceMock>(); services.SwapTransientWithSingleton <IAzureQueueService, AzureQueueServiceMock>(); if (_mockServicesForScenarioProvider != null) { _mockServicesForScenarioProvider.RegisterServices(services); } services.AddAuthentication("IntegrationTest") .AddScheme <AuthenticationSchemeOptions, IntegrationTestAuthenticationHandler>( "IntegrationTest", options => { } ); IConfiguration configuration; var sp = services.BuildServiceProvider(); using (var scope = sp.CreateScope()) { var scopedServices = scope.ServiceProvider; configuration = scopedServices.GetRequiredService <IConfiguration>(); } var dbConnectionString = IntegrationTestConnectionStringUtil.GetDatabaseConnectionString(configuration); services.AddDbContext <SepesDbContext>(options => options.UseSqlServer( dbConnectionString, options => { options.MigrationsAssembly("Sepes.Infrastructure"); options.EnableRetryOnFailure(10, TimeSpan.FromSeconds(10), null); } )); sp = services.BuildServiceProvider(); SepesDbContext dbContext; using (var scope = sp.CreateScope()) { var scopedServices = scope.ServiceProvider; dbContext = scopedServices.GetRequiredService <SepesDbContext>(); dbContext.Database.Migrate(); } }); builder.ConfigureAppConfiguration((context, configBuilder) => { configBuilder.AddInMemoryCollection( new Dictionary <string, string> { [ConfigConstants.IS_INTEGRATION_TEST] = "true", ["AllowCorsDomains"] = "http://localhost:80", ["CostAllocationTypeTagName"] = "INTTEST-CostAllocationType", ["CostAllocationCodeTagName"] = "INTTEST-CostAllocationCode" }); }); }
protected override void ConfigureWebHost(IWebHostBuilder builder) => builder.ConfigureTestServices(services => { services.AddSingleton <IApiClient>(new MockApiClient()); services.AddSingleton <IAdminService>(new MockAdminService()); });
/// <inheritdoc /> protected override void ConfigureWebHost(IWebHostBuilder builder) => builder.ConfigureTestServices(_initializeCompositionRoot);
protected override void ConfigureWebHost(IWebHostBuilder builder) { builder.ConfigureTestServices(services => { services.RemoveAll(typeof(IHostedService)); }).UseTestServer(); }
protected override void ConfigureWebHost(IWebHostBuilder builder) { builder.ConfigureTestServices( services => { // constant time in all integration testing services.Replace( new ServiceDescriptor( typeof(ITimeService), typeof(TimeServiceMock), ServiceLifetime.Transient ) ); } ); builder.ConfigureServices( services => { var serviceProvider = new ServiceCollection() .AddEntityFrameworkInMemoryDatabase() .BuildServiceProvider(); services.AddDbContext <RepositoryContext>( options => { options.UseInMemoryDatabase(TestDbName) .ConfigureWarnings( x => x.Ignore(InMemoryEventId.TransactionIgnoredWarning) ); options.UseInternalServiceProvider(serviceProvider); } ); services.PostConfigure <JwtBearerOptions>( JwtBearerDefaults.AuthenticationScheme, options => { options.TokenValidationParameters = new TokenValidationParameters { SignatureValidator = (token, parameters) => new JwtSecurityToken(token), ValidateIssuer = false, ValidateLifetime = false, ValidateIssuerSigningKey = false, ValidateAudience = false }; } ); using var scope = services.BuildServiceProvider().CreateScope(); var appDb = scope.ServiceProvider.GetRequiredService <RepositoryContext>(); appDb.Database.EnsureDeleted(); appDb.Database.EnsureCreated(); try { CommonSeeder.Seed(appDb); } catch (Exception ex) { var logger = scope.ServiceProvider .GetRequiredService <ILogger <CustomWebApplicationFactoryWithInMemoryDb <TStartup> > >(); logger.LogError( ex, "An error occurred while seeding the database with messages. Error: {ex.Message}" ); } } ); }
protected override void ConfigureWebHost(IWebHostBuilder builder) { builder.ConfigureTestServices(services => { // Create a new service provider. var serviceProvider = new ServiceCollection() .AddEntityFrameworkInMemoryDatabase() .BuildServiceProvider(); // Add a database context (ApplicationDbContext) using an in-memory // database for testing. services.RemoveAll <ApplicationDbContext>(); services.AddDbContext <ApplicationDbContext>((options, context) => { context.UseInMemoryDatabase("InMemoryDbForTesting") .UseInternalServiceProvider(serviceProvider); }); // Build the service provider. var sp = services.BuildServiceProvider(); // Create a scope to obtain a reference to the database // context (ApplicationDbContext). using (var scope = sp.CreateScope()) { var scopedServices = scope.ServiceProvider; var db = scopedServices.GetRequiredService <ApplicationDbContext>(); var logger = scopedServices .GetRequiredService <ILogger <CustomWebApplicationFactory <TStartup> > >(); var userManager = scopedServices.GetRequiredService <UserManager <IdentityUser> >(); // Ensure the database is created. db.Database.EnsureCreated(); if (!db.Database.IsInMemory()) { throw new Exception("Database is not in-memory"); } try { // Seed the database with test data. var alice = new IdentityUser { UserName = "******", Email = "*****@*****.**" }; var result = userManager.CreateAsync(alice, "#SecurePassword123").Result; if (!result.Succeeded) { throw new Exception("Unable to create alice:\r\n" + string.Join("\r\n", result.Errors.Select(error => $"{error.Code}: {error.Description}"))); } var emailConfirmationToken = userManager.GenerateEmailConfirmationTokenAsync(alice).Result; result = userManager.ConfirmEmailAsync(alice, emailConfirmationToken).Result; if (!result.Succeeded) { throw new Exception("Unable to verify alices email address:\r\n" + string.Join("\r\n", result.Errors.Select(error => $"{error.Code}: {error.Description}"))); } } catch (Exception ex) { logger.LogError(ex, "An error occurred seeding the " + "database with test messages. Error: {Message}", ex.Message); } } }); }
protected override void ConfigureWebHost(IWebHostBuilder builder) { builder.ConfigureTestServices(s => { s.AddSingleton(this.FakeRfidReader); }); }
private static void ConfigureWebHostBuilder(IWebHostBuilder builder) => builder.ConfigureTestServices(s => s.AddSingleton <TestService, OverridenService>());
protected override void ConfigureWebHost(IWebHostBuilder builder) { builder.ConfigureTestServices(services => services.AddSingleton <IContextSecurityProvider>(_ => new StubManagedIdentityProvider())); }