예제 #1
0
        public async Task ViewModel_is_created_using_custom_factory()
        {
            // Arrange
            var client = new SelfContainedWebApplicationFactoryWithWebHost <When_registering_view_model_factory>
                         (
                configureServices: services =>
            {
                services.AddViewModelComposition(options =>
                {
                    options.AssemblyScanner.Disable();
                    options.RegisterCompositionHandler <TestGetHandler>();
                    options.RegisterGlobalViewModelFactory <TestViewModelFactory>();
                });
                services.AddRouting();
            },
                configure: app =>
            {
                app.UseRouting();
                app.UseEndpoints(builder => builder.MapCompositionHandlers());
            }
                         ).CreateClient();

            client.DefaultRequestHeaders.Add("Accept-Casing", "casing/pascal");
            // Act
            var response = await client.GetAsync("/sample/1");

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

            var responseObj = JObject.Parse(responseString);

            // Assert
            Assert.True(response.IsSuccessStatusCode);
            Assert.Equal("some value", responseObj?.SelectToken(nameof(CustomViewModel.AValue))?.Value <string>());
        }
예제 #2
0
        public async Task Default_status_code_should_be_overwritten()
        {
            // Arrange
            var expectedStatusCode = HttpStatusCode.Forbidden;
            var client             = new SelfContainedWebApplicationFactoryWithWebHost <When_setting_custom_http_status_code>
                                     (
                configureServices: services =>
            {
                services.AddViewModelComposition(options =>
                {
                    options.AssemblyScanner.Disable();
                    options.RegisterCompositionHandler <CustomStatusCodeHandler>();
                });
                services.AddControllers();
                services.AddRouting();
            },
                configure: app =>
            {
                app.UseRouting();
                app.UseEndpoints(builder =>
                {
                    builder.MapCompositionHandlers();
                    builder.MapControllers();
                });
            }
                                     ).CreateClient();

            // Act
            var composedResponse = await client.GetAsync("/sample/1");

            // Assert
            Assert.Equal(expectedStatusCode, composedResponse.StatusCode);
        }
        public async Task Default_status_code_should_be_overwritten()
        {
            // Arrange
            var expectedStatusCode = HttpStatusCode.Forbidden;
            var client             = new SelfContainedWebApplicationFactoryWithWebHost <When_setting_custom_http_status_code>
                                     (
                configureServices: services =>
            {
                services.AddViewModelComposition(options =>
                {
                    options.AssemblyScanner.Disable();
                    options.RegisterRequestsHandler <CustomStatusCodeHandler>();
                });
                services.AddRouting();
            },
                configure: app =>
            {
                app.RunCompositionGatewayWithDefaultRoutes();
            }
                                     ).CreateClient();

            // Act
            var response = await client.GetAsync("/custom-status-code/1");

            // Assert
            Assert.Equal(expectedStatusCode, response.StatusCode);
        }
