示例#1
0
        public async Task A_Transaction_Will_Be_Created()
        {
            const int Quantity_To_Sell = 8;

            var client = _factory.CreateDefaultClient();

            var createdAccountDetails = await CreateAccount(client);

            var purchase = await CreatePurchase(client, createdAccountDetails);

            var requestData = new SellRequest()
            {
                AccountNumber = createdAccountDetails.AccountNumber,
                MinUnitPrice  = 100,
                ProductCode   = Constants.ProductA,
                Quantity      = Quantity_To_Sell
            };

            var response = await client.PostAsJsonAsync("/api/Sales", requestData);

            response.EnsureSuccessStatusCode();
            var responseData = await response.Content.ReadAsJsonAsync <Sale>();

            Assert.True(responseData.Success);
            Assert.Equal(Constants.ProductA, responseData.ProductCode);
            Assert.Equal(Quantity_To_Sell, responseData.Quantity);
            Assert.True(responseData.UnitPrice >= requestData.MinUnitPrice);
            Assert.Equal(responseData.UnitPrice * Quantity_To_Sell, responseData.TotalValue);
            Assert.NotEqual(Guid.Empty, responseData.TransactionID);
        }
        /// <summary>
        /// Asynchronously authenticates the user and returns the claims associated with the authenticated user.
        /// </summary>
        /// <param name="server">The test server to use to authenticate the user.</param>
        /// <returns>
        /// A dictionary containing the claims for the authenticated user.
        /// </returns>
        protected async Task <IDictionary <string, Claim> > AuthenticateUserAsync(WebApplicationFactory <Program> server)
        {
            IEnumerable <string> cookies;

            // Arrange - Force a request chain that challenges the request to the authentication
            // handler and returns an authentication cookie to log the user in to the application.
            using (var client = server.CreateDefaultClient(new LoopbackRedirectHandler()
            {
                UserIdentity = UserIdentity, UserAttributes = UserAttributes
            }))
            {
                // Act
                using (var result = await client.GetAsync("/me"))
                {
                    // Assert
                    result.StatusCode.ShouldBe(HttpStatusCode.Found);

                    cookies = result.Headers.GetValues("Set-Cookie");
                }
            }

            XElement element;

            // Arrange - Perform an authenticated HTTP request to get the claims for the logged-in users
            using (var client = server.CreateDefaultClient())
            {
                client.DefaultRequestHeaders.Add("Cookie", cookies);

                // Act
                using (var result = await client.GetAsync("/me"))
                {
                    // Assert
                    result.StatusCode.ShouldBe(HttpStatusCode.OK);
                    result.Content.Headers.ContentType.MediaType.ShouldBe("text/xml");

                    string xml = await result.Content.ReadAsStringAsync();

                    element = XElement.Parse(xml);
                }
            }

            element.Name.ShouldBe("claims");
            element.Elements("claim").Count().ShouldBeGreaterThanOrEqualTo(1);

            var claims = new List <Claim>();

            foreach (var claim in element.Elements("claim"))
            {
                claims.Add(
                    new Claim(
                        claim.Attribute("type").Value,
                        claim.Attribute("value").Value,
                        claim.Attribute("valueType").Value,
                        claim.Attribute("issuer").Value));
            }

            return(claims.ToDictionary((key) => key.Type, (value) => value));
        }
示例#3
0
        public void WebApplicationFactory_should_initialize_Api_once()
        {
            for (int i = 0; i < 10; ++i)
            {
                _factory.CreateDefaultClient();
            }

            // This looks ok, the server is initialized once
            Assert.Equal(1, Startup.NumberOfCalls);
        }
示例#4
0
        public async Task Given_A_New_Account_Then_No_Data_Will_Be_Returned()
        {
            var client = _factory.CreateDefaultClient();

            var createdAccountDetails = await CreateAccount(client);

            var response = await client.GetAsync($"/api/Accounts/{createdAccountDetails.AccountNumber}/Transactions");

            var transactions = await response.Content.ReadAsJsonAsync <IEnumerable <Transaction> >();

            Assert.Empty(transactions);
        }
示例#5
0
        public async Task ShouldLogHelloWorld()
        {
            // Arrange

            // Act
            await _factory.CreateDefaultClient().GetAsync("/");

            var log = Assert.Single(_factory.GetSerilogTestLoggerSink().LogEntries);

            // Assert the message rendered by a default formatter
            Assert.Equal("Hello \"World\"!", log.Message);
        }
