Пример #1
0
        public async Task Post_Accepts_Contact_With_Name_Mocked_Repo()
        {
            var mockRepo = new DataRepositoryCodeMock {
                AllContacts = new List <ContactInfo>()
            };
            var webHost = new Microsoft.AspNetCore.Hosting.WebHostBuilder()
                          .UseStartup <Demo.WebApp.Startup>()
                          .ConfigureServices(
                services =>
            {
                services.AddSingleton <IDataRepository>(t => mockRepo);
            }
                );;
            var server = new Microsoft.AspNetCore.TestHost.TestServer(webHost);

            var client = server.CreateClient();

            var content = new StringContent(@"{'name':'Bobby Tables','email': '*****@*****.**'}", Encoding.UTF8, "application/json");

            var response = await client.PostAsync("api/contact", content);

            Assert.Equal(HttpStatusCode.OK, response.StatusCode);

            var responseString = await response.Content.ReadAsStringAsync();

            mockRepo.AllContacts.Any(c => c.Name == "Bobby Tables");
        }
Пример #2
0
        public Microsoft.AspNetCore.TestHost.TestServer CreateServer()
        {
            var path = Assembly.GetAssembly(typeof(AccountScenarioBase))
                       .Location;

            var hostBuilder = new WebHostBuilder()
                              .UseContentRoot(Path.GetDirectoryName(path))
                              .ConfigureAppConfiguration(cb =>
            {
                cb.AddJsonFile("appsettings.json", optional: false)
                .AddEnvironmentVariables();
            }).UseStartup <Banking.Api.Startup>();

            Microsoft.AspNetCore.TestHost.TestServer testServer = null;
            try
            {
                testServer = new TestServer(hostBuilder);
            }
            catch (System.Exception ex)
            {
            }



            return(testServer);
        }
Пример #3
0
        protected MultiTenantIntegrationTestBase()
        {
            server = new Microsoft.AspNetCore.TestHost.TestServer(new WebHostBuilder()
                                                                  .UseStartup <IdentityFramework.Iam.TestServer.Startup>()
                                                                  .ConfigureAppConfiguration((hostingContext, config) =>
            {
                config.AddInMemoryCollection(new Dictionary <string, string>()
                {
                    { "UseMultitenancy", "true" },
                    { "TestMode", "true" }
                });
            })
                                                                  .ConfigureTestServices(services =>
            {
                services.AddIdentity <User, Role>()
                .AddEntityFrameworkStores <IdentityDbContext <User, Role, long> >()
                .AddDefaultTokenProviders();

                services.AddAuthentication(options =>
                {
                    options.DefaultAuthenticateScheme = "Bearer";
                    options.DefaultChallengeScheme    = "Bearer";
                }).AddJwtBearer(configureOptions =>
                {
                    configureOptions.ClaimsIssuer = Startup.TokenValidationParameters.ValidIssuer;
                    configureOptions.TokenValidationParameters = Startup.TokenValidationParameters;
                    configureOptions.SaveToken = true;
                });

                services.AddAuthorization();

                services.AddMvc();

                services.AddDbContext <IdentityDbContext <User, Role, long> >(options =>
                                                                              options.UseInMemoryDatabase("test"));

                services.AddMultiTenantIamCore <long>();
                services.Add(new Microsoft.Extensions.DependencyInjection.ServiceDescriptor(typeof(IMultiTenantUserClaimStore <User, long>),
                                                                                            typeof(MemoryMultiTenantStore <User, Role, long, long>),
                                                                                            Microsoft.Extensions.DependencyInjection.ServiceLifetime.Singleton));
                services.Add(new Microsoft.Extensions.DependencyInjection.ServiceDescriptor(typeof(IMultiTenantUserRoleStore <User, long>),
                                                                                            typeof(MemoryMultiTenantStore <User, Role, long, long>),
                                                                                            Microsoft.Extensions.DependencyInjection.ServiceLifetime.Singleton));
                services.Add(new Microsoft.Extensions.DependencyInjection.ServiceDescriptor(typeof(IMultiTenantRoleClaimStore <Role, long>),
                                                                                            typeof(MemoryMultiTenantStore <User, Role, long, long>),
                                                                                            Microsoft.Extensions.DependencyInjection.ServiceLifetime.Singleton));
                services.Add(new Microsoft.Extensions.DependencyInjection.ServiceDescriptor(typeof(IMultiTenantIamProvider <long>),
                                                                                            typeof(MemoryMultiTenantIamProvider <long>),
                                                                                            Microsoft.Extensions.DependencyInjection.ServiceLifetime.Singleton));
            }));
            IdentityFramework.Iam.TestServer.Program.SeedMtData(server.Host.Services);
        }
    public static TestClientFactory GetXpoWebApiTestClientFactory(Type startupType)
    {
        if (_testServer == null)
        {
            var hostBuilder = new WebHostBuilder();
            hostBuilder.UseStartup(startupType);
            _testServer = new Microsoft.AspNetCore.TestHost.TestServer(hostBuilder);
        }

        var testClient = MintClient();
        var testServerHttpClientFactory = new TestClientFactory(testClient);

        return(testServerHttpClientFactory);
    }
