Ejemplo n.º 1
0
        public async Task <Offering> RequestAsync(OfferingRequest request, IVendorCredentials credentials)
        {
            if (request == null)
            {
                throw new ArgumentNullException(nameof(request));
            }

            Offering offering = null;

            var client = _httpClientCreator.Create(credentials);

            var webRequest = new HttpRequestMessage(HttpMethod.Post, _configuration.ServiceUrl)
            {
                Content = new StringContent(_serializer.Serialize(request), 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)
            {
                offering = _deserializer.Deserialize <Offering>(response.Content.ReadAsStringAsync().Result);

                offering.Success = true;
            }
            else
            {
                offering = ProcessUnsuccessfulRequest(response);
            }

            return(offering);
        }
Ejemplo n.º 2
0
    public void OnSendOfferingRequset(byte type, string itemId, byte useHc, ServerCallbackDelegate callback)
    {
        OfferingRequest request = new OfferingRequest();

        request.type   = type;
        request.itemId = itemId;
        request.useHc  = useHc;

        SendCommand(request, callback);
    }
        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_Request_IsNull_Then_Request_Throws_ArgumentNullException()
        {
            // set up
            OfferingRequest request = null;

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

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

            Assert.Equal("request", baseEx.ParamName);
        }
        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);
        }
Ejemplo n.º 6
0
        public async Task <Offering> RequestAsync(OfferingRequest request)
        {
            IVendorCredentials credentials;

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

            return(await RequestAsync(request, credentials));
        }
Ejemplo n.º 7
0
        public async Task CreateOfferingProductAndPublish()
        {
            string platformIdentifier = PlatformId;
            string platformName       = ServiceConstants.FMPPlatformName;
            string platformHostName   = PlatformHost;
            string productSku         = "SKU300";
            string productExternalId  = ProductExternalId;
            string offeringFullName   = "Put the cloth";
            string offeringCategory   = "externalDev";
            IntegrationsWebAppClient integrationsClientV2 = new IntegrationsWebAppClient(ServiceConstants.IntegrationsAPIUrl, platformName);
            IntegrationsWebAppClient integrationsClientV1 = new IntegrationsWebAppClient(ServiceConstants.IntegrationsAPIUrl, platformIdentifier);

            PostProductRequest createProductRequest = new PostProductRequest
            {
                Identifier         = productExternalId,
                AlternateSkus      = null,
                BrandSku           = "4WW3274",
                Cost               = 11,
                DisplayProductCode = productSku,
                IsOcm              = false,
                IsPurchaseable     = true,
                Name               = "product test name",
                OemRelationships   = new List <ProductOem>
                {
                    new ProductOem
                    {
                        OemName = "name",
                        Type    = 2,
                        OemSku  = "pika"
                    }
                },
                ProductCode     = productSku,
                ProductLeadType = 2,
                Prop65Message   = new ProductProp65Message
                {
                    MessageBody = "This product has been created through a test automation tool"
                },
                SearchKeywords = "test",
                Shipping       = new ProductShippingAttributes()
                {
                    FreightClass      = 179,
                    IsFreeShip        = true,
                    IsFreightOnly     = false,
                    IsQuickShip       = true,
                    WeightActual      = 6.72m,
                    WeightDimensional = 20.62m,
                    Height            = 9.61m,
                    Width             = 16.48m,
                    Length            = 9.60m
                },
                Specs = new List <ProductSpecification>
                {
                    new ProductSpecification
                    {
                        Name  = "pika pika",
                        Value = "chu shock"
                    }
                },
            };

            HttpResponseExtended <ProductResponse> createProductResponse = await integrationsClientV2.Products.Create(createProductRequest);

            Assert.IsNotNull(createProductResponse, $"{nameof(createProductResponse)} is null");
            Assert.IsTrue(createProductResponse.Success == true, $"Product status code is {createProductResponse.StatusCode}");
            Assert.IsNotNull(createProductResponse.Result.ExternalIdentifier, $"{nameof(createProductResponse.Result.ExternalIdentifier)} is null");

            OfferingRequest createOfferingRequest = new OfferingRequest
            {
                Identifier = OfferingExternalId,
                CatalogId  = "externalDev",
                Links      = new List <OfferingLink>
                {
                    new OfferingLink
                    {
                        Label     = "hot side catalog",
                        Url       = "http://tevin.info/unbranded-steel-chicken/primary/bypass",
                        Reference = "20"
                    }
                },
                CategoryIds = new List <string>//TODO: add a real category should be an external identifier
                {
                    offeringCategory
                },
                Description  = "Description for this test offering e2e",
                FullName     = offeringFullName,
                HomeCategory = offeringCategory,
                HtmlPage     = new HtmlPage
                {
                    H1    = $"H1 {offeringFullName}",
                    Title = $"Title {offeringFullName}",
                    Meta  = $"Meta {offeringFullName}",
                    Url   = $"{offeringFullName.ToLower().Replace(" ", "-")}"
                },
                IsPreviewAble = true,
                IsPublishAble = true,
                ProductId     = createProductResponse.Result.ExternalIdentifier
            };

            HttpResponseExtended <OfferingResponse> createOfferingResponse = await integrationsClientV2.Offering.Create(createOfferingRequest);

            Assert.IsNotNull(createOfferingResponse, $"{nameof(createOfferingResponse)} is null");
            Assert.IsTrue(createOfferingResponse.Success, $"Offering response status is {createOfferingResponse.StatusCode}");

            //Publish merchandise
            PublishMerchandiseRequest publishMerchandiseRequest = new PublishMerchandiseRequest
            {
                Hostname         = platformHostName,
                PromoteOnSuccess = true,
                ClearUnusedCache = true
            };

            HttpResponse <PublishMerchandiseResponse> publishMerchandiseResponse = await integrationsClientV1.PublishMerchandise.Publish(publishMerchandiseRequest);

            Assert.IsNotNull(publishMerchandiseResponse, $"{nameof(publishMerchandiseResponse)} is null");
            Assert.IsNull(publishMerchandiseResponse.Message, publishMerchandiseResponse.Message);

            //publish content request
            PublishContentRequest publishContentRequest = new PublishContentRequest
            {
                Hostname = platformHostName
            };

            //HttpResponse<PublishContentResponse> publishContentResponse = await integrationsClientV1.PublishContent.Publish(publishContentRequest);

            //Assert.IsNotNull(publishContentResponse, $"{nameof(publishContentResponse)}");
        }
        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);
        }