示例#6
0
        public async Task ShouldLogHelloWorld()
        {
            // Arrange

            // Act
            await _factory.CreateDefaultClient().GetAsync("/");

            // Assert
            Assert.Equal(1, _sink.Writes.Count);
            var log = _sink.Writes.Single();

            // Assert the message rendered by a default formatter
            Assert.Equal("Hello World!", log.Message);
        }
示例#7
0
        protected virtual WebApplicationFactory <Startup> CreateFactory()
        {
            var f = new WebApplicationFactory <Startup>()
                    .WithWebHostBuilder(builder => builder.UseContentRoot("."));
            //{
            //    Environment = TestEnvironment
            //};

            var secretRepository = new SecretStore();

            secretRepository.Assign("1234", "ABCD");

            var mrb        = new HmacMessageRepresentationBuilder();
            var calculator = new HmacSignatureCalculator();

            HmacClient = new HmacClient
            {
                ClientId = "1234"
            };
            var hmacHandler = new HmacClientHandler(HmacClient);
            var requestContentMd5Handler = new RequestContentMd5Handler();
            var hmacSigningHandler       = new HmacSigningHandler(secretRepository, mrb, calculator);

            // Inject all the handlers in the correct order
            Client = f.CreateDefaultClient(hmacHandler, requestContentMd5Handler, hmacSigningHandler);

            //Startup = Program.Startup;

            return(f);
        }
示例#8
0
 public static HttpClient CreateClientForGrpc <TEntryPoint>(this WebApplicationFactory <TEntryPoint> webApplicationFactory) where TEntryPoint : class
 {
     return(webApplicationFactory.CreateDefaultClient(new DelegatingHandler[]
     {
         new OverrideResponseHttpVersionHandler(HttpVersion.Version20)
     }));
 }
示例#9
0
 public static void Initialize()
 {
     Instance = new WebApplicationFactory <Startup>();
     // Actually the WebApplicationFactory has a problem that until CreateDefaultClient() is called, no underlying TestServer instance is created.
     // Also, the underlying TestServer creation has a race condition, calling it from tests running in parallel may cause multiple servers to be spawned.
     Instance.CreateDefaultClient();
 }
示例#10
0
 public static HttpClient CreateHttpClient <TStartup>(this WebApplicationFactory <TStartup> factory)
     where TStartup : class
 {
     return(factory.CreateDefaultClient(
                new TestHttpClientAuthenticationHandler(),
                new HttpClientExceptionHandler()));
 }
示例#11
0
        public void Test1()
        {
            Environment.SetEnvironmentVariable("rp_enabled", "false");

            var client = _factory.CreateDefaultClient();

            client.MaxResponseContentBufferSize = int.MaxValue;

            GrpcChannel ch = GrpcChannel.ForAddress("http://localhost", new GrpcChannelOptions
            {
                HttpClient            = client,
                MaxReceiveMessageSize = null
            });

            var service = new Gauge.Messages.Reporter.ReporterClient(ch);

            service.NotifyExecutionStarting(
                new Gauge.Messages.ExecutionStartingRequest()
            {
                CurrentExecutionInfo = new Gauge.Messages.ExecutionInfo
                {
                    ProjectName = new string('A', 150 * 1024 * 1024)
                }
            });
        }
示例#12
0
        public async Task The_Account_Number_Is_Generated()
        {
            var client = _factory.CreateDefaultClient();

            var requestData = new NewAccountRequest()
            {
                AccountName = "Test Account - " + Guid.NewGuid().ToString()
            };

            var response = await client.PostAsJsonAsync("/api/Accounts", requestData);

            response.EnsureSuccessStatusCode();
            var responseData = await response.Content.ReadAsJsonAsync <AccountDetails>();

            Assert.NotEqual(Guid.Empty, responseData.AccountNumber);
        }
示例#13
0
 public ModelBindingShould(WebApplicationFactory <Example.Startup> factory, ITestOutputHelper output)
 {
     _factory     = factory;
     _output      = output;
     _postCapture = new HttpPostCaptureDelegatingHandler();
     _client      = factory.CreateDefaultClient(_postCapture);
 }
        public PaymentsenseCodingChallengeControllerTests(WebApplicationFactory <Startup> factory)
        {
            _httpClient = factory.CreateDefaultClient();
            _mockLogger = new Mock <ILoggerManager>();

            sut = new CountriesController(_mockLogger.Object);
        }
