public void BuildActionModels_BaseAuthorizeFiltersAreStillValidWhenOverriden()
        {
            // Arrange
            var options = new TestOptionsManager<AuthorizationOptions>();
            options.Value.AddPolicy("Base", policy => policy.RequireClaim("Basic").RequireClaim("Basic2"));
            options.Value.AddPolicy("Derived", policy => policy.RequireClaim("Derived"));

            var provider = new AuthorizationApplicationModelProvider(options);
            var defaultProvider = new DefaultApplicationModelProvider(new TestOptionsManager<MvcOptions>());

            var context = new ApplicationModelProviderContext(new[] { typeof(DerivedController).GetTypeInfo() });
            defaultProvider.OnProvidersExecuting(context);

            // Act
            provider.OnProvidersExecuting(context);

            // Assert
            var controller = Assert.Single(context.Result.Controllers);
            var action = Assert.Single(controller.Actions);
            Assert.Equal("Authorize", action.ActionName);
            Assert.Null(action.AttributeRouteModel);
            var authorizeFilters = action.Filters.OfType<AuthorizeFilter>();
            Assert.Single(authorizeFilters);
            Assert.Equal(3, authorizeFilters.First().Policy.Requirements.Count);
        }
        public void GoogleTanslateTest_Func()
        {
            // Arrange
            var logger = new Mock<ILogger<JsonStringLocalizer>>().Object;
            var option = new TestOptionsManager<Anderman.JsonLocalization.DependencyInjection.LocalizationOptions>();
            var googleService = new GoogleTranslater(logger, option);

            // Act


            // Assert
            Assert.Equal("Welcome", googleService.TryTranslateWord("Welkom", new CultureInfo("nl-NL"), new CultureInfo("en-US")), ignoreCase: true);
            Assert.Equal("{{test}} ", GoogleTranslater.FixStringFormatPlaceholders("{ { test } } { }"), ignoreCase: true);
        }
        private static IServiceProvider CreateServices()
        {
            var options = new TestOptionsManager<MvcOptions>();
            options.Value.OutputFormatters.Add(new StringOutputFormatter());
            options.Value.OutputFormatters.Add(new JsonOutputFormatter());

            var services = new ServiceCollection();
            services.AddSingleton(new ObjectResultExecutor(
                options,
                new TestHttpResponseStreamWriterFactory(),
                NullLoggerFactory.Instance));

            return services.BuildServiceProvider();
        }
        public void FindView_ReturnsNotFoundResult_WhenNoViewEnginesAreRegistered()
        {
            // Arrange
            var viewName = "test-view";
            var actionContext = GetActionContext();
            var optionsAccessor = new TestOptionsManager<MvcViewOptions>();
            var compositeViewEngine = new CompositeViewEngine(optionsAccessor);

            // Act
            var result = compositeViewEngine.FindView(actionContext, viewName);

            // Assert
            Assert.False(result.Success);
            Assert.Empty(result.SearchedLocations);
        }
        public void FindView_ReturnsNotFoundResult_WhenNoViewEnginesAreRegistered()
        {
            // Arrange
            var expected = $"'{typeof(MvcViewOptions).FullName}.{nameof(MvcViewOptions.ViewEngines)}' must not be " +
                           $"empty. At least one '{typeof(IViewEngine).FullName}' is required to locate a view for rendering.";
            var viewName            = "my-partial-view";
            var optionsAccessor     = new TestOptionsManager <MvcViewOptions>();
            var compositeViewEngine = new CompositeViewEngine(optionsAccessor);

            // Act & AssertS
            var exception = Assert.Throws <InvalidOperationException>(
                () => compositeViewEngine.FindView(GetActionContext(), viewName, isMainPage: false));

            Assert.Equal(expected, exception.Message);
        }
        public void GetView_ReturnsNotFoundResult_WhenNoViewEnginesAreRegistered(bool isMainPage)
        {
            // Arrange
            var expected = $"'{typeof(MvcViewOptions).FullName}.{nameof(MvcViewOptions.ViewEngines)}' must not be " +
                           $"empty. At least one '{typeof(IViewEngine).FullName}' is required to locate a view for rendering.";
            var viewName            = "test-view.cshtml";
            var optionsAccessor     = new TestOptionsManager <MvcViewOptions>();
            var compositeViewEngine = new CompositeViewEngine(optionsAccessor);

            // Act & Assert
            var exception = Assert.Throws <InvalidOperationException>(
                () => compositeViewEngine.GetView("~/Index.html", viewName, isMainPage));

            Assert.Equal(expected, exception.Message);
        }
        public void FindView_IsMainPage_ReturnsNotFoundResult_WhenNoViewEnginesAreRegistered()
        {
            // Arrange
            var viewName            = "test-view";
            var actionContext       = GetActionContext();
            var optionsAccessor     = new TestOptionsManager <MvcViewOptions>();
            var compositeViewEngine = new CompositeViewEngine(optionsAccessor);

            // Act
            var result = compositeViewEngine.FindView(actionContext, viewName, isMainPage: true);

            // Assert
            Assert.False(result.Success);
            Assert.Empty(result.SearchedLocations);
        }
        public void ViewEngines_UsesListOfViewEnginesFromOptions()
        {
            // Arrange
            var viewEngine1 = Mock.Of<IViewEngine>();
            var viewEngine2 = Mock.Of<IViewEngine>();
            var optionsAccessor = new TestOptionsManager<MvcViewOptions>();
            optionsAccessor.Value.ViewEngines.Add(viewEngine1);
            optionsAccessor.Value.ViewEngines.Add(viewEngine2);
            var compositeViewEngine = new CompositeViewEngine(optionsAccessor);

            // Act
            var result = compositeViewEngine.ViewEngines;

            // Assert
            Assert.Equal(new[] { viewEngine1, viewEngine2 }, result);
        }
示例#9
0
        public static TestModelBinderFactory Create(
            IModelMetadataProvider metadataProvider,
            params IModelBinderProvider[] providers)
        {
            if (metadataProvider == null)
            {
                metadataProvider = TestModelMetadataProvider.CreateDefaultProvider();
            }

            var options = new TestOptionsManager<MvcOptions>();
            foreach (var provider in providers)
            {
                options.Value.ModelBinderProviders.Add(provider);
            }
            return new TestModelBinderFactory(metadataProvider, options);
        }
示例#10
0
        public void OnProvidersExecuting_DoesNothingIfHandlerHasNoResponseCacheAttributes()
        {
            // Arrange
            var options  = new TestOptionsManager <MvcOptions>();
            var provider = new ResponseCacheFilterApplicationModelProvider(options);
            var typeInfo = typeof(PageWithoutResponseCache).GetTypeInfo();
            var context  = GetApplicationProviderContext(typeInfo);

            // Act
            provider.OnProvidersExecuting(context);

            // Assert
            Assert.Collection(
                context.PageApplicationModel.Filters,
                f => Assert.IsType <PageHandlerPageFilter>(f));
        }