Ejemplo n.º 9
0
        public override async Task TestScenarioSetUp(OfferingTestData testData)
        {
            //create catalog
            CatalogRequest catalogRequest = new CatalogRequest
            {
                Name               = "Seed catalog name",
                Identifier         = Guid.NewGuid(),
                CreatedBy          = "Seed helper",
                ExternalIdentifier = testData.CatalogExtId,
                PlatformIdentifier = new Guid(ServiceConstants.AllPointsPlatformId),
                CreatedUtc         = DateTime.UtcNow.ToString(),
                UpdatedUtc         = DateTime.UtcNow.ToString()
            };
            await Client.Catalogs.Create(catalogRequest);

            //create a category
            CategoryRequest categoryRequest = new CategoryRequest
            {
                CatalogId     = testData.CatalogExtId,
                Identifier    = testData.CategoryExtId,
                FullName      = "sample category name",
                IsLanding     = false,
                ShortName     = "sample name",
                IsTopMenu     = false,
                UrlSegment    = "sample-category-name/",
                CollapseOrder = 1,
                HtmlPage      = new HtmlPage
                {
                    H1    = "H1 sample thing",
                    Title = "Title sample thing",
                    Meta  = "Meta sample thing",
                    Url   = "any-thing/"
                },
                IsSubcatalog = false,
                IsMore       = false,
                CreatedBy    = "temporal test method"
            };
            await Client.Categories.Create(categoryRequest);

            //create a brand
            PostBrandRequest brandRequest = new PostBrandRequest
            {
                CreatedBy          = "temporal test method",
                CreatedUtc         = DateTime.Now.ToString(),
                UpdatedUtc         = DateTime.Now.ToString(),
                ExternalIdentifier = testData.BrandExtId,
                Identifier         = Guid.NewGuid(),
                PlatformIdentifier = new Guid(ServiceConstants.AllPointsPlatformId),
                FullName           = "test name",
                ShortName          = "test name short",
                HtmlPage           = new HtmlPage
                {
                    H1    = "test",
                    Meta  = "meta",
                    Title = "test title",
                    Url   = "test/"
                },
                Favorability = 2,
                UrlSegment   = "test/"
            };
            await Client.Brands.Create(brandRequest);

            //create a product
            ProductRequest productRequest = new ProductRequest
            {
                CreatedBy          = "temporal product request",
                Identifier         = testData.ProductExtId,
                Cost               = 11,
                DisplayProductCode = "temporal-sku",
                IsOcm              = false,
                IsPurchaseable     = true,
                Name               = "product test name",
                ProductCode        = "temporal-sku",
                Prop65Message      = new ProductProp65Message
                {
                    MessageBody = "This product has been created through a test automation tool"
                },
                SearchKeywords = "test,seed",
                Shipping       = new ProductShippingAttributes
                {
                    FreightClass      = 179,
                    IsFreeShip        = false,
                    IsFreightOnly     = false,
                    IsQuickShip       = false,
                    WeightActual      = 6.72m,
                    WeightDimensional = 20.62m,
                    Height            = 9.61m,
                    Width             = 16.48m,
                    Length            = 9.60m
                },
                Specs = new List <ProductSpecification>
                {
                    new ProductSpecification
                    {
                        Name  = "name of spec",
                        Value = "value of spec"
                    }
                },
                OemRelationships = new List <ProductOem>
                {
                    new ProductOem
                    {
                        OemName = "oem name 01",
                        Type    = 1,
                        OemSku  = "FakeOemSku"
                    }
                },
                ProductLeadType        = 1,
                BrandSku               = "fake",
                PrimaryBrandIdentifier = testData.BrandExtId
            };
            await Client.Products.Create(productRequest);

            //create a offering
            string          offeringFullName = "temporal frozen Sturkey";
            OfferingRequest offeringRequest  = new OfferingRequest
            {
                CreatedBy    = "temporal offering",
                Identifier   = testData.OfferingExtId,
                CatalogId    = testData.CatalogExtId,
                ProductId    = testData.ProductExtId,
                HomeCategory = testData.CategoryExtId,
                CategoryIds  = new List <string>(),
                Description  = "temporal Description for this offering",
                FullName     = offeringFullName,
                HtmlPage     = new HtmlPage
                {
                    H1    = $"H1 {offeringFullName}",
                    Title = $"Title {offeringFullName}",
                    Meta  = $"Meta {offeringFullName}",
                    Url   = $"{offeringFullName.Replace(" ", "-")}"
                },
                IsPublishAble = true,
                IsPreviewAble = true,
                Links         = new List <OfferingLink>(),
            };
            await Client.Offerings.Create(offeringRequest);
        }