Пример #5
0
        private static HttpClient GetByConfig(Action <WebHostBuilder> configureDelegate)
        {
            var b = new WebHostBuilder();

            configureDelegate(b);
            b.UseStartup <TSetup>();
            var fc = new FeatureCollection();
            var f  = new HttpConnectionFeature();

            f.RemoteIpAddress = new IPAddress(new byte[] { 172, 0, 0, 1 });
            f.RemotePort      = 80;
            fc.Set(f);
            var srv = new Microsoft.AspNetCore.TestHost.TestServer(b, fc);

            return(srv.CreateClient());
        }
Пример #6
0
        public async Task Post_Rejects_Contact_With_Missing_Name()
        {
            var webHost = new Microsoft.AspNetCore.Hosting.WebHostBuilder().UseStartup <Demo.WebApp.Startup>();
            var server  = new Microsoft.AspNetCore.TestHost.TestServer(webHost);

            var client = server.CreateClient();

            var content = new StringContent(@"{'email': '*****@*****.**'}", Encoding.UTF8, "application/json");

            var response = await client.PostAsync("api/contact", content);

            Assert.Equal(HttpStatusCode.BadRequest, response.StatusCode);

            var responseString = await response.Content.ReadAsStringAsync();

            var actualErrors = JsonConvert.DeserializeObject <Dictionary <string, string[]> >(responseString);

            Assert.Equal("The Name field is required.", actualErrors["Name"][0]);
        }