示例#11
0
        public static TestModelBinderFactory Create(
            IModelMetadataProvider metadataProvider,
            params IModelBinderProvider[] providers)
        {
            if (metadataProvider == null)
            {
                metadataProvider = TestModelMetadataProvider.CreateDefaultProvider();
            }

            var options = new TestOptionsManager <MvcOptions>();

            foreach (var provider in providers)
            {
                options.Value.ModelBinderProviders.Add(provider);
            }
            return(new TestModelBinderFactory(metadataProvider, options));
        }
示例#12
0
        public void ViewEngines_UsesListOfViewEnginesFromOptions()
        {
            // Arrange
            var viewEngine1     = Mock.Of <IViewEngine>();
            var viewEngine2     = Mock.Of <IViewEngine>();
            var optionsAccessor = new TestOptionsManager <MvcViewOptions>();

            optionsAccessor.Value.ViewEngines.Add(viewEngine1);
            optionsAccessor.Value.ViewEngines.Add(viewEngine2);
            var compositeViewEngine = new CompositeViewEngine(optionsAccessor);

            // Act
            var result = compositeViewEngine.ViewEngines;

            // Assert
            Assert.Equal(new[] { viewEngine1, viewEngine2 }, result);
        }
示例#13
0
        public static TestModelBinderFactory CreateDefault(
            IModelMetadataProvider metadataProvider,
            params IModelBinderProvider[] providers)
        {
            if (metadataProvider == null)
            {
                metadataProvider = TestModelMetadataProvider.CreateDefaultProvider();
            }

            var options = new TestOptionsManager<MvcOptions>();
            foreach (var provider in providers)
            {
                options.Value.ModelBinderProviders.Add(provider);
            }
            new MvcCoreMvcOptionsSetup(new TestHttpRequestStreamReaderFactory()).Configure(options.Value);
            return new TestModelBinderFactory(metadataProvider, options);
        }
        public void OnProvidersExecuting_ThrowsIfControllerWithAttribute_HasActionsWithoutAttributeRouting()
        {
            // Arrange
            var context = GetContext(typeof(ActionsWithoutAttributeRouting));
            var options = new TestOptionsManager <ApiBehaviorOptions>(new ApiBehaviorOptions
            {
                InvalidModelStateResponseFactory = _ => null,
            });

            var provider = new ApiBehaviorApplicationModelProvider(options, NullLoggerFactory.Instance);

            // Act & Assert
            var ex = Assert.Throws <InvalidOperationException>(() => provider.OnProvidersExecuting(context));

            Assert.Equal(
                "Action methods on controllers annotated with ApiControllerAttribute must have an attribute route.",
                ex.Message);
        }
示例#15
0
        private static IServiceProvider CreateServices()
        {
            var options = new TestOptionsManager <MvcOptions>();

            options.Value.OutputFormatters.Add(new StringOutputFormatter());
            options.Value.OutputFormatters.Add(new JsonOutputFormatter(
                                                   new JsonSerializerSettings(),
                                                   ArrayPool <char> .Shared));

            var services = new ServiceCollection();

            services.AddSingleton(new ObjectResultExecutor(
                                      options,
                                      new TestHttpResponseStreamWriterFactory(),
                                      NullLoggerFactory.Instance));

            return(services.BuildServiceProvider());
        }
        public void JsonStringLocalizerTest_FuncWithArguments()
        {
            // Arrange

            var logger = new Mock<ILogger<JsonStringLocalizer>>();
            var option = new TestOptionsManager<Anderman.JsonLocalization.DependencyInjection.LocalizationOptions>();
            var mockTranslate = new Mock<ITranslater>();
            mockTranslate.Setup(m => m.TryTranslateWord("Unknown", new CultureInfo("en-US"), CultureInfo.CurrentUICulture.Parent)).Returns("Onbekend");
            var stringLocalizer = new JsonStringLocalizer("HomeController", MockCache(), logger.Object, option, mockTranslate.Object);
            // Act


            // Assert
            Assert.Equal("_{1|2}{a few words|more words|many words}", stringLocalizer["StringOptions", "_"]);
            Assert.Equal("_1a few words", stringLocalizer["StringOptions", "_", 0]);
            Assert.Equal("_2more words", stringLocalizer["StringOptions", "_", 1]);
            Assert.Equal("_2many words", stringLocalizer["StringOptions", "_", 2]);
        }
示例#17
0
        public void CreateBinder_Throws_WhenNoProviders()
        {
            // Arrange
            var expected = $"'{typeof(MvcOptions).FullName}.{nameof(MvcOptions.ModelBinderProviders)}' must not be " +
                           $"empty. At least one '{typeof(IModelBinderProvider).FullName}' is required to model bind.";
            var metadataProvider = new TestModelMetadataProvider();
            var options          = new TestOptionsManager <MvcOptions>();
            var factory          = new ModelBinderFactory(metadataProvider, options);
            var context          = new ModelBinderFactoryContext()
            {
                Metadata = metadataProvider.GetMetadataForType(typeof(string)),
            };

            // Act & Assert
            var exception = Assert.Throws <InvalidOperationException>(() => factory.CreateBinder(context));

            Assert.Equal(expected, exception.Message);
        }
示例#18
0
        public static TestModelBinderFactory CreateDefault(
            IModelMetadataProvider metadataProvider,
            params IModelBinderProvider[] providers)
        {
            if (metadataProvider == null)
            {
                metadataProvider = TestModelMetadataProvider.CreateDefaultProvider();
            }

            var options = new TestOptionsManager <MvcOptions>();

            foreach (var provider in providers)
            {
                options.Value.ModelBinderProviders.Add(provider);
            }
            new MvcCoreMvcOptionsSetup(new TestHttpRequestStreamReaderFactory()).Configure(options.Value);
            return(new TestModelBinderFactory(metadataProvider, options));
        }
        public void GetChangeToken_WatchesAllCshtmlFilesUnderFileSystemRoot()
        {
            // Arrange
            var fileProvider = new Mock <IFileProvider>();
            var accessor     = Mock.Of <IRazorViewEngineFileProviderAccessor>(a => a.FileProvider == fileProvider.Object);

            var templateEngine = new RazorTemplateEngine(
                RazorEngine.Create(),
                new FileProviderRazorProject(accessor));
            var options        = new TestOptionsManager <RazorPagesOptions>();
            var changeProvider = new PageActionDescriptorChangeProvider(templateEngine, accessor, options);

            // Act
            var changeToken = changeProvider.GetChangeToken();

            // Assert
            fileProvider.Verify(f => f.Watch("/Pages/**/*.cshtml"));
        }
示例#20
0
        public void FindView_ReturnsNotFoundResult_WhenExactlyOneViewEngineIsRegisteredWhichReturnsNotFoundResult()
        {
            // Arrange
            var viewName = "test-view";
            var engine = new Mock<IViewEngine>();
            engine.Setup(e => e.FindView(It.IsAny<ActionContext>(), It.IsAny<string>()))
                   .Returns(ViewEngineResult.NotFound(viewName, new[] { "controller/test-view" }));
            var optionsAccessor = new TestOptionsManager<MvcViewOptions>();
            optionsAccessor.Value.ViewEngines.Add(engine.Object);
            var compositeViewEngine = new CompositeViewEngine(optionsAccessor);

            // Act
            var result = compositeViewEngine.FindView(GetActionContext(), viewName);

            // Assert
            Assert.False(result.Success);
            Assert.Equal(new[] { "controller/test-view" }, result.SearchedLocations);
        }
