public TestServerBuilder UsingImpostersMiddleware(Imposter imposter) { var impostersAsStubConfiguration = new ImpostersAsStubConfiguration(new[] { imposter }); Action <IApplicationBuilder> action = app => app.UseStubImposters(impostersAsStubConfiguration); _webHostBuilder.Configure(action); return(this); }
public async Task LargePayload_DisposesRequest_AfterResponseIsCompleted() { // Arrange var data = new byte[2048]; var character = Encoding.ASCII.GetBytes("a"); for (var i = 0; i < data.Length; i++) { data[i] = character[0]; } var builder = new WebHostBuilder(); RequestDelegate app = async ctx => { var disposable = new TestDisposable(); ctx.Response.RegisterForDispose(disposable); await ctx.Response.Body.WriteAsync(data, 0, 1024); Assert.False(disposable.IsDisposed); await ctx.Response.Body.WriteAsync(data, 1024, 1024); }; builder.Configure(appBuilder => appBuilder.Run(app)); var server = new TestServer(builder); var client = server.CreateClient(); // Act & Assert var response = await client.GetAsync("http://localhost:12345"); }
public void Initialize(string basePath = null) { var builder = new WebHostBuilder(); builder.ConfigureServices(ConfigureServices); builder.Configure(app => { if (basePath != null) { app.Map(basePath, map => { ConfigureApp(map); }); } else { ConfigureApp(app); } }); Server = new TestServer(builder); Handler = Server.CreateHandler(); BrowserClient = new BrowserClient(new BrowserHandler(Handler)); Client = new HttpClient(Handler); }
private static TestServer CreateAuthorizationServer(Action <OpenIdConnectServerOptions> configuration = null) { var builder = new WebHostBuilder(); builder.UseEnvironment("Testing"); builder.ConfigureServices(services => services.AddAuthentication()); builder.Configure(app => { app.UseOpenIdConnectServer(options => { options.AllowInsecureHttp = true; options.SigningCredentials.AddCertificate( assembly: typeof(OpenIdConnectServerMiddlewareTests).GetTypeInfo().Assembly, resource: "AspNet.Security.OpenIdConnect.Server.Tests.Certificate.pfx", password: "******"); // Note: overriding the default data protection provider is not necessary for the tests to pass, // but is useful to ensure unnecessary keys are not persisted in testing environments, which also // helps make the unit tests run faster, as no registry or disk access is required in this case. options.DataProtectionProvider = new EphemeralDataProtectionProvider(app.ApplicationServices); // Run the configuration delegate // registered by the unit tests. configuration?.Invoke(options); }); }); return(new TestServer(builder)); }
private static TestServer CreateAuthorizationServer(Action <OpenIddictServerBuilder> configuration = null) { var builder = new WebHostBuilder(); builder.UseEnvironment("Testing"); builder.ConfigureLogging(options => options.AddDebug()); builder.ConfigureServices(services => { services.AddAuthentication(); services.AddOptions(); services.AddDistributedMemoryCache(); services.AddOpenIddict() .AddCore(options => { options.SetDefaultApplicationEntity <OpenIddictApplication>() .SetDefaultAuthorizationEntity <OpenIddictAuthorization>() .SetDefaultScopeEntity <OpenIddictScope>() .SetDefaultTokenEntity <OpenIddictToken>(); }) .AddServer(options => configuration?.Invoke(options)); }); builder.Configure(app => { app.UseAuthentication(); app.Run(context => context.ChallengeAsync(OpenIddictServerDefaults.AuthenticationScheme)); }); return(new TestServer(builder)); }
private static TestServer CreateAuthorizationServer(Action <OpenIdConnectServerOptions> configuration = null) { var builder = new WebHostBuilder(); builder.UseEnvironment("Testing"); builder.ConfigureServices(services => services.AddAuthentication()); builder.Configure(app => { app.UseOpenIdConnectServer(options => { options.AllowInsecureHttp = true; // Note: overriding the default data protection provider is not necessary for the tests to pass, // but is useful to ensure unnecessary keys are not persisted in testing environments, which also // helps make the unit tests run faster, as no registry or disk access is required in this case. options.DataProtectionProvider = new EphemeralDataProtectionProvider(app.ApplicationServices); // Run the configuration delegate // registered by the unit tests. configuration?.Invoke(options); }); }); return(new TestServer(builder)); }
public async Task GetException_WhenDeveloperPageIsConfigured_ShouldBeInternalServerError() { // Arrange var builder = new WebHostBuilder(); builder.ConfigureServices(services => { services.AddMvc(); }); builder.Configure(app => app .UseDeveloperExceptionPage() .Use((context, next) => { throw new Exception("Wow!", new Exception("Exactly!")); })); using var testServer = new TestServer(builder); using var client = testServer.CreateClient(); // Act using var response = await client.GetAsync("/exception"); // Assert response.Should().Be500InternalServerError(); }
public PodeListener(CancellationToken cancellationToken, PodeListenerType type = PodeListenerType.Http) { CancellationToken = cancellationToken; IsDisposed = false; Type = type; WebBuilder = new WebHostBuilder(); WebBuilder.ConfigureServices(s => s.AddRouting()); WebBuilder.Configure(app => { var routeHandler = new RouteHandler(ctx => { var _podeContext = new PodeContext(ctx, this); this.AddContext(_podeContext); return(_podeContext.Start()); }); var routeBuilder = new RouteBuilder(app, routeHandler); routeBuilder.MapRoute("pode sub-routes", "{*.}"); var routes = routeBuilder.Build(); app.UseRouter(routes); }); Sockets = new List <PodeSocket>(); Contexts = new BlockingCollection <PodeContext>(); }
public TrustedDeviceAuthorizationIntegrationTests(ITestOutputHelper output) { _output = output; var builder = new WebHostBuilder(); builder.ConfigureServices(services => { services.AddSingleton <ITotpService, MockTotpService>(); services.AddIdentityServer(options => { options.EmitStaticAudienceClaim = true; }) .AddInMemoryIdentityResources(GetIdentityResources()) .AddInMemoryApiScopes(GetApiScopes()) .AddInMemoryApiResources(GetApiResources()) .AddInMemoryClients(GetClients()) .AddTestUsers(GetTestUsers()) .AddInMemoryPersistedGrants() .AddTrustedDeviceAuthorization() .AddDeveloperSigningCredential(persistKey: false); }); builder.Configure(app => { app.UseIdentityServer(); }); var server = new TestServer(builder); var handler = server.CreateHandler(); _httpClient = new HttpClient(handler) { BaseAddress = new Uri(BaseUrl) }; }
public void Initialize(string basePath = null, bool enableLogging = false) { var builder = new WebHostBuilder(); builder.ConfigureServices(ConfigureServices); builder.Configure(app => { if (basePath != null) { app.Map(basePath, map => { ConfigureApp(map); }); } else { ConfigureApp(app); } }); if (enableLogging) { builder.ConfigureLogging((ctx, b) => b.AddConsole()); } Server = new TestServer(builder); Handler = Server.CreateHandler(); BrowserClient = new BrowserClient(new BrowserHandler(Handler)); BackChannelClient = new HttpClient(Handler); }
private static TestServer CreateResourceServer(Action <OpenIddictValidationBuilder> configuration = null) { var builder = new WebHostBuilder(); builder.UseEnvironment("Testing"); builder.ConfigureLogging(options => options.AddDebug()); builder.ConfigureServices(services => { services.AddAuthentication(); services.AddOptions(); services.AddDistributedMemoryCache(); services.AddOpenIddict() .AddValidation(options => configuration?.Invoke(options)); }); builder.Configure(app => { app.UseAuthentication(); app.Run(context => context.ChallengeAsync(OpenIddictValidationDefaults.AuthenticationScheme)); }); return(new TestServer(builder)); }
public void CanRegisterActorsInMultipleCalls() { var builder = new WebHostBuilder(); builder.UseActors(options => { options.Actors.RegisterActor <TestActor1>(); }); builder.UseActors(options => { options.Actors.RegisterActor <TestActor2>(); }); // Configuring the HTTP pipeline is required. It's ok if it's empty. builder.Configure(_ => {}); var host = builder.Build(); var runtime = host.Services.GetRequiredService <ActorRuntime>(); Assert.Collection( runtime.RegisteredActors.Select(r => r.Type.ActorTypeName).OrderBy(t => t), t => Assert.Equal(ActorTypeInformation.Get(typeof(TestActor1)).ActorTypeName, t), t => Assert.Equal(ActorTypeInformation.Get(typeof(TestActor2)).ActorTypeName, t)); }
private static TestServer CreateAuthorizationServer() { var builder = new WebHostBuilder(); builder.UseEnvironment("Testing"); builder.ConfigureServices(services => { services.AddAuthentication(options => { options.DefaultScheme = OpenIdConnectConstantsExt.Auth.DefaultScheme; }) .AddOpenIdConnectServer(options => { options.AuthorizationEndpointPath = "/connect/authorize"; options.LogoutEndpointPath = "/connect/logout"; options.TokenEndpointPath = "/connect/token"; options.UserinfoEndpointPath = "/connect/userinfo"; options.Provider = new OpenIdConnectServerProvider { OnValidateLogoutRequest = context => { // Reject non-POST logout requests. if ( !string.Equals(context.HttpContext.Request.Method, "POST", StringComparison.OrdinalIgnoreCase)) { context.Reject( OpenIdConnectConstants.Errors.InvalidRequest, "Only POST requests are supported."); } return(Task.FromResult(0)); }, OnValidateAuthorizationRequest = context => { if ( !string.Equals(context.HttpContext.Request.Method, "POST", StringComparison.OrdinalIgnoreCase)) { context.Reject( OpenIdConnectConstants.Errors.InvalidRequest, "Only POST requests are supported."); } return(Task.FromResult(0)); } }; }); services.AddLogging(); }); builder.Configure(app => { app.UseAuthentication(); }); return(new TestServer(builder)); }
public static void Main(string[] args) { var config = new ConfigurationBuilder() .AddEnvironmentVariables(prefix: "ASPNETCORE_") .AddCommandLine(args) .Build(); // The url all requests will be forwarded to var baseUriArg = config["baseUri"]; if (String.IsNullOrWhiteSpace(baseUriArg)) { throw new ArgumentException("--baseUri is required"); } var baseUri = new Uri(baseUriArg); // Cache base URI values _scheme = baseUri.Scheme; _host = new HostString(baseUri.Authority); _pathBase = baseUri.AbsolutePath; _appendQuery = new QueryString(baseUri.Query); Console.WriteLine($"Base URI: {baseUriArg}"); BenchmarksEventSource.MeasureAspNetVersion(); BenchmarksEventSource.MeasureNetCoreAppVersion(); var builder = new WebHostBuilder() .ConfigureLogging(loggerFactory => { // Don't enable console logging if no specific level is defined (perf) if (Enum.TryParse(config["LogLevel"], out LogLevel logLevel)) { Console.WriteLine($"Console Logging enabled with level '{logLevel}'"); loggerFactory.AddConsole().SetMinimumLevel(logLevel); } }) .UseKestrel((context, kestrelOptions) => { kestrelOptions.ConfigureHttpsDefaults(httpsOptions => { httpsOptions.ServerCertificate = new X509Certificate2(Path.Combine(context.HostingEnvironment.ContentRootPath, "testCert.pfx"), "testPassword"); }); }) .UseContentRoot(Directory.GetCurrentDirectory()) .UseConfiguration(config) ; InitializeHttpClient(); builder = builder.Configure(app => app.Run(ProxyRequest)); builder .Build() .Run(); }
//private void CreateBasic(out ) protected WebHostBuilder CreateDefaultWebHostBuilder() { var webHostBuilder = new WebHostBuilder(); webHostBuilder.ConfigureLogging(lb => lb.AddXUnit(outputHelper).AddFilter("RTUITLab", LogLevel.Trace)); webHostBuilder.Configure(app => app.UseWebAppConfigure()); webHostBuilder.ConfigureServices(services => services.AddSingleton <TestValuesStorage>()); return(webHostBuilder); }
private static TestServer CreateAuthorizationServer(Action <OpenIdConnectServerOptions> configuration = null) { var builder = new WebHostBuilder(); builder.UseEnvironment("Testing"); builder.ConfigureServices(services => { services.AddAuthentication(); services.AddLogging(); }); builder.Configure(app => { app.UseOpenIdConnectServer(options => { options.Provider = new OpenIdConnectServerProvider { OnValidateLogoutRequest = context => { // Reject non-POST logout requests. if ( !string.Equals(context.HttpContext.Request.Method, "POST", StringComparison.OrdinalIgnoreCase)) { context.Reject( OpenIdConnectConstants.Errors.InvalidRequest, "Only POST requests are supported."); } return(Task.FromResult(0)); }, OnValidateAuthorizationRequest = context => { if ( !string.Equals(context.HttpContext.Request.Method, "POST", StringComparison.OrdinalIgnoreCase)) { context.Reject( OpenIdConnectConstants.Errors.InvalidRequest, "Only POST requests are supported."); } return(Task.FromResult(0)); } }; // Run the configuration delegate // registered by the unit tests. configuration?.Invoke(options); }); }); return(new TestServer(builder)); }
public void BeforeTest(ITest test) { if (!(test.Fixture is IRequireTestEndpoint requireTestEndpoint)) { throw new Exception( $"Test should implement interface '{typeof(IRequireTestEndpoint)}'" + $" instead of using the attribute '{GetType()}'"); } var hostConfig = test.Fixture as IRequireTestEndpointHostBuilder; var appConfig = test.Fixture as IRequireTestEndpointApplicationBuilder; var servicesConfig = test.Fixture as IRequireTestEndpointServices; var overrideConfig = test.Fixture as IRequireTestEndpointOverride; var hostBuilder = new WebHostBuilder(); hostConfig?.Configure(hostBuilder); hostBuilder.Configure(x => appConfig?.Configure(x)); if (servicesConfig != null) { hostBuilder.ConfigureServices(servicesConfig.Configure); } if (overrideConfig != null) { hostBuilder.Configure(x => x.Run(overrideConfig.ServerRun)); } var startupDefinition = test.Fixture.GetType() .GetInterfaces() .SingleOrDefault(x => x.IsGenericType && x.GetGenericTypeDefinition() == typeof(IRequireTestEndpointStartup <>)); if (startupDefinition != null) { var startupType = startupDefinition.GetGenericArguments()[0]; hostBuilder.UseStartup(startupType); } testServer = requireTestEndpoint.Endpoint = new Microsoft.AspNetCore.TestHost.TestServer(hostBuilder); }
public static void Main(string[] args) { var config = new ConfigurationBuilder() .AddEnvironmentVariables(prefix: "ASPNETCORE_") .AddCommandLine(args) .Build(); // The url all requests will be forwarded to var baseUriArg = config["baseUri"]; if (String.IsNullOrWhiteSpace(baseUriArg)) { throw new ArgumentException("--baseUri is required"); } var baseUri = new Uri(baseUriArg); // Cache base URI values _scheme = baseUri.Scheme; _host = new HostString(baseUri.Authority); _pathBase = baseUri.AbsolutePath; _appendQuery = new QueryString(baseUri.Query); Console.WriteLine($"Base URI: {baseUriArg}"); WriteStatistics(); var builder = new WebHostBuilder() .ConfigureLogging(loggerFactory => { // Don't enable console logging if no specific level is defined (perf) if (Enum.TryParse(config["LogLevel"], out LogLevel logLevel)) { Console.WriteLine($"Console Logging enabled with level '{logLevel}'"); loggerFactory.AddConsole().SetMinimumLevel(logLevel); } }) .UseKestrel() .UseContentRoot(Directory.GetCurrentDirectory()) .UseConfiguration(config) ; InitializeHttpClient(); builder = builder.Configure(app => app.Run(ProxyRequest)); builder .Build() .Run(); }
public void WebHostAddCloudFoundryConfiguration_Adds() { var hostbuilder = new WebHostBuilder(); hostbuilder.Configure(builder => { }); hostbuilder.AddCloudFoundryConfiguration(); var host = hostbuilder.Build(); var cfg = host.Services.GetService(typeof(IConfiguration)) as IConfigurationRoot; Assert.Contains(cfg.Providers, ctype => ctype is CloudFoundryConfigurationProvider); }
public async Task TestExceptionLogger() { Mock <IMailSender> emailSenderMock = null; int processManualTimes = 0; var hostBuilder = new WebHostBuilder(); hostBuilder.ConfigureServices(collection => { emailSenderMock = new Mock <IMailSender>(); emailSenderMock.Setup(p => p.SendEmail(It.IsAny <IEnumerable <MailAddress> >(), It.IsAny <string>(), It.IsAny <string>())).Throws <NotImplementedException>(); collection.AddSingleton <IMailSender>(provider => emailSenderMock.Object); }); hostBuilder.Configure(app => { var options = new ExceptionHandlerOptions(); options.MailOptions = new MailOptions { To = new List <MailAddress> { new MailAddress { Address = "*****@*****.**" }, new MailAddress { Address = "*****@*****.**" } }, Subject = "Test Error" }; options.ManualProcess = exception => { processManualTimes++; }; app.UseSymonExceptionHandler(options); app.Run(context => { throw new Exception("Server Error"); }); }); using (var testServer = new TestServer(hostBuilder)) { await Assert.ThrowsAsync <Exception>(async() => await testServer.CreateRequest("/").GetAsync()); Assert.Equal(1, processManualTimes); emailSenderMock.Verify( p => p.SendEmailAsync(It.IsAny <IEnumerable <MailAddress> >(), It.IsAny <string>(), It.IsAny <string>()), Times.Once); } }
public void Setup() { _redis = ConnectionMultiplexer.Connect("localhost:6379"); var hostBuilder = new WebHostBuilder(); hostBuilder.ConfigureServices(services => ConfigureServices(services)); hostBuilder.Configure(app => Configure(app)); hostBuilder.UseContentRoot(Directory.GetCurrentDirectory()); hostBuilder.UseKestrel(); hostBuilder.UseUrls("http://localhost:5051"); _host = hostBuilder.Build(); _host.Start(); }
//----------------------------------------------------------------------------------------------------------------------------------------------------- public override void Activate() { base.Activate(); var builder = new WebHostBuilder(); BuildListenUrls(); builder.UseKestrel(ConfigureKestrelServer); builder.UseUrls(_listenUrls.ToArray()); builder.Configure(ConfigureWebHost); _host = builder.Build(); _host.Start(); }
public void WebHostAddCloudConfigurationFoundry_Adds() { var hostbuilder = new WebHostBuilder(); hostbuilder.Configure(builder => { }); hostbuilder.AddCloudFoundryConfiguration(); var host = hostbuilder.Build(); var instanceInfo = host.Services.GetApplicationInstanceInfo(); Assert.IsAssignableFrom <CloudFoundryApplicationOptions>(instanceInfo); var cfg = host.Services.GetService(typeof(IConfiguration)) as IConfigurationRoot; Assert.Contains(cfg.Providers, ctype => ctype is CloudFoundryConfigurationProvider); }
/// <summary> /// Starts the webserver using the specified scriptrunner /// </summary> /// <param name="scriptRunner">Script runner used</param> /// <returns>Task</returns> public Task Start(IScriptRunner scriptRunner) { WebHostBuilder hostBuilder = new WebHostBuilder(); var loggerFactory = new LoggerFactory(); hostBuilder.UseKestrel(x => { x.AddServerHeader = false; }); hostBuilder.UseUrls(this.baseAddress); hostBuilder.ConfigureServices(x => this.ConfigureServices(loggerFactory, scriptRunner, x)); hostBuilder.Configure(this.Configuration); this.host = hostBuilder.Build(); return(this.host.RunAsync(this.cancel.Token)); }
public IRunner Build() { IWebHostBuilder builder = new WebHostBuilder(); builder.ConfigureServices(services => { services.AddSingleton <TFunction>(); services.AddSingleton(sp => SerializerFactory()); }); builder.Configure(app => { app.Run(_requestHandler); }); builder.UseKestrel(options => { options.Listen(IPAddress.Loopback, Port); }); var host = builder.Build(); return(new LambdaRunner(host)); }
private IWebHostBuilder SetupWebHost(StringWriter testOutput) { var hostBuilder = new WebHostBuilder(); // Configure services #if ASPNETCORE2_0 hostBuilder.UseLogJam((LogManagerConfig config, WebHostBuilderContext hostBuilderContext) => #else hostBuilder.UseLogJam((LogManagerConfig config, IServiceProvider serviceProvider) => #endif { config.UseTestOutput(_testOutput); config.UseTextWriter(testOutput); }); hostBuilder.ConfigureServices(serviceCollection => { IMvcCoreBuilder mvcCoreBuilder = serviceCollection.AddMvcCore(); mvcCoreBuilder.AddJsonFormatters(); #if ASPNETCORE2_0 serviceCollection.Configure <LoggerFilterOptions>(filterOptions => filterOptions.MinLevel = LogLevel.Trace); #else serviceCollection.Configure <FilterLoggerSettings>(filterSettings => filterSettings.Add("Default", LogLevel.Trace)); #endif }); // Configure webapp hostBuilder.Configure(appBuilder => { appBuilder.UseStatusCodePages(); appBuilder.UseExceptionHandler(new ExceptionHandlerOptions() { ExceptionHandler = async context => { context.Response.StatusCode = 500; await context.Response.WriteAsync("Unhandled exception"); } }); appBuilder.UseMvc(); }); return(hostBuilder); }
public TestServerFixture() { var webHostBuilder = new WebHostBuilder(); webHostBuilder.ConfigureServices(services => { services.AddCasbinAuthorization(options => { options.DefaultModelPath = TestUtility.GetExampleFile("basic_model.conf"); options.DefaultPolicyPath = TestUtility.GetExampleFile("basic_policy.csv"); }) .BuildServiceProvider(); }); webHostBuilder.Configure(app => { app.UseCasbinAuthorization(); }); TestServer = new TestServer(webHostBuilder); }
public async Task AuthorizationMiddleware_NotConfigured_WhenEndpointIsNotFound() { // Arrange var builder = new WebHostBuilder(); builder.Configure(app => { app.UseRouting(); app.UseEndpoints(b => b.Map("/", TestDelegate).RequireAuthorization()); }) .ConfigureServices(services => { services.AddRouting(); }); using var server = new TestServer(builder); var response = await server.CreateRequest("/not-found").SendAsync("GET"); Assert.Equal(HttpStatusCode.NotFound, response.StatusCode); }
public async Task AuthorizationMiddleware_NotConfigured_Throws() { // Arrange var builder = new WebHostBuilder(); builder.Configure(app => { app.UseRouting(); app.UseEndpoints(b => b.Map("/", TestDelegate).RequireAuthorization()); }) .ConfigureServices(services => { services.AddAuthorization(options => options.DefaultPolicy = new AuthorizationPolicyBuilder().RequireAssertion(_ => true).Build()); services.AddRouting(); }); using var server = new TestServer(builder); var ex = await Assert.ThrowsAsync <InvalidOperationException>(() => server.CreateRequest("/").SendAsync("GET")); Assert.Equal(AuthErrorMessage, ex.Message); }
static void Main(string[] args) { /* * new WebHostBuilder() * .UseKestrel() * .Configure(app => app.Run(context => context.Response.WriteAsync("Hello World!"))) * .Build() * .Run(); */ //1.生成WebHostBuilder var webHostBuilder = new WebHostBuilder(); //2.注册Server webHostBuilder.UseKestrel(); //3.添加中间件 webHostBuilder.Configure(app => app.Run(context => context.Response.WriteAsync("Hello World!"))); //4.构建WebHost IWebHost webHost = webHostBuilder.Build(); //5.启动 webHost.Run(); }