예제 #4
0
        public void Should_not_register_duplicated_handlers()
        {
            IServiceProvider container = null;
            // Arrange
            var factory = new SelfContainedWebApplicationFactoryWithWebHost <When_assembly_scanning>
                          (
                configureServices: services =>
            {
                services.AddViewModelComposition();
                services.AddRouting();
            },
                configure: app =>
            {
                container = app.ApplicationServices;
                app.RunCompositionGatewayWithDefaultRoutes();
            }
                          );

            factory.CreateClient();

            var handler = container.GetServices <IInterceptRoutes>()
                          .SingleOrDefault(svc => svc is SampleNeverInvokedHandler);

            Assert.NotNull(handler);
        }
        public async Task Should_invoke_subscribers()
        {
            // Arrange
            var client = new SelfContainedWebApplicationFactoryWithWebHost <When_using_events>
                         (
                configureServices: services =>
            {
                services.AddViewModelComposition(options =>
                {
                    options.AssemblyScanner.Disable();
                    options.RegisterRequestsHandler <AHandler>();
                    options.RegisterCompositionEventsSubscriber <ASubscriber>();
                });
                services.AddRouting();
            },
                configure: app =>
            {
                app.RunCompositionGatewayWithDefaultRoutes();
            }
                         ).CreateClient();

            // Act
            var response = await client.GetAsync("/matching-handlers/32");

            // Assert
            response.EnsureSuccessStatusCode();

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

            dynamic body = JObject.Parse(contentString);

            Assert.Equal(32, (int)body.handlerValue);
            Assert.Equal(32, (int)body.subscriberValue);
        }
        public async Task Should_return_success_code()
        {
            // Arrange
            var client = new SelfContainedWebApplicationFactoryWithWebHost <When_a_matching_handler_is_found>
                         (
                configureServices: services =>
            {
                services.AddViewModelComposition(options =>
                {
                    options.AssemblyScanner.Disable();
                    options.RegisterRequestsHandler <CatchAllMatchingHandler>();
                });
                services.AddRouting();
            },
                configure: app =>
            {
                app.RunCompositionGatewayWithDefaultRoutes();
            }
                         ).CreateClient();

            // Act
            var response = await client.GetAsync("/matching-handlers/1");

            // Assert
            response.EnsureSuccessStatusCode();
        }
예제 #7
0
        public async Task Throws_if_output_formatters_are_not_enabled()
        {
            await Assert.ThrowsAsync <NotSupportedException>(async() =>
            {
                // Arrange
                var client = new SelfContainedWebApplicationFactoryWithWebHost <Dummy>
                             (
                    configureServices: services =>
                {
                    services.AddViewModelComposition(options =>
                    {
                        options.AssemblyScanner.Disable();
                        options.RegisterCompositionHandler <TestGetStringHandler>();
                        options.RegisterCompositionHandler <TestGetIntegerHandler>();
                        options.ResponseSerialization.UseOutputFormatters = false;
                    });
                    services.AddRouting();
                    services.AddControllers()
                    .AddNewtonsoftJson();
                },
                    configure: app =>
                {
                    app.UseRouting();
                    app.UseEndpoints(builder => builder.MapCompositionHandlers());
                }
                             ).CreateClient();

                // Act
                var response = await client.GetAsync("/sample/1");
            });
        }
예제 #8
0
        public async Task ViewModel_is_intercepted_as_expected()
        {
            // Arrange
            var previewHandler = new TestPreviewHandler();
            var client         = new SelfContainedWebApplicationFactoryWithWebHost <Get_with_2_handlers>
                                 (
                configureServices: services =>
            {
                services.AddSingleton <IViewModelPreviewHandler>(previewHandler);
                services.AddViewModelComposition(options =>
                {
                    options.AssemblyScanner.Disable();
                    options.RegisterCompositionHandler <TestGetHandler>();
                });
                services.AddRouting();
            },
                configure: app =>
            {
                app.UseRouting();
                app.UseEndpoints(builder => builder.MapCompositionHandlers());
            }
                                 ).CreateClient();

            // Act
            var response = await client.GetAsync("/sample/1");

            // Assert
            Assert.True(response.IsSuccessStatusCode);
            Assert.True(previewHandler.Invoked);
        }