示例#21
0
        public void OnProvidersExecuting_MakesControllerVisibleInApiExplorer_IfItIsAnnotatedWithAttribute()
        {
            // Arrange
            var context = GetContext(typeof(TestApiController));
            var options = new TestOptionsManager <ApiBehaviorOptions>(new ApiBehaviorOptions
            {
                SuppressModelStateInvalidFilter = true,
            });

            var provider = GetProvider(options);

            // Act
            provider.OnProvidersExecuting(context);

            // Assert
            var controller = Assert.Single(context.Result.Controllers);

            Assert.True(controller.ApiExplorer.IsVisible);
        }
示例#22
0
        public void FindView_ReturnsView_WhenExactlyOneViewEngineIsRegisteredWhichReturnsAFoundResult()
        {
            // Arrange
            var viewName = "test-view";
            var engine = new Mock<IViewEngine>();
            var view = Mock.Of<IView>();
            engine.Setup(e => e.FindView(It.IsAny<ActionContext>(), It.IsAny<string>()))
                   .Returns(ViewEngineResult.Found(viewName, view));
            var optionsAccessor = new TestOptionsManager<MvcViewOptions>();
            optionsAccessor.Value.ViewEngines.Add(engine.Object);
            var compositeViewEngine = new CompositeViewEngine(optionsAccessor);

            // Act
            var result = compositeViewEngine.FindView(GetActionContext(), viewName);

            // Assert
            Assert.True(result.Success);
            Assert.Same(view, result.View);
        }
示例#23
0
        private ControllerActionDescriptorProvider GetActionDescriptorProvider()
        {
            var controllerTypes = typeof(DefaultActionSelectorTests)
                                  .GetNestedTypes(BindingFlags.NonPublic)
                                  .Select(t => t.GetTypeInfo())
                                  .ToList();

            var options = new TestOptionsManager <MvcOptions>();

            var controllerTypeProvider = new StaticControllerTypeProvider(controllerTypes);
            var modelProvider          = new DefaultApplicationModelProvider(options);

            var provider = new ControllerActionDescriptorProvider(
                controllerTypeProvider,
                new[] { modelProvider },
                options);

            return(provider);
        }
示例#24
0
        public void OnProvidersExecuting_AddsMultipleSelectorsForIndexPages()
        {
            // Arrange
            var fileProvider = new TestFileProvider();
            var file1        = fileProvider.AddFile("/Pages/Index.cshtml", "@page");
            var file2        = fileProvider.AddFile("/Pages/Test.cshtml", "Hello world");
            var file3        = fileProvider.AddFile("/Pages/Admin/Index.cshtml", "@page \"test\"");

            var dir2 = fileProvider.AddDirectoryContent("/Pages/Admin", new[] { file3 });
            var dir1 = fileProvider.AddDirectoryContent("/Pages", new IFileInfo[] { dir2, file1, file2 });

            fileProvider.AddDirectoryContent("/", new[] { dir1 });

            var project = new TestRazorProject(fileProvider);

            var optionsManager = new TestOptionsManager <RazorPagesOptions>();

            optionsManager.Value.RootDirectory = "/";
            var provider = new RazorProjectPageRouteModelProvider(project, optionsManager, NullLoggerFactory.Instance);
            var context  = new PageRouteModelProviderContext();

            // Act
            provider.OnProvidersExecuting(context);

            // Assert
            Assert.Collection(context.RouteModels,
                              model =>
            {
                Assert.Equal("/Pages/Admin/Index.cshtml", model.RelativePath);
                Assert.Equal("/Pages/Admin/Index", model.ViewEnginePath);
                Assert.Collection(model.Selectors,
                                  selector => Assert.Equal("Pages/Admin/Index/test", selector.AttributeRouteModel.Template),
                                  selector => Assert.Equal("Pages/Admin/test", selector.AttributeRouteModel.Template));
            },
                              model =>
            {
                Assert.Equal("/Pages/Index.cshtml", model.RelativePath);
                Assert.Equal("/Pages/Index", model.ViewEnginePath);
                Assert.Collection(model.Selectors,
                                  selector => Assert.Equal("Pages/Index", selector.AttributeRouteModel.Template),
                                  selector => Assert.Equal("Pages", selector.AttributeRouteModel.Template));
            });
        }
示例#25
0
        public void OnProvidersExecuting_DoesNotAddModelStateInvalidFilterToController_IfFeatureIsDisabledViaOptions()
        {
            // Arrange
            var context = GetContext(typeof(TestApiController));
            var options = new TestOptionsManager <ApiBehaviorOptions>(new ApiBehaviorOptions
            {
                SuppressModelStateInvalidFilter = true,
            });

            var provider = GetProvider(options);

            // Act
            provider.OnProvidersExecuting(context);

            // Assert
            var controllerModel = Assert.Single(context.Result.Controllers);

            Assert.DoesNotContain(typeof(ModelStateInvalidFilter), controllerModel.Filters.Select(f => f.GetType()));
        }
        public void OnProvidersExecuting_AddsModelStateInvalidFilter_IfTypeIsAnnotatedWithAttribute()
        {
            // Arrange
            var context = GetContext(typeof(TestApiController));
            var options = new TestOptionsManager <ApiBehaviorOptions>(new ApiBehaviorOptions
            {
                InvalidModelStateResponseFactory = _ => null,
            });

            var provider = new ApiBehaviorApplicationModelProvider(options, NullLoggerFactory.Instance);

            // Act
            provider.OnProvidersExecuting(context);

            // Assert
            var actionModel = Assert.Single(Assert.Single(context.Result.Controllers).Actions);

            Assert.IsType <ModelStateInvalidFilter>(actionModel.Filters.Last());
        }
示例#27
0
        public void FindView_ReturnsNotFoundResult_WhenExactlyOneViewEngineIsRegisteredWhichReturnsNotFoundResult()
        {
            // Arrange
            var viewName = "test-view";
            var engine   = new Mock <IViewEngine>();

            engine.Setup(e => e.FindView(It.IsAny <ActionContext>(), It.IsAny <string>()))
            .Returns(ViewEngineResult.NotFound(viewName, new[] { "controller/test-view" }));
            var optionsAccessor = new TestOptionsManager <MvcViewOptions>();

            optionsAccessor.Value.ViewEngines.Add(engine.Object);
            var compositeViewEngine = new CompositeViewEngine(optionsAccessor);

            // Act
            var result = compositeViewEngine.FindView(GetActionContext(), viewName);

            // Assert
            Assert.False(result.Success);
            Assert.Equal(new[] { "controller/test-view" }, result.SearchedLocations);
        }
        public void CreateBinder_Throws_WhenBinderNotCreated()
        {
            // Arrange
            var metadataProvider = new TestModelMetadataProvider();
            var options          = new TestOptionsManager <MvcOptions>();
            var factory          = new ModelBinderFactory(metadataProvider, options);

            var context = new ModelBinderFactoryContext()
            {
                Metadata = metadataProvider.GetMetadataForType(typeof(string)),
            };

            // Act
            var exception = Assert.Throws <InvalidOperationException>(() => factory.CreateBinder(context));

            // Assert
            Assert.Equal(
                $"Could not create a model binder for model object of type '{typeof(string).FullName}'.",
                exception.Message);
        }
        public void JsonStringLocalizerWithCultureTest_Func()
        {
            // Arrange
            var logger = new Mock<ILogger<JsonStringLocalizer>>();
            var option = new TestOptionsManager<Anderman.JsonLocalization.DependencyInjection.LocalizationOptions>();

            var mockTranslate = new Mock<ITranslater>();
            mockTranslate.Setup(m => m.TryTranslateWord("Unknown", new CultureInfo("en-US"), CultureInfo.CurrentUICulture.Parent)).Returns("Onbekend");
            var stringLocalizer = new JsonStringLocalizer("HomeController", MockCache(), logger.Object, option,mockTranslate.Object).WithCulture(CultureInfo.CurrentUICulture);

            // Act


            // Assert
            Assert.Equal("Culture specific", stringLocalizer["specific"]);
            Assert.Equal("Culture neutral", stringLocalizer["neutral"]);
            Assert.Equal("Culture Invariant", stringLocalizer["Invariant"]);
            Assert.True(stringLocalizer["Unknown"].ResourceNotFound);
            Assert.False(stringLocalizer["Unknown"].ResourceNotFound);
        }