示例#15
0
        public TestAppFactory(WebApplicationFactory <Startup> factory)
        {
            Environment.SetEnvironmentVariable("SES_ACCESS_KEY", "access-key");
            Environment.SetEnvironmentVariable("SES_SECRET_KEY", "secret-key");

            _factory = factory.WithWebHostBuilder(builder =>
            {
                builder
                .UseEnvironment("integrationtest")
                .UseContentRoot(Path.GetFullPath(Path.Combine(
                                                     PlatformServices.Default.Application.ApplicationBasePath,
                                                     "..", "..", "..", "..", "..", "src", "StockportWebapp")))
                .ConfigureTestServices(services =>
                {
                    services.AddSingleton <IHttpClient>(p => GetHttpClient(p.GetService <ILoggerFactory>()));
                    services.AddSingleton <Func <HttpClient> >(p => () =>
                                                               new HttpClient(new FakeResponseHandlerFactory().ResponseHandler));
                    services.AddSingleton <IHttpEmailClient, FakeHttpEmailClient>();
                    services.AddMvc(options =>
                    {
                        for (var i = 0; i < options.Filters.Count; i++)
                        {
                            options.Filters.RemoveAt(i);
                        }
                    });
                });
            });

            _client = _factory.CreateDefaultClient();
        }
示例#16
0
 public AppFixture()
 {
     _webAppFactory = new WebApplicationFactory <Startup>().WithWebHostBuilder(builder =>
     {
         builder.UseEnvironment("IntegrationTesting");
         builder.ConfigureAppConfiguration(configBuilder =>
         {
             var config               = configBuilder.Build();
             var azureAdOptions       = config.GetSection("AzureAd").Get <AzureAdOptions>();
             var appAuthentication    = config.GetSection("AppAuthenticationSetting").Get <AppAuthenticationSettings>();
             var userAuthentication   = config.GetSection("UserAuthenticationSettings").Get <UserAuthenticationSettings>();
             var userAdmin            = config.GetSection("UserAdmin").Get <UserAuthenticationSettingsDetails>();
             var userRegular          = config.GetSection("UserRegular").Get <UserAuthenticationSettingsDetails>();
             var userNotInDatabase    = config.GetSection("UserNotInDatabase").Get <UserAuthenticationSettingsDetails>();
             var userNoRoles          = config.GetSection("UserNoRoles").Get <UserAuthenticationSettingsDetails>();
             var wrongRolesScopesComb = config.GetSection("WrongRolesScopesComb").Get <UserAuthenticationSettingsWrongRolesScopesComb>();
             Settings = new IntegrationTestSettings
             {
                 Authority            = $@"{azureAdOptions.Authority}/v2.0",
                 ApplicationIdUri     = azureAdOptions.ApplicationIdUri,
                 AppAuthentication    = appAuthentication,
                 UserAuthentication   = userAuthentication,
                 UserAdmin            = userAdmin,
                 UserRegular          = userRegular,
                 UserNotInDatabase    = userNotInDatabase,
                 UserNoRoles          = userNoRoles,
                 WrongRolesScopesComb = wrongRolesScopesComb
             };
         });
     });
     Client = _webAppFactory.CreateDefaultClient();
 }
示例#17
0
        public async Task HealthCheck_Always_ShouldReturnOk()
        {
            var httpClient = _factory.CreateDefaultClient();

            var response = await httpClient.GetAsync(HealthCheckEndpoint);

            response.EnsureSuccessStatusCode();
        }
        public static GrpcChannel CreateGrpcChannel(this WebApplicationFactory <Startup> factory, DelegatingHandler handler)
        {
            var client = factory.CreateDefaultClient(handler);

            return(GrpcChannel.ForAddress(client.BaseAddress, new GrpcChannelOptions
            {
                HttpClient = client
            }));
        }
        public static GrpcChannel CreateGrpcChannel(this WebApplicationFactory <Startup> factory)
        {
            var client = factory.CreateDefaultClient(new ResponseVersionHandler());

            return(GrpcChannel.ForAddress(client.BaseAddress, new GrpcChannelOptions
            {
                HttpClient = client
            }));
        }
 public void OneTimeSetUp()
 {
     webAppFactory = new WebApplicationFactory <Startup>(port: 4972);
     webAppFactory.CreateDefaultClient();
     client            = webAppFactory.CreateClient();
     scope             = webAppFactory.Host.Services.CreateScope();
     serviceProvider   = scope.ServiceProvider;
     usuarioController = new UsuarioController(serviceProvider.GetService <IUsuarioService>());
 }
        public void OneTimeSetup()
        {
            var testEnvironemt = new TestEnvironment(services =>
            {
            });

            factory = new TestAppFactory();
            client  = factory.CreateDefaultClient(new LoggingHandler());
        }