예제 #9
0
        public async Task Should_return_404()
        {
            // Arrange
            var client = new SelfContainedWebApplicationFactoryWithWebHost <When_no_handlers_are_defined>
                         (
                configureServices: services =>
            {
                services.AddViewModelComposition(options =>
                {
                    options.AssemblyScanner.Disable();
                });
                services.AddRouting();
            },
                configure: app =>
            {
                app.RunCompositionGatewayWithDefaultRoutes();
            }
                         ).CreateClient();

            // Act
            var response = await client.GetAsync("/no-handlers-are-registered/1");

            // Assert
            Assert.Equal(HttpStatusCode.NotFound, response.StatusCode);
        }
        public async Task Return_404()
        {
            // Arrange
            var client = new SelfContainedWebApplicationFactoryWithWebHost <Get_with_no_matching_handlers>
                         (
                configureServices: services =>
            {
                services.AddViewModelComposition(options =>
                {
                    options.AssemblyScanner.Disable();
                    options.RegisterCompositionHandler <EmptyResponseHandler>();
                });
                services.AddRouting();
            },
                configure: app =>
            {
                app.UseRouting();
                app.UseEndpoints(builder => builder.MapCompositionHandlers());
            }
                         ).CreateClient();

            // Act
            var response = await client.GetAsync("/not-valid/1");

            // Assert
            Assert.Equal(HttpStatusCode.NotFound, response.StatusCode);
        }
        public async Task Is_found()
        {
            // Arrange
            var client = new SelfContainedWebApplicationFactoryWithWebHost <Get_with_matching_handler>
                         (
                configureServices: services =>
            {
                services.AddViewModelComposition(options =>
                {
                    options.AssemblyScanner.Disable();
                    options.RegisterCompositionHandler <EmptyResponseHandler>();
                });
                services.AddRouting();
            },
                configure: app =>
            {
                app.UseRouting();
                app.UseEndpoints(builder => builder.MapCompositionHandlers());
            }
                         ).CreateClient();

            // Act
            var response = await client.GetAsync("/empty-response/1");

            // Assert
            Assert.True(response.IsSuccessStatusCode);
        }
예제 #12
0
        public async Task Request_header_should_be_not_null_if_not_explicitly_set()
        {
            // Arrange
            var client = new SelfContainedWebApplicationFactoryWithWebHost <When_a_matching_handler_is_found>
                         (
                configureServices: services =>
            {
                services.AddViewModelComposition(options =>
                {
                    options.AssemblyScanner.Disable();
                    options.RegisterRequestsHandler <CatchAllMatchingHandler>();
                });
                services.AddRouting();
            },
                configure: app =>
            {
                app.RunCompositionGatewayWithDefaultRoutes();
            }
                         ).CreateClient();

            // Act
            var response = await client.GetAsync("/matching-handlers/1");

            // Assert
            response.EnsureSuccessStatusCode();

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

            dynamic body = JObject.Parse(contentString);

            Assert.NotNull(body.requestId);
        }
        public async Task Should_throw_if_camel_case_request_and_no_valid_contract_resolver()
        {
            await Assert.ThrowsAsync <ArgumentException>(async() =>
            {
                // Arrange
                var client = new SelfContainedWebApplicationFactoryWithWebHost <Get_with_matching_handler>
                             (
                    configureServices: services =>
                {
                    services.AddViewModelComposition(options =>
                    {
                        options.AssemblyScanner.Disable();
                        options.RegisterCompositionHandler <ResponseHandler>();
                        options.ResponseSerialization.DefaultResponseCasing = ResponseCasing.CamelCase;
                        options.ResponseSerialization.UseCustomJsonSerializerSettings(request =>
                        {
                            return(new JsonSerializerSettings());
                        });
                    });
                    services.AddRouting();
                },
                    configure: app =>
                {
                    app.UseRouting();
                    app.UseEndpoints(builder => builder.MapCompositionHandlers());
                }
                             ).CreateClient();

                // Act
                await client.GetAsync("/empty-response/1");
            });
        }