示例#30
0
        private static TestRazorViewCompiler GetViewCompiler(
            TestFileProvider fileProvider = null,
            Action <RoslynCompilationContext> compilationCallback = null,
            RazorReferenceManager referenceManager          = null,
            IList <CompiledViewDescriptor> precompiledViews = null)
        {
            fileProvider = fileProvider ?? new TestFileProvider();
            var accessor = Mock.Of <IRazorViewEngineFileProviderAccessor>(a => a.FileProvider == fileProvider);

            compilationCallback = compilationCallback ?? (_ => { });
            var options = new TestOptionsManager <RazorViewEngineOptions>();

            if (referenceManager == null)
            {
                var applicationPartManager = new ApplicationPartManager();
                var assembly = typeof(RazorViewCompilerTest).Assembly;
                applicationPartManager.ApplicationParts.Add(new AssemblyPart(assembly));
                applicationPartManager.FeatureProviders.Add(new MetadataReferenceFeatureProvider());

                referenceManager = new DefaultRazorReferenceManager(applicationPartManager, options);
            }

            precompiledViews = precompiledViews ?? Array.Empty <CompiledViewDescriptor>();

            var projectSystem  = new FileProviderRazorProject(accessor);
            var templateEngine = new RazorTemplateEngine(RazorEngine.Create(), projectSystem)
            {
                Options =
                {
                    ImportsFileName = "_ViewImports.cshtml",
                }
            };
            var viewCompiler = new TestRazorViewCompiler(
                fileProvider,
                templateEngine,
                new CSharpCompiler(referenceManager, Mock.Of <IHostingEnvironment>()),
                compilationCallback,
                precompiledViews);

            return(viewCompiler);
        }
        private HttpContext GetHttpContext()
        {
            var options = new TestOptionsManager <MvcViewOptions>();

            var viewExecutor = new PartialViewResultExecutor(
                options,
                new TestHttpResponseStreamWriterFactory(),
                new CompositeViewEngine(options),
                new TempDataDictionaryFactory(new SessionStateTempDataProvider()),
                new DiagnosticListener("Microsoft.AspNetCore"),
                NullLoggerFactory.Instance);

            var services = new ServiceCollection();

            services.AddSingleton(viewExecutor);

            var httpContext = new DefaultHttpContext();

            httpContext.RequestServices = services.BuildServiceProvider();
            return(httpContext);
        }
示例#32
0
        public void FindView_ReturnsView_WhenExactlyOneViewEngineIsRegisteredWhichReturnsAFoundResult()
        {
            // Arrange
            var viewName = "test-view";
            var engine   = new Mock <IViewEngine>();
            var view     = Mock.Of <IView>();

            engine.Setup(e => e.FindView(It.IsAny <ActionContext>(), It.IsAny <string>()))
            .Returns(ViewEngineResult.Found(viewName, view));
            var optionsAccessor = new TestOptionsManager <MvcViewOptions>();

            optionsAccessor.Value.ViewEngines.Add(engine.Object);
            var compositeViewEngine = new CompositeViewEngine(optionsAccessor);

            // Act
            var result = compositeViewEngine.FindView(GetActionContext(), viewName);

            // Assert
            Assert.True(result.Success);
            Assert.Same(view, result.View);
        }
示例#33
0
        public void OnProvidersExecuting_DoesNotModifyVisibilityInApiExplorer_IfValueIsAlreadySet()
        {
            // Arrange
            var context = GetContext(typeof(TestApiController));

            context.Result.Controllers[0].ApiExplorer.IsVisible = false;
            var options = new TestOptionsManager <ApiBehaviorOptions>(new ApiBehaviorOptions
            {
                SuppressModelStateInvalidFilter = true,
            });

            var provider = GetProvider(options);

            // Act
            provider.OnProvidersExecuting(context);

            // Assert
            var controller = Assert.Single(context.Result.Controllers);

            Assert.False(controller.ApiExplorer.IsVisible);
        }
        public void Load_InvokesApplicationModelConventions()
        {
            // Arrange
            var descriptor = new PageActionDescriptor();

            var compilerProvider = GetCompilerProvider();

            var model    = new PageApplicationModel(descriptor, typeof(object).GetTypeInfo(), new object[0]);
            var provider = new Mock <IPageApplicationModelProvider>();

            provider.Setup(p => p.OnProvidersExecuting(It.IsAny <PageApplicationModelProviderContext>()))
            .Callback((PageApplicationModelProviderContext c) =>
            {
                c.PageApplicationModel = model;
            });
            var providers = new[] { provider.Object };

            var razorPagesOptions = new TestOptionsManager <RazorPagesOptions>();
            var mvcOptions        = new TestOptionsManager <MvcOptions>();
            var convention        = new Mock <IPageApplicationModelConvention>();

            convention.Setup(c => c.Apply(It.IsAny <PageApplicationModel>()))
            .Callback((PageApplicationModel m) =>
            {
                Assert.Same(model, m);
            });
            razorPagesOptions.Value.Conventions.Add(convention.Object);

            var loader = new DefaultPageLoader(
                providers,
                compilerProvider,
                razorPagesOptions,
                mvcOptions);

            // Act
            var result = loader.Load(new PageActionDescriptor());

            // Assert
            convention.Verify();
        }