示例#22
0
        public TestFixture()
        {
            _factory = new WebApplicationFactory <Startup>();
            var client = _factory.CreateDefaultClient(new ResponseVersionHandler());

            GrpcChannel = GrpcChannel.ForAddress(client.BaseAddress, new GrpcChannelOptions
            {
                HttpClient = client
            });
        }
        public async Task VerifyHealthCheckAPIAsync(string url)
        {
            // Arrange
            var client = factory.CreateDefaultClient();

            // Act
            string healthStatus = await client.GetStringAsync(url);

            // Assert
            Assert.Equal("Healthy", healthStatus, true);
        }
示例#24
0
        public async Task A_Transaction_Will_Be_Created()
        {
            var client = _factory.CreateDefaultClient();

            var createdAccountDetails = await CreateAccount(client);

            var requestData = new BuyRequest()
            {
                AccountNumber = createdAccountDetails.AccountNumber,
                MaxUnitPrice  = 150,
                ProductCode   = Constants.ProductA,
                Quantity      = 10
            };

            var response = await client.PostAsJsonAsync("/api/Purchases", requestData);

            response.EnsureSuccessStatusCode();
            var responseData = await response.Content.ReadAsJsonAsync <Purchase>();

            Assert.True(responseData.Success);
        }
示例#25
0
        public async Task ShouldReturnSuccessResponse()
        {
            using var factory = new WebApplicationFactory <Startup>();
            var client   = factory.CreateDefaultClient();
            var response = await client.GetAsync("api/values");

            Assert.AreEqual(HttpStatusCode.OK, response.StatusCode);
            Assert.AreEqual("application/json; charset=utf-8", response.Content.Headers.ContentType?.ToString());

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

            Assert.AreEqual("[\"value1\",\"value2\"]", json);
        }
        public void Start()
        {
            var factory = new WebApplicationFactory <Startup>().WithWebHostBuilder(configuration =>
            {
                configuration.ConfigureLogging(logging =>
                {
                    logging.ClearProviders(); // stop the output being incredibly verbose since we're doing thousands of requests
                });
            });

            this.server = factory;
            this.client = factory.CreateDefaultClient();
        }
        public BaGetClientIntegrationTests(
            BaGetWebApplicationFactory factory,
            ITestOutputHelper output)
        {
            _factory = factory.WithOutput(output);

            var serviceIndexUrl = new Uri(_factory.Server.BaseAddress, "v3/index.json");

            var httpClient = _factory.CreateDefaultClient();

            _clientFactory = new NuGetClientFactory(httpClient, serviceIndexUrl.AbsoluteUri);
            _client        = new NuGetClient(_clientFactory);
        }
        public async Task GetExchangesShouldGetExchangeRatesFromAllSourcesGivenSourceSpecifiedAsAll()
        {
            HttpClient client = _factory.CreateDefaultClient();

            HttpResponseMessage response = await client.GetAsync("/api/v1/exchanges/all");

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

            var exchangeRates = await response.Content.ReadAsAsync <IEnumerable <ExchangeRatesViewModel> >();

            Assert.NotNull(exchangeRates);
            Assert.NotEmpty(exchangeRates);
        }
示例#29
0
        public async Task The_Known_Products_Are_Returned()
        {
            var client = _factory.CreateDefaultClient();

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

            var products = await response.Content.ReadAsJsonAsync <List <Product> >();

            Assert.Equal(4, products.Count());
            Assert.Equal(Constants.ProductA, products[0].ProductCode);
            Assert.Equal(Constants.ProductB, products[1].ProductCode);
            Assert.Equal(Constants.ProductC, products[2].ProductCode);
            Assert.Equal(Constants.ProductD, products[3].ProductCode);
        }
示例#30
0
        public async Task Which_Does_Not_Exist_Then_A_404_Error_Will_Be_Returned()
        {
            var client = _factory.CreateDefaultClient();

            var madeUpAccountNumber = Guid.NewGuid().ToString();

            var response = await client.GetAsync("/api/Accounts/" + madeUpAccountNumber);

            Assert.Equal(HttpStatusCode.NotFound, response.StatusCode);
        }