コード例 #1
0
        public async Task <OfferingResultWriteResponse> WriteAsync(OfferingResult offeringResult, IVendorCredentials credentials)
        {
            if (offeringResult == null)
            {
                throw new ArgumentNullException(nameof(offeringResult));
            }

            var writeResponse = new OfferingResultWriteResponse();

            var client = _httpClientCreator.Create(credentials);

            var webRequest = new HttpRequestMessage(HttpMethod.Post, _configuration.ServiceUrl)
            {
                Content = new StringContent(_serializer.Serialize(offeringResult), Encoding.UTF8, "application/json")
            };

            webRequest.Headers.Add(AuthTokenHeaderKey, _authTokenGenerator.Generate(credentials.Id, credentials.SharedSecret));

            var response = await client.SendAsync(webRequest).ConfigureAwait(false);;

            if (response.IsSuccessStatusCode)
            {
                writeResponse.Success = true;
            }
            else
            {
                writeResponse = ProcessUnsuccessfulRequest(response);
            }

            return(writeResponse);
        }
コード例 #2
0
        public void When_Result_IsNull_Then_Write_Throws_ArgumentNullException()
        {
            // set up
            OfferingResult result = null;

            // execute
            var ex = Assert.Throws <AggregateException>(() => _subject.Write(result));

            // verify
            var baseEx = (ArgumentNullException)ex.GetBaseException();

            Assert.Equal("offeringResult", baseEx.ParamName);
        }
コード例 #3
0
        public void When_NoDefaultCredentials_Then_Write_Throws_InvalidOperationException()
        {
            // set up
            var subject = new OfferingResultWriter(_configuration.Object, _serializer.Object, _deserializer.Object, _httpClientCreator.Object, _authTokenGenerator.Object);
            var result  = new OfferingResult();

            // execute
            var ex = Assert.Throws <AggregateException>(() => subject.Write(result));

            // verify
            var baseEx = (InvalidOperationException)ex.GetBaseException();

            Assert.Equal("No default credentials defined", baseEx.Message);
        }
コード例 #4
0
        public async Task <OfferingResultWriteResponse> WriteAsync(OfferingResult offeringResult)
        {
            IVendorCredentials credentials;

            if (_defaultCredentials == null)
            {
#if NETFULL
                credentials = new VendorCredentialsFromConfig();
#else
                throw new InvalidOperationException("No default credentials defined");
#endif
            }
            else
            {
                credentials = _defaultCredentials;
            }

            return(await WriteAsync(offeringResult, credentials));
        }
コード例 #5
0
        public void When_ValidRequest_Write_Returns_OfferingWriteResult_Success_True()
        {
            // set up
#if (NET452)
            // explicitly support TLS 1.2
            ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;
#endif

#if NETFULL
            var vendorId = Guid.Parse(ConfigurationManager.AppSettings[VendorCredentialsFromConfig.IdKey]);
            var secret   = Guid.Parse(ConfigurationManager.AppSettings[VendorCredentialsFromConfig.SharedSecretKey]);

            var requestor = OfferingRequestor.Create(vendorId, secret);
            var writer    = OfferingResultWriter.Create(vendorId, secret);
#else
            var builder = new ConfigurationBuilder()
                          .SetBasePath(string.Concat(Directory.GetCurrentDirectory(), @"\..\..\..\..\..\..\InsuranceHub.Tests.Configuration"))
                          .AddJsonFile("InsuranceHub.Client.Test.Acceptance.json");

            var rootConfig = builder.Build();

            var vendorCredentials = rootConfig.GetSection("insuranceHub:credentials").Get <VendorCredentials>();
            var requestorConfig   = rootConfig.GetSection("insuranceHub:offeringRequestService").Get <OfferingRequestorConfiguration>();
            var writerConfig      = rootConfig.GetSection("insuranceHub:offeringResultService").Get <OfferingResultWriterConfiguration>();

            var requestor = new OfferingRequestor(requestorConfig, new JsonSerializer(), new JsonDeserializer(), new HttpClientCreator(new ProxyConfiguration()), new TokenGenerator(new HmacSha256HashGenerator(Encoding.UTF8), new DateTimeProvider()), vendorCredentials);

            var writer = new OfferingResultWriter(writerConfig, new JsonSerializer(), new JsonDeserializer(), new HttpClientCreator(new ProxyConfiguration()), new TokenGenerator(new HmacSha256HashGenerator(Encoding.UTF8), new DateTimeProvider()), vendorCredentials);
#endif

            var vendorReference = Guid.NewGuid();

            var products = new List <Product>
            {
                new Product {
                    CategoryCode = "TKT", CurrencyCode = "GBP", Price = 10.50, CompletionDate = DateTime.UtcNow.AddMonths(2)
                }
            };

            var request = new OfferingRequest
            {
#if NETFULL
                VendorId = vendorId,
#else
                VendorId = vendorCredentials.Id,
#endif
                VendorRequestReference = vendorReference.ToString("N"),
                PremiumAsSummary       = true,
                Products = products.ToArray()
            };

            var offering = requestor.Request(request);

            var sales = new List <ProductSale>();

            foreach (var productOffering in offering.ProductOfferings)
            {
                sales.Add(new ProductSale
                {
                    ProductOfferingId = productOffering.Id,
                    Sold = true
                });
            }

            var offeringResult = new OfferingResult
            {
#if NETFULL
                VendorId = vendorId,
#else
                VendorId = vendorCredentials.Id,
#endif
                OfferingId          = offering.Id,
                VendorSaleReference = "InvoiceNumber",
                CustomerForename    = "Forename",
                CustomerSurname     = "Surname",
                Sales = sales.ToArray()
            };

            // exercise
            var actual = writer.Write(offeringResult);

            // verify
            Assert.NotNull(actual);
            Assert.IsType <OfferingResultWriteResponse>(actual);
            Assert.True(actual.Success);
        }
