private TestDotvvmRequestContext PrepareRequest( string fileName, PostbackRequestModel postback = null ) { var context = DotvvmTestHelper.CreateContext(configuration); context.CsrfToken = null; context.Route = new Framework.Routing.DotvvmRoute( "testpage", fileName, null, null, configuration); var httpContext = (TestHttpContext)context.HttpContext; if (postback is object) { httpContext.Request.Method = "POST"; httpContext.Request.Headers["X-DotVVM-PostBack"] = new[] { "true" }; httpContext.Request.Body = new MemoryStream( new UTF8Encoding(false).GetBytes( JsonConvert.SerializeObject(postback) ) ); } return(context); }
public string CompileBinding(string expression, Type[] contexts, Type expectedType) { var configuration = DotvvmTestHelper.CreateConfiguration(); configuration.RegisterApiClient(typeof(TestApiClient), "http://server/api", "./apiscript.js", "_api"); configuration.Markup.ImportedNamespaces.Add(new NamespaceImport("DotVVM.Framework.Tests.Binding")); var context = DataContextStack.Create(contexts.FirstOrDefault() ?? typeof(object), extensionParameters: new BindingExtensionParameter[] { new BindingPageInfoExtensionParameter(), }.Concat(configuration.Markup.DefaultExtensionParameters).ToArray()); for (int i = 1; i < contexts.Length; i++) { context = DataContextStack.Create(contexts[i], context); } var parser = new BindingExpressionBuilder(); var expressionTree = parser.ParseWithLambdaConversion(expression, context, BindingParserOptions.Create <ValueBindingExpression>(), expectedType); var jsExpression = configuration.ServiceProvider.GetRequiredService <StaticCommandBindingCompiler>().CompileToJavascript(context, expressionTree); return(KnockoutHelper.GenerateClientPostBackScript( "", new FakeCommandBinding(BindingPropertyResolvers.FormatJavascript(jsExpression, nullChecks: false), null), new Literal(), new PostbackScriptOptions( allowPostbackHandlers: false, returnValue: null, commandArgs: CodeParameterAssignment.FromIdentifier("commandArguments") ))); }
public void LocalizablePresenter_RedirectsOnInvalidLanguageCode() { var config = DotvvmConfiguration.CreateDefault(); var presenterFactory = LocalizablePresenter.BasedOnParameter("Lang"); config.RouteTable.Add("Test", "test/Lang", "test", new { Lang = "en" }, presenterFactory); var context = DotvvmTestHelper.CreateContext(config); context.Parameters["Lang"] = "cz"; context.Route = config.RouteTable.First(); var httpRequest = new TestHttpContext(); httpRequest.Request = new TestHttpRequest(httpRequest) { PathBase = "" }; httpRequest.Request.Headers.Add(HostingConstants.SpaContentPlaceHolderHeaderName, new string[0]); context.HttpContext = httpRequest; var localizablePresenter = presenterFactory(config.ServiceProvider); Assert.ThrowsException <DotvvmInterruptRequestExecutionException>(() => localizablePresenter.ProcessRequest(context)); }
public void ControlCollection_InitializedAncestorModified() { var innerInitCalled = false; var root = new ControlLifeCycleMock { InitAction = (control, context) => { // generate a child control in the Init phase control.Children.Add(new ControlLifeCycleMock()); // generate a second child that adds elements inside the first child control.Children.Add(new ControlLifeCycleMock() { InitAction = (control2, context2) => { control2.Parent.CastTo <DotvvmControl>().Children.First().Children.Add(new ControlLifeCycleMock() { InitAction = (control3, context3) => { // verify that the lately added control still calls the Init innerInitCalled = true; } }); } }); } }; root.SetValue(Internal.RequestContextProperty, DotvvmTestHelper.CreateContext()); DotvvmControlCollection.InvokePageLifeCycleEventRecursive(root, LifeCycleEventType.Init); Assert.IsTrue(innerInitCalled); }
public void ControlCollection_AddingToOptimizedControl() { var eventLog = new List <ControlLifeCycleEvent>(); var root = new ControlLifeCycleMock(eventLog, "root") { InitAction = (control, context) => { control.Children.Add(new ControlLifeCycleMock(eventLog, "root_a") { LifecycleRequirements = ControlLifecycleRequirements.None, }); }, }; root.SetValue(Internal.RequestContextProperty, DotvvmTestHelper.CreateContext()); DotvvmControlCollection.InvokePageLifeCycleEventRecursive(root, LifeCycleEventType.PreRender); var root_New = new ControlLifeCycleMock(eventLog, "root_New"); root.Children.Add(root_New); var root_a_New = new ControlLifeCycleMock(eventLog, "root_a_New"); root.Children.First().Children.Add(root_a_New); Assert.IsTrue(eventLog.Count(e => e.Control == root_a_New) == eventLog.Count(e => e.Control == root_New), "Control added to root has not the same number of event as control added to the optimized one."); }
public void ControlCollection_ControlsCreatedOnLoad() { var innerInitCalled = false; var innerLoadCalled = false; var root = new ControlLifeCycleMock { LoadAction = (control, context) => { // generate a child control in the Load phase control.Children.Add(new ControlLifeCycleMock() { InitAction = (control2, context2) => { // test whether the Init on the inner control is called innerInitCalled = true; }, LoadAction = (control2, context2) => { // test whether the Load on the inner control is called innerLoadCalled = true; } }); } }; root.SetValue(Internal.RequestContextProperty, DotvvmTestHelper.CreateContext()); DotvvmControlCollection.InvokePageLifeCycleEventRecursive(root, LifeCycleEventType.Init); DotvvmControlCollection.InvokePageLifeCycleEventRecursive(root, LifeCycleEventType.Load); Assert.IsTrue(innerInitCalled); Assert.IsTrue(innerLoadCalled); }
public void ResourceManager_SimpleTest() { var configuration = DotvvmTestHelper.CreateConfiguration(); var manager = new ResourceManager(configuration.Resources); manager.AddRequiredResource(ResourceConstants.GlobalizeResourceName); Assert.AreEqual(configuration.Resources.FindResource(ResourceConstants.GlobalizeResourceName), manager.GetResourcesInOrder().First()); }
private DotvvmControl CompileMarkup(string markup, Dictionary <string, string> markupFiles = null, bool compileTwice = false, [CallerMemberName] string fileName = null) { if (markupFiles == null) { markupFiles = new Dictionary <string, string>(); } markupFiles[fileName + ".dothtml"] = markup; var config = DotvvmTestHelper.CreateConfiguration(services => { services.AddSingleton <IMarkupFileLoader>(new FakeMarkupFileLoader(markupFiles)); services.AddSingleton <CustomControlFactory>((s, t) => t == typeof(TestCustomDependencyInjectionControl) ? new TestCustomDependencyInjectionControl("") { IsCorrectlyCreated = true } : throw new Exception()); }); context = DotvvmTestHelper.CreateContext(config); context.Configuration.ApplicationPhysicalPath = Path.GetTempPath(); context.Configuration.Markup.Controls.Add(new DotvvmControlConfiguration() { TagPrefix = "cc", TagName = "Test1", Src = "test1.dothtml" }); context.Configuration.Markup.Controls.Add(new DotvvmControlConfiguration() { TagPrefix = "cc", TagName = "Test2", Src = "test2.dothtml" }); context.Configuration.Markup.Controls.Add(new DotvvmControlConfiguration() { TagPrefix = "cc", TagName = "Test3", Src = "test3.dothtml" }); context.Configuration.Markup.Controls.Add(new DotvvmControlConfiguration() { TagPrefix = "cc", TagName = "Test4", Src = "test4.dothtml" }); context.Configuration.Markup.Controls.Add(new DotvvmControlConfiguration() { TagPrefix = "cc", TagName = "Test5", Src = "test5.dothtml" }); context.Configuration.Markup.AddCodeControls("ff", typeof(TestControl)); context.Configuration.Markup.AddAssembly(typeof(DefaultViewCompilerTests).GetTypeInfo().Assembly.GetName().Name); var controlBuilderFactory = context.Services.GetRequiredService <IControlBuilderFactory>(); var(_, controlBuilder) = controlBuilderFactory.GetControlBuilder(fileName + ".dothtml"); var result = controlBuilder.Value.BuildControl(controlBuilderFactory, context.Services); if (compileTwice) { result = controlBuilder.Value.BuildControl(controlBuilderFactory, context.Services); } result.SetValue(Internal.RequestContextProperty, context); return(result); }
ResolvedControl ParseControl(string markup, Type viewModel = null) { viewModel = viewModel ?? typeof(TestViewModel); var tree = DotvvmTestHelper.ParseResolvedTree($"@viewModel {viewModel}\n{markup}"); var control = tree.Content.First(c => c.Metadata.Type != typeof(RawLiteral)); return(control); }
public void ControlCollection_NestedControlsWithNoneRequirementParent() { var initCalled = false; var loadCalled = false; var preRenderCalled = false; var firstChild = new ControlLifeCycleMock() { LifecycleRequirements = ControlLifecycleRequirements.All, }; var secondChild = new ControlLifeCycleMock() { LifecycleRequirements = ControlLifecycleRequirements.All, InitAction = (control, _) => { initCalled = true; }, LoadAction = (control, _) => { loadCalled = true; }, PreRenderAction = (control, _) => { preRenderCalled = true; } }; var root = new ControlLifeCycleMock(); root.RenderAction = (control, _) => { var innerRoot = new ControlLifeCycleMock() { LifecycleRequirements = ControlLifecycleRequirements.None }; root.Children.Add(innerRoot); var td1 = new ControlLifeCycleMock() { LifecycleRequirements = ControlLifecycleRequirements.None }; innerRoot.Children.Add(td1); td1.Children.Add(firstChild); var td2 = new ControlLifeCycleMock() { LifecycleRequirements = ControlLifecycleRequirements.None }; innerRoot.Children.Add(td2); td2.Children.Add(secondChild); }; root.SetValue(Internal.RequestContextProperty, DotvvmTestHelper.CreateContext()); DotvvmControlCollection.InvokePageLifeCycleEventRecursive(root, LifeCycleEventType.PreRenderComplete); root.Render(null, null); Assert.IsTrue(initCalled); Assert.IsTrue(loadCalled); Assert.IsTrue(preRenderCalled); }
string WriteHtml(Action <HtmlWriter> a) { var text = new StringWriter(); a(new HtmlWriter(text, new TestDotvvmRequestContext() { Configuration = DotvvmTestHelper.CreateConfiguration() })); return(text.ToString()); }
public void ResourceManager_DependentResources_Css() { var configuration = DotvvmTestHelper.CreateConfiguration(); var manager = new ResourceManager(configuration.Resources); manager.AddRequiredResource(ResourceConstants.DotvvmFileUploadCssResourceName); var resourcesInCorrectOrder = manager.GetResourcesInOrder().ToList(); Assert.AreEqual(configuration.Resources.FindResource(ResourceConstants.DotvvmFileUploadCssResourceName), resourcesInCorrectOrder[0]); }
private static TestDotvvmRequestContext CreateContext(object viewModel, DotvvmConfiguration configuration = null) { configuration = configuration ?? DotvvmTestHelper.CreateConfiguration(); return(new TestDotvvmRequestContext() { Configuration = configuration, ResourceManager = new ResourceManagement.ResourceManager(configuration.Resources), ViewModel = viewModel }); }
private JObject CreateDiff(Action <DotvvmConfiguration> fn) { var config = DotvvmTestHelper.CreateConfiguration(); var json0 = JObject.FromObject(config, serializer); fn(config); var json1 = JObject.FromObject(config, serializer); return(JsonUtils.Diff(json0, json1)); }
public void ResourceManager_ConfigurationDeserialization() { //define var config1 = DotvvmTestHelper.CreateConfiguration(); config1.Resources.Register("rs1", new ScriptResource(new FileResourceLocation("file.js"))); config1.Resources.Register("rs2", new StylesheetResource(new UrlResourceLocation("http://c.c/"))); config1.Resources.Register("rs3", new StylesheetResource(new EmbeddedResourceLocation(typeof(DotvvmConfiguration).GetTypeInfo().Assembly, "DotVVM.Framework.Resources.Scripts.knockout-latest.js", "../file.js"))); config1.Resources.Register("rs4", new InlineScriptResource("CODE", ResourceRenderPosition.Head)); config1.Resources.Register("rs5", new NullResource()); config1.Resources.Register("rs6", new ScriptResource( new UrlResourceLocation("http://d.d/")) { LocationFallback = new ResourceLocationFallback("condition", new FileResourceLocation("file1.js")) }); config1.Resources.Register("rs7", new PolyfillResource() { RenderPosition = ResourceRenderPosition.Head }); config1.Resources.Register("rs8", new ScriptResource(new JQueryGlobalizeResourceLocation(CultureInfo.GetCultureInfo("en-US")))); // serialize & deserialize JsonSerializerSettings settings = new JsonSerializerSettings { TypeNameHandling = TypeNameHandling.Auto }; var config2 = JsonConvert.DeserializeObject <DotvvmConfiguration>(JsonConvert.SerializeObject(config1, settings), settings); //test Assert.IsTrue(config2.Resources.FindResource("rs1") is ScriptResource rs1 && rs1.Location is FileResourceLocation rs1loc && rs1loc.FilePath == "file.js"); Assert.IsTrue(config2.Resources.FindResource("rs2") is StylesheetResource rs2 && rs2.Location is UrlResourceLocation rs2loc && rs2loc.Url == "http://c.c/"); Assert.IsTrue(config2.Resources.FindResource("rs3") is StylesheetResource rs3 && rs3.Location is EmbeddedResourceLocation rs3loc && rs3loc.Assembly.GetName().Name == "DotVVM.Framework" && rs3loc.Name == "DotVVM.Framework.Resources.Scripts.knockout-latest.js" && rs3loc.DebugFilePath == "../file.js"); Assert.IsTrue(config2.Resources.FindResource("rs4") is InlineScriptResource rs4 && rs4.RenderPosition == ResourceRenderPosition.Head && rs4.Code == "CODE"); Assert.IsTrue(config2.Resources.FindResource("rs5") is NullResource); Assert.IsTrue(config2.Resources.FindResource("rs6") is ScriptResource rs6 && rs6.Location is UrlResourceLocation rs6loc && rs6loc.Url == "http://d.d/" && rs6.LocationFallback.JavascriptCondition == "condition" && rs6.LocationFallback.AlternativeLocations.Single() is FileResourceLocation rs6loc2 && rs6loc2.FilePath == "file1.js"); Assert.IsTrue(config2.Resources.FindResource("rs7") is PolyfillResource rs7 && rs7.RenderPosition == ResourceRenderPosition.Head); Assert.IsTrue(config2.Resources.FindResource("rs8") is ScriptResource rs8 && rs8.Location is JQueryGlobalizeResourceLocation rs8loc); }
public ModelStateFromExpressionTests() { this.viewModel = new ViewModel(); this.viewModel.Context = new TestDotvvmRequestContext { Configuration = DotvvmTestHelper.CreateConfiguration() }; this.viewModel.Context.Configuration.ServiceLocator.GetService <IViewModelSerializationMapper>().Map(typeof(ViewModel), m => { m.Property(nameof(ViewModel.RenamedProperty)).Name = "rp"; }); }
public void ResourceManager_DependentResources() { var configuration = DotvvmTestHelper.CreateConfiguration(); var manager = new ResourceManager(configuration); manager.AddRequiredResource(ResourceConstants.DotvvmResourceName); var resourcesInCorrectOrder = manager.GetResourcesInOrder().ToList(); Assert.AreEqual(configuration.Resources.FindResource(ResourceConstants.KnockoutJSResourceName), resourcesInCorrectOrder[0]); Assert.AreEqual(configuration.Resources.FindResource(ResourceConstants.DotvvmResourceName + ".internal"), resourcesInCorrectOrder[1]); Assert.AreEqual(configuration.Resources.FindResource(ResourceConstants.DotvvmResourceName), resourcesInCorrectOrder[2]); }
public ControlTestHelper(bool debug = true, Action <DotvvmConfiguration> config = null, Action <IServiceCollection> services = null) { fileLoader = new FakeMarkupFileLoader(null); this.configuration = DotvvmTestHelper.CreateConfiguration(s => { s.AddSingleton <IMarkupFileLoader>(fileLoader); services?.Invoke(s); }); this.configuration.Markup.AddCodeControls("tc", exampleControl: typeof(FakeHeadResourceLink)); this.configuration.ApplicationPhysicalPath = Path.GetTempPath(); this.configuration.Debug = debug; config?.Invoke(this.configuration); presenter = (DotvvmPresenter)this.configuration.ServiceProvider.GetRequiredService <IDotvvmPresenter>(); }
public void ResourceManager_ConfigurationOldDeserialization() { var json = string.Format(@" {{ 'resources': {{ 'scripts': {{ '{0}': {{ 'url': 'different url', 'globalObjectName': '$'}} }}, 'stylesheets': {{ 'newResource': {{ 'url': 'test' }} }} }} }}", ResourceConstants.GlobalizeResourceName); var configuration = DotvvmTestHelper.CreateConfiguration(); JsonConvert.PopulateObject(json.Replace("'", "\""), configuration); Assert.IsTrue(configuration.Resources.FindResource(ResourceConstants.GlobalizeResourceName) is ScriptResource); Assert.IsTrue(configuration.Resources.FindResource("newResource") is StylesheetResource); }
public string CompileBinding(Func<Dictionary<string, Expression>, Expression> expr, Type[] contexts) { var context = DataContextStack.Create(contexts.FirstOrDefault() ?? typeof(object), extensionParameters: new BindingExtensionParameter[]{ new BindingPageInfoExtensionParameter() }); for (int i = 1; i < contexts.Length; i++) { context = DataContextStack.Create(contexts[i], context); } var expressionTree = expr(BindingExpressionBuilder.GetParameters(context).ToDictionary(e => e.Name, e => (Expression)e)); var configuration = DotvvmTestHelper.CreateConfiguration(); var jsExpression = new JsParenthesizedExpression(configuration.ServiceProvider.GetRequiredService<JavascriptTranslator>().CompileToJavascript(expressionTree, context)); jsExpression.AcceptVisitor(new KnockoutObservableHandlingVisitor(true)); JsTemporaryVariableResolver.ResolveVariables(jsExpression); return JavascriptTranslator.FormatKnockoutScript(jsExpression.Expression); }
public void PropertyPath_GetPropertyPath() { var viewModel = new SampleViewModel { Context = new TestDotvvmRequestContext { Configuration = DotvvmTestHelper.CreateConfiguration(), ModelState = new ModelState() } }; viewModel.Context.ModelState.ValidationTarget = viewModel; var error = viewModel.AddModelError(vm => vm.Users[0].Post.PostText, "Testing validation error."); Assert.AreEqual("Users()[0]().Post().PostText", error.PropertyPath); }
public void IntegrityCheck_ShouldSucceed() { //Arrange var configuration = DotvvmTestHelper.CreateConfiguration(); configuration.Resources.Register("jquery", new ScriptResource { Location = new UrlResourceLocation(_jqueryUri), VerifyResourceIntegrity = true, IntegrityHash = _integrityHash }); var jquery = configuration.Resources.FindResource("jquery") as ScriptResource; //Act string scriptTag = RenderResource(configuration, jquery); //Assert Assert.IsTrue(scriptTag.Contains("integrity")); Assert.IsTrue(scriptTag.Contains(_integrityHash)); }
public void RouteTable_Deserialization() { var config1 = DotvvmTestHelper.CreateConfiguration(); config1.RouteTable.Add("route1", "url1", "file1.dothtml", new { a = "ccc" }); config1.RouteTable.Add("route2", "url2/{int:posint}", "file1.dothtml", new { a = "ccc" }); // Add unknwon constraint, simulate user defined constraint that is not known to the VS Extension var r = new DotvvmRoute("url3", "file1.dothtml", new { }, () => null, config1); typeof(RouteBase).GetProperty("Url").SetMethod.Invoke(r, new[] { "url3/{a:unsuppotedConstraint}" }); config1.RouteTable.Add("route3", r); var settings = new JsonSerializerSettings { TypeNameHandling = TypeNameHandling.Auto }; var config2 = JsonConvert.DeserializeObject<DotvvmConfiguration>(JsonConvert.SerializeObject(config1, settings), settings); Assert.AreEqual(config2.RouteTable["route1"].Url, "url1"); Assert.AreEqual(config2.RouteTable["route2"].Url, "url2/{int:posint}"); Assert.AreEqual(config2.RouteTable["route3"].Url, "url3/{a:unsuppotedConstraint}"); }
public string CompileBinding(string expression, Type[] contexts, Type expectedType) { var context = DataContextStack.Create(contexts.FirstOrDefault() ?? typeof(object), extensionParameters: new BindingExtensionParameter[] { new BindingPageInfoExtensionParameter() }); for (int i = 1; i < contexts.Length; i++) { context = DataContextStack.Create(contexts[i], context); } var parser = new BindingExpressionBuilder(); var expressionTree = TypeConversion.ImplicitConversion(parser.Parse(expression, context, BindingParserOptions.Create <ValueBindingExpression>()), expectedType, true, true); var configuration = DotvvmTestHelper.CreateConfiguration(); var jsExpression = new JsParenthesizedExpression(configuration.ServiceLocator.GetService <JavascriptTranslator>().CompileToJavascript(expressionTree, context)); jsExpression.AcceptVisitor(new KnockoutObservableHandlingVisitor(true)); JsTemporaryVariableResolver.ResolveVariables(jsExpression); return(JavascriptTranslator.FormatKnockoutScript(jsExpression.Expression)); }
public void MustEncodeUrls(string forbiddenString) { var resources = new IResource [] { new ScriptResource(new UrlResourceLocation("http://server.com/" + forbiddenString + "somethingelse")), new StylesheetResource(new UrlResourceLocation("file:///" + forbiddenString)) { LocationFallback = new ResourceLocationFallback("true", new UrlResourceLocation(forbiddenString), new UrlResourceLocation("http://" + forbiddenString)) } }; var cx = DotvvmTestHelper.CreateContext(DotvvmTestHelper.DefaultConfig); var output = new StringWriter(); var w = new HtmlWriter(output, cx); foreach (var a in resources) { a.Render(w, cx, forbiddenString); } Assert.IsFalse(output.ToString().Contains(forbiddenString)); }
public void PropertyPath_GetPropertyPath() { var viewModel = new SampleViewModel { Context = new TestDotvvmRequestContext { Configuration = DotvvmTestHelper.CreateConfiguration(), ModelState = new ModelState() } }; var error = new ViewModelValidationError { ErrorMessage = "Testing validation error.", PropertyPath = PropertyPath.BuildPath <SampleViewModel>(vm => vm.Users[0].Post.PostText, viewModel.Context.Configuration) }; viewModel.Context.ModelState.Errors.Add(error); Assert.AreEqual("Users()[0].Post().PostText", error.PropertyPath); }
public void INIT() { this.configuration = DotvvmTestHelper.CreateConfiguration(); configuration.RegisterApiClient(typeof(TestApiClient), "http://server/api", "./apiscript.js", "_testApi"); this.bindingService = configuration.ServiceProvider.GetRequiredService <BindingCompilationService>(); }
private IViewModelValidator CreateValidator() => DotvvmTestHelper.CreateConfiguration().ServiceLocator.GetService <IViewModelValidator>();
public ConfigurationSerializationTests() { DotvvmTestHelper.EnsureCompiledAssemblyCache(); }
public void INIT() { this.configuration = DotvvmTestHelper.CreateConfiguration(); this.bindingService = configuration.ServiceProvider.GetRequiredService <BindingCompilationService>(); }