Ejemplo n.º 10
0
        public async Task POST_Offering_Success()
        {
            string offeringFullName   = "frozen turkey ready to deploy";
            string externalIdentifier = "postOfferingExternal01";

            OfferingTestData testData = new OfferingTestData
            {
                OfferingExtId = externalIdentifier,
                CategoryExtId = "offeringCategoryExternal01",
                CatalogExtId  = "offeringCatalogExternal01",
                ProductExtId  = "offeringProductExternal01",
                BrandExtId    = "offeringBrandExternal01"
            };

            //create catalog
            CatalogRequest catalogRequest = new CatalogRequest
            {
                Name               = "Seed catalog name",
                Identifier         = Guid.NewGuid(),
                CreatedBy          = "Seed helper",
                ExternalIdentifier = testData.CatalogExtId,
                PlatformIdentifier = new Guid(ServiceConstants.AllPointsPlatformId),
                CreatedUtc         = DateTime.UtcNow.ToString(),
                UpdatedUtc         = DateTime.UtcNow.ToString()
            };
            await Client.Catalogs.Create(catalogRequest);

            //create a category
            CategoryRequest categoryRequest = new CategoryRequest
            {
                CatalogId     = testData.CatalogExtId,
                Identifier    = testData.CategoryExtId,
                FullName      = "sample category name",
                IsLanding     = false,
                ShortName     = "sample name",
                IsTopMenu     = false,
                UrlSegment    = "sample-category-name/",
                CollapseOrder = 1,
                HtmlPage      = new HtmlPage
                {
                    H1    = "H1 sample thing",
                    Title = "Title sample thing",
                    Meta  = "Meta sample thing",
                    Url   = "any-thing/"
                },
                IsSubcatalog = false,
                IsMore       = false,
                CreatedBy    = "temporal test method"
            };
            await Client.Categories.Create(categoryRequest);

            //create a brand
            PostBrandRequest brandRequest = new PostBrandRequest
            {
                CreatedBy          = "temporal test method",
                CreatedUtc         = DateTime.Now.ToString(),
                UpdatedUtc         = DateTime.Now.ToString(),
                ExternalIdentifier = testData.BrandExtId,
                Identifier         = Guid.NewGuid(),
                PlatformIdentifier = new Guid(ServiceConstants.AllPointsPlatformId),
                FullName           = "test name",
                ShortName          = "test name short",
                HtmlPage           = new HtmlPage
                {
                    H1    = "test",
                    Meta  = "meta",
                    Title = "test title",
                    Url   = "test/"
                },
                Favorability = 2,
                UrlSegment   = "test/"
            };
            await Client.Brands.Create(brandRequest);

            //create a product
            ProductRequest productRequest = new ProductRequest
            {
                CreatedBy          = "temporal product request",
                Identifier         = testData.ProductExtId,
                Cost               = 11,
                DisplayProductCode = "temporal-sku",
                IsOcm              = false,
                IsPurchaseable     = true,
                Name               = "product test name",
                ProductCode        = "temporal-sku",
                Prop65Message      = new ProductProp65Message
                {
                    MessageBody = "This product has been created through a test automation tool"
                },
                SearchKeywords = "test,seed",
                Shipping       = new ProductShippingAttributes
                {
                    FreightClass      = 179,
                    IsFreeShip        = false,
                    IsFreightOnly     = false,
                    IsQuickShip       = false,
                    WeightActual      = 6.72m,
                    WeightDimensional = 20.62m,
                    Height            = 9.61m,
                    Width             = 16.48m,
                    Length            = 9.60m
                },
                Specs = new List <ProductSpecification>
                {
                    new ProductSpecification
                    {
                        Name  = "name of spec",
                        Value = "value of spec"
                    }
                },
                OemRelationships = new List <ProductOem>
                {
                    new ProductOem
                    {
                        OemName = "oem name 01",
                        Type    = 1,
                        OemSku  = "FakeOemSku"
                    }
                },
                ProductLeadType        = 1,
                BrandSku               = "fake",
                PrimaryBrandIdentifier = testData.BrandExtId
            };
            await Client.Products.Create(productRequest);

            OfferingRequest request = new OfferingRequest
            {
                Identifier   = externalIdentifier,
                CatalogId    = testData.CatalogExtId,
                ProductId    = testData.ProductExtId,
                HomeCategory = testData.CategoryExtId,
                CategoryIds  = new List <string>(),
                Description  = "Description for this offering p:",
                FullName     = offeringFullName,
                HtmlPage     = new HtmlPage
                {
                    H1    = $"H1 {offeringFullName}",
                    Title = $"Title {offeringFullName}",
                    Meta  = $"Meta {offeringFullName}",
                    Url   = $"{offeringFullName.Replace(" ", "-")}"
                },
                IsPublishAble = true,
                IsPreviewAble = true,
                Links         = new List <OfferingLink>(),
                CreatedBy     = "post offering request"
            };

            HttpResponseExtended <OfferingResponse> response = await Client.Offerings.Create(request);

            Assert.IsNotNull(response, $"{nameof(response)} cannot be null");
            Assert.AreEqual(200, response.StatusCode);
            Assert.IsTrue(response.Success, $"Response status is not successful");
            Assert.IsNotNull(response.Result, $"{nameof(response.Result)} is null");

            //test scenario clean up
            await TestScenarioCleanUp(testData);
        }
Ejemplo n.º 11
0
 public Offering Request(OfferingRequest request, IVendorCredentials credentials)
 {
     return(RequestAsync(request, credentials).Result);
 }
Ejemplo n.º 12
0
 public Offering Request(OfferingRequest request)
 {
     return(RequestAsync(request).Result);
 }
        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);
        }