Пример #7
0
        protected IntegrationTestBase()
        {
            server = new Microsoft.AspNetCore.TestHost.TestServer(new WebHostBuilder()
                                                                  .UseStartup <IdentityFramework.Iam.TestServer.Startup>()
                                                                  .ConfigureAppConfiguration((hostingContext, config) =>
            {
                config.AddInMemoryCollection(new Dictionary <string, string>()
                {
                    { "UseMultitenancy", "false" },
                    { "TestMode", "true" }
                });
            })
                                                                  .ConfigureTestServices(services =>
            {
                services.AddIdentity <User, Role>()
                .AddEntityFrameworkStores <IdentityDbContext <User, Role, long> >()
                .AddDefaultTokenProviders();

                services.AddAuthentication(options =>
                {
                    options.DefaultAuthenticateScheme = "Bearer";
                    options.DefaultChallengeScheme    = "Bearer";
                }).AddJwtBearer(configureOptions =>
                {
                    configureOptions.ClaimsIssuer = Startup.TokenValidationParameters.ValidIssuer;
                    configureOptions.TokenValidationParameters = Startup.TokenValidationParameters;
                    configureOptions.SaveToken = true;
                });

                services.AddAuthorization();

                services.AddMvc();

                services.AddDbContext <IdentityDbContext <User, Role, long> >(options =>
                                                                              options.UseInMemoryDatabase("test"));

                services.AddIamCore();

                services.AddSingleton <IIamProvider, MemoryIamProvider>();
            }));
            IdentityFramework.Iam.TestServer.Program.SeedData(server.Host.Services);
        }
        protected IntegrationTestBase()
        {
            _server = new Microsoft.AspNetCore.TestHost.TestServer(new WebHostBuilder()
                                                                   .UseStartup <IdentityFramework.Iam.TestServer.Startup>()
                                                                   .ConfigureAppConfiguration((hostingContext, config) =>
            {
                config.AddJsonFile("appsettings.json", optional: false, reloadOnChange: true);
                config.AddEnvironmentVariables();
                config.AddInMemoryCollection(new Dictionary <string, string>()
                {
                    { "UseMultitenancy", "false" },
                    { "TestMode", "true" }
                });
            })
                                                                   .ConfigureTestServices(services =>
            {
                services.AddIdentity <User, Role>()
                .AddEntityFrameworkStores <IamDbContext <User, Role, long> >()
                .AddDefaultTokenProviders();

                services.AddAuthentication(options =>
                {
                    options.DefaultAuthenticateScheme = "Bearer";
                    options.DefaultChallengeScheme    = "Bearer";
                }).AddJwtBearer(configureOptions =>
                {
                    configureOptions.ClaimsIssuer = Startup.TokenValidationParameters.ValidIssuer;
                    configureOptions.TokenValidationParameters = Startup.TokenValidationParameters;
                    configureOptions.SaveToken = true;
                });

                services.AddAuthorization();

                services.AddMvc();

                services.AddIamEntityFramework <User, Role, long>(options =>
                                                                  options.UseSqlServer(ConfigurationHelper.GetConnectionString()));
            }));

            IdentityFramework.Iam.TestServer.Program.SeedData(_server.Host.Services, typeof(IamDbContext <User, Role, long>), ConfigurationHelper.GetConnectionString());
        }
Пример #9
0
        public async Task Get_Returns_Data_With_Moq()
        {
            var mockRepo = new Mock <IDataRepository>();
            var webHost  = new Microsoft.AspNetCore.Hosting.WebHostBuilder()
                           .UseStartup <Demo.WebApp.Startup>()
                           .ConfigureServices(
                services =>
            {
                services.AddSingleton <IDataRepository>(t => mockRepo.Object);
            }
                );;
            var server = new Microsoft.AspNetCore.TestHost.TestServer(webHost);

            var client = server.CreateClient();

            client.DefaultRequestHeaders.Add("ApiKey", "SomeKey");

            var response = await client.GetAsync("api/contact");

            Assert.Equal(HttpStatusCode.OK, response.StatusCode);

            mockRepo.Verify(r => r.GetAllContacts(), Times.Once);
        }
Пример #10
0
        public async Task Get_Returns_Data_With_Mock()
        {
            var mockRepo = A.Fake <IDataRepository>();
            var webHost  = new Microsoft.AspNetCore.Hosting.WebHostBuilder()
                           .UseStartup <Demo.WebApp.Startup>()
                           .ConfigureServices(
                services =>
            {
                services.AddSingleton <IDataRepository>(t => mockRepo);
            }
                );;
            var server = new Microsoft.AspNetCore.TestHost.TestServer(webHost);

            var client = server.CreateClient();

            client.DefaultRequestHeaders.Add("ApiKey", "SomeKey");

            var response = await client.GetAsync("api/contact");

            Assert.AreEqual(HttpStatusCode.OK, response.StatusCode);

            A.CallTo(() => mockRepo.GetAllContacts()).MustHaveHappened();
        }