示例#35
0
        public void OnProvidersExecuting_ThrowsIfRouteTemplateHasOverridePattern()
        {
            // Arrange
            var fileProvider = new TestFileProvider();
            var file         = fileProvider.AddFile("/Index.cshtml", "@page \"/custom-route\"");

            fileProvider.AddDirectoryContent("/", new[] { file });

            var project = new TestRazorProject(fileProvider);

            var optionsManager = new TestOptionsManager <RazorPagesOptions>();

            optionsManager.Value.RootDirectory = "/";
            var provider = new RazorProjectPageRouteModelProvider(project, optionsManager, NullLoggerFactory.Instance);
            var context  = new PageRouteModelProviderContext();

            // Act & Assert
            var ex = Assert.Throws <InvalidOperationException>(() => provider.OnProvidersExecuting(context));

            Assert.Equal("The route for the page at '/Index.cshtml' cannot start with / or ~/. Pages do not support overriding the file path of the page.",
                         ex.Message);
        }
        public void OnProvidersExecuting_CollatesAttributesFromInheritedTypes()
        {
            // Arrange
            var options = new TestOptionsManager <AuthorizationOptions>();

            options.Value.AddPolicy("Base", policy => policy.RequireClaim("Basic").RequireClaim("Basic2"));
            options.Value.AddPolicy("Derived", policy => policy.RequireClaim("Derived"));

            var policyProvider       = new DefaultAuthorizationPolicyProvider(options);
            var autorizationProvider = new AuthorizationPageApplicationModelProvider(policyProvider);

            var context = GetApplicationProviderContext(typeof(TestPageWithDerivedModel).GetTypeInfo());

            // Act
            autorizationProvider.OnProvidersExecuting(context);

            // Assert
            var authorizeFilter = Assert.IsType <AuthorizeFilter>(Assert.Single(context.PageApplicationModel.Filters));

            // Basic + Basic2 + Derived authorize
            Assert.Equal(3, authorizeFilter.Policy.Requirements.Count);
        }
示例#37
0
        public void OnProvidersExecuting_DiscoversFilesUnderBasePath()
        {
            // Arrange
            var fileProvider = new TestFileProvider();
            var dir1         = fileProvider.AddDirectoryContent("/Pages",
                                                                new[]
            {
                fileProvider.AddFile("/Pages/Index.cshtml", "@page"),
                fileProvider.AddFile("/Pages/_Layout.cshtml", "@page")
            });
            var dir2 = fileProvider.AddDirectoryContent("/NotPages",
                                                        new[]
            {
                fileProvider.AddFile("/NotPages/Index.cshtml", "@page"),
                fileProvider.AddFile("/NotPages/_Layout.cshtml", "@page")
            });
            var rootFile = fileProvider.AddFile("/Index.cshtml", "@page");

            fileProvider.AddDirectoryContent("/", new IFileInfo[] { rootFile, dir1, dir2 });

            var project = new TestRazorProject(fileProvider);

            var optionsManager = new TestOptionsManager <RazorPagesOptions>();

            optionsManager.Value.RootDirectory = "/Pages";
            var provider = new RazorProjectPageRouteModelProvider(project, optionsManager, NullLoggerFactory.Instance);
            var context  = new PageRouteModelProviderContext();

            // Act
            provider.OnProvidersExecuting(context);

            // Assert
            Assert.Collection(context.RouteModels,
                              model =>
            {
                Assert.Equal("/Pages/Index.cshtml", model.RelativePath);
            });
        }
        private DefaultAntiforgery GetAntiforgery(
            HttpContext httpContext,
            AntiforgeryOptions options = null,
            IAntiforgeryTokenGenerator tokenGenerator   = null,
            IAntiforgeryTokenSerializer tokenSerializer = null,
            IAntiforgeryTokenStore tokenStore           = null)
        {
            var optionsManager = new TestOptionsManager();

            if (options != null)
            {
                optionsManager.Value = options;
            }

            var loggerFactory = httpContext.RequestServices.GetRequiredService <ILoggerFactory>();

            return(new DefaultAntiforgery(
                       antiforgeryOptionsAccessor: optionsManager,
                       tokenGenerator: tokenGenerator,
                       tokenSerializer: tokenSerializer,
                       tokenStore: tokenStore,
                       loggerFactory: loggerFactory));
        }
示例#39
0
        public void GetView_ReturnsView_WhenExactlyOneViewEngineIsRegisteredWhichReturnsAFoundResult(bool isMainPage)
        {
            // Arrange
            var viewName         = "test-view.cshtml";
            var expectedViewName = "~/" + viewName;
            var engine           = new Mock <IViewEngine>(MockBehavior.Strict);
            var view             = Mock.Of <IView>();

            engine
            .Setup(e => e.GetView("~/Index.html", viewName, isMainPage))
            .Returns(ViewEngineResult.Found(expectedViewName, view));
            var optionsAccessor = new TestOptionsManager <MvcViewOptions>();

            optionsAccessor.Value.ViewEngines.Add(engine.Object);
            var compositeViewEngine = new CompositeViewEngine(optionsAccessor);

            // Act
            var result = compositeViewEngine.GetView("~/Index.html", viewName, isMainPage);

            // Assert
            Assert.True(result.Success);
            Assert.Same(view, result.View);
        }
        public void CreateBinder_CreatesNoOpBinder_WhenPropertyBindingIsNotAllowed()
        {
            // Arrange
            var metadataProvider = new TestModelMetadataProvider();

            metadataProvider
            .ForProperty <Widget>(nameof(Widget.Id))
            .BindingDetails(m => m.IsBindingAllowed = false);

            var modelBinder = new ByteArrayModelBinder();

            var options = new TestOptionsManager <MvcOptions>();

            options.Value.ModelBinderProviders.Add(new TestModelBinderProvider(c =>
            {
                if (c.Metadata.ModelType == typeof(WidgetId))
                {
                    return(modelBinder);
                }

                return(null);
            }));

            var factory = new ModelBinderFactory(metadataProvider, options);

            var context = new ModelBinderFactoryContext()
            {
                Metadata = metadataProvider.GetMetadataForProperty(typeof(Widget), nameof(Widget.Id)),
            };

            // Act
            var result = factory.CreateBinder(context);

            // Assert
            Assert.NotNull(result);
            Assert.IsType <NoOpBinder>(result);
        }
        public void CreateBinder_BreaksCycles()
        {
            // Arrange
            var metadataProvider = new TestModelMetadataProvider();

            var callCount = 0;

            var options = new TestOptionsManager <MvcOptions>();

            options.Value.ModelBinderProviders.Add(new TestModelBinderProvider(c =>
            {
                var currentCallCount = ++callCount;
                Assert.Equal(typeof(Employee), c.Metadata.ModelType);
                var binder = c.CreateBinder(c.Metadata.Properties[nameof(Employee.Manager)]);

                if (currentCallCount == 2)
                {
                    Assert.IsType <PlaceholderBinder>(binder);
                }

                return(Mock.Of <IModelBinder>());
            }));

            var factory = new ModelBinderFactory(metadataProvider, options);

            var context = new ModelBinderFactoryContext()
            {
                Metadata = metadataProvider.GetMetadataForType(typeof(Employee)),
            };

            // Act
            var result = factory.CreateBinder(context);

            // Assert
            Assert.NotNull(result);
        }
        private static HttpContext GetHttpContext()
        {
            var httpContext = new Mock<HttpContext>();
            var realContext = new DefaultHttpContext();
            var request = realContext.Request;
            request.PathBase = new PathString("");
            var response = realContext.Response;
            response.Body = new MemoryStream();

            httpContext.Setup(o => o.Request)
                       .Returns(request);
            var optionsAccessor = new TestOptionsManager<MvcOptions>();
            optionsAccessor.Value.OutputFormatters.Add(new StringOutputFormatter());
            optionsAccessor.Value.OutputFormatters.Add(new JsonOutputFormatter());
            httpContext.Setup(o => o.RequestServices.GetService(typeof(IOptions<MvcOptions>)))
                .Returns(optionsAccessor);
            httpContext.Setup(o => o.RequestServices.GetService(typeof(ILogger<ObjectResult>)))
                .Returns(new Mock<ILogger<ObjectResult>>().Object);
            httpContext.Setup(o => o.Response)
                       .Returns(response);

            httpContext.Setup(o => o.RequestServices.GetService(typeof(IActionBindingContextAccessor)))
                       .Returns(new ActionBindingContextAccessor());

            return httpContext.Object;
        }
        private PartialViewResultExecutor GetViewExecutor(DiagnosticSource diagnosticSource = null)
        {
            if (diagnosticSource == null)
            {
                diagnosticSource = new DiagnosticListener("Test");
            }

            var viewEngine = new Mock<IViewEngine>(MockBehavior.Strict);
            viewEngine
                .Setup(e => e.FindPartialView(It.IsAny<ActionContext>(), It.IsAny<string>()))
                .Returns<ActionContext, string>((_, name) => ViewEngineResult.Found(name, Mock.Of<IView>()));

            var options = new TestOptionsManager<MvcViewOptions>();
            options.Value.ViewEngines.Add(viewEngine.Object);

            var viewExecutor = new PartialViewResultExecutor(
                options,
                new TestHttpResponseStreamWriterFactory(),
                new CompositeViewEngine(options),
                diagnosticSource,
                NullLoggerFactory.Instance);

            return viewExecutor;
        }