コード例 #6
0
        public OfferingResultWriterFixture()
        {
            _configuration      = new Mock <IOfferingResultWriterConfiguration>();
            _serializer         = new Mock <ISerializer>();
            _deserializer       = new Mock <IDeserializer>();
            _httpClientCreator  = new Mock <IHttpClientCreator>();
            _authTokenGenerator = new Mock <IAuthTokenGenerator>();
            _vendorCredentials  = new Mock <IVendorCredentials>();

            _serviceUrl  = new Uri("https://test.com");
            _throwErrors = true;

            _configuration.Setup(x => x.ServiceUrl).Returns(_serviceUrl);
            _configuration.Setup(x => x.ThrowExceptions).Returns(_throwErrors);

            _id     = Guid.NewGuid();
            _secret = Guid.NewGuid();

            _vendorCredentials.Setup(x => x.Id).Returns(_id);
            _vendorCredentials.Setup(x => x.SharedSecret).Returns((_secret));

            _offeringResult = new OfferingResult
            {
                VendorId            = _id,
                Sales               = new List <ProductSale>().ToArray(),
                VendorSaleReference = "abc123"
            };

            _offeringResultError = new OfferingResult
            {
                VendorId            = _id,
                Sales               = new List <ProductSale>().ToArray(),
                VendorSaleReference = "123456"
            };

            _offeringResultErrorWithNoBody = new OfferingResult
            {
                VendorId            = _id,
                Sales               = new List <ProductSale>().ToArray(),
                VendorSaleReference = "xyz999"
            };

            _offeringResultInvalid = new OfferingResult
            {
                VendorId            = _id,
                Sales               = new List <ProductSale>().ToArray(),
                VendorSaleReference = "666"
            };

            _authToken = "token";

            _okContent                   = "okContent";
            _okResponseBody              = "okResponse";
            _errorContent                = "errorContent";
            _errorResponseBody           = "errorResponse";
            _errorContentWithNoBody      = "errorContentWithNoBody";
            _errorResponseBodyWithNoBody = string.Empty;
            _invalidContent              = "invalidContent";
            _invalidResponseBody         = "InvalidResponse";

            _serializer.Setup(x => x.Serialize(_offeringResult)).Returns(_okContent);
            _serializer.Setup(x => x.Serialize(_offeringResultError)).Returns(_errorContent);
            _serializer.Setup(x => x.Serialize(_offeringResultErrorWithNoBody)).Returns(_errorContentWithNoBody);
            _serializer.Setup(x => x.Serialize(_offeringResultInvalid)).Returns(_invalidContent);

            _mockHttpHandler = new MockHttpMessageHandler();

            _mockHttpHandler.When(HttpMethod.Post, _serviceUrl.AbsoluteUri)
            .WithContent(_okContent)
            .WithHeaders("X-InsuranceHub-AuthToken", _authToken)
            .Respond("application/json", _okResponseBody);

            _mockHttpHandler.When(HttpMethod.Post, _serviceUrl.AbsoluteUri)
            .WithContent(_errorContent)
            .WithHeaders("X-InsuranceHub-AuthToken", _authToken)
            .Respond(HttpStatusCode.InternalServerError, "application/json", _errorResponseBody);

            _mockHttpHandler.When(HttpMethod.Post, _serviceUrl.AbsoluteUri)
            .WithContent(_errorContentWithNoBody)
            .WithHeaders("X-InsuranceHub-AuthToken", _authToken)
            .Respond(HttpStatusCode.InternalServerError, "application/json", _errorResponseBodyWithNoBody);

            _mockHttpHandler.When(HttpMethod.Post, _serviceUrl.AbsoluteUri)
            .WithContent(_invalidContent)
            .WithHeaders("X-InsuranceHub-AuthToken", _authToken)
            .Respond(HttpStatusCode.BadRequest, "application/json", _invalidResponseBody);

            _client = new HttpClient(_mockHttpHandler);

            _errorResponse = new ErrorResponse
            {
                ValidationMessages = new List <string>(),
                Message            = "errorMessage"
            };

            _invalidResponse = new ErrorResponse
            {
                ValidationMessages = new List <string> {
                    "validationMessage1", "validationMessage2"
                },
                Message = "invalidRequest"
            };

            _deserializer.Setup(x => x.Deserialize <ErrorResponse>(_errorResponseBody)).Returns(_errorResponse);
            _deserializer.Setup(x => x.Deserialize <ErrorResponse>(_invalidResponseBody)).Returns(_invalidResponse);

            _httpClientCreator.Setup(x => x.Create(It.IsAny <IVendorCredentials>())).Returns(_client);

            _authTokenGenerator.Setup(x => x.Generate(It.IsAny <Guid>(), It.IsAny <Guid>())).Returns(_authToken);

            _subject = new OfferingResultWriter(_configuration.Object, _serializer.Object, _deserializer.Object, _httpClientCreator.Object, _authTokenGenerator.Object, _vendorCredentials.Object);
        }
コード例 #7
0
 public OfferingResultWriteResponse Write(OfferingResult offeringResult, IVendorCredentials credentials)
 {
     return(WriteAsync(offeringResult, credentials).Result);
 }
コード例 #8
0
 public OfferingResultWriteResponse Write(OfferingResult offeringResult)
 {
     return(WriteAsync(offeringResult).Result);
 }