コード例 #1
0
 public PaymentModelValidationProvider()
 {
     // Initialise config values to validate model, defaults are assigned if not found
     _minAmount           = decimal.TryParse(PGConfiguration.TryGetValue("MinAmount"), out var minAmount) ? minAmount : 0;
     _maxAmount           = decimal.TryParse(PGConfiguration.TryGetValue("MaxAmount"), out var maxAmount) ? maxAmount : 10000;
     _supportedCurrencies = PGConfiguration.TryGetValue("SupportedCurrencies")?
                            .Split(',', StringSplitOptions.RemoveEmptyEntries).Select(str => str.Trim()).ToHashSet() ?? new HashSet <string>()
     {
         "GBP", "EUR", "USD"
     };
 }
コード例 #2
0
        public void CreatePaymentAsync_Payment_Inserted_Returns_true()
        {
            // Arrange
            var bankUrl = "someUrl";

            var configRootMock = new Mock<IConfigurationSection>();
            configRootMock.SetupGet(m => m.Key)
                .Returns("ExternalBankUri");
            configRootMock.SetupGet(m => m.Value)
                .Returns(bankUrl);

            var configurationSections = new IConfigurationSection[1]
            {
                configRootMock.Object,
            };

            PGConfiguration.SetKeyValues(configurationSections);

            var dbContextMock = _mocks.Create<IDatabaseContext>();
            dbContextMock.Setup(m => m.Insert(It.Is<PaymentDto>(p =>
                 p.Uid == "Fake" &&
                 p.State == Framework.Enums.PaymentState.Completed)))
                .Returns(1);

            var responseMessage = new HttpResponseMessage();
            responseMessage.StatusCode = HttpStatusCode.OK;
            responseMessage.Content = new FakeHttpContent("Fake");

            var httpClientWrapperMock = _mocks.Create<IHttpClientWrapper>();
            httpClientWrapperMock.Setup(m => m.PostAsync(bankUrl, It.IsAny<StringContent>()))
                .Returns(Task.FromResult(responseMessage));
            httpClientWrapperMock.Setup(m => m.Dispose());

            var paymentBLL = new PaymentBLL(dbContextMock.Object, httpClientWrapperMock.Object);

            // Act
            var res = paymentBLL.CreatePaymentAsync(new PaymentDto()).Result;

            // Assert
            _mocks.Verify();
            Assert.AreEqual(res, true);
        }
コード例 #3
0
        public void SetKeyValues_Key_Values_Set()
        {
            var key1   = "Key1";
            var value1 = "Value1";
            var key2   = "Key2";
            var value2 = "Value2";

            var configRootMock = new Mock <IConfigurationSection>();

            configRootMock.SetupGet(m => m.Key)
            .Returns(key1);
            configRootMock.SetupGet(m => m.Value)
            .Returns(value1);

            var configRootMock2 = new Mock <IConfigurationSection>();

            configRootMock2.SetupGet(m => m.Key)
            .Returns(key2);
            configRootMock2.SetupGet(m => m.Value)
            .Returns("Value2");

            var configurationSections = new IConfigurationSection[2]
            {
                configRootMock.Object,
                configRootMock2.Object
            };

            // Act
            PGConfiguration.SetKeyValues(configurationSections);
            var key1Result           = PGConfiguration.TryGetValue(key1);
            var key2Result           = PGConfiguration.TryGetValue(key2);
            var nonexistantKeyResult = PGConfiguration.TryGetValue("Random");

            // Assert
            configRootMock.Verify();
            configRootMock2.Verify();
            Assert.AreEqual(key1Result, value1);
            Assert.AreEqual(key2Result, value2);
            Assert.AreEqual(nonexistantKeyResult, null);
        }