示例#44
0
        public void CreateBinder_BreaksCycles()
        {
            // Arrange
            var metadataProvider = new TestModelMetadataProvider();

            var callCount = 0;

            var options = new TestOptionsManager<MvcOptions>();
            options.Value.ModelBinderProviders.Add(new TestModelBinderProvider(c =>
            {
                var currentCallCount = ++callCount;
                Assert.Equal(typeof(Employee), c.Metadata.ModelType);
                var binder = c.CreateBinder(c.Metadata.Properties[nameof(Employee.Manager)]);

                if (currentCallCount == 2)
                {
                    Assert.IsType<PlaceholderBinder>(binder);
                }

                return Mock.Of<IModelBinder>();
            }));

            var factory = new ModelBinderFactory(metadataProvider, options);

            var context = new ModelBinderFactoryContext()
            {
                Metadata = metadataProvider.GetMetadataForType(typeof(Employee)),
            };

            // Act
            var result = factory.CreateBinder(context);

            // Assert
            Assert.NotNull(result);
        }
示例#45
0
        public void CreateBinder_Throws_WhenBinderNotCreated()
        {
            // Arrange
            var metadataProvider = new TestModelMetadataProvider();
            var options = new TestOptionsManager<MvcOptions>();
            var factory = new ModelBinderFactory(metadataProvider, options);

            var context = new ModelBinderFactoryContext()
            {
                Metadata = metadataProvider.GetMetadataForType(typeof(string)),
            };

            // Act
            var exception = Assert.Throws<InvalidOperationException>(() => factory.CreateBinder(context));

            // Assert
            Assert.Equal(
                $"Could not create a model binder for model object of type '{typeof(string).FullName}'.",
                exception.Message);
        }
示例#46
0
        private RouteContext CreateRouteContext(
            ActionDescriptor actionDescriptor = null,
            IActionSelector actionSelector = null,
            IActionInvokerFactory invokerFactory = null,
            ILoggerFactory loggerFactory = null,
            IOptions<MvcOptions> optionsAccessor = null,
            object diagnosticListener = null)
        {
            if (actionDescriptor == null)
            {
                var mockAction = new Mock<ActionDescriptor>();
                actionDescriptor = mockAction.Object;
            }

            if (actionSelector == null)
            {
                var mockActionSelector = new Mock<IActionSelector>();
                mockActionSelector.Setup(a => a.Select(It.IsAny<RouteContext>()))
                    .Returns(actionDescriptor);

                actionSelector = mockActionSelector.Object;
            }

            if (invokerFactory == null)
            {
                var mockInvoker = new Mock<IActionInvoker>();
                mockInvoker.Setup(i => i.InvokeAsync())
                    .Returns(Task.FromResult(true));

                var mockInvokerFactory = new Mock<IActionInvokerFactory>();
                mockInvokerFactory.Setup(f => f.CreateInvoker(It.IsAny<ActionContext>()))
                    .Returns(mockInvoker.Object);

                invokerFactory = mockInvokerFactory.Object;
            }

            if (loggerFactory == null)
            {
                loggerFactory = NullLoggerFactory.Instance;
            }

            if (optionsAccessor == null)
            {
                optionsAccessor = new TestOptionsManager<MvcOptions>();
            }

            var diagnosticSource = new DiagnosticListener("Microsoft.AspNetCore");
            if (diagnosticListener != null)
            {
                diagnosticSource.SubscribeWithAdapter(diagnosticListener);
            }

            var routingFeature = new RoutingFeature();

            var httpContext = new Mock<HttpContext>();
            httpContext
                .Setup(h => h.RequestServices.GetService(typeof(IActionContextAccessor)))
                .Returns(new ActionContextAccessor());
            httpContext
                .Setup(h => h.RequestServices.GetService(typeof(IActionSelector)))
                .Returns(actionSelector);
            httpContext
                .Setup(h => h.RequestServices.GetService(typeof(IActionInvokerFactory)))
                .Returns(invokerFactory);
            httpContext
                .Setup(h => h.RequestServices.GetService(typeof(ILoggerFactory)))
                .Returns(loggerFactory);
            httpContext
                .Setup(h => h.RequestServices.GetService(typeof(MvcMarkerService)))
                .Returns(new MvcMarkerService());
            httpContext
                .Setup(h => h.RequestServices.GetService(typeof(IOptions<MvcOptions>)))
                .Returns(optionsAccessor);
            httpContext
                .Setup(h => h.RequestServices.GetService(typeof(DiagnosticSource)))
                .Returns(diagnosticSource);
            httpContext
                .Setup(h => h.Features[typeof(IRoutingFeature)])
                .Returns(routingFeature);

            var routeContext = new RouteContext(httpContext.Object);
            routingFeature.RouteData = routeContext.RouteData;
            return routeContext;
        }
示例#47
0
        public void CreateBinder_DoesNotCache_WhenTokenIsNull()
        {
            // Arrange
            var metadataProvider = new TestModelMetadataProvider();

            var options = new TestOptionsManager<MvcOptions>();
            options.Value.ModelBinderProviders.Add(new TestModelBinderProvider(c =>
            {
                Assert.Equal(typeof(Employee), c.Metadata.ModelType);
                return Mock.Of<IModelBinder>();
            }));

            var factory = new ModelBinderFactory(metadataProvider, options);

            var context = new ModelBinderFactoryContext()
            {
                Metadata = metadataProvider.GetMetadataForType(typeof(Employee)),
            };

            // Act
            var result1 = factory.CreateBinder(context);
            var result2 = factory.CreateBinder(context);

            // Assert
            Assert.NotSame(result1, result2);
        }