예제 #14
0
        public void Make_sure_filter_is_added_to_mvc()
        {
            MvcOptions mvcOptions = null;

            // Arrange
            var factory = new SelfContainedWebApplicationFactoryWithWebHost <When_configuring_Mvc_support>
                          (
                configureServices: services =>
            {
                services.AddMvc(options => mvcOptions = options);
                services.AddViewModelComposition(options =>
                {
                    options.AddMvcSupport();
                });
            },
                configure: app =>
            {
                app.UseMvc();
            }
                          );

            // Act
            factory.CreateClient();

            // Assert
            var registeredFilter = mvcOptions
                                   .Filters
                                   .SingleOrDefault(f =>
            {
                return(f is TypeFilterAttribute tfa &&
                       tfa.ImplementationType == typeof(CompositionActionFilter));
            });

            Assert.NotNull(registeredFilter);
        }
        public async Task Request_header_should_be_not_null_if_not_explicitly_set()
        {
            // Arrange
            var client = new SelfContainedWebApplicationFactoryWithWebHost <Get_with_matching_handler>
                         (
                configureServices: services =>
            {
                services.AddViewModelComposition(options =>
                {
                    options.AssemblyScanner.Disable();
                    options.RegisterCompositionHandler <EmptyResponseHandler>();
                });
                services.AddRouting();
            },
                configure: app =>
            {
                app.UseRouting();
                app.UseEndpoints(builder => builder.MapCompositionHandlers());
            }
                         ).CreateClient();

            // Act
            var response = await client.GetAsync("/empty-response/1");

            // Assert
            Assert.True(response.IsSuccessStatusCode);

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

            dynamic body = JObject.Parse(contentString);

            Assert.NotNull(body.requestId);
        }
예제 #16
0
 public void An_exception_is_thrown_if_more_than_one_global_factory_is_registered()
 {
     Assert.Throws <NotSupportedException>(() =>
     {
         // Arrange
         var client = new SelfContainedWebApplicationFactoryWithWebHost <When_registering_view_model_factory>
                      (
             configureServices: services =>
         {
             services.AddViewModelComposition(options =>
             {
                 options.AssemblyScanner.Disable();
                 options.RegisterCompositionHandler <TestGetHandler>();
                 options.RegisterGlobalViewModelFactory <TestViewModelFactory>();
                 options.RegisterGlobalViewModelFactory <TestViewModelFactory>();
             });
             services.AddRouting();
         },
             configure: app =>
         {
             app.UseRouting();
             app.UseEndpoints(builder => builder.MapCompositionHandlers());
         }
                      ).CreateClient();
     });
 }
예제 #17
0
        public async Task Returns_expected_response(TestVariant variant)
        {
            // Arrange
            var expectedString = "this is a string value";
            var expectedNumber = 32;

            var client = new SelfContainedWebApplicationFactoryWithWebHost <Dummy>
                         (
                configureServices: services =>
            {
                services.AddViewModelComposition(options =>
                {
                    options.AssemblyScanner.Disable();
                    options.EnableWriteSupport();

                    variant.CompositionOptions?.Invoke(options);
                });
                services.AddRouting();

                variant.ConfigureServices?.Invoke(services);
            },
                configure: app =>
            {
                app.UseRouting();
                app.UseEndpoints(builder => builder.MapCompositionHandlers());

                variant.Configure?.Invoke(app);
            }
                         ).CreateClient();

            variant.ConfigureHttpClient?.Invoke(client);

            dynamic model = new ExpandoObject();

            model.AString = expectedString;
            model.ANumber = expectedNumber;

            var json          = (string)JsonConvert.SerializeObject(model);
            var stringContent = new StringContent(json, Encoding.UTF8, MediaTypeNames.Application.Json);

            stringContent.Headers.ContentLength = json.Length;

            // Act
            var response = await client.PostAsync("/sample/1", stringContent);

            // Assert
            Assert.True(response.IsSuccessStatusCode);

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

            var responseObj = JObject.Parse(responseString);

            Assert.Equal(expectedString, responseObj?.SelectToken("AString")?.Value <string>());
            Assert.Equal(expectedNumber, responseObj?.SelectToken("ANumber")?.Value <int>());
            Assert.Equal($"ANumber: {expectedNumber}.", responseObj?.SelectToken("AValue")?.Value <string>());
        }