Пример #11
0
        public async Task WebSocketWorks()
        {
            // Arrange
            // This logger will attempt to access information from HttpRequest once the HttpContext is created
            var logger = new VerifierLogger();
            RequestDelegate appDelegate = async ctx =>
            {
                if (ctx.WebSockets.IsWebSocketRequest)
                {
                    Assert.False(ctx.Request.Headers.ContainsKey(HeaderNames.SecWebSocketProtocol));
                    var websocket = await ctx.WebSockets.AcceptWebSocketAsync();
                    var receiveArray = new byte[1024];
                    while (true)
                    {
                        var receiveResult = await websocket.ReceiveAsync(new System.ArraySegment<byte>(receiveArray), CancellationToken.None);
                        if (receiveResult.MessageType == WebSocketMessageType.Close)
                        {
                            await websocket.CloseAsync(WebSocketCloseStatus.NormalClosure, "Normal Closure", CancellationToken.None);
                            break;
                        }
                        else
                        {
                            var sendBuffer = new System.ArraySegment<byte>(receiveArray, 0, receiveResult.Count);
                            await websocket.SendAsync(sendBuffer, receiveResult.MessageType, receiveResult.EndOfMessage, CancellationToken.None);
                        }
                    }
                }
            };
            var builder = new WebHostBuilder()
                .ConfigureServices(services =>
                {
                    services.AddSingleton<ILogger<IWebHost>>(logger);
                })
                .Configure(app =>
                {
                    app.Run(appDelegate);
                });
            var server = new TestServer(builder);

            // Act
            var client = server.CreateWebSocketClient();
            // The HttpContext will be created and the logger will make sure that the HttpRequest exists and contains reasonable values
            var clientSocket = await client.ConnectAsync(new System.Uri("http://localhost"), CancellationToken.None);
            var hello = Encoding.UTF8.GetBytes("hello");
            await clientSocket.SendAsync(new System.ArraySegment<byte>(hello), WebSocketMessageType.Text, true, CancellationToken.None);
            var world = Encoding.UTF8.GetBytes("world!");
            await clientSocket.SendAsync(new System.ArraySegment<byte>(world), WebSocketMessageType.Binary, true, CancellationToken.None);
            await clientSocket.CloseOutputAsync(WebSocketCloseStatus.NormalClosure, "Normal Closure", CancellationToken.None);

            // Assert
            Assert.Equal(WebSocketState.CloseSent, clientSocket.State);

            var buffer = new byte[1024];
            var result = await clientSocket.ReceiveAsync(new System.ArraySegment<byte>(buffer), CancellationToken.None);
            Assert.Equal(hello.Length, result.Count);
            Assert.True(hello.SequenceEqual(buffer.Take(hello.Length)));
            Assert.Equal(WebSocketMessageType.Text, result.MessageType);

            result = await clientSocket.ReceiveAsync(new System.ArraySegment<byte>(buffer), CancellationToken.None);
            Assert.Equal(world.Length, result.Count);
            Assert.True(world.SequenceEqual(buffer.Take(world.Length)));
            Assert.Equal(WebSocketMessageType.Binary, result.MessageType);

            result = await clientSocket.ReceiveAsync(new System.ArraySegment<byte>(buffer), CancellationToken.None);
            Assert.Equal(WebSocketMessageType.Close, result.MessageType);
            Assert.Equal(WebSocketState.Closed, clientSocket.State);

            clientSocket.Dispose();
        }
Пример #12
0
        public async Task ClientStreaming_Cancellation()
        {
            // Arrange
            var responseStartedSyncPoint = new SyncPoint();
            var responseReadSyncPoint = new SyncPoint();
            var responseEndingSyncPoint = new SyncPoint();
            var requestStreamSyncPoint = new SyncPoint();
            var readCanceled = false;

            RequestDelegate appDelegate = async ctx =>
            {
                // Send headers
                await ctx.Response.BodyWriter.FlushAsync();

                // Ensure headers received by client
                await responseStartedSyncPoint.WaitToContinue();

                var serverBuffer = new byte[1024];
                var serverLength = await ctx.Request.Body.ReadAsync(serverBuffer);

                Assert.Equal("SENT", Encoding.UTF8.GetString(serverBuffer, 0, serverLength));

                await responseReadSyncPoint.WaitToContinue();

                try
                {
                    await ctx.Request.Body.ReadAsync(serverBuffer);
                }
                catch (OperationCanceledException)
                {
                    readCanceled = true;
                }

                await responseEndingSyncPoint.WaitToContinue();
            };

            Stream requestStream = null;

            var builder = new WebHostBuilder().Configure(app => app.Run(appDelegate));
            var server = new TestServer(builder);
            var client = server.CreateClient();

            var httpRequest = new HttpRequestMessage(HttpMethod.Post, "http://localhost:12345");
            httpRequest.Version = new Version(2, 0);
            httpRequest.Content = new PushContent(async stream =>
            {
                requestStream = stream;
                await requestStreamSyncPoint.WaitToContinue();
            });

            // Act
            var response = await client.SendAsync(httpRequest, HttpCompletionOption.ResponseHeadersRead).DefaultTimeout();

            await responseStartedSyncPoint.WaitForSyncPoint().DefaultTimeout();
            responseStartedSyncPoint.Continue();

            var responseContent = await response.Content.ReadAsStreamAsync().DefaultTimeout();

            // Assert

            // Ensure request stream has started
            await requestStreamSyncPoint.WaitForSyncPoint();

            // Write to request
            await requestStream.WriteAsync(Encoding.UTF8.GetBytes("SENT")).AsTask().DefaultTimeout();
            await requestStream.FlushAsync().DefaultTimeout();
            await responseReadSyncPoint.WaitForSyncPoint().DefaultTimeout();

            // Cancel request. Disposing response must be used because SendAsync has finished.
            response.Dispose();
            responseReadSyncPoint.Continue();

            await responseEndingSyncPoint.WaitForSyncPoint().DefaultTimeout();
            responseEndingSyncPoint.Continue();

            Assert.True(readCanceled);

            requestStreamSyncPoint.Continue();
        }