コード例 #4
0
        public void CreatePaymentAsync_Status_Code_Not_200_Returns_False()
        {
            // Arrange
            var bankUrl = "someUrl";

            var configRootMock = new Mock<IConfigurationSection>();
            configRootMock.SetupGet(m => m.Key)
                .Returns("ExternalBankUri");
            configRootMock.SetupGet(m => m.Value)
                .Returns(bankUrl);

            var configurationSections = new IConfigurationSection[1]
            {
                configRootMock.Object,
            };

            PGConfiguration.SetKeyValues(configurationSections);

            var responseMessage = new HttpResponseMessage();
            responseMessage.StatusCode = HttpStatusCode.NotFound;
            responseMessage.Content = new FakeHttpContent("Fake");

            var httpClientWrapperMock = _mocks.Create<IHttpClientWrapper>();
            httpClientWrapperMock.Setup(m => m.PostAsync(bankUrl, It.IsAny<StringContent>()))
                .Returns(Task.FromResult(responseMessage));
            httpClientWrapperMock.Setup(m => m.Dispose());

            var paymentBLL = new PaymentBLL(null, httpClientWrapperMock.Object);

            // Act
            var res = paymentBLL.CreatePaymentAsync(new PaymentDto()).Result;

            // Assert
            _mocks.Verify();
            Assert.AreEqual(res, false);
        }
コード例 #5
0
        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {
            // Setup middleware to handle application exceptions
            app.UseExceptionHandler(errorApp =>
            {
                errorApp.UseMiddleware <ExceptionHandlerMiddleware>();
            });

            // Enable middleware to serve generated Swagger as a JSON endpoint.
            app.UseSwagger();

            // Enable middleware to serve swagger-ui (HTML, JS, CSS, etc.),
            // specifying the Swagger JSON endpoint.
            app.UseSwaggerUI(c =>
            {
                c.SwaggerEndpoint("/swagger/v1/swagger.json", "PaymentGateway API");
            });

            // Small custom middlewares
            app.Use(async(context, next) =>
            {
                // Read request body for improved logging
                context.Request.EnableBuffering();
                var requestReader = new StreamReader(context.Request?.Body);
                Environment.SetEnvironmentVariable(Constants.PGRequestBody, await requestReader.ReadToEndAsync());
                context.Request.Body.Position = 0;

                // Return header to search through logs
                context.Response.Headers.Add("TraceIdentifier", context.TraceIdentifier);
                context.Response.OnStarting(() =>
                {
                    // When exception thrown use ExceptionHandlerMiddleware
                    if (context.Response.StatusCode != 500)
                    {
                        var id = context.User.Identity;
                        Log.Information($"TraceIdentifier: {context.TraceIdentifier}\n"
                                        + $"Request URI: {context.Request?.Method} {context.Request?.GetEncodedUrl()}\n"
                                        + $"Request Body: {Environment.GetEnvironmentVariable(Constants.PGRequestBody)}\n"
                                        + $"Status Code: {context.Response.StatusCode}\n"
                                        + $"Request user: {id?.Name ?? "(anon)"}\n");
                    }

                    return(Task.CompletedTask);
                });

                await next.Invoke();
            });

            app.UseHttpsRedirection();

            app.UseRouting();

            // Authenticate first to see who the user is
            app.UseAuthentication();
            // Authorise then if access allowed
            app.UseAuthorization();

            app.UseEndpoints(endpoints =>
            {
                endpoints.MapControllers();
            });

            // Load defaults from appsettings.json
            var appConfig = new ConfigurationBuilder()
                            .SetBasePath(AppContext.BaseDirectory)
                            .AddJsonFile("appsettings.json", optional: false)
                            .Build();

            // Set environment config values
            PGConfiguration.SetKeyValues(appConfig.GetChildren());
        }
コード例 #6
0
 public PaymentBLL(IDatabaseContext db, IHttpClientWrapper httpClient)
 {
     _db         = db;
     _httpClient = httpClient;
     _bankUri    = PGConfiguration.TryGetValue("ExternalBankUri");
 }