예제 #18
0
        public async Task Returns_expected_response()
        {
            var expectedString = "this is a string value";
            var expectedNumber = 32;

            // Arrange
            var client = new SelfContainedWebApplicationFactoryWithWebHost <Get_with_2_handlers>
                         (
                configureServices: services =>
            {
                services.AddViewModelComposition(options =>
                {
                    options.AssemblyScanner.Disable();
                    options.RegisterCompositionHandler <TestStringHandler>();
                    options.RegisterCompositionHandler <TestIntegerHandler>();
                    options.EnableCompositionOverControllers();
                    options.EnableWriteSupport();
                });
                services.AddRouting();
                services.AddControllers()
                .AddNewtonsoftJson();
            },
                configure: app =>
            {
                app.UseRouting();
                app.UseEndpoints(builder =>
                {
                    builder.MapControllers();
                    builder.MapCompositionHandlers();
                });
            }
                         ).CreateClient();

            dynamic model = new ExpandoObject();

            model.AString = expectedString;
            model.ANumber = expectedNumber;

            var json          = (string)JsonConvert.SerializeObject(model);
            var stringContent = new StringContent(json, Encoding.UTF8, MediaTypeNames.Application.Json);

            stringContent.Headers.ContentLength = json.Length;

            // Act
            var response = await client.PostAsync("/api/CompositionOverControllerPost/1", stringContent);

            // Assert
            Assert.True(response.IsSuccessStatusCode);

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

            var responseObj = JObject.Parse(responseString);

            Assert.Equal(expectedString, responseObj?.SelectToken("AString")?.Value <string>());
            Assert.Equal(expectedNumber, responseObj?.SelectToken("ANumber")?.Value <int>());
        }
        public async Task Should_not_throw_if_camel_case_request_and_valid_contract_resolver()
        {
            var invokedUseCustomJsonSerializerSettings = false;
            var expectedComposedRequestId = Guid.NewGuid().ToString();

            // Arrange
            var client = new SelfContainedWebApplicationFactoryWithWebHost <Get_with_matching_handler>
                         (
                configureServices: services =>
            {
                services.AddViewModelComposition(options =>
                {
                    options.AssemblyScanner.Disable();
                    options.RegisterCompositionHandler <ResponseHandler>();
                    options.ResponseSerialization.DefaultResponseCasing = ResponseCasing.CamelCase;
                    options.ResponseSerialization.UseCustomJsonSerializerSettings(request =>
                    {
                        invokedUseCustomJsonSerializerSettings = true;
                        return(new JsonSerializerSettings()
                        {
                            ContractResolver = new CamelCasePropertyNamesContractResolver()
                        });
                    });
                });
                services.AddRouting();
            },
                configure: app =>
            {
                app.UseRouting();
                app.UseEndpoints(builder => builder.MapCompositionHandlers());
            }
                         ).CreateClient();

            client.DefaultRequestHeaders.Add("composed-request-id", expectedComposedRequestId);

            // Act
            var response = await client.GetAsync("/empty-response/1");

            // Assert
            Assert.True(invokedUseCustomJsonSerializerSettings);
            Assert.True(response.IsSuccessStatusCode);

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

            dynamic body = JObject.Parse(contentString);

            Assert.Equal(expectedComposedRequestId, (string)body.requestId);
        }
        public async Task Both_composition_endpoint_and_Mvc_endpoint_return_expected_values()
        {
            // Arrange
            var client = new SelfContainedWebApplicationFactoryWithWebHost <Dummy>
                         (
                configureServices: services =>
            {
                services.AddViewModelComposition(options =>
                {
                    options.AssemblyScanner.Disable();
                    options.RegisterCompositionHandler <TestGetStringHandler>();
                    options.RegisterCompositionHandler <TestGetIntegerHandler>();
                });
                services.AddControllers();
                services.AddRouting();
            },
                configure: app =>
            {
                app.UseRouting();
                app.UseEndpoints(builder =>
                {
                    builder.MapCompositionHandlers();
                    builder.MapControllers();
                });
            }
                         ).CreateClient();

            client.DefaultRequestHeaders.Add("Accept-Casing", "casing/pascal");

            // Act
            var composedResponse = await client.GetAsync("/sample/1");

            var apiResponse = await client.GetAsync("/api/sample/32");

            // Assert
            Assert.True(composedResponse.IsSuccessStatusCode);
            Assert.True(apiResponse.IsSuccessStatusCode);

            var responseObj = JObject.Parse(await composedResponse.Content.ReadAsStringAsync());

            Assert.Equal("sample", responseObj?.SelectToken("AString")?.Value <string>());
            Assert.Equal(1, responseObj?.SelectToken("ANumber")?.Value <int>());

            var apiResponsObj = await apiResponse.Content.ReadAsStringAsync();

            Assert.Equal(32, int.Parse(apiResponsObj));
        }
        public void ViewModel_preview_handlers_are_registered_automatically()
        {
            IEnumerable <IViewModelPreviewHandler> expectedPreviewHandlers = null;

            // Arrange
            var client = new SelfContainedWebApplicationFactoryWithWebHost <When_using_assembly_scanner>
                         (
                configureServices: services =>
            {
                services.AddViewModelComposition(options =>
                {
                    options.TypesFilter = type =>
                    {
                        if (type.Assembly.FullName.Contains("TestClassLibraryWithHandlers"))
                        {
                            return(true);
                        }

                        if (type == typeof(CustomizationsThatAccessTheConfiguration))
                        {
                            return(false);
                        }

                        if (type.IsNestedTypeOf <When_using_assembly_scanner>())
                        {
                            return(true);
                        }

                        return(false);
                    };
                });
                services.AddRouting();
            },
                configure: app =>
            {
                app.UseRouting();
                app.UseEndpoints(builder => builder.MapCompositionHandlers());

                expectedPreviewHandlers = app.ApplicationServices.GetServices <IViewModelPreviewHandler>();
            }
                         ).CreateClient();

            // Assert
            Assert.NotNull(expectedPreviewHandlers);
            Assert.True(expectedPreviewHandlers.Single().GetType() == typeof(TestPreviewHandler));
        }
        public void Options_customization_can_access_configuration_if_set()
        {
            // Arrange
            var config  = new FakeConfig();
            var factory = new SelfContainedWebApplicationFactoryWithWebHost <When_using_assembly_scanner>
                          (
                configureServices: services =>
            {
                services.AddViewModelComposition(options =>
                {
                    options.TypesFilter = type =>
                    {
                        if (type.Assembly.FullName.Contains("TestClassLibraryWithHandlers"))
                        {
                            return(true);
                        }

                        if (type == typeof(EmptyCustomizations))
                        {
                            return(false);
                        }

                        if (type.IsNestedTypeOf <When_using_assembly_scanner>())
                        {
                            return(true);
                        }

                        return(false);
                    };
                }, config);
                services.AddRouting();
            },
                configure: app =>
            {
                app.UseRouting();
                app.UseEndpoints(builder => builder.MapCompositionHandlers());
            }
                          );

            // Act
            var client = factory.CreateClient();

            // Assert
            Assert.Same(config, _customizationsThatAccessTheConfigurationConfig);
        }
        public async Task Options_customization_are_invoked()
        {
            // Arrange
            var client = new SelfContainedWebApplicationFactoryWithWebHost <When_using_assembly_scanner>
                         (
                configureServices: services =>
            {
                services.AddViewModelComposition(options =>
                {
                    options.TypesFilter = type =>
                    {
                        if (type.Assembly.FullName.Contains("TestClassLibraryWithHandlers"))
                        {
                            return(true);
                        }

                        if (type == typeof(CustomizationsThatAccessTheConfiguration))
                        {
                            return(false);
                        }

                        if (type.IsNestedTypeOf <When_using_assembly_scanner>())
                        {
                            return(true);
                        }

                        return(false);
                    };
                });
                services.AddRouting();
            },
                configure: app =>
            {
                app.UseRouting();
                app.UseEndpoints(builder => builder.MapCompositionHandlers());
            }
                         ).CreateClient();

            // Act
            var response = await client.GetAsync("/empty-response/1");

            // Assert
            Assert.True(response.IsSuccessStatusCode);
            Assert.True(_invokedCustomizations);
        }
