public void When_ValidRequest_Request_Returns_Offering()
        {
            // 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);
#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 requestor = new OfferingRequestor(requestorConfig, 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()
            };

            // exercise
            var actual = requestor.Request(request);

            // verify
            Assert.NotNull(actual);
            Assert.IsType <Offering>(actual);
            Assert.True(actual.Success);
        }
        public void When_NoDefaultCredentials_Then_Request_Uses_VendorCredentialsFromConfig()
        {
            // set up
            var subject = new OfferingRequestor(_configuration.Object, _serializer.Object, _deserializer.Object, _httpClientCreator.Object, _authTokenGenerator.Object);

            // execute
            subject.Request(_offeringRequest);

            // verify
            _authTokenGenerator.Verify(x => x.Generate(
                                           Guid.Parse(ConfigurationManager.AppSettings[VendorCredentialsFromConfig.IdKey]),
                                           Guid.Parse(ConfigurationManager.AppSettings[VendorCredentialsFromConfig.SharedSecretKey])), Times.Once);
        }
        public void When_NoDefaultCredentials_Then_Request_Throws_InvalidOperationException()
        {
            // set up
            var subject = new OfferingRequestor(_configuration.Object, _serializer.Object, _deserializer.Object, _httpClientCreator.Object, _authTokenGenerator.Object);
            var request = new OfferingRequest();

            // execute
            var ex = Assert.Throws <AggregateException>(() => subject.Request(request));

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

            Assert.Equal("No default credentials defined", baseEx.Message);
        }
        public OfferingRequestorFixture()
        {
            _configuration      = new Mock <IOfferingRequestorConfiguration>();
            _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));

            _offeringRequest = new OfferingRequest
            {
                VendorId               = _id,
                Products               = new List <Product>().ToArray(),
                PremiumAsSummary       = true,
                VendorRequestReference = "abc123"
            };

            _offeringRequestError = new OfferingRequest
            {
                VendorId               = _id,
                Products               = new List <Product>().ToArray(),
                PremiumAsSummary       = true,
                VendorRequestReference = "123456"
            };

            _offeringRequestErrorWithNoBody = new OfferingRequest
            {
                VendorId               = _id,
                Products               = new List <Product>().ToArray(),
                PremiumAsSummary       = true,
                VendorRequestReference = "xyz999"
            };

            _offeringRequestInvalid = new OfferingRequest
            {
                VendorId               = _id,
                Products               = new List <Product>().ToArray(),
                PremiumAsSummary       = true,
                VendorRequestReference = "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(_offeringRequest)).Returns(_okContent);
            _serializer.Setup(x => x.Serialize(_offeringRequestError)).Returns(_errorContent);
            _serializer.Setup(x => x.Serialize(_offeringRequestErrorWithNoBody)).Returns(_errorContentWithNoBody);
            _serializer.Setup(x => x.Serialize(_offeringRequestInvalid)).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);

            _offering = new Offering();

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

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

            _deserializer.Setup(x => x.Deserialize <Offering>(_okResponseBody)).Returns(_offering);
            _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 OfferingRequestor(_configuration.Object, _serializer.Object, _deserializer.Object, _httpClientCreator.Object, _authTokenGenerator.Object, _vendorCredentials.Object);
        }
        public void When_ThrowExceptions_IsTrue_InvalidCredentials_Request_Throws_WebException()
        {
            // 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.NewGuid();

            var defaultCredentials = new VendorCredentials
            {
                Id           = vendorId,
                SharedSecret = secret
            };

            var requestor = new OfferingRequestor(new OfferingRequestorConfiguration {
                ThrowExceptions = true
            }, new JsonSerializer(), new JsonDeserializer(), new HttpClientCreator(new ProxyConfiguration()), new TokenGenerator(new HmacSha256HashGenerator(Encoding.UTF8), new DateTimeProvider()), defaultCredentials);
#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>();
            vendorCredentials.SharedSecret = Guid.NewGuid();

            var requestorConfig = rootConfig.GetSection("insuranceHub:offeringRequestService").Get <OfferingRequestorConfiguration>();
            requestorConfig.ThrowExceptions = true;

            var requestor = new OfferingRequestor(requestorConfig, 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()
            };

            // exercise
            var ex = Assert.Throws <AggregateException>(() => requestor.Request(request));

            // verify
            Assert.IsType <WebException>(ex.GetBaseException());
            var baseEx = (WebException)ex.GetBaseException();
            Assert.NotNull(baseEx.Response);
            Assert.IsType <SimpleWebResponse>(baseEx.Response);
            var response = (SimpleWebResponse)baseEx.Response;
            Assert.Equal(HttpStatusCode.Unauthorized, response.StatusCode);
        }
        public void When_ThrowExceptions_IsFalse_UnknownCategoryCode_Request_Returns_Offering_WithErrorResponse_500()
        {
            // 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 defaultCredentials = new VendorCredentials
            {
                Id           = vendorId,
                SharedSecret = secret
            };

            var requestor = new OfferingRequestor(new OfferingRequestorConfiguration {
                ThrowExceptions = false
            }, new JsonSerializer(), new JsonDeserializer(), new HttpClientCreator(new ProxyConfiguration()), new TokenGenerator(new HmacSha256HashGenerator(Encoding.UTF8), new DateTimeProvider()), defaultCredentials);
#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>();
            requestorConfig.ThrowExceptions = false;

            var requestor = new OfferingRequestor(requestorConfig, 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 = "Unknown", 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()
            };

            // exercise
            var actual = requestor.Request(request);

            // verify
            Assert.NotNull(actual);
            Assert.NotNull(actual.ErrorResponse);
            Assert.IsType <Offering>(actual);
            Assert.False(actual.Success);
            Assert.Equal($"Product not forund for VendorId:'{request.VendorId:N}' and CategoryCode:'Unknown'", actual.ErrorResponse.Message);
            Assert.Equal(HttpStatusCode.InternalServerError, actual.ErrorResponse.HttpStatusCode);
        }