示例#48
0
        public void FindView_ReturnsViewFromFirstViewEngineWithFoundResult()
        {
            // Arrange
            var viewName = "foo";
            var engine1 = new Mock<IViewEngine>();
            var engine2 = new Mock<IViewEngine>();
            var engine3 = new Mock<IViewEngine>();
            var view2 = Mock.Of<IView>();
            var view3 = Mock.Of<IView>();
            engine1.Setup(e => e.FindView(It.IsAny<ActionContext>(), It.IsAny<string>()))
                   .Returns(ViewEngineResult.NotFound(viewName, Enumerable.Empty<string>()));
            engine2.Setup(e => e.FindView(It.IsAny<ActionContext>(), It.IsAny<string>()))
                   .Returns(ViewEngineResult.Found(viewName, view2));
            engine3.Setup(e => e.FindView(It.IsAny<ActionContext>(), It.IsAny<string>()))
                   .Returns(ViewEngineResult.Found(viewName, view3));

            var optionsAccessor = new TestOptionsManager<MvcViewOptions>();
            optionsAccessor.Value.ViewEngines.Add(engine1.Object);
            optionsAccessor.Value.ViewEngines.Add(engine2.Object);
            optionsAccessor.Value.ViewEngines.Add(engine3.Object);
            var compositeViewEngine = new CompositeViewEngine(optionsAccessor);

            // Act
            var result = compositeViewEngine.FindView(GetActionContext(), viewName);

            // Assert
            Assert.True(result.Success);
            Assert.Same(view2, result.View);
            Assert.Equal(viewName, result.ViewName);
        }
        private ControllerActionDescriptorProvider GetProvider(
            TypeInfo controllerTypeInfo,
            IApplicationModelConvention convention)
        {
            var options = new TestOptionsManager<MvcOptions>();
            options.Value.Conventions.Add(convention);

            var controllerTypeProvider = new StaticControllerTypeProvider(new[] { controllerTypeInfo });
            var modelProvider = new DefaultApplicationModelProvider(options);

            var provider = new ControllerActionDescriptorProvider(
                controllerTypeProvider,
                new[] { modelProvider },
                options);

            return provider;
        }
        private ControllerActionDescriptorProvider GetProvider(
            params TypeInfo[] controllerTypeInfos)
        {
            var options = new TestOptionsManager<MvcOptions>();

            var controllerTypeProvider = new StaticControllerTypeProvider(controllerTypeInfos);
            var modelProvider = new DefaultApplicationModelProvider(options);

            var provider = new ControllerActionDescriptorProvider(
                controllerTypeProvider,
                new[] { modelProvider },
                options);

            return provider;
        }
        private ControllerActionDescriptorProvider GetProvider(
            TypeInfo controllerTypeInfo,
            IEnumerable<IFilterMetadata> filters = null)
        {
            var options = new TestOptionsManager<MvcOptions>();
            if (filters != null)
            {
                foreach (var filter in filters)
                {
                    options.Value.Filters.Add(filter);
                }
            }

            var controllerTypeProvider = new StaticControllerTypeProvider(new[] { controllerTypeInfo });
            var modelProvider = new DefaultApplicationModelProvider(options);

            var provider = new ControllerActionDescriptorProvider(
                controllerTypeProvider,
                new[] { modelProvider },
                options);

            return provider;
        }
        public void ApplyConventions_RunsInOrderOfDecreasingScope()
        {
            // Arrange
            var sequence = 0;

            var applicationConvention = new Mock<IApplicationModelConvention>();
            applicationConvention
                .Setup(c => c.Apply(It.IsAny<ApplicationModel>()))
                .Callback(() => { Assert.Equal(0, sequence++); });

            var controllerConvention = new Mock<IControllerModelConvention>();
            controllerConvention
                .Setup(c => c.Apply(It.IsAny<ControllerModel>()))
                .Callback(() => { Assert.Equal(1, sequence++); });

            var actionConvention = new Mock<IActionModelConvention>();
            actionConvention
                .Setup(c => c.Apply(It.IsAny<ActionModel>()))
                .Callback(() => { Assert.Equal(2, sequence++); });

            var parameterConvention = new Mock<IParameterModelConvention>();
            parameterConvention
                .Setup(c => c.Apply(It.IsAny<ParameterModel>()))
                .Callback(() => { Assert.Equal(3, sequence++); });

            var options = new TestOptionsManager<MvcOptions>();
            options.Value.Conventions.Add(applicationConvention.Object);

            var applicationModel = new ApplicationModel();

            var controller = new ControllerModel(typeof(ConventionsController).GetTypeInfo(),
                                                 new List<object>() { controllerConvention.Object });
            controller.Application = applicationModel;
            applicationModel.Controllers.Add(controller);

            var methodInfo = typeof(ConventionsController).GetMethod("Create");
            var actionModel = new ActionModel(methodInfo, new List<object>() { actionConvention.Object });
            actionModel.Controller = controller;
            controller.Actions.Add(actionModel);

            var parameterInfo = actionModel.ActionMethod.GetParameters().Single();
            var parameterModel = new ParameterModel(parameterInfo,
                                           new List<object>() { parameterConvention.Object });
            parameterModel.Action = actionModel;
            actionModel.Parameters.Add(parameterModel);

            // Act
            ApplicationModelConventions.ApplyConventions(applicationModel, options.Value.Conventions);

            // Assert
            Assert.Equal(4, sequence);
        }
示例#53
0
        public void CreateBinder_PassesExpectedBindingInfo(
            BindingInfo parameterBindingInfo,
            BindingMetadata bindingMetadata,
            BindingInfo expectedInfo)
        {
            // Arrange
            var metadataProvider = new TestModelMetadataProvider();
            metadataProvider.ForType<Employee>().BindingDetails(binding =>
            {
                binding.BinderModelName = bindingMetadata.BinderModelName;
                binding.BinderType = bindingMetadata.BinderType;
                binding.BindingSource = bindingMetadata.BindingSource;
                if (bindingMetadata.PropertyFilterProvider != null)
                {
                    binding.PropertyFilterProvider = bindingMetadata.PropertyFilterProvider;
                }
            });

            var modelBinder = Mock.Of<IModelBinder>();
            var modelBinderProvider = new TestModelBinderProvider(context =>
            {
                Assert.Equal(typeof(Employee), context.Metadata.ModelType);

                Assert.NotNull(context.BindingInfo);
                Assert.Equal(expectedInfo.BinderModelName, context.BindingInfo.BinderModelName, StringComparer.Ordinal);
                Assert.Equal(expectedInfo.BinderType, context.BindingInfo.BinderType);
                Assert.Equal(expectedInfo.BindingSource, context.BindingInfo.BindingSource);
                Assert.Same(expectedInfo.PropertyFilterProvider, context.BindingInfo.PropertyFilterProvider);

                return modelBinder;
            });

            var options = new TestOptionsManager<MvcOptions>();
            options.Value.ModelBinderProviders.Insert(0, modelBinderProvider);

            var factory = new ModelBinderFactory(metadataProvider, options);
            var factoryContext = new ModelBinderFactoryContext
            {
                BindingInfo = parameterBindingInfo,
                Metadata = metadataProvider.GetMetadataForType(typeof(Employee)),
            };

            // Act & Assert
            var result = factory.CreateBinder(factoryContext);

            // Confirm our IModelBinderProvider was called.
            Assert.Same(modelBinder, result);
        }