예제 #24
0
        public void Should_not_fail_due_to_invalid_assemblies()
        {
            // Arrange
            var factory = new SelfContainedWebApplicationFactoryWithWebHost <When_assembly_scanning>
                          (
                configureServices: services =>
            {
                services.AddViewModelComposition();
                services.AddRouting();
            },
                configure: app =>
            {
                app.RunCompositionGatewayWithDefaultRoutes();
            }
                          );

            factory.CreateClient();
        }
예제 #25
0
        public async Task Fails_if_composition_over_controllers_is_disabled()
        {
            // Arrange
            var client = new SelfContainedWebApplicationFactoryWithWebHost <Get_with_2_handlers>
                         (
                configureServices: services =>
            {
                services.AddViewModelComposition(options =>
                {
                    options.AssemblyScanner.Disable();
                    options.RegisterCompositionHandler <TestGetStrinHandler>();
                    options.RegisterCompositionHandler <CaseInsensitiveRoute_TestGetIntegerHandler>();
                });
                services.AddRouting();
                services.AddControllers()
                .AddNewtonsoftJson();
            },
                configure: app =>
            {
                app.UseRouting();
                app.UseEndpoints(builder =>
                {
                    builder.MapControllers();
                    builder.MapCompositionHandlers();
                });
            }
                         ).CreateClient();

            Exception capturedException = null;

            try
            {
                // Act
                var response = await client.GetAsync("/api/CompositionOverController/1");
            }
            catch (Exception e)
            {
                capturedException = e;
            }

            // Assert
            Assert.NotNull(capturedException);
            Assert.Equal("Microsoft.AspNetCore.Routing.Matching.AmbiguousMatchException", capturedException.GetType().FullName);
        }
        public async Task Uses_defined_factory_and_output_formatters()
        {
            // Arrange
            var client = new SelfContainedWebApplicationFactoryWithWebHost <Dummy>
                         (
                configureServices: services =>
            {
                services.AddViewModelComposition(options =>
                {
                    options.AssemblyScanner.Disable();
                    options.RegisterCompositionHandler <TestGetStringHandler>();
                    options.RegisterCompositionHandler <TestGetIntegerHandler>();
                    options.RegisterEndpointScopedViewModelFactory <TestFactory>();
                    options.ResponseSerialization.UseOutputFormatters = true;
                });
                services.AddRouting();
                services.AddControllers().AddNewtonsoftJson(options =>
                {
                    options.SerializerSettings.ContractResolver = new DefaultContractResolver()
                    {
                        NamingStrategy = new DefaultNamingStrategy()
                    };
                });
            },
                configure: app =>
            {
                app.UseRouting();
                app.UseEndpoints(builder => builder.MapCompositionHandlers());
            }
                         ).CreateClient();

            // Act
            var response = await client.GetAsync("/sample/1");

            // Assert
            Assert.True(response.IsSuccessStatusCode);

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

            var responseObj = JObject.Parse(responseString);

            Assert.Equal("sample", responseObj?.SelectToken("AString")?.Value <string>());
            Assert.Equal(1, responseObj?.SelectToken("ANumber")?.Value <int>());
        }