Пример #13
0
        public async Task ClientStreamingWorks()
        {
            // Arrange
            var responseStartedSyncPoint = new SyncPoint();
            var requestEndingSyncPoint = new SyncPoint();
            var requestStreamSyncPoint = new SyncPoint();

            RequestDelegate appDelegate = async ctx =>
            {
                // Send headers
                await ctx.Response.BodyWriter.FlushAsync();

                // Ensure headers received by client
                await responseStartedSyncPoint.WaitToContinue();

                await ctx.Response.WriteAsync("STARTED");

                // ReadToEndAsync will wait until request body is complete
                var requestString = await new StreamReader(ctx.Request.Body).ReadToEndAsync();
                await ctx.Response.WriteAsync(requestString + " POST Response");

                await requestEndingSyncPoint.WaitToContinue();
            };

            Stream requestStream = null;

            var builder = new WebHostBuilder().Configure(app => app.Run(appDelegate));
            var server = new TestServer(builder);
            var client = server.CreateClient();

            var httpRequest = new HttpRequestMessage(HttpMethod.Post, "http://localhost:12345");
            httpRequest.Version = new Version(2, 0);
            httpRequest.Content = new PushContent(async stream =>
            {
                requestStream = stream;
                await requestStreamSyncPoint.WaitToContinue();
            });

            // Act
            var response = await client.SendAsync(httpRequest, HttpCompletionOption.ResponseHeadersRead).DefaultTimeout();

            await responseStartedSyncPoint.WaitForSyncPoint().DefaultTimeout();
            responseStartedSyncPoint.Continue();

            var responseContent = await response.Content.ReadAsStreamAsync().DefaultTimeout();

            // Assert

            // Ensure request stream has started
            await requestStreamSyncPoint.WaitForSyncPoint();

            byte[] buffer = new byte[1024];
            var length = await responseContent.ReadAsync(buffer).AsTask().DefaultTimeout();
            Assert.Equal("STARTED", Encoding.UTF8.GetString(buffer, 0, length));

            // Send content and finish request body
            await requestStream.WriteAsync(Encoding.UTF8.GetBytes("Hello world")).AsTask().DefaultTimeout();
            await requestStream.FlushAsync().DefaultTimeout();
            requestStreamSyncPoint.Continue();

            // Ensure content is received while request is in progress
            length = await responseContent.ReadAsync(buffer).AsTask().DefaultTimeout();
            Assert.Equal("Hello world POST Response", Encoding.UTF8.GetString(buffer, 0, length));

            // Request is ending
            await requestEndingSyncPoint.WaitForSyncPoint().DefaultTimeout();
            requestEndingSyncPoint.Continue();

            // No more response content
            length = await responseContent.ReadAsync(buffer).AsTask().DefaultTimeout();
            Assert.Equal(0, length);
        }