示例#54
0
        private IServiceProvider GetServiceProvider(Dictionary<string, CacheProfile> cacheProfiles)
        {
            var serviceProvider = new Mock<IServiceProvider>();
            var optionsAccessor = new TestOptionsManager<MvcOptions>();
            if (cacheProfiles != null)
            {
                foreach (var p in cacheProfiles)
                {
                    optionsAccessor.Options.CacheProfiles.Add(p.Key, p.Value);
                }
            }

            serviceProvider
                .Setup(s => s.GetService(typeof(IOptions<MvcOptions>)))
                .Returns(optionsAccessor);

            return serviceProvider.Object;
        }
示例#55
0
        public void CreateBinder_NestedProperties()
        {
            // Arrange
            var metadataProvider = new TestModelMetadataProvider();

            var options = new TestOptionsManager<MvcOptions>();
            options.Value.ModelBinderProviders.Add(new TestModelBinderProvider(c =>
            {
                if (c.Metadata.ModelType == typeof(Widget))
                {
                    Assert.NotNull(c.CreateBinder(c.Metadata.Properties[nameof(Widget.Id)]));
                    return Mock.Of<IModelBinder>();
                }
                else if (c.Metadata.ModelType == typeof(WidgetId))
                {
                    return Mock.Of<IModelBinder>();
                }

                return null;
            }));

            var factory = new ModelBinderFactory(metadataProvider, options);

            var context = new ModelBinderFactoryContext()
            {
                Metadata = metadataProvider.GetMetadataForType(typeof(Widget)),
            };

            // Act
            var result = factory.CreateBinder(context);

            // Assert
            Assert.NotNull(result);
        }
示例#56
0
        public void FindPartialView_ReturnsNotFound_IfAllViewEnginesReturnNotFound()
        {
            // Arrange
            var viewName = "foo";
            var engine1 = new Mock<IViewEngine>();
            var engine2 = new Mock<IViewEngine>();
            var engine3 = new Mock<IViewEngine>();
            engine1.Setup(e => e.FindPartialView(It.IsAny<ActionContext>(), It.IsAny<string>()))
                   .Returns(ViewEngineResult.NotFound(viewName, new[] { "1", "2" }));
            engine2.Setup(e => e.FindPartialView(It.IsAny<ActionContext>(), It.IsAny<string>()))
                   .Returns(ViewEngineResult.NotFound(viewName, new[] { "3" }));
            engine3.Setup(e => e.FindPartialView(It.IsAny<ActionContext>(), It.IsAny<string>()))
                   .Returns(ViewEngineResult.NotFound(viewName, new[] { "4", "5" }));

            var optionsAccessor = new TestOptionsManager<MvcViewOptions>();
            optionsAccessor.Value.ViewEngines.Add(engine1.Object);
            optionsAccessor.Value.ViewEngines.Add(engine2.Object);
            optionsAccessor.Value.ViewEngines.Add(engine3.Object);
            var compositeViewEngine = new CompositeViewEngine(optionsAccessor);

            // Act
            var result = compositeViewEngine.FindPartialView(GetActionContext(), viewName);

            // Assert
            Assert.False(result.Success);
            Assert.Equal(new[] { "1", "2", "3", "4", "5" }, result.SearchedLocations);
        }
        private HttpContext GetHttpContext()
        {
            var options = new TestOptionsManager<MvcViewOptions>();

            var viewExecutor = new PartialViewResultExecutor(
                options,
                new TestHttpResponseStreamWriterFactory(),
                new CompositeViewEngine(options),
                new TempDataDictionaryFactory(new SessionStateTempDataProvider()),
                new DiagnosticListener("Microsoft.AspNet"),
                NullLoggerFactory.Instance);

            var services = new ServiceCollection();
            services.AddSingleton(viewExecutor);

            var httpContext = new DefaultHttpContext();
            httpContext.RequestServices = services.BuildServiceProvider();
            return httpContext;
        }
        private ViewResultExecutor GetViewExecutor(DiagnosticListener diagnosticSource = null)
        {
            if (diagnosticSource == null)
            {
                diagnosticSource = new DiagnosticListener("Test");
            }

            var viewEngine = new Mock<IViewEngine>(MockBehavior.Strict);
            viewEngine
                .Setup(e => e.GetView(/*executingFilePath*/ null, It.IsAny<string>(), /*isMainPage*/ true))
                .Returns<string, string, bool>(
                    (path, name, partial) => ViewEngineResult.NotFound(name, Enumerable.Empty<string>()));
            viewEngine
                .Setup(e => e.FindView(It.IsAny<ActionContext>(), It.IsAny<string>(), /*isMainPage*/ true))
                .Returns<ActionContext, string, bool>(
                    (context, name, partial) => ViewEngineResult.Found(name, Mock.Of<IView>()));

            var options = new TestOptionsManager<MvcViewOptions>();
            options.Value.ViewEngines.Add(viewEngine.Object);

            var viewExecutor = new ViewResultExecutor(
                options,
                new TestHttpResponseStreamWriterFactory(),
                new CompositeViewEngine(options),
                new TempDataDictionaryFactory(new SessionStateTempDataProvider()),
                diagnosticSource,
                NullLoggerFactory.Instance);

            return viewExecutor;
        }
示例#59
0
        public void CreateBinder_CreatesNoOpBinder_WhenPropertyDoesntHaveABinder()
        {
            // Arrange
            var metadataProvider = new TestModelMetadataProvider();

            // There isn't a provider that can handle WidgetId.
            var options = new TestOptionsManager<MvcOptions>();
            options.Value.ModelBinderProviders.Add(new TestModelBinderProvider(c =>
            {
                if (c.Metadata.ModelType == typeof(Widget))
                {
                    Assert.NotNull(c.CreateBinder(c.Metadata.Properties[nameof(Widget.Id)]));
                    return Mock.Of<IModelBinder>();
                }

                return null;
            }));

            var factory = new ModelBinderFactory(metadataProvider, options);

            var context = new ModelBinderFactoryContext()
            {
                Metadata = metadataProvider.GetMetadataForType(typeof(Widget)),
            };

            // Act
            var result = factory.CreateBinder(context);

            // Assert
            Assert.NotNull(result);
        }
        private ControllerActionDescriptorProvider GetActionDescriptorProvider()
        {
            var controllerTypes = typeof(DefaultActionSelectorTests)
                .GetNestedTypes(BindingFlags.NonPublic)
                .Select(t => t.GetTypeInfo())
                .ToList();

            var options = new TestOptionsManager<MvcOptions>();

            var controllerTypeProvider = new StaticControllerTypeProvider(controllerTypes);
            var modelProvider = new DefaultApplicationModelProvider(options);

            var provider = new ControllerActionDescriptorProvider(
                controllerTypeProvider,
                new[] { modelProvider },
                options);

            return provider;
        }