예제 #27
0
        public async Task Returns_expected_bad_request_using_output_formatters()
        {
            // Arrange
            var client = new SelfContainedWebApplicationFactoryWithWebHost <Dummy>
                         (
                configureServices: services =>
            {
                services.AddViewModelComposition(options =>
                {
                    options.AssemblyScanner.Disable();
                    options.RegisterCompositionHandler <TestGetStringHandler>();
                    options.RegisterCompositionHandler <TestGetIntegerHandler>();
                    options.ResponseSerialization.UseOutputFormatters = true;
                });
                services.AddRouting();
                services.AddControllers()
                .AddNewtonsoftJson();
            },
                configure: app =>
            {
                app.UseRouting();
                app.UseEndpoints(builder => builder.MapCompositionHandlers());
            }
                         ).CreateClient();

            // Act
            var response = await client.GetAsync("/sample/1");

            // Assert
            Assert.False(response.IsSuccessStatusCode);
            Assert.Equal(HttpStatusCode.BadRequest, response.StatusCode);

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

            dynamic responseObj = JObject.Parse(responseString);

            dynamic errors   = responseObj.errors;
            var     idErrors = (JArray)errors["Id"];

            var error = idErrors[0].Value <string>();

            Assert.Equal(expectedError, error);
        }
예제 #28
0
        public async Task Returns_expected_response()
        {
            // Arrange
            var client = new SelfContainedWebApplicationFactoryWithWebHost <Get_with_2_handlers>
                         (
                configureServices: services =>
            {
                services.AddViewModelComposition(options =>
                {
                    options.AssemblyScanner.Disable();
                    options.RegisterCompositionHandler <TestGetStrinHandler>();
                    options.RegisterCompositionHandler <CaseSensitiveRoute_TestGetIntegerHandler>();
                    options.EnableCompositionOverControllers();
                });
                services.AddRouting();
                services.AddControllers()
                .AddNewtonsoftJson();
            },
                configure: app =>
            {
                app.UseRouting();
                app.UseEndpoints(builder =>
                {
                    builder.MapControllers();
                    builder.MapCompositionHandlers();
                });
            }
                         ).CreateClient();

            // Act
            var response = await client.GetAsync("/api/compositionovercontroller/1");

            // Assert
            Assert.True(response.IsSuccessStatusCode);

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

            var responseObj = JObject.Parse(responseString);

            Assert.Equal("sample", responseObj?.SelectToken("AString")?.Value <string>());
            Assert.Equal(1, responseObj?.SelectToken("ANumber")?.Value <int>());
        }
예제 #29
0
        public async Task If_attributes_are_of_the_same_type_and_same_template_handler_should_be_invoked_multiple_times()
        {
            // Arrange
            var client =
                new SelfContainedWebApplicationFactoryWithWebHost <Dummy>
                (
                    configureServices: services =>
            {
                services.AddViewModelComposition(options =>
                {
                    options.AssemblyScanner.Disable();
                    options.RegisterGlobalViewModelFactory <InvocationCountViewModelFactory>();
                    options.RegisterCompositionHandler <MultipleGetAttributesSameTemplateHandler>();
                });
                services.AddControllers();
                services.AddRouting();
            },
                    configure: app =>
            {
                app.UseRouting();
                app.UseEndpoints(builder =>
                {
                    builder.MapCompositionHandlers();
                    builder.MapControllers();
                });
            }
                ).CreateClient();

            // Act
            var composedResponse = await client.GetAsync("/multiple/attributes");

            // Assert
            Assert.True(composedResponse.IsSuccessStatusCode);

            var responseString = await composedResponse.Content.ReadAsStringAsync();

            var responseObj     = JObject.Parse(responseString);
            var invocationCount = responseObj?.GetValue("invocationCount")?.Value <int>();

            Assert.Equal(2, invocationCount);
        }
예제 #30
0
        public async Task Matching_handlers_are_found()
        {
            // Arrange
            var client = new SelfContainedWebApplicationFactoryWithWebHost <When_using_assembly_scanner>
                         (
                configureServices: services =>
            {
                services.AddViewModelComposition(options =>
                {
                    options.TypesFilter = type =>
                    {
                        if (type.Assembly.FullName.Contains("TestClassLibraryWithHandlers"))
                        {
                            return(true);
                        }

                        if (type.IsNested && typeof(When_using_assembly_scanner).GetNestedTypes(BindingFlags.NonPublic | BindingFlags.Public)
                            .Contains(type))
                        {
                            return(true);
                        }

                        return(false);
                    };
                });
                services.AddRouting();
            },
                configure: app =>
            {
                app.UseRouting();
                app.UseEndpoints(builder => builder.MapCompositionHandlers());
            }
                         ).CreateClient();

            // Act
            var response = await client.GetAsync("/empty-response/1");

            // Assert
            Assert.True(response.IsSuccessStatusCode);
        }