diff --git a/spark.build b/spark.build index e9f6067c..f7535431 100644 --- a/spark.build +++ b/spark.build @@ -110,6 +110,7 @@ + diff --git a/src/Castle.MonoRail.Views.Spark/Castle.MonoRail.Views.Spark.csproj b/src/Castle.MonoRail.Views.Spark/Castle.MonoRail.Views.Spark.csproj index f346ef9b..5223b53f 100644 --- a/src/Castle.MonoRail.Views.Spark/Castle.MonoRail.Views.Spark.csproj +++ b/src/Castle.MonoRail.Views.Spark/Castle.MonoRail.Views.Spark.csproj @@ -42,7 +42,7 @@ - + diff --git a/src/Spark.JsTests/Spark.JsTests.csproj b/src/Spark.JsTests/Spark.JsTests.csproj index 5594a10a..91f5e9b7 100644 --- a/src/Spark.JsTests/Spark.JsTests.csproj +++ b/src/Spark.JsTests/Spark.JsTests.csproj @@ -13,7 +13,7 @@ - + diff --git a/src/Spark.Python.Tests/Spark.Python.Tests.csproj b/src/Spark.Python.Tests/Spark.Python.Tests.csproj index cf649785..79d3becd 100644 --- a/src/Spark.Python.Tests/Spark.Python.Tests.csproj +++ b/src/Spark.Python.Tests/Spark.Python.Tests.csproj @@ -24,6 +24,6 @@ - + \ No newline at end of file diff --git a/src/Spark.Ruby.Tests/Spark.Ruby.Tests.csproj b/src/Spark.Ruby.Tests/Spark.Ruby.Tests.csproj index 9bfbec95..c4aad4ee 100644 --- a/src/Spark.Ruby.Tests/Spark.Ruby.Tests.csproj +++ b/src/Spark.Ruby.Tests/Spark.Ruby.Tests.csproj @@ -28,6 +28,6 @@ - + \ No newline at end of file diff --git a/src/Spark.Web.Mvc/Spark.Web.Mvc.csproj b/src/Spark.Web.Mvc/Spark.Web.Mvc.csproj index 532d6a97..b135270a 100644 --- a/src/Spark.Web.Mvc/Spark.Web.Mvc.csproj +++ b/src/Spark.Web.Mvc/Spark.Web.Mvc.csproj @@ -34,7 +34,7 @@ - + diff --git a/src/Spark.Tests/App.config b/src/Spark.Web.Tests/App.config similarity index 90% rename from src/Spark.Tests/App.config rename to src/Spark.Web.Tests/App.config index 56a1d2c7..e035c404 100644 --- a/src/Spark.Tests/App.config +++ b/src/Spark.Web.Tests/App.config @@ -1,33 +1,33 @@ - - - -
- - - - - - - - - - - - - - - - - - - - - - - - + + + +
+ + + + + + + + + + + + + + + + + + + + + + + + diff --git a/src/Spark.Tests/BatchCompilationTester.cs b/src/Spark.Web.Tests/BatchCompilationTester.cs similarity index 96% rename from src/Spark.Tests/BatchCompilationTester.cs rename to src/Spark.Web.Tests/BatchCompilationTester.cs index 6ab53cbf..5727a324 100644 --- a/src/Spark.Tests/BatchCompilationTester.cs +++ b/src/Spark.Web.Tests/BatchCompilationTester.cs @@ -1,151 +1,150 @@ -// Copyright 2008-2009 Louis DeJardin - http://whereslou.com -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// -using System; -using System.Collections.Generic; -using System.Linq; -using System.Reflection; -using System.Reflection.Emit; -using NUnit.Framework; -using Spark.Compiler; -using Spark.FileSystem; -using Spark.Tests.Precompiled; -using System.IO; - -namespace Spark.Tests -{ - [TestFixture] - public class BatchCompilationTester - { - private ISparkViewEngine engine; - - [SetUp] - public void Init() - { - var settings = new SparkSettings() - .SetPageBaseType(typeof(Stubs.StubSparkView)); - - engine = new SparkViewEngine(settings) - { - ViewFolder = new InMemoryViewFolder - { - {Path.Combine("Home","Index.spark"), "

Hello world

"}, - {Path.Combine("Home","List.spark"), "
  1. one
  2. two
"} - } - }; - } - - [Test] - public void CompileMultipleDescriptors() - { - var descriptors = new[] - { - new SparkViewDescriptor().AddTemplate(Path.Combine("Home","Index.spark")), - new SparkViewDescriptor().AddTemplate(Path.Combine("Home","List.spark")) - }; - - var assembly = engine.BatchCompilation(descriptors); - - var types = assembly.GetTypes(); - Assert.AreEqual(2, types.Count()); - - var entry0 = engine.GetEntry(descriptors[0]); - var view0 = entry0.CreateInstance(); - var result0 = view0.RenderView(); - Assert.AreEqual("

Hello world

", result0); - - var entry1 = engine.GetEntry(descriptors[1]); - var view1 = entry1.CreateInstance(); - var result1 = view1.RenderView(); - Assert.AreEqual("
  1. one
  2. two
", result1); - - Assert.AreSame(view0.GetType().Assembly, view1.GetType().Assembly); - } - - [Test] - public void DescriptorsAreEqual() - { - var descriptor = new SparkViewDescriptor() - .SetTargetNamespace("Foo") - .AddTemplate(Path.Combine("Home","Index.spark")); - - var assembly = engine.BatchCompilation(new[] { descriptor }); - - var types = assembly.GetTypes(); - Assert.AreEqual(1, types.Count()); - - var attribs = types[0].GetCustomAttributes(typeof(SparkViewAttribute), false); - var sparkViewAttrib = (SparkViewAttribute)attribs[0]; - - var key0 = descriptor; - var key1 = sparkViewAttrib.BuildDescriptor(); - - Assert.AreEqual(key0, key1); - } - - [Test] - public void DescriptorsWithNoTargetNamespace() - { - var descriptor = new SparkViewDescriptor().AddTemplate(Path.Combine("Home","Index.spark")); - - var assembly = engine.BatchCompilation(new[] { descriptor }); - - var types = assembly.GetTypes(); - Assert.AreEqual(1, types.Count()); - - var attribs = types[0].GetCustomAttributes(typeof(SparkViewAttribute), false); - var sparkViewAttrib = (SparkViewAttribute)attribs[0]; - - var key0 = descriptor; - var key1 = sparkViewAttrib.BuildDescriptor(); - - Assert.AreEqual(key0, key1); - } - - [Test] - public void LoadCompiledViews() - { - var descriptors = engine.LoadBatchCompilation(GetType().Assembly); - Assert.AreEqual(2, descriptors.Count); - - var view1 = engine.CreateInstance(new SparkViewDescriptor() - .SetTargetNamespace("Spark.Tests.Precompiled") - .AddTemplate(Path.Combine("Foo","Bar.spark")) - .AddTemplate(Path.Combine("Shared","Quux.spark"))); - Assert.AreEqual(typeof(View1), view1.GetType()); - - var view2 = engine.CreateInstance(new SparkViewDescriptor() - .SetTargetNamespace("Spark.Tests.Precompiled") - .AddTemplate(Path.Combine("Hello","World.spark")) - .AddTemplate(Path.Combine("Shared","Default.spark"))); - Assert.AreEqual(typeof(View2), view2.GetType()); - } - - [Test] - public void AvoidNotSupportedExceptionForDynamicAssemblies() - { - var assemblyName = new AssemblyName - { - Name = "DynamicAssembly", - }; - var assemblyBuilder = AppDomain.CurrentDomain.DefineDynamicAssembly(assemblyName, AssemblyBuilderAccess.RunAndSave); - var moduleBuilder = assemblyBuilder.DefineDynamicModule("DynamicModule", "DynamicAssembly.dll"); - var type = moduleBuilder.DefineType("DynamicType", TypeAttributes.Public).CreateType(); - assemblyBuilder.Save("DynamicAssembly.dll"); - Assert.IsTrue(type.Assembly.IsDynamic()); - } - - - } -} +// Copyright 2008-2009 Louis DeJardin - http://whereslou.com +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +using System; +using System.Linq; +using System.Reflection; +using System.Reflection.Emit; +using NUnit.Framework; +using Spark.Compiler; +using Spark.FileSystem; +using Spark.Tests.Precompiled; +using System.IO; + +namespace Spark.Tests +{ + [TestFixture] + public class BatchCompilationTester + { + private ISparkViewEngine engine; + + [SetUp] + public void Init() + { + var settings = new SparkSettings() + .SetPageBaseType(typeof(Stubs.StubSparkView)); + + engine = new SparkViewEngine(settings) + { + ViewFolder = new InMemoryViewFolder + { + {Path.Combine("Home","Index.spark"), "

Hello world

"}, + {Path.Combine("Home","List.spark"), "
  1. one
  2. two
"} + } + }; + } + + [Test] + public void CompileMultipleDescriptors() + { + var descriptors = new[] + { + new SparkViewDescriptor().AddTemplate(Path.Combine("Home","Index.spark")), + new SparkViewDescriptor().AddTemplate(Path.Combine("Home","List.spark")) + }; + + var assembly = engine.BatchCompilation(descriptors); + + var types = assembly.GetTypes(); + Assert.AreEqual(2, types.Count()); + + var entry0 = engine.GetEntry(descriptors[0]); + var view0 = entry0.CreateInstance(); + var result0 = view0.RenderView(); + Assert.AreEqual("

Hello world

", result0); + + var entry1 = engine.GetEntry(descriptors[1]); + var view1 = entry1.CreateInstance(); + var result1 = view1.RenderView(); + Assert.AreEqual("
  1. one
  2. two
", result1); + + Assert.AreSame(view0.GetType().Assembly, view1.GetType().Assembly); + } + + [Test] + public void DescriptorsAreEqual() + { + var descriptor = new SparkViewDescriptor() + .SetTargetNamespace("Foo") + .AddTemplate(Path.Combine("Home","Index.spark")); + + var assembly = engine.BatchCompilation(new[] { descriptor }); + + var types = assembly.GetTypes(); + Assert.AreEqual(1, types.Count()); + + var attribs = types[0].GetCustomAttributes(typeof(SparkViewAttribute), false); + var sparkViewAttrib = (SparkViewAttribute)attribs[0]; + + var key0 = descriptor; + var key1 = sparkViewAttrib.BuildDescriptor(); + + Assert.AreEqual(key0, key1); + } + + [Test] + public void DescriptorsWithNoTargetNamespace() + { + var descriptor = new SparkViewDescriptor().AddTemplate(Path.Combine("Home","Index.spark")); + + var assembly = engine.BatchCompilation(new[] { descriptor }); + + var types = assembly.GetTypes(); + Assert.AreEqual(1, types.Count()); + + var attribs = types[0].GetCustomAttributes(typeof(SparkViewAttribute), false); + var sparkViewAttrib = (SparkViewAttribute)attribs[0]; + + var key0 = descriptor; + var key1 = sparkViewAttrib.BuildDescriptor(); + + Assert.AreEqual(key0, key1); + } + + [Test] + public void LoadCompiledViews() + { + var descriptors = engine.LoadBatchCompilation(GetType().Assembly); + Assert.AreEqual(2, descriptors.Count); + + var view1 = engine.CreateInstance(new SparkViewDescriptor() + .SetTargetNamespace("Spark.Tests.Precompiled") + .AddTemplate(Path.Combine("Foo","Bar.spark")) + .AddTemplate(Path.Combine("Shared","Quux.spark"))); + Assert.AreEqual(typeof(View1), view1.GetType()); + + var view2 = engine.CreateInstance(new SparkViewDescriptor() + .SetTargetNamespace("Spark.Tests.Precompiled") + .AddTemplate(Path.Combine("Hello","World.spark")) + .AddTemplate(Path.Combine("Shared","Default.spark"))); + Assert.AreEqual(typeof(View2), view2.GetType()); + } + + [Test] + public void AvoidNotSupportedExceptionForDynamicAssemblies() + { + var assemblyName = new AssemblyName + { + Name = "DynamicAssembly", + }; + var assemblyBuilder = AppDomain.CurrentDomain.DefineDynamicAssembly(assemblyName, AssemblyBuilderAccess.RunAndSave); + var moduleBuilder = assemblyBuilder.DefineDynamicModule("DynamicModule", "DynamicAssembly.dll"); + var type = moduleBuilder.DefineType("DynamicType", TypeAttributes.Public).CreateType(); + assemblyBuilder.Save("DynamicAssembly.dll"); + Assert.IsTrue(type.Assembly.IsDynamic()); + } + + + } +} diff --git a/src/Spark.Tests/Bindings/BindingExecutionTester.cs b/src/Spark.Web.Tests/Bindings/BindingExecutionTester.cs similarity index 97% rename from src/Spark.Tests/Bindings/BindingExecutionTester.cs rename to src/Spark.Web.Tests/Bindings/BindingExecutionTester.cs index cbced035..e3b16307 100644 --- a/src/Spark.Tests/Bindings/BindingExecutionTester.cs +++ b/src/Spark.Web.Tests/Bindings/BindingExecutionTester.cs @@ -1,393 +1,391 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using NUnit.Framework; - -using Spark.FileSystem; -using Spark.Tests.Stubs; -using System.IO; - -namespace Spark.Tests.Bindings -{ - [TestFixture] - public class BindingExecutionTester - { - - private InMemoryViewFolder _viewFolder; - private StubViewFactory _factory; - - [SetUp] - public void Init() - { - _viewFolder = new InMemoryViewFolder(); - - _factory = new StubViewFactory - { - Engine = new SparkViewEngine( - new SparkSettings() - .SetPageBaseType(typeof(StubSparkView))) - { - ViewFolder = _viewFolder - } - }; - } - - private string Render(string viewName) - { - return Render(viewName, new StubViewData()); - } - - private string Render(string viewName, StubViewData viewData) - { - var context = new StubViewContext { ControllerName = "home", ViewName = viewName, Output = new StringBuilder(), Data = viewData }; - _factory.RenderView(context); - return context.Output.ToString() - .Replace("\r\n\r\n", "\r\n") - .Replace("\r\n\r\n", "\r\n"); - } - - [Test] - public void ElementReplacedWithSimpleString() - { - _viewFolder.Add("bindings.xml", @"""world"""); - _viewFolder.Add(Path.Combine("home", "index.spark"), @"

"); - - var contents = Render("index"); - Assert.That(contents, Is.EqualTo(@"

world

")); - } - - - [Test] - public void ElementReplacedWithMacroCall() - { - _viewFolder.Add("bindings.xml", @"World()"); - _viewFolder.Add(Path.Combine("home", "index.spark"), @"

success"); - - var contents = Render("index"); - Assert.That(contents, Is.EqualTo(@"

success

")); - } - - [Test] - public void ElementReplacedWithMacroCallAndAnArgument() - { - _viewFolder.Add("bindings.xml", @"World('@foo')"); - _viewFolder.Add(Path.Combine("home", "index.spark"), @"

success ${beta}!"); - - var contents = Render("index"); - Assert.That(contents, Is.EqualTo(@"

success alpha!

")); - } - - [Test] - public void BindingRefersToAttributeWithCode() - { - _viewFolder.Add("bindings.xml", @"World('@foo')"); - _viewFolder.Add(Path.Combine("home", "index.spark"), @"

success ${beta}!"); - - var contents = Render("index"); - Assert.That(contents, Is.EqualTo(@"

success 7!

")); - } - - - [Test] - public void BindingRefersToAttributeWithMixedCodeAndText() - { - _viewFolder.Add("bindings.xml", @"World('@foo')"); - _viewFolder.Add(Path.Combine("home", "index.spark"), @"

success ${beta}!"); - - var contents = Render("index"); - Assert.That(contents, Is.EqualTo(@"

success one 7 two /TestApp three!

")); - } - - [Test] - public void BindingRefersToAttributeWithMixedCodeAndTextWithOptional() - { - _viewFolder.Add("bindings.xml", @"World('@@foo')"); - _viewFolder.Add(Path.Combine("home", "index.spark"), @"

success ${beta}!"); - - var contents = Render("index"); - Assert.That(contents, Is.EqualTo(@"

success one 7 two /TestApp three!

")); - } - - [Test] - public void BindingRefersToAttributeWithMixedCodeAndTextWithOptionalNotSupplied() - { - _viewFolder.Add("bindings.xml", @"World('@@foo')"); - _viewFolder.Add(Path.Combine("home", "index.spark"), @"

success ${beta}!"); - - var contents = Render("index"); - Assert.That(contents, Is.EqualTo(@"

success !

")); - } - - [Test] - public void BindingRefersToAttributeWithMixedCodeAndTextWithAttributeNotSupplied() - { - _viewFolder.Add("bindings.xml", @"World('@foo')"); - _viewFolder.Add(Path.Combine("home", "index.spark"), @"

success ${beta}!"); - - var contents = Render("index"); - Assert.That(contents, Is.EqualTo(@"

")); - } - - [Test] - public void BindingRefersToAttributeWithUnescapedCode() { - _viewFolder.Add("bindings.xml", @"World(@foo)"); - _viewFolder.Add(Path.Combine("home", "index.spark"), @"

success ${beta}!"); - - var contents = Render("index"); - Assert.That(contents, Is.EqualTo(@"

success one 7 two /TestApp three!

")); - } - - [Test] - public void CorrectBindingUsedBasedOnAttributesPresent() - { - _viewFolder.Add("bindings.xml", @" -""foo is "" + '@foo' + ""!"" -""bar is "" + '@bar' + ""!"" -"); - _viewFolder.Add(Path.Combine("home", "index.spark"), @"

,

"); - - var contents = Render("index"); - Assert.That(contents, Is.EqualTo(@"

foo is one!, bar is two!

")); - } - - [Test] - public void WildcardBindAsObjectInitializer() - { - _viewFolder.Add("bindings.xml", @" -Callback(new{'@*'}) -"); - _viewFolder.Add(Path.Combine("home", "index.spark"), @"

, ,

"); - - Func cb = x => x.ToString(); - var contents = Render("index", new StubViewData { { "Callback", cb } }); - - // default to anon object's ToString() style - Assert.That(contents, Is.EqualTo(@"

{ foo = one }, { bar = two }, { foo = -/TestApp-, bar = four }

")); - } - - [Test] - public void NamedReferencesAreNotUsedByWildcardReferences() - { - _viewFolder.Add("bindings.xml", @" -Callback('@foo', new{'@*'}) -Callback(""nada"", new{'@*'}) -"); - - _viewFolder.Add(Path.Combine("home", "index.spark"), @"

, ,

"); - - Func cb = (a, x) => '[' + a + ']' + x.ToString(); - var contents = Render("index", new StubViewData { { "Callback", cb } }); - - // default to anon object's ToString() style - Assert.That(contents, Is.EqualTo(@"

[one]{ }, [nada]{ bar = two }, [-/TestApp-]{ bar = four }

")); - } - - [Test] - public void WildcardReferencesWillNotUseElementsMatchedByLongerPrefix() - { - _viewFolder.Add("bindings.xml", @" -Callback('@foo', new{'@*'}, new{'@route.*'}) -"); - - _viewFolder.Add(Path.Combine("home", "index.spark"), @"

, ,

"); - - Func cb = (a, x, y) => '[' + a + ']' + x.ToString() + y.ToString(); - var contents = Render("index", new StubViewData { { "Callback", cb } }); - - // default to anon object's ToString() style - Assert.That(contents, Is.EqualTo(@"

[one]{ }{ }, [one]{ bar = two }{ }, [one]{ bar = 2 }{ id = three }

")); - } - - [Test] - public void StatementPhraseWillBeExecutedInsteadOfOutput() - { - _viewFolder.Add("bindings.xml", @" -#Output.Write(4+5); -"); - - _viewFolder.Add(Path.Combine("home", "index.spark"), @"

"); - var contents = Render("index"); - Assert.That(contents, Is.EqualTo(@"

9

")); - } - - [Test] - public void TwoPhraseBindingMayWrapOtherMaterial() - { - _viewFolder.Add("bindings.xml", @" -@a@b -"); - - _viewFolder.Add(Path.Combine("home", "index.spark"), @"

world

"); - var contents = Render("index"); - Assert.That(contents, Is.EqualTo(@"

3world5

")); - } - - [Test] - public void ChildReferenceWillSpoolAndProvideContentAsString() - { - _viewFolder.Add("bindings.xml", @" -'@a' + 'child::*' + '@b' -"); - - _viewFolder.Add(Path.Combine("home", "index.spark"), @"

world

"); - var contents = Render("index"); - Assert.That(contents, Is.EqualTo(@"

3world5

")); - } - - [Test, Ignore("The child::* is always treated as text. So this test does not represent the current capabilities.")] - public void ChildReferenceWillSpoolAndProvideContentAsCode() { - _viewFolder.Add("bindings.xml", @" -'@a' + child::* + '@b' -"); - - _viewFolder.Add(Path.Combine("home", "index.spark"), @"

(8+7)+""4""${55}

"); - var contents = Render("index"); - Assert.That(contents, Is.EqualTo(@"

31545

")); - } - - [Test] - public void ChildReferenceWillNotMatchSelfClosingElements() - { - _viewFolder.Add("bindings.xml", @" -'@a' + 'child::*' + '@b' -'@a' + ""no text"" + '@b' -"); - - _viewFolder.Add(Path.Combine("home", "index.spark"), @"

world

"); - - var contents = Render("index"); - - Assert.That(contents, Is.EqualTo(@"

1world2345no text6

")); - } - - [Test] - public void CurleyBracesExpandAsDictionaryInitialization() - { - _viewFolder.Add("bindings.xml", @" -new System.Collections.Generic.Dictionary<string,object>{{'@*'}}.Count -"); - - _viewFolder.Add(Path.Combine("home", "index.spark"), @"

"); - - var contents = Render("index"); - - Assert.That(contents, Is.EqualTo(@"

2005

")); - } - - [Test] - public void ExpressionNextToBindingShouldMaintainWhiteSpace() - { - _viewFolder.Add("bindings.xml", @"child::*"); - _viewFolder.Add(Path.Combine("home","index.spark"), @"

${'1234'} Smith St

"); - - var contents = Render("index"); - Assert.That(contents, Is.EqualTo(@"

1234 Smith St

")); - } - - [Test] - public void ExpressionNextToBindingShouldMaintainWhiteSpaceWithLoops() - { - _viewFolder.Add("bindings.xml", @"child::*"); - _viewFolder.Add(Path.Combine("home","index.spark"), @" -
    - -
  • ${name} is okay too I suppose.
  • -
    -
"); - - var contents = Render("index"); - Assert.That(contents, Is.EqualTo(@" -
    -
  • alpha is okay too I suppose.
  • -
  • beta is okay too I suppose.
  • -
  • gamma is okay too I suppose.
  • -
")); - } - - [Test] - public void ExpressionNextToBindingShouldMaintainWhiteSpaceWithLoopsInternal() - { - _viewFolder.Add("bindings.xml", @"child::*"); - _viewFolder.Add(Path.Combine("home","index.spark"), @" -
    -
  • ${name} is okay too I suppose.
  • -
"); - - var contents = Render("index"); - Assert.That(contents, Is.EqualTo(@" -
    -
  • alpha is okay too I suppose.
  • -
  • beta is okay too I suppose.
  • -
  • gamma is okay too I suppose.
  • -
")); - } - - [Test] - public void BindingShouldMaintainNewLine() - { - _viewFolder.Add("bindings.xml", @"child::*"); - _viewFolder.Add(Path.Combine("home", "index.spark"), @" -

- John St -

"); - - var contents = Render("index"); - Assert.That(contents, Is.EqualTo(@" -

- John St -

")); - } - - [Test] - public void BindingNextToBindingShouldMaintainNewLine() - { - _viewFolder.Add("bindings.xml", @"child::*"); - _viewFolder.Add(Path.Combine("home", "index.spark"), @" -

- John St - Smith St -

"); - - var contents = Render("index"); - Assert.That(contents, Is.EqualTo(@" -

- John St - Smith St -

")); - } - - [Test] - public void BindingShouldMaintainNewLineWithNoChild() - { - _viewFolder.Add("bindings.xml", @"'@tt'"); - _viewFolder.Add(Path.Combine("home", "index.spark"), @" -

- -

"); - - var contents = Render("index"); - Assert.That(contents, Is.EqualTo(@" -

- John St -

")); - } - - [Test] - public void BindingShouldMaintainNewLineWithNoChildAndCode() - { - _viewFolder.Add("bindings.xml", @"'@tt'"); - _viewFolder.Add(Path.Combine("home", "index.spark"), @" -

- - -

"); - - var contents = Render("index"); - Assert.That(contents, Is.EqualTo(@" -

- 23 -

")); - } - } -} +using System; +using System.Text; +using NUnit.Framework; + +using Spark.FileSystem; +using Spark.Tests.Stubs; +using System.IO; + +namespace Spark.Tests.Bindings +{ + [TestFixture] + public class BindingExecutionTester + { + + private InMemoryViewFolder _viewFolder; + private StubViewFactory _factory; + + [SetUp] + public void Init() + { + _viewFolder = new InMemoryViewFolder(); + + _factory = new StubViewFactory + { + Engine = new SparkViewEngine( + new SparkSettings() + .SetPageBaseType(typeof(StubSparkView))) + { + ViewFolder = _viewFolder + } + }; + } + + private string Render(string viewName) + { + return Render(viewName, new StubViewData()); + } + + private string Render(string viewName, StubViewData viewData) + { + var context = new StubViewContext { ControllerName = "home", ViewName = viewName, Output = new StringBuilder(), Data = viewData }; + _factory.RenderView(context); + return context.Output.ToString() + .Replace("\r\n\r\n", "\r\n") + .Replace("\r\n\r\n", "\r\n"); + } + + [Test] + public void ElementReplacedWithSimpleString() + { + _viewFolder.Add("bindings.xml", @"""world"""); + _viewFolder.Add(Path.Combine("home", "index.spark"), @"

"); + + var contents = Render("index"); + Assert.That(contents, Is.EqualTo(@"

world

")); + } + + + [Test] + public void ElementReplacedWithMacroCall() + { + _viewFolder.Add("bindings.xml", @"World()"); + _viewFolder.Add(Path.Combine("home", "index.spark"), @"

success"); + + var contents = Render("index"); + Assert.That(contents, Is.EqualTo(@"

success

")); + } + + [Test] + public void ElementReplacedWithMacroCallAndAnArgument() + { + _viewFolder.Add("bindings.xml", @"World('@foo')"); + _viewFolder.Add(Path.Combine("home", "index.spark"), @"

success ${beta}!"); + + var contents = Render("index"); + Assert.That(contents, Is.EqualTo(@"

success alpha!

")); + } + + [Test] + public void BindingRefersToAttributeWithCode() + { + _viewFolder.Add("bindings.xml", @"World('@foo')"); + _viewFolder.Add(Path.Combine("home", "index.spark"), @"

success ${beta}!"); + + var contents = Render("index"); + Assert.That(contents, Is.EqualTo(@"

success 7!

")); + } + + + [Test] + public void BindingRefersToAttributeWithMixedCodeAndText() + { + _viewFolder.Add("bindings.xml", @"World('@foo')"); + _viewFolder.Add(Path.Combine("home", "index.spark"), @"

success ${beta}!"); + + var contents = Render("index"); + Assert.That(contents, Is.EqualTo(@"

success one 7 two /TestApp three!

")); + } + + [Test] + public void BindingRefersToAttributeWithMixedCodeAndTextWithOptional() + { + _viewFolder.Add("bindings.xml", @"World('@@foo')"); + _viewFolder.Add(Path.Combine("home", "index.spark"), @"

success ${beta}!"); + + var contents = Render("index"); + Assert.That(contents, Is.EqualTo(@"

success one 7 two /TestApp three!

")); + } + + [Test] + public void BindingRefersToAttributeWithMixedCodeAndTextWithOptionalNotSupplied() + { + _viewFolder.Add("bindings.xml", @"World('@@foo')"); + _viewFolder.Add(Path.Combine("home", "index.spark"), @"

success ${beta}!"); + + var contents = Render("index"); + Assert.That(contents, Is.EqualTo(@"

success !

")); + } + + [Test] + public void BindingRefersToAttributeWithMixedCodeAndTextWithAttributeNotSupplied() + { + _viewFolder.Add("bindings.xml", @"World('@foo')"); + _viewFolder.Add(Path.Combine("home", "index.spark"), @"

success ${beta}!"); + + var contents = Render("index"); + Assert.That(contents, Is.EqualTo(@"

")); + } + + [Test] + public void BindingRefersToAttributeWithUnescapedCode() { + _viewFolder.Add("bindings.xml", @"World(@foo)"); + _viewFolder.Add(Path.Combine("home", "index.spark"), @"

success ${beta}!"); + + var contents = Render("index"); + Assert.That(contents, Is.EqualTo(@"

success one 7 two /TestApp three!

")); + } + + [Test] + public void CorrectBindingUsedBasedOnAttributesPresent() + { + _viewFolder.Add("bindings.xml", @" +""foo is "" + '@foo' + ""!"" +""bar is "" + '@bar' + ""!"" +"); + _viewFolder.Add(Path.Combine("home", "index.spark"), @"

,

"); + + var contents = Render("index"); + Assert.That(contents, Is.EqualTo(@"

foo is one!, bar is two!

")); + } + + [Test] + public void WildcardBindAsObjectInitializer() + { + _viewFolder.Add("bindings.xml", @" +Callback(new{'@*'}) +"); + _viewFolder.Add(Path.Combine("home", "index.spark"), @"

, ,

"); + + Func cb = x => x.ToString(); + var contents = Render("index", new StubViewData { { "Callback", cb } }); + + // default to anon object's ToString() style + Assert.That(contents, Is.EqualTo(@"

{ foo = one }, { bar = two }, { foo = -/TestApp-, bar = four }

")); + } + + [Test] + public void NamedReferencesAreNotUsedByWildcardReferences() + { + _viewFolder.Add("bindings.xml", @" +Callback('@foo', new{'@*'}) +Callback(""nada"", new{'@*'}) +"); + + _viewFolder.Add(Path.Combine("home", "index.spark"), @"

, ,

"); + + Func cb = (a, x) => '[' + a + ']' + x.ToString(); + var contents = Render("index", new StubViewData { { "Callback", cb } }); + + // default to anon object's ToString() style + Assert.That(contents, Is.EqualTo(@"

[one]{ }, [nada]{ bar = two }, [-/TestApp-]{ bar = four }

")); + } + + [Test] + public void WildcardReferencesWillNotUseElementsMatchedByLongerPrefix() + { + _viewFolder.Add("bindings.xml", @" +Callback('@foo', new{'@*'}, new{'@route.*'}) +"); + + _viewFolder.Add(Path.Combine("home", "index.spark"), @"

, ,

"); + + Func cb = (a, x, y) => '[' + a + ']' + x.ToString() + y.ToString(); + var contents = Render("index", new StubViewData { { "Callback", cb } }); + + // default to anon object's ToString() style + Assert.That(contents, Is.EqualTo(@"

[one]{ }{ }, [one]{ bar = two }{ }, [one]{ bar = 2 }{ id = three }

")); + } + + [Test] + public void StatementPhraseWillBeExecutedInsteadOfOutput() + { + _viewFolder.Add("bindings.xml", @" +#Output.Write(4+5); +"); + + _viewFolder.Add(Path.Combine("home", "index.spark"), @"

"); + var contents = Render("index"); + Assert.That(contents, Is.EqualTo(@"

9

")); + } + + [Test] + public void TwoPhraseBindingMayWrapOtherMaterial() + { + _viewFolder.Add("bindings.xml", @" +@a@b +"); + + _viewFolder.Add(Path.Combine("home", "index.spark"), @"

world

"); + var contents = Render("index"); + Assert.That(contents, Is.EqualTo(@"

3world5

")); + } + + [Test] + public void ChildReferenceWillSpoolAndProvideContentAsString() + { + _viewFolder.Add("bindings.xml", @" +'@a' + 'child::*' + '@b' +"); + + _viewFolder.Add(Path.Combine("home", "index.spark"), @"

world

"); + var contents = Render("index"); + Assert.That(contents, Is.EqualTo(@"

3world5

")); + } + + [Test, Ignore("The child::* is always treated as text. So this test does not represent the current capabilities.")] + public void ChildReferenceWillSpoolAndProvideContentAsCode() { + _viewFolder.Add("bindings.xml", @" +'@a' + child::* + '@b' +"); + + _viewFolder.Add(Path.Combine("home", "index.spark"), @"

(8+7)+""4""${55}

"); + var contents = Render("index"); + Assert.That(contents, Is.EqualTo(@"

31545

")); + } + + [Test] + public void ChildReferenceWillNotMatchSelfClosingElements() + { + _viewFolder.Add("bindings.xml", @" +'@a' + 'child::*' + '@b' +'@a' + ""no text"" + '@b' +"); + + _viewFolder.Add(Path.Combine("home", "index.spark"), @"

world

"); + + var contents = Render("index"); + + Assert.That(contents, Is.EqualTo(@"

1world2345no text6

")); + } + + [Test] + public void CurleyBracesExpandAsDictionaryInitialization() + { + _viewFolder.Add("bindings.xml", @" +new System.Collections.Generic.Dictionary<string,object>{{'@*'}}.Count +"); + + _viewFolder.Add(Path.Combine("home", "index.spark"), @"

"); + + var contents = Render("index"); + + Assert.That(contents, Is.EqualTo(@"

2005

")); + } + + [Test] + public void ExpressionNextToBindingShouldMaintainWhiteSpace() + { + _viewFolder.Add("bindings.xml", @"child::*"); + _viewFolder.Add(Path.Combine("home","index.spark"), @"

${'1234'} Smith St

"); + + var contents = Render("index"); + Assert.That(contents, Is.EqualTo(@"

1234 Smith St

")); + } + + [Test] + public void ExpressionNextToBindingShouldMaintainWhiteSpaceWithLoops() + { + _viewFolder.Add("bindings.xml", @"child::*"); + _viewFolder.Add(Path.Combine("home","index.spark"), @" +
    + +
  • ${name} is okay too I suppose.
  • +
    +
"); + + var contents = Render("index"); + Assert.That(contents, Is.EqualTo(@" +
    +
  • alpha is okay too I suppose.
  • +
  • beta is okay too I suppose.
  • +
  • gamma is okay too I suppose.
  • +
")); + } + + [Test] + public void ExpressionNextToBindingShouldMaintainWhiteSpaceWithLoopsInternal() + { + _viewFolder.Add("bindings.xml", @"child::*"); + _viewFolder.Add(Path.Combine("home","index.spark"), @" +
    +
  • ${name} is okay too I suppose.
  • +
"); + + var contents = Render("index"); + Assert.That(contents, Is.EqualTo(@" +
    +
  • alpha is okay too I suppose.
  • +
  • beta is okay too I suppose.
  • +
  • gamma is okay too I suppose.
  • +
")); + } + + [Test] + public void BindingShouldMaintainNewLine() + { + _viewFolder.Add("bindings.xml", @"child::*"); + _viewFolder.Add(Path.Combine("home", "index.spark"), @" +

+ John St +

"); + + var contents = Render("index"); + Assert.That(contents, Is.EqualTo(@" +

+ John St +

")); + } + + [Test] + public void BindingNextToBindingShouldMaintainNewLine() + { + _viewFolder.Add("bindings.xml", @"child::*"); + _viewFolder.Add(Path.Combine("home", "index.spark"), @" +

+ John St + Smith St +

"); + + var contents = Render("index"); + Assert.That(contents, Is.EqualTo(@" +

+ John St + Smith St +

")); + } + + [Test] + public void BindingShouldMaintainNewLineWithNoChild() + { + _viewFolder.Add("bindings.xml", @"'@tt'"); + _viewFolder.Add(Path.Combine("home", "index.spark"), @" +

+ +

"); + + var contents = Render("index"); + Assert.That(contents, Is.EqualTo(@" +

+ John St +

")); + } + + [Test] + public void BindingShouldMaintainNewLineWithNoChildAndCode() + { + _viewFolder.Add("bindings.xml", @"'@tt'"); + _viewFolder.Add(Path.Combine("home", "index.spark"), @" +

+ + +

"); + + var contents = Render("index"); + Assert.That(contents, Is.EqualTo(@" +

+ 23 +

")); + } + } +} diff --git a/src/Spark.Tests/Caching/CacheElementTester.cs b/src/Spark.Web.Tests/Caching/CacheElementTester.cs similarity index 96% rename from src/Spark.Tests/Caching/CacheElementTester.cs rename to src/Spark.Web.Tests/Caching/CacheElementTester.cs index 529b67c1..1a89b919 100644 --- a/src/Spark.Tests/Caching/CacheElementTester.cs +++ b/src/Spark.Web.Tests/Caching/CacheElementTester.cs @@ -1,557 +1,556 @@ -//------------------------------------------------------------------------- -// -// Copyright 2008-2010 Louis DeJardin - http://whereslou.com -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// -// Louis DeJardin -// Jacob Proffitt -// John Gietzen -//------------------------------------------------------------------------- - - -namespace Spark.Tests.Caching -{ - using System; - using System.Collections.Generic; - using System.Linq; - using System.Text; - using NUnit.Framework; - - using Spark.FileSystem; - using Spark.Tests.Stubs; - using System.IO; - - [TestFixture] - public class CacheElementTester - { - - private InMemoryViewFolder _viewFolder; - private StubViewFactory _factory; - private StubCacheService _cacheService; - - [SetUp] - public void Init() - { - _viewFolder = new InMemoryViewFolder(); - _cacheService = new StubCacheService(); - _factory = new StubViewFactory - { - Engine = new SparkViewEngine( - new SparkSettings() - .SetPageBaseType(typeof(StubSparkView))) - { - ViewFolder = _viewFolder - }, - CacheService = _cacheService - }; - } - - private string Render(string viewName) - { - return Render(viewName, new StubViewData()); - } - - private string Render(string viewName, StubViewData viewData) - { - var context = new StubViewContext { ControllerName = "home", ViewName = viewName, Output = new StringBuilder(), Data = viewData }; - _factory.RenderView(context); - return context.Output.ToString() - .Replace("\r\n\r\n", "\r\n") - .Replace("\r\n\r\n", "\r\n"); - } - - [Test] - public void TemplateRunsNormallyThroughCacheMiss() - { - _viewFolder.Add(Path.Combine("home", "index.spark"), @" -""/> -
- -

${ViewData.Model()}

-
-
"); - var calls = 0; - var contents = Render("index", new StubViewData> - { - Model = () => (++calls).ToString() - }); - Assert.That(contents, Is.EqualTo(@" -
-

1

-
")); - Assert.That(calls, Is.EqualTo(1)); - } - - [Test] - public void TemplateDoesNotRunThroughCacheHit() - { - _viewFolder.Add(Path.Combine("home", "index.spark"), @" -""/> -
- -

${ViewData.Model()}

-
-
"); - int calls = 0; - var data = new StubViewData> - { - Model = () => (++calls).ToString() - }; - - var contents = Render("index", data); - Assert.That(contents, Is.EqualTo(@" -
-

1

-
")); - Assert.That(calls, Is.EqualTo(1)); - - contents = Render("index", data); - Assert.That(contents, Is.EqualTo(@" -
-

1

-
")); - Assert.That(calls, Is.EqualTo(1)); - - } - - [Test] - public void CacheInMacroShouldActAsSameSite() - { - _viewFolder.Add(Path.Combine("home", "index.spark"), @" -""/> - -

${ViewData.Model()}

-
-
-${foo()} -${foo()} -
"); - - int calls = 0; - var data = new StubViewData> - { - Model = () => (++calls).ToString() - }; - - var contents = Render("index", data); - Assert.That(contents, Tests.Contains.InOrder( - "

1

", - "

1

")); - - Assert.That(calls, Is.EqualTo(1)); - - contents = Render("index", data); - Assert.That(contents, Tests.Contains.InOrder( - "

1

", - "

1

")); - - Assert.That(calls, Is.EqualTo(1)); - } - - [Test] - public void MultipleCachesShouldActAsDifferentSite() - { - _viewFolder.Add(Path.Combine("home", "index.spark"), @" -""/> -
- -

${ViewData.Model()}

-
- -

${ViewData.Model()}

-
-
"); - - var calls = 0; - var data = new StubViewData> - { - Model = () => (++calls).ToString() - }; - - var contents = Render("index", data); - Assert.That(contents, Is.EqualTo(@" -
-

1

-

2

-
")); - Assert.That(calls, Is.EqualTo(2)); - - - contents = Render("index", data); - Assert.That(contents, Is.EqualTo(@" -
-

1

-

2

-
")); - Assert.That(calls, Is.EqualTo(2)); - } - - [Test] - public void NamedContentShouldIndividuallySpoolAndCache() - { - _viewFolder.Add(Path.Combine("home", "index.spark"), @" -""/> -
- -

f${ViewData.Model()}[1]

-
-cache - -

${ViewData.Model()}[2]c

- -

f${ViewData.Model()}[3]c

-
- -

b${ViewData.Model()}[4]c

-
-

${ViewData.Model()}[5]c

-
- -

b${ViewData.Model()}[6]

-
-placed -

${ViewData.Model()}[7]

- - -

${ViewData.Model()}[8]

-
"); - - var calls = 0; - var data = new StubViewData> - { - Model = () => (++calls).ToString() - }; - - var contents = Render("index", data); - Assert.That(calls, Is.EqualTo(8)); - Assert.That(contents, Is.EqualTo(@" -
-cache -

2[2]c

-

5[5]c

-placed -

7[7]

-

f1[1]

-

f3[3]c

-

b4[4]c

-

b6[6]

-

8[8]

-
")); - - - contents = Render("index", data); - Assert.That(calls, Is.EqualTo(12)); - Assert.That(contents, Is.EqualTo(@" -
-cache -

2[2]c

-

5[5]c

-placed -

11[7]

-

f9[1]

-

f3[3]c

-

b4[4]c

-

b10[6]

-

12[8]

-
")); - } - - - [Test] - public void OutputWhileNamedContentActiveShouldAppearOnceAtCorrectTarget() - { - - _viewFolder.Add(Path.Combine("home", "index.spark"), @" -""/> -
    - -
  • ${ViewData.Model()}[1]
  • -
    -
  • ${ViewData.Model()}[2]
  • - - -
  • ${ViewData.Model()}[3]c
  • - -hana - -
  • ${ViewData.Model()}[4]c
  • -
    -
    -
  • ${ViewData.Model()}[5]
  • - -
  • ${ViewData.Model()}[6]
  • -
    - -
"); - - var calls = 0; - var data = new StubViewData> - { - Model = () => (++calls).ToString() - }; - - var contents = Render("index", data); - Assert.That(calls, Is.EqualTo(6)); - Assert.That(contents, Is.EqualTo(@" -
    -
  • 2[2]
  • -
  • 5[5]
  • -
  • 1[1]
  • -
  • 3[3]c
  • -hana -
  • 4[4]c
  • -
  • 6[6]
  • -
")); - - - contents = Render("index", data); - Assert.That(calls, Is.EqualTo(10)); - Assert.That(contents, Is.EqualTo(@" -
    -
  • 8[2]
  • -
  • 9[5]
  • -
  • 7[1]
  • -
  • 3[3]c
  • -hana -
  • 4[4]c
  • -
  • 10[6]
  • -
")); - } - - - [Test] - public void OnceFlagsSetWhenCacheRecordedShouldBeSetWhenCacheReplayed() - { - _viewFolder.Add(Path.Combine("home", "index.spark"), @" -""/> -
    -
  • ${ViewData.Model()}[1]
  • - -
  • ${ViewData.Model()}[2]
  • -
  • ${ViewData.Model()}[3]
  • -
    -
  • ${ViewData.Model()}[4]
  • -
  • ${ViewData.Model()}[5]
  • -
  • ${ViewData.Model()}[6]
  • -
  • ${ViewData.Model()}[7]
  • -
"); - - var calls = 0; - var data = new StubViewData> - { - Model = () => (++calls).ToString() - }; - - var contents = Render("index", data); - Assert.That(calls, Is.EqualTo(3)); - Assert.That(contents, Is.EqualTo(@" -
    -
  • 1[1]
  • -
  • 2[2]
  • -
  • 3[4]
  • -
")); - - contents = Render("index", data); - Assert.That(calls, Is.EqualTo(5)); - Assert.That(contents, Is.EqualTo(@" -
    -
  • 4[1]
  • -
  • 2[2]
  • -
  • 5[4]
  • -
")); - } - - [Test] - public void CacheFinallyShouldNotThrowExceptionWhenKeyIsBad() - { - _viewFolder.Add(Path.Combine("home", "index.spark"), @" - -#throw new System.ApplicationException(); - - -foo - -"); - Assert.That(() => Render("index", new StubViewData()), Throws.TypeOf()); - } - - [Test] - public void CacheAttributeUsedAsKey() - { - _viewFolder.Add(Path.Combine("home", "index.spark"), @" - - -

${x}:${++count}

-
"); - - var contents = Render("index"); - Assert.That(contents, Tests.Contains.InOrder( - "

1:1

", - "

3:2

", - "

5:3

", - "

2:4

", - "

3:2

", - "

3:2

", - "

5:3

", - "

7:5

")); - } - - [Test] - public void CacheExpiresTakesOutContentAfterTime() - { - _viewFolder.Add(Path.Combine("home", "index.spark"), @" -""/> - - -

${x}:${ViewData.Model()}

-
-
-

last:${ViewData.Model()}

-"); - - var calls = 0; - var data = new StubViewData> - { - Model = () => (++calls).ToString() - }; - - var contents = Render("index", data); - Assert.That(contents, Tests.Contains.InOrder( - "

1:1

", - "

2:2

", - "

3:3

", - "

1:1

", - "

2:2

", - "

3:3

", - "

last:4

")); - - _cacheService.UtcNow = _cacheService.UtcNow.AddSeconds(25); - contents = Render("index", data); - Assert.That(contents, Tests.Contains.InOrder( - "

1:1

", - "

2:2

", - "

3:3

", - "

1:1

", - "

2:2

", - "

3:3

", - "

last:4

")); - - _cacheService.UtcNow = _cacheService.UtcNow.AddSeconds(10); - contents = Render("index", data); - Assert.That(contents, Tests.Contains.InOrder( - "

1:5

", - "

2:6

", - "

3:7

", - "

1:5

", - "

2:6

", - "

3:7

", - "

last:4

")); - - _cacheService.UtcNow = _cacheService.UtcNow.AddSeconds(10); - contents = Render("index", data); - Assert.That(contents, Tests.Contains.InOrder( - "

1:5

", - "

2:6

", - "

3:7

", - "

1:5

", - "

2:6

", - "

3:7

", - "

last:8

")); - } - - [Test] - public void CommaCreatesMultiPartKey() - { - _viewFolder.Add(Path.Combine("home", "index.spark"), - @" -""/> - -

${x}:${ViewData.Model()}

-
"); - - var calls = 0; - var data = new StubViewData> - { - Model = () => (++calls).ToString() - }; - - var contents = Render("index", data); - Assert.That(contents, Tests.Contains.InOrder( - "

1:1

", - "

2:2

", - "

3:3

", - "

1:4

", - "

2:5

", - "

3:6

")); - - Assert.That(_cacheService.AllKeys.Count(x => x.Substring(32) == "1\u001f0"), Is.EqualTo(1)); - Assert.That(_cacheService.AllKeys.Count(x => x.Substring(32) == "2\u001f1"), Is.EqualTo(1)); - Assert.That(_cacheService.AllKeys.Count(x => x.Substring(32) == "3\u001f2"), Is.EqualTo(1)); - Assert.That(_cacheService.AllKeys.Count(x => x.Substring(32) == "1\u001f3"), Is.EqualTo(1)); - Assert.That(_cacheService.AllKeys.Count(x => x.Substring(32) == "2\u001f4"), Is.EqualTo(1)); - Assert.That(_cacheService.AllKeys.Count(x => x.Substring(32) == "3\u001f5"), Is.EqualTo(1)); - } - - - [Test] - public void SignalWillExpireOutputCachingEntry() - { - _viewFolder.Add(Path.Combine("home", "index.spark"), @" -"" datasignal='Spark.ICacheSignal'/> -
- -

${ViewData.Model()}

-
-
"); - var signal = new CacheSignal(); - var calls = 0; - var data = new StubViewData> - { - Model = () => (++calls).ToString() - }; - data["datasignal"] = signal; - - var contents = Render("index", data); - Assert.That(contents, Is.EqualTo(@" -
-

1

-
")); - Assert.That(calls, Is.EqualTo(1)); - - contents = Render("index", data); - Assert.That(contents, Is.EqualTo(@" -
-

1

-
")); - Assert.That(calls, Is.EqualTo(1)); - - signal.FireChanged(); - - contents = Render("index", data); - Assert.That(contents, Is.EqualTo(@" -
-

2

-
")); - Assert.That(calls, Is.EqualTo(2)); - - contents = Render("index", data); - Assert.That(contents, Is.EqualTo(@" -
-

2

-
")); - Assert.That(calls, Is.EqualTo(2)); - - } - } -} +//------------------------------------------------------------------------- +// +// Copyright 2008-2010 Louis DeJardin - http://whereslou.com +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +// Louis DeJardin +// Jacob Proffitt +// John Gietzen +//------------------------------------------------------------------------- + + +namespace Spark.Tests.Caching +{ + using System; + using System.Linq; + using System.Text; + using NUnit.Framework; + + using Spark.FileSystem; + using Spark.Tests.Stubs; + using System.IO; + + [TestFixture] + public class CacheElementTester + { + + private InMemoryViewFolder _viewFolder; + private StubViewFactory _factory; + private StubCacheService _cacheService; + + [SetUp] + public void Init() + { + _viewFolder = new InMemoryViewFolder(); + _cacheService = new StubCacheService(); + _factory = new StubViewFactory + { + Engine = new SparkViewEngine( + new SparkSettings() + .SetPageBaseType(typeof(StubSparkView))) + { + ViewFolder = _viewFolder + }, + CacheService = _cacheService + }; + } + + private string Render(string viewName) + { + return Render(viewName, new StubViewData()); + } + + private string Render(string viewName, StubViewData viewData) + { + var context = new StubViewContext { ControllerName = "home", ViewName = viewName, Output = new StringBuilder(), Data = viewData }; + _factory.RenderView(context); + return context.Output.ToString() + .Replace("\r\n\r\n", "\r\n") + .Replace("\r\n\r\n", "\r\n"); + } + + [Test] + public void TemplateRunsNormallyThroughCacheMiss() + { + _viewFolder.Add(Path.Combine("home", "index.spark"), @" +""/> +
+ +

${ViewData.Model()}

+
+
"); + var calls = 0; + var contents = Render("index", new StubViewData> + { + Model = () => (++calls).ToString() + }); + Assert.That(contents, Is.EqualTo(@" +
+

1

+
")); + Assert.That(calls, Is.EqualTo(1)); + } + + [Test] + public void TemplateDoesNotRunThroughCacheHit() + { + _viewFolder.Add(Path.Combine("home", "index.spark"), @" +""/> +
+ +

${ViewData.Model()}

+
+
"); + int calls = 0; + var data = new StubViewData> + { + Model = () => (++calls).ToString() + }; + + var contents = Render("index", data); + Assert.That(contents, Is.EqualTo(@" +
+

1

+
")); + Assert.That(calls, Is.EqualTo(1)); + + contents = Render("index", data); + Assert.That(contents, Is.EqualTo(@" +
+

1

+
")); + Assert.That(calls, Is.EqualTo(1)); + + } + + [Test] + public void CacheInMacroShouldActAsSameSite() + { + _viewFolder.Add(Path.Combine("home", "index.spark"), @" +""/> + +

${ViewData.Model()}

+
+
+${foo()} +${foo()} +
"); + + int calls = 0; + var data = new StubViewData> + { + Model = () => (++calls).ToString() + }; + + var contents = Render("index", data); + Assert.That(contents, Tests.Contains.InOrder( + "

1

", + "

1

")); + + Assert.That(calls, Is.EqualTo(1)); + + contents = Render("index", data); + Assert.That(contents, Tests.Contains.InOrder( + "

1

", + "

1

")); + + Assert.That(calls, Is.EqualTo(1)); + } + + [Test] + public void MultipleCachesShouldActAsDifferentSite() + { + _viewFolder.Add(Path.Combine("home", "index.spark"), @" +""/> +
+ +

${ViewData.Model()}

+
+ +

${ViewData.Model()}

+
+
"); + + var calls = 0; + var data = new StubViewData> + { + Model = () => (++calls).ToString() + }; + + var contents = Render("index", data); + Assert.That(contents, Is.EqualTo(@" +
+

1

+

2

+
")); + Assert.That(calls, Is.EqualTo(2)); + + + contents = Render("index", data); + Assert.That(contents, Is.EqualTo(@" +
+

1

+

2

+
")); + Assert.That(calls, Is.EqualTo(2)); + } + + [Test] + public void NamedContentShouldIndividuallySpoolAndCache() + { + _viewFolder.Add(Path.Combine("home", "index.spark"), @" +""/> +
+ +

f${ViewData.Model()}[1]

+
+cache + +

${ViewData.Model()}[2]c

+ +

f${ViewData.Model()}[3]c

+
+ +

b${ViewData.Model()}[4]c

+
+

${ViewData.Model()}[5]c

+
+ +

b${ViewData.Model()}[6]

+
+placed +

${ViewData.Model()}[7]

+ + +

${ViewData.Model()}[8]

+
"); + + var calls = 0; + var data = new StubViewData> + { + Model = () => (++calls).ToString() + }; + + var contents = Render("index", data); + Assert.That(calls, Is.EqualTo(8)); + Assert.That(contents, Is.EqualTo(@" +
+cache +

2[2]c

+

5[5]c

+placed +

7[7]

+

f1[1]

+

f3[3]c

+

b4[4]c

+

b6[6]

+

8[8]

+
")); + + + contents = Render("index", data); + Assert.That(calls, Is.EqualTo(12)); + Assert.That(contents, Is.EqualTo(@" +
+cache +

2[2]c

+

5[5]c

+placed +

11[7]

+

f9[1]

+

f3[3]c

+

b4[4]c

+

b10[6]

+

12[8]

+
")); + } + + + [Test] + public void OutputWhileNamedContentActiveShouldAppearOnceAtCorrectTarget() + { + + _viewFolder.Add(Path.Combine("home", "index.spark"), @" +""/> +
    + +
  • ${ViewData.Model()}[1]
  • +
    +
  • ${ViewData.Model()}[2]
  • + + +
  • ${ViewData.Model()}[3]c
  • + +hana + +
  • ${ViewData.Model()}[4]c
  • +
    +
    +
  • ${ViewData.Model()}[5]
  • + +
  • ${ViewData.Model()}[6]
  • +
    + +
"); + + var calls = 0; + var data = new StubViewData> + { + Model = () => (++calls).ToString() + }; + + var contents = Render("index", data); + Assert.That(calls, Is.EqualTo(6)); + Assert.That(contents, Is.EqualTo(@" +
    +
  • 2[2]
  • +
  • 5[5]
  • +
  • 1[1]
  • +
  • 3[3]c
  • +hana +
  • 4[4]c
  • +
  • 6[6]
  • +
")); + + + contents = Render("index", data); + Assert.That(calls, Is.EqualTo(10)); + Assert.That(contents, Is.EqualTo(@" +
    +
  • 8[2]
  • +
  • 9[5]
  • +
  • 7[1]
  • +
  • 3[3]c
  • +hana +
  • 4[4]c
  • +
  • 10[6]
  • +
")); + } + + + [Test] + public void OnceFlagsSetWhenCacheRecordedShouldBeSetWhenCacheReplayed() + { + _viewFolder.Add(Path.Combine("home", "index.spark"), @" +""/> +
    +
  • ${ViewData.Model()}[1]
  • + +
  • ${ViewData.Model()}[2]
  • +
  • ${ViewData.Model()}[3]
  • +
    +
  • ${ViewData.Model()}[4]
  • +
  • ${ViewData.Model()}[5]
  • +
  • ${ViewData.Model()}[6]
  • +
  • ${ViewData.Model()}[7]
  • +
"); + + var calls = 0; + var data = new StubViewData> + { + Model = () => (++calls).ToString() + }; + + var contents = Render("index", data); + Assert.That(calls, Is.EqualTo(3)); + Assert.That(contents, Is.EqualTo(@" +
    +
  • 1[1]
  • +
  • 2[2]
  • +
  • 3[4]
  • +
")); + + contents = Render("index", data); + Assert.That(calls, Is.EqualTo(5)); + Assert.That(contents, Is.EqualTo(@" +
    +
  • 4[1]
  • +
  • 2[2]
  • +
  • 5[4]
  • +
")); + } + + [Test] + public void CacheFinallyShouldNotThrowExceptionWhenKeyIsBad() + { + _viewFolder.Add(Path.Combine("home", "index.spark"), @" + +#throw new System.ApplicationException(); + + +foo + +"); + Assert.That(() => Render("index", new StubViewData()), Throws.TypeOf()); + } + + [Test] + public void CacheAttributeUsedAsKey() + { + _viewFolder.Add(Path.Combine("home", "index.spark"), @" + + +

${x}:${++count}

+
"); + + var contents = Render("index"); + Assert.That(contents, Tests.Contains.InOrder( + "

1:1

", + "

3:2

", + "

5:3

", + "

2:4

", + "

3:2

", + "

3:2

", + "

5:3

", + "

7:5

")); + } + + [Test] + public void CacheExpiresTakesOutContentAfterTime() + { + _viewFolder.Add(Path.Combine("home", "index.spark"), @" +""/> + + +

${x}:${ViewData.Model()}

+
+
+

last:${ViewData.Model()}

+"); + + var calls = 0; + var data = new StubViewData> + { + Model = () => (++calls).ToString() + }; + + var contents = Render("index", data); + Assert.That(contents, Tests.Contains.InOrder( + "

1:1

", + "

2:2

", + "

3:3

", + "

1:1

", + "

2:2

", + "

3:3

", + "

last:4

")); + + _cacheService.UtcNow = _cacheService.UtcNow.AddSeconds(25); + contents = Render("index", data); + Assert.That(contents, Tests.Contains.InOrder( + "

1:1

", + "

2:2

", + "

3:3

", + "

1:1

", + "

2:2

", + "

3:3

", + "

last:4

")); + + _cacheService.UtcNow = _cacheService.UtcNow.AddSeconds(10); + contents = Render("index", data); + Assert.That(contents, Tests.Contains.InOrder( + "

1:5

", + "

2:6

", + "

3:7

", + "

1:5

", + "

2:6

", + "

3:7

", + "

last:4

")); + + _cacheService.UtcNow = _cacheService.UtcNow.AddSeconds(10); + contents = Render("index", data); + Assert.That(contents, Tests.Contains.InOrder( + "

1:5

", + "

2:6

", + "

3:7

", + "

1:5

", + "

2:6

", + "

3:7

", + "

last:8

")); + } + + [Test] + public void CommaCreatesMultiPartKey() + { + _viewFolder.Add(Path.Combine("home", "index.spark"), + @" +""/> + +

${x}:${ViewData.Model()}

+
"); + + var calls = 0; + var data = new StubViewData> + { + Model = () => (++calls).ToString() + }; + + var contents = Render("index", data); + Assert.That(contents, Tests.Contains.InOrder( + "

1:1

", + "

2:2

", + "

3:3

", + "

1:4

", + "

2:5

", + "

3:6

")); + + Assert.That(_cacheService.AllKeys.Count(x => x.Substring(32) == "1\u001f0"), Is.EqualTo(1)); + Assert.That(_cacheService.AllKeys.Count(x => x.Substring(32) == "2\u001f1"), Is.EqualTo(1)); + Assert.That(_cacheService.AllKeys.Count(x => x.Substring(32) == "3\u001f2"), Is.EqualTo(1)); + Assert.That(_cacheService.AllKeys.Count(x => x.Substring(32) == "1\u001f3"), Is.EqualTo(1)); + Assert.That(_cacheService.AllKeys.Count(x => x.Substring(32) == "2\u001f4"), Is.EqualTo(1)); + Assert.That(_cacheService.AllKeys.Count(x => x.Substring(32) == "3\u001f5"), Is.EqualTo(1)); + } + + + [Test] + public void SignalWillExpireOutputCachingEntry() + { + _viewFolder.Add(Path.Combine("home", "index.spark"), @" +"" datasignal='Spark.ICacheSignal'/> +
+ +

${ViewData.Model()}

+
+
"); + var signal = new CacheSignal(); + var calls = 0; + var data = new StubViewData> + { + Model = () => (++calls).ToString() + }; + data["datasignal"] = signal; + + var contents = Render("index", data); + Assert.That(contents, Is.EqualTo(@" +
+

1

+
")); + Assert.That(calls, Is.EqualTo(1)); + + contents = Render("index", data); + Assert.That(contents, Is.EqualTo(@" +
+

1

+
")); + Assert.That(calls, Is.EqualTo(1)); + + signal.FireChanged(); + + contents = Render("index", data); + Assert.That(contents, Is.EqualTo(@" +
+

2

+
")); + Assert.That(calls, Is.EqualTo(2)); + + contents = Render("index", data); + Assert.That(contents, Is.EqualTo(@" +
+

2

+
")); + Assert.That(calls, Is.EqualTo(2)); + + } + } +} diff --git a/src/Spark.Tests/Caching/CacheOriginatorTester.cs b/src/Spark.Web.Tests/Caching/CacheOriginatorTester.cs similarity index 95% rename from src/Spark.Tests/Caching/CacheOriginatorTester.cs rename to src/Spark.Web.Tests/Caching/CacheOriginatorTester.cs index cdf42f4d..9a4ddaa0 100644 --- a/src/Spark.Tests/Caching/CacheOriginatorTester.cs +++ b/src/Spark.Web.Tests/Caching/CacheOriginatorTester.cs @@ -1,184 +1,180 @@ -using System; -using System.Collections.Generic; -using System.IO; -using System.Linq; -using System.Text; -using NUnit.Framework; - -using Spark.Caching; -using Spark.Spool; - -namespace Spark.Tests.Caching -{ - [TestFixture] - public class CacheOriginatorTester - { - private SparkViewContext _subject; - private CacheOriginator _originator; - - private SparkViewContext _subject2; - private CacheOriginator _originator2; - - - [SetUp] - public void Init() - { - _subject = new SparkViewContext {Output = new SpoolWriter()}; - _originator = new CacheOriginator(_subject); - - _subject2 = new SparkViewContext { Output = new SpoolWriter() }; - _originator2 = new CacheOriginator(_subject2); - } - - [Test] - public void OriginatorShouldCreateMemento() - { - _originator.BeginMemento(); - var memento = _originator.EndMemento(); - Assert.That(memento, Is.Not.Null); - } - - [Test] - public void ApplyMementoShouldAddTextToStream() - { - _originator.BeginMemento(); - _subject.Output.Write("Hello"); - _subject.Output.Write("World"); - var memento = _originator.EndMemento(); - - _originator2.DoMemento(memento); - Assert.That(_subject2.Output.ToString(), Is.EqualTo("HelloWorld")); - } - - [Test] - public void AdditionalWritesBeforeAndAfterAreMoot() - { - _subject.Output.Write("Alpha"); - _originator.BeginMemento(); - _subject.Output.Write("Beta"); - var memento = _originator.EndMemento(); - _subject.Output.Write("Gamma"); - - _subject2.Output.Write("Delta"); - _originator2.DoMemento(memento); - _subject2.Output.Write("Epsilon"); - - Assert.That(_subject.Output.ToString(), Is.EqualTo("AlphaBetaGamma")); - Assert.That(_subject2.Output.ToString(), Is.EqualTo("DeltaBetaEpsilon")); - } - - [Test] - public void DisposingSpoolWritersShouldNotDamageCaches() - { - _subject.Output.Write("Alpha"); - _originator.BeginMemento(); - _subject.Output.Write("Beta"); - var memento = _originator.EndMemento(); - _subject.Output.Write("Gamma"); - - _subject2.Output.Write("Delta"); - _originator2.DoMemento(memento); - _subject2.Output.Write("Epsilon"); - - Assert.That(_subject.Output.ToString(), Is.EqualTo("AlphaBetaGamma")); - Assert.That(_subject2.Output.ToString(), Is.EqualTo("DeltaBetaEpsilon")); - - _subject.Output.Dispose(); - Assert.That(_subject2.Output.ToString(), Is.EqualTo("DeltaBetaEpsilon")); - _subject2.Output.Dispose(); - - var subject3 = new SparkViewContext { Output = new SpoolWriter() }; - - subject3.Output.Write("Zeta"); - new CacheOriginator(subject3).DoMemento(memento); - subject3.Output.Write("Eta"); - Assert.That(subject3.Output.ToString(), Is.EqualTo("ZetaBetaEta")); - } - - [Test] - public void AddedNamedContentAddedWhenApplied() - { - _originator.BeginMemento(); - _subject.Content.Add("foo", new SpoolWriter()); - _subject.Output.Write("alpha"); - _subject.Content["foo"].Write("beta"); - var memento = _originator.EndMemento(); - - _originator2.DoMemento(memento); - - Assert.That(_subject2.Output.ToString(), Is.EqualTo("alpha")); - Assert.That(_subject2.Content["foo"].ToString(), Is.EqualTo("beta")); - } - - [Test] - public void WrittenNamedContentWrittenWhenApplied() - { - _subject.Content.Add("foo", new SpoolWriter()); - _subject.Content["foo"].Write("hello"); - - _originator.BeginMemento(); - _subject.Output.Write("alpha"); - _subject.Content["foo"].Write("beta"); - var memento = _originator.EndMemento(); - - _subject2.Content.Add("foo", new SpoolWriter()); - _subject2.Content["foo"].Write("world"); - - _originator2.DoMemento(memento); - - Assert.That(_subject2.Output.ToString(), Is.EqualTo("alpha")); - Assert.That(_subject2.Content["foo"].ToString(), Is.EqualTo("worldbeta")); - } - - [Test] - public void OnceCollectionExtendedWhenApplied() - { - _subject.OnceTable.Add("hana", "duul"); - _originator.BeginMemento(); - _subject.OnceTable.Add("set", "net"); - var memento = _originator.EndMemento(); - _subject.OnceTable.Add("daset", "yaset"); - - _subject2.OnceTable.Add("ilgot", "yadul"); - _originator2.DoMemento(memento); - _subject2.OnceTable.Add("ahop", "yuul"); - - Assert.That(_subject.OnceTable.Count(), Is.EqualTo(3)); - Assert.That(_subject.OnceTable["hana"], Is.EqualTo("duul")); - Assert.That(_subject.OnceTable["set"], Is.EqualTo("net")); - Assert.That(_subject.OnceTable["daset"], Is.EqualTo("yaset")); - - Assert.That(_subject2.OnceTable.Count(), Is.EqualTo(3)); - Assert.That(_subject2.OnceTable["ilgot"], Is.EqualTo("yadul")); - Assert.That(_subject2.OnceTable["set"], Is.EqualTo("net")); - Assert.That(_subject2.OnceTable["ahop"], Is.EqualTo("yuul")); - } - - [Test] - public void OutputWhileNamedContentActiveShouldAppearOnceAtCorrectTarget() - { - _subject.Content.Add("foo", new SpoolWriter()); - _subject.Content.Add("bar", new SpoolWriter()); - _subject.Output = _subject.Content["foo"]; - _subject.Output.Write("hello"); - - _originator.BeginMemento(); - _subject.Content["foo"].Write(" "); - _subject.Content["bar"].Write("yadda"); - _subject.Output.Write("world"); - _subject.Content["foo"].Write("!"); - var memento = _originator.EndMemento(); - - Assert.That(_subject.Output.ToString(), Is.EqualTo("hello world!")); - Assert.That(_subject.Content["foo"].ToString(), Is.EqualTo("hello world!")); - - _subject2.Content.Add("foo", new SpoolWriter()); - _subject2.Output = _subject2.Content["foo"]; - _subject2.Output.Write("hello"); - _originator2.DoMemento(memento); - - Assert.That(_subject2.Output.ToString(), Is.EqualTo("hello world!")); - Assert.That(_subject2.Content["foo"].ToString(), Is.EqualTo("hello world!")); - } - } -} +using System.Linq; +using NUnit.Framework; + +using Spark.Caching; +using Spark.Spool; + +namespace Spark.Tests.Caching +{ + [TestFixture] + public class CacheOriginatorTester + { + private SparkViewContext _subject; + private CacheOriginator _originator; + + private SparkViewContext _subject2; + private CacheOriginator _originator2; + + + [SetUp] + public void Init() + { + _subject = new SparkViewContext {Output = new SpoolWriter()}; + _originator = new CacheOriginator(_subject); + + _subject2 = new SparkViewContext { Output = new SpoolWriter() }; + _originator2 = new CacheOriginator(_subject2); + } + + [Test] + public void OriginatorShouldCreateMemento() + { + _originator.BeginMemento(); + var memento = _originator.EndMemento(); + Assert.That(memento, Is.Not.Null); + } + + [Test] + public void ApplyMementoShouldAddTextToStream() + { + _originator.BeginMemento(); + _subject.Output.Write("Hello"); + _subject.Output.Write("World"); + var memento = _originator.EndMemento(); + + _originator2.DoMemento(memento); + Assert.That(_subject2.Output.ToString(), Is.EqualTo("HelloWorld")); + } + + [Test] + public void AdditionalWritesBeforeAndAfterAreMoot() + { + _subject.Output.Write("Alpha"); + _originator.BeginMemento(); + _subject.Output.Write("Beta"); + var memento = _originator.EndMemento(); + _subject.Output.Write("Gamma"); + + _subject2.Output.Write("Delta"); + _originator2.DoMemento(memento); + _subject2.Output.Write("Epsilon"); + + Assert.That(_subject.Output.ToString(), Is.EqualTo("AlphaBetaGamma")); + Assert.That(_subject2.Output.ToString(), Is.EqualTo("DeltaBetaEpsilon")); + } + + [Test] + public void DisposingSpoolWritersShouldNotDamageCaches() + { + _subject.Output.Write("Alpha"); + _originator.BeginMemento(); + _subject.Output.Write("Beta"); + var memento = _originator.EndMemento(); + _subject.Output.Write("Gamma"); + + _subject2.Output.Write("Delta"); + _originator2.DoMemento(memento); + _subject2.Output.Write("Epsilon"); + + Assert.That(_subject.Output.ToString(), Is.EqualTo("AlphaBetaGamma")); + Assert.That(_subject2.Output.ToString(), Is.EqualTo("DeltaBetaEpsilon")); + + _subject.Output.Dispose(); + Assert.That(_subject2.Output.ToString(), Is.EqualTo("DeltaBetaEpsilon")); + _subject2.Output.Dispose(); + + var subject3 = new SparkViewContext { Output = new SpoolWriter() }; + + subject3.Output.Write("Zeta"); + new CacheOriginator(subject3).DoMemento(memento); + subject3.Output.Write("Eta"); + Assert.That(subject3.Output.ToString(), Is.EqualTo("ZetaBetaEta")); + } + + [Test] + public void AddedNamedContentAddedWhenApplied() + { + _originator.BeginMemento(); + _subject.Content.Add("foo", new SpoolWriter()); + _subject.Output.Write("alpha"); + _subject.Content["foo"].Write("beta"); + var memento = _originator.EndMemento(); + + _originator2.DoMemento(memento); + + Assert.That(_subject2.Output.ToString(), Is.EqualTo("alpha")); + Assert.That(_subject2.Content["foo"].ToString(), Is.EqualTo("beta")); + } + + [Test] + public void WrittenNamedContentWrittenWhenApplied() + { + _subject.Content.Add("foo", new SpoolWriter()); + _subject.Content["foo"].Write("hello"); + + _originator.BeginMemento(); + _subject.Output.Write("alpha"); + _subject.Content["foo"].Write("beta"); + var memento = _originator.EndMemento(); + + _subject2.Content.Add("foo", new SpoolWriter()); + _subject2.Content["foo"].Write("world"); + + _originator2.DoMemento(memento); + + Assert.That(_subject2.Output.ToString(), Is.EqualTo("alpha")); + Assert.That(_subject2.Content["foo"].ToString(), Is.EqualTo("worldbeta")); + } + + [Test] + public void OnceCollectionExtendedWhenApplied() + { + _subject.OnceTable.Add("hana", "duul"); + _originator.BeginMemento(); + _subject.OnceTable.Add("set", "net"); + var memento = _originator.EndMemento(); + _subject.OnceTable.Add("daset", "yaset"); + + _subject2.OnceTable.Add("ilgot", "yadul"); + _originator2.DoMemento(memento); + _subject2.OnceTable.Add("ahop", "yuul"); + + Assert.That(_subject.OnceTable.Count(), Is.EqualTo(3)); + Assert.That(_subject.OnceTable["hana"], Is.EqualTo("duul")); + Assert.That(_subject.OnceTable["set"], Is.EqualTo("net")); + Assert.That(_subject.OnceTable["daset"], Is.EqualTo("yaset")); + + Assert.That(_subject2.OnceTable.Count(), Is.EqualTo(3)); + Assert.That(_subject2.OnceTable["ilgot"], Is.EqualTo("yadul")); + Assert.That(_subject2.OnceTable["set"], Is.EqualTo("net")); + Assert.That(_subject2.OnceTable["ahop"], Is.EqualTo("yuul")); + } + + [Test] + public void OutputWhileNamedContentActiveShouldAppearOnceAtCorrectTarget() + { + _subject.Content.Add("foo", new SpoolWriter()); + _subject.Content.Add("bar", new SpoolWriter()); + _subject.Output = _subject.Content["foo"]; + _subject.Output.Write("hello"); + + _originator.BeginMemento(); + _subject.Content["foo"].Write(" "); + _subject.Content["bar"].Write("yadda"); + _subject.Output.Write("world"); + _subject.Content["foo"].Write("!"); + var memento = _originator.EndMemento(); + + Assert.That(_subject.Output.ToString(), Is.EqualTo("hello world!")); + Assert.That(_subject.Content["foo"].ToString(), Is.EqualTo("hello world!")); + + _subject2.Content.Add("foo", new SpoolWriter()); + _subject2.Output = _subject2.Content["foo"]; + _subject2.Output.Write("hello"); + _originator2.DoMemento(memento); + + Assert.That(_subject2.Output.ToString(), Is.EqualTo("hello world!")); + Assert.That(_subject2.Content["foo"].ToString(), Is.EqualTo("hello world!")); + } + } +} diff --git a/src/Spark.Tests/Caching/CacheSignalTester.cs b/src/Spark.Web.Tests/Caching/CacheSignalTester.cs similarity index 94% rename from src/Spark.Tests/Caching/CacheSignalTester.cs rename to src/Spark.Web.Tests/Caching/CacheSignalTester.cs index 14869999..51e87662 100644 --- a/src/Spark.Tests/Caching/CacheSignalTester.cs +++ b/src/Spark.Web.Tests/Caching/CacheSignalTester.cs @@ -1,85 +1,82 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using NUnit.Framework; - - -namespace Spark.Tests.Caching -{ - [TestFixture] - public class CacheSignalTester - { - [Test] - public void SignalCanBeFiredExternally() - { - var fired = false; - var signal = new CacheSignal(); - signal.Changed += (sender, e) => { fired = true; }; - - Assert.That(fired, Is.False); - signal.FireChanged(); - Assert.That(fired, Is.True); - } - - [Test] - public void UnusedSignalCanBeFiredSafely() - { - var signal = new CacheSignal(); - signal.FireChanged(); - signal.Changed += ignore_signal_event_handler; - signal.FireChanged(); - signal.Changed -= ignore_signal_event_handler; - signal.FireChanged(); - } - - static void ignore_signal_event_handler(object sender, EventArgs e) - { - } - - static void ignore_signal_event_handler2(object sender, EventArgs e) - { - } - - [Test] - public void EnableAndDisableShouldBeCalledAsEventHandlerCountTransitionsBetweenZeroAndNonZero() - { - var signal = new EnableTestingSignal(); - - Assert.That(signal.Enabled, Is.False); - signal.FireChanged(); - Assert.That(signal.Enabled, Is.False); - - Assert.That(signal.Enabled, Is.False); - signal.Changed += ignore_signal_event_handler; - Assert.That(signal.Enabled, Is.True); - signal.Changed -= ignore_signal_event_handler; - Assert.That(signal.Enabled, Is.False); - - signal.Changed += ignore_signal_event_handler; - Assert.That(signal.Enabled, Is.True); - signal.Changed += ignore_signal_event_handler2; - Assert.That(signal.Enabled, Is.True); - signal.Changed -= ignore_signal_event_handler; - Assert.That(signal.Enabled, Is.True); - signal.Changed -= ignore_signal_event_handler2; - Assert.That(signal.Enabled, Is.False); - } - - class EnableTestingSignal : CacheSignal - { - protected override void Enable() - { - Assert.That(Enabled, Is.False); - Enabled = true; - } - protected override void Disable() - { - Assert.That(Enabled, Is.True); - Enabled = false; - } - - public bool Enabled { get; set; } - } - } -} +using System; +using NUnit.Framework; + + +namespace Spark.Tests.Caching +{ + [TestFixture] + public class CacheSignalTester + { + [Test] + public void SignalCanBeFiredExternally() + { + var fired = false; + var signal = new CacheSignal(); + signal.Changed += (sender, e) => { fired = true; }; + + Assert.That(fired, Is.False); + signal.FireChanged(); + Assert.That(fired, Is.True); + } + + [Test] + public void UnusedSignalCanBeFiredSafely() + { + var signal = new CacheSignal(); + signal.FireChanged(); + signal.Changed += ignore_signal_event_handler; + signal.FireChanged(); + signal.Changed -= ignore_signal_event_handler; + signal.FireChanged(); + } + + static void ignore_signal_event_handler(object sender, EventArgs e) + { + } + + static void ignore_signal_event_handler2(object sender, EventArgs e) + { + } + + [Test] + public void EnableAndDisableShouldBeCalledAsEventHandlerCountTransitionsBetweenZeroAndNonZero() + { + var signal = new EnableTestingSignal(); + + Assert.That(signal.Enabled, Is.False); + signal.FireChanged(); + Assert.That(signal.Enabled, Is.False); + + Assert.That(signal.Enabled, Is.False); + signal.Changed += ignore_signal_event_handler; + Assert.That(signal.Enabled, Is.True); + signal.Changed -= ignore_signal_event_handler; + Assert.That(signal.Enabled, Is.False); + + signal.Changed += ignore_signal_event_handler; + Assert.That(signal.Enabled, Is.True); + signal.Changed += ignore_signal_event_handler2; + Assert.That(signal.Enabled, Is.True); + signal.Changed -= ignore_signal_event_handler; + Assert.That(signal.Enabled, Is.True); + signal.Changed -= ignore_signal_event_handler2; + Assert.That(signal.Enabled, Is.False); + } + + class EnableTestingSignal : CacheSignal + { + protected override void Enable() + { + Assert.That(Enabled, Is.False); + Enabled = true; + } + protected override void Disable() + { + Assert.That(Enabled, Is.True); + Enabled = false; + } + + public bool Enabled { get; set; } + } + } +} diff --git a/src/Spark.Tests/Caching/CacheUtilitiesTester.cs b/src/Spark.Web.Tests/Caching/CacheUtilitiesTester.cs similarity index 97% rename from src/Spark.Tests/Caching/CacheUtilitiesTester.cs rename to src/Spark.Web.Tests/Caching/CacheUtilitiesTester.cs index f83b1dd4..8e278499 100644 --- a/src/Spark.Tests/Caching/CacheUtilitiesTester.cs +++ b/src/Spark.Web.Tests/Caching/CacheUtilitiesTester.cs @@ -1,56 +1,56 @@ -using System; -using System.Globalization; -using System.Threading; -using NUnit.Framework; - -using Spark.Utilities; - -namespace Spark.Tests.Caching -{ - [TestFixture] - public class CacheUtilitiesTester - { - [Test] - public void KeyConcatinationShouldSimplyStringConcatWithZeroOrOneParts() - { - var id0 = CacheUtilities.ToIdentifier("foo", new object[] { }); - Assert.That(id0, Is.EqualTo("foo")); - - var id1a = CacheUtilities.ToIdentifier("foo", new object[] { "bar" }); - Assert.That(id1a, Is.EqualTo("foobar")); - - using (new CurrentCultureScope("")) - { - var id1b = CacheUtilities.ToIdentifier("foo", new object[] {45.2}); - Assert.That(id1b, Is.EqualTo("foo45.2")); - } - } - - [Test] - public void KeyMultipleKeysHaveUnitSeperatorDelimitingParts() - { - var id2 = CacheUtilities.ToIdentifier("foo", new object[] { "bar", "quux" }); - Assert.That(id2, Is.EqualTo("foobar\u001fquux")); - - using (new CurrentCultureScope("")) - { - var id3 = CacheUtilities.ToIdentifier("foo", new object[] {45.2, null, this}); - Assert.That(id3, Is.EqualTo("foo45.2\u001f\u001fSpark.Tests.Caching.CacheUtilitiesTester")); - } - } - - public class CurrentCultureScope : IDisposable - { - private readonly CultureInfo _culture; - public CurrentCultureScope(string name) - { - _culture = Thread.CurrentThread.CurrentCulture; - Thread.CurrentThread.CurrentCulture = new CultureInfo(name); - } - public void Dispose() - { - Thread.CurrentThread.CurrentCulture = _culture; - } - } - } -} +using System; +using System.Globalization; +using System.Threading; +using NUnit.Framework; + +using Spark.Utilities; + +namespace Spark.Tests.Caching +{ + [TestFixture] + public class CacheUtilitiesTester + { + [Test] + public void KeyConcatinationShouldSimplyStringConcatWithZeroOrOneParts() + { + var id0 = CacheUtilities.ToIdentifier("foo", new object[] { }); + Assert.That(id0, Is.EqualTo("foo")); + + var id1a = CacheUtilities.ToIdentifier("foo", new object[] { "bar" }); + Assert.That(id1a, Is.EqualTo("foobar")); + + using (new CurrentCultureScope("")) + { + var id1b = CacheUtilities.ToIdentifier("foo", new object[] {45.2}); + Assert.That(id1b, Is.EqualTo("foo45.2")); + } + } + + [Test] + public void KeyMultipleKeysHaveUnitSeperatorDelimitingParts() + { + var id2 = CacheUtilities.ToIdentifier("foo", new object[] { "bar", "quux" }); + Assert.That(id2, Is.EqualTo("foobar\u001fquux")); + + using (new CurrentCultureScope("")) + { + var id3 = CacheUtilities.ToIdentifier("foo", new object[] {45.2, null, this}); + Assert.That(id3, Is.EqualTo("foo45.2\u001f\u001fSpark.Tests.Caching.CacheUtilitiesTester")); + } + } + + public class CurrentCultureScope : IDisposable + { + private readonly CultureInfo _culture; + public CurrentCultureScope(string name) + { + _culture = Thread.CurrentThread.CurrentCulture; + Thread.CurrentThread.CurrentCulture = new CultureInfo(name); + } + public void Dispose() + { + Thread.CurrentThread.CurrentCulture = _culture; + } + } + } +} diff --git a/src/Spark.Tests/Caching/TextWriterOriginatorTester.cs b/src/Spark.Web.Tests/Caching/TextWriterOriginatorTester.cs similarity index 91% rename from src/Spark.Tests/Caching/TextWriterOriginatorTester.cs rename to src/Spark.Web.Tests/Caching/TextWriterOriginatorTester.cs index ddcb6d59..9a702a5c 100644 --- a/src/Spark.Tests/Caching/TextWriterOriginatorTester.cs +++ b/src/Spark.Web.Tests/Caching/TextWriterOriginatorTester.cs @@ -1,61 +1,57 @@ -using System; -using System.Collections.Generic; -using System.IO; -using System.Linq; -using System.Text; -using NUnit.Framework; - -using Spark.Caching; -using Spark.Spool; - -namespace Spark.Tests.Caching -{ - [TestFixture] - public class TextWriterOriginatorTester - { - [Test] - public void StringWriterOriginatorBuildsMementoWithChanges() - { - var writer = new StringWriter(); - var originator = TextWriterOriginator.Create(writer); - - writer.Write("Alpha"); - originator.BeginMemento(); - writer.Write("Beta"); - var memento = originator.EndMemento(); - writer.Write("Gamma"); - - var writer2 = new StringWriter(); - writer2.Write("Delta"); - TextWriterOriginator.Create(writer2).DoMemento(memento); - writer2.Write("Epsilon"); - - Assert.That(writer.ToString(), Is.EqualTo("AlphaBetaGamma")); - Assert.That(writer2.ToString(), Is.EqualTo("DeltaBetaEpsilon")); - } - - [Test] - public void SpoolWriterOriginatorBuildsMementoWithChanges() - { - var writer = new SpoolWriter(); - var originator = TextWriterOriginator.Create(writer); - - writer.Write("Alpha"); - originator.BeginMemento(); - writer.Write("B"); - writer.Write("e"); - writer.Write("t"); - writer.Write("a"); - var memento = originator.EndMemento(); - writer.Write("Gamma"); - - var writer2 = new SpoolWriter(); - writer2.Write("Delta"); - TextWriterOriginator.Create(writer2).DoMemento(memento); - writer2.Write("Epsilon"); - - Assert.That(writer.ToString(), Is.EqualTo("AlphaBetaGamma")); - Assert.That(writer2.ToString(), Is.EqualTo("DeltaBetaEpsilon")); - } - } -} +using System.IO; +using NUnit.Framework; + +using Spark.Caching; +using Spark.Spool; + +namespace Spark.Tests.Caching +{ + [TestFixture] + public class TextWriterOriginatorTester + { + [Test] + public void StringWriterOriginatorBuildsMementoWithChanges() + { + var writer = new StringWriter(); + var originator = TextWriterOriginator.Create(writer); + + writer.Write("Alpha"); + originator.BeginMemento(); + writer.Write("Beta"); + var memento = originator.EndMemento(); + writer.Write("Gamma"); + + var writer2 = new StringWriter(); + writer2.Write("Delta"); + TextWriterOriginator.Create(writer2).DoMemento(memento); + writer2.Write("Epsilon"); + + Assert.That(writer.ToString(), Is.EqualTo("AlphaBetaGamma")); + Assert.That(writer2.ToString(), Is.EqualTo("DeltaBetaEpsilon")); + } + + [Test] + public void SpoolWriterOriginatorBuildsMementoWithChanges() + { + var writer = new SpoolWriter(); + var originator = TextWriterOriginator.Create(writer); + + writer.Write("Alpha"); + originator.BeginMemento(); + writer.Write("B"); + writer.Write("e"); + writer.Write("t"); + writer.Write("a"); + var memento = originator.EndMemento(); + writer.Write("Gamma"); + + var writer2 = new SpoolWriter(); + writer2.Write("Delta"); + TextWriterOriginator.Create(writer2).DoMemento(memento); + writer2.Write("Epsilon"); + + Assert.That(writer.ToString(), Is.EqualTo("AlphaBetaGamma")); + Assert.That(writer2.ToString(), Is.EqualTo("DeltaBetaEpsilon")); + } + } +} diff --git a/src/Spark.Tests/Compiler/CSharpViewCompilerTester.cs b/src/Spark.Web.Tests/Compiler/CSharpViewCompilerTester.cs similarity index 97% rename from src/Spark.Tests/Compiler/CSharpViewCompilerTester.cs rename to src/Spark.Web.Tests/Compiler/CSharpViewCompilerTester.cs index fd359605..1e61db65 100644 --- a/src/Spark.Tests/Compiler/CSharpViewCompilerTester.cs +++ b/src/Spark.Web.Tests/Compiler/CSharpViewCompilerTester.cs @@ -1,390 +1,390 @@ -// Copyright 2008-2009 Louis DeJardin - http://whereslou.com -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// -using System.Collections.Generic; - -using Spark.Compiler; -using NUnit.Framework; -using Spark.Compiler.CSharp; -using Spark.Tests.Models; -using Spark.Tests.Stubs; - -namespace Spark.Tests.Compiler -{ - [TestFixture] - public class CSharpViewCompilerTester - { - - [SetUp] - public void Init() - { - } - - private static void DoCompileView(ViewCompiler compiler, IList chunks) - { - compiler.CompileView(new[] { chunks }, new[] { chunks }); - } - - [Test] - public void MakeAndCompile() - { - var compiler = new CSharpViewCompiler { BaseClass = "Spark.SparkViewBase" }; - - DoCompileView(compiler, new[] { new SendLiteralChunk { Text = "hello world" } }); - - var instance = compiler.CreateInstance(); - string contents = instance.RenderView(); - - Assert.That(contents.Contains("hello world")); - } - - - [Test] - public void UnsafeLiteralCharacters() - { - var text = "hello\t\r\n\"world"; - var compiler = new CSharpViewCompiler { BaseClass = "Spark.SparkViewBase" }; - DoCompileView(compiler, new[] { new SendLiteralChunk { Text = text } }); - - Assert.That(compiler.SourceCode.Contains("Write(\"hello\\t\\r\\n\\\"world\")")); - - var instance = compiler.CreateInstance(); - string contents = instance.RenderView(); - - Assert.AreEqual(text, contents); - } - - [Test] - public void SimpleOutput() - { - var compiler = new CSharpViewCompiler { BaseClass = "Spark.SparkViewBase" }; - DoCompileView(compiler, new[] { new SendExpressionChunk { Code = "3 + 4" } }); - var instance = compiler.CreateInstance(); - string contents = instance.RenderView(); - Assert.AreEqual("7", contents); - } - - [Test] - public void LocalVariableDecl() - { - var compiler = new CSharpViewCompiler { BaseClass = "Spark.SparkViewBase" }; - DoCompileView(compiler, new Chunk[] - { - new LocalVariableChunk { Name = "i", Value = "5" }, - new SendExpressionChunk { Code = "i" } - }); - var instance = compiler.CreateInstance(); - string contents = instance.RenderView(); - - Assert.AreEqual("5", contents); - } - - [Test] - public void ForEachLoop() - { - var compiler = new CSharpViewCompiler { BaseClass = "Spark.SparkViewBase" }; - DoCompileView(compiler, new Chunk[] - { - new LocalVariableChunk {Name = "data", Value = "new[]{3,4,5}"}, - new SendLiteralChunk {Text = "
    "}, - new ForEachChunk - { - Code = "var item in data", - Body = new Chunk[] - { - new SendLiteralChunk {Text = "
  • "}, - new SendExpressionChunk {Code = "item"}, - new SendLiteralChunk {Text = "
  • "} - } - }, - new SendLiteralChunk {Text = "
"} - }); - var instance = compiler.CreateInstance(); - var contents = instance.RenderView(); - Assert.AreEqual("
  • 3
  • 4
  • 5
", contents); - } - - [Test] - public void GlobalVariables() - { - var compiler = new CSharpViewCompiler { BaseClass = "Spark.SparkViewBase" }; - DoCompileView(compiler, new Chunk[] - { - new SendExpressionChunk{Code="title"}, - new AssignVariableChunk{ Name="item", Value="8"}, - new SendLiteralChunk{ Text=":"}, - new SendExpressionChunk{Code="item"}, - new GlobalVariableChunk{ Name="title", Value="\"hello world\""}, - new GlobalVariableChunk{ Name="item", Value="3"} - }); - var instance = compiler.CreateInstance(); - var contents = instance.RenderView(); - Assert.AreEqual("hello world:8", contents); - } - - [Test] - public void TargetNamespace() - { - var compiler = new CSharpViewCompiler - { - BaseClass = "Spark.SparkViewBase", - Descriptor = new SparkViewDescriptor { TargetNamespace = "Testing.Target.Namespace" } - }; - DoCompileView(compiler, new Chunk[] { new SendLiteralChunk { Text = "Hello" } }); - var instance = compiler.CreateInstance(); - Assert.AreEqual("Testing.Target.Namespace", instance.GetType().Namespace); - - } - - - [Test] - public void ProvideFullException() - { - var compiler = new CSharpViewCompiler { BaseClass = "Spark.SparkViewBase" }; - Assert.That(() => - DoCompileView(compiler, new Chunk[] - { - new SendExpressionChunk {Code = "NoSuchVariable"} - }), - Throws.TypeOf()); - } - - [Test] - public void IfTrueCondition() - { - var compiler = new CSharpViewCompiler { BaseClass = "Spark.SparkViewBase" }; - - var trueChunks = new Chunk[] { new SendLiteralChunk { Text = "wastrue" } }; - - DoCompileView(compiler, new Chunk[] - { - new SendLiteralChunk {Text = "

"}, - new LocalVariableChunk{Name="arg", Value="5"}, - new ConditionalChunk{Type=ConditionalType.If, Condition="arg==5", Body=trueChunks}, - new SendLiteralChunk {Text = "

"} - }); - var instance = compiler.CreateInstance(); - var contents = instance.RenderView(); - Assert.AreEqual("

wastrue

", contents); - } - - [Test] - public void IfFalseCondition() - { - var compiler = new CSharpViewCompiler { BaseClass = "Spark.SparkViewBase" }; - - var trueChunks = new Chunk[] { new SendLiteralChunk { Text = "wastrue" } }; - - DoCompileView(compiler, new Chunk[] - { - new SendLiteralChunk {Text = "

"}, - new LocalVariableChunk{Name="arg", Value="5"}, - new ConditionalChunk{Type=ConditionalType.If, Condition="arg==6", Body=trueChunks}, - new SendLiteralChunk {Text = "

"} - }); - var instance = compiler.CreateInstance(); - var contents = instance.RenderView(); - Assert.AreEqual("

", contents); - } - - [Test] - public void IfElseFalseCondition() - { - var compiler = new CSharpViewCompiler { BaseClass = "Spark.SparkViewBase" }; - - var trueChunks = new Chunk[] { new SendLiteralChunk { Text = "wastrue" } }; - var falseChunks = new Chunk[] { new SendLiteralChunk { Text = "wasfalse" } }; - - DoCompileView(compiler, new Chunk[] - { - new SendLiteralChunk {Text = "

"}, - new LocalVariableChunk{Name="arg", Value="5"}, - new ConditionalChunk{Type=ConditionalType.If, Condition="arg==6", Body=trueChunks}, - new ConditionalChunk{Type=ConditionalType.Else, Body=falseChunks}, - new SendLiteralChunk {Text = "

"} - }); - var instance = compiler.CreateInstance(); - var contents = instance.RenderView(); - Assert.AreEqual("

wasfalse

", contents); - } - - [Test] - public void UnlessTrueCondition() - { - var compiler = new CSharpViewCompiler { BaseClass = "Spark.SparkViewBase" }; - - var trueChunks = new Chunk[] { new SendLiteralChunk { Text = "wastrue" } }; - - DoCompileView(compiler, new Chunk[] - { - new SendLiteralChunk {Text = "

"}, - new LocalVariableChunk{Name="arg", Value="5"}, - new ConditionalChunk{Type=ConditionalType.Unless, Condition="arg==5", Body=trueChunks}, - new SendLiteralChunk {Text = "

"} - }); - var instance = compiler.CreateInstance(); - var contents = instance.RenderView(); - Assert.AreEqual("

", contents); - } - - [Test] - public void UnlessFalseCondition() - { - var compiler = new CSharpViewCompiler { BaseClass = "Spark.SparkViewBase" }; - - var trueChunks = new Chunk[] { new SendLiteralChunk { Text = "wastrue" } }; - - DoCompileView(compiler, new Chunk[] - { - new SendLiteralChunk {Text = "

"}, - new LocalVariableChunk{Name="arg", Value="5"}, - new ConditionalChunk{Type=ConditionalType.Unless, Condition="arg==6", Body=trueChunks}, - new SendLiteralChunk {Text = "

"} - }); - var instance = compiler.CreateInstance(); - var contents = instance.RenderView(); - Assert.AreEqual("

wastrue

", contents); - } - - [Test] - public void LenientSilentNullDoesNotCauseWarningCS0168() - { - var compiler = new CSharpViewCompiler() - { - BaseClass = "Spark.Tests.Stubs.StubSparkView", - NullBehaviour = NullBehaviour.Lenient - }; - var chunks = new Chunk[] - { - new ViewDataChunk { Name="comment", Type="Spark.Tests.Models.Comment"}, - new SendExpressionChunk {Code = "comment.Text", SilentNulls = true} - }; - compiler.CompileView(new[] { chunks }, new[] { chunks }); - Assert.That(compiler.SourceCode.Contains("catch(System.NullReferenceException)")); - } - - [Test] - public void LenientOutputNullDoesNotCauseWarningCS0168() - { - var compiler = new CSharpViewCompiler() - { - BaseClass = "Spark.Tests.Stubs.StubSparkView", - NullBehaviour = NullBehaviour.Lenient - }; - var chunks = new Chunk[] - { - new ViewDataChunk { Name="comment", Type="Spark.Tests.Models.Comment"}, - new SendExpressionChunk {Code = "comment.Text", SilentNulls = false} - }; - compiler.CompileView(new[] { chunks }, new[] { chunks }); - Assert.That(compiler.SourceCode.Contains("catch(System.NullReferenceException)")); - } - - [Test] - public void StrictNullUsesException() - { - var compiler = new CSharpViewCompiler() - { - BaseClass = "Spark.Tests.Stubs.StubSparkView", - NullBehaviour = NullBehaviour.Strict - }; - var chunks = new Chunk[] - { - new ViewDataChunk { Name="comment", Type="Spark.Tests.Models.Comment"}, - new SendExpressionChunk {Code = "comment.Text", SilentNulls = false} - }; - compiler.CompileView(new[] { chunks }, new[] { chunks }); - Assert.That(compiler.SourceCode.Contains("catch(System.NullReferenceException ex)")); - Assert.That(compiler.SourceCode.Contains("ArgumentNullException(")); - Assert.That(compiler.SourceCode.Contains(", ex);")); - } - - [Test] - public void PageBaseTypeOverridesBaseClass() - { - var compiler = new CSharpViewCompiler() - { - BaseClass = "Spark.Tests.Stubs.StubSparkView", - NullBehaviour = NullBehaviour.Strict - }; - DoCompileView(compiler, new Chunk[] - { - new PageBaseTypeChunk { BaseClass="Spark.Tests.Stubs.StubSparkView2"}, - new SendLiteralChunk{ Text = "Hello world"} - }); - var instance = compiler.CreateInstance(); - Assert.That(instance, Is.InstanceOf(typeof(StubSparkView2))); - } - - - [Test] - public void PageBaseTypeWorksWithOptionalModel() - { - var compiler = new CSharpViewCompiler() - { - BaseClass = "Spark.Tests.Stubs.StubSparkView", - NullBehaviour = NullBehaviour.Strict - }; - DoCompileView(compiler, new Chunk[] - { - new PageBaseTypeChunk {BaseClass = "Spark.Tests.Stubs.StubSparkView2"}, - new ViewDataModelChunk {TModel = "Spark.Tests.Models.Comment"}, - new SendLiteralChunk {Text = "Hello world"} - }); - var instance = compiler.CreateInstance(); - Assert.That(instance, Is.InstanceOf(typeof(StubSparkView2))); - Assert.That(instance, Is.InstanceOf(typeof(StubSparkView2))); - } - - [Test] - public void PageBaseTypeWorksWithGenericParametersIncluded() - { - var compiler = new CSharpViewCompiler() - { - BaseClass = "Spark.Tests.Stubs.StubSparkView", - NullBehaviour = NullBehaviour.Strict - }; - DoCompileView(compiler, new Chunk[] - { - new PageBaseTypeChunk {BaseClass = "Spark.Tests.Stubs.StubSparkView3"}, - new SendLiteralChunk {Text = "Hello world"} - }); - var instance = compiler.CreateInstance(); - Assert.That(instance, Is.InstanceOf(typeof(StubSparkView2))); - Assert.That(instance, Is.InstanceOf(typeof(StubSparkView2))); - Assert.That(instance, Is.InstanceOf(typeof(StubSparkView3))); - } - - [Test] - public void Markdown() - { - var compiler = new CSharpViewCompiler { BaseClass = "Spark.SparkViewBase" }; - - var innerChunks = new Chunk[] { new SendLiteralChunk { Text = "*test*" } }; - - DoCompileView(compiler, new Chunk[] - { - new MarkdownChunk {Body = innerChunks} - }); - - Assert.That(compiler.SourceCode, Does.Contain("using(MarkdownOutputScope())")); - Assert.That(compiler.SourceCode, Does.Contain("Output.Write(\"*test*\");")); - - var instance = compiler.CreateInstance(); - var contents = instance.RenderView().Trim(); - - Assert.That(contents, Is.EqualTo("

test

")); - } - } +// Copyright 2008-2009 Louis DeJardin - http://whereslou.com +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +using System.Collections.Generic; + +using Spark.Compiler; +using NUnit.Framework; +using Spark.Compiler.CSharp; +using Spark.Tests.Models; +using Spark.Tests.Stubs; + +namespace Spark.Tests.Compiler +{ + [TestFixture] + public class CSharpViewCompilerTester + { + + [SetUp] + public void Init() + { + } + + private static void DoCompileView(ViewCompiler compiler, IList chunks) + { + compiler.CompileView(new[] { chunks }, new[] { chunks }); + } + + [Test] + public void MakeAndCompile() + { + var compiler = new CSharpViewCompiler { BaseClass = "Spark.SparkViewBase" }; + + DoCompileView(compiler, new[] { new SendLiteralChunk { Text = "hello world" } }); + + var instance = compiler.CreateInstance(); + string contents = instance.RenderView(); + + Assert.That(contents.Contains("hello world")); + } + + + [Test] + public void UnsafeLiteralCharacters() + { + var text = "hello\t\r\n\"world"; + var compiler = new CSharpViewCompiler { BaseClass = "Spark.SparkViewBase" }; + DoCompileView(compiler, new[] { new SendLiteralChunk { Text = text } }); + + Assert.That(compiler.SourceCode.Contains("Write(\"hello\\t\\r\\n\\\"world\")")); + + var instance = compiler.CreateInstance(); + string contents = instance.RenderView(); + + Assert.AreEqual(text, contents); + } + + [Test] + public void SimpleOutput() + { + var compiler = new CSharpViewCompiler { BaseClass = "Spark.SparkViewBase" }; + DoCompileView(compiler, new[] { new SendExpressionChunk { Code = "3 + 4" } }); + var instance = compiler.CreateInstance(); + string contents = instance.RenderView(); + Assert.AreEqual("7", contents); + } + + [Test] + public void LocalVariableDecl() + { + var compiler = new CSharpViewCompiler { BaseClass = "Spark.SparkViewBase" }; + DoCompileView(compiler, new Chunk[] + { + new LocalVariableChunk { Name = "i", Value = "5" }, + new SendExpressionChunk { Code = "i" } + }); + var instance = compiler.CreateInstance(); + string contents = instance.RenderView(); + + Assert.AreEqual("5", contents); + } + + [Test] + public void ForEachLoop() + { + var compiler = new CSharpViewCompiler { BaseClass = "Spark.SparkViewBase" }; + DoCompileView(compiler, new Chunk[] + { + new LocalVariableChunk {Name = "data", Value = "new[]{3,4,5}"}, + new SendLiteralChunk {Text = "
    "}, + new ForEachChunk + { + Code = "var item in data", + Body = new Chunk[] + { + new SendLiteralChunk {Text = "
  • "}, + new SendExpressionChunk {Code = "item"}, + new SendLiteralChunk {Text = "
  • "} + } + }, + new SendLiteralChunk {Text = "
"} + }); + var instance = compiler.CreateInstance(); + var contents = instance.RenderView(); + Assert.AreEqual("
  • 3
  • 4
  • 5
", contents); + } + + [Test] + public void GlobalVariables() + { + var compiler = new CSharpViewCompiler { BaseClass = "Spark.SparkViewBase" }; + DoCompileView(compiler, new Chunk[] + { + new SendExpressionChunk{Code="title"}, + new AssignVariableChunk{ Name="item", Value="8"}, + new SendLiteralChunk{ Text=":"}, + new SendExpressionChunk{Code="item"}, + new GlobalVariableChunk{ Name="title", Value="\"hello world\""}, + new GlobalVariableChunk{ Name="item", Value="3"} + }); + var instance = compiler.CreateInstance(); + var contents = instance.RenderView(); + Assert.AreEqual("hello world:8", contents); + } + + [Test] + public void TargetNamespace() + { + var compiler = new CSharpViewCompiler + { + BaseClass = "Spark.SparkViewBase", + Descriptor = new SparkViewDescriptor { TargetNamespace = "Testing.Target.Namespace" } + }; + DoCompileView(compiler, new Chunk[] { new SendLiteralChunk { Text = "Hello" } }); + var instance = compiler.CreateInstance(); + Assert.AreEqual("Testing.Target.Namespace", instance.GetType().Namespace); + + } + + + [Test] + public void ProvideFullException() + { + var compiler = new CSharpViewCompiler { BaseClass = "Spark.SparkViewBase" }; + Assert.That(() => + DoCompileView(compiler, new Chunk[] + { + new SendExpressionChunk {Code = "NoSuchVariable"} + }), + Throws.TypeOf()); + } + + [Test] + public void IfTrueCondition() + { + var compiler = new CSharpViewCompiler { BaseClass = "Spark.SparkViewBase" }; + + var trueChunks = new Chunk[] { new SendLiteralChunk { Text = "wastrue" } }; + + DoCompileView(compiler, new Chunk[] + { + new SendLiteralChunk {Text = "

"}, + new LocalVariableChunk{Name="arg", Value="5"}, + new ConditionalChunk{Type=ConditionalType.If, Condition="arg==5", Body=trueChunks}, + new SendLiteralChunk {Text = "

"} + }); + var instance = compiler.CreateInstance(); + var contents = instance.RenderView(); + Assert.AreEqual("

wastrue

", contents); + } + + [Test] + public void IfFalseCondition() + { + var compiler = new CSharpViewCompiler { BaseClass = "Spark.SparkViewBase" }; + + var trueChunks = new Chunk[] { new SendLiteralChunk { Text = "wastrue" } }; + + DoCompileView(compiler, new Chunk[] + { + new SendLiteralChunk {Text = "

"}, + new LocalVariableChunk{Name="arg", Value="5"}, + new ConditionalChunk{Type=ConditionalType.If, Condition="arg==6", Body=trueChunks}, + new SendLiteralChunk {Text = "

"} + }); + var instance = compiler.CreateInstance(); + var contents = instance.RenderView(); + Assert.AreEqual("

", contents); + } + + [Test] + public void IfElseFalseCondition() + { + var compiler = new CSharpViewCompiler { BaseClass = "Spark.SparkViewBase" }; + + var trueChunks = new Chunk[] { new SendLiteralChunk { Text = "wastrue" } }; + var falseChunks = new Chunk[] { new SendLiteralChunk { Text = "wasfalse" } }; + + DoCompileView(compiler, new Chunk[] + { + new SendLiteralChunk {Text = "

"}, + new LocalVariableChunk{Name="arg", Value="5"}, + new ConditionalChunk{Type=ConditionalType.If, Condition="arg==6", Body=trueChunks}, + new ConditionalChunk{Type=ConditionalType.Else, Body=falseChunks}, + new SendLiteralChunk {Text = "

"} + }); + var instance = compiler.CreateInstance(); + var contents = instance.RenderView(); + Assert.AreEqual("

wasfalse

", contents); + } + + [Test] + public void UnlessTrueCondition() + { + var compiler = new CSharpViewCompiler { BaseClass = "Spark.SparkViewBase" }; + + var trueChunks = new Chunk[] { new SendLiteralChunk { Text = "wastrue" } }; + + DoCompileView(compiler, new Chunk[] + { + new SendLiteralChunk {Text = "

"}, + new LocalVariableChunk{Name="arg", Value="5"}, + new ConditionalChunk{Type=ConditionalType.Unless, Condition="arg==5", Body=trueChunks}, + new SendLiteralChunk {Text = "

"} + }); + var instance = compiler.CreateInstance(); + var contents = instance.RenderView(); + Assert.AreEqual("

", contents); + } + + [Test] + public void UnlessFalseCondition() + { + var compiler = new CSharpViewCompiler { BaseClass = "Spark.SparkViewBase" }; + + var trueChunks = new Chunk[] { new SendLiteralChunk { Text = "wastrue" } }; + + DoCompileView(compiler, new Chunk[] + { + new SendLiteralChunk {Text = "

"}, + new LocalVariableChunk{Name="arg", Value="5"}, + new ConditionalChunk{Type=ConditionalType.Unless, Condition="arg==6", Body=trueChunks}, + new SendLiteralChunk {Text = "

"} + }); + var instance = compiler.CreateInstance(); + var contents = instance.RenderView(); + Assert.AreEqual("

wastrue

", contents); + } + + [Test] + public void LenientSilentNullDoesNotCauseWarningCS0168() + { + var compiler = new CSharpViewCompiler() + { + BaseClass = "Spark.Tests.Stubs.StubSparkView", + NullBehaviour = NullBehaviour.Lenient + }; + var chunks = new Chunk[] + { + new ViewDataChunk { Name="comment", Type="Spark.Tests.Models.Comment"}, + new SendExpressionChunk {Code = "comment.Text", SilentNulls = true} + }; + compiler.CompileView(new[] { chunks }, new[] { chunks }); + Assert.That(compiler.SourceCode.Contains("catch(System.NullReferenceException)")); + } + + [Test] + public void LenientOutputNullDoesNotCauseWarningCS0168() + { + var compiler = new CSharpViewCompiler() + { + BaseClass = "Spark.Tests.Stubs.StubSparkView", + NullBehaviour = NullBehaviour.Lenient + }; + var chunks = new Chunk[] + { + new ViewDataChunk { Name="comment", Type="Spark.Tests.Models.Comment"}, + new SendExpressionChunk {Code = "comment.Text", SilentNulls = false} + }; + compiler.CompileView(new[] { chunks }, new[] { chunks }); + Assert.That(compiler.SourceCode.Contains("catch(System.NullReferenceException)")); + } + + [Test] + public void StrictNullUsesException() + { + var compiler = new CSharpViewCompiler() + { + BaseClass = "Spark.Tests.Stubs.StubSparkView", + NullBehaviour = NullBehaviour.Strict + }; + var chunks = new Chunk[] + { + new ViewDataChunk { Name="comment", Type="Spark.Tests.Models.Comment"}, + new SendExpressionChunk {Code = "comment.Text", SilentNulls = false} + }; + compiler.CompileView(new[] { chunks }, new[] { chunks }); + Assert.That(compiler.SourceCode.Contains("catch(System.NullReferenceException ex)")); + Assert.That(compiler.SourceCode.Contains("ArgumentNullException(")); + Assert.That(compiler.SourceCode.Contains(", ex);")); + } + + [Test] + public void PageBaseTypeOverridesBaseClass() + { + var compiler = new CSharpViewCompiler() + { + BaseClass = "Spark.Tests.Stubs.StubSparkView", + NullBehaviour = NullBehaviour.Strict + }; + DoCompileView(compiler, new Chunk[] + { + new PageBaseTypeChunk { BaseClass="Spark.Tests.Stubs.StubSparkView2"}, + new SendLiteralChunk{ Text = "Hello world"} + }); + var instance = compiler.CreateInstance(); + Assert.That(instance, Is.InstanceOf(typeof(StubSparkView2))); + } + + + [Test] + public void PageBaseTypeWorksWithOptionalModel() + { + var compiler = new CSharpViewCompiler() + { + BaseClass = "Spark.Tests.Stubs.StubSparkView", + NullBehaviour = NullBehaviour.Strict + }; + DoCompileView(compiler, new Chunk[] + { + new PageBaseTypeChunk {BaseClass = "Spark.Tests.Stubs.StubSparkView2"}, + new ViewDataModelChunk {TModel = "Spark.Tests.Models.Comment"}, + new SendLiteralChunk {Text = "Hello world"} + }); + var instance = compiler.CreateInstance(); + Assert.That(instance, Is.InstanceOf(typeof(StubSparkView2))); + Assert.That(instance, Is.InstanceOf(typeof(StubSparkView2))); + } + + [Test] + public void PageBaseTypeWorksWithGenericParametersIncluded() + { + var compiler = new CSharpViewCompiler() + { + BaseClass = "Spark.Tests.Stubs.StubSparkView", + NullBehaviour = NullBehaviour.Strict + }; + DoCompileView(compiler, new Chunk[] + { + new PageBaseTypeChunk {BaseClass = "Spark.Tests.Stubs.StubSparkView3"}, + new SendLiteralChunk {Text = "Hello world"} + }); + var instance = compiler.CreateInstance(); + Assert.That(instance, Is.InstanceOf(typeof(StubSparkView2))); + Assert.That(instance, Is.InstanceOf(typeof(StubSparkView2))); + Assert.That(instance, Is.InstanceOf(typeof(StubSparkView3))); + } + + [Test] + public void Markdown() + { + var compiler = new CSharpViewCompiler { BaseClass = "Spark.SparkViewBase" }; + + var innerChunks = new Chunk[] { new SendLiteralChunk { Text = "*test*" } }; + + DoCompileView(compiler, new Chunk[] + { + new MarkdownChunk {Body = innerChunks} + }); + + Assert.That(compiler.SourceCode, Does.Contain("using(MarkdownOutputScope())")); + Assert.That(compiler.SourceCode, Does.Contain("Output.Write(\"*test*\");")); + + var instance = compiler.CreateInstance(); + var contents = instance.RenderView().Trim(); + + Assert.That(contents, Is.EqualTo("

test

")); + } + } } \ No newline at end of file diff --git a/src/Spark.Tests/Compiler/SourceMappingTester.cs b/src/Spark.Web.Tests/Compiler/SourceMappingTester.cs similarity index 95% rename from src/Spark.Tests/Compiler/SourceMappingTester.cs rename to src/Spark.Web.Tests/Compiler/SourceMappingTester.cs index ce0d1af9..5e4cb19f 100644 --- a/src/Spark.Tests/Compiler/SourceMappingTester.cs +++ b/src/Spark.Web.Tests/Compiler/SourceMappingTester.cs @@ -1,157 +1,152 @@ -// Copyright 2008-2009 Louis DeJardin - http://whereslou.com -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using NUnit.Framework; - -using Spark.FileSystem; -using Spark.Tests.Stubs; -using System.IO; - -namespace Spark.Tests.Compiler -{ - [TestFixture] - public class SourceMappingTester - { - private ISparkViewEngine _engine; - private InMemoryViewFolder _viewFolder; - private ISparkViewEntry _entry; - - [SetUp] - public void Init() - { - var settings = new SparkSettings() - .SetPageBaseType(typeof(StubSparkView)); - var container = new SparkServiceContainer(settings); - - _viewFolder = new InMemoryViewFolder(); - - container.SetServiceBuilder(c => _viewFolder); - - _engine = container.GetService(); - } - - private string RenderView(SparkViewDescriptor descriptor) - { - _entry = _engine.CreateEntry(descriptor); - var view = _entry.CreateInstance(); - var contents = view.RenderView(); - _engine.ReleaseInstance(view); - return contents; - } - - [Test] - public void SimpleExpressionsEntirelyMapped() - { - _viewFolder.Add(Path.Combine("Home", "Index.spark"), "

Hello ${\"world\"}

"); - - var contents = RenderView(new SparkViewDescriptor() - .AddTemplate(Path.Combine("Home", "Index.spark"))); - - Assert.AreEqual("

Hello world

", contents); - Assert.AreEqual(1, _entry.SourceMappings.Count); - Assert.AreEqual("\"world\"", _entry.SourceMappings[0].Source.Value); - Assert.AreEqual(Path.Combine("Home", "Index.spark"), _entry.SourceMappings[0].Source.Begin.SourceContext.FileName); - Assert.AreEqual(11, _entry.SourceMappings[0].Source.Begin.Offset); - - var resultOffset = _entry.SourceMappings[0].OutputBegin; - var resultLength = _entry.SourceMappings[0].OutputEnd - _entry.SourceMappings[0].OutputBegin; - Assert.AreEqual("\"world\"", _entry.SourceCode.Substring(resultOffset, resultLength)); - } - - [Test] - public void EmbeddedCodeMapped() - { - _viewFolder.Add(Path.Combine("Home", "Index.spark"), "

<%var x = 5;%>${x}

"); - - var contents = RenderView(new SparkViewDescriptor() - .AddTemplate(Path.Combine("Home", "Index.spark"))); - - Assert.AreEqual("

5

", contents); - Assert.AreEqual(2, _entry.SourceMappings.Count); - Assert.AreEqual("var x = 5;", _entry.SourceMappings[0].Source.Value); - Assert.AreEqual(Path.Combine("Home", "Index.spark"), _entry.SourceMappings[0].Source.Begin.SourceContext.FileName); - Assert.AreEqual(5, _entry.SourceMappings[0].Source.Begin.Offset); - - var resultOffset = _entry.SourceMappings[0].OutputBegin; - var resultLength = _entry.SourceMappings[0].OutputEnd - _entry.SourceMappings[0].OutputBegin; - Assert.AreEqual("var x = 5;", _entry.SourceCode.Substring(resultOffset, resultLength)); - } - - - [Test] - public void ExpressionInAttributeMapped() - { - _viewFolder.Add(Path.Combine("Home", "Index.spark"), "

World

"); - - var contents = RenderView(new SparkViewDescriptor() - .AddTemplate(Path.Combine("Home", "Index.spark"))); - - Assert.AreEqual("

World

", contents); - Assert.AreEqual(1, _entry.SourceMappings.Count); - Assert.AreEqual("\"Hello\"", _entry.SourceMappings[0].Source.Value); - Assert.AreEqual(Path.Combine("Home", "Index.spark"), _entry.SourceMappings[0].Source.Begin.SourceContext.FileName); - Assert.AreEqual(12, _entry.SourceMappings[0].Source.Begin.Offset); - - var resultOffset = _entry.SourceMappings[0].OutputBegin; - var resultLength = _entry.SourceMappings[0].OutputEnd - _entry.SourceMappings[0].OutputBegin; - Assert.AreEqual("\"Hello\"", _entry.SourceCode.Substring(resultOffset, resultLength)); - } - - [Test] - public void SingleQuotesAreAvoided() - { - _viewFolder.Add(Path.Combine("Home", "Index.spark"), "

World

"); - - var contents = RenderView(new SparkViewDescriptor() - .AddTemplate(Path.Combine("Home", "Index.spark"))); - - Assert.AreEqual("

World

", contents); - Assert.AreEqual(2, _entry.SourceMappings.Count); - Assert.AreEqual("Hello", _entry.SourceMappings[0].Source.Value); - Assert.AreEqual(Path.Combine("Home", "Index.spark"), _entry.SourceMappings[0].Source.Begin.SourceContext.FileName); - Assert.AreEqual(13, _entry.SourceMappings[0].Source.Begin.Offset); - - Assert.AreEqual(" + 5", _entry.SourceMappings[1].Source.Value); - Assert.AreEqual(Path.Combine("Home", "Index.spark"), _entry.SourceMappings[1].Source.Begin.SourceContext.FileName); - Assert.AreEqual(19, _entry.SourceMappings[1].Source.Begin.Offset); - - var resultOffset = _entry.SourceMappings[0].OutputBegin; - var resultLength = _entry.SourceMappings[0].OutputEnd - _entry.SourceMappings[0].OutputBegin; - Assert.AreEqual("Hello", _entry.SourceCode.Substring(resultOffset, resultLength)); - - resultOffset = _entry.SourceMappings[1].OutputBegin; - resultLength = _entry.SourceMappings[1].OutputEnd - _entry.SourceMappings[1].OutputBegin; - Assert.AreEqual(" + 5", _entry.SourceCode.Substring(resultOffset, resultLength)); - } - - [Test] - public void WarningsShouldNotCauseCompilationToFail() { - _viewFolder.Add(Path.Combine("Home", "Index.spark"), @" -

-## warning I am a warning -Hello -

"); - - var contents = RenderView(new SparkViewDescriptor() - .AddTemplate(Path.Combine("Home", "Index.spark"))); - - Assert.That(contents, Does.Contain("Hello")); - Assert.That(contents, Is.Not.StringContaining("warning")); - } - } +// Copyright 2008-2009 Louis DeJardin - http://whereslou.com +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +using NUnit.Framework; +using Spark.FileSystem; +using Spark.Tests.Stubs; +using System.IO; + +namespace Spark.Tests.Compiler +{ + [TestFixture] + public class SourceMappingTester + { + private ISparkViewEngine _engine; + private InMemoryViewFolder _viewFolder; + private ISparkViewEntry _entry; + + [SetUp] + public void Init() + { + var settings = new SparkSettings() + .SetPageBaseType(typeof(StubSparkView)); + var container = new SparkServiceContainer(settings); + + _viewFolder = new InMemoryViewFolder(); + + container.SetServiceBuilder(c => _viewFolder); + + _engine = container.GetService(); + } + + private string RenderView(SparkViewDescriptor descriptor) + { + _entry = _engine.CreateEntry(descriptor); + var view = _entry.CreateInstance(); + var contents = view.RenderView(); + _engine.ReleaseInstance(view); + return contents; + } + + [Test] + public void SimpleExpressionsEntirelyMapped() + { + _viewFolder.Add(Path.Combine("Home", "Index.spark"), "

Hello ${\"world\"}

"); + + var contents = RenderView(new SparkViewDescriptor() + .AddTemplate(Path.Combine("Home", "Index.spark"))); + + Assert.AreEqual("

Hello world

", contents); + Assert.AreEqual(1, _entry.SourceMappings.Count); + Assert.AreEqual("\"world\"", _entry.SourceMappings[0].Source.Value); + Assert.AreEqual(Path.Combine("Home", "Index.spark"), _entry.SourceMappings[0].Source.Begin.SourceContext.FileName); + Assert.AreEqual(11, _entry.SourceMappings[0].Source.Begin.Offset); + + var resultOffset = _entry.SourceMappings[0].OutputBegin; + var resultLength = _entry.SourceMappings[0].OutputEnd - _entry.SourceMappings[0].OutputBegin; + Assert.AreEqual("\"world\"", _entry.SourceCode.Substring(resultOffset, resultLength)); + } + + [Test] + public void EmbeddedCodeMapped() + { + _viewFolder.Add(Path.Combine("Home", "Index.spark"), "

<%var x = 5;%>${x}

"); + + var contents = RenderView(new SparkViewDescriptor() + .AddTemplate(Path.Combine("Home", "Index.spark"))); + + Assert.AreEqual("

5

", contents); + Assert.AreEqual(2, _entry.SourceMappings.Count); + Assert.AreEqual("var x = 5;", _entry.SourceMappings[0].Source.Value); + Assert.AreEqual(Path.Combine("Home", "Index.spark"), _entry.SourceMappings[0].Source.Begin.SourceContext.FileName); + Assert.AreEqual(5, _entry.SourceMappings[0].Source.Begin.Offset); + + var resultOffset = _entry.SourceMappings[0].OutputBegin; + var resultLength = _entry.SourceMappings[0].OutputEnd - _entry.SourceMappings[0].OutputBegin; + Assert.AreEqual("var x = 5;", _entry.SourceCode.Substring(resultOffset, resultLength)); + } + + + [Test] + public void ExpressionInAttributeMapped() + { + _viewFolder.Add(Path.Combine("Home", "Index.spark"), "

World

"); + + var contents = RenderView(new SparkViewDescriptor() + .AddTemplate(Path.Combine("Home", "Index.spark"))); + + Assert.AreEqual("

World

", contents); + Assert.AreEqual(1, _entry.SourceMappings.Count); + Assert.AreEqual("\"Hello\"", _entry.SourceMappings[0].Source.Value); + Assert.AreEqual(Path.Combine("Home", "Index.spark"), _entry.SourceMappings[0].Source.Begin.SourceContext.FileName); + Assert.AreEqual(12, _entry.SourceMappings[0].Source.Begin.Offset); + + var resultOffset = _entry.SourceMappings[0].OutputBegin; + var resultLength = _entry.SourceMappings[0].OutputEnd - _entry.SourceMappings[0].OutputBegin; + Assert.AreEqual("\"Hello\"", _entry.SourceCode.Substring(resultOffset, resultLength)); + } + + [Test] + public void SingleQuotesAreAvoided() + { + _viewFolder.Add(Path.Combine("Home", "Index.spark"), "

World

"); + + var contents = RenderView(new SparkViewDescriptor() + .AddTemplate(Path.Combine("Home", "Index.spark"))); + + Assert.AreEqual("

World

", contents); + Assert.AreEqual(2, _entry.SourceMappings.Count); + Assert.AreEqual("Hello", _entry.SourceMappings[0].Source.Value); + Assert.AreEqual(Path.Combine("Home", "Index.spark"), _entry.SourceMappings[0].Source.Begin.SourceContext.FileName); + Assert.AreEqual(13, _entry.SourceMappings[0].Source.Begin.Offset); + + Assert.AreEqual(" + 5", _entry.SourceMappings[1].Source.Value); + Assert.AreEqual(Path.Combine("Home", "Index.spark"), _entry.SourceMappings[1].Source.Begin.SourceContext.FileName); + Assert.AreEqual(19, _entry.SourceMappings[1].Source.Begin.Offset); + + var resultOffset = _entry.SourceMappings[0].OutputBegin; + var resultLength = _entry.SourceMappings[0].OutputEnd - _entry.SourceMappings[0].OutputBegin; + Assert.AreEqual("Hello", _entry.SourceCode.Substring(resultOffset, resultLength)); + + resultOffset = _entry.SourceMappings[1].OutputBegin; + resultLength = _entry.SourceMappings[1].OutputEnd - _entry.SourceMappings[1].OutputBegin; + Assert.AreEqual(" + 5", _entry.SourceCode.Substring(resultOffset, resultLength)); + } + + [Test] + public void WarningsShouldNotCauseCompilationToFail() { + _viewFolder.Add(Path.Combine("Home", "Index.spark"), @" +

+## warning I am a warning +Hello +

"); + + var contents = RenderView(new SparkViewDescriptor() + .AddTemplate(Path.Combine("Home", "Index.spark"))); + + Assert.That(contents, Does.Contain("Hello")); + Assert.That(contents, Does.Not.Contains("warning")); + } + } } \ No newline at end of file diff --git a/src/Spark.Tests/Compiler/VisualBasicViewCompilerTester.cs b/src/Spark.Web.Tests/Compiler/VisualBasicViewCompilerTester.cs similarity index 97% rename from src/Spark.Tests/Compiler/VisualBasicViewCompilerTester.cs rename to src/Spark.Web.Tests/Compiler/VisualBasicViewCompilerTester.cs index 9f28a9ab..6efc5d21 100644 --- a/src/Spark.Tests/Compiler/VisualBasicViewCompilerTester.cs +++ b/src/Spark.Web.Tests/Compiler/VisualBasicViewCompilerTester.cs @@ -1,425 +1,425 @@ -// Copyright 2008-2009 Louis DeJardin - http://whereslou.com -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// -using System; -using System.Collections.Generic; - -using Spark.Compiler; -using NUnit.Framework; -using Spark.Compiler.VisualBasic; -using Spark.Tests.Models; -using Spark.Tests.Stubs; - -namespace Spark.Tests.Compiler -{ - [TestFixture] - public class VisualBasicViewCompilerTester - { - - [SetUp] - public void Init() - { - } - - private static void DoCompileView(ViewCompiler compiler, IList chunks) - { - compiler.CompileView(new[] { chunks }, new[] { chunks }); - } - - [Test] - public void MakeAndCompile() - { - var compiler = CreateCompiler(); - - DoCompileView(compiler, new[] { new SendLiteralChunk { Text = "hello world" } }); - - var instance = compiler.CreateInstance(); - string contents = instance.RenderView(); - - Assert.That(contents.Contains("hello world")); - } - - [Test] - public void StronglyTypedBase() - { - var compiler = new VisualBasicViewCompiler { BaseClass = "Spark.Tests.Stubs.StubSparkView" }; - - DoCompileView(compiler, new Chunk[] - { - new SendLiteralChunk { Text = "hello world" }, - new ViewDataModelChunk { TModel="Global.System.String"} - }); - - var instance = compiler.CreateInstance(); - string contents = instance.RenderView(); - - Assert.That(contents.Contains("hello world")); - } - - [Test] - public void UnsafeLiteralCharacters() - { - var text = "hello\t\r\n\"world"; - var compiler = CreateCompiler(); - DoCompileView(compiler, new[] { new SendLiteralChunk { Text = text } }); - - Assert.That(compiler.SourceCode.Contains("Write(\"hello")); - - var instance = compiler.CreateInstance(); - string contents = instance.RenderView(); - - Assert.That(contents, Is.EqualTo(text)); - } - - private static VisualBasicViewCompiler CreateCompiler() - { - return new VisualBasicViewCompiler - { - BaseClass = "Spark.AbstractSparkView", - UseAssemblies = new[] { "Microsoft.VisualBasic, Version=8.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" }, - UseNamespaces = new[] { "Microsoft.VisualBasic" } - }; - } - - [Test] - public void SimpleOutput() - { - var compiler = new VisualBasicViewCompiler { BaseClass = "Spark.AbstractSparkView" }; - DoCompileView(compiler, new[] { new SendExpressionChunk { Code = "3 + 4" } }); - var instance = compiler.CreateInstance(); - string contents = instance.RenderView(); - Assert.AreEqual("7", contents); - } - - [Test] - public void LenientNullBehavior() - { - var compiler = CreateCompiler(); - - DoCompileView(compiler, new[] { new SendExpressionChunk { Code = "CType(Nothing, String).Length" } }); - var instance = compiler.CreateInstance(); - var contents = instance.RenderView(); - Assert.That(contents, Is.EqualTo("${CType(Nothing, String).Length}")); - } - - [Test] - public void SilentNullBehavior() - { - var compiler = CreateCompiler(); - - DoCompileView(compiler, new[] { new SendExpressionChunk { Code = "CType(Nothing, String).Length", SilentNulls = true } }); - var instance = compiler.CreateInstance(); - var contents = instance.RenderView(); - Assert.That(contents, Is.EqualTo("")); - } - - [Test] - public void RethrowNullBehavior() - { - var compiler = CreateCompiler(); - compiler.NullBehaviour = NullBehaviour.Strict; - - DoCompileView(compiler, new[] { new SendExpressionChunk { Code = "CType(Nothing, String).Length" } }); - var instance = compiler.CreateInstance(); - Assert.That(() => instance.RenderView(), Throws.TypeOf()); - } - - [Test] - public void LocalVariableDecl() - { - var compiler = new VisualBasicViewCompiler { BaseClass = "Spark.AbstractSparkView" }; - DoCompileView(compiler, new Chunk[] - { - new LocalVariableChunk { Name = "i", Value = "5" }, - new SendExpressionChunk { Code = "i" } - }); - var instance = compiler.CreateInstance(); - string contents = instance.RenderView(); - - Assert.AreEqual("5", contents); - } - - [Test] - public void ForEachLoop() - { - var compiler = new VisualBasicViewCompiler { BaseClass = "Spark.AbstractSparkView" }; - DoCompileView(compiler, new Chunk[] - { - new LocalVariableChunk {Name = "data", Value = "new Integer(){3,4,5}"}, - new SendLiteralChunk {Text = "
    "}, - new ForEachChunk - { - Code = "item As Integer in data", - Body = new Chunk[] - { - new SendLiteralChunk {Text = "
  • "}, - new SendExpressionChunk {Code = "item"}, - new SendLiteralChunk {Text = "
  • "} - } - }, - new SendLiteralChunk {Text = "
"} - }); - var instance = compiler.CreateInstance(); - var contents = instance.RenderView(); - Assert.AreEqual("
  • 3
  • 4
  • 5
", contents); - } - - [Test] - public void ForEachAutoVariables() - { - var compiler = new VisualBasicViewCompiler { BaseClass = "Spark.AbstractSparkView" }; - DoCompileView(compiler, new Chunk[] - { - new LocalVariableChunk {Name = "data", Value = "new Integer(){3,4,5}"}, - new SendLiteralChunk {Text = "
    "}, - new ForEachChunk - { - Code = "item As Integer in data", - Body = new Chunk[] - { - new SendLiteralChunk {Text = "
  • "}, - new SendExpressionChunk {Code = "item"}, - new SendExpressionChunk {Code = "itemIsFirst"}, - new SendExpressionChunk {Code = "itemIsLast"}, - new SendExpressionChunk {Code = "itemIndex"}, - new SendExpressionChunk {Code = "itemCount"}, - new SendLiteralChunk {Text = "
  • "} - } - }, - new SendLiteralChunk {Text = "
"} - }); - var instance = compiler.CreateInstance(); - var contents = instance.RenderView(); - Assert.AreEqual("
  • 3TrueFalse03
  • 4FalseFalse13
  • 5FalseTrue23
", contents); - } - - [Test] - public void GlobalVariables() - { - var compiler = new VisualBasicViewCompiler { BaseClass = "Spark.AbstractSparkView" }; - DoCompileView(compiler, new Chunk[] - { - new SendExpressionChunk{Code="title"}, - new AssignVariableChunk{ Name="item", Value="8"}, - new SendLiteralChunk{ Text=":"}, - new SendExpressionChunk{Code="item"}, - new GlobalVariableChunk{ Name="title", Value="\"hello world\""}, - new GlobalVariableChunk{ Name="item", Value="3"} - }); - var instance = compiler.CreateInstance(); - var contents = instance.RenderView(); - Assert.AreEqual("hello world:8", contents); - } - - [Test] - [Platform(Exclude = "Mono", Reason = "Problems with Mono-2.10+/Linux and the VB compiler prevent this from running.")] - public void TargetNamespace() - { - var compiler = new VisualBasicViewCompiler - { - BaseClass = "Spark.AbstractSparkView", - Descriptor = new SparkViewDescriptor { TargetNamespace = "Testing.Target.Namespace" } - }; - - DoCompileView(compiler, new Chunk[] { new SendLiteralChunk { Text = "Hello" } }); - var instance = compiler.CreateInstance(); - Assert.AreEqual("Testing.Target.Namespace", instance.GetType().Namespace); - } - - - [Test] - public void ProvideFullException() - { - var compiler = new VisualBasicViewCompiler { BaseClass = "Spark.AbstractSparkView" }; - Assert.That(() => - DoCompileView(compiler, new Chunk[] - { - new SendExpressionChunk {Code = "NoSuchVariable"} - }), - Throws.TypeOf()); - } - - [Test] - public void IfTrueCondition() - { - var compiler = new VisualBasicViewCompiler { BaseClass = "Spark.AbstractSparkView" }; - - var trueChunks = new Chunk[] { new SendLiteralChunk { Text = "wastrue" } }; - - DoCompileView(compiler, new Chunk[] - { - new SendLiteralChunk {Text = "

"}, - new LocalVariableChunk{Name="arg", Value="5"}, - new ConditionalChunk{Type=ConditionalType.If, Condition="arg=5", Body=trueChunks}, - new SendLiteralChunk {Text = "

"} - }); - var instance = compiler.CreateInstance(); - var contents = instance.RenderView(); - Assert.AreEqual("

wastrue

", contents); - } - - [Test] - public void IfFalseCondition() - { - var compiler = new VisualBasicViewCompiler { BaseClass = "Spark.AbstractSparkView" }; - - var trueChunks = new Chunk[] { new SendLiteralChunk { Text = "wastrue" } }; - - DoCompileView(compiler, new Chunk[] - { - new SendLiteralChunk {Text = "

"}, - new LocalVariableChunk{Name="arg", Value="5"}, - new ConditionalChunk{Type=ConditionalType.If, Condition="arg=6", Body=trueChunks}, - new SendLiteralChunk {Text = "

"} - }); - var instance = compiler.CreateInstance(); - var contents = instance.RenderView(); - Assert.AreEqual("

", contents); - } - - [Test] - public void IfElseFalseCondition() - { - var compiler = new VisualBasicViewCompiler { BaseClass = "Spark.AbstractSparkView" }; - - var trueChunks = new Chunk[] { new SendLiteralChunk { Text = "wastrue" } }; - var falseChunks = new Chunk[] { new SendLiteralChunk { Text = "wasfalse" } }; - - DoCompileView(compiler, new Chunk[] - { - new SendLiteralChunk {Text = "

"}, - new LocalVariableChunk{Name="arg", Value="5"}, - new ConditionalChunk{Type=ConditionalType.If, Condition="arg=6", Body=trueChunks}, - new ConditionalChunk{Type=ConditionalType.Else, Body=falseChunks}, - new SendLiteralChunk {Text = "

"} - }); - var instance = compiler.CreateInstance(); - var contents = instance.RenderView(); - Assert.AreEqual("

wasfalse

", contents); - } - - [Test] - public void UnlessTrueCondition() - { - var compiler = new VisualBasicViewCompiler { BaseClass = "Spark.AbstractSparkView" }; - - var trueChunks = new Chunk[] { new SendLiteralChunk { Text = "wastrue" } }; - - DoCompileView(compiler, new Chunk[] - { - new SendLiteralChunk {Text = "

"}, - new LocalVariableChunk{Name="arg", Value="5"}, - new ConditionalChunk{Type=ConditionalType.Unless, Condition="arg=5", Body=trueChunks}, - new SendLiteralChunk {Text = "

"} - }); - var instance = compiler.CreateInstance(); - var contents = instance.RenderView(); - Assert.AreEqual("

", contents); - } - - [Test] - public void UnlessFalseCondition() - { - var compiler = new VisualBasicViewCompiler { BaseClass = "Spark.AbstractSparkView" }; - - var trueChunks = new Chunk[] { new SendLiteralChunk { Text = "wastrue" } }; - - DoCompileView(compiler, new Chunk[] - { - new SendLiteralChunk {Text = "

"}, - new LocalVariableChunk{Name="arg", Value="5"}, - new ConditionalChunk{Type=ConditionalType.Unless, Condition="arg=6", Body=trueChunks}, - new SendLiteralChunk {Text = "

"} - }); - var instance = compiler.CreateInstance(); - var contents = instance.RenderView(); - Assert.AreEqual("

wastrue

", contents); - } - - [Test] - public void StrictNullUsesException() - { - var compiler = new VisualBasicViewCompiler() - { - BaseClass = "Spark.Tests.Stubs.StubSparkView", - NullBehaviour = NullBehaviour.Strict - }; - var chunks = new Chunk[] - { - new ViewDataChunk { Name="comment", Type="Spark.Tests.Models.Comment"}, - new SendExpressionChunk {Code = "comment.Text", SilentNulls = false} - }; - compiler.CompileView(new[] { chunks }, new[] { chunks }); - Assert.That(compiler.SourceCode.Contains("Catch ex As Global.System.NullReferenceException")); - Assert.That(compiler.SourceCode.Contains("ArgumentNullException(")); - Assert.That(compiler.SourceCode.Contains(", ex)")); - } - - [Test] - public void PageBaseTypeOverridesBaseClass() - { - var compiler = new VisualBasicViewCompiler() - { - BaseClass = "Spark.Tests.Stubs.StubSparkView", - NullBehaviour = NullBehaviour.Strict - }; - DoCompileView(compiler, new Chunk[] - { - new PageBaseTypeChunk { BaseClass="Spark.Tests.Stubs.StubSparkView2"}, - new SendLiteralChunk{ Text = "Hello world"} - }); - var instance = compiler.CreateInstance(); - Assert.That(instance, Is.InstanceOf(typeof(StubSparkView2))); - } - - - [Test] - public void PageBaseTypeWorksWithOptionalModel() - { - var compiler = new VisualBasicViewCompiler() - { - BaseClass = "Spark.Tests.Stubs.StubSparkView", - NullBehaviour = NullBehaviour.Strict - }; - DoCompileView(compiler, new Chunk[] - { - new PageBaseTypeChunk {BaseClass = "Spark.Tests.Stubs.StubSparkView2"}, - new ViewDataModelChunk {TModel = "Spark.Tests.Models.Comment"}, - new SendLiteralChunk {Text = "Hello world"} - }); - var instance = compiler.CreateInstance(); - Assert.That(instance, Is.InstanceOf(typeof(StubSparkView2))); - Assert.That(instance, Is.InstanceOf(typeof(StubSparkView2))); - } - - [Test] - public void PageBaseTypeWorksWithGenericParametersIncluded() - { - var compiler = new VisualBasicViewCompiler() - { - BaseClass = "Spark.Tests.Stubs.StubSparkView", - NullBehaviour = NullBehaviour.Strict - }; - DoCompileView(compiler, new Chunk[] - { - new PageBaseTypeChunk {BaseClass = "Spark.Tests.Stubs.StubSparkView3(Of Spark.Tests.Models.Comment, string)"}, - new SendLiteralChunk {Text = "Hello world"} - }); - var instance = compiler.CreateInstance(); - Assert.That(instance, Is.InstanceOf(typeof(StubSparkView2))); - Assert.That(instance, Is.InstanceOf(typeof(StubSparkView2))); - Assert.That(instance, Is.InstanceOf(typeof(StubSparkView3))); - } - } +// Copyright 2008-2009 Louis DeJardin - http://whereslou.com +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +using System; +using System.Collections.Generic; + +using Spark.Compiler; +using NUnit.Framework; +using Spark.Compiler.VisualBasic; +using Spark.Tests.Models; +using Spark.Tests.Stubs; + +namespace Spark.Tests.Compiler +{ + [TestFixture] + public class VisualBasicViewCompilerTester + { + + [SetUp] + public void Init() + { + } + + private static void DoCompileView(ViewCompiler compiler, IList chunks) + { + compiler.CompileView(new[] { chunks }, new[] { chunks }); + } + + [Test] + public void MakeAndCompile() + { + var compiler = CreateCompiler(); + + DoCompileView(compiler, new[] { new SendLiteralChunk { Text = "hello world" } }); + + var instance = compiler.CreateInstance(); + string contents = instance.RenderView(); + + Assert.That(contents.Contains("hello world")); + } + + [Test] + public void StronglyTypedBase() + { + var compiler = new VisualBasicViewCompiler { BaseClass = "Spark.Tests.Stubs.StubSparkView" }; + + DoCompileView(compiler, new Chunk[] + { + new SendLiteralChunk { Text = "hello world" }, + new ViewDataModelChunk { TModel="Global.System.String"} + }); + + var instance = compiler.CreateInstance(); + string contents = instance.RenderView(); + + Assert.That(contents.Contains("hello world")); + } + + [Test] + public void UnsafeLiteralCharacters() + { + var text = "hello\t\r\n\"world"; + var compiler = CreateCompiler(); + DoCompileView(compiler, new[] { new SendLiteralChunk { Text = text } }); + + Assert.That(compiler.SourceCode.Contains("Write(\"hello")); + + var instance = compiler.CreateInstance(); + string contents = instance.RenderView(); + + Assert.That(contents, Is.EqualTo(text)); + } + + private static VisualBasicViewCompiler CreateCompiler() + { + return new VisualBasicViewCompiler + { + BaseClass = "Spark.AbstractSparkView", + UseAssemblies = new[] { "Microsoft.VisualBasic, Version=8.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" }, + UseNamespaces = new[] { "Microsoft.VisualBasic" } + }; + } + + [Test] + public void SimpleOutput() + { + var compiler = new VisualBasicViewCompiler { BaseClass = "Spark.AbstractSparkView" }; + DoCompileView(compiler, new[] { new SendExpressionChunk { Code = "3 + 4" } }); + var instance = compiler.CreateInstance(); + string contents = instance.RenderView(); + Assert.AreEqual("7", contents); + } + + [Test] + public void LenientNullBehavior() + { + var compiler = CreateCompiler(); + + DoCompileView(compiler, new[] { new SendExpressionChunk { Code = "CType(Nothing, String).Length" } }); + var instance = compiler.CreateInstance(); + var contents = instance.RenderView(); + Assert.That(contents, Is.EqualTo("${CType(Nothing, String).Length}")); + } + + [Test] + public void SilentNullBehavior() + { + var compiler = CreateCompiler(); + + DoCompileView(compiler, new[] { new SendExpressionChunk { Code = "CType(Nothing, String).Length", SilentNulls = true } }); + var instance = compiler.CreateInstance(); + var contents = instance.RenderView(); + Assert.That(contents, Is.EqualTo("")); + } + + [Test] + public void RethrowNullBehavior() + { + var compiler = CreateCompiler(); + compiler.NullBehaviour = NullBehaviour.Strict; + + DoCompileView(compiler, new[] { new SendExpressionChunk { Code = "CType(Nothing, String).Length" } }); + var instance = compiler.CreateInstance(); + Assert.That(() => instance.RenderView(), Throws.TypeOf()); + } + + [Test] + public void LocalVariableDecl() + { + var compiler = new VisualBasicViewCompiler { BaseClass = "Spark.AbstractSparkView" }; + DoCompileView(compiler, new Chunk[] + { + new LocalVariableChunk { Name = "i", Value = "5" }, + new SendExpressionChunk { Code = "i" } + }); + var instance = compiler.CreateInstance(); + string contents = instance.RenderView(); + + Assert.AreEqual("5", contents); + } + + [Test] + public void ForEachLoop() + { + var compiler = new VisualBasicViewCompiler { BaseClass = "Spark.AbstractSparkView" }; + DoCompileView(compiler, new Chunk[] + { + new LocalVariableChunk {Name = "data", Value = "new Integer(){3,4,5}"}, + new SendLiteralChunk {Text = "
    "}, + new ForEachChunk + { + Code = "item As Integer in data", + Body = new Chunk[] + { + new SendLiteralChunk {Text = "
  • "}, + new SendExpressionChunk {Code = "item"}, + new SendLiteralChunk {Text = "
  • "} + } + }, + new SendLiteralChunk {Text = "
"} + }); + var instance = compiler.CreateInstance(); + var contents = instance.RenderView(); + Assert.AreEqual("
  • 3
  • 4
  • 5
", contents); + } + + [Test] + public void ForEachAutoVariables() + { + var compiler = new VisualBasicViewCompiler { BaseClass = "Spark.AbstractSparkView" }; + DoCompileView(compiler, new Chunk[] + { + new LocalVariableChunk {Name = "data", Value = "new Integer(){3,4,5}"}, + new SendLiteralChunk {Text = "
    "}, + new ForEachChunk + { + Code = "item As Integer in data", + Body = new Chunk[] + { + new SendLiteralChunk {Text = "
  • "}, + new SendExpressionChunk {Code = "item"}, + new SendExpressionChunk {Code = "itemIsFirst"}, + new SendExpressionChunk {Code = "itemIsLast"}, + new SendExpressionChunk {Code = "itemIndex"}, + new SendExpressionChunk {Code = "itemCount"}, + new SendLiteralChunk {Text = "
  • "} + } + }, + new SendLiteralChunk {Text = "
"} + }); + var instance = compiler.CreateInstance(); + var contents = instance.RenderView(); + Assert.AreEqual("
  • 3TrueFalse03
  • 4FalseFalse13
  • 5FalseTrue23
", contents); + } + + [Test] + public void GlobalVariables() + { + var compiler = new VisualBasicViewCompiler { BaseClass = "Spark.AbstractSparkView" }; + DoCompileView(compiler, new Chunk[] + { + new SendExpressionChunk{Code="title"}, + new AssignVariableChunk{ Name="item", Value="8"}, + new SendLiteralChunk{ Text=":"}, + new SendExpressionChunk{Code="item"}, + new GlobalVariableChunk{ Name="title", Value="\"hello world\""}, + new GlobalVariableChunk{ Name="item", Value="3"} + }); + var instance = compiler.CreateInstance(); + var contents = instance.RenderView(); + Assert.AreEqual("hello world:8", contents); + } + + [Test] + [Platform(Exclude = "Mono", Reason = "Problems with Mono-2.10+/Linux and the VB compiler prevent this from running.")] + public void TargetNamespace() + { + var compiler = new VisualBasicViewCompiler + { + BaseClass = "Spark.AbstractSparkView", + Descriptor = new SparkViewDescriptor { TargetNamespace = "Testing.Target.Namespace" } + }; + + DoCompileView(compiler, new Chunk[] { new SendLiteralChunk { Text = "Hello" } }); + var instance = compiler.CreateInstance(); + Assert.AreEqual("Testing.Target.Namespace", instance.GetType().Namespace); + } + + + [Test] + public void ProvideFullException() + { + var compiler = new VisualBasicViewCompiler { BaseClass = "Spark.AbstractSparkView" }; + Assert.That(() => + DoCompileView(compiler, new Chunk[] + { + new SendExpressionChunk {Code = "NoSuchVariable"} + }), + Throws.TypeOf()); + } + + [Test] + public void IfTrueCondition() + { + var compiler = new VisualBasicViewCompiler { BaseClass = "Spark.AbstractSparkView" }; + + var trueChunks = new Chunk[] { new SendLiteralChunk { Text = "wastrue" } }; + + DoCompileView(compiler, new Chunk[] + { + new SendLiteralChunk {Text = "

"}, + new LocalVariableChunk{Name="arg", Value="5"}, + new ConditionalChunk{Type=ConditionalType.If, Condition="arg=5", Body=trueChunks}, + new SendLiteralChunk {Text = "

"} + }); + var instance = compiler.CreateInstance(); + var contents = instance.RenderView(); + Assert.AreEqual("

wastrue

", contents); + } + + [Test] + public void IfFalseCondition() + { + var compiler = new VisualBasicViewCompiler { BaseClass = "Spark.AbstractSparkView" }; + + var trueChunks = new Chunk[] { new SendLiteralChunk { Text = "wastrue" } }; + + DoCompileView(compiler, new Chunk[] + { + new SendLiteralChunk {Text = "

"}, + new LocalVariableChunk{Name="arg", Value="5"}, + new ConditionalChunk{Type=ConditionalType.If, Condition="arg=6", Body=trueChunks}, + new SendLiteralChunk {Text = "

"} + }); + var instance = compiler.CreateInstance(); + var contents = instance.RenderView(); + Assert.AreEqual("

", contents); + } + + [Test] + public void IfElseFalseCondition() + { + var compiler = new VisualBasicViewCompiler { BaseClass = "Spark.AbstractSparkView" }; + + var trueChunks = new Chunk[] { new SendLiteralChunk { Text = "wastrue" } }; + var falseChunks = new Chunk[] { new SendLiteralChunk { Text = "wasfalse" } }; + + DoCompileView(compiler, new Chunk[] + { + new SendLiteralChunk {Text = "

"}, + new LocalVariableChunk{Name="arg", Value="5"}, + new ConditionalChunk{Type=ConditionalType.If, Condition="arg=6", Body=trueChunks}, + new ConditionalChunk{Type=ConditionalType.Else, Body=falseChunks}, + new SendLiteralChunk {Text = "

"} + }); + var instance = compiler.CreateInstance(); + var contents = instance.RenderView(); + Assert.AreEqual("

wasfalse

", contents); + } + + [Test] + public void UnlessTrueCondition() + { + var compiler = new VisualBasicViewCompiler { BaseClass = "Spark.AbstractSparkView" }; + + var trueChunks = new Chunk[] { new SendLiteralChunk { Text = "wastrue" } }; + + DoCompileView(compiler, new Chunk[] + { + new SendLiteralChunk {Text = "

"}, + new LocalVariableChunk{Name="arg", Value="5"}, + new ConditionalChunk{Type=ConditionalType.Unless, Condition="arg=5", Body=trueChunks}, + new SendLiteralChunk {Text = "

"} + }); + var instance = compiler.CreateInstance(); + var contents = instance.RenderView(); + Assert.AreEqual("

", contents); + } + + [Test] + public void UnlessFalseCondition() + { + var compiler = new VisualBasicViewCompiler { BaseClass = "Spark.AbstractSparkView" }; + + var trueChunks = new Chunk[] { new SendLiteralChunk { Text = "wastrue" } }; + + DoCompileView(compiler, new Chunk[] + { + new SendLiteralChunk {Text = "

"}, + new LocalVariableChunk{Name="arg", Value="5"}, + new ConditionalChunk{Type=ConditionalType.Unless, Condition="arg=6", Body=trueChunks}, + new SendLiteralChunk {Text = "

"} + }); + var instance = compiler.CreateInstance(); + var contents = instance.RenderView(); + Assert.AreEqual("

wastrue

", contents); + } + + [Test] + public void StrictNullUsesException() + { + var compiler = new VisualBasicViewCompiler() + { + BaseClass = "Spark.Tests.Stubs.StubSparkView", + NullBehaviour = NullBehaviour.Strict + }; + var chunks = new Chunk[] + { + new ViewDataChunk { Name="comment", Type="Spark.Tests.Models.Comment"}, + new SendExpressionChunk {Code = "comment.Text", SilentNulls = false} + }; + compiler.CompileView(new[] { chunks }, new[] { chunks }); + Assert.That(compiler.SourceCode.Contains("Catch ex As Global.System.NullReferenceException")); + Assert.That(compiler.SourceCode.Contains("ArgumentNullException(")); + Assert.That(compiler.SourceCode.Contains(", ex)")); + } + + [Test] + public void PageBaseTypeOverridesBaseClass() + { + var compiler = new VisualBasicViewCompiler() + { + BaseClass = "Spark.Tests.Stubs.StubSparkView", + NullBehaviour = NullBehaviour.Strict + }; + DoCompileView(compiler, new Chunk[] + { + new PageBaseTypeChunk { BaseClass="Spark.Tests.Stubs.StubSparkView2"}, + new SendLiteralChunk{ Text = "Hello world"} + }); + var instance = compiler.CreateInstance(); + Assert.That(instance, Is.InstanceOf(typeof(StubSparkView2))); + } + + + [Test] + public void PageBaseTypeWorksWithOptionalModel() + { + var compiler = new VisualBasicViewCompiler() + { + BaseClass = "Spark.Tests.Stubs.StubSparkView", + NullBehaviour = NullBehaviour.Strict + }; + DoCompileView(compiler, new Chunk[] + { + new PageBaseTypeChunk {BaseClass = "Spark.Tests.Stubs.StubSparkView2"}, + new ViewDataModelChunk {TModel = "Spark.Tests.Models.Comment"}, + new SendLiteralChunk {Text = "Hello world"} + }); + var instance = compiler.CreateInstance(); + Assert.That(instance, Is.InstanceOf(typeof(StubSparkView2))); + Assert.That(instance, Is.InstanceOf(typeof(StubSparkView2))); + } + + [Test] + public void PageBaseTypeWorksWithGenericParametersIncluded() + { + var compiler = new VisualBasicViewCompiler() + { + BaseClass = "Spark.Tests.Stubs.StubSparkView", + NullBehaviour = NullBehaviour.Strict + }; + DoCompileView(compiler, new Chunk[] + { + new PageBaseTypeChunk {BaseClass = "Spark.Tests.Stubs.StubSparkView3(Of Spark.Tests.Models.Comment, string)"}, + new SendLiteralChunk {Text = "Hello world"} + }); + var instance = compiler.CreateInstance(); + Assert.That(instance, Is.InstanceOf(typeof(StubSparkView2))); + Assert.That(instance, Is.InstanceOf(typeof(StubSparkView2))); + Assert.That(instance, Is.InstanceOf(typeof(StubSparkView3))); + } + } } \ No newline at end of file diff --git a/src/Spark.Tests/SparkSectionHandlerTester.cs b/src/Spark.Web.Tests/Configuration/SparkSectionHandlerTester.cs similarity index 83% rename from src/Spark.Tests/SparkSectionHandlerTester.cs rename to src/Spark.Web.Tests/Configuration/SparkSectionHandlerTester.cs index a6231fee..9e54da0f 100644 --- a/src/Spark.Tests/SparkSectionHandlerTester.cs +++ b/src/Spark.Web.Tests/Configuration/SparkSectionHandlerTester.cs @@ -1,98 +1,96 @@ -// Copyright 2008-2009 Louis DeJardin - http://whereslou.com -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// -using System; -using System.Collections.Generic; -using System.Configuration; -using System.IO; -using System.Linq; -using System.Text; -using NUnit.Framework; -using Spark.Configuration; -using Spark.FileSystem; -using Spark.Tests.Stubs; - -namespace Spark.Tests -{ - [TestFixture] - public class SparkSectionHandlerTester - { - [Test] - public void CanLoadFromAppConfig() - { - var config = (SparkSectionHandler)ConfigurationManager.GetSection("spark"); - Assert.IsTrue(config.Compilation.Debug); - Assert.AreEqual(NullBehaviour.Strict, config.Compilation.NullBehaviour); - Assert.AreEqual(1, config.Compilation.Assemblies.Count); - Assert.AreEqual(typeof(StubSparkView).FullName, config.Pages.PageBaseType); - Assert.AreEqual(1, config.Pages.Namespaces.Count); - } - - [Test] - public void CreateSectionHandlerFluentInterface() - { - var config = new SparkSectionHandler() - .SetDebug(true) - .AddNamespace("System") - .AddNamespace("System.Collections.Generic") - .AddNamespace("System.Linq") - .AddAssembly(typeof(TestAttribute).Assembly) - .AddAssembly("Spark.Tests"); - - Assert.IsTrue(config.Compilation.Debug); - Assert.AreEqual(3, config.Pages.Namespaces.Count); - Assert.AreEqual(2, config.Compilation.Assemblies.Count); - } - - [Test] - public void CreateSettingsFluentInterface() - { - var settings = new SparkSettings() - .SetDebug(true) - .SetNullBehaviour(NullBehaviour.Lenient) - .AddNamespace("System") - .AddNamespace("System.Collections.Generic") - .AddNamespace("System.Linq") - .AddAssembly(typeof(TestAttribute).Assembly) - .AddAssembly("Spark.Tests"); - - Assert.IsTrue(settings.Debug); - Assert.AreEqual(NullBehaviour.Lenient, settings.NullBehaviour); - Assert.AreEqual(3, settings.UseNamespaces.Count()); - Assert.AreEqual(2, settings.UseAssemblies.Count()); - } - - [Test] - public void UseAssemblyAndNamespaceFromSettings() - { - var settings = new SparkSettings() - .AddNamespace("System.Web") - .AddAssembly("System.Web, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a") - .SetPageBaseType(typeof(StubSparkView)); - - var views = new InMemoryViewFolder - { - {Path.Combine("home", "index.spark"), "
${ProcessStatus.Alive}
"} - }; - - var engine = new SparkViewEngine(settings) {ViewFolder = views}; - - var descriptor = new SparkViewDescriptor(); - descriptor.Templates.Add(Path.Combine("home","index.spark")); - - var contents = engine.CreateInstance(descriptor).RenderView(); - Assert.AreEqual("
Alive
", contents); - } - } +// Copyright 2008-2009 Louis DeJardin - http://whereslou.com +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +using System.Configuration; +using System.IO; +using System.Linq; +using NUnit.Framework; +using Spark.Configuration; +using Spark.FileSystem; +using Spark.Tests.Stubs; + +namespace Spark.Tests.Configuration +{ + [TestFixture] + public class SparkSectionHandlerTester + { + [Test] + public void CanLoadFromAppConfig() + { + var config = (SparkSectionHandler)ConfigurationManager.GetSection("spark"); + Assert.IsTrue(config.Compilation.Debug); + Assert.AreEqual(NullBehaviour.Strict, config.Compilation.NullBehaviour); + Assert.AreEqual(1, config.Compilation.Assemblies.Count); + Assert.AreEqual(typeof(StubSparkView).FullName, config.Pages.PageBaseType); + Assert.AreEqual(1, config.Pages.Namespaces.Count); + } + + [Test] + public void CreateSectionHandlerFluentInterface() + { + var config = new SparkSectionHandler() + .SetDebug(true) + .AddNamespace("System") + .AddNamespace("System.Collections.Generic") + .AddNamespace("System.Linq") + .AddAssembly(typeof(TestAttribute).Assembly) + .AddAssembly("Spark.Tests"); + + Assert.IsTrue(config.Compilation.Debug); + Assert.AreEqual(3, config.Pages.Namespaces.Count); + Assert.AreEqual(2, config.Compilation.Assemblies.Count); + } + + [Test] + public void CreateSettingsFluentInterface() + { + var settings = new SparkSettings() + .SetDebug(true) + .SetNullBehaviour(NullBehaviour.Lenient) + .AddNamespace("System") + .AddNamespace("System.Collections.Generic") + .AddNamespace("System.Linq") + .AddAssembly(typeof(TestAttribute).Assembly) + .AddAssembly("Spark.Tests"); + + Assert.IsTrue(settings.Debug); + Assert.AreEqual(NullBehaviour.Lenient, settings.NullBehaviour); + Assert.AreEqual(3, settings.UseNamespaces.Count()); + Assert.AreEqual(2, settings.UseAssemblies.Count()); + } + + [Test] + public void UseAssemblyAndNamespaceFromSettings() + { + var settings = new SparkSettings() + .AddNamespace("System.Web") + .AddAssembly("System.Web, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a") + .SetPageBaseType(typeof(StubSparkView)); + + var views = new InMemoryViewFolder + { + { Path.Combine("home", "index.spark"), "
${ProcessStatus.Alive}
" } + }; + + var engine = new SparkViewEngine(settings) { ViewFolder = views }; + + var descriptor = new SparkViewDescriptor(); + descriptor.Templates.Add(Path.Combine("home", "index.spark")); + + var contents = engine.CreateInstance(descriptor).RenderView(); + Assert.AreEqual("
Alive
", contents); + } + } } \ No newline at end of file diff --git a/src/Spark.Tests/FileSystem/InMemoryViewFolderTester.cs b/src/Spark.Web.Tests/FileSystem/InMemoryViewFolderTester.cs similarity index 97% rename from src/Spark.Tests/FileSystem/InMemoryViewFolderTester.cs rename to src/Spark.Web.Tests/FileSystem/InMemoryViewFolderTester.cs index 530afc10..472e3a68 100644 --- a/src/Spark.Tests/FileSystem/InMemoryViewFolderTester.cs +++ b/src/Spark.Web.Tests/FileSystem/InMemoryViewFolderTester.cs @@ -1,161 +1,161 @@ -// Copyright 2008-2009 Louis DeJardin - http://whereslou.com -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// -using System.IO; -using System.Linq; -using NUnit.Framework; -using Spark.FileSystem; -using Spark.Tests.Stubs; - - -namespace Spark.Tests.FileSystem -{ - [TestFixture] - public class InMemoryViewFolderTester - { - [Test] - public void HasViewCaseInsensitive() - { - var folder = new InMemoryViewFolder(); - Assert.IsFalse(folder.HasView(Path.Combine("Home", "Index.spark"))); - folder.Add(Path.Combine("Home", "Index.spark"), "stuff"); - Assert.IsTrue(folder.HasView(Path.Combine("Home", "Index.spark"))); - Assert.IsFalse(folder.HasView(Path.Combine("Home", "Index"))); - Assert.IsTrue(folder.HasView(Path.Combine("Home", "index.spark"))); - Assert.IsTrue(folder.HasView(Path.Combine("home", "INDEX.SPARK"))); - } - - [Test] - public void ListViewsInFolder() - { - var folder = new InMemoryViewFolder - { - {Path.Combine("Home", "Alpha.spark"), "stuff"}, - {Path.Combine("Home", "Beta.spark"), "stuff"}, - {Path.Combine("Home2", "Gamma.spark"), "stuff"}, - {Path.Combine("home", "Delta.spark"), "stuff"}, - {Path.Combine("Home","Something","else.spark"), "stuff"} - }; - - var views = folder.ListViews("Home"); - - var baseNames = views.Select(v => Path.GetFileNameWithoutExtension(v)).ToArray(); - Assert.AreEqual(3, baseNames.Count()); - Assert.Contains("Alpha", baseNames); - Assert.Contains("Beta", baseNames); - Assert.Contains("Delta", baseNames); - } - - [Test] - public void FileNotFoundException() - { - var folder = new InMemoryViewFolder(); - folder.Add(Path.Combine("Home", "Index.spark"), "stuff"); - Assert.That(() => folder.GetViewSource(Path.Combine("Home", "List.spark")), - Throws.TypeOf()); - } - - [Test] - public void ReadFileContents() - { - var folder = new InMemoryViewFolder(); - folder.Add(Path.Combine("Home", "Index.spark"), "this is the file contents"); - var source = folder.GetViewSource(Path.Combine("Home", "Index.spark")); - using (var stream = source.OpenViewStream()) - { - using(var reader = new StreamReader(stream)) - { - var contents = reader.ReadToEnd(); - Assert.AreEqual("this is the file contents", contents); - } - } - } - - [Test] - public void LastModifiedChanges() - { - var folder = new InMemoryViewFolder(); - folder.Add(Path.Combine("Home", "Index.spark"), "this is the file contents"); - var source1 = folder.GetViewSource(Path.Combine("Home", "Index.spark")); - var lastModified1 = source1.LastModified; - - folder.Set(Path.Combine("Home", "Index.spark"), "this is the file contents"); - var source2 = folder.GetViewSource(Path.Combine("Home", "Index.spark")); - var lastModified2 = source2.LastModified; - - Assert.AreNotEqual(lastModified1, lastModified2); - - var lastModified1b = source1.LastModified; - var lastModified2b = source1.LastModified; - - Assert.AreNotEqual(lastModified1, lastModified1b); - Assert.AreEqual(lastModified1b, lastModified2b); - - } - - [Test] - public void InMemoryViewFolderUsedByEngine() - { - var folder = new InMemoryViewFolder(); - folder.Add(Path.Combine("home", "index.spark"), "

Hello world

"); - var engine = new SparkViewEngine(new SparkSettings().SetPageBaseType(typeof (StubSparkView))){ViewFolder = folder}; - - var descriptor = new SparkViewDescriptor(); - descriptor.Templates.Add(Path.Combine("home", "index.spark")); - var view = engine.CreateInstance(descriptor); - var contents = view.RenderView(); - Assert.AreEqual("

Hello world

", contents); - } - - static string ReadToEnd(IViewFolder viewFolder, string path) - { - using (var stream = viewFolder.GetViewSource(path).OpenViewStream()) - { - using (var reader = new StreamReader(stream)) - { - return reader.ReadToEnd(); - } - } - } - - static string RenderView(ISparkViewEngine engine, string path) - { - var descriptor = new SparkViewDescriptor() - .AddTemplate(path); - - return engine - .CreateInstance(descriptor) - .RenderView(); - } - - [Test] - public void UnicodeCharactersSurviveConversionToByteArrayAndBack() - { - var folder = new InMemoryViewFolder(); - folder.Add(Path.Combine("Home", "fr.spark"), "Fran\u00E7ais"); - folder.Add(Path.Combine("Home", "ru.spark"), "\u0420\u0443\u0441\u0441\u043A\u0438\u0439"); - folder.Add(Path.Combine("Home", "ja.spark"), "\u65E5\u672C\u8A9E"); - - Assert.That(ReadToEnd(folder, Path.Combine("Home", "fr.spark")), Is.EqualTo("Français")); - Assert.That(ReadToEnd(folder, Path.Combine("Home", "ru.spark")), Is.EqualTo("Русский")); - Assert.That(ReadToEnd(folder, Path.Combine("Home", "ja.spark")), Is.EqualTo("日本語")); - - var settings = new SparkSettings().SetPageBaseType(typeof(StubSparkView)); - var engine = new SparkViewEngine(settings) { ViewFolder = folder }; - Assert.That(RenderView(engine, Path.Combine("Home", "fr.spark")), Is.EqualTo("Français")); - Assert.That(RenderView(engine, Path.Combine("Home", "ru.spark")), Is.EqualTo("Русский")); - Assert.That(RenderView(engine, Path.Combine("Home", "ja.spark")), Is.EqualTo("日本語")); - } - } -} +// Copyright 2008-2009 Louis DeJardin - http://whereslou.com +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +using System.IO; +using System.Linq; +using NUnit.Framework; +using Spark.FileSystem; +using Spark.Tests.Stubs; + + +namespace Spark.Tests.FileSystem +{ + [TestFixture] + public class InMemoryViewFolderTester + { + [Test] + public void HasViewCaseInsensitive() + { + var folder = new InMemoryViewFolder(); + Assert.IsFalse(folder.HasView(Path.Combine("Home", "Index.spark"))); + folder.Add(Path.Combine("Home", "Index.spark"), "stuff"); + Assert.IsTrue(folder.HasView(Path.Combine("Home", "Index.spark"))); + Assert.IsFalse(folder.HasView(Path.Combine("Home", "Index"))); + Assert.IsTrue(folder.HasView(Path.Combine("Home", "index.spark"))); + Assert.IsTrue(folder.HasView(Path.Combine("home", "INDEX.SPARK"))); + } + + [Test] + public void ListViewsInFolder() + { + var folder = new InMemoryViewFolder + { + {Path.Combine("Home", "Alpha.spark"), "stuff"}, + {Path.Combine("Home", "Beta.spark"), "stuff"}, + {Path.Combine("Home2", "Gamma.spark"), "stuff"}, + {Path.Combine("home", "Delta.spark"), "stuff"}, + {Path.Combine("Home","Something","else.spark"), "stuff"} + }; + + var views = folder.ListViews("Home"); + + var baseNames = views.Select(v => Path.GetFileNameWithoutExtension(v)).ToArray(); + Assert.AreEqual(3, baseNames.Count()); + Assert.Contains("Alpha", baseNames); + Assert.Contains("Beta", baseNames); + Assert.Contains("Delta", baseNames); + } + + [Test] + public void FileNotFoundException() + { + var folder = new InMemoryViewFolder(); + folder.Add(Path.Combine("Home", "Index.spark"), "stuff"); + Assert.That(() => folder.GetViewSource(Path.Combine("Home", "List.spark")), + Throws.TypeOf()); + } + + [Test] + public void ReadFileContents() + { + var folder = new InMemoryViewFolder(); + folder.Add(Path.Combine("Home", "Index.spark"), "this is the file contents"); + var source = folder.GetViewSource(Path.Combine("Home", "Index.spark")); + using (var stream = source.OpenViewStream()) + { + using(var reader = new StreamReader(stream)) + { + var contents = reader.ReadToEnd(); + Assert.AreEqual("this is the file contents", contents); + } + } + } + + [Test] + public void LastModifiedChanges() + { + var folder = new InMemoryViewFolder(); + folder.Add(Path.Combine("Home", "Index.spark"), "this is the file contents"); + var source1 = folder.GetViewSource(Path.Combine("Home", "Index.spark")); + var lastModified1 = source1.LastModified; + + folder.Set(Path.Combine("Home", "Index.spark"), "this is the file contents"); + var source2 = folder.GetViewSource(Path.Combine("Home", "Index.spark")); + var lastModified2 = source2.LastModified; + + Assert.AreNotEqual(lastModified1, lastModified2); + + var lastModified1b = source1.LastModified; + var lastModified2b = source1.LastModified; + + Assert.AreNotEqual(lastModified1, lastModified1b); + Assert.AreEqual(lastModified1b, lastModified2b); + + } + + [Test] + public void InMemoryViewFolderUsedByEngine() + { + var folder = new InMemoryViewFolder(); + folder.Add(Path.Combine("home", "index.spark"), "

Hello world

"); + var engine = new SparkViewEngine(new SparkSettings().SetPageBaseType(typeof (StubSparkView))){ViewFolder = folder}; + + var descriptor = new SparkViewDescriptor(); + descriptor.Templates.Add(Path.Combine("home", "index.spark")); + var view = engine.CreateInstance(descriptor); + var contents = view.RenderView(); + Assert.AreEqual("

Hello world

", contents); + } + + static string ReadToEnd(IViewFolder viewFolder, string path) + { + using (var stream = viewFolder.GetViewSource(path).OpenViewStream()) + { + using (var reader = new StreamReader(stream)) + { + return reader.ReadToEnd(); + } + } + } + + static string RenderView(ISparkViewEngine engine, string path) + { + var descriptor = new SparkViewDescriptor() + .AddTemplate(path); + + return engine + .CreateInstance(descriptor) + .RenderView(); + } + + [Test] + public void UnicodeCharactersSurviveConversionToByteArrayAndBack() + { + var folder = new InMemoryViewFolder(); + folder.Add(Path.Combine("Home", "fr.spark"), "Fran\u00E7ais"); + folder.Add(Path.Combine("Home", "ru.spark"), "\u0420\u0443\u0441\u0441\u043A\u0438\u0439"); + folder.Add(Path.Combine("Home", "ja.spark"), "\u65E5\u672C\u8A9E"); + + Assert.That(ReadToEnd(folder, Path.Combine("Home", "fr.spark")), Is.EqualTo("Français")); + Assert.That(ReadToEnd(folder, Path.Combine("Home", "ru.spark")), Is.EqualTo("Русский")); + Assert.That(ReadToEnd(folder, Path.Combine("Home", "ja.spark")), Is.EqualTo("日本語")); + + var settings = new SparkSettings().SetPageBaseType(typeof(StubSparkView)); + var engine = new SparkViewEngine(settings) { ViewFolder = folder }; + Assert.That(RenderView(engine, Path.Combine("Home", "fr.spark")), Is.EqualTo("Français")); + Assert.That(RenderView(engine, Path.Combine("Home", "ru.spark")), Is.EqualTo("Русский")); + Assert.That(RenderView(engine, Path.Combine("Home", "ja.spark")), Is.EqualTo("日本語")); + } + } +} diff --git a/src/Spark.Tests/FileSystem/ViewFolderSettingsTester.cs b/src/Spark.Web.Tests/FileSystem/ViewFolderSettingsTester.cs similarity index 83% rename from src/Spark.Tests/FileSystem/ViewFolderSettingsTester.cs rename to src/Spark.Web.Tests/FileSystem/ViewFolderSettingsTester.cs index ba7c6927..0d785954 100644 --- a/src/Spark.Tests/FileSystem/ViewFolderSettingsTester.cs +++ b/src/Spark.Web.Tests/FileSystem/ViewFolderSettingsTester.cs @@ -1,119 +1,116 @@ -// Copyright 2008-2009 Louis DeJardin - http://whereslou.com -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// -using System; -using System.Collections.Generic; -using System.Linq; -using System.Reflection; -using System.Text; -using NUnit.Framework; -using Spark.FileSystem; - -namespace Spark.Tests.FileSystem -{ - [TestFixture] - public class ViewFolderSettingsTester - { - [Test] - public void ApplySettings() - { - var settings = new SparkSettings() - .AddViewFolder(ViewFolderType.VirtualPathProvider, new Dictionary { { "virtualBaseDir", "~/MoreViews/" } }); - var engine = new SparkViewEngine(settings); - - var folder = engine.ViewFolder; - Assert.IsAssignableFrom(typeof(CombinedViewFolder), folder); - var combined = (CombinedViewFolder)folder; - Assert.IsAssignableFrom(typeof(VirtualPathProviderViewFolder), combined.Second); - var vpp = (VirtualPathProviderViewFolder)combined.Second; - Assert.AreEqual("~/MoreViews/", vpp.VirtualBaseDir); - } - - [Test] - public void CustomViewFolder() - { - var settings = new SparkSettings() - .AddViewFolder(typeof(MyViewFolder), new Dictionary { { "foo", "quux" }, { "bar", "42" } }); - var engine = new SparkViewEngine(settings); - - var folder = engine.ViewFolder; - Assert.IsAssignableFrom(typeof(CombinedViewFolder), folder); - var combined = (CombinedViewFolder)folder; - Assert.IsAssignableFrom(typeof(MyViewFolder), combined.Second); - var customFolder = (MyViewFolder)combined.Second; - Assert.AreEqual("quux", customFolder.Foo); - Assert.AreEqual(42, customFolder.Bar); - } - - [Test] - public void AssemblyParameter() - { - var settings = new SparkSettings() - .AddViewFolder(ViewFolderType.EmbeddedResource, new Dictionary { { "assembly", "Spark.Tests" }, { "resourcePath", "Spark.Tests.Views" } }); - - var engine = new SparkViewEngine(settings); - - var folder = engine.ViewFolder; - Assert.IsAssignableFrom(typeof(CombinedViewFolder), folder); - var combined = (CombinedViewFolder)folder; - Assert.IsAssignableFrom(typeof(EmbeddedViewFolder), combined.Second); - var embeddedViewFolder = (EmbeddedViewFolder)combined.Second; - Assert.AreEqual(Assembly.Load("Spark.Tests"), embeddedViewFolder.Assembly); - } - - [Test] - public void TypeFileSystemCreatesFileSystemViewFolder() - { - var settings = new SparkSettings() - .AddViewFolder(ViewFolderType.FileSystem, new Dictionary - { - {"basePath", @"e:\no\such\path"} - }); - var engine = new SparkViewEngine(settings); - var folder = engine.ViewFolder; - Assert.IsAssignableFrom(typeof(CombinedViewFolder), folder); - var combined = (CombinedViewFolder)folder; - Assert.IsAssignableFrom(typeof(FileSystemViewFolder), combined.Second); - var fileSystemViewFolder = (FileSystemViewFolder)combined.Second; - Assert.AreEqual(@"e:\no\such\path", fileSystemViewFolder.BasePath); - } - - public class MyViewFolder : IViewFolder - { - public string Foo { get; set; } - public int Bar { get; set; } - - public MyViewFolder(string foo, int bar) - { - Foo = foo; - Bar = bar; - } - - public IViewFile GetViewSource(string path) - { - throw new System.NotImplementedException(); - } - - public IList ListViews(string path) - { - throw new System.NotImplementedException(); - } - - public bool HasView(string path) - { - throw new System.NotImplementedException(); - } - } - } -} +// Copyright 2008-2009 Louis DeJardin - http://whereslou.com +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +using System.Collections.Generic; +using System.Reflection; +using NUnit.Framework; + +namespace Spark.FileSystem +{ + [TestFixture] + public class ViewFolderSettingsTester + { + [Test] + public void ApplySettings() + { + var settings = new SparkSettings() + .AddViewFolder(typeof(VirtualPathProviderViewFolder), new Dictionary { { "virtualBaseDir", "~/MoreViews/" } }); + var engine = new SparkViewEngine(settings); + + var folder = engine.ViewFolder; + Assert.IsAssignableFrom(typeof(CombinedViewFolder), folder); + var combined = (CombinedViewFolder)folder; + Assert.IsAssignableFrom(typeof(VirtualPathProviderViewFolder), combined.Second); + var vpp = (VirtualPathProviderViewFolder)combined.Second; + Assert.AreEqual("~/MoreViews/", vpp.VirtualBaseDir); + } + + [Test] + public void CustomViewFolder() + { + var settings = new SparkSettings() + .AddViewFolder(typeof(MyViewFolder), new Dictionary { { "foo", "quux" }, { "bar", "42" } }); + var engine = new SparkViewEngine(settings); + + var folder = engine.ViewFolder; + Assert.IsAssignableFrom(typeof(CombinedViewFolder), folder); + var combined = (CombinedViewFolder)folder; + Assert.IsAssignableFrom(typeof(MyViewFolder), combined.Second); + var customFolder = (MyViewFolder)combined.Second; + Assert.AreEqual("quux", customFolder.Foo); + Assert.AreEqual(42, customFolder.Bar); + } + + [Test] + public void AssemblyParameter() + { + var settings = new SparkSettings() + .AddViewFolder(typeof(EmbeddedViewFolder), new Dictionary { { "assembly", "Spark.Tests" }, { "resourcePath", "Spark.Tests.Views" } }); + + var engine = new SparkViewEngine(settings); + + var folder = engine.ViewFolder; + Assert.IsAssignableFrom(typeof(CombinedViewFolder), folder); + var combined = (CombinedViewFolder)folder; + Assert.IsAssignableFrom(typeof(EmbeddedViewFolder), combined.Second); + var embeddedViewFolder = (EmbeddedViewFolder)combined.Second; + Assert.AreEqual(Assembly.Load("Spark.Tests"), embeddedViewFolder.Assembly); + } + + [Test] + public void TypeFileSystemCreatesFileSystemViewFolder() + { + var settings = new SparkSettings() + .AddViewFolder(typeof(FileSystemViewFolder), new Dictionary + { + { "basePath", @"e:\no\such\path" } + }); + var engine = new SparkViewEngine(settings); + var folder = engine.ViewFolder; + Assert.IsAssignableFrom(typeof(CombinedViewFolder), folder); + var combined = (CombinedViewFolder)folder; + Assert.IsAssignableFrom(typeof(FileSystemViewFolder), combined.Second); + var fileSystemViewFolder = (FileSystemViewFolder)combined.Second; + Assert.AreEqual(@"e:\no\such\path", fileSystemViewFolder.BasePath); + } + + public class MyViewFolder : IViewFolder + { + public string Foo { get; set; } + public int Bar { get; set; } + + public MyViewFolder(string foo, int bar) + { + Foo = foo; + Bar = bar; + } + + public IViewFile GetViewSource(string path) + { + throw new System.NotImplementedException(); + } + + public IList ListViews(string path) + { + throw new System.NotImplementedException(); + } + + public bool HasView(string path) + { + throw new System.NotImplementedException(); + } + } + } +} diff --git a/src/Spark.Tests/ImportAndIncludeTester.cs b/src/Spark.Web.Tests/ImportAndIncludeTester.cs similarity index 97% rename from src/Spark.Tests/ImportAndIncludeTester.cs rename to src/Spark.Web.Tests/ImportAndIncludeTester.cs index 26ff7995..8118b07e 100644 --- a/src/Spark.Tests/ImportAndIncludeTester.cs +++ b/src/Spark.Web.Tests/ImportAndIncludeTester.cs @@ -1,236 +1,233 @@ -// Copyright 2008-2009 Louis DeJardin - http://whereslou.com -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// -using System; -using System.Collections.Generic; -using System.IO; -using System.Linq; -using System.Text; -using NUnit.Framework; -using Spark.Compiler; -using Spark.FileSystem; -using Spark.Tests.Stubs; - -namespace Spark.Tests -{ - [TestFixture] - public class ImportAndIncludeTester - { - private ISparkView CreateView(IViewFolder viewFolder, string template) - { - var settings = new SparkSettings().SetPageBaseType(typeof(StubSparkView)); - - var engine = new SparkViewEngine(settings) - { - ViewFolder = viewFolder - }; - - return engine.CreateInstance(new SparkViewDescriptor().AddTemplate(template)); - } - - [Test] - public void ImportExplicitFile() - { - var view = CreateView(new InMemoryViewFolder - { - {Path.Combine("importing", "index.spark"), "

hello ${name}

"}, - {Path.Combine("importing", "extra.spark"), "this is imported "} - }, Path.Combine("importing", "index.spark")); - - var contents = view.RenderView(); - Assert.AreEqual("

hello world

", contents); - Assert.IsFalse(contents.Contains("import")); - } - - [Test] - public void ImportExplicitFileFromShared() - { - var view = CreateView(new InMemoryViewFolder - { - {Path.Combine("importing", "index.spark"), "

hello ${name}

"}, - {Path.Combine("shared", "extra.spark"), "this is imported "} - }, Path.Combine("importing", "index.spark")); - var contents = view.RenderView(); - Assert.AreEqual("

hello world

", contents); - Assert.IsFalse(contents.Contains("import")); - } - - [Test] - public void ImportExplicitWithoutExtension() - { - var view = CreateView(new InMemoryViewFolder - { - {Path.Combine("importing", "index.spark"), "

${foo()} ${name}

"}, - {Path.Combine("importing", "another.spark"), "hello"}, - {Path.Combine("shared", "extra.spark"), "this is imported "} - }, Path.Combine("importing", "index.spark")); - - var contents = view.RenderView(); - Assert.AreEqual("

hello world

", contents); - Assert.IsFalse(contents.Contains("import")); - } - - [Test] - public void ImportImplicit() - { - var view = CreateView(new InMemoryViewFolder - { - {Path.Combine("importing", "index.spark"), "

${foo()} ${name}

"}, - {Path.Combine("importing", "_global.spark"), "hello"}, - {Path.Combine("shared", "_global.spark"), "this is imported "} - }, Path.Combine("importing", "index.spark")); - - var contents = view.RenderView(); - Assert.AreEqual("

hello world

", contents); - Assert.IsFalse(contents.Contains("import")); - } - - - [Test] - public void IncludeFile() - { - var view = CreateView(new InMemoryViewFolder - { - {Path.Combine("including", "index.spark"), "

"}, - {Path.Combine("including", "stuff.spark"), "hello world"} - }, Path.Combine("including", "index.spark")); - var contents = view.RenderView(); - Assert.AreEqual("

hello world

", contents); - } - - [Test] - public void MissingFileThrowsException() - { - Assert.That(() => - { - var view = CreateView(new InMemoryViewFolder - { - { - Path.Combine("including", "index.spark"), - "

" - } - }, Path.Combine("including", "index.spark")); - view.RenderView(); - }, - Throws.TypeOf()); - } - - - [Test] - public void MissingFileWithEmptyFallbackIsBlank() - { - var view = CreateView(new InMemoryViewFolder - { - {Path.Combine("including", "index.spark"), "

"} - }, Path.Combine("including", "index.spark")); - var contents = view.RenderView(); - Assert.AreEqual("

", contents); - } - - [Test] - public void MissingFileWithFallbackUsesContents() - { - var view = CreateView(new InMemoryViewFolder - { - {Path.Combine("including", "index.spark"), "

hello world

"} - }, Path.Combine("including", "index.spark")); - var contents = view.RenderView(); - Assert.AreEqual("

hello world

", contents); - } - - [Test] - public void ValidIncludeFallbackDisappears() - { - var view = CreateView(new InMemoryViewFolder - { - {Path.Combine("including", "index.spark"), "

hello world

"}, - {Path.Combine("including", "stuff.spark"), "another file"} - }, Path.Combine("including", "index.spark")); - var contents = view.RenderView(); - Assert.AreEqual("

another file

", contents); - } - - [Test] - public void FallbackContainsAnotherInclude() - { - var view = CreateView(new InMemoryViewFolder - { - {Path.Combine("including", "index.spark"), "

"}, - {Path.Combine("including", "other.spark"), "other file"} - }, Path.Combine("including", "index.spark")); - var contents = view.RenderView(); - Assert.AreEqual("

other file

", contents); - } - - [Test] - public void IncludeRelativePath() - { - var view = CreateView(new InMemoryViewFolder - { - {Path.Combine("including", "index.spark"), "

"}, - {Path.Combine("lib", "other.spark"), "other file"} - }, Path.Combine("including", "index.spark")); - var contents = view.RenderView(); - Assert.AreEqual("

other file

", contents); - } - [Test] - public void IncludeInsideAnInclude() - { - var view = CreateView(new InMemoryViewFolder - { - {Path.Combine("including", "index.spark"), "

"}, - {Path.Combine("lib", "other.spark"), "other file"}, - {Path.Combine("lib", "third.spark"), "third file"} - }, Path.Combine("including", "index.spark")); - var contents = view.RenderView(); - Assert.AreEqual("

other third file file

", contents); - } - - [Test] - public void UsingXmlns() - { - var view = CreateView(new InMemoryViewFolder - { - {Path.Combine("including", "index.spark"), "

"}, - {Path.Combine("lib", "other.spark"), "other file"} - }, Path.Combine("including", "index.spark")); - var contents = view.RenderView(); - Assert.AreEqual("

other file

", contents); - } - - [Test] - public void IncludingAsText() - { - var view = CreateView(new InMemoryViewFolder - { - {Path.Combine("including", "index.spark"), "

"}, - {Path.Combine("including", "item.spark"), "
  • at&t
  • "} - }, Path.Combine("including", "index.spark")); - var contents = view.RenderView(); - Assert.AreEqual("

    <li>at&t</li>

    ", contents); - } - - [Test] - public void IncludingAsHtmlWithDollar() - { - var view = CreateView(new InMemoryViewFolder - { - {Path.Combine("including", "index.spark"), "

    "}, - {Path.Combine("including", "jquery.templ.htm"), "

    ${Title}

    "} - }, Path.Combine("including", "index.spark")); - var contents = view.RenderView(); - Assert.AreEqual("

    ${Title}

    ", contents); - } - } -} +// Copyright 2008-2009 Louis DeJardin - http://whereslou.com +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +using System.IO; +using NUnit.Framework; +using Spark.Compiler; +using Spark.FileSystem; +using Spark.Tests.Stubs; + +namespace Spark.Tests +{ + [TestFixture] + public class ImportAndIncludeTester + { + private ISparkView CreateView(IViewFolder viewFolder, string template) + { + var settings = new SparkSettings().SetPageBaseType(typeof(StubSparkView)); + + var engine = new SparkViewEngine(settings) + { + ViewFolder = viewFolder + }; + + return engine.CreateInstance(new SparkViewDescriptor().AddTemplate(template)); + } + + [Test] + public void ImportExplicitFile() + { + var view = CreateView(new InMemoryViewFolder + { + {Path.Combine("importing", "index.spark"), "

    hello ${name}

    "}, + {Path.Combine("importing", "extra.spark"), "this is imported "} + }, Path.Combine("importing", "index.spark")); + + var contents = view.RenderView(); + Assert.AreEqual("

    hello world

    ", contents); + Assert.IsFalse(contents.Contains("import")); + } + + [Test] + public void ImportExplicitFileFromShared() + { + var view = CreateView(new InMemoryViewFolder + { + {Path.Combine("importing", "index.spark"), "

    hello ${name}

    "}, + {Path.Combine("shared", "extra.spark"), "this is imported "} + }, Path.Combine("importing", "index.spark")); + var contents = view.RenderView(); + Assert.AreEqual("

    hello world

    ", contents); + Assert.IsFalse(contents.Contains("import")); + } + + [Test] + public void ImportExplicitWithoutExtension() + { + var view = CreateView(new InMemoryViewFolder + { + {Path.Combine("importing", "index.spark"), "

    ${foo()} ${name}

    "}, + {Path.Combine("importing", "another.spark"), "hello"}, + {Path.Combine("shared", "extra.spark"), "this is imported "} + }, Path.Combine("importing", "index.spark")); + + var contents = view.RenderView(); + Assert.AreEqual("

    hello world

    ", contents); + Assert.IsFalse(contents.Contains("import")); + } + + [Test] + public void ImportImplicit() + { + var view = CreateView(new InMemoryViewFolder + { + {Path.Combine("importing", "index.spark"), "

    ${foo()} ${name}

    "}, + {Path.Combine("importing", "_global.spark"), "hello"}, + {Path.Combine("shared", "_global.spark"), "this is imported "} + }, Path.Combine("importing", "index.spark")); + + var contents = view.RenderView(); + Assert.AreEqual("

    hello world

    ", contents); + Assert.IsFalse(contents.Contains("import")); + } + + + [Test] + public void IncludeFile() + { + var view = CreateView(new InMemoryViewFolder + { + {Path.Combine("including", "index.spark"), "

    "}, + {Path.Combine("including", "stuff.spark"), "hello world"} + }, Path.Combine("including", "index.spark")); + var contents = view.RenderView(); + Assert.AreEqual("

    hello world

    ", contents); + } + + [Test] + public void MissingFileThrowsException() + { + Assert.That(() => + { + var view = CreateView(new InMemoryViewFolder + { + { + Path.Combine("including", "index.spark"), + "

    " + } + }, Path.Combine("including", "index.spark")); + view.RenderView(); + }, + Throws.TypeOf()); + } + + + [Test] + public void MissingFileWithEmptyFallbackIsBlank() + { + var view = CreateView(new InMemoryViewFolder + { + {Path.Combine("including", "index.spark"), "

    "} + }, Path.Combine("including", "index.spark")); + var contents = view.RenderView(); + Assert.AreEqual("

    ", contents); + } + + [Test] + public void MissingFileWithFallbackUsesContents() + { + var view = CreateView(new InMemoryViewFolder + { + {Path.Combine("including", "index.spark"), "

    hello world

    "} + }, Path.Combine("including", "index.spark")); + var contents = view.RenderView(); + Assert.AreEqual("

    hello world

    ", contents); + } + + [Test] + public void ValidIncludeFallbackDisappears() + { + var view = CreateView(new InMemoryViewFolder + { + {Path.Combine("including", "index.spark"), "

    hello world

    "}, + {Path.Combine("including", "stuff.spark"), "another file"} + }, Path.Combine("including", "index.spark")); + var contents = view.RenderView(); + Assert.AreEqual("

    another file

    ", contents); + } + + [Test] + public void FallbackContainsAnotherInclude() + { + var view = CreateView(new InMemoryViewFolder + { + {Path.Combine("including", "index.spark"), "

    "}, + {Path.Combine("including", "other.spark"), "other file"} + }, Path.Combine("including", "index.spark")); + var contents = view.RenderView(); + Assert.AreEqual("

    other file

    ", contents); + } + + [Test] + public void IncludeRelativePath() + { + var view = CreateView(new InMemoryViewFolder + { + {Path.Combine("including", "index.spark"), "

    "}, + {Path.Combine("lib", "other.spark"), "other file"} + }, Path.Combine("including", "index.spark")); + var contents = view.RenderView(); + Assert.AreEqual("

    other file

    ", contents); + } + [Test] + public void IncludeInsideAnInclude() + { + var view = CreateView(new InMemoryViewFolder + { + {Path.Combine("including", "index.spark"), "

    "}, + {Path.Combine("lib", "other.spark"), "other file"}, + {Path.Combine("lib", "third.spark"), "third file"} + }, Path.Combine("including", "index.spark")); + var contents = view.RenderView(); + Assert.AreEqual("

    other third file file

    ", contents); + } + + [Test] + public void UsingXmlns() + { + var view = CreateView(new InMemoryViewFolder + { + {Path.Combine("including", "index.spark"), "

    "}, + {Path.Combine("lib", "other.spark"), "other file"} + }, Path.Combine("including", "index.spark")); + var contents = view.RenderView(); + Assert.AreEqual("

    other file

    ", contents); + } + + [Test] + public void IncludingAsText() + { + var view = CreateView(new InMemoryViewFolder + { + {Path.Combine("including", "index.spark"), "

    "}, + {Path.Combine("including", "item.spark"), "
  • at&t
  • "} + }, Path.Combine("including", "index.spark")); + var contents = view.RenderView(); + Assert.AreEqual("

    <li>at&t</li>

    ", contents); + } + + [Test] + public void IncludingAsHtmlWithDollar() + { + var view = CreateView(new InMemoryViewFolder + { + {Path.Combine("including", "index.spark"), "

    "}, + {Path.Combine("including", "jquery.templ.htm"), "

    ${Title}

    "} + }, Path.Combine("including", "index.spark")); + var contents = view.RenderView(); + Assert.AreEqual("

    ${Title}

    ", contents); + } + } +} diff --git a/src/Spark.Tests/Parser/AutomaticEncodingTester.cs b/src/Spark.Web.Tests/Parser/AutomaticEncodingTester.cs similarity index 96% rename from src/Spark.Tests/Parser/AutomaticEncodingTester.cs rename to src/Spark.Web.Tests/Parser/AutomaticEncodingTester.cs index ed973e14..da495fa9 100644 --- a/src/Spark.Tests/Parser/AutomaticEncodingTester.cs +++ b/src/Spark.Web.Tests/Parser/AutomaticEncodingTester.cs @@ -1,187 +1,185 @@ -// Copyright 2008-2009 Louis DeJardin - http://whereslou.com -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using NUnit.Framework; - -using Spark.FileSystem; -using Spark.Parser; -using Spark.Parser.Markup; -using Spark.Tests.Stubs; -using System.IO; - -namespace Spark.Tests.Parser -{ - [TestFixture] - public class AutomaticEncodingTester - { - private ISparkViewEngine _engine; - private InMemoryViewFolder _viewFolder; - private ISparkViewEntry _entry; - private SparkSettings _settings; - - [SetUp] - public void Init() - { - Init(false); - } - - public void Init(bool automaticEncoding) - { - _settings = new SparkSettings() - .SetPageBaseType(typeof(StubSparkView)) - .SetAutomaticEncoding(automaticEncoding); - var container = new SparkServiceContainer(_settings); - - _viewFolder = new InMemoryViewFolder(); - - container.SetServiceBuilder(c => _viewFolder); - - _engine = container.GetService(); - } - - private string RenderView(SparkViewDescriptor descriptor) - { - _entry = _engine.CreateEntry(descriptor); - var view = _entry.CreateInstance(); - var contents = view.RenderView(); - _engine.ReleaseInstance(view); - return contents; - } - - private Position Source(string content) - { - return new Position(new SourceContext(content)); - } - - [Test] - public void DollarSyntaxHasRawContentWhenDisabled() - { - var settings = new ParserSettings {AutomaticEncoding = false}; - var grammar = new MarkupGrammar(settings); - var result = grammar.Nodes(Source("${'hello world'}")); - - Assert.AreEqual(1, result.Value.Count); - Assert.AreEqual("\"hello world\"", (string)((ExpressionNode)result.Value[0]).Code); - Assert.IsFalse(((ExpressionNode)result.Value[0]).AutomaticEncoding); - } - - [Test] - public void BangSyntaxHasRawContentWhenDisabled() - { - var settings = new ParserSettings { AutomaticEncoding = false }; - var grammar = new MarkupGrammar(settings); - var result = grammar.Nodes(Source("!{'hello world'}")); - - Assert.AreEqual(1, result.Value.Count); - Assert.AreEqual("\"hello world\"", (string)((ExpressionNode)result.Value[0]).Code); - Assert.IsFalse(((ExpressionNode)result.Value[0]).AutomaticEncoding); - } - - - [Test] - public void DollarHasEncodedContentWhenEnabled() - { - var settings = new ParserSettings { AutomaticEncoding = true }; - var grammar = new MarkupGrammar(settings); - var result = grammar.Nodes(Source("${'hello world'}")); - - Assert.AreEqual(1, result.Value.Count); - Assert.AreEqual("\"hello world\"", (string)((ExpressionNode)result.Value[0]).Code); - Assert.IsTrue(((ExpressionNode)result.Value[0]).AutomaticEncoding); - } - - - [Test] - public void BangSyntaxStillHasRawContentWhenEnabled() - { - var settings = new ParserSettings { AutomaticEncoding = true }; - var grammar = new MarkupGrammar(settings); - var result = grammar.Nodes(Source("!{'hello world'}")); - - Assert.AreEqual(1, result.Value.Count); - Assert.AreEqual("\"hello world\"", (string)((ExpressionNode)result.Value[0]).Code); - Assert.IsFalse(((ExpressionNode)result.Value[0]).AutomaticEncoding); - } - - [Test] - public void AutomaticEncodingFalseAlwaysAllowsRawHtml() - { - Init(false); - _viewFolder.Add(Path.Combine("home", "index.spark"), "${'hello'} !{'world'}"); - var content = RenderView(new SparkViewDescriptor().AddTemplate(Path.Combine("home", "index.spark"))); - Assert.AreEqual("hello world", content); - } - - [Test] - public void AutomaticEncodingTrueEncodesDollarSyntax() - { - Init(true); - _viewFolder.Add(Path.Combine("home", "index.spark"), "${'hello'} !{'world'}"); - var content = RenderView(new SparkViewDescriptor().AddTemplate(Path.Combine("home", "index.spark"))); - Assert.AreEqual("<span>hello</span> world", content); - } - - [Test] - public void AutomaticEncodingTrueOmitsRedundantEncoding() - { - Init(true); - _viewFolder.Add(Path.Combine("home", "index.spark"), "${H('hello')} !{H('world')}"); - var content = RenderView(new SparkViewDescriptor().AddTemplate(Path.Combine("home", "index.spark"))); - Assert.AreEqual("<span>hello</span> <span>world</span>", content); - } - - - [Test] - public void HashSyntaxForStatementsByDefault() - { - var settings = new ParserSettings { AutomaticEncoding = true }; - var grammar = new MarkupGrammar(settings); - var result = grammar.Nodes(Source(" #foo \r\n")); - - Assert.AreEqual(2, result.Value.Count); - var statement = result.Value.OfType().Single(); - Assert.That(statement.Code.ToString(), Is.EqualTo("foo ")); - } - - [Test] - public void CustomMarkerForStatements() - { - var settings = new ParserSettings { AutomaticEncoding = true, StatementMarker="hi" }; - var grammar = new MarkupGrammar(settings); - var result = grammar.Nodes(Source(" hibernate \r\n")); - - Assert.AreEqual(2, result.Value.Count); - var statement = result.Value.OfType().Single(); - Assert.That(statement.Code.ToString(), Is.EqualTo("bernate ")); - } - - - [Test] - public void HashSyntaxIgnoredWhenCustomMarkerProvided() - { - var settings = new ParserSettings { AutomaticEncoding = true, StatementMarker = "hi" }; - var grammar = new MarkupGrammar(settings); - var result = grammar.Nodes(Source(" #foo \r\n")); - - Assert.AreEqual(1, result.Value.Count); - var statement = result.Value.OfType().Any(); - Assert.That(statement, Is.False); - } - - } -} +// Copyright 2008-2009 Louis DeJardin - http://whereslou.com +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +using System.Linq; +using NUnit.Framework; + +using Spark.FileSystem; +using Spark.Parser; +using Spark.Parser.Markup; +using Spark.Tests.Stubs; +using System.IO; + +namespace Spark.Tests.Parser +{ + [TestFixture] + public class AutomaticEncodingTester + { + private ISparkViewEngine _engine; + private InMemoryViewFolder _viewFolder; + private ISparkViewEntry _entry; + private SparkSettings _settings; + + [SetUp] + public void Init() + { + Init(false); + } + + public void Init(bool automaticEncoding) + { + _settings = new SparkSettings() + .SetPageBaseType(typeof(StubSparkView)) + .SetAutomaticEncoding(automaticEncoding); + var container = new SparkServiceContainer(_settings); + + _viewFolder = new InMemoryViewFolder(); + + container.SetServiceBuilder(c => _viewFolder); + + _engine = container.GetService(); + } + + private string RenderView(SparkViewDescriptor descriptor) + { + _entry = _engine.CreateEntry(descriptor); + var view = _entry.CreateInstance(); + var contents = view.RenderView(); + _engine.ReleaseInstance(view); + return contents; + } + + private Position Source(string content) + { + return new Position(new SourceContext(content)); + } + + [Test] + public void DollarSyntaxHasRawContentWhenDisabled() + { + var settings = new ParserSettings {AutomaticEncoding = false}; + var grammar = new MarkupGrammar(settings); + var result = grammar.Nodes(Source("${'hello world'}")); + + Assert.AreEqual(1, result.Value.Count); + Assert.AreEqual("\"hello world\"", (string)((ExpressionNode)result.Value[0]).Code); + Assert.IsFalse(((ExpressionNode)result.Value[0]).AutomaticEncoding); + } + + [Test] + public void BangSyntaxHasRawContentWhenDisabled() + { + var settings = new ParserSettings { AutomaticEncoding = false }; + var grammar = new MarkupGrammar(settings); + var result = grammar.Nodes(Source("!{'hello world'}")); + + Assert.AreEqual(1, result.Value.Count); + Assert.AreEqual("\"hello world\"", (string)((ExpressionNode)result.Value[0]).Code); + Assert.IsFalse(((ExpressionNode)result.Value[0]).AutomaticEncoding); + } + + + [Test] + public void DollarHasEncodedContentWhenEnabled() + { + var settings = new ParserSettings { AutomaticEncoding = true }; + var grammar = new MarkupGrammar(settings); + var result = grammar.Nodes(Source("${'hello world'}")); + + Assert.AreEqual(1, result.Value.Count); + Assert.AreEqual("\"hello world\"", (string)((ExpressionNode)result.Value[0]).Code); + Assert.IsTrue(((ExpressionNode)result.Value[0]).AutomaticEncoding); + } + + + [Test] + public void BangSyntaxStillHasRawContentWhenEnabled() + { + var settings = new ParserSettings { AutomaticEncoding = true }; + var grammar = new MarkupGrammar(settings); + var result = grammar.Nodes(Source("!{'hello world'}")); + + Assert.AreEqual(1, result.Value.Count); + Assert.AreEqual("\"hello world\"", (string)((ExpressionNode)result.Value[0]).Code); + Assert.IsFalse(((ExpressionNode)result.Value[0]).AutomaticEncoding); + } + + [Test] + public void AutomaticEncodingFalseAlwaysAllowsRawHtml() + { + Init(false); + _viewFolder.Add(Path.Combine("home", "index.spark"), "${'hello'} !{'world'}"); + var content = RenderView(new SparkViewDescriptor().AddTemplate(Path.Combine("home", "index.spark"))); + Assert.AreEqual("hello world", content); + } + + [Test] + public void AutomaticEncodingTrueEncodesDollarSyntax() + { + Init(true); + _viewFolder.Add(Path.Combine("home", "index.spark"), "${'hello'} !{'world'}"); + var content = RenderView(new SparkViewDescriptor().AddTemplate(Path.Combine("home", "index.spark"))); + Assert.AreEqual("<span>hello</span> world", content); + } + + [Test] + public void AutomaticEncodingTrueOmitsRedundantEncoding() + { + Init(true); + _viewFolder.Add(Path.Combine("home", "index.spark"), "${H('hello')} !{H('world')}"); + var content = RenderView(new SparkViewDescriptor().AddTemplate(Path.Combine("home", "index.spark"))); + Assert.AreEqual("<span>hello</span> <span>world</span>", content); + } + + + [Test] + public void HashSyntaxForStatementsByDefault() + { + var settings = new ParserSettings { AutomaticEncoding = true }; + var grammar = new MarkupGrammar(settings); + var result = grammar.Nodes(Source(" #foo \r\n")); + + Assert.AreEqual(2, result.Value.Count); + var statement = result.Value.OfType().Single(); + Assert.That(statement.Code.ToString(), Is.EqualTo("foo ")); + } + + [Test] + public void CustomMarkerForStatements() + { + var settings = new ParserSettings { AutomaticEncoding = true, StatementMarker="hi" }; + var grammar = new MarkupGrammar(settings); + var result = grammar.Nodes(Source(" hibernate \r\n")); + + Assert.AreEqual(2, result.Value.Count); + var statement = result.Value.OfType().Single(); + Assert.That(statement.Code.ToString(), Is.EqualTo("bernate ")); + } + + + [Test] + public void HashSyntaxIgnoredWhenCustomMarkerProvided() + { + var settings = new ParserSettings { AutomaticEncoding = true, StatementMarker = "hi" }; + var grammar = new MarkupGrammar(settings); + var result = grammar.Nodes(Source(" #foo \r\n")); + + Assert.AreEqual(1, result.Value.Count); + var statement = result.Value.OfType().Any(); + Assert.That(statement, Is.False); + } + + } +} diff --git a/src/Spark.Tests/Parser/CSharpSyntaxProviderTester.cs b/src/Spark.Web.Tests/Parser/CSharpSyntaxProviderTester.cs similarity index 97% rename from src/Spark.Tests/Parser/CSharpSyntaxProviderTester.cs rename to src/Spark.Web.Tests/Parser/CSharpSyntaxProviderTester.cs index 06dcd2d5..c97d9bb9 100644 --- a/src/Spark.Tests/Parser/CSharpSyntaxProviderTester.cs +++ b/src/Spark.Web.Tests/Parser/CSharpSyntaxProviderTester.cs @@ -1,76 +1,76 @@ -// Copyright 2008-2009 Louis DeJardin - http://whereslou.com -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// -using NUnit.Framework; -using Spark.Compiler.NodeVisitors; -using Spark.FileSystem; -using Spark.Parser.Syntax; -using Spark.Tests.Stubs; -using System.IO; - -namespace Spark.Tests.Parser -{ - [TestFixture] - public class CSharpSyntaxProviderTester - { - private readonly CSharpSyntaxProvider _syntax = new CSharpSyntaxProvider(); - - [Test] - public void CanParseSimpleFile() - { - var context = new VisitorContext { ViewFolder = new FileSystemViewFolder("Spark.Tests.Views") }; - var result = _syntax.GetChunks(context, Path.Combine("Home", "childview.spark")); - Assert.IsNotNull(result); - } - - [Test] - public void UsingCSharpSyntaxInsideEngine() - { - // engine takes base class and IViewFolder - var engine = new SparkViewEngine( - new SparkSettings().SetPageBaseType("Spark.Tests.Stubs.StubSparkView")) { SyntaxProvider = _syntax, ViewFolder = new FileSystemViewFolder("Spark.Tests.Views") }; - - // describe and instantiate view - var descriptor = new SparkViewDescriptor(); - descriptor.Templates.Add(Path.Combine("Code", "simplecode.spark")); - var view = (StubSparkView)engine.CreateInstance(descriptor); - - // provide data and render - view.ViewData["hello"] = "world"; - var code = view.RenderView(); - - Assert.IsNotNull(code); - } - - - [Test] - public void StatementAndExpressionInCode() - { - // engine takes base class and IViewFolder - var engine = new SparkViewEngine( - new SparkSettings().SetPageBaseType("Spark.Tests.Stubs.StubSparkView")) { SyntaxProvider = _syntax, ViewFolder = new FileSystemViewFolder("Spark.Tests.Views") }; - - // describe and instantiate view - var descriptor = new SparkViewDescriptor(); - descriptor.Templates.Add(Path.Combine("Code", "foreach.spark")); - var view = (StubSparkView)engine.CreateInstance(descriptor); - - // provide data and render - view.ViewData["hello"] = "world"; - var code = view.RenderView(); - - Assert.IsNotNull(code); - } - } +// Copyright 2008-2009 Louis DeJardin - http://whereslou.com +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +using NUnit.Framework; +using Spark.Compiler.NodeVisitors; +using Spark.FileSystem; +using Spark.Parser.Syntax; +using Spark.Tests.Stubs; +using System.IO; + +namespace Spark.Tests.Parser +{ + [TestFixture] + public class CSharpSyntaxProviderTester + { + private readonly CSharpSyntaxProvider _syntax = new CSharpSyntaxProvider(); + + [Test] + public void CanParseSimpleFile() + { + var context = new VisitorContext { ViewFolder = new FileSystemViewFolder("Spark.Tests.Views") }; + var result = _syntax.GetChunks(context, Path.Combine("Home", "childview.spark")); + Assert.IsNotNull(result); + } + + [Test] + public void UsingCSharpSyntaxInsideEngine() + { + // engine takes base class and IViewFolder + var engine = new SparkViewEngine( + new SparkSettings().SetPageBaseType("Spark.Tests.Stubs.StubSparkView")) { SyntaxProvider = _syntax, ViewFolder = new FileSystemViewFolder("Spark.Tests.Views") }; + + // describe and instantiate view + var descriptor = new SparkViewDescriptor(); + descriptor.Templates.Add(Path.Combine("Code", "simplecode.spark")); + var view = (StubSparkView)engine.CreateInstance(descriptor); + + // provide data and render + view.ViewData["hello"] = "world"; + var code = view.RenderView(); + + Assert.IsNotNull(code); + } + + + [Test] + public void StatementAndExpressionInCode() + { + // engine takes base class and IViewFolder + var engine = new SparkViewEngine( + new SparkSettings().SetPageBaseType("Spark.Tests.Stubs.StubSparkView")) { SyntaxProvider = _syntax, ViewFolder = new FileSystemViewFolder("Spark.Tests.Views") }; + + // describe and instantiate view + var descriptor = new SparkViewDescriptor(); + descriptor.Templates.Add(Path.Combine("Code", "foreach.spark")); + var view = (StubSparkView)engine.CreateInstance(descriptor); + + // provide data and render + view.ViewData["hello"] = "world"; + var code = view.RenderView(); + + Assert.IsNotNull(code); + } + } } \ No newline at end of file diff --git a/src/Spark.Tests/Precompiled/ComplexPrecompileController.cs b/src/Spark.Web.Tests/Precompiled/ComplexPrecompileController.cs similarity index 97% rename from src/Spark.Tests/Precompiled/ComplexPrecompileController.cs rename to src/Spark.Web.Tests/Precompiled/ComplexPrecompileController.cs index 2e0dd548..970c8bd4 100644 --- a/src/Spark.Tests/Precompiled/ComplexPrecompileController.cs +++ b/src/Spark.Web.Tests/Precompiled/ComplexPrecompileController.cs @@ -1,23 +1,23 @@ -// Copyright 2008-2009 Louis DeJardin - http://whereslou.com -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// -namespace Spark.Tests.Precompiled -{ - [Precompile(Exclude = "Show*", Layout = "Default")] - [Precompile(Include = "_Foo _Bar", Layout = "Ajax")] - [Precompile(Include = "Show*", Layout = "Showing")] - public class ComplexPrecompileController - { - } -} +// Copyright 2008-2009 Louis DeJardin - http://whereslou.com +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +namespace Spark.Tests.Precompiled +{ + [Precompile(Exclude = "Show*", Layout = "Default")] + [Precompile(Include = "_Foo _Bar", Layout = "Ajax")] + [Precompile(Include = "Show*", Layout = "Showing")] + public class ComplexPrecompileController + { + } +} diff --git a/src/Spark.Tests/Precompiled/SimplePrecompileController.cs b/src/Spark.Web.Tests/Precompiled/SimplePrecompileController.cs similarity index 97% rename from src/Spark.Tests/Precompiled/SimplePrecompileController.cs rename to src/Spark.Web.Tests/Precompiled/SimplePrecompileController.cs index a182ba2e..173627aa 100644 --- a/src/Spark.Tests/Precompiled/SimplePrecompileController.cs +++ b/src/Spark.Web.Tests/Precompiled/SimplePrecompileController.cs @@ -1,21 +1,21 @@ -// Copyright 2008-2009 Louis DeJardin - http://whereslou.com -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// -namespace Spark.Tests.Precompiled -{ - [Precompile] - public class SimplePrecompileController - { - } +// Copyright 2008-2009 Louis DeJardin - http://whereslou.com +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +namespace Spark.Tests.Precompiled +{ + [Precompile] + public class SimplePrecompileController + { + } } \ No newline at end of file diff --git a/src/Spark.Tests/Precompiled/View1.cs b/src/Spark.Web.Tests/Precompiled/View1.cs similarity index 90% rename from src/Spark.Tests/Precompiled/View1.cs rename to src/Spark.Web.Tests/Precompiled/View1.cs index 903e7b1e..b4a2b96b 100644 --- a/src/Spark.Tests/Precompiled/View1.cs +++ b/src/Spark.Web.Tests/Precompiled/View1.cs @@ -1,44 +1,40 @@ -// Copyright 2008-2009 Louis DeJardin - http://whereslou.com -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// -using System; -using System.Collections.Generic; -using System.IO; -using System.Linq; -using System.Text; -using Spark.Tests.Stubs; - -namespace Spark.Tests.Precompiled -{ - [SparkView( - TargetNamespace = "Spark.Tests.Precompiled", - Templates = new[] { "Foo\\Bar.spark", "Shared\\Quux.spark" })] - public class View1 : StubSparkView - { - public override void Render() - { - Output.Write("

    Hello world

    "); - } - - public override Guid GeneratedViewId - { - get { return new Guid("11111111123412341234123456123456"); } - } - - public override bool TryGetViewData(string name, out object value) - { - throw new NotImplementedException(); - } - } -} +// Copyright 2008-2009 Louis DeJardin - http://whereslou.com +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +using System; +using Spark.Tests.Stubs; + +namespace Spark.Tests.Precompiled +{ + [SparkView( + TargetNamespace = "Spark.Tests.Precompiled", + Templates = new[] { "Foo\\Bar.spark", "Shared\\Quux.spark" })] + public class View1 : StubSparkView + { + public override void Render() + { + Output.Write("

    Hello world

    "); + } + + public override Guid GeneratedViewId + { + get { return new Guid("11111111123412341234123456123456"); } + } + + public override bool TryGetViewData(string name, out object value) + { + throw new NotImplementedException(); + } + } +} diff --git a/src/Spark.Tests/Precompiled/View2.cs b/src/Spark.Web.Tests/Precompiled/View2.cs similarity index 96% rename from src/Spark.Tests/Precompiled/View2.cs rename to src/Spark.Web.Tests/Precompiled/View2.cs index b475eccb..4f648b1e 100644 --- a/src/Spark.Tests/Precompiled/View2.cs +++ b/src/Spark.Web.Tests/Precompiled/View2.cs @@ -1,44 +1,44 @@ -// Copyright 2008-2009 Louis DeJardin - http://whereslou.com -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// -using System; -using System.Collections.Generic; -using System.IO; -using System.Linq; -using System.Text; -using Spark.Tests.Stubs; - -namespace Spark.Tests.Precompiled -{ - [SparkView( - TargetNamespace = "Spark.Tests.Precompiled", - Templates = new[] { "Hello\\World.spark", "Shared\\Default.spark" })] - public class View2 : ISparkView - { - public void RenderView(TextWriter writer) - { - writer.Write("

    Hello world

    "); - } - - public Guid GeneratedViewId - { - get { return new Guid("22222222123412341234123456123456"); } - } - - public bool TryGetViewData(string name, out object value) - { - throw new System.NotImplementedException(); - } - } -} +// Copyright 2008-2009 Louis DeJardin - http://whereslou.com +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +using System; +using System.Collections.Generic; +using System.IO; +using System.Linq; +using System.Text; +using Spark.Tests.Stubs; + +namespace Spark.Tests.Precompiled +{ + [SparkView( + TargetNamespace = "Spark.Tests.Precompiled", + Templates = new[] { "Hello\\World.spark", "Shared\\Default.spark" })] + public class View2 : ISparkView + { + public void RenderView(TextWriter writer) + { + writer.Write("

    Hello world

    "); + } + + public Guid GeneratedViewId + { + get { return new Guid("22222222123412341234123456123456"); } + } + + public bool TryGetViewData(string name, out object value) + { + throw new System.NotImplementedException(); + } + } +} diff --git a/src/Spark.Tests/Precompiled/View3.cs b/src/Spark.Web.Tests/Precompiled/View3.cs similarity index 96% rename from src/Spark.Tests/Precompiled/View3.cs rename to src/Spark.Web.Tests/Precompiled/View3.cs index e6aa53ac..f5f1b9cb 100644 --- a/src/Spark.Tests/Precompiled/View3.cs +++ b/src/Spark.Web.Tests/Precompiled/View3.cs @@ -1,39 +1,39 @@ -// Copyright 2008-2009 Louis DeJardin - http://whereslou.com -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// -using System; -using System.Collections.Generic; -using System.IO; -using System.Linq; -using System.Text; -using Spark.Tests.Stubs; - -namespace Spark.Tests.Precompiled -{ - [SparkView( - TargetNamespace = "Spark.Tests.Precompiled", - Templates = new[] { "Hello\\Sailor.spark", "Shared\\Default.spark" })] - public class View3 - { - public void RenderView(TextWriter writer) - { - writer.Write("

    Hello world

    "); - } - - public Guid GeneratedViewId - { - get { return new Guid("33333333123412341234123456123456"); } - } - } -} +// Copyright 2008-2009 Louis DeJardin - http://whereslou.com +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +using System; +using System.Collections.Generic; +using System.IO; +using System.Linq; +using System.Text; +using Spark.Tests.Stubs; + +namespace Spark.Tests.Precompiled +{ + [SparkView( + TargetNamespace = "Spark.Tests.Precompiled", + Templates = new[] { "Hello\\Sailor.spark", "Shared\\Default.spark" })] + public class View3 + { + public void RenderView(TextWriter writer) + { + writer.Write("

    Hello world

    "); + } + + public Guid GeneratedViewId + { + get { return new Guid("33333333123412341234123456123456"); } + } + } +} diff --git a/src/Spark.Tests/PrefixSupportTester.cs b/src/Spark.Web.Tests/PrefixSupportTester.cs similarity index 96% rename from src/Spark.Tests/PrefixSupportTester.cs rename to src/Spark.Web.Tests/PrefixSupportTester.cs index 7afb043d..f7496fd7 100644 --- a/src/Spark.Tests/PrefixSupportTester.cs +++ b/src/Spark.Web.Tests/PrefixSupportTester.cs @@ -1,218 +1,215 @@ -// Copyright 2008-2009 Louis DeJardin - http://whereslou.com -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// -using System; -using System.Collections.Generic; -using System.IO; -using System.Linq; -using System.Text; -using NUnit.Framework; -using Spark.FileSystem; -using Spark.Tests.Stubs; - -namespace Spark.Tests -{ - [TestFixture] - public class PrefixSupportTester - { - private SparkSettings _settings; - private SparkViewEngine _engine; - - [SetUp] - public void Init() - { - _settings = new SparkSettings() - .SetPageBaseType(typeof(StubSparkView)); - - _engine = new SparkViewEngine(_settings) - { - ViewFolder = new FileSystemViewFolder("Spark.Tests.Views") - }; - } - - static void ContainsInOrder(string content, params string[] values) - { - int index = 0; - foreach (string value in values) - { - int nextIndex = content.IndexOf(value, index); - Assert.GreaterOrEqual(nextIndex, 0, string.Format("Looking for {0}", value)); - index = nextIndex + value.Length; - } - } - - [Test] - public void PrefixFromSettings() - { - var settings = new SparkSettings() - .SetPageBaseType(typeof(StubSparkView)) - .SetPrefix("s"); - - var engine = new SparkViewEngine(settings) - { - ViewFolder = new FileSystemViewFolder("Spark.Tests.Views") - }; - - var view = (StubSparkView)engine.CreateInstance(new SparkViewDescriptor().AddTemplate(Path.Combine("Prefix", "prefix-from-settings.spark"))); - view.ViewData["Names"] = new[] { "alpha", "beta", "gamma" }; - - var output = new StringWriter(); - view.RenderView(output); - - ContainsInOrder(output.ToString(), - "", - "", - "", - "element ignored", - "

    attribute ignored

    " - ); - } - - - [Test] - public void PrefixFromXmlns() - { - var view = (StubSparkView)_engine.CreateInstance(new SparkViewDescriptor().AddTemplate(Path.Combine("Prefix", "prefix-from-xmlns.spark"))); - view.ViewData["Names"] = new[] { "alpha", "beta", "gamma" }; - - var output = new StringWriter(); - view.RenderView(output); - - ContainsInOrder(output.ToString(), - "", - "", - "", - "element ignored", - "

    attribute ignored

    "); - } - - - [Test] - public void ConditionalAttributes() - { - var view = (StubSparkView)_engine.CreateInstance(new SparkViewDescriptor().AddTemplate(Path.Combine("Prefix", "conditional-attributes.spark"))); - var output = new StringWriter(); - view.RenderView(output); - - ContainsInOrder(output.ToString(), - "ok1", - "ok2", - "ok3", - "ok4"); - - Assert.IsFalse(output.ToString().Contains("fail")); - Assert.IsFalse(output.ToString().Contains("if")); - Assert.IsFalse(output.ToString().Contains("else")); - Assert.IsFalse(output.ToString().Contains("condition")); - Assert.IsFalse(output.ToString().Contains("unless fail")); - } - - [Test] - public void MacroAndContentPrefixes() - { - var view = - (StubSparkView) - _engine.CreateInstance(new SparkViewDescriptor().AddTemplate(Path.Combine("Prefix", "macro-content-prefix.spark"))); - var output = new StringWriter(); - view.RenderView(output); - - ContainsInOrder(output.ToString(), - "

    one

    ", - "

    two

    ", - "

    Hello, world!

    ", - "

    three

    ", - "

    four

    ", - "ignored", - "ignored", - "ignored", - "ignored", - "ignored" - ); - } - - [Test] - public void SegmentAndRenderPrefixes() - { - var view = - (StubSparkView) - _engine.CreateInstance(new SparkViewDescriptor().AddTemplate(Path.Combine("Prefix", "segment-render-prefix.spark"))); - var output = new StringWriter(); - view.RenderView(output); - - ContainsInOrder(output.ToString(), - "

    one

    ", - "

    two

    ", - "

    three

    ", - "ignored", - "ignored", - "ignored", - "ignored", - "ignored" - ); - } - - [Test] - public void SectionAsSegmentAndRenderPrefixes() - { - var settings = new SparkSettings() - .SetPageBaseType(typeof (StubSparkView)) - .SetParseSectionTagAsSegment(true); - - var engine = new SparkViewEngine(settings) - { - ViewFolder = new FileSystemViewFolder("Spark.Tests.Views") - }; - - var view = - (StubSparkView) - engine.CreateInstance(new SparkViewDescriptor().AddTemplate(Path.Combine("Prefix", "section-render-prefix.spark"))); - var output = new StringWriter(); - view.RenderView(output); - - ContainsInOrder(output.ToString(), - "

    one

    ", - "

    two

    ", - "

    three

    ", - "ignored", - "ignored", - "ignored", - "ignored", - "ignored" - ); - } - - [Test] - public void MacroAndContentPrefixesFromSettings() - { - _engine.Settings = new SparkSettings() - .SetPageBaseType(typeof(StubSparkView)) - .SetPrefix("s"); - - var view = - (StubSparkView) - _engine.CreateInstance(new SparkViewDescriptor().AddTemplate(Path.Combine("Prefix", "macro-content-prefix-from-settings.spark"))); - var output = new StringWriter(); - view.RenderView(output); - - ContainsInOrder(output.ToString(), - "

    one

    ", - "

    two

    ", - "

    Hello, world!

    ", - "

    three

    ", - "

    four

    ", - "ignored" - ); - } - } -} +// Copyright 2008-2009 Louis DeJardin - http://whereslou.com +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +using System.IO; +using NUnit.Framework; +using Spark.FileSystem; +using Spark.Tests.Stubs; + +namespace Spark.Tests +{ + [TestFixture] + public class PrefixSupportTester + { + private SparkSettings _settings; + private SparkViewEngine _engine; + + [SetUp] + public void Init() + { + _settings = new SparkSettings() + .SetPageBaseType(typeof(StubSparkView)); + + _engine = new SparkViewEngine(_settings) + { + ViewFolder = new FileSystemViewFolder("Spark.Tests.Views") + }; + } + + static void ContainsInOrder(string content, params string[] values) + { + int index = 0; + foreach (string value in values) + { + int nextIndex = content.IndexOf(value, index); + Assert.GreaterOrEqual(nextIndex, 0, string.Format("Looking for {0}", value)); + index = nextIndex + value.Length; + } + } + + [Test] + public void PrefixFromSettings() + { + var settings = new SparkSettings() + .SetPageBaseType(typeof(StubSparkView)) + .SetPrefix("s"); + + var engine = new SparkViewEngine(settings) + { + ViewFolder = new FileSystemViewFolder("Spark.Tests.Views") + }; + + var view = (StubSparkView)engine.CreateInstance(new SparkViewDescriptor().AddTemplate(Path.Combine("Prefix", "prefix-from-settings.spark"))); + view.ViewData["Names"] = new[] { "alpha", "beta", "gamma" }; + + var output = new StringWriter(); + view.RenderView(output); + + ContainsInOrder(output.ToString(), + "", + "", + "", + "element ignored", + "

    attribute ignored

    " + ); + } + + + [Test] + public void PrefixFromXmlns() + { + var view = (StubSparkView)_engine.CreateInstance(new SparkViewDescriptor().AddTemplate(Path.Combine("Prefix", "prefix-from-xmlns.spark"))); + view.ViewData["Names"] = new[] { "alpha", "beta", "gamma" }; + + var output = new StringWriter(); + view.RenderView(output); + + ContainsInOrder(output.ToString(), + "", + "", + "", + "element ignored", + "

    attribute ignored

    "); + } + + + [Test] + public void ConditionalAttributes() + { + var view = (StubSparkView)_engine.CreateInstance(new SparkViewDescriptor().AddTemplate(Path.Combine("Prefix", "conditional-attributes.spark"))); + var output = new StringWriter(); + view.RenderView(output); + + ContainsInOrder(output.ToString(), + "ok1", + "ok2", + "ok3", + "ok4"); + + Assert.IsFalse(output.ToString().Contains("fail")); + Assert.IsFalse(output.ToString().Contains("if")); + Assert.IsFalse(output.ToString().Contains("else")); + Assert.IsFalse(output.ToString().Contains("condition")); + Assert.IsFalse(output.ToString().Contains("unless fail")); + } + + [Test] + public void MacroAndContentPrefixes() + { + var view = + (StubSparkView) + _engine.CreateInstance(new SparkViewDescriptor().AddTemplate(Path.Combine("Prefix", "macro-content-prefix.spark"))); + var output = new StringWriter(); + view.RenderView(output); + + ContainsInOrder(output.ToString(), + "

    one

    ", + "

    two

    ", + "

    Hello, world!

    ", + "

    three

    ", + "

    four

    ", + "ignored", + "ignored", + "ignored", + "ignored", + "ignored" + ); + } + + [Test] + public void SegmentAndRenderPrefixes() + { + var view = + (StubSparkView) + _engine.CreateInstance(new SparkViewDescriptor().AddTemplate(Path.Combine("Prefix", "segment-render-prefix.spark"))); + var output = new StringWriter(); + view.RenderView(output); + + ContainsInOrder(output.ToString(), + "

    one

    ", + "

    two

    ", + "

    three

    ", + "ignored", + "ignored", + "ignored", + "ignored", + "ignored" + ); + } + + [Test] + public void SectionAsSegmentAndRenderPrefixes() + { + var settings = new SparkSettings() + .SetPageBaseType(typeof (StubSparkView)) + .SetParseSectionTagAsSegment(true); + + var engine = new SparkViewEngine(settings) + { + ViewFolder = new FileSystemViewFolder("Spark.Tests.Views") + }; + + var view = + (StubSparkView) + engine.CreateInstance(new SparkViewDescriptor().AddTemplate(Path.Combine("Prefix", "section-render-prefix.spark"))); + var output = new StringWriter(); + view.RenderView(output); + + ContainsInOrder(output.ToString(), + "

    one

    ", + "

    two

    ", + "

    three

    ", + "ignored", + "ignored", + "ignored", + "ignored", + "ignored" + ); + } + + [Test] + public void MacroAndContentPrefixesFromSettings() + { + _engine.Settings = new SparkSettings() + .SetPageBaseType(typeof(StubSparkView)) + .SetPrefix("s"); + + var view = + (StubSparkView) + _engine.CreateInstance(new SparkViewDescriptor().AddTemplate(Path.Combine("Prefix", "macro-content-prefix-from-settings.spark"))); + var output = new StringWriter(); + view.RenderView(output); + + ContainsInOrder(output.ToString(), + "

    one

    ", + "

    two

    ", + "

    Hello, world!

    ", + "

    three

    ", + "

    four

    ", + "ignored" + ); + } + } +} diff --git a/src/Spark.Web.Tests/Spark.Web.Tests.csproj b/src/Spark.Web.Tests/Spark.Web.Tests.csproj new file mode 100644 index 00000000..5a5f6d34 --- /dev/null +++ b/src/Spark.Web.Tests/Spark.Web.Tests.csproj @@ -0,0 +1,22 @@ + + + Library + net481 + AllRules.ruleset + Spark + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/src/Spark.Tests/SparkBatchDescriptorTester.cs b/src/Spark.Web.Tests/SparkBatchDescriptorTester.cs similarity index 93% rename from src/Spark.Tests/SparkBatchDescriptorTester.cs rename to src/Spark.Web.Tests/SparkBatchDescriptorTester.cs index cc680718..bd882389 100644 --- a/src/Spark.Tests/SparkBatchDescriptorTester.cs +++ b/src/Spark.Web.Tests/SparkBatchDescriptorTester.cs @@ -1,70 +1,68 @@ -// Copyright 2008-2009 Louis DeJardin - http://whereslou.com -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using NUnit.Framework; -using Spark.Tests.Precompiled; - -namespace Spark.Tests -{ - [TestFixture] - public class SparkBatchDescriptorTester - { - - [Test] - public void BatchForControllerWithSimplePrecompileAttrib() - { - var batch = new SparkBatchDescriptor() - .FromAttributes(); - - Assert.AreEqual(1, batch.Entries.Count); - Assert.AreSame(typeof(SimplePrecompileController), batch.Entries[0].ControllerType); - Assert.AreEqual(0, batch.Entries[0].ExcludeViews.Count); - Assert.AreEqual(0, batch.Entries[0].IncludeViews.Count); - Assert.AreEqual(0, batch.Entries[0].LayoutNames.Count); - } - - [Test] - public void BatchForControllerWithComplexPrecompileAttrib() - { - var batch = new SparkBatchDescriptor() - .FromAttributes(); - - Assert.AreEqual(3, batch.Entries.Count); - var forDefault = batch.Entries.First(e => e.LayoutNames[0][0] == "Default"); - var forAjax = batch.Entries.First(e => e.LayoutNames[0][0] == "Ajax"); - var forShowing = batch.Entries.First(e => e.LayoutNames[0][0] == "Showing"); - - Assert.AreEqual(0, forDefault.IncludeViews.Count); - Assert.AreEqual(1, forDefault.ExcludeViews.Count); - Assert.AreEqual(2, forAjax.IncludeViews.Count); - Assert.AreEqual(0, forAjax.ExcludeViews.Count); - Assert.AreEqual(1, forShowing.IncludeViews.Count); - Assert.AreEqual(0, forShowing.ExcludeViews.Count); - } - - [Test] - public void BatchFromAssembly() - { - var batch = new SparkBatchDescriptor() - .FromAssemblyNamed("Spark.Tests"); - - Assert.AreEqual(1, batch.Entries.Count(e => e.ControllerType == typeof(SimplePrecompileController))); - Assert.AreEqual(3, batch.Entries.Count(e => e.ControllerType == typeof(ComplexPrecompileController))); - } - } -} +// Copyright 2008-2009 Louis DeJardin - http://whereslou.com +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +using System.Linq; +using NUnit.Framework; +using Spark.Tests.Precompiled; + +namespace Spark.Tests +{ + [TestFixture] + public class SparkBatchDescriptorTester + { + + [Test] + public void BatchForControllerWithSimplePrecompileAttrib() + { + var batch = new SparkBatchDescriptor() + .FromAttributes(); + + Assert.AreEqual(1, batch.Entries.Count); + Assert.AreSame(typeof(SimplePrecompileController), batch.Entries[0].ControllerType); + Assert.AreEqual(0, batch.Entries[0].ExcludeViews.Count); + Assert.AreEqual(0, batch.Entries[0].IncludeViews.Count); + Assert.AreEqual(0, batch.Entries[0].LayoutNames.Count); + } + + [Test] + public void BatchForControllerWithComplexPrecompileAttrib() + { + var batch = new SparkBatchDescriptor() + .FromAttributes(); + + Assert.AreEqual(3, batch.Entries.Count); + var forDefault = batch.Entries.First(e => e.LayoutNames[0][0] == "Default"); + var forAjax = batch.Entries.First(e => e.LayoutNames[0][0] == "Ajax"); + var forShowing = batch.Entries.First(e => e.LayoutNames[0][0] == "Showing"); + + Assert.AreEqual(0, forDefault.IncludeViews.Count); + Assert.AreEqual(1, forDefault.ExcludeViews.Count); + Assert.AreEqual(2, forAjax.IncludeViews.Count); + Assert.AreEqual(0, forAjax.ExcludeViews.Count); + Assert.AreEqual(1, forShowing.IncludeViews.Count); + Assert.AreEqual(0, forShowing.ExcludeViews.Count); + } + + [Test] + public void BatchFromAssembly() + { + var batch = new SparkBatchDescriptor() + .FromAssemblyNamed("Spark.Web.Tests"); + + Assert.AreEqual(1, batch.Entries.Count(e => e.ControllerType == typeof(SimplePrecompileController))); + Assert.AreEqual(3, batch.Entries.Count(e => e.ControllerType == typeof(ComplexPrecompileController))); + } + } +} diff --git a/src/Spark.Tests/SparkDecoratorTester.cs b/src/Spark.Web.Tests/SparkDecoratorTester.cs similarity index 90% rename from src/Spark.Tests/SparkDecoratorTester.cs rename to src/Spark.Web.Tests/SparkDecoratorTester.cs index c12b3548..1dd21de0 100644 --- a/src/Spark.Tests/SparkDecoratorTester.cs +++ b/src/Spark.Web.Tests/SparkDecoratorTester.cs @@ -1,72 +1,67 @@ -using System; -using System.Collections.Generic; -using System.IO; -using System.Linq; -using System.Text; -using NUnit.Framework; -using Spark.Spool; - -namespace Spark.Tests -{ - [TestFixture] - public class SparkDecoratorTester - { - [Test] - public void OutputContentCollectionWorksBetweenLayers() - { - var layer0 = new TestLayer0(); - var layer1 = new TestLayer1(layer0); - var content = layer1.RenderView(); - Assert.AreEqual("[layer1top][layer0head][layer1head][layer0][layer1bottom]", content); - } - - public class TestLayer0 : SparkViewDecorator - { - public TestLayer0() - : base(null) - { - } - - public override Guid GeneratedViewId - { - get { throw new System.NotImplementedException(); } - } - - public override void Render() - { - Output.Write("[layer0]"); - - using (OutputScope("head")) - { - Output.Write("[layer0head]"); - } - } - } - - public class TestLayer1 : SparkViewDecorator - { - public TestLayer1(SparkViewBase decorated) - : base(decorated) - { - } - - public override Guid GeneratedViewId - { - get { throw new System.NotImplementedException(); } - } - - public override void Render() - { - using (OutputScope("head")) - { - Output.Write("[layer1head]"); - } - - Output.Write("[layer1top]"); - Output.Write(Content["head"]); - Output.Write(Content["view"]); - Output.Write("[layer1bottom]"); - } - } - } -} +using System; +using NUnit.Framework; + +namespace Spark.Tests +{ + [TestFixture] + public class SparkDecoratorTester + { + [Test] + public void OutputContentCollectionWorksBetweenLayers() + { + var layer0 = new TestLayer0(); + var layer1 = new TestLayer1(layer0); + var content = layer1.RenderView(); + Assert.AreEqual("[layer1top][layer0head][layer1head][layer0][layer1bottom]", content); + } + + public class TestLayer0 : SparkViewDecorator + { + public TestLayer0() + : base(null) + { + } + + public override Guid GeneratedViewId + { + get { throw new System.NotImplementedException(); } + } + + public override void Render() + { + Output.Write("[layer0]"); + + using (OutputScope("head")) + { + Output.Write("[layer0head]"); + } + } + } + + public class TestLayer1 : SparkViewDecorator + { + public TestLayer1(SparkViewBase decorated) + : base(decorated) + { + } + + public override Guid GeneratedViewId + { + get { throw new System.NotImplementedException(); } + } + + public override void Render() + { + using (OutputScope("head")) + { + Output.Write("[layer1head]"); + } + + Output.Write("[layer1top]"); + Output.Write(Content["head"]); + Output.Write(Content["view"]); + Output.Write("[layer1bottom]"); + } + } + } +} diff --git a/src/Spark.Tests/SparkExtensionTester.cs b/src/Spark.Web.Tests/SparkExtensionTester.cs similarity index 97% rename from src/Spark.Tests/SparkExtensionTester.cs rename to src/Spark.Web.Tests/SparkExtensionTester.cs index 8d4e9a88..1d9bd7d2 100644 --- a/src/Spark.Tests/SparkExtensionTester.cs +++ b/src/Spark.Web.Tests/SparkExtensionTester.cs @@ -1,74 +1,74 @@ -// Copyright 2008-2009 Louis DeJardin - http://whereslou.com -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// -using System.Collections.Generic; -using System.Text; -using NUnit.Framework; -using Spark.Compiler; -using Spark.Compiler.ChunkVisitors; -using Spark.Compiler.NodeVisitors; -using Spark.FileSystem; -using Spark.Parser.Markup; -using System.IO; - -namespace Spark.Tests -{ - [TestFixture] - public class SparkExtensionTester - { - private SparkViewEngine engine; - - [SetUp] - public void Init() - { - engine = new SparkViewEngine(new SparkSettings().SetPageBaseType("Spark.Tests.Stubs.StubSparkView")) - {ViewFolder = new FileSystemViewFolder("Spark.Tests.Views")}; - engine.ExtensionFactory = new StubExtensionFactory(); - } - - [Test] - public void TestExtensions() - { - var descriptor = new SparkViewDescriptor(); - descriptor.Templates.Add(Path.Combine("Home", "extensionelements.spark")); - var entry = engine.CreateEntry(descriptor); - Assert.That(entry.SourceCode.Contains("//this was a test")); - } - } - - internal class StubExtensionFactory : ISparkExtensionFactory - { - public ISparkExtension CreateExtension(VisitorContext context, ElementNode node) - { - if (node.Name == "unittest") - return new TestExtension(); - - return null; - } - } - - internal class TestExtension : ISparkExtension - { - public void VisitNode(INodeVisitor visitor, IList body, IList chunks) - { - - } - - public void VisitChunk(IChunkVisitor visitor, OutputLocation location, IList chunks, StringBuilder output) - { - if (location == OutputLocation.UsingNamespace) - output.AppendLine("//this was a test"); - } - } -} +// Copyright 2008-2009 Louis DeJardin - http://whereslou.com +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +using System.Collections.Generic; +using System.Text; +using NUnit.Framework; +using Spark.Compiler; +using Spark.Compiler.ChunkVisitors; +using Spark.Compiler.NodeVisitors; +using Spark.FileSystem; +using Spark.Parser.Markup; +using System.IO; + +namespace Spark.Tests +{ + [TestFixture] + public class SparkExtensionTester + { + private SparkViewEngine engine; + + [SetUp] + public void Init() + { + engine = new SparkViewEngine(new SparkSettings().SetPageBaseType("Spark.Tests.Stubs.StubSparkView")) + {ViewFolder = new FileSystemViewFolder("Spark.Tests.Views")}; + engine.ExtensionFactory = new StubExtensionFactory(); + } + + [Test] + public void TestExtensions() + { + var descriptor = new SparkViewDescriptor(); + descriptor.Templates.Add(Path.Combine("Home", "extensionelements.spark")); + var entry = engine.CreateEntry(descriptor); + Assert.That(entry.SourceCode.Contains("//this was a test")); + } + } + + internal class StubExtensionFactory : ISparkExtensionFactory + { + public ISparkExtension CreateExtension(VisitorContext context, ElementNode node) + { + if (node.Name == "unittest") + return new TestExtension(); + + return null; + } + } + + internal class TestExtension : ISparkExtension + { + public void VisitNode(INodeVisitor visitor, IList body, IList chunks) + { + + } + + public void VisitChunk(IChunkVisitor visitor, OutputLocation location, IList chunks, StringBuilder output) + { + if (location == OutputLocation.UsingNamespace) + output.AppendLine("//this was a test"); + } + } +} diff --git a/src/Spark.Tests/SparkServiceContainerTester.cs b/src/Spark.Web.Tests/SparkServiceContainerTester.cs similarity index 97% rename from src/Spark.Tests/SparkServiceContainerTester.cs rename to src/Spark.Web.Tests/SparkServiceContainerTester.cs index e05b8d63..1ab00e8e 100644 --- a/src/Spark.Tests/SparkServiceContainerTester.cs +++ b/src/Spark.Web.Tests/SparkServiceContainerTester.cs @@ -1,164 +1,164 @@ -// Copyright 2008-2009 Louis DeJardin - http://whereslou.com -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// -using System; -using System.Collections.Generic; -using System.Configuration; -using System.Linq; -using System.Text; -using NUnit.Framework; -using Spark.Bindings; -using Spark.FileSystem; -using System.IO; - -namespace Spark.Tests -{ - [TestFixture] - public class SparkServiceContainerTester - { - [Test] - public void ContainerCreatesDefaultServices() - { - var container = new SparkServiceContainer(); - - var langauageFactory = container.GetService(); - Assert.IsInstanceOf(typeof(DefaultLanguageFactory), langauageFactory); - - var resourcePathManager = container.GetService(); - Assert.IsInstanceOf(typeof(DefaultResourcePathManager), resourcePathManager); - - var bindingProvider = container.GetService(); - Assert.IsInstanceOf(typeof(DefaultBindingProvider), bindingProvider); - - var partialProvider = container.GetService(); - Assert.IsInstanceOf(typeof(DefaultPartialProvider), partialProvider); - - var partialReferenceProvider = container.GetService(); - Assert.IsInstanceOf(typeof(DefaultPartialReferenceProvider), partialReferenceProvider); - } - - [Test] - public void ConfigSettingsUsedByDefault() - { - var container = new SparkServiceContainer(); - - var settings = container.GetService().Settings; - Assert.AreSame(ConfigurationManager.GetSection("spark"), settings); - } - - [Test] - public void CreatedSettingsUsedWhenProvided() - { - var settings = new SparkSettings().SetPrefix("foo"); - var container = new SparkServiceContainer(settings); - - var settings2 = container.GetService().Settings; - Assert.AreSame(settings, settings2); - } - - [Test] - public void SettingsServiceReplacesType() - { - var container = new SparkServiceContainer(); - container.SetService(new StubExtensionFactory()); - Assert.IsInstanceOf(typeof(StubExtensionFactory), container.GetService()); - } - - [Test] - public void AddingServiceInstanceCallsInitialize() - { - var container = new SparkServiceContainer(); - var service = new TestService(); - Assert.IsFalse(service.Initialized); - container.SetService(service); - Assert.IsTrue(service.Initialized); - Assert.AreSame(service, container.GetService()); - } - - [Test] - public void AddingServiceBuilderCallsInitialize() - { - var container = new SparkServiceContainer(); - container.SetServiceBuilder(typeof(ITestService), c => new TestService()); - var service = container.GetService(); - Assert.IsInstanceOf(typeof(TestService), service); - Assert.IsTrue(((TestService)service).Initialized); - } - - [Test] - public void EngineGetsCustomServiceAndViewFolderSettings() - { - var settings = new SparkSettings(); - settings.AddViewFolder(typeof(TestViewFolder), - new Dictionary { { "testpath", Path.Combine("hello", "world.spark") } }); - - var container = new SparkServiceContainer(settings); - container.SetServiceBuilder(c=>new TestActivatorFactory()); - - var engine = container.GetService(); - Assert.IsInstanceOf(typeof(TestActivatorFactory), engine.ViewActivatorFactory); - - Assert.IsTrue(engine.ViewFolder.HasView(Path.Combine("hello", "world.spark"))); - } - } - - public interface ITestService - { - - } - public class TestService : ITestService, ISparkServiceInitialize - { - public bool Initialized { get; set; } - public void Initialize(ISparkServiceContainer container) - { - Initialized = true; - } - } - public class TestViewFolder : IViewFolder - { - private readonly string _testpath; - - public TestViewFolder(string testpath) - { - _testpath = testpath; - } - - public IViewFile GetViewSource(string path) - { - throw new System.NotImplementedException(); - } - - public IList ListViews(string path) - { - throw new System.NotImplementedException(); - } - - public bool HasView(string path) - { - return path == _testpath; - } - } - public class TestActivatorFactory : IViewActivatorFactory - { - public IViewActivator Register(Type type) - { - throw new System.NotImplementedException(); - } - - public void Unregister(Type type, IViewActivator activator) - { - throw new System.NotImplementedException(); - } - } -} +// Copyright 2008-2009 Louis DeJardin - http://whereslou.com +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +using System; +using System.Collections.Generic; +using System.Configuration; +using System.Linq; +using System.Text; +using NUnit.Framework; +using Spark.Bindings; +using Spark.FileSystem; +using System.IO; + +namespace Spark.Tests +{ + [TestFixture] + public class SparkServiceContainerTester + { + [Test] + public void ContainerCreatesDefaultServices() + { + var container = new SparkServiceContainer(); + + var langauageFactory = container.GetService(); + Assert.IsInstanceOf(typeof(DefaultLanguageFactory), langauageFactory); + + var resourcePathManager = container.GetService(); + Assert.IsInstanceOf(typeof(DefaultResourcePathManager), resourcePathManager); + + var bindingProvider = container.GetService(); + Assert.IsInstanceOf(typeof(DefaultBindingProvider), bindingProvider); + + var partialProvider = container.GetService(); + Assert.IsInstanceOf(typeof(DefaultPartialProvider), partialProvider); + + var partialReferenceProvider = container.GetService(); + Assert.IsInstanceOf(typeof(DefaultPartialReferenceProvider), partialReferenceProvider); + } + + [Test] + public void ConfigSettingsUsedByDefault() + { + var container = new SparkServiceContainer(); + + var settings = container.GetService().Settings; + Assert.AreSame(ConfigurationManager.GetSection("spark"), settings); + } + + [Test] + public void CreatedSettingsUsedWhenProvided() + { + var settings = new SparkSettings().SetPrefix("foo"); + var container = new SparkServiceContainer(settings); + + var settings2 = container.GetService().Settings; + Assert.AreSame(settings, settings2); + } + + [Test] + public void SettingsServiceReplacesType() + { + var container = new SparkServiceContainer(); + container.SetService(new StubExtensionFactory()); + Assert.IsInstanceOf(typeof(StubExtensionFactory), container.GetService()); + } + + [Test] + public void AddingServiceInstanceCallsInitialize() + { + var container = new SparkServiceContainer(); + var service = new TestService(); + Assert.IsFalse(service.Initialized); + container.SetService(service); + Assert.IsTrue(service.Initialized); + Assert.AreSame(service, container.GetService()); + } + + [Test] + public void AddingServiceBuilderCallsInitialize() + { + var container = new SparkServiceContainer(); + container.SetServiceBuilder(typeof(ITestService), c => new TestService()); + var service = container.GetService(); + Assert.IsInstanceOf(typeof(TestService), service); + Assert.IsTrue(((TestService)service).Initialized); + } + + [Test] + public void EngineGetsCustomServiceAndViewFolderSettings() + { + var settings = new SparkSettings(); + settings.AddViewFolder(typeof(TestViewFolder), + new Dictionary { { "testpath", Path.Combine("hello", "world.spark") } }); + + var container = new SparkServiceContainer(settings); + container.SetServiceBuilder(c=>new TestActivatorFactory()); + + var engine = container.GetService(); + Assert.IsInstanceOf(typeof(TestActivatorFactory), engine.ViewActivatorFactory); + + Assert.IsTrue(engine.ViewFolder.HasView(Path.Combine("hello", "world.spark"))); + } + } + + public interface ITestService + { + + } + public class TestService : ITestService, ISparkServiceInitialize + { + public bool Initialized { get; set; } + public void Initialize(ISparkServiceContainer container) + { + Initialized = true; + } + } + public class TestViewFolder : IViewFolder + { + private readonly string _testpath; + + public TestViewFolder(string testpath) + { + _testpath = testpath; + } + + public IViewFile GetViewSource(string path) + { + throw new System.NotImplementedException(); + } + + public IList ListViews(string path) + { + throw new System.NotImplementedException(); + } + + public bool HasView(string path) + { + return path == _testpath; + } + } + public class TestActivatorFactory : IViewActivatorFactory + { + public IViewActivator Register(Type type) + { + throw new System.NotImplementedException(); + } + + public void Unregister(Type type, IViewActivator activator) + { + throw new System.NotImplementedException(); + } + } +} diff --git a/src/Spark.Tests/SparkViewFactoryTester.cs b/src/Spark.Web.Tests/SparkViewFactoryTester.cs similarity index 97% rename from src/Spark.Tests/SparkViewFactoryTester.cs rename to src/Spark.Web.Tests/SparkViewFactoryTester.cs index 92f4e8f1..9e186fda 100644 --- a/src/Spark.Tests/SparkViewFactoryTester.cs +++ b/src/Spark.Web.Tests/SparkViewFactoryTester.cs @@ -1,1481 +1,1478 @@ -//------------------------------------------------------------------------- -// -// Copyright 2008-2010 Louis DeJardin - http://whereslou.com -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// -// Louis DeJardin -// Gauthier Segay -// Jacob Proffitt -// John Gietzen -//------------------------------------------------------------------------- - -using System.Linq; - -namespace Spark.Tests -{ - using System; - using System.Collections.Generic; - using System.Text; - using NUnit.Framework; - - using Rhino.Mocks; - using Spark.Compiler; - using Spark.FileSystem; - using Spark.Tests.Models; - using Spark.Tests.Stubs; - - [TestFixture, Category("SparkViewEngine")] - public class SparkViewFactoryTester - { - private MockRepository mocks; - - private StubViewFactory factory; - private SparkViewEngine engine; - private StringBuilder sb; - private SparkSettings settings; - - [SetUp] - public void Init() - { - settings = new SparkSettings().SetPageBaseType("Spark.Tests.Stubs.StubSparkView"); - engine = new SparkViewEngine(settings) { ViewFolder = new FileSystemViewFolder("Spark.Tests.Views") }; - factory = new StubViewFactory { Engine = engine }; - - sb = new StringBuilder(); - - mocks = new MockRepository(); - - } - - StubViewContext MakeViewContext(string viewName, string masterName) - { - return new StubViewContext { ControllerName = "Home", ViewName = viewName, MasterName = masterName, Output = sb }; - } - - StubViewContext MakeViewContext(string viewName, string masterName, StubViewData data) - { - return new StubViewContext { ControllerName = "Home", ViewName = viewName, MasterName = masterName, Output = sb, Data = data }; - } - - - - [Test] - public void RenderPlainView() - { - mocks.ReplayAll(); - - factory.RenderView(MakeViewContext("Index", null)); - - mocks.VerifyAll(); - } - - - [Test] - public void ForEachTest() - { - mocks.ReplayAll(); - - factory.RenderView(MakeViewContext("foreach", null)); - - mocks.VerifyAll(); - - string content = sb.ToString(); - Assert.That(content.Contains(@"
  • 1: foo
  • ")); - Assert.That(content.Contains(@"
  • 2: bar
  • ")); - Assert.That(content.Contains(@"
  • 3: baaz
  • ")); - } - - - [Test] - public void GlobalSetTest() - { - - mocks.ReplayAll(); - - factory.RenderView(MakeViewContext("globalset", null)); - - mocks.VerifyAll(); - - string content = sb.ToString(); - Assert.That(content.Contains("

    default: Global set test

    ")); - Assert.That(content.Contains("

    7==7

    ")); - } - - [Test] - public void MasterTest() - { - mocks.ReplayAll(); - - factory.RenderView(MakeViewContext("childview", "layout")); - - mocks.VerifyAll(); - string content = sb.ToString(); - Assert.That(content.Contains("Standalone Index View")); - Assert.That(content.Contains("

    Standalone Index View

    ")); - Assert.That(content.Contains("

    no header by default

    ")); - Assert.That(content.Contains("

    no footer by default

    ")); - } - - [Test] - public void CaptureNamedContent() - { - - mocks.ReplayAll(); - - factory.RenderView(MakeViewContext("namedcontent", "layout")); - - mocks.VerifyAll(); - string content = sb.ToString(); - Assert.That(content.Contains("

    main content

    ")); - Assert.That(content.Contains("

    this is the header

    ")); - Assert.That(content.Contains("

    footer part one

    ")); - Assert.That(content.Contains("

    footer part two

    ")); - } - - [Test] - public void UsingPartialFile() - { - mocks.ReplayAll(); - - factory.RenderView(MakeViewContext("usingpartial", null)); - - mocks.VerifyAll(); - string content = sb.ToString(); - Assert.That(content.Contains("
  • Partial where x=\"zero\"
  • ")); - Assert.That(content.Contains("
  • Partial where x=\"one\"
  • ")); - Assert.That(content.Contains("
  • Partial where x=\"two\"
  • ")); - Assert.That(content.Contains("
  • Partial where x=\"three\"
  • ")); - Assert.That(content.Contains("
  • Partial where x=\"four\"
  • ")); - } - - [Test] - public void UsingPartialWithRenderElement() - { - mocks.ReplayAll(); - - factory.RenderView(MakeViewContext("usingpartial-render-element", null)); - - mocks.VerifyAll(); - string content = sb.ToString(); - Assert.That(content.Contains("
  • Partial where x=\"zero\"
  • ")); - Assert.That(content.Contains("
  • Partial where x=\"one\"
  • ")); - Assert.That(content.Contains("
  • Partial where x=\"two\"
  • ")); - Assert.That(content.Contains("
  • Partial where x=\"three\"
  • ")); - Assert.That(content.Contains("
  • Partial where x=\"four\"
  • ")); - } - - [Test] - public void UsingPartialFileImplicit() - { - mocks.ReplayAll(); - - factory.RenderView(MakeViewContext("usingpartialimplicit", null)); - - mocks.VerifyAll(); - string content = sb.ToString(); - Assert.That(content.Contains("
  • one
  • ")); - Assert.That(content.Contains("
  • two
  • ")); - } - - [Test] - public void UsingNamespace() - { - mocks.ReplayAll(); - var viewContext = MakeViewContext("usingnamespace", null); - - factory.RenderView(viewContext); - - mocks.VerifyAll(); - string content = sb.ToString(); - Assert.That(content.Contains("

    Foo

    ")); - Assert.That(content.Contains("

    Bar

    ")); - Assert.That(content.Contains("

    Hello

    ")); - } - - [Test] - public void IfElseElements() - { - mocks.ReplayAll(); - var viewContext = MakeViewContext("ifelement", null); - factory.RenderView(viewContext); - mocks.VerifyAll(); - - string content = sb.ToString(); - Assert.That(!content.Contains("argis5

    ")); - Assert.That(!content.Contains("

    argis6

    ")); - Assert.That(content.Contains("

    argisstill5

    ")); - Assert.That(!content.Contains("

    argisnotstill5

    ")); - Assert.That(!content.Contains("

    argisnow6

    ")); - Assert.That(content.Contains("

    argisstillnot6

    ")); - } - - - [Test] - public void IfElseAttributes() - { - mocks.ReplayAll(); - var viewContext = MakeViewContext("ifattribute", null); - factory.RenderView(viewContext); - mocks.VerifyAll(); - - string content = sb.ToString(); - Assert.That(!content.Contains("argis5

    ")); - Assert.That(!content.Contains("

    argis6

    ")); - Assert.That(content.Contains("

    argisstill5

    ")); - Assert.That(!content.Contains("

    argisnotstill5

    ")); - Assert.That(!content.Contains("

    argisnow6

    ")); - Assert.That(content.Contains("

    argisstillnot6

    ")); - } - - [Test] - public void UnlessElements() - { - mocks.ReplayAll(); - var viewContext = MakeViewContext("unlesselement", null); - factory.RenderView(viewContext); - mocks.VerifyAll(); - - string content = sb.ToString(); - Assert.That(!content.Contains("argisnot6

    ")); - Assert.That(!content.Contains("

    argis5

    ")); - } - - [Test] - public void UnlessAttributes() - { - mocks.ReplayAll(); - var viewContext = MakeViewContext("unlessattribute", null); - factory.RenderView(viewContext); - mocks.VerifyAll(); - - string content = sb.ToString(); - Assert.That(!content.Contains("argisnot6

    ")); - Assert.That(!content.Contains("

    argis5

    ")); - } - - [Test] - public void ChainingElseIfElement() - { - mocks.ReplayAll(); - var viewContext = MakeViewContext("elseifelement", null); - factory.RenderView(viewContext); - mocks.VerifyAll(); - string content = sb.ToString(); - Assert.That(content, Contains.InOrder( - "

    Hi Bob!

    ", - "

    Administrator James

    ", - "

    Test user.

    ", - "

    Anonymous user.

    ")); - } - - [Test] - public void ChainingElseIfElement2() - { - mocks.ReplayAll(); - var viewContext = MakeViewContext("elseifelement2", null); - factory.RenderView(viewContext); - mocks.VerifyAll(); - string content = sb.ToString(); - - Assert.That(content, Contains.InOrder( - "

    Hi Bob!

    ", - "

    Administrator James

    ", - "

    Test user.

    ", - "

    Anonymous user.

    ")); - } - [Test] - public void ChainingElseIfAttribute() - { - mocks.ReplayAll(); - var viewContext = MakeViewContext("elseifattribute", null); - factory.RenderView(viewContext); - mocks.VerifyAll(); - string content = sb.ToString(); - Assert.That(content, Contains.InOrder( - "

    Hi Bob!

    ", - "

    Administrator James

    ", - "

    Test user.

    ", - "

    Anonymous user.

    ")); - } - - [Test] - public void EachAttribute() - { - mocks.ReplayAll(); - var viewContext = MakeViewContext("eachattribute", null); - factory.RenderView(viewContext); - mocks.VerifyAll(); - string content = sb.ToString(); - Assert.That(content, Contains.InOrder( - "Bob", - "James", - "SpecialName", - "Anonymous")); - } - - [Test] - public void EachAttributeWhitespace() - { - mocks.ReplayAll(); - var viewContext = MakeViewContext("eachattribute-whitespace", null); - factory.RenderView(viewContext); - mocks.VerifyAll(); - var content = sb.ToString(); - var expected = -@"
      -
    • 1
    • -
    • 2
    • -
    • 3
    • -
    - -
      -
    - -

    - 1,2,3, -

    - -

    -

    - -

    - 1 - 2 - 3 -

    - -

    - ?: -

    - -

    - -

    - abc -

    - -

    -

    - -

    - abc -

    - -

    -

    - -

    -

    abc
    -

    - -

    -

    def
    -

    -"; - - // Ignore differences in line-ending style. - content = content.Replace("\r\n", "\n").Replace("\r", "\n"); - expected = expected.Replace("\r\n", "\n").Replace("\r", "\n"); - - Assert.That(content, Is.EqualTo(expected)); - } - - [Test] - public void MarkupBasedMacros() - { - var data = new StubViewData - { - {"username", "Bob"}, - {"comments", new[] { - new Comment {Text = "Alpha"}, - new Comment {Text = "Beta"}, - new Comment {Text = "Gamma"} - }} - }; - - mocks.ReplayAll(); - var viewContext = MakeViewContext("macros", null, data); - - factory.RenderView(viewContext); - mocks.VerifyAll(); - string content = sb.ToString(); - Assert.That(content, Contains.InOrder( - "

    Bob

    ", "

    Alpha

    ", - "

    Bob

    ", "

    Beta

    ", - "

    Bob

    ", "

    Gamma

    ", - "Rating: 5")); - } - - [Test] - public void TestForEachIndex() - { - mocks.ReplayAll(); - var viewContext = MakeViewContext("foreachindex", null); - factory.RenderView(viewContext); - mocks.VerifyAll(); - - string content = sb.ToString(); - Assert.That(content, Contains.InOrder( - "

    0: Alpha

    ", - "

    1: Beta

    ", - "

    2: Gamma

    ", - "

    3: Delta

    ", - "
  • Alpha
  • ", - "
  • Beta
  • ", - "
  • Gamma
  • ", - "
  • Delta
  • " - )); - } - - [Test] - public void ForEachMoreAutoVariable() - { - mocks.ReplayAll(); - var viewContext = MakeViewContext("foreach-moreautovariables", null); - factory.RenderView(viewContext); - mocks.VerifyAll(); - - string content = sb.ToString().Replace(" ", "").Replace("\t", "").Replace("\r\n", ""); - Assert.That(content, Contains.InOrder( - "one04TrueFalseFalseTrue", - "two14FalseFalseTrueFalse", - "three24FalseFalseFalseTrue", - "four34FalseTrueTrueFalse")); - } - - - [Test] - public void ConditionalTestElement() - { - mocks.ReplayAll(); - var viewContext = MakeViewContext("testelement", null); - factory.RenderView(viewContext); - mocks.VerifyAll(); - - string content = sb.ToString(); - Assert.That(content, Contains.InOrder( - "

    out-1

    ", - "

    out-2

    ", - "

    out-3

    ", - "

    out-4

    ", - "

    out-5

    ", - "

    out-6

    ")); - - Assert.IsFalse(content.Contains("fail")); - - } - - [Test] - public void ConditionalTestElementNested() - { - mocks.ReplayAll(); - var viewContext = MakeViewContext("testelementnested", null); - factory.RenderView(viewContext); - mocks.VerifyAll(); - - string content = sb.ToString().Replace(" ", "").Replace("\r", "").Replace("\n", ""); - Assert.AreEqual("

    a

    b

    c

    d

    e

    f

    ", content); - - } - - [Test] - public void PartialFilesCanHaveSpecialElements() - { - mocks.ReplayAll(); - var viewContext = MakeViewContext("partialspecialelements", null, new StubViewData { { "foo", "alpha" } }); - factory.RenderView(viewContext); - mocks.VerifyAll(); - - string content = sb.ToString(); - Assert.That(content, Contains.InOrder( - "Hi there, alpha.", - "Hi there, alpha.")); - } - - [Test] - public void StatementTerminatingStrings() - { - mocks.ReplayAll(); - var viewContext = MakeViewContext("statement-terminating-strings", null); - factory.RenderView(viewContext); - mocks.VerifyAll(); - - string content = sb.ToString().Replace(" ", "").Replace("\r", "").Replace("\n", ""); - Assert.AreEqual("

    a:1

    b:2

    c:3%>

    d:<%4%>

    e:5%>

    f:<%6%>

    ", content); - - } - - [Test] - public void ExpressionHasVerbatimStrings() - { - mocks.ReplayAll(); - var viewContext = MakeViewContext("expression-has-verbatim-strings", null); - factory.RenderView(viewContext); - mocks.VerifyAll(); - - string content = sb.ToString().Replace(" ", "").Replace("\r", "").Replace("\n", ""); - Assert.AreEqual("

    a\\\"b

    c\\\"}d

    ", content); - } - - [Test] - public void RelativeApplicationPaths() - { - mocks.ReplayAll(); - var viewContext = MakeViewContext("relativeapplicationpaths", null); - factory.RenderView(viewContext); - mocks.VerifyAll(); - - string content = sb.ToString(); - - Assert.That(content, Contains.InOrder( - "", - "", - "

    ")); - } - - [Test] - public void UseAssembly() - { - mocks.ReplayAll(); - var viewContext = MakeViewContext("useassembly", null); - factory.RenderView(viewContext); - mocks.VerifyAll(); - - string content = sb.ToString(); - - Assert.That(content, Contains.InOrder( - "

    SortByCategory

    ")); - } - - [Test] - public void AddViewDataMoreThanOnce() - { - mocks.ReplayAll(); - var viewData = new StubViewData { { "comment", new Comment { Text = "Hello world" } } }; - var viewContext = MakeViewContext("addviewdatamorethanonce", null, viewData); - factory.RenderView(viewContext); - mocks.VerifyAll(); - - string content = sb.ToString(); - - Assert.That(content, Contains.InOrder( - "
    Hello world
    ", - "
    \r\n Again: Hello world\r\n
    ")); - } - - - [Test] - public void AddViewDataDifferentTypes() - { - mocks.ReplayAll(); - var viewData = new StubViewData { { "comment", new Comment { Text = "Hello world" } } }; - var viewContext = MakeViewContext("addviewdatadifferenttypes", null, viewData); - Assert.That(() => factory.RenderView(viewContext), Throws.TypeOf()); - mocks.VerifyAll(); - } - - [Test] - public void RenderPartialWithContainedContent() - { - mocks.ReplayAll(); - var viewContext = MakeViewContext("render-partial-with-contained-content", null); - factory.RenderView(viewContext); - mocks.VerifyAll(); - string content = sb.ToString(); - - Assert.That(content, Contains.InOrder( - "xbox", - "xtop", - "xb1", - "xb2", - "xb3", - "xb4", - "xboxcontent", - "Hello World", - "xbottom", - "xb4", - "xb3", - "xb2", - "xb1")); - } - - [Test] - public void RenderPartialWithSegmentContent() - { - mocks.ReplayAll(); - var viewContext = MakeViewContext("render-partial-with-segment-content", null); - factory.RenderView(viewContext); - mocks.VerifyAll(); - string content = sb.ToString(); - - Assert.That(content, Contains.InOrder( - "xbox", - "xtop", - "xb1", - "xb2", - "xb3", - "xb4", - "xboxcontent", - "title=\"My Tooltip\"", - "

    This is a test

    ", - "Hello World", - "xbottom", - "xb4", - "xb3", - "xb2", - "xb1")); - } - - [Test] - public void RenderPartialWithSectionAsHtml5ContentByDefault() - { - mocks.ReplayAll(); - var viewContext = MakeViewContext("render-partial-section-or-ignore", null); - factory.RenderView(viewContext); - mocks.VerifyAll(); - string content = sb.ToString(); - - Assert.That(content, Contains.InOrder( - "xbox", - "xtop", - "xb1", - "xb2", - "xb3", - "xb4", - "xboxcontent", - "
    ", - "

    This is a test

    ", - "
    ", - "
    ", - "My Tooltip", - "
    ", - "

    Hello World

    ", - "xbottom", - "xb4", - "xb3", - "xb2", - "xb1")); - } - - [Test] - public void RenderPartialWithSectionAsSegmentContentFromSettings() - { - settings.SetParseSectionTagAsSegment(true); - - mocks.ReplayAll(); - var viewContext = MakeViewContext("render-partial-section-or-ignore", null); - factory.RenderView(viewContext); - mocks.VerifyAll(); - string content = sb.ToString(); - - Assert.That(content, Contains.InOrder( - "xbox", - "xtop", - "xb1", - "xb2", - "xb3", - "xb4", - "xboxcontent", - "title=\"My Tooltip\"", - "

    This is a test

    ", - "Hello World", - "xbottom", - "xb4", - "xb3", - "xb2", - "xb1")); - } - - [Test] - public void RenderlPartialWithDotInName() - { - mocks.ReplayAll(); - var viewContext = MakeViewContext("render-dotted-partial", null); - factory.RenderView(viewContext); - mocks.VerifyAll(); - string content = sb.ToString(); - - Assert.That(content, Contains.InOrder( - "

    ", - "this.is.some.text:", - "test456", - "

    " - )); - - Assert.IsFalse(content.Contains("beforedataafter

    ")); - } - - [Test] - public void ConstAndReadonlyGlobals() - { - mocks.ReplayAll(); - var viewContext = MakeViewContext("const-and-readonly-globals", null); - factory.RenderView(viewContext); - mocks.VerifyAll(); - string content = sb.ToString().Replace("\r", "").Replace("\n", "").Replace("\t", "").Replace(" ", ""); - - Assert.AreEqual("
    1. 3
    2. 4
    3. 5
    4. 6
    5. 7
    ", content); - } - - [Test] - public void PrefixContentNotation() - { - mocks.ReplayAll(); - var viewContext = MakeViewContext("prefix-content-notation", null); - factory.RenderView(viewContext); - mocks.VerifyAll(); - string content = sb.ToString().Replace("\r", "").Replace("\n", "").Replace("\t", "").Replace(" ", ""); - - Assert.That(content.Contains("onetwothree")); - } - - [Test] - public void DynamicAttributes() - { - mocks.ReplayAll(); - var viewContext = MakeViewContext("dynamic-attributes", null); - factory.RenderView(viewContext); - mocks.VerifyAll(); - string content = sb.ToString(); - - Assert.That(content, Contains.InOrder( - "
    ", - @"", - @"", - @"", - @"", - - @"", - @"", - @"", - @"", - - @"", - @"", - - @"", - @"", - "
    " - )); - } - - [Test] - public void XMLDeclAndProcessingInstruction() - { - mocks.ReplayAll(); - var viewContext = MakeViewContext("xmldecl-and-processing-instruction", null); - factory.RenderView(viewContext); - mocks.VerifyAll(); - string content = sb.ToString(); - - Assert.That(content, Contains.InOrder( - "", - "" - )); - } - - - [Test] - public void ForEachAutovariablesUsedInline() - { - mocks.ReplayAll(); - var viewContext = MakeViewContext("foreach-autovariables-used-inline", null); - factory.RenderView(viewContext); - mocks.VerifyAll(); - string content = sb.ToString(); - - Assert.That(content, Contains.InOrder( - "", - "blah", "blah")); - - } - - [Test] - public void AlternateViewdataSyntax() - { - mocks.ReplayAll(); - var viewData = new StubViewData> { { "my-data", "alpha" } }; - viewData.Model = new[] { "beta", "gamma", "delta" }; - - var viewContext = MakeViewContext("alternate-viewdata-syntax", null, viewData); - factory.RenderView(viewContext); - mocks.VerifyAll(); - string content = sb.ToString(); - - Assert.That(content, Contains.InOrder( - "

    ", "alpha", "

    ", - "

    ", "beta", "

    ", - "

    ", "gamma", "

    ", - "

    ", "delta", "

    " - )); - } - - [Test] - public void DefaultValuesDontCollideWithExistingLocals() - { - mocks.ReplayAll(); - - var viewContext = MakeViewContext("DefaultValuesDontCollideWithExistingLocals", null); - factory.RenderView(viewContext); - mocks.VerifyAll(); - string content = sb.ToString(); - - Assert.IsFalse(content.Contains("default")); - - Assert.That(content, Contains.InOrder("ok1", "ok2")); - Assert.IsFalse(content.Contains("fail")); - } - - [Test] - public void DefaultValuesDontReplaceGlobals() - { - mocks.ReplayAll(); - - var viewContext = MakeViewContext("DefaultValuesDontReplaceGlobals", null); - factory.RenderView(viewContext); - mocks.VerifyAll(); - string content = sb.ToString(); - - Assert.IsFalse(content.Contains("default")); - - Assert.That(content, Contains.InOrder("ok1", "ok2")); - Assert.IsFalse(content.Contains("fail")); - } - - [Test] - public void DefaultValuesDontReplaceViewData() - { - mocks.ReplayAll(); - var viewData = new StubViewData { { "x1", 5 }, { "x2", 5 } }; - var viewContext = MakeViewContext("DefaultValuesDontReplaceViewData", null, viewData); - factory.RenderView(viewContext); - mocks.VerifyAll(); - string content = sb.ToString(); - - Assert.IsFalse(content.Contains("default")); - - Assert.That(content, Contains.InOrder("ok1", "ok2")); - Assert.IsFalse(content.Contains("fail")); - } - - - [Test] - public void DefaultValuesActAsLocal() - { - mocks.ReplayAll(); - var viewContext = MakeViewContext("DefaultValuesActAsLocal", null); - factory.RenderView(viewContext); - mocks.VerifyAll(); - string content = sb.ToString(); - - Assert.IsFalse(content.Contains("default")); - - Assert.That(content, Contains.InOrder("ok1", "ok2")); - Assert.IsFalse(content.Contains("fail")); - } - - [Test] - public void DefaultValuesStandInForNullViewData() - { - mocks.ReplayAll(); - var viewData = new StubViewData(); - var viewContext = MakeViewContext("DefaultValuesStandInForNullViewData", null, viewData); - factory.RenderView(viewContext); - mocks.VerifyAll(); - string content = sb.ToString(); - - Assert.IsFalse(content.Contains("default")); - - Assert.That(content, Contains.InOrder("ok1", "ok2")); - Assert.IsFalse(content.Contains("fail")); - } - - [Test] - public void NullExceptionHandledAutomatically() - { - mocks.ReplayAll(); - var viewData = new StubViewData(); - var viewContext = MakeViewContext("NullExceptionHandledAutomatically", null, viewData); - factory.RenderView(viewContext); - mocks.VerifyAll(); - string content = sb.ToString(); - - Assert.IsFalse(content.Contains("default")); - - Assert.That(content, Contains.InOrder( - "

    name kaboom *${user.Name}*

    ", - "

    name silently **

    ", - "

    name fixed *fred*

    ")); - } - - [Test] - public void CodeCommentsCanHaveQuotes() - { - mocks.ReplayAll(); - var viewContext = MakeViewContext("CodeCommentsCanHaveQuotes", null); - factory.RenderView(viewContext); - mocks.VerifyAll(); - string content = sb.ToString(); - - Assert.IsFalse(content.Contains("broken")); - Assert.That(content, Contains.InOrder("one", "two", "three", "four", "five")); - } - - [Test] - public void ConditionalAttributeDelimitedBySpaces() - { - mocks.ReplayAll(); - var viewContext = MakeViewContext("ConditionalAttributeDelimitedBySpaces", null); - factory.RenderView(viewContext); - mocks.VerifyAll(); - string content = sb.ToString(); - - Assert.IsFalse(content.Contains("broken")); - Assert.That(content, Contains.InOrder( - "

    ", - "

    ", - "

    ", - "

    ", - "
    ", - "
    ", - "")); - } - - - [Test] - public void OnceAttribute() - { - mocks.ReplayAll(); - var viewContext = MakeViewContext("OnceAttribute", null); - factory.RenderView(viewContext); - mocks.VerifyAll(); - string content = sb.ToString(); - - Assert.That(content, Contains.InOrder( - "foo1", - "bar0", - "quux2", - "a1")); - - Assert.IsFalse(content.Contains("foo2")); - Assert.IsFalse(content.Contains("foo3")); - Assert.IsFalse(content.Contains("bar1")); - Assert.IsFalse(content.Contains("bar3")); - Assert.IsFalse(content.Contains("a2")); - } - - - [Test] - public void EachAttributeWorksOnSpecialNodes() - { - mocks.ReplayAll(); - var viewContext = MakeViewContext("EachAttributeWorksOnSpecialNodes", null); - factory.RenderView(viewContext); - mocks.VerifyAll(); - string content = sb.ToString(); - - Assert.That(content, Contains.InOrder( - "

    name-0-alpha

    ", - "

    name-1-beta

    ", - "

    name-2-gamma

    ", - "one", - "two", - "three")); - } - - [Test] - public void IfAttributeWorksOnSpecialNodes() - { - mocks.ReplayAll(); - var viewContext = MakeViewContext("IfAttributeWorksOnSpecialNodes", null); - factory.RenderView(viewContext); - mocks.VerifyAll(); - string content = sb.ToString(); - - Assert.That(content, Contains.InOrder( - "

    name-0-alpha

    ", - "

    name-2-gamma

    ", - "one", - "three")); - - Assert.IsFalse(content.Contains("beta")); - Assert.IsFalse(content.Contains("two")); - } - - [Test] - public void UnlessAttributeWorksOnSpecialNodes() - { - mocks.ReplayAll(); - var viewContext = MakeViewContext("UnlessAttributeWorksOnSpecialNodes", null); - factory.RenderView(viewContext); - mocks.VerifyAll(); - string content = sb.ToString(); - - Assert.That(content, Contains.InOrder( - "

    name-0-alpha

    ", - "

    name-2-gamma

    ", - "one", - "three")); - - Assert.IsFalse(content.Contains("beta")); - Assert.IsFalse(content.Contains("two")); - } - - [Test] - public void OnceAttributeWorksOnSpecialNodes() - { - mocks.ReplayAll(); - var viewContext = MakeViewContext("OnceAttributeWorksOnSpecialNodes", null); - factory.RenderView(viewContext); - mocks.VerifyAll(); - string content = sb.ToString(); - - Assert.That(content, Contains.InOrder( - "

    name-0-alpha

    ", - "foo1", - "bar0", - "quux2")); - - Assert.IsFalse(content.Contains("name-1")); - Assert.IsFalse(content.Contains("name-2")); - Assert.IsFalse(content.Contains("foo2")); - Assert.IsFalse(content.Contains("foo3")); - Assert.IsFalse(content.Contains("bar1")); - Assert.IsFalse(content.Contains("bar3")); - } - - [Test] - public void LateBoundEvalResolvesViewData() - { - mocks.ReplayAll(); - var viewData = new StubViewData() - { - {"alpha", "hi"}, - {"beta", "yadda"} - }; - var viewContext = MakeViewContext("LateBoundEvalResolvesViewData", null, viewData); - factory.RenderView(viewContext); - mocks.VerifyAll(); - string content = sb.ToString(); - - Assert.That(content, Contains.InOrder( - "

    hi

    ", - "

    <strong>hi</strong>

    ", - "yadda", - "

    42

    ")); - - } - - [Test] - public void PartialInMacroMayUseDefaultElement() - { - mocks.ReplayAll(); - var viewContext = MakeViewContext("PartialInMacroMayUseDefaultElement", null); - factory.RenderView(viewContext); - mocks.VerifyAll(); - string content = sb.ToString(); - - Assert.That(content, Contains.InOrder( - "

    3hello

    ", - "

    2hello.

    ", - "

    1hello..

    ", - "

    0hello...

    ")); - - } - - [Test] - public void RecursivePartialsThrowCompilerException() - { - mocks.ReplayAll(); - var viewContext = MakeViewContext("RecursivePartialsThrowCompilerException", null); - Assert.That(() => - factory.RenderView(viewContext), - Throws.TypeOf()); - } - - [Test] - public void NestedPartialsCanBackRenderUpAndReRenderDown() - { - mocks.ReplayAll(); - var viewContext = MakeViewContext("NestedPartialsCanBackRenderUpAndReRenderDown", null); - factory.RenderView(viewContext); - mocks.VerifyAll(); - string content = sb.ToString(); - - var stripped = content.Replace(" ", "").Replace("\t", "").Replace("\r\n", ""); - Assert.That(stripped, Is.EqualTo( - "[001][101]" + - "[201][102]" + - "[201][104][202]" + - "[106][002][107]" + - "[201][109][202]" + - "[111][202]" + - "[112][003]")); - } - - [Test] - public void SegmentRenderingFallbackMayRenderSegment() - { - mocks.ReplayAll(); - var viewContext = MakeViewContext("SegmentRenderingFallbackMayRenderSegment", null); - factory.RenderView(viewContext); - mocks.VerifyAll(); - string content = sb.ToString(); - var stripped = content.Replace(" ", "").Replace("\t", "").Replace("\r\n", ""); - Assert.That(stripped, Is.EqualTo( - "[001]" + - "[101][102]" + - "[002][004]" + - "[103][104]" + - "[005]")); - } - - [Test] - public void Markdown() - { - mocks.ReplayAll(); - var viewContext = MakeViewContext("markdown", null); - factory.RenderView(viewContext); - mocks.VerifyAll(); - - string content = sb.ToString(); - - Assert.That(content, Contains.InOrder( - "
    ", "code block on the first line", "
    ", - "

    ", "Regular text.", "

    ", - "
    ", "code block indented by spaces", "
    ", - "

    ", "Regular text.", "

    ", - "
    ", "the lines in this block",
    -                "all contain trailing spaces", "
    ", - "

    ", "Regular Text.", "

    ", - "
    ", "code block on the last line", "
    ")); - } - - [Test] - public void Ignore() - { - mocks.ReplayAll(); - var viewContext = MakeViewContext("ignore", null); - factory.RenderView(viewContext); - mocks.VerifyAll(); - - string content = sb.ToString(); - - Assert.That(content, Contains.InOrder( - "
    ", - "Regular text ${This.isnt.code < 0}", - "", - "
    ")); - Assert.IsFalse(content.Contains("")); - Assert.IsFalse(content.Contains("")); - } - - [Test] - public void Escape() - { - mocks.ReplayAll(); - var viewContext = MakeViewContext("escape", null); - factory.RenderView(viewContext); - mocks.VerifyAll(); - - string content = sb.ToString(); - - Assert.That(content, Contains.InOrder( - "
    ", - "${Encoded.Escaped.with.a.dollar < 0}", - "${Encoded.Escaped.with.a.backslash < 0}", - "${Encoded.Escaped.with.a.backtick < 0}", - "
    ")); - - Assert.That(content, Contains.InOrder( - "
    ", - "!{Unencoded.Escaped.with.a.dollar < 0}", - "!{Unencoded.Escaped.with.a.backslash < 0}", - "!{Unencoded.Escaped.with.a.backtick < 0}", - "
    ")); - - Assert.That(content, Contains.InOrder( - "
    ", - "$!{Encoded.Silent.Nulls.Escaped.with.a.dollar < 0}", - "$!{Encoded.Silent.Nulls.Escaped.with.a.backslash < 0}", - "$!{Encoded.Silent.Nulls.Escaped.with.a.backtick < 0}", - "
    ")); - } - - [Test] - public void PreserveSingleQuotes() - { - mocks.ReplayAll(); - var viewContext = MakeViewContext("preserveSingleQuotes", null); - factory.RenderView(viewContext); - mocks.VerifyAll(); - - string content = sb.ToString(); - - Assert.That(content, Is.EqualTo(@"")); - } - - [Test] - public void PreserveDoubleQuotes() - { - mocks.ReplayAll(); - var viewContext = MakeViewContext("preserveDoubleQuotes", null); - factory.RenderView(viewContext); - mocks.VerifyAll(); - - string content = sb.ToString(); - - Assert.That(content, Is.EqualTo(@"")); - } - - - [Test] - public void ShadeFileRenders() - { - mocks.ReplayAll(); - var viewContext = MakeViewContext("ShadeFileRenders", null); - factory.RenderView(viewContext, Constants.DotShade); - mocks.VerifyAll(); - - var content = sb.ToString(); - - Assert.That(content, Contains.InOrder( - "", - "", - "", - "offset test", - "", - "", - "
    ", - "

    ", - "offset test", - "

    ", - "
    ", - "", - "")); - } - - [Test] - public void ShadeEvaluatesExpressions() - { - mocks.ReplayAll(); - var viewContext = MakeViewContext("ShadeEvaluatesExpressions", null); - factory.RenderView(viewContext, Constants.DotShade); - mocks.VerifyAll(); - - var content = sb.ToString(); - - Assert.That(content, Contains.InOrder( - "

    ", - "", - "8", - "", - "", - "2", " and ", "7", - "", - "

    ")); - } - - [Test] - public void ShadeSupportsAttributesAndMayTreatSomeElementsAsSpecialNodes() - { - mocks.ReplayAll(); - var viewContext = MakeViewContext("ShadeSupportsAttributesAndMayTreatSomeElementsAsSpecialNodes", null); - factory.RenderView(viewContext, Constants.DotShade); - mocks.VerifyAll(); - - var content = sb.ToString(); - - Assert.That(content, Contains.InOrder( - "
      ", - "
    • Welcome
    • ", - "
    • to
    • ", - "
    • the
    • ", - "
    • Machine
    • ", - "
    ", - "

    ", - "4", - "

    ")); - } - - [Test] - public void ShadeCodeMayBeDashOrAtBraced() - { - mocks.ReplayAll(); - var viewContext = MakeViewContext("ShadeCodeMayBeDashOrAtBraced", null); - factory.RenderView(viewContext, Constants.DotShade); - mocks.VerifyAll(); - - var content = sb.ToString(); - - Assert.That(content, Contains.InOrder( - "
      ", - "
    • emocleW
    • ", - "
    • ot
    • ", - "
    • eht
    • ", - "
    • enihcaM
    • ", - "
    ")); - } - - - [Test] - public void ShadeTextMayContainExpressions() - { - mocks.ReplayAll(); - var viewContext = MakeViewContext("ShadeTextMayContainExpressions", null); - factory.RenderView(viewContext, Constants.DotShade); - mocks.VerifyAll(); - - var content = sb.ToString(); - - Assert.That(content, Contains.InOrder( - "

    ", - "8", - "2 and 7", - "

    ")); - } - - [Test] - public void TextOrientedAttributesApplyToVarAndSet() - { - mocks.ReplayAll(); - ((SparkSettings)engine.Settings).AttributeBehaviour = AttributeBehaviour.TextOriented; - var viewContext = MakeViewContext("TextOrientedAttributesApplyToVarAndSet", null); - factory.RenderView(viewContext, Constants.DotSpark); - mocks.VerifyAll(); - - var content = sb.ToString(); - - Assert.That(content, Contains.InOrder( - "

    String:HelloWorld

    ", - "

    Int32:42

    ")); - } - - [Test] - public void TextOrientedAttributesApplyToUseFile() - { - mocks.ReplayAll(); - ((SparkSettings)engine.Settings).AttributeBehaviour = AttributeBehaviour.TextOriented; - var viewContext = MakeViewContext("TextOrientedAttributesApplyToUseFile", null); - factory.RenderView(viewContext, Constants.DotSpark); - mocks.VerifyAll(); - - var content = sb.ToString(); - - Assert.That(content, Contains.InOrder( - "Hello", - "Hello World!", - "42")); - } - - [Test] - public void TextOrientedAttributesApplyToDefault() - { - mocks.ReplayAll(); - ((SparkSettings)engine.Settings).AttributeBehaviour = AttributeBehaviour.TextOriented; - var viewContext = MakeViewContext("TextOrientedAttributesApplyToDefault", null); - factory.RenderView(viewContext, Constants.DotSpark); - mocks.VerifyAll(); - - var content = sb.ToString(); - - Assert.That(content, Contains.InOrder( - "

    String:World

    ", - "

    String:Hello World!

    ", - "

    Int32:42

    ")); - } - - - [Test] - public void TextOrientedAttributesApplyToGlobal() - { - mocks.ReplayAll(); - ((SparkSettings)engine.Settings).AttributeBehaviour = AttributeBehaviour.TextOriented; - var viewContext = MakeViewContext("TextOrientedAttributesApplyToGlobal", null); - factory.RenderView(viewContext, Constants.DotSpark); - mocks.VerifyAll(); - - var content = sb.ToString(); - - Assert.That(content, Contains.InOrder( - "

    String:World

    ", - "

    String:Hello World!

    ", - "

    Int32:42

    ")); - } - - - [Test] - public void ShadeElementsMayStackOnOneLine() - { - mocks.ReplayAll(); - var viewContext = MakeViewContext("ShadeElementsMayStackOnOneLine", null); - factory.RenderView(viewContext, Constants.DotShade); - mocks.VerifyAll(); - - var content = sb.ToString(); - - Assert.That(content, Contains.InOrder( - "", - "", - "", - "offset test", - "", - "", - "
    ", - "

    ", - "offset test", - "

    ", - "
    ", - "", - "")); - } - } -} +//------------------------------------------------------------------------- +// +// Copyright 2008-2010 Louis DeJardin - http://whereslou.com +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +// Louis DeJardin +// Gauthier Segay +// Jacob Proffitt +// John Gietzen +//------------------------------------------------------------------------- + +namespace Spark.Tests +{ + using System.Collections.Generic; + using System.Text; + using NUnit.Framework; + + using Rhino.Mocks; + using Spark.Compiler; + using Spark.FileSystem; + using Spark.Tests.Models; + using Spark.Tests.Stubs; + + [TestFixture, Category("SparkViewEngine")] + public class SparkViewFactoryTester + { + private MockRepository mocks; + + private StubViewFactory factory; + private SparkViewEngine engine; + private StringBuilder sb; + private SparkSettings settings; + + [SetUp] + public void Init() + { + settings = new SparkSettings().SetPageBaseType("Spark.Tests.Stubs.StubSparkView"); + engine = new SparkViewEngine(settings) { ViewFolder = new FileSystemViewFolder("Spark.Tests.Views") }; + factory = new StubViewFactory { Engine = engine }; + + sb = new StringBuilder(); + + mocks = new MockRepository(); + + } + + StubViewContext MakeViewContext(string viewName, string masterName) + { + return new StubViewContext { ControllerName = "Home", ViewName = viewName, MasterName = masterName, Output = sb }; + } + + StubViewContext MakeViewContext(string viewName, string masterName, StubViewData data) + { + return new StubViewContext { ControllerName = "Home", ViewName = viewName, MasterName = masterName, Output = sb, Data = data }; + } + + + + [Test] + public void RenderPlainView() + { + mocks.ReplayAll(); + + factory.RenderView(MakeViewContext("Index", null)); + + mocks.VerifyAll(); + } + + + [Test] + public void ForEachTest() + { + mocks.ReplayAll(); + + factory.RenderView(MakeViewContext("foreach", null)); + + mocks.VerifyAll(); + + string content = sb.ToString(); + Assert.That(content.Contains(@"
  • 1: foo
  • ")); + Assert.That(content.Contains(@"
  • 2: bar
  • ")); + Assert.That(content.Contains(@"
  • 3: baaz
  • ")); + } + + + [Test] + public void GlobalSetTest() + { + + mocks.ReplayAll(); + + factory.RenderView(MakeViewContext("globalset", null)); + + mocks.VerifyAll(); + + string content = sb.ToString(); + Assert.That(content.Contains("

    default: Global set test

    ")); + Assert.That(content.Contains("

    7==7

    ")); + } + + [Test] + public void MasterTest() + { + mocks.ReplayAll(); + + factory.RenderView(MakeViewContext("childview", "layout")); + + mocks.VerifyAll(); + string content = sb.ToString(); + Assert.That(content.Contains("Standalone Index View")); + Assert.That(content.Contains("

    Standalone Index View

    ")); + Assert.That(content.Contains("

    no header by default

    ")); + Assert.That(content.Contains("

    no footer by default

    ")); + } + + [Test] + public void CaptureNamedContent() + { + + mocks.ReplayAll(); + + factory.RenderView(MakeViewContext("namedcontent", "layout")); + + mocks.VerifyAll(); + string content = sb.ToString(); + Assert.That(content.Contains("

    main content

    ")); + Assert.That(content.Contains("

    this is the header

    ")); + Assert.That(content.Contains("

    footer part one

    ")); + Assert.That(content.Contains("

    footer part two

    ")); + } + + [Test] + public void UsingPartialFile() + { + mocks.ReplayAll(); + + factory.RenderView(MakeViewContext("usingpartial", null)); + + mocks.VerifyAll(); + string content = sb.ToString(); + Assert.That(content.Contains("
  • Partial where x=\"zero\"
  • ")); + Assert.That(content.Contains("
  • Partial where x=\"one\"
  • ")); + Assert.That(content.Contains("
  • Partial where x=\"two\"
  • ")); + Assert.That(content.Contains("
  • Partial where x=\"three\"
  • ")); + Assert.That(content.Contains("
  • Partial where x=\"four\"
  • ")); + } + + [Test] + public void UsingPartialWithRenderElement() + { + mocks.ReplayAll(); + + factory.RenderView(MakeViewContext("usingpartial-render-element", null)); + + mocks.VerifyAll(); + string content = sb.ToString(); + Assert.That(content.Contains("
  • Partial where x=\"zero\"
  • ")); + Assert.That(content.Contains("
  • Partial where x=\"one\"
  • ")); + Assert.That(content.Contains("
  • Partial where x=\"two\"
  • ")); + Assert.That(content.Contains("
  • Partial where x=\"three\"
  • ")); + Assert.That(content.Contains("
  • Partial where x=\"four\"
  • ")); + } + + [Test] + public void UsingPartialFileImplicit() + { + mocks.ReplayAll(); + + factory.RenderView(MakeViewContext("usingpartialimplicit", null)); + + mocks.VerifyAll(); + string content = sb.ToString(); + Assert.That(content.Contains("
  • one
  • ")); + Assert.That(content.Contains("
  • two
  • ")); + } + + [Test] + public void UsingNamespace() + { + mocks.ReplayAll(); + var viewContext = MakeViewContext("usingnamespace", null); + + factory.RenderView(viewContext); + + mocks.VerifyAll(); + string content = sb.ToString(); + Assert.That(content.Contains("

    Foo

    ")); + Assert.That(content.Contains("

    Bar

    ")); + Assert.That(content.Contains("

    Hello

    ")); + } + + [Test] + public void IfElseElements() + { + mocks.ReplayAll(); + var viewContext = MakeViewContext("ifelement", null); + factory.RenderView(viewContext); + mocks.VerifyAll(); + + string content = sb.ToString(); + Assert.That(!content.Contains("argis5

    ")); + Assert.That(!content.Contains("

    argis6

    ")); + Assert.That(content.Contains("

    argisstill5

    ")); + Assert.That(!content.Contains("

    argisnotstill5

    ")); + Assert.That(!content.Contains("

    argisnow6

    ")); + Assert.That(content.Contains("

    argisstillnot6

    ")); + } + + + [Test] + public void IfElseAttributes() + { + mocks.ReplayAll(); + var viewContext = MakeViewContext("ifattribute", null); + factory.RenderView(viewContext); + mocks.VerifyAll(); + + string content = sb.ToString(); + Assert.That(!content.Contains("argis5

    ")); + Assert.That(!content.Contains("

    argis6

    ")); + Assert.That(content.Contains("

    argisstill5

    ")); + Assert.That(!content.Contains("

    argisnotstill5

    ")); + Assert.That(!content.Contains("

    argisnow6

    ")); + Assert.That(content.Contains("

    argisstillnot6

    ")); + } + + [Test] + public void UnlessElements() + { + mocks.ReplayAll(); + var viewContext = MakeViewContext("unlesselement", null); + factory.RenderView(viewContext); + mocks.VerifyAll(); + + string content = sb.ToString(); + Assert.That(!content.Contains("argisnot6

    ")); + Assert.That(!content.Contains("

    argis5

    ")); + } + + [Test] + public void UnlessAttributes() + { + mocks.ReplayAll(); + var viewContext = MakeViewContext("unlessattribute", null); + factory.RenderView(viewContext); + mocks.VerifyAll(); + + string content = sb.ToString(); + Assert.That(!content.Contains("argisnot6

    ")); + Assert.That(!content.Contains("

    argis5

    ")); + } + + [Test] + public void ChainingElseIfElement() + { + mocks.ReplayAll(); + var viewContext = MakeViewContext("elseifelement", null); + factory.RenderView(viewContext); + mocks.VerifyAll(); + string content = sb.ToString(); + Assert.That(content, Contains.InOrder( + "

    Hi Bob!

    ", + "

    Administrator James

    ", + "

    Test user.

    ", + "

    Anonymous user.

    ")); + } + + [Test] + public void ChainingElseIfElement2() + { + mocks.ReplayAll(); + var viewContext = MakeViewContext("elseifelement2", null); + factory.RenderView(viewContext); + mocks.VerifyAll(); + string content = sb.ToString(); + + Assert.That(content, Contains.InOrder( + "

    Hi Bob!

    ", + "

    Administrator James

    ", + "

    Test user.

    ", + "

    Anonymous user.

    ")); + } + [Test] + public void ChainingElseIfAttribute() + { + mocks.ReplayAll(); + var viewContext = MakeViewContext("elseifattribute", null); + factory.RenderView(viewContext); + mocks.VerifyAll(); + string content = sb.ToString(); + Assert.That(content, Contains.InOrder( + "

    Hi Bob!

    ", + "

    Administrator James

    ", + "

    Test user.

    ", + "

    Anonymous user.

    ")); + } + + [Test] + public void EachAttribute() + { + mocks.ReplayAll(); + var viewContext = MakeViewContext("eachattribute", null); + factory.RenderView(viewContext); + mocks.VerifyAll(); + string content = sb.ToString(); + Assert.That(content, Contains.InOrder( + "Bob", + "James", + "SpecialName", + "Anonymous")); + } + + [Test] + public void EachAttributeWhitespace() + { + mocks.ReplayAll(); + var viewContext = MakeViewContext("eachattribute-whitespace", null); + factory.RenderView(viewContext); + mocks.VerifyAll(); + var content = sb.ToString(); + var expected = +@"
      +
    • 1
    • +
    • 2
    • +
    • 3
    • +
    + +
      +
    + +

    + 1,2,3, +

    + +

    +

    + +

    + 1 + 2 + 3 +

    + +

    + ?: +

    + +

    + +

    + abc +

    + +

    +

    + +

    + abc +

    + +

    +

    + +

    +

    abc
    +

    + +

    +

    def
    +

    +"; + + // Ignore differences in line-ending style. + content = content.Replace("\r\n", "\n").Replace("\r", "\n"); + expected = expected.Replace("\r\n", "\n").Replace("\r", "\n"); + + Assert.That(content, Is.EqualTo(expected)); + } + + [Test] + public void MarkupBasedMacros() + { + var data = new StubViewData + { + {"username", "Bob"}, + {"comments", new[] { + new Comment {Text = "Alpha"}, + new Comment {Text = "Beta"}, + new Comment {Text = "Gamma"} + }} + }; + + mocks.ReplayAll(); + var viewContext = MakeViewContext("macros", null, data); + + factory.RenderView(viewContext); + mocks.VerifyAll(); + string content = sb.ToString(); + Assert.That(content, Contains.InOrder( + "

    Bob

    ", "

    Alpha

    ", + "

    Bob

    ", "

    Beta

    ", + "

    Bob

    ", "

    Gamma

    ", + "Rating: 5")); + } + + [Test] + public void TestForEachIndex() + { + mocks.ReplayAll(); + var viewContext = MakeViewContext("foreachindex", null); + factory.RenderView(viewContext); + mocks.VerifyAll(); + + string content = sb.ToString(); + Assert.That(content, Contains.InOrder( + "

    0: Alpha

    ", + "

    1: Beta

    ", + "

    2: Gamma

    ", + "

    3: Delta

    ", + "
  • Alpha
  • ", + "
  • Beta
  • ", + "
  • Gamma
  • ", + "
  • Delta
  • " + )); + } + + [Test] + public void ForEachMoreAutoVariable() + { + mocks.ReplayAll(); + var viewContext = MakeViewContext("foreach-moreautovariables", null); + factory.RenderView(viewContext); + mocks.VerifyAll(); + + string content = sb.ToString().Replace(" ", "").Replace("\t", "").Replace("\r\n", ""); + Assert.That(content, Contains.InOrder( + "one04TrueFalseFalseTrue", + "two14FalseFalseTrueFalse", + "three24FalseFalseFalseTrue", + "four34FalseTrueTrueFalse")); + } + + + [Test] + public void ConditionalTestElement() + { + mocks.ReplayAll(); + var viewContext = MakeViewContext("testelement", null); + factory.RenderView(viewContext); + mocks.VerifyAll(); + + string content = sb.ToString(); + Assert.That(content, Contains.InOrder( + "

    out-1

    ", + "

    out-2

    ", + "

    out-3

    ", + "

    out-4

    ", + "

    out-5

    ", + "

    out-6

    ")); + + Assert.IsFalse(content.Contains("fail")); + + } + + [Test] + public void ConditionalTestElementNested() + { + mocks.ReplayAll(); + var viewContext = MakeViewContext("testelementnested", null); + factory.RenderView(viewContext); + mocks.VerifyAll(); + + string content = sb.ToString().Replace(" ", "").Replace("\r", "").Replace("\n", ""); + Assert.AreEqual("

    a

    b

    c

    d

    e

    f

    ", content); + + } + + [Test] + public void PartialFilesCanHaveSpecialElements() + { + mocks.ReplayAll(); + var viewContext = MakeViewContext("partialspecialelements", null, new StubViewData { { "foo", "alpha" } }); + factory.RenderView(viewContext); + mocks.VerifyAll(); + + string content = sb.ToString(); + Assert.That(content, Contains.InOrder( + "Hi there, alpha.", + "Hi there, alpha.")); + } + + [Test] + public void StatementTerminatingStrings() + { + mocks.ReplayAll(); + var viewContext = MakeViewContext("statement-terminating-strings", null); + factory.RenderView(viewContext); + mocks.VerifyAll(); + + string content = sb.ToString().Replace(" ", "").Replace("\r", "").Replace("\n", ""); + Assert.AreEqual("

    a:1

    b:2

    c:3%>

    d:<%4%>

    e:5%>

    f:<%6%>

    ", content); + + } + + [Test] + public void ExpressionHasVerbatimStrings() + { + mocks.ReplayAll(); + var viewContext = MakeViewContext("expression-has-verbatim-strings", null); + factory.RenderView(viewContext); + mocks.VerifyAll(); + + string content = sb.ToString().Replace(" ", "").Replace("\r", "").Replace("\n", ""); + Assert.AreEqual("

    a\\\"b

    c\\\"}d

    ", content); + } + + [Test] + public void RelativeApplicationPaths() + { + mocks.ReplayAll(); + var viewContext = MakeViewContext("relativeapplicationpaths", null); + factory.RenderView(viewContext); + mocks.VerifyAll(); + + string content = sb.ToString(); + + Assert.That(content, Contains.InOrder( + "", + "", + "

    ")); + } + + [Test] + public void UseAssembly() + { + mocks.ReplayAll(); + var viewContext = MakeViewContext("useassembly", null); + factory.RenderView(viewContext); + mocks.VerifyAll(); + + string content = sb.ToString(); + + Assert.That(content, Contains.InOrder( + "

    SortByCategory

    ")); + } + + [Test] + public void AddViewDataMoreThanOnce() + { + mocks.ReplayAll(); + var viewData = new StubViewData { { "comment", new Comment { Text = "Hello world" } } }; + var viewContext = MakeViewContext("addviewdatamorethanonce", null, viewData); + factory.RenderView(viewContext); + mocks.VerifyAll(); + + string content = sb.ToString(); + + Assert.That(content, Contains.InOrder( + "
    Hello world
    ", + "
    \r\n Again: Hello world\r\n
    ")); + } + + + [Test] + public void AddViewDataDifferentTypes() + { + mocks.ReplayAll(); + var viewData = new StubViewData { { "comment", new Comment { Text = "Hello world" } } }; + var viewContext = MakeViewContext("addviewdatadifferenttypes", null, viewData); + Assert.That(() => factory.RenderView(viewContext), Throws.TypeOf()); + mocks.VerifyAll(); + } + + [Test] + public void RenderPartialWithContainedContent() + { + mocks.ReplayAll(); + var viewContext = MakeViewContext("render-partial-with-contained-content", null); + factory.RenderView(viewContext); + mocks.VerifyAll(); + string content = sb.ToString(); + + Assert.That(content, Contains.InOrder( + "xbox", + "xtop", + "xb1", + "xb2", + "xb3", + "xb4", + "xboxcontent", + "Hello World", + "xbottom", + "xb4", + "xb3", + "xb2", + "xb1")); + } + + [Test] + public void RenderPartialWithSegmentContent() + { + mocks.ReplayAll(); + var viewContext = MakeViewContext("render-partial-with-segment-content", null); + factory.RenderView(viewContext); + mocks.VerifyAll(); + string content = sb.ToString(); + + Assert.That(content, Contains.InOrder( + "xbox", + "xtop", + "xb1", + "xb2", + "xb3", + "xb4", + "xboxcontent", + "title=\"My Tooltip\"", + "

    This is a test

    ", + "Hello World", + "xbottom", + "xb4", + "xb3", + "xb2", + "xb1")); + } + + [Test] + public void RenderPartialWithSectionAsHtml5ContentByDefault() + { + mocks.ReplayAll(); + var viewContext = MakeViewContext("render-partial-section-or-ignore", null); + factory.RenderView(viewContext); + mocks.VerifyAll(); + string content = sb.ToString(); + + Assert.That(content, Contains.InOrder( + "xbox", + "xtop", + "xb1", + "xb2", + "xb3", + "xb4", + "xboxcontent", + "
    ", + "

    This is a test

    ", + "
    ", + "
    ", + "My Tooltip", + "
    ", + "

    Hello World

    ", + "xbottom", + "xb4", + "xb3", + "xb2", + "xb1")); + } + + [Test] + public void RenderPartialWithSectionAsSegmentContentFromSettings() + { + settings.SetParseSectionTagAsSegment(true); + + mocks.ReplayAll(); + var viewContext = MakeViewContext("render-partial-section-or-ignore", null); + factory.RenderView(viewContext); + mocks.VerifyAll(); + string content = sb.ToString(); + + Assert.That(content, Contains.InOrder( + "xbox", + "xtop", + "xb1", + "xb2", + "xb3", + "xb4", + "xboxcontent", + "title=\"My Tooltip\"", + "

    This is a test

    ", + "Hello World", + "xbottom", + "xb4", + "xb3", + "xb2", + "xb1")); + } + + [Test] + public void RenderlPartialWithDotInName() + { + mocks.ReplayAll(); + var viewContext = MakeViewContext("render-dotted-partial", null); + factory.RenderView(viewContext); + mocks.VerifyAll(); + string content = sb.ToString(); + + Assert.That(content, Contains.InOrder( + "

    ", + "this.is.some.text:", + "test456", + "

    " + )); + + Assert.IsFalse(content.Contains("beforedataafter

    ")); + } + + [Test] + public void ConstAndReadonlyGlobals() + { + mocks.ReplayAll(); + var viewContext = MakeViewContext("const-and-readonly-globals", null); + factory.RenderView(viewContext); + mocks.VerifyAll(); + string content = sb.ToString().Replace("\r", "").Replace("\n", "").Replace("\t", "").Replace(" ", ""); + + Assert.AreEqual("
    1. 3
    2. 4
    3. 5
    4. 6
    5. 7
    ", content); + } + + [Test] + public void PrefixContentNotation() + { + mocks.ReplayAll(); + var viewContext = MakeViewContext("prefix-content-notation", null); + factory.RenderView(viewContext); + mocks.VerifyAll(); + string content = sb.ToString().Replace("\r", "").Replace("\n", "").Replace("\t", "").Replace(" ", ""); + + Assert.That(content.Contains("onetwothree")); + } + + [Test] + public void DynamicAttributes() + { + mocks.ReplayAll(); + var viewContext = MakeViewContext("dynamic-attributes", null); + factory.RenderView(viewContext); + mocks.VerifyAll(); + string content = sb.ToString(); + + Assert.That(content, Contains.InOrder( + "
    ", + @"", + @"", + @"", + @"", + + @"", + @"", + @"", + @"", + + @"", + @"", + + @"", + @"", + "
    " + )); + } + + [Test] + public void XMLDeclAndProcessingInstruction() + { + mocks.ReplayAll(); + var viewContext = MakeViewContext("xmldecl-and-processing-instruction", null); + factory.RenderView(viewContext); + mocks.VerifyAll(); + string content = sb.ToString(); + + Assert.That(content, Contains.InOrder( + "", + "" + )); + } + + + [Test] + public void ForEachAutovariablesUsedInline() + { + mocks.ReplayAll(); + var viewContext = MakeViewContext("foreach-autovariables-used-inline", null); + factory.RenderView(viewContext); + mocks.VerifyAll(); + string content = sb.ToString(); + + Assert.That(content, Contains.InOrder( + "", + "blah", "blah")); + + } + + [Test] + public void AlternateViewdataSyntax() + { + mocks.ReplayAll(); + var viewData = new StubViewData> { { "my-data", "alpha" } }; + viewData.Model = new[] { "beta", "gamma", "delta" }; + + var viewContext = MakeViewContext("alternate-viewdata-syntax", null, viewData); + factory.RenderView(viewContext); + mocks.VerifyAll(); + string content = sb.ToString(); + + Assert.That(content, Contains.InOrder( + "

    ", "alpha", "

    ", + "

    ", "beta", "

    ", + "

    ", "gamma", "

    ", + "

    ", "delta", "

    " + )); + } + + [Test] + public void DefaultValuesDontCollideWithExistingLocals() + { + mocks.ReplayAll(); + + var viewContext = MakeViewContext("DefaultValuesDontCollideWithExistingLocals", null); + factory.RenderView(viewContext); + mocks.VerifyAll(); + string content = sb.ToString(); + + Assert.IsFalse(content.Contains("default")); + + Assert.That(content, Contains.InOrder("ok1", "ok2")); + Assert.IsFalse(content.Contains("fail")); + } + + [Test] + public void DefaultValuesDontReplaceGlobals() + { + mocks.ReplayAll(); + + var viewContext = MakeViewContext("DefaultValuesDontReplaceGlobals", null); + factory.RenderView(viewContext); + mocks.VerifyAll(); + string content = sb.ToString(); + + Assert.IsFalse(content.Contains("default")); + + Assert.That(content, Contains.InOrder("ok1", "ok2")); + Assert.IsFalse(content.Contains("fail")); + } + + [Test] + public void DefaultValuesDontReplaceViewData() + { + mocks.ReplayAll(); + var viewData = new StubViewData { { "x1", 5 }, { "x2", 5 } }; + var viewContext = MakeViewContext("DefaultValuesDontReplaceViewData", null, viewData); + factory.RenderView(viewContext); + mocks.VerifyAll(); + string content = sb.ToString(); + + Assert.IsFalse(content.Contains("default")); + + Assert.That(content, Contains.InOrder("ok1", "ok2")); + Assert.IsFalse(content.Contains("fail")); + } + + + [Test] + public void DefaultValuesActAsLocal() + { + mocks.ReplayAll(); + var viewContext = MakeViewContext("DefaultValuesActAsLocal", null); + factory.RenderView(viewContext); + mocks.VerifyAll(); + string content = sb.ToString(); + + Assert.IsFalse(content.Contains("default")); + + Assert.That(content, Contains.InOrder("ok1", "ok2")); + Assert.IsFalse(content.Contains("fail")); + } + + [Test] + public void DefaultValuesStandInForNullViewData() + { + mocks.ReplayAll(); + var viewData = new StubViewData(); + var viewContext = MakeViewContext("DefaultValuesStandInForNullViewData", null, viewData); + factory.RenderView(viewContext); + mocks.VerifyAll(); + string content = sb.ToString(); + + Assert.IsFalse(content.Contains("default")); + + Assert.That(content, Contains.InOrder("ok1", "ok2")); + Assert.IsFalse(content.Contains("fail")); + } + + [Test] + public void NullExceptionHandledAutomatically() + { + mocks.ReplayAll(); + var viewData = new StubViewData(); + var viewContext = MakeViewContext("NullExceptionHandledAutomatically", null, viewData); + factory.RenderView(viewContext); + mocks.VerifyAll(); + string content = sb.ToString(); + + Assert.IsFalse(content.Contains("default")); + + Assert.That(content, Contains.InOrder( + "

    name kaboom *${user.Name}*

    ", + "

    name silently **

    ", + "

    name fixed *fred*

    ")); + } + + [Test] + public void CodeCommentsCanHaveQuotes() + { + mocks.ReplayAll(); + var viewContext = MakeViewContext("CodeCommentsCanHaveQuotes", null); + factory.RenderView(viewContext); + mocks.VerifyAll(); + string content = sb.ToString(); + + Assert.IsFalse(content.Contains("broken")); + Assert.That(content, Contains.InOrder("one", "two", "three", "four", "five")); + } + + [Test] + public void ConditionalAttributeDelimitedBySpaces() + { + mocks.ReplayAll(); + var viewContext = MakeViewContext("ConditionalAttributeDelimitedBySpaces", null); + factory.RenderView(viewContext); + mocks.VerifyAll(); + string content = sb.ToString(); + + Assert.IsFalse(content.Contains("broken")); + Assert.That(content, Contains.InOrder( + "

    ", + "

    ", + "

    ", + "

    ", + "
    ", + "
    ", + "")); + } + + + [Test] + public void OnceAttribute() + { + mocks.ReplayAll(); + var viewContext = MakeViewContext("OnceAttribute", null); + factory.RenderView(viewContext); + mocks.VerifyAll(); + string content = sb.ToString(); + + Assert.That(content, Contains.InOrder( + "foo1", + "bar0", + "quux2", + "a1")); + + Assert.IsFalse(content.Contains("foo2")); + Assert.IsFalse(content.Contains("foo3")); + Assert.IsFalse(content.Contains("bar1")); + Assert.IsFalse(content.Contains("bar3")); + Assert.IsFalse(content.Contains("a2")); + } + + + [Test] + public void EachAttributeWorksOnSpecialNodes() + { + mocks.ReplayAll(); + var viewContext = MakeViewContext("EachAttributeWorksOnSpecialNodes", null); + factory.RenderView(viewContext); + mocks.VerifyAll(); + string content = sb.ToString(); + + Assert.That(content, Contains.InOrder( + "

    name-0-alpha

    ", + "

    name-1-beta

    ", + "

    name-2-gamma

    ", + "one", + "two", + "three")); + } + + [Test] + public void IfAttributeWorksOnSpecialNodes() + { + mocks.ReplayAll(); + var viewContext = MakeViewContext("IfAttributeWorksOnSpecialNodes", null); + factory.RenderView(viewContext); + mocks.VerifyAll(); + string content = sb.ToString(); + + Assert.That(content, Contains.InOrder( + "

    name-0-alpha

    ", + "

    name-2-gamma

    ", + "one", + "three")); + + Assert.IsFalse(content.Contains("beta")); + Assert.IsFalse(content.Contains("two")); + } + + [Test] + public void UnlessAttributeWorksOnSpecialNodes() + { + mocks.ReplayAll(); + var viewContext = MakeViewContext("UnlessAttributeWorksOnSpecialNodes", null); + factory.RenderView(viewContext); + mocks.VerifyAll(); + string content = sb.ToString(); + + Assert.That(content, Contains.InOrder( + "

    name-0-alpha

    ", + "

    name-2-gamma

    ", + "one", + "three")); + + Assert.IsFalse(content.Contains("beta")); + Assert.IsFalse(content.Contains("two")); + } + + [Test] + public void OnceAttributeWorksOnSpecialNodes() + { + mocks.ReplayAll(); + var viewContext = MakeViewContext("OnceAttributeWorksOnSpecialNodes", null); + factory.RenderView(viewContext); + mocks.VerifyAll(); + string content = sb.ToString(); + + Assert.That(content, Contains.InOrder( + "

    name-0-alpha

    ", + "foo1", + "bar0", + "quux2")); + + Assert.IsFalse(content.Contains("name-1")); + Assert.IsFalse(content.Contains("name-2")); + Assert.IsFalse(content.Contains("foo2")); + Assert.IsFalse(content.Contains("foo3")); + Assert.IsFalse(content.Contains("bar1")); + Assert.IsFalse(content.Contains("bar3")); + } + + [Test] + public void LateBoundEvalResolvesViewData() + { + mocks.ReplayAll(); + var viewData = new StubViewData() + { + {"alpha", "hi"}, + {"beta", "yadda"} + }; + var viewContext = MakeViewContext("LateBoundEvalResolvesViewData", null, viewData); + factory.RenderView(viewContext); + mocks.VerifyAll(); + string content = sb.ToString(); + + Assert.That(content, Contains.InOrder( + "

    hi

    ", + "

    <strong>hi</strong>

    ", + "yadda", + "

    42

    ")); + + } + + [Test] + public void PartialInMacroMayUseDefaultElement() + { + mocks.ReplayAll(); + var viewContext = MakeViewContext("PartialInMacroMayUseDefaultElement", null); + factory.RenderView(viewContext); + mocks.VerifyAll(); + string content = sb.ToString(); + + Assert.That(content, Contains.InOrder( + "

    3hello

    ", + "

    2hello.

    ", + "

    1hello..

    ", + "

    0hello...

    ")); + + } + + [Test] + public void RecursivePartialsThrowCompilerException() + { + mocks.ReplayAll(); + var viewContext = MakeViewContext("RecursivePartialsThrowCompilerException", null); + Assert.That(() => + factory.RenderView(viewContext), + Throws.TypeOf()); + } + + [Test] + public void NestedPartialsCanBackRenderUpAndReRenderDown() + { + mocks.ReplayAll(); + var viewContext = MakeViewContext("NestedPartialsCanBackRenderUpAndReRenderDown", null); + factory.RenderView(viewContext); + mocks.VerifyAll(); + string content = sb.ToString(); + + var stripped = content.Replace(" ", "").Replace("\t", "").Replace("\r\n", ""); + Assert.That(stripped, Is.EqualTo( + "[001][101]" + + "[201][102]" + + "[201][104][202]" + + "[106][002][107]" + + "[201][109][202]" + + "[111][202]" + + "[112][003]")); + } + + [Test] + public void SegmentRenderingFallbackMayRenderSegment() + { + mocks.ReplayAll(); + var viewContext = MakeViewContext("SegmentRenderingFallbackMayRenderSegment", null); + factory.RenderView(viewContext); + mocks.VerifyAll(); + string content = sb.ToString(); + var stripped = content.Replace(" ", "").Replace("\t", "").Replace("\r\n", ""); + Assert.That(stripped, Is.EqualTo( + "[001]" + + "[101][102]" + + "[002][004]" + + "[103][104]" + + "[005]")); + } + + [Test] + public void Markdown() + { + mocks.ReplayAll(); + var viewContext = MakeViewContext("markdown", null); + factory.RenderView(viewContext); + mocks.VerifyAll(); + + string content = sb.ToString(); + + Assert.That(content, Contains.InOrder( + "
    ", "code block on the first line", "
    ", + "

    ", "Regular text.", "

    ", + "
    ", "code block indented by spaces", "
    ", + "

    ", "Regular text.", "

    ", + "
    ", "the lines in this block",
    +                "all contain trailing spaces", "
    ", + "

    ", "Regular Text.", "

    ", + "
    ", "code block on the last line", "
    ")); + } + + [Test] + public void Ignore() + { + mocks.ReplayAll(); + var viewContext = MakeViewContext("ignore", null); + factory.RenderView(viewContext); + mocks.VerifyAll(); + + string content = sb.ToString(); + + Assert.That(content, Contains.InOrder( + "
    ", + "Regular text ${This.isnt.code < 0}", + "", + "
    ")); + Assert.IsFalse(content.Contains("")); + Assert.IsFalse(content.Contains("")); + } + + [Test] + public void Escape() + { + mocks.ReplayAll(); + var viewContext = MakeViewContext("escape", null); + factory.RenderView(viewContext); + mocks.VerifyAll(); + + string content = sb.ToString(); + + Assert.That(content, Contains.InOrder( + "
    ", + "${Encoded.Escaped.with.a.dollar < 0}", + "${Encoded.Escaped.with.a.backslash < 0}", + "${Encoded.Escaped.with.a.backtick < 0}", + "
    ")); + + Assert.That(content, Contains.InOrder( + "
    ", + "!{Unencoded.Escaped.with.a.dollar < 0}", + "!{Unencoded.Escaped.with.a.backslash < 0}", + "!{Unencoded.Escaped.with.a.backtick < 0}", + "
    ")); + + Assert.That(content, Contains.InOrder( + "
    ", + "$!{Encoded.Silent.Nulls.Escaped.with.a.dollar < 0}", + "$!{Encoded.Silent.Nulls.Escaped.with.a.backslash < 0}", + "$!{Encoded.Silent.Nulls.Escaped.with.a.backtick < 0}", + "
    ")); + } + + [Test] + public void PreserveSingleQuotes() + { + mocks.ReplayAll(); + var viewContext = MakeViewContext("preserveSingleQuotes", null); + factory.RenderView(viewContext); + mocks.VerifyAll(); + + string content = sb.ToString(); + + Assert.That(content, Is.EqualTo(@"")); + } + + [Test] + public void PreserveDoubleQuotes() + { + mocks.ReplayAll(); + var viewContext = MakeViewContext("preserveDoubleQuotes", null); + factory.RenderView(viewContext); + mocks.VerifyAll(); + + string content = sb.ToString(); + + Assert.That(content, Is.EqualTo(@"")); + } + + + [Test] + public void ShadeFileRenders() + { + mocks.ReplayAll(); + var viewContext = MakeViewContext("ShadeFileRenders", null); + factory.RenderView(viewContext, Constants.DotShade); + mocks.VerifyAll(); + + var content = sb.ToString(); + + Assert.That(content, Contains.InOrder( + "", + "", + "", + "offset test", + "", + "", + "
    ", + "

    ", + "offset test", + "

    ", + "
    ", + "", + "")); + } + + [Test] + public void ShadeEvaluatesExpressions() + { + mocks.ReplayAll(); + var viewContext = MakeViewContext("ShadeEvaluatesExpressions", null); + factory.RenderView(viewContext, Constants.DotShade); + mocks.VerifyAll(); + + var content = sb.ToString(); + + Assert.That(content, Contains.InOrder( + "

    ", + "", + "8", + "", + "", + "2", " and ", "7", + "", + "

    ")); + } + + [Test] + public void ShadeSupportsAttributesAndMayTreatSomeElementsAsSpecialNodes() + { + mocks.ReplayAll(); + var viewContext = MakeViewContext("ShadeSupportsAttributesAndMayTreatSomeElementsAsSpecialNodes", null); + factory.RenderView(viewContext, Constants.DotShade); + mocks.VerifyAll(); + + var content = sb.ToString(); + + Assert.That(content, Contains.InOrder( + "
      ", + "
    • Welcome
    • ", + "
    • to
    • ", + "
    • the
    • ", + "
    • Machine
    • ", + "
    ", + "

    ", + "4", + "

    ")); + } + + [Test] + public void ShadeCodeMayBeDashOrAtBraced() + { + mocks.ReplayAll(); + var viewContext = MakeViewContext("ShadeCodeMayBeDashOrAtBraced", null); + factory.RenderView(viewContext, Constants.DotShade); + mocks.VerifyAll(); + + var content = sb.ToString(); + + Assert.That(content, Contains.InOrder( + "
      ", + "
    • emocleW
    • ", + "
    • ot
    • ", + "
    • eht
    • ", + "
    • enihcaM
    • ", + "
    ")); + } + + + [Test] + public void ShadeTextMayContainExpressions() + { + mocks.ReplayAll(); + var viewContext = MakeViewContext("ShadeTextMayContainExpressions", null); + factory.RenderView(viewContext, Constants.DotShade); + mocks.VerifyAll(); + + var content = sb.ToString(); + + Assert.That(content, Contains.InOrder( + "

    ", + "8", + "2 and 7", + "

    ")); + } + + [Test] + public void TextOrientedAttributesApplyToVarAndSet() + { + mocks.ReplayAll(); + ((SparkSettings)engine.Settings).AttributeBehaviour = AttributeBehaviour.TextOriented; + var viewContext = MakeViewContext("TextOrientedAttributesApplyToVarAndSet", null); + factory.RenderView(viewContext, Constants.DotSpark); + mocks.VerifyAll(); + + var content = sb.ToString(); + + Assert.That(content, Contains.InOrder( + "

    String:HelloWorld

    ", + "

    Int32:42

    ")); + } + + [Test] + public void TextOrientedAttributesApplyToUseFile() + { + mocks.ReplayAll(); + ((SparkSettings)engine.Settings).AttributeBehaviour = AttributeBehaviour.TextOriented; + var viewContext = MakeViewContext("TextOrientedAttributesApplyToUseFile", null); + factory.RenderView(viewContext, Constants.DotSpark); + mocks.VerifyAll(); + + var content = sb.ToString(); + + Assert.That(content, Contains.InOrder( + "Hello", + "Hello World!", + "42")); + } + + [Test] + public void TextOrientedAttributesApplyToDefault() + { + mocks.ReplayAll(); + ((SparkSettings)engine.Settings).AttributeBehaviour = AttributeBehaviour.TextOriented; + var viewContext = MakeViewContext("TextOrientedAttributesApplyToDefault", null); + factory.RenderView(viewContext, Constants.DotSpark); + mocks.VerifyAll(); + + var content = sb.ToString(); + + Assert.That(content, Contains.InOrder( + "

    String:World

    ", + "

    String:Hello World!

    ", + "

    Int32:42

    ")); + } + + + [Test] + public void TextOrientedAttributesApplyToGlobal() + { + mocks.ReplayAll(); + ((SparkSettings)engine.Settings).AttributeBehaviour = AttributeBehaviour.TextOriented; + var viewContext = MakeViewContext("TextOrientedAttributesApplyToGlobal", null); + factory.RenderView(viewContext, Constants.DotSpark); + mocks.VerifyAll(); + + var content = sb.ToString(); + + Assert.That(content, Contains.InOrder( + "

    String:World

    ", + "

    String:Hello World!

    ", + "

    Int32:42

    ")); + } + + + [Test] + public void ShadeElementsMayStackOnOneLine() + { + mocks.ReplayAll(); + var viewContext = MakeViewContext("ShadeElementsMayStackOnOneLine", null); + factory.RenderView(viewContext, Constants.DotShade); + mocks.VerifyAll(); + + var content = sb.ToString(); + + Assert.That(content, Contains.InOrder( + "", + "", + "", + "offset test", + "", + "", + "
    ", + "

    ", + "offset test", + "

    ", + "
    ", + "", + "")); + } + } +} diff --git a/src/Spark.Tests/Stubs/StubCacheService.cs b/src/Spark.Web.Tests/Stubs/StubCacheService.cs similarity index 96% rename from src/Spark.Tests/Stubs/StubCacheService.cs rename to src/Spark.Web.Tests/Stubs/StubCacheService.cs index ecda5669..74ee302c 100644 --- a/src/Spark.Tests/Stubs/StubCacheService.cs +++ b/src/Spark.Web.Tests/Stubs/StubCacheService.cs @@ -1,63 +1,63 @@ -using System; -using System.Collections.Generic; - -namespace Spark.Tests.Stubs -{ - public class StubCacheService : ICacheService - { - private readonly IDictionary _cache = new Dictionary(); - - public StubCacheService() - { - UtcNow = new DateTime(2009, 1, 2, 3, 4, 5); - } - - public object Get(string identifier) - { - Entry item; - return _cache.TryGetValue(identifier, out item) && IsValid(item) ? item.Value : null; - } - - private bool IsValid(Entry item) - { - return item.UtcExpires == CacheExpires.NoAbsoluteExpiration || - item.UtcExpires > UtcNow; - } - - public void Store(string identifier, CacheExpires expires, ICacheSignal signal, object item) - { - _cache[identifier] = new Entry {Value = item, UtcExpires = ToAbsolute(expires)}; - - if (signal != null) - { - signal.Changed += (sender, e) => _cache.Remove(identifier); - } - } - - private DateTime ToAbsolute(CacheExpires expires) - { - // this is less sophisticated than the web caching implementation, but - // it only needs to satisfy expectations of unit tests. they should always - // use utc for abs - - if (expires == null) - return CacheExpires.NoAbsoluteExpiration; - - if (expires.Sliding != CacheExpires.NoSlidingExpiration) - { - return UtcNow.Add(expires.Sliding); - } - - return expires.Absolute; - } - - public DateTime UtcNow { get; set; } - public IEnumerable AllKeys { get { return _cache.Keys; } } - - class Entry - { - public object Value { get; set; } - public DateTime UtcExpires { get; set; } - } - } +using System; +using System.Collections.Generic; + +namespace Spark.Tests.Stubs +{ + public class StubCacheService : ICacheService + { + private readonly IDictionary _cache = new Dictionary(); + + public StubCacheService() + { + UtcNow = new DateTime(2009, 1, 2, 3, 4, 5); + } + + public object Get(string identifier) + { + Entry item; + return _cache.TryGetValue(identifier, out item) && IsValid(item) ? item.Value : null; + } + + private bool IsValid(Entry item) + { + return item.UtcExpires == CacheExpires.NoAbsoluteExpiration || + item.UtcExpires > UtcNow; + } + + public void Store(string identifier, CacheExpires expires, ICacheSignal signal, object item) + { + _cache[identifier] = new Entry {Value = item, UtcExpires = ToAbsolute(expires)}; + + if (signal != null) + { + signal.Changed += (sender, e) => _cache.Remove(identifier); + } + } + + private DateTime ToAbsolute(CacheExpires expires) + { + // this is less sophisticated than the web caching implementation, but + // it only needs to satisfy expectations of unit tests. they should always + // use utc for abs + + if (expires == null) + return CacheExpires.NoAbsoluteExpiration; + + if (expires.Sliding != CacheExpires.NoSlidingExpiration) + { + return UtcNow.Add(expires.Sliding); + } + + return expires.Absolute; + } + + public DateTime UtcNow { get; set; } + public IEnumerable AllKeys { get { return _cache.Keys; } } + + class Entry + { + public object Value { get; set; } + public DateTime UtcExpires { get; set; } + } + } } \ No newline at end of file diff --git a/src/Spark.Tests/Stubs/StubSparkView.cs b/src/Spark.Web.Tests/Stubs/StubSparkView.cs similarity index 96% rename from src/Spark.Tests/Stubs/StubSparkView.cs rename to src/Spark.Web.Tests/Stubs/StubSparkView.cs index 60562d4d..cc729d98 100644 --- a/src/Spark.Tests/Stubs/StubSparkView.cs +++ b/src/Spark.Web.Tests/Stubs/StubSparkView.cs @@ -1,68 +1,68 @@ -// Copyright 2008-2009 Louis DeJardin - http://whereslou.com -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// -using System; -using System.Web; - -namespace Spark.Tests.Stubs -{ - public abstract class StubSparkView : SparkViewBase - { - protected StubSparkView() - { - ViewData = new StubViewData(); - } - - public StubViewData ViewData { get; set; } - - public string SiteRoot - { - get { return "/TestApp"; } - } - - public string SiteResource(string path) - { - return SiteRoot + path.TrimStart('~'); - } - - public override bool TryGetViewData(string name, out object value) - { - return ViewData.TryGetValue(name, out value); - } - - public string H(object content) - { - return HttpUtility.HtmlEncode(Convert.ToString(content)); - } - - public object HTML(object value) - { - return value; - } - - public object Eval(string expression) - { - return ViewData.Eval(expression); - } - } - - public abstract class StubSparkView : StubSparkView - { - public new StubViewData ViewData - { - get { return (StubViewData)base.ViewData; } - set { base.ViewData = value; } - } - } -} +// Copyright 2008-2009 Louis DeJardin - http://whereslou.com +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +using System; +using System.Web; + +namespace Spark.Tests.Stubs +{ + public abstract class StubSparkView : SparkViewBase + { + protected StubSparkView() + { + ViewData = new StubViewData(); + } + + public StubViewData ViewData { get; set; } + + public string SiteRoot + { + get { return "/TestApp"; } + } + + public string SiteResource(string path) + { + return SiteRoot + path.TrimStart('~'); + } + + public override bool TryGetViewData(string name, out object value) + { + return ViewData.TryGetValue(name, out value); + } + + public string H(object content) + { + return HttpUtility.HtmlEncode(Convert.ToString(content)); + } + + public object HTML(object value) + { + return value; + } + + public object Eval(string expression) + { + return ViewData.Eval(expression); + } + } + + public abstract class StubSparkView : StubSparkView + { + public new StubViewData ViewData + { + get { return (StubViewData)base.ViewData; } + set { base.ViewData = value; } + } + } +} diff --git a/src/Spark.Tests/Stubs/StubSparkView2.cs b/src/Spark.Web.Tests/Stubs/StubSparkView2.cs similarity index 95% rename from src/Spark.Tests/Stubs/StubSparkView2.cs rename to src/Spark.Web.Tests/Stubs/StubSparkView2.cs index a63ac3b6..d0c1e644 100644 --- a/src/Spark.Tests/Stubs/StubSparkView2.cs +++ b/src/Spark.Web.Tests/Stubs/StubSparkView2.cs @@ -1,57 +1,57 @@ -using System; -using System.Web; - -namespace Spark.Tests.Stubs -{ - public abstract class StubSparkView2 : AbstractSparkView - { - protected StubSparkView2() - { - ViewData = new StubViewData(); - } - - public StubViewData ViewData { get; set; } - - public string SiteRoot - { - get { return "/TestApp"; } - } - - public string SiteResource(string path) - { - return SiteRoot + path.TrimStart('~'); - } - - public override bool TryGetViewData(string name, out object value) - { - return ViewData.TryGetValue(name, out value); - } - - public string H(object content) - { - return HttpUtility.HtmlEncode(Convert.ToString(content)); - } - - public object Eval(string expression) - { - return ViewData.Eval(expression); - } - } - - public abstract class StubSparkView2 : StubSparkView2 - { - public new StubViewData ViewData - { - get { return (StubViewData)base.ViewData; } - set { base.ViewData = value; } - } - } - - public abstract class StubSparkView3 : StubSparkView2 - { - public TMore GetMore() - { - return default(TMore); - } - } +using System; +using System.Web; + +namespace Spark.Tests.Stubs +{ + public abstract class StubSparkView2 : AbstractSparkView + { + protected StubSparkView2() + { + ViewData = new StubViewData(); + } + + public StubViewData ViewData { get; set; } + + public string SiteRoot + { + get { return "/TestApp"; } + } + + public string SiteResource(string path) + { + return SiteRoot + path.TrimStart('~'); + } + + public override bool TryGetViewData(string name, out object value) + { + return ViewData.TryGetValue(name, out value); + } + + public string H(object content) + { + return HttpUtility.HtmlEncode(Convert.ToString(content)); + } + + public object Eval(string expression) + { + return ViewData.Eval(expression); + } + } + + public abstract class StubSparkView2 : StubSparkView2 + { + public new StubViewData ViewData + { + get { return (StubViewData)base.ViewData; } + set { base.ViewData = value; } + } + } + + public abstract class StubSparkView3 : StubSparkView2 + { + public TMore GetMore() + { + return default(TMore); + } + } } \ No newline at end of file diff --git a/src/Spark.Tests/Stubs/StubViewFactory.cs b/src/Spark.Web.Tests/Stubs/StubViewFactory.cs similarity index 91% rename from src/Spark.Tests/Stubs/StubViewFactory.cs rename to src/Spark.Web.Tests/Stubs/StubViewFactory.cs index 8d28ac06..a0a8fcd7 100644 --- a/src/Spark.Tests/Stubs/StubViewFactory.cs +++ b/src/Spark.Web.Tests/Stubs/StubViewFactory.cs @@ -1,42 +1,38 @@ -// Copyright 2008-2009 Louis DeJardin - http://whereslou.com -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// -using System; -using System.Collections.Generic; -using System.IO; -using System.Linq; -using System.Text; -using Spark.FileSystem; - -namespace Spark.Tests.Stubs -{ - public class StubViewFactory - { - public ISparkViewEngine Engine { get; set; } - public ICacheService CacheService { get; set; } - - public void RenderView(StubViewContext viewContext, string extension = null) - { - var descriptor = new SparkViewDescriptor(); - descriptor.Templates.Add(Path.Combine(viewContext.ControllerName, viewContext.ViewName + (extension ?? Constants.DotSpark))); - if (viewContext.MasterName != null) - descriptor.Templates.Add(Path.Combine(Constants.Shared, viewContext.MasterName + (extension ?? Constants.DotSpark))); - - var sparkView = Engine.CreateInstance(descriptor); - ((StubSparkView)sparkView).ViewData = viewContext.Data; - ((StubSparkView)sparkView).CacheService = CacheService; - sparkView.RenderView(new StringWriter(viewContext.Output)); - } - } +// Copyright 2008-2009 Louis DeJardin - http://whereslou.com +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +using System.IO; + +namespace Spark.Tests.Stubs +{ + public class StubViewFactory + { + public ISparkViewEngine Engine { get; set; } + public ICacheService CacheService { get; set; } + + public void RenderView(StubViewContext viewContext, string extension = null) + { + var descriptor = new SparkViewDescriptor(); + descriptor.Templates.Add(Path.Combine(viewContext.ControllerName, viewContext.ViewName + (extension ?? Constants.DotSpark))); + if (viewContext.MasterName != null) + descriptor.Templates.Add(Path.Combine(Constants.Shared, viewContext.MasterName + (extension ?? Constants.DotSpark))); + + var sparkView = Engine.CreateInstance(descriptor); + ((StubSparkView)sparkView).ViewData = viewContext.Data; + ((StubSparkView)sparkView).CacheService = CacheService; + sparkView.RenderView(new StringWriter(viewContext.Output)); + } + } } \ No newline at end of file diff --git a/src/Spark.Tests/ViewActivatorTester.cs b/src/Spark.Web.Tests/ViewActivatorTester.cs similarity index 95% rename from src/Spark.Tests/ViewActivatorTester.cs rename to src/Spark.Web.Tests/ViewActivatorTester.cs index 2558973f..8432e51d 100644 --- a/src/Spark.Tests/ViewActivatorTester.cs +++ b/src/Spark.Web.Tests/ViewActivatorTester.cs @@ -1,142 +1,139 @@ -// Copyright 2008-2009 Louis DeJardin - http://whereslou.com -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// -using System; -using System.Collections.Generic; -using System.Diagnostics; -using System.IO; -using System.Linq; -using System.Text; -using NUnit.Framework; -using Spark.FileSystem; -using Spark.Tests.Stubs; - -namespace Spark.Tests -{ - [TestFixture] - public class ViewActivatorTester - { - class TestView : ISparkView - { - public void RenderView(TextWriter writer) - { - throw new System.NotImplementedException(); - } - - public Guid GeneratedViewId - { - get { throw new System.NotImplementedException(); } - } - - public bool TryGetViewData(string name, out object value) - { - throw new System.NotImplementedException(); - } - } - - class CustomFactory : IViewActivatorFactory, IViewActivator - { - public IViewActivator Register(Type type) - { - return this; - } - - public void Unregister(Type type, IViewActivator activator) - { - - } - - public ISparkView Activate(Type type) - { - return new TestView(); - } - - public void Release(Type type, ISparkView view) - { - } - } - - [Test] - public void CreateViewInstance() - { - var type = typeof(TestView); - var factory = new DefaultViewActivator(); - var activator = factory.Register(type); - var view = activator.Activate(type); - Assert.IsNotNull(view); - Assert.IsAssignableFrom(typeof(TestView), view); - } - - [Test] - public void FastCreateViewInstance() - { - var type = typeof(TestView); - var factory = new FastViewActivator(); - var activator = factory.Register(type); - var view = activator.Activate(type); - Assert.IsNotNull(view); - Assert.IsAssignableFrom(typeof(TestView), view); - } - - [Test] - public void CustomViewActivator() - { - var engine = new SparkViewEngine( - new SparkSettings().SetPageBaseType(typeof(StubSparkView))) - { - ViewActivatorFactory = new CustomFactory(), - ViewFolder = new InMemoryViewFolder { { "hello/world.spark", "

    hello world

    " } } - }; - - var descriptor = new SparkViewDescriptor().AddTemplate("hello/world.spark"); - var view = engine.CreateInstance(descriptor); - - Assert.IsNotNull(view); - Assert.IsAssignableFrom(typeof(TestView), view); - } - - [Test, Explicit] - public void PerfTest() - { - var type = typeof(TestView); - var defFactory = new DefaultViewActivator(); - var fastFactory = new FastViewActivator(); - - var activator = defFactory.Register(type); - var fastActivator = fastFactory.Register(type); - var iterations = 1000000; - - Stopwatch sw = new Stopwatch(); - sw.Start(); - - for (int i = 0; i < iterations; i++) - { - var view = activator.Activate(type); - } - sw.Stop(); - - Console.WriteLine("Default took: {0}ms", sw.Elapsed.TotalMilliseconds); - sw.Reset(); - - sw.Start(); - - for (int i = 0; i < iterations; i++) - { - var view = fastActivator.Activate(type); - } - sw.Stop(); - Console.WriteLine("Fast took: {0}ms", sw.Elapsed.TotalMilliseconds); - } - } -} +// Copyright 2008-2009 Louis DeJardin - http://whereslou.com +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +using System; +using System.Diagnostics; +using System.IO; +using NUnit.Framework; +using Spark.FileSystem; +using Spark.Tests.Stubs; + +namespace Spark.Tests +{ + [TestFixture] + public class ViewActivatorTester + { + class TestView : ISparkView + { + public void RenderView(TextWriter writer) + { + throw new System.NotImplementedException(); + } + + public Guid GeneratedViewId + { + get { throw new System.NotImplementedException(); } + } + + public bool TryGetViewData(string name, out object value) + { + throw new System.NotImplementedException(); + } + } + + class CustomFactory : IViewActivatorFactory, IViewActivator + { + public IViewActivator Register(Type type) + { + return this; + } + + public void Unregister(Type type, IViewActivator activator) + { + + } + + public ISparkView Activate(Type type) + { + return new TestView(); + } + + public void Release(Type type, ISparkView view) + { + } + } + + [Test] + public void CreateViewInstance() + { + var type = typeof(TestView); + var factory = new DefaultViewActivator(); + var activator = factory.Register(type); + var view = activator.Activate(type); + Assert.IsNotNull(view); + Assert.IsAssignableFrom(typeof(TestView), view); + } + + [Test] + public void FastCreateViewInstance() + { + var type = typeof(TestView); + var factory = new FastViewActivator(); + var activator = factory.Register(type); + var view = activator.Activate(type); + Assert.IsNotNull(view); + Assert.IsAssignableFrom(typeof(TestView), view); + } + + [Test] + public void CustomViewActivator() + { + var engine = new SparkViewEngine( + new SparkSettings().SetPageBaseType(typeof(StubSparkView))) + { + ViewActivatorFactory = new CustomFactory(), + ViewFolder = new InMemoryViewFolder { { "hello/world.spark", "

    hello world

    " } } + }; + + var descriptor = new SparkViewDescriptor().AddTemplate("hello/world.spark"); + var view = engine.CreateInstance(descriptor); + + Assert.IsNotNull(view); + Assert.IsAssignableFrom(typeof(TestView), view); + } + + [Test, Explicit] + public void PerfTest() + { + var type = typeof(TestView); + var defFactory = new DefaultViewActivator(); + var fastFactory = new FastViewActivator(); + + var activator = defFactory.Register(type); + var fastActivator = fastFactory.Register(type); + var iterations = 1000000; + + Stopwatch sw = new Stopwatch(); + sw.Start(); + + for (int i = 0; i < iterations; i++) + { + var view = activator.Activate(type); + } + sw.Stop(); + + Console.WriteLine("Default took: {0}ms", sw.Elapsed.TotalMilliseconds); + sw.Reset(); + + sw.Start(); + + for (int i = 0; i < iterations; i++) + { + var view = fastActivator.Activate(type); + } + sw.Stop(); + Console.WriteLine("Fast took: {0}ms", sw.Elapsed.TotalMilliseconds); + } + } +} diff --git a/src/Spark.Tests/VisualBasicViewTester.cs b/src/Spark.Web.Tests/VisualBasicViewTester.cs similarity index 92% rename from src/Spark.Tests/VisualBasicViewTester.cs rename to src/Spark.Web.Tests/VisualBasicViewTester.cs index 85430b07..dfb62248 100644 --- a/src/Spark.Tests/VisualBasicViewTester.cs +++ b/src/Spark.Web.Tests/VisualBasicViewTester.cs @@ -1,364 +1,361 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using NUnit.Framework; - -using Spark.FileSystem; -using Spark.Tests.Models; -using Spark.Tests.Stubs; -using System.IO; - -namespace Spark.Tests -{ - [TestFixture] - [Platform(Exclude = "Mono", Reason = "Problems with Mono-2.10+/Linux and the VB compiler prevent this from running.")] - public class VisualBasicViewTester - { - private InMemoryViewFolder _viewFolder; - private StubViewFactory _factory; - - [SetUp] - public void Init() - { - _viewFolder = new InMemoryViewFolder(); - _factory = new StubViewFactory - { - Engine = new SparkViewEngine( - new SparkSettings() - .SetDefaultLanguage(LanguageType.VisualBasic) - .SetPageBaseType(typeof(StubSparkView))) - { - ViewFolder = _viewFolder - } - }; - } - - private string Render(string viewName) - { - return Render(viewName, new StubViewData()); - } - - private string Render(string viewName, StubViewData viewData) - { - var context = new StubViewContext() { ControllerName = "vbhome", ViewName = viewName, Output = new StringBuilder(), Data = viewData }; - _factory.RenderView(context); - return context.Output.ToString(); - } - - - - [Test] - public void CompileAndRunVisualBasicView() - { - _viewFolder.Add(Path.Combine("vbhome", "index.spark"), "Hello world"); - var contents = Render("index"); - Assert.That(contents, Is.EqualTo("Hello world")); - } - - [Test] - public void ShouldWriteTabAndCrlf() - { - _viewFolder.Add(Path.Combine("vbhome", "index.spark"), "Hello\r\n\tworld"); - var contents = Render("index"); - Assert.That(contents, Is.EqualTo("Hello\r\n\tworld")); - } - - [Test] - public void CodeStatementChunks() - { - _viewFolder.Add(Path.Combine("vbhome", "index.spark"), @" -#Dim foo = 'hi there' -<%Dim bar = 'hello again'%> -${foo} ${bar}"); - - var contents = Render("index"); - Assert.That(contents.Trim(), Is.EqualTo("hi there hello again")); - } - - [Test] - public void GlobalVariableChunks() - { - _viewFolder.Add(Path.Combine("vbhome", "index.spark"), @" - -${foo} ${bar} -#bar='there' -${bar} -"); - - var contents = Render("index"); - Assert.That(contents.Trim(), Is.EqualTo("5 hello\r\nthere")); - } - - [Test] - public void TypedGlobalVariableChunks() - { - _viewFolder.Add(Path.Combine("vbhome", "index.spark"), @" - -${bar} ${bar.Length} -"); - - var contents = Render("index"); - Assert.That(contents.Trim(), Is.EqualTo("hello 5")); - } - - [Test] - public void LocalVariableChunks() - { - _viewFolder.Add(Path.Combine("vbhome", "index.spark"), @" - - -${foo} ${bar} ${bar.Length} -"); - - var contents = Render("index"); - Assert.That(contents.Trim(), Is.EqualTo("5 hello 5")); - } - - [Test] - public void DefaultValuesDontCollideWithExistingLocals() - { - _viewFolder.Add(Path.Combine("vbhome", "index.spark"), @" - - - - -

    ok1

    -fail - - - -

    ok2

    - fail -
    -
    - -"); - var contents = Render("index"); - - Assert.That(contents, Does.Contain("ok1")); - Assert.That(contents, Does.Contain("ok2")); - Assert.That(contents, Is.Not.StringContaining("fail")); - } - - [Test] - public void DefaultValuesDontReplaceGlobals() - { - _viewFolder.Add(Path.Combine("vbhome", "index.spark"), @" - - -

    ok1

    -fail - - -

    ok2

    - fail -
    - - - -"); - var contents = Render("index"); - - Assert.That(contents, Does.Contain("ok1")); - Assert.That(contents, Does.Contain("ok2")); - Assert.That(contents, Is.Not.StringContaining("fail")); - } - - - [Test] - public void DefaultValuesDontReplaceViewData() - { - _viewFolder.Add(Path.Combine("vbhome", "index.spark"), @" - - -

    ok1

    -fail - - -

    ok2

    - fail -
    - - - -"); - var contents = Render("index", new StubViewData { { "x1", 5 }, { "x2", 5 } }); - - Assert.That(contents, Does.Contain("ok1")); - Assert.That(contents, Does.Contain("ok2")); - Assert.That(contents, Is.Not.StringContaining("fail")); - } - - - [Test] - public void DefaultValuesActAsLocal() - { - _viewFolder.Add(Path.Combine("vbhome", "index.spark"), @" - - -

    ok1

    -fail - - -

    ok2

    - fail -
    - -"); - var contents = Render("index"); - - Assert.That(contents, Does.Contain("ok1")); - Assert.That(contents, Does.Contain("ok2")); - Assert.That(contents, Is.Not.StringContaining("fail")); - } - - [Test] - public void DefaultValuesStandInForNullViewData() - { - _viewFolder.Add(Path.Combine("vbhome", "index.spark"), @" -

    ok1

    -fail - - -

    ok2

    - fail -
    - - - - - -"); - var contents = Render("index"); - - Assert.That(contents, Does.Contain("ok1")); - Assert.That(contents, Does.Contain("ok2")); - Assert.That(contents, Is.Not.StringContaining("fail")); - } - - [Test] - public void ViewDataChunks() - { - _viewFolder.Add(Path.Combine("vbhome", "index.spark"), @" - -${x1} ${x2} -"); - var contents = Render("index", new StubViewData { { "x1", 4 }, { "x2", "hello" } }); - Assert.That(contents.Trim(), Is.EqualTo("4 hello")); - } - - [Test] - public void ViewDataModelChunk() - { - - _viewFolder.Add(Path.Combine("vbhome", "index.spark"), @" - -${Comment.Text} -"); - var comment = new Comment { Text = "hello world" }; - var contents = Render("index", new StubViewData { Model = comment }); - Assert.That(contents.Trim(), Is.EqualTo("hello world")); - } - - [Test] - public void AssignChunk() - { - _viewFolder.Add(Path.Combine("vbhome", "index.spark"), @" -#Dim x = 4 - -${x} -"); - var contents = Render("index"); - Assert.That(contents.Trim(), Is.EqualTo("5")); - } - - [Test] - public void ContentNameAndUseContentChunk() - { - _viewFolder.Add(Path.Combine("vbhome", "index.spark"), @" -bar -[] -"); - var contents = Render("index"); - Assert.That(contents.Trim(), Is.EqualTo("[bar]")); - } - - [Test] - public void RenderPartialChunk() - { - _viewFolder.Add(Path.Combine("vbhome", "index.spark"), @"[]"); - _viewFolder.Add(Path.Combine("shared", "_foo.spark"), @"bar"); - - var contents = Render("index"); - Assert.That(contents.Trim(), Is.EqualTo("[bar]")); - } - - [Test] - public void ContentVarChunk() - { - _viewFolder.Add(Path.Combine("vbhome", "index.spark"), @" -bar -[${foo}] -"); - - var contents = Render("index"); - Assert.That(contents.Trim(), Is.EqualTo("[bar]")); - } - - [Test] - public void ContentSetChunk() - { - _viewFolder.Add(Path.Combine("vbhome", "index.spark"), @" - -fred -bar -quad -[${foo}] -"); - - var contents = Render("index"); - Assert.That(contents.Trim(), Is.EqualTo("[barfredquad]")); - } - - [Test] - public void ConditionalAttributes() - { - _viewFolder.Add(Path.Combine("vbhome", "index.spark"), @" - - - - - - - - -"); - - var contents = Render("index"); - Assert.That(contents.Trim(), Is.EqualTo(@" - - - - - - - - -")); - } - - [Test] - public void MacroChunks() - { - _viewFolder.Add(Path.Combine("vbhome", "index.spark"), @" -bar -bar2${quux}bar3 -${foo2('alpha')} ${foo} -"); - - var contents = Render("index"); - Assert.That(contents.Trim(), Is.EqualTo("bar2alphabar3 bar")); - } - } -} +using System.Text; +using NUnit.Framework; + +using Spark.FileSystem; +using Spark.Tests.Models; +using Spark.Tests.Stubs; +using System.IO; + +namespace Spark.Tests +{ + [TestFixture] + [Platform(Exclude = "Mono", Reason = "Problems with Mono-2.10+/Linux and the VB compiler prevent this from running.")] + public class VisualBasicViewTester + { + private InMemoryViewFolder _viewFolder; + private StubViewFactory _factory; + + [SetUp] + public void Init() + { + _viewFolder = new InMemoryViewFolder(); + _factory = new StubViewFactory + { + Engine = new SparkViewEngine( + new SparkSettings() + .SetDefaultLanguage(LanguageType.VisualBasic) + .SetPageBaseType(typeof(StubSparkView))) + { + ViewFolder = _viewFolder + } + }; + } + + private string Render(string viewName) + { + return Render(viewName, new StubViewData()); + } + + private string Render(string viewName, StubViewData viewData) + { + var context = new StubViewContext() { ControllerName = "vbhome", ViewName = viewName, Output = new StringBuilder(), Data = viewData }; + _factory.RenderView(context); + return context.Output.ToString(); + } + + + + [Test] + public void CompileAndRunVisualBasicView() + { + _viewFolder.Add(Path.Combine("vbhome", "index.spark"), "Hello world"); + var contents = Render("index"); + Assert.That(contents, Is.EqualTo("Hello world")); + } + + [Test] + public void ShouldWriteTabAndCrlf() + { + _viewFolder.Add(Path.Combine("vbhome", "index.spark"), "Hello\r\n\tworld"); + var contents = Render("index"); + Assert.That(contents, Is.EqualTo("Hello\r\n\tworld")); + } + + [Test] + public void CodeStatementChunks() + { + _viewFolder.Add(Path.Combine("vbhome", "index.spark"), @" +#Dim foo = 'hi there' +<%Dim bar = 'hello again'%> +${foo} ${bar}"); + + var contents = Render("index"); + Assert.That(contents.Trim(), Is.EqualTo("hi there hello again")); + } + + [Test] + public void GlobalVariableChunks() + { + _viewFolder.Add(Path.Combine("vbhome", "index.spark"), @" + +${foo} ${bar} +#bar='there' +${bar} +"); + + var contents = Render("index"); + Assert.That(contents.Trim(), Is.EqualTo("5 hello\r\nthere")); + } + + [Test] + public void TypedGlobalVariableChunks() + { + _viewFolder.Add(Path.Combine("vbhome", "index.spark"), @" + +${bar} ${bar.Length} +"); + + var contents = Render("index"); + Assert.That(contents.Trim(), Is.EqualTo("hello 5")); + } + + [Test] + public void LocalVariableChunks() + { + _viewFolder.Add(Path.Combine("vbhome", "index.spark"), @" + + +${foo} ${bar} ${bar.Length} +"); + + var contents = Render("index"); + Assert.That(contents.Trim(), Is.EqualTo("5 hello 5")); + } + + [Test] + public void DefaultValuesDontCollideWithExistingLocals() + { + _viewFolder.Add(Path.Combine("vbhome", "index.spark"), @" + + + + +

    ok1

    +fail + + + +

    ok2

    + fail +
    +
    + +"); + var contents = Render("index"); + + Assert.That(contents, Does.Contain("ok1")); + Assert.That(contents, Does.Contain("ok2")); + Assert.That(contents, Does.Not.Contains("fail")); + } + + [Test] + public void DefaultValuesDontReplaceGlobals() + { + _viewFolder.Add(Path.Combine("vbhome", "index.spark"), @" + + +

    ok1

    +fail + + +

    ok2

    + fail +
    + + + +"); + var contents = Render("index"); + + Assert.That(contents, Does.Contain("ok1")); + Assert.That(contents, Does.Contain("ok2")); + Assert.That(contents, Does.Not.Contains("fail")); + } + + + [Test] + public void DefaultValuesDontReplaceViewData() + { + _viewFolder.Add(Path.Combine("vbhome", "index.spark"), @" + + +

    ok1

    +fail + + +

    ok2

    + fail +
    + + + +"); + var contents = Render("index", new StubViewData { { "x1", 5 }, { "x2", 5 } }); + + Assert.That(contents, Does.Contain("ok1")); + Assert.That(contents, Does.Contain("ok2")); + Assert.That(contents, Does.Not.Contains("fail")); + } + + + [Test] + public void DefaultValuesActAsLocal() + { + _viewFolder.Add(Path.Combine("vbhome", "index.spark"), @" + + +

    ok1

    +fail + + +

    ok2

    + fail +
    + +"); + var contents = Render("index"); + + Assert.That(contents, Does.Contain("ok1")); + Assert.That(contents, Does.Contain("ok2")); + Assert.That(contents, Does.Not.Contains("fail")); + } + + [Test] + public void DefaultValuesStandInForNullViewData() + { + _viewFolder.Add(Path.Combine("vbhome", "index.spark"), @" +

    ok1

    +fail + + +

    ok2

    + fail +
    + + + + + +"); + var contents = Render("index"); + + Assert.That(contents, Does.Contain("ok1")); + Assert.That(contents, Does.Contain("ok2")); + Assert.That(contents, Does.Not.Contains("fail")); + } + + [Test] + public void ViewDataChunks() + { + _viewFolder.Add(Path.Combine("vbhome", "index.spark"), @" + +${x1} ${x2} +"); + var contents = Render("index", new StubViewData { { "x1", 4 }, { "x2", "hello" } }); + Assert.That(contents.Trim(), Is.EqualTo("4 hello")); + } + + [Test] + public void ViewDataModelChunk() + { + + _viewFolder.Add(Path.Combine("vbhome", "index.spark"), @" + +${Comment.Text} +"); + var comment = new Comment { Text = "hello world" }; + var contents = Render("index", new StubViewData { Model = comment }); + Assert.That(contents.Trim(), Is.EqualTo("hello world")); + } + + [Test] + public void AssignChunk() + { + _viewFolder.Add(Path.Combine("vbhome", "index.spark"), @" +#Dim x = 4 + +${x} +"); + var contents = Render("index"); + Assert.That(contents.Trim(), Is.EqualTo("5")); + } + + [Test] + public void ContentNameAndUseContentChunk() + { + _viewFolder.Add(Path.Combine("vbhome", "index.spark"), @" +bar +[] +"); + var contents = Render("index"); + Assert.That(contents.Trim(), Is.EqualTo("[bar]")); + } + + [Test] + public void RenderPartialChunk() + { + _viewFolder.Add(Path.Combine("vbhome", "index.spark"), @"[]"); + _viewFolder.Add(Path.Combine("shared", "_foo.spark"), @"bar"); + + var contents = Render("index"); + Assert.That(contents.Trim(), Is.EqualTo("[bar]")); + } + + [Test] + public void ContentVarChunk() + { + _viewFolder.Add(Path.Combine("vbhome", "index.spark"), @" +bar +[${foo}] +"); + + var contents = Render("index"); + Assert.That(contents.Trim(), Is.EqualTo("[bar]")); + } + + [Test] + public void ContentSetChunk() + { + _viewFolder.Add(Path.Combine("vbhome", "index.spark"), @" + +fred +bar +quad +[${foo}] +"); + + var contents = Render("index"); + Assert.That(contents.Trim(), Is.EqualTo("[barfredquad]")); + } + + [Test] + public void ConditionalAttributes() + { + _viewFolder.Add(Path.Combine("vbhome", "index.spark"), @" + + + + + + + + +"); + + var contents = Render("index"); + Assert.That(contents.Trim(), Is.EqualTo(@" + + + + + + + + +")); + } + + [Test] + public void MacroChunks() + { + _viewFolder.Add(Path.Combine("vbhome", "index.spark"), @" +bar +bar2${quux}bar3 +${foo2('alpha')} ${foo} +"); + + var contents = Render("index"); + Assert.That(contents.Trim(), Is.EqualTo("bar2alphabar3 bar")); + } + } +} diff --git a/src/Spark/AbstractSparkView.cs b/src/Spark.Web/AbstractSparkView.cs similarity index 88% rename from src/Spark/AbstractSparkView.cs rename to src/Spark.Web/AbstractSparkView.cs index f08ae462..1345b441 100644 --- a/src/Spark/AbstractSparkView.cs +++ b/src/Spark.Web/AbstractSparkView.cs @@ -1,34 +1,30 @@ -// Copyright 2008-2009 Louis DeJardin - http://whereslou.com -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// -using System; -using System.Collections.Generic; -using System.IO; -using Spark.Spool; - -namespace Spark -{ - public abstract class AbstractSparkView : SparkViewDecorator - { - protected AbstractSparkView() - : this(null) - { - } - protected AbstractSparkView(SparkViewBase decorated) - : base(decorated) - { - } - - } -} +// Copyright 2008-2009 Louis DeJardin - http://whereslou.com +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +namespace Spark +{ + public abstract class AbstractSparkView : SparkViewDecorator + { + protected AbstractSparkView() + : this(null) + { + } + protected AbstractSparkView(SparkViewBase decorated) + : base(decorated) + { + } + + } +} diff --git a/src/Spark/CacheExpires.cs b/src/Spark.Web/CacheExpires.cs similarity index 96% rename from src/Spark/CacheExpires.cs rename to src/Spark.Web/CacheExpires.cs index c62d2645..ba91cbca 100644 --- a/src/Spark/CacheExpires.cs +++ b/src/Spark.Web/CacheExpires.cs @@ -1,39 +1,39 @@ -using System; - -namespace Spark -{ - public class CacheExpires - { - private static CacheExpires _empty = new CacheExpires(); - - public CacheExpires() - { - Absolute = NoAbsoluteExpiration; - Sliding = NoSlidingExpiration; - } - - public CacheExpires(DateTime absolute) - { - Absolute = absolute; - Sliding = NoSlidingExpiration; - } - - public CacheExpires(TimeSpan sliding) - { - Absolute = NoAbsoluteExpiration; - Sliding = sliding; - } - - public CacheExpires(double sliding) - : this(TimeSpan.FromSeconds(sliding)) - { - } - - public DateTime Absolute { get; set; } - public TimeSpan Sliding { get; set; } - - public static DateTime NoAbsoluteExpiration { get { return System.Web.Caching.Cache.NoAbsoluteExpiration; } } - public static TimeSpan NoSlidingExpiration { get { return System.Web.Caching.Cache.NoSlidingExpiration; } } - public static CacheExpires Empty { get { return _empty; } } - } +using System; + +namespace Spark +{ + public class CacheExpires + { + private static CacheExpires _empty = new CacheExpires(); + + public CacheExpires() + { + Absolute = NoAbsoluteExpiration; + Sliding = NoSlidingExpiration; + } + + public CacheExpires(DateTime absolute) + { + Absolute = absolute; + Sliding = NoSlidingExpiration; + } + + public CacheExpires(TimeSpan sliding) + { + Absolute = NoAbsoluteExpiration; + Sliding = sliding; + } + + public CacheExpires(double sliding) + : this(TimeSpan.FromSeconds(sliding)) + { + } + + public DateTime Absolute { get; set; } + public TimeSpan Sliding { get; set; } + + public static DateTime NoAbsoluteExpiration { get { return System.Web.Caching.Cache.NoAbsoluteExpiration; } } + public static TimeSpan NoSlidingExpiration { get { return System.Web.Caching.Cache.NoSlidingExpiration; } } + public static CacheExpires Empty { get { return _empty; } } + } } \ No newline at end of file diff --git a/src/Spark/CacheSignal.cs b/src/Spark.Web/CacheSignal.cs similarity index 96% rename from src/Spark/CacheSignal.cs rename to src/Spark.Web/CacheSignal.cs index 7ac3a54e..5e00d3ab 100644 --- a/src/Spark/CacheSignal.cs +++ b/src/Spark.Web/CacheSignal.cs @@ -1,76 +1,76 @@ -using System; - -namespace Spark -{ - public class CacheSignal : ICacheSignal - { - private EventHandler _changed; - private bool _enabled; - - /// - /// Changed event calls Enable and Disable when - /// any handlers are added and all handlers are - /// removed respectively. - /// - public event EventHandler Changed - { - add - { - lock (this) - { - _changed += value; - if (_enabled) - return; - - Enable(); - _enabled = true; - } - } - remove - { - lock (this) - { - _changed -= value; - if (_enabled != true || ChangedIsEmpty() == false) - return; - - Disable(); - _enabled = false; - } - } - } - - private bool ChangedIsEmpty() - { - return _changed == null || - _changed.GetInvocationList().Length == 0; - } - - /// - /// Optionally implemented by descendant to wire up the infrastructure - /// to produce Changed events. That infrastructure is expected - /// to call FireChanged. - /// - protected virtual void Enable() - { - } - - /// - /// Optionally implemented by descendant to tear down listening infrastructure - /// when no cache dependencies remain listenning to the signal. - /// - protected virtual void Disable() - { - } - - /// - /// Called externally or from a descendant class to signal cache entries - /// connected to this signal should all be removed - /// - public void FireChanged() - { - if (_changed != null) - _changed(this, EventArgs.Empty); - } - } -} +using System; + +namespace Spark +{ + public class CacheSignal : ICacheSignal + { + private EventHandler _changed; + private bool _enabled; + + /// + /// Changed event calls Enable and Disable when + /// any handlers are added and all handlers are + /// removed respectively. + /// + public event EventHandler Changed + { + add + { + lock (this) + { + _changed += value; + if (_enabled) + return; + + Enable(); + _enabled = true; + } + } + remove + { + lock (this) + { + _changed -= value; + if (_enabled != true || ChangedIsEmpty() == false) + return; + + Disable(); + _enabled = false; + } + } + } + + private bool ChangedIsEmpty() + { + return _changed == null || + _changed.GetInvocationList().Length == 0; + } + + /// + /// Optionally implemented by descendant to wire up the infrastructure + /// to produce Changed events. That infrastructure is expected + /// to call FireChanged. + /// + protected virtual void Enable() + { + } + + /// + /// Optionally implemented by descendant to tear down listening infrastructure + /// when no cache dependencies remain listenning to the signal. + /// + protected virtual void Disable() + { + } + + /// + /// Called externally or from a descendant class to signal cache entries + /// connected to this signal should all be removed + /// + public void FireChanged() + { + if (_changed != null) + _changed(this, EventArgs.Empty); + } + } +} diff --git a/src/Spark/Caching/CacheMemento.cs b/src/Spark.Web/Caching/CacheMemento.cs similarity index 96% rename from src/Spark/Caching/CacheMemento.cs rename to src/Spark.Web/Caching/CacheMemento.cs index eb5385cc..18c92a74 100644 --- a/src/Spark/Caching/CacheMemento.cs +++ b/src/Spark.Web/Caching/CacheMemento.cs @@ -1,19 +1,19 @@ -using System; -using System.Collections.Generic; -using Spark.Spool; - -namespace Spark.Caching -{ - public class CacheMemento - { - public CacheMemento() - { - Content = new Dictionary(); - OnceTable = new Dictionary(); - } - - public SpoolWriter SpoolOutput { get; set; } - public Dictionary Content { get; set;} - public Dictionary OnceTable { get; set; } - } -} +using System; +using System.Collections.Generic; +using Spark.Spool; + +namespace Spark.Caching +{ + public class CacheMemento + { + public CacheMemento() + { + Content = new Dictionary(); + OnceTable = new Dictionary(); + } + + public SpoolWriter SpoolOutput { get; set; } + public Dictionary Content { get; set;} + public Dictionary OnceTable { get; set; } + } +} diff --git a/src/Spark/Caching/CacheOriginator.cs b/src/Spark.Web/Caching/CacheOriginator.cs similarity index 97% rename from src/Spark/Caching/CacheOriginator.cs rename to src/Spark.Web/Caching/CacheOriginator.cs index e9f3a74e..c0b1511d 100644 --- a/src/Spark/Caching/CacheOriginator.cs +++ b/src/Spark.Web/Caching/CacheOriginator.cs @@ -1,116 +1,116 @@ -using System.Collections.Generic; -using System.IO; -using System.Linq; -using Spark.Spool; - -namespace Spark.Caching -{ - public class CacheOriginator - { - private readonly SparkViewContext _state; - - private TextWriter _priorOutput; - private SpoolWriter _spoolOutput; - - private readonly Dictionary _priorContent = new Dictionary(); - private Dictionary _priorOnceTable; - - public CacheOriginator(SparkViewContext state) - { - _state = state; - } - - /// - /// Establishes original state for memento capturing purposes - /// - public void BeginMemento() - { - foreach (var content in _state.Content) - { - var writerOriginator = TextWriterOriginator.Create(content.Value); - _priorContent.Add(content.Key, writerOriginator); - writerOriginator.BeginMemento(); - } - - _priorOnceTable = _state.OnceTable.ToDictionary(kv=>kv.Key, kv=>kv.Value); - - // capture current output also if it's not locked into a named output at the moment - // this could be a case in view's output, direct to network, or various macro or content captures - if (_state.Content.Any(kv => ReferenceEquals(kv.Value, _state.Output)) == false) - { - _priorOutput = _state.Output; - _spoolOutput = new SpoolWriter(); - _state.Output = _spoolOutput; - } - } - - /// - /// Finalizes state change and creates memento - /// - /// memento holding the details of the resulting state delta - public CacheMemento EndMemento() - { - var memento = new CacheMemento(); - - // for capturing subject.Output directly, replay what was spooled, and save it - // in the memento - if (_priorOutput != null) - { - _spoolOutput.WriteTo(_priorOutput); - _state.Output = _priorOutput; - memento.SpoolOutput = _spoolOutput; - } - - // save any deltas on named content that have expanded - foreach (var content in _priorContent) - { - var textMemento = content.Value.EndMemento(); - if (textMemento.Written.Any(part=>string.IsNullOrEmpty(part) == false)) - memento.Content.Add(content.Key, textMemento); - } - - // also save any named content in it's entirety that added created after BeginMemento was called - foreach (var content in _state.Content.Where(kv => _priorContent.ContainsKey(kv.Key) == false)) - { - var originator = TextWriterOriginator.Create(content.Value); - memento.Content.Add(content.Key, originator.CreateMemento()); - } - - // capture anything from the oncetable that was added after BeginMemento was called - var newItems = _state.OnceTable.Where(once => _priorOnceTable.ContainsKey(once.Key) == false); - memento.OnceTable = newItems.ToDictionary(once => once.Key, once => once.Value); - return memento; - } - - /// - /// Applies previously captured state delta to view, effectively replaying cached fragment - /// - /// memento captured in previous begin/end calls - public void DoMemento(CacheMemento memento) - { - memento.SpoolOutput.WriteTo(_state.Output); - - foreach (var content in memento.Content) - { - // create named content if it doesn't exist - TextWriter writer; - if (_state.Content.TryGetValue(content.Key, out writer) == false) - { - writer = new SpoolWriter(); - _state.Content.Add(content.Key, writer); - } - - // and in any case apply the delta - var originator = TextWriterOriginator.Create(writer); - originator.DoMemento(content.Value); - } - - // add recorded once deltas that were not yet in this subject's table - var newItems = memento.OnceTable.Where(once => _state.OnceTable.ContainsKey(once.Key) == false); - foreach (var once in newItems) - { - _state.OnceTable.Add(once.Key, once.Value); - } - } - } -} +using System.Collections.Generic; +using System.IO; +using System.Linq; +using Spark.Spool; + +namespace Spark.Caching +{ + public class CacheOriginator + { + private readonly SparkViewContext _state; + + private TextWriter _priorOutput; + private SpoolWriter _spoolOutput; + + private readonly Dictionary _priorContent = new Dictionary(); + private Dictionary _priorOnceTable; + + public CacheOriginator(SparkViewContext state) + { + _state = state; + } + + /// + /// Establishes original state for memento capturing purposes + /// + public void BeginMemento() + { + foreach (var content in _state.Content) + { + var writerOriginator = TextWriterOriginator.Create(content.Value); + _priorContent.Add(content.Key, writerOriginator); + writerOriginator.BeginMemento(); + } + + _priorOnceTable = _state.OnceTable.ToDictionary(kv=>kv.Key, kv=>kv.Value); + + // capture current output also if it's not locked into a named output at the moment + // this could be a case in view's output, direct to network, or various macro or content captures + if (_state.Content.Any(kv => ReferenceEquals(kv.Value, _state.Output)) == false) + { + _priorOutput = _state.Output; + _spoolOutput = new SpoolWriter(); + _state.Output = _spoolOutput; + } + } + + /// + /// Finalizes state change and creates memento + /// + /// memento holding the details of the resulting state delta + public CacheMemento EndMemento() + { + var memento = new CacheMemento(); + + // for capturing subject.Output directly, replay what was spooled, and save it + // in the memento + if (_priorOutput != null) + { + _spoolOutput.WriteTo(_priorOutput); + _state.Output = _priorOutput; + memento.SpoolOutput = _spoolOutput; + } + + // save any deltas on named content that have expanded + foreach (var content in _priorContent) + { + var textMemento = content.Value.EndMemento(); + if (textMemento.Written.Any(part=>string.IsNullOrEmpty(part) == false)) + memento.Content.Add(content.Key, textMemento); + } + + // also save any named content in it's entirety that added created after BeginMemento was called + foreach (var content in _state.Content.Where(kv => _priorContent.ContainsKey(kv.Key) == false)) + { + var originator = TextWriterOriginator.Create(content.Value); + memento.Content.Add(content.Key, originator.CreateMemento()); + } + + // capture anything from the oncetable that was added after BeginMemento was called + var newItems = _state.OnceTable.Where(once => _priorOnceTable.ContainsKey(once.Key) == false); + memento.OnceTable = newItems.ToDictionary(once => once.Key, once => once.Value); + return memento; + } + + /// + /// Applies previously captured state delta to view, effectively replaying cached fragment + /// + /// memento captured in previous begin/end calls + public void DoMemento(CacheMemento memento) + { + memento.SpoolOutput.WriteTo(_state.Output); + + foreach (var content in memento.Content) + { + // create named content if it doesn't exist + TextWriter writer; + if (_state.Content.TryGetValue(content.Key, out writer) == false) + { + writer = new SpoolWriter(); + _state.Content.Add(content.Key, writer); + } + + // and in any case apply the delta + var originator = TextWriterOriginator.Create(writer); + originator.DoMemento(content.Value); + } + + // add recorded once deltas that were not yet in this subject's table + var newItems = memento.OnceTable.Where(once => _state.OnceTable.ContainsKey(once.Key) == false); + foreach (var once in newItems) + { + _state.OnceTable.Add(once.Key, once.Value); + } + } + } +} diff --git a/src/Spark/Caching/DefaultCacheService.cs b/src/Spark.Web/Caching/DefaultCacheService.cs similarity index 96% rename from src/Spark/Caching/DefaultCacheService.cs rename to src/Spark.Web/Caching/DefaultCacheService.cs index f0359de3..e692259d 100644 --- a/src/Spark/Caching/DefaultCacheService.cs +++ b/src/Spark.Web/Caching/DefaultCacheService.cs @@ -1,66 +1,66 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Web.Caching; - -namespace Spark.Caching -{ - public class DefaultCacheService : ICacheService - { - private readonly Cache _cache; - - public DefaultCacheService(Cache cache) - { - _cache = cache; - } - - public object Get(string identifier) - { - return _cache.Get(identifier); - } - - public void Store(string identifier, CacheExpires expires, ICacheSignal signal, object item) - { - _cache.Insert( - identifier, - item, - SignalDependency.For(signal), - (expires ?? CacheExpires.Empty).Absolute, - (expires ?? CacheExpires.Empty).Sliding); - } - - class SignalDependency : CacheDependency - { - private readonly ICacheSignal _signal; - - SignalDependency(ICacheSignal signal) - { - _signal = signal; - _signal.Changed += SignalChanged; - } - - ~SignalDependency() - { - _signal.Changed -= SignalChanged; - } - - public static CacheDependency For(ICacheSignal signal) - { - return signal == null ? null : new SignalDependency(signal); - } - - void SignalChanged(object sender, EventArgs e) - { - NotifyDependencyChanged(this, e); - } - - protected override void DependencyDispose() - { - _signal.Changed -= SignalChanged; - } - } - - } - -} +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Web.Caching; + +namespace Spark.Caching +{ + public class DefaultCacheService : ICacheService + { + private readonly Cache _cache; + + public DefaultCacheService(Cache cache) + { + _cache = cache; + } + + public object Get(string identifier) + { + return _cache.Get(identifier); + } + + public void Store(string identifier, CacheExpires expires, ICacheSignal signal, object item) + { + _cache.Insert( + identifier, + item, + SignalDependency.For(signal), + (expires ?? CacheExpires.Empty).Absolute, + (expires ?? CacheExpires.Empty).Sliding); + } + + class SignalDependency : CacheDependency + { + private readonly ICacheSignal _signal; + + SignalDependency(ICacheSignal signal) + { + _signal = signal; + _signal.Changed += SignalChanged; + } + + ~SignalDependency() + { + _signal.Changed -= SignalChanged; + } + + public static CacheDependency For(ICacheSignal signal) + { + return signal == null ? null : new SignalDependency(signal); + } + + void SignalChanged(object sender, EventArgs e) + { + NotifyDependencyChanged(this, e); + } + + protected override void DependencyDispose() + { + _signal.Changed -= SignalChanged; + } + } + + } + +} diff --git a/src/Spark/Caching/SpoolWriterOriginator.cs b/src/Spark.Web/Caching/SpoolWriterOriginator.cs similarity index 96% rename from src/Spark/Caching/SpoolWriterOriginator.cs rename to src/Spark.Web/Caching/SpoolWriterOriginator.cs index 5bab6278..f2055cfb 100644 --- a/src/Spark/Caching/SpoolWriterOriginator.cs +++ b/src/Spark.Web/Caching/SpoolWriterOriginator.cs @@ -1,38 +1,38 @@ -using System; -using System.Linq; -using Spark.Spool; - -namespace Spark.Caching -{ - public class SpoolWriterOriginator : TextWriterOriginator - { - private readonly SpoolWriter _writer; - private int _priorStringCount; - - public SpoolWriterOriginator(SpoolWriter writer) - { - _writer = writer; - } - - public override TextWriterMemento CreateMemento() - { - return new TextWriterMemento { Written = _writer.ToArray() }; - } - - public override void BeginMemento() - { - _priorStringCount = _writer.Count(); - } - - public override TextWriterMemento EndMemento() - { - return new TextWriterMemento { Written = _writer.Skip(_priorStringCount).ToArray() }; - } - - public override void DoMemento(TextWriterMemento memento) - { - foreach (var written in memento.Written) - _writer.Write(written); - } - } +using System; +using System.Linq; +using Spark.Spool; + +namespace Spark.Caching +{ + public class SpoolWriterOriginator : TextWriterOriginator + { + private readonly SpoolWriter _writer; + private int _priorStringCount; + + public SpoolWriterOriginator(SpoolWriter writer) + { + _writer = writer; + } + + public override TextWriterMemento CreateMemento() + { + return new TextWriterMemento { Written = _writer.ToArray() }; + } + + public override void BeginMemento() + { + _priorStringCount = _writer.Count(); + } + + public override TextWriterMemento EndMemento() + { + return new TextWriterMemento { Written = _writer.Skip(_priorStringCount).ToArray() }; + } + + public override void DoMemento(TextWriterMemento memento) + { + foreach (var written in memento.Written) + _writer.Write(written); + } + } } \ No newline at end of file diff --git a/src/Spark/Caching/StringWriterOriginator.cs b/src/Spark.Web/Caching/StringWriterOriginator.cs similarity index 96% rename from src/Spark/Caching/StringWriterOriginator.cs rename to src/Spark.Web/Caching/StringWriterOriginator.cs index e81c39a9..421d0ce3 100644 --- a/src/Spark/Caching/StringWriterOriginator.cs +++ b/src/Spark.Web/Caching/StringWriterOriginator.cs @@ -1,39 +1,39 @@ -using System; -using System.IO; - -namespace Spark.Caching -{ - public class StringWriterOriginator : TextWriterOriginator - { - private readonly StringWriter _writer; - private int _priorLength; - - public StringWriterOriginator(StringWriter writer) - { - _writer = writer; - } - - public override TextWriterMemento CreateMemento() - { - return new TextWriterMemento {Written = new[] {_writer.ToString()}}; - } - - public override void BeginMemento() - { - _priorLength = _writer.GetStringBuilder().Length; - } - - public override TextWriterMemento EndMemento() - { - var currentLength = _writer.GetStringBuilder().Length; - var written = _writer.GetStringBuilder().ToString(_priorLength, currentLength - _priorLength); - return new TextWriterMemento { Written = new[] { written } }; - } - - public override void DoMemento(TextWriterMemento memento) - { - foreach(var written in memento.Written) - _writer.Write(written); - } - } -} +using System; +using System.IO; + +namespace Spark.Caching +{ + public class StringWriterOriginator : TextWriterOriginator + { + private readonly StringWriter _writer; + private int _priorLength; + + public StringWriterOriginator(StringWriter writer) + { + _writer = writer; + } + + public override TextWriterMemento CreateMemento() + { + return new TextWriterMemento {Written = new[] {_writer.ToString()}}; + } + + public override void BeginMemento() + { + _priorLength = _writer.GetStringBuilder().Length; + } + + public override TextWriterMemento EndMemento() + { + var currentLength = _writer.GetStringBuilder().Length; + var written = _writer.GetStringBuilder().ToString(_priorLength, currentLength - _priorLength); + return new TextWriterMemento { Written = new[] { written } }; + } + + public override void DoMemento(TextWriterMemento memento) + { + foreach(var written in memento.Written) + _writer.Write(written); + } + } +} diff --git a/src/Spark/Caching/TextWriterOriginator.cs b/src/Spark.Web/Caching/TextWriterOriginator.cs similarity index 96% rename from src/Spark/Caching/TextWriterOriginator.cs rename to src/Spark.Web/Caching/TextWriterOriginator.cs index 76ab4b20..b9885705 100644 --- a/src/Spark/Caching/TextWriterOriginator.cs +++ b/src/Spark.Web/Caching/TextWriterOriginator.cs @@ -1,30 +1,30 @@ -using System; -using System.Collections.Generic; -using System.IO; -using Spark.Spool; - -namespace Spark.Caching -{ - public abstract class TextWriterOriginator - { - public static TextWriterOriginator Create(TextWriter writer) - { - if (writer is SpoolWriter) - return new SpoolWriterOriginator((SpoolWriter) writer); - if (writer is StringWriter) - return new StringWriterOriginator((StringWriter)writer); - throw new InvalidCastException("writer is unknown type " + writer.GetType().FullName); - } - - public abstract TextWriterMemento CreateMemento(); - public abstract void BeginMemento(); - public abstract TextWriterMemento EndMemento(); - - public abstract void DoMemento(TextWriterMemento memento); - } - - public class TextWriterMemento - { - public IEnumerable Written { get; set; } - } +using System; +using System.Collections.Generic; +using System.IO; +using Spark.Spool; + +namespace Spark.Caching +{ + public abstract class TextWriterOriginator + { + public static TextWriterOriginator Create(TextWriter writer) + { + if (writer is SpoolWriter) + return new SpoolWriterOriginator((SpoolWriter) writer); + if (writer is StringWriter) + return new StringWriterOriginator((StringWriter)writer); + throw new InvalidCastException("writer is unknown type " + writer.GetType().FullName); + } + + public abstract TextWriterMemento CreateMemento(); + public abstract void BeginMemento(); + public abstract TextWriterMemento EndMemento(); + + public abstract void DoMemento(TextWriterMemento memento); + } + + public class TextWriterMemento + { + public IEnumerable Written { get; set; } + } } \ No newline at end of file diff --git a/src/Spark/Configuration/AssemblyElement.cs b/src/Spark.Web/Configuration/AssemblyElement.cs similarity index 87% rename from src/Spark/Configuration/AssemblyElement.cs rename to src/Spark.Web/Configuration/AssemblyElement.cs index 2c390343..a7333c5a 100644 --- a/src/Spark/Configuration/AssemblyElement.cs +++ b/src/Spark.Web/Configuration/AssemblyElement.cs @@ -1,28 +1,28 @@ -// Copyright 2008-2009 Louis DeJardin - http://whereslou.com -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// -using System.Configuration; - -namespace Spark.Configuration -{ - public class AssemblyElement : ConfigurationElement - { - [ConfigurationProperty("assembly")] - public string Assembly - { - get { return (string)this["assembly"]; } - set { this["assembly"] = value; } - } - } +// Copyright 2008-2009 Louis DeJardin - http://whereslou.com +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +using System.Configuration; + +namespace Spark.Configuration +{ + public class AssemblyElement : ConfigurationElement + { + [ConfigurationProperty("assembly")] + public string Assembly + { + get => (string)this["assembly"]; + set => this["assembly"] = value; + } + } } \ No newline at end of file diff --git a/src/Spark/Configuration/AssemblyElementCollection.cs b/src/Spark.Web/Configuration/AssemblyElementCollection.cs similarity index 97% rename from src/Spark/Configuration/AssemblyElementCollection.cs rename to src/Spark.Web/Configuration/AssemblyElementCollection.cs index 2542a7f5..9f1a1873 100644 --- a/src/Spark/Configuration/AssemblyElementCollection.cs +++ b/src/Spark.Web/Configuration/AssemblyElementCollection.cs @@ -1,36 +1,36 @@ -// Copyright 2008-2009 Louis DeJardin - http://whereslou.com -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// -using System.Configuration; - -namespace Spark.Configuration -{ - public class AssemblyElementCollection : ConfigurationElementCollection - { - protected override ConfigurationElement CreateNewElement() - { - return new AssemblyElement(); - } - - protected override object GetElementKey(ConfigurationElement element) - { - return ((AssemblyElement)element).Assembly; - } - - public void Add(string assembly) - { - BaseAdd(new AssemblyElement { Assembly = assembly }); - } - } +// Copyright 2008-2009 Louis DeJardin - http://whereslou.com +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +using System.Configuration; + +namespace Spark.Configuration +{ + public class AssemblyElementCollection : ConfigurationElementCollection + { + protected override ConfigurationElement CreateNewElement() + { + return new AssemblyElement(); + } + + protected override object GetElementKey(ConfigurationElement element) + { + return ((AssemblyElement)element).Assembly; + } + + public void Add(string assembly) + { + BaseAdd(new AssemblyElement { Assembly = assembly }); + } + } } \ No newline at end of file diff --git a/src/Spark/Configuration/CompilationElement.cs b/src/Spark.Web/Configuration/CompilationElement.cs similarity index 69% rename from src/Spark/Configuration/CompilationElement.cs rename to src/Spark.Web/Configuration/CompilationElement.cs index 810584d7..7a75cd24 100644 --- a/src/Spark/Configuration/CompilationElement.cs +++ b/src/Spark.Web/Configuration/CompilationElement.cs @@ -1,58 +1,57 @@ -// Copyright 2008-2009 Louis DeJardin - http://whereslou.com -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// -using System; -using System.Configuration; - -namespace Spark.Configuration -{ - public class CompilationElement : ConfigurationElement - { - [ConfigurationProperty("debug")] - public bool Debug - { - get { return (bool)this["debug"]; } - set { this["debug"] = value; } - } - - [ConfigurationProperty("nullBehaviour", DefaultValue = NullBehaviour.Lenient)] - public NullBehaviour NullBehaviour - { - get { return (NullBehaviour)this["nullBehaviour"]; } - set { this["nullBehaviour"] = value; } - } - - [ConfigurationProperty("attributeBehaviour", DefaultValue = AttributeBehaviour.CodeOriented)] - public AttributeBehaviour AttributeBehaviour - { - get { return (AttributeBehaviour)this["attributeBehaviour"]; } - set { this["attributeBehaviour"] = value; } - } - - [ConfigurationProperty("defaultLanguage", DefaultValue = LanguageType.Default)] - public LanguageType DefaultLanguage - { - get { return (LanguageType)this["defaultLanguage"]; } - set { this["defaultLanguage"] = value; } - } - - [ConfigurationProperty("assemblies")] - [ConfigurationCollection(typeof(AssemblyElementCollection))] - public AssemblyElementCollection Assemblies - { - get { return (AssemblyElementCollection)this["assemblies"]; } - set { this["assemblies"] = value; } - } - } -} +// Copyright 2008-2009 Louis DeJardin - http://whereslou.com +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +using System.Configuration; + +namespace Spark.Configuration +{ + public class CompilationElement : ConfigurationElement + { + [ConfigurationProperty("debug")] + public bool Debug + { + get => (bool)this["debug"]; + set => this["debug"] = value; + } + + [ConfigurationProperty("nullBehaviour", DefaultValue = NullBehaviour.Lenient)] + public NullBehaviour NullBehaviour + { + get => (NullBehaviour)this["nullBehaviour"]; + set => this["nullBehaviour"] = value; + } + + [ConfigurationProperty("attributeBehaviour", DefaultValue = AttributeBehaviour.CodeOriented)] + public AttributeBehaviour AttributeBehaviour + { + get => (AttributeBehaviour)this["attributeBehaviour"]; + set => this["attributeBehaviour"] = value; + } + + [ConfigurationProperty("defaultLanguage", DefaultValue = LanguageType.Default)] + public LanguageType DefaultLanguage + { + get => (LanguageType)this["defaultLanguage"]; + set => this["defaultLanguage"] = value; + } + + [ConfigurationProperty("assemblies")] + [ConfigurationCollection(typeof(AssemblyElementCollection))] + public AssemblyElementCollection Assemblies + { + get => (AssemblyElementCollection)this["assemblies"]; + set => this["assemblies"] = value; + } + } +} diff --git a/src/Spark/Configuration/NamespaceElement.cs b/src/Spark.Web/Configuration/NamespaceElement.cs similarity index 86% rename from src/Spark/Configuration/NamespaceElement.cs rename to src/Spark.Web/Configuration/NamespaceElement.cs index f0434643..3e06fd11 100644 --- a/src/Spark/Configuration/NamespaceElement.cs +++ b/src/Spark.Web/Configuration/NamespaceElement.cs @@ -1,28 +1,28 @@ -// Copyright 2008-2009 Louis DeJardin - http://whereslou.com -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// -using System.Configuration; - -namespace Spark.Configuration -{ - public class NamespaceElement : ConfigurationElement - { - [ConfigurationProperty("namespace")] - public string Namespace - { - get { return (string)this["namespace"]; } - set { this["namespace"] = value; } - } - } +// Copyright 2008-2009 Louis DeJardin - http://whereslou.com +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +using System.Configuration; + +namespace Spark.Configuration +{ + public class NamespaceElement : ConfigurationElement + { + [ConfigurationProperty("namespace")] + public string Namespace + { + get => (string)this["namespace"]; + set => this["namespace"] = value; + } + } } \ No newline at end of file diff --git a/src/Spark/Configuration/NamespaceElementCollection.cs b/src/Spark.Web/Configuration/NamespaceElementCollection.cs similarity index 97% rename from src/Spark/Configuration/NamespaceElementCollection.cs rename to src/Spark.Web/Configuration/NamespaceElementCollection.cs index cf9d2196..3a649c98 100644 --- a/src/Spark/Configuration/NamespaceElementCollection.cs +++ b/src/Spark.Web/Configuration/NamespaceElementCollection.cs @@ -1,36 +1,36 @@ -// Copyright 2008-2009 Louis DeJardin - http://whereslou.com -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// -using System.Configuration; - -namespace Spark.Configuration -{ - public class NamespaceElementCollection : ConfigurationElementCollection - { - protected override ConfigurationElement CreateNewElement() - { - return new NamespaceElement(); - } - - protected override object GetElementKey(ConfigurationElement element) - { - return ((NamespaceElement)element).Namespace; - } - - public void Add(string ns) - { - base.BaseAdd(new NamespaceElement { Namespace = ns }); - } - } +// Copyright 2008-2009 Louis DeJardin - http://whereslou.com +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +using System.Configuration; + +namespace Spark.Configuration +{ + public class NamespaceElementCollection : ConfigurationElementCollection + { + protected override ConfigurationElement CreateNewElement() + { + return new NamespaceElement(); + } + + protected override object GetElementKey(ConfigurationElement element) + { + return ((NamespaceElement)element).Namespace; + } + + public void Add(string ns) + { + base.BaseAdd(new NamespaceElement { Namespace = ns }); + } + } } \ No newline at end of file diff --git a/src/Spark/Configuration/PagesElement.cs b/src/Spark.Web/Configuration/PagesElement.cs similarity index 64% rename from src/Spark/Configuration/PagesElement.cs rename to src/Spark.Web/Configuration/PagesElement.cs index bad0186f..a343c2e3 100644 --- a/src/Spark/Configuration/PagesElement.cs +++ b/src/Spark.Web/Configuration/PagesElement.cs @@ -1,77 +1,73 @@ -// Copyright 2008-2009 Louis DeJardin - http://whereslou.com -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// -using System; -using System.Collections.Generic; -using System.Configuration; -using System.Linq; -using System.Text; -using Spark.Parser; - -namespace Spark.Configuration -{ - public class PagesElement : ConfigurationElement - { - [ConfigurationProperty("pageBaseType")] - public string PageBaseType - { - get { return (string)this["pageBaseType"]; } - set { this["pageBaseType"] = value; } - } - - [ConfigurationProperty("prefix")] - public string Prefix - { - get { return (string)this["prefix"]; } - set { this["prefix"] = value; } - } - - [ConfigurationProperty("automaticEncoding", DefaultValue = ParserSettings.DefaultAutomaticEncoding)] - public bool AutomaticEncoding - { - get { return (bool)this["automaticEncoding"]; } - set { this["automaticEncoding"] = value; } - } - - [ConfigurationProperty("statementMarker", DefaultValue = "#")] - public string StatementMarker - { - get { return (string)this["statementMarker"]; } - set { this["statementMarker"] = value; } - } - - [ConfigurationProperty("namespaces")] - [ConfigurationCollection(typeof(NamespaceElementCollection))] - public NamespaceElementCollection Namespaces - { - get { return (NamespaceElementCollection)this["namespaces"]; } - set { this["namespaces"] = value; } - } - - [ConfigurationProperty("resources")] - [ConfigurationCollection(typeof(ResourcePathElementCollection))] - public ResourcePathElementCollection Resources - { - get { return (ResourcePathElementCollection)this["resources"]; } - set { this["resources"] = value; } - } - - [ConfigurationProperty("parseSectionTagAsSegment")] - public bool ParseSectionTagAsSegment - { - get { return (bool)this["parseSectionTagAsSegment"]; } - set { this["parseSectionTagAsSegment"] = value; } - } - } -} +// Copyright 2008-2009 Louis DeJardin - http://whereslou.com +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +using System.Configuration; +using Spark.Parser; + +namespace Spark.Configuration +{ + public class PagesElement : ConfigurationElement + { + [ConfigurationProperty("pageBaseType")] + public string PageBaseType + { + get => (string)this["pageBaseType"]; + set => this["pageBaseType"] = value; + } + + [ConfigurationProperty("prefix")] + public string Prefix + { + get => (string)this["prefix"]; + set => this["prefix"] = value; + } + + [ConfigurationProperty("automaticEncoding", DefaultValue = ParserSettings.DefaultAutomaticEncoding)] + public bool AutomaticEncoding + { + get => (bool)this["automaticEncoding"]; + set => this["automaticEncoding"] = value; + } + + [ConfigurationProperty("statementMarker", DefaultValue = "#")] + public string StatementMarker + { + get => (string)this["statementMarker"]; + set => this["statementMarker"] = value; + } + + [ConfigurationProperty("namespaces")] + [ConfigurationCollection(typeof(NamespaceElementCollection))] + public NamespaceElementCollection Namespaces + { + get => (NamespaceElementCollection)this["namespaces"]; + set => this["namespaces"] = value; + } + + [ConfigurationProperty("resources")] + [ConfigurationCollection(typeof(ResourcePathElementCollection))] + public ResourcePathElementCollection Resources + { + get => (ResourcePathElementCollection)this["resources"]; + set => this["resources"] = value; + } + + [ConfigurationProperty("parseSectionTagAsSegment")] + public bool ParseSectionTagAsSegment + { + get => (bool)this["parseSectionTagAsSegment"]; + set => this["parseSectionTagAsSegment"] = value; + } + } +} diff --git a/src/Spark/Configuration/ResourcePathElement.cs b/src/Spark.Web/Configuration/ResourcePathElement.cs similarity index 76% rename from src/Spark/Configuration/ResourcePathElement.cs rename to src/Spark.Web/Configuration/ResourcePathElement.cs index 0f3bb571..065bbd13 100644 --- a/src/Spark/Configuration/ResourcePathElement.cs +++ b/src/Spark.Web/Configuration/ResourcePathElement.cs @@ -1,42 +1,42 @@ -// Copyright 2008-2009 Louis DeJardin - http://whereslou.com -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// -using System.Configuration; - -namespace Spark.Configuration -{ - public class ResourcePathElement : ConfigurationElement - { - [ConfigurationProperty("match")] - public string Match - { - get { return (string)this["match"]; } - set { this["match"] = value; } - } - - [ConfigurationProperty("location")] - public string Location - { - get { return (string)this["location"]; } - set { this["location"] = value; } - } - - [ConfigurationProperty("stop")] - public bool Stop - { - get { return (bool) this["stop"]; } - set { this["stop"] = value; } - } - } +// Copyright 2008-2009 Louis DeJardin - http://whereslou.com +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +using System.Configuration; + +namespace Spark.Configuration +{ + public class ResourcePathElement : ConfigurationElement + { + [ConfigurationProperty("match")] + public string Match + { + get => (string)this["match"]; + set => this["match"] = value; + } + + [ConfigurationProperty("location")] + public string Location + { + get => (string)this["location"]; + set => this["location"] = value; + } + + [ConfigurationProperty("stop")] + public bool Stop + { + get => (bool) this["stop"]; + set => this["stop"] = value; + } + } } \ No newline at end of file diff --git a/src/Spark/Configuration/ResourcePathElementCollection.cs b/src/Spark.Web/Configuration/ResourcePathElementCollection.cs similarity index 90% rename from src/Spark/Configuration/ResourcePathElementCollection.cs rename to src/Spark.Web/Configuration/ResourcePathElementCollection.cs index 8ee15940..c3fe4fa8 100644 --- a/src/Spark/Configuration/ResourcePathElementCollection.cs +++ b/src/Spark.Web/Configuration/ResourcePathElementCollection.cs @@ -1,40 +1,36 @@ -// Copyright 2008-2009 Louis DeJardin - http://whereslou.com -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// -using System; -using System.Collections.Generic; -using System.Configuration; -using System.Linq; -using System.Text; - -namespace Spark.Configuration -{ - public class ResourcePathElementCollection : ConfigurationElementCollection - { - protected override ConfigurationElement CreateNewElement() - { - return new ResourcePathElement(); - } - - protected override object GetElementKey(ConfigurationElement element) - { - return ((ResourcePathElement)element).Match; - } - - public void Add(string match, string location, bool stop) - { - base.BaseAdd(new ResourcePathElement { Match = match, Location = location, Stop = stop}); - } - } -} +// Copyright 2008-2009 Louis DeJardin - http://whereslou.com +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +using System.Configuration; + +namespace Spark.Configuration +{ + public class ResourcePathElementCollection : ConfigurationElementCollection + { + protected override ConfigurationElement CreateNewElement() + { + return new ResourcePathElement(); + } + + protected override object GetElementKey(ConfigurationElement element) + { + return ((ResourcePathElement)element).Match; + } + + public void Add(string match, string location, bool stop) + { + base.BaseAdd(new ResourcePathElement { Match = match, Location = location, Stop = stop}); + } + } +} diff --git a/src/Spark/Configuration/SparkSectionHandler.cs b/src/Spark.Web/Configuration/SparkSectionHandler.cs similarity index 67% rename from src/Spark/Configuration/SparkSectionHandler.cs rename to src/Spark.Web/Configuration/SparkSectionHandler.cs index e337f933..aeee8403 100644 --- a/src/Spark/Configuration/SparkSectionHandler.cs +++ b/src/Spark.Web/Configuration/SparkSectionHandler.cs @@ -1,172 +1,148 @@ -// Copyright 2008-2009 Louis DeJardin - http://whereslou.com -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// -using System; -using System.Collections.Generic; -using System.Configuration; -using System.Reflection; -using Spark.Parser; - -namespace Spark.Configuration -{ - public class SparkSectionHandler : ConfigurationSection, ISparkSettings - { - [ConfigurationProperty("xmlns")] - public string XmlNamespace - { - get { return (string)this["xmlns"]; } - set { this["xmlns"] = value; } - } - - [ConfigurationProperty("compilation")] - public CompilationElement Compilation - { - get { return (CompilationElement)this["compilation"]; } - set { this["compilation"] = value; } - } - - [ConfigurationProperty("pages")] - public PagesElement Pages - { - get { return (PagesElement)this["pages"]; } - set { this["pages"] = value; } - } - - [ConfigurationProperty("views")] - public ViewFolderElementCollection Views - { - get { return (ViewFolderElementCollection)this["views"]; } - set { this["views"] = value; } - } - - public SparkSectionHandler SetDebug(bool debug) - { - Compilation.Debug = debug; - return this; - } - - public SparkSectionHandler SetPageBaseType(string typeName) - { - Pages.PageBaseType = typeName; - return this; - } - - public SparkSectionHandler SetPageBaseType(Type type) - { - Pages.PageBaseType = type.FullName; - return this; - } - - public SparkSectionHandler AddAssembly(string assembly) - { - Compilation.Assemblies.Add(assembly); - return this; - } - - public SparkSectionHandler AddAssembly(Assembly assembly) - { - Compilation.Assemblies.Add(assembly.FullName); - return this; - } - - public SparkSectionHandler AddNamespace(string ns) - { - Pages.Namespaces.Add(ns); - return this; - } - - bool ISparkSettings.Debug - { - get { return Compilation.Debug; } - } - - bool IParserSettings.AutomaticEncoding - { - get { return Pages.AutomaticEncoding; } - } - - string IParserSettings.StatementMarker - { - get { return Pages.StatementMarker; } - } - - NullBehaviour ISparkSettings.NullBehaviour - { - get { return Compilation.NullBehaviour; } - } - - AttributeBehaviour ISparkSettings.AttributeBehaviour - { - get { return Compilation.AttributeBehaviour; } - } - - string ISparkSettings.Prefix - { - get { return Pages.Prefix; } - } - - bool ISparkSettings.ParseSectionTagAsSegment - { - get { return Pages.ParseSectionTagAsSegment; } - } - - string ISparkSettings.PageBaseType - { - get { return Pages.PageBaseType; } - set { Pages.PageBaseType = value; } - } - - LanguageType ISparkSettings.DefaultLanguage - { - get { return Compilation.DefaultLanguage; } - } - - IEnumerable ISparkSettings.UseNamespaces - { - get - { - foreach (NamespaceElement ns in Pages.Namespaces) - yield return ns.Namespace; - } - } - - IEnumerable ISparkSettings.UseAssemblies - { - get - { - foreach (AssemblyElement assembly in Compilation.Assemblies) - yield return assembly.Assembly; - } - } - - IEnumerable ISparkSettings.ResourceMappings - { - get - { - foreach (ResourcePathElement resource in Pages.Resources) - yield return new SimpleResourceMapping { Match = resource.Match, Location = resource.Location }; - } - } - - IEnumerable ISparkSettings.ViewFolders - { - get - { - foreach (ViewFolderElement viewFolder in Views) - yield return viewFolder; - } - } - - } -} +// Copyright 2008-2009 Louis DeJardin - http://whereslou.com +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +using System; +using System.Collections.Generic; +using System.Configuration; +using System.Reflection; +using Spark.Parser; + +namespace Spark.Configuration +{ + public class SparkSectionHandler : ConfigurationSection, ISparkSettings + { + [ConfigurationProperty("xmlns")] + public string XmlNamespace + { + get => (string)this["xmlns"]; + set => this["xmlns"] = value; + } + + [ConfigurationProperty("compilation")] + public CompilationElement Compilation + { + get => (CompilationElement)this["compilation"]; + set => this["compilation"] = value; + } + + [ConfigurationProperty("pages")] + public PagesElement Pages + { + get => (PagesElement)this["pages"]; + set => this["pages"] = value; + } + + [ConfigurationProperty("views")] + public ViewFolderElementCollection Views + { + get => (ViewFolderElementCollection)this["views"]; + set => this["views"] = value; + } + + public SparkSectionHandler SetDebug(bool debug) + { + Compilation.Debug = debug; + return this; + } + + public SparkSectionHandler SetPageBaseType(string typeName) + { + Pages.PageBaseType = typeName; + return this; + } + + public SparkSectionHandler SetPageBaseType(Type type) + { + Pages.PageBaseType = type.FullName; + return this; + } + + public SparkSectionHandler AddAssembly(string assembly) + { + Compilation.Assemblies.Add(assembly); + return this; + } + + public SparkSectionHandler AddAssembly(Assembly assembly) + { + Compilation.Assemblies.Add(assembly.FullName); + return this; + } + + public SparkSectionHandler AddNamespace(string ns) + { + Pages.Namespaces.Add(ns); + return this; + } + + bool ISparkSettings.Debug => Compilation.Debug; + + bool IParserSettings.AutomaticEncoding => Pages.AutomaticEncoding; + + string IParserSettings.StatementMarker => Pages.StatementMarker; + + NullBehaviour ISparkSettings.NullBehaviour => Compilation.NullBehaviour; + + AttributeBehaviour ISparkSettings.AttributeBehaviour => Compilation.AttributeBehaviour; + + string ISparkSettings.Prefix => Pages.Prefix; + + bool ISparkSettings.ParseSectionTagAsSegment => Pages.ParseSectionTagAsSegment; + + string ISparkSettings.PageBaseType + { + get => Pages.PageBaseType; + set => Pages.PageBaseType = value; + } + + LanguageType ISparkSettings.DefaultLanguage => Compilation.DefaultLanguage; + + IEnumerable ISparkSettings.UseNamespaces + { + get + { + foreach (NamespaceElement ns in Pages.Namespaces) + yield return ns.Namespace; + } + } + + IEnumerable ISparkSettings.UseAssemblies + { + get + { + foreach (AssemblyElement assembly in Compilation.Assemblies) + yield return assembly.Assembly; + } + } + + IEnumerable ISparkSettings.ResourceMappings + { + get + { + foreach (ResourcePathElement resource in Pages.Resources) + yield return new SimpleResourceMapping { Match = resource.Match, Location = resource.Location }; + } + } + + IEnumerable ISparkSettings.ViewFolders + { + get + { + foreach (ViewFolderElement viewFolder in Views) + yield return viewFolder; + } + } + + } +} diff --git a/src/Spark/Configuration/ViewFolderElement.cs b/src/Spark.Web/Configuration/ViewFolderElement.cs similarity index 70% rename from src/Spark/Configuration/ViewFolderElement.cs rename to src/Spark.Web/Configuration/ViewFolderElement.cs index 3689d51e..e211acb3 100644 --- a/src/Spark/Configuration/ViewFolderElement.cs +++ b/src/Spark.Web/Configuration/ViewFolderElement.cs @@ -1,65 +1,56 @@ -// Copyright 2008-2009 Louis DeJardin - http://whereslou.com -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// -using System.Collections.Generic; -using System.Configuration; -using Spark.FileSystem; - -namespace Spark.Configuration -{ - public class ViewFolderElement : ConfigurationElement, IViewFolderSettings - { - public ViewFolderElement() - { - Parameters = new Dictionary(); - } - - [ConfigurationProperty("name")] - public string Name - { - get { return (string)this["name"]; } - set { this["name"] = value; } - } - - [ConfigurationProperty("folderType")] - public ViewFolderType FolderType - { - get { return (ViewFolderType)this["folderType"]; } - set { this["folderType"] = value; } - } - - [ConfigurationProperty("type")] - public string Type - { - get { return (string)this["type"]; } - set { this["type"] = value; } - } - - [ConfigurationProperty("subfolder")] - public string Subfolder - { - get { return (string)this["subfolder"]; } - set { this["subfolder"] = value; } - } - - public IDictionary Parameters { get; set;} - - - protected override bool OnDeserializeUnrecognizedAttribute(string name, string value) - { - Parameters.Add(name, value); - return true; - } - } +// Copyright 2008-2009 Louis DeJardin - http://whereslou.com +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +using System.Collections.Generic; +using System.Configuration; + +namespace Spark.Configuration +{ + public class ViewFolderElement : ConfigurationElement, IViewFolderSettings + { + public ViewFolderElement() + { + Parameters = new Dictionary(); + } + + [ConfigurationProperty("name")] + public string Name + { + get => (string)this["name"]; + set => this["name"] = value; + } + + [ConfigurationProperty("type")] + public string Type + { + get => (string)this["type"]; + set => this["type"] = value; + } + + [ConfigurationProperty("subfolder")] + public string Subfolder + { + get => (string)this["subfolder"]; + set => this["subfolder"] = value; + } + + public IDictionary Parameters { get; set;} + + protected override bool OnDeserializeUnrecognizedAttribute(string name, string value) + { + Parameters.Add(name, value); + return true; + } + } } \ No newline at end of file diff --git a/src/Spark/Configuration/ViewFolderElementCollection.cs b/src/Spark.Web/Configuration/ViewFolderElementCollection.cs similarity index 97% rename from src/Spark/Configuration/ViewFolderElementCollection.cs rename to src/Spark.Web/Configuration/ViewFolderElementCollection.cs index 85782898..124cdf79 100644 --- a/src/Spark/Configuration/ViewFolderElementCollection.cs +++ b/src/Spark.Web/Configuration/ViewFolderElementCollection.cs @@ -1,36 +1,36 @@ -// Copyright 2008-2009 Louis DeJardin - http://whereslou.com -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// -using System.Configuration; - -namespace Spark.Configuration -{ - public class ViewFolderElementCollection : ConfigurationElementCollection - { - protected override ConfigurationElement CreateNewElement() - { - return new ViewFolderElement(); - } - - protected override object GetElementKey(ConfigurationElement element) - { - return ((ViewFolderElement)element).Name; - } - - public void Add(string name) - { - base.BaseAdd(new ViewFolderElement { Name = name }); - } - } +// Copyright 2008-2009 Louis DeJardin - http://whereslou.com +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +using System.Configuration; + +namespace Spark.Configuration +{ + public class ViewFolderElementCollection : ConfigurationElementCollection + { + protected override ConfigurationElement CreateNewElement() + { + return new ViewFolderElement(); + } + + protected override object GetElementKey(ConfigurationElement element) + { + return ((ViewFolderElement)element).Name; + } + + public void Add(string name) + { + base.BaseAdd(new ViewFolderElement { Name = name }); + } + } } \ No newline at end of file diff --git a/src/Spark/FileSystem/IViewFolderExtensions.cs b/src/Spark.Web/FileSystem/ViewFolderExtensions.cs similarity index 63% rename from src/Spark/FileSystem/IViewFolderExtensions.cs rename to src/Spark.Web/FileSystem/ViewFolderExtensions.cs index 6c2d7d08..24e5c808 100644 --- a/src/Spark/FileSystem/IViewFolderExtensions.cs +++ b/src/Spark.Web/FileSystem/ViewFolderExtensions.cs @@ -1,47 +1,32 @@ -// Copyright 2008-2009 Louis DeJardin - http://whereslou.com -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Web; - -namespace Spark.FileSystem -{ - public static class IViewFolderExtensions - { - public static IViewFolder Append(this IViewFolder viewFolder, IViewFolder additional) - { - return new CombinedViewFolder(viewFolder, additional); - } - - public static IViewFolder AddSharedPath(this IViewFolder viewFolder, string virtualPath) - { - var vppFolder = new SubViewFolder(new VirtualPathProviderViewFolder(virtualPath), "Shared"); - return Append(viewFolder, vppFolder); - } - - public static IViewFolder AddLayoutsPath(this IViewFolder viewFolder, string virtualPath) - { - var vppFolder = new SubViewFolder(new VirtualPathProviderViewFolder(virtualPath), "Layouts"); - return Append(viewFolder, vppFolder); - } - - public static IViewFolder ApplySettings(this IViewFolder viewFolder, ISparkSettings settings) - { - return viewFolder; - } - } -} +// Copyright 2008-2009 Louis DeJardin - http://whereslou.com +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +namespace Spark.FileSystem +{ + public static class ViewFolderExtensions + { + public static IViewFolder AddSharedPath(this IViewFolder viewFolder, string virtualPath) + { + var vppFolder = new SubViewFolder(new VirtualPathProviderViewFolder(virtualPath), "Shared"); + return viewFolder.Append(vppFolder); + } + + public static IViewFolder AddLayoutsPath(this IViewFolder viewFolder, string virtualPath) + { + var vppFolder = new SubViewFolder(new VirtualPathProviderViewFolder(virtualPath), "Layouts"); + return viewFolder.Append(vppFolder); + } + } +} diff --git a/src/Spark/FileSystem/VirtualPathProviderViewFolder.cs b/src/Spark.Web/FileSystem/VirtualPathProviderViewFolder.cs similarity index 89% rename from src/Spark/FileSystem/VirtualPathProviderViewFolder.cs rename to src/Spark.Web/FileSystem/VirtualPathProviderViewFolder.cs index ec1635c6..b9e18bf0 100644 --- a/src/Spark/FileSystem/VirtualPathProviderViewFolder.cs +++ b/src/Spark.Web/FileSystem/VirtualPathProviderViewFolder.cs @@ -1,88 +1,84 @@ -// Copyright 2008-2009 Louis DeJardin - http://whereslou.com -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// -using System; -using System.Collections.Generic; -using System.IO; -using System.Linq; -using System.Text; -using System.Web.Hosting; - -namespace Spark.FileSystem -{ - public class VirtualPathProviderViewFolder : IViewFolder - { - private readonly string _virtualBaseDir; - - public VirtualPathProviderViewFolder(string virtualBaseDir) - { - _virtualBaseDir = virtualBaseDir.TrimEnd(Path.AltDirectorySeparatorChar, Path.DirectorySeparatorChar) + "/"; - } - - public string VirtualBaseDir - { - get { return _virtualBaseDir; } - } - - public IViewFile GetViewSource(string path) - { - var file = HostingEnvironment.VirtualPathProvider.GetFile(Combine(path)); - return new VirtualPathFile(file); - } - - public class VirtualPathFile : IViewFile - { - private readonly VirtualFile _file; - - public VirtualPathFile(VirtualFile file) - { - _file = file; - } - - public long LastModified - { - get - { - var hash = HostingEnvironment.VirtualPathProvider.GetFileHash(_file.VirtualPath, new[] { _file.VirtualPath }); - return hash.GetHashCode(); - } - } - - public Stream OpenViewStream() - { - return _file.Open(); - } - } - - public IList ListViews(string path) - { - var directory = HostingEnvironment.VirtualPathProvider.GetDirectory(Combine(path)); - return directory.Files.OfType().Select(f => f.VirtualPath).ToArray(); - } - - public bool HasView(string path) - { - return HostingEnvironment.VirtualPathProvider.FileExists(Combine(path)); - } - - private string Combine(string path) - { - if (string.IsNullOrEmpty(path)) - return VirtualBaseDir; - - return HostingEnvironment.VirtualPathProvider.CombineVirtualPaths(VirtualBaseDir, path); - } - } - -} +// Copyright 2008-2009 Louis DeJardin - http://whereslou.com +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +using System.Collections.Generic; +using System.IO; +using System.Linq; +using System.Web.Hosting; + +namespace Spark.FileSystem +{ + public class VirtualPathProviderViewFolder : IViewFolder + { + private readonly string _virtualBaseDir; + + public VirtualPathProviderViewFolder(string virtualBaseDir) + { + _virtualBaseDir = virtualBaseDir.TrimEnd(Path.AltDirectorySeparatorChar, Path.DirectorySeparatorChar) + "/"; + } + + public string VirtualBaseDir => _virtualBaseDir; + + public IViewFile GetViewSource(string path) + { + var file = HostingEnvironment.VirtualPathProvider.GetFile(Combine(path)); + return new VirtualPathFile(file); + } + + public class VirtualPathFile : IViewFile + { + private readonly VirtualFile _file; + + public VirtualPathFile(VirtualFile file) + { + _file = file; + } + + public long LastModified + { + get + { + var hash = HostingEnvironment.VirtualPathProvider.GetFileHash(_file.VirtualPath, new[] { _file.VirtualPath }); + return hash.GetHashCode(); + } + } + + public Stream OpenViewStream() + { + return _file.Open(); + } + } + + public IList ListViews(string path) + { + var directory = HostingEnvironment.VirtualPathProvider.GetDirectory(Combine(path)); + return directory.Files.OfType().Select(f => f.VirtualPath).ToArray(); + } + + public bool HasView(string path) + { + return HostingEnvironment.VirtualPathProvider.FileExists(Combine(path)); + } + + private string Combine(string path) + { + if (string.IsNullOrEmpty(path)) + return VirtualBaseDir; + + return HostingEnvironment.VirtualPathProvider.CombineVirtualPaths(VirtualBaseDir, path); + } + } + +} diff --git a/src/Spark/ICacheService.cs b/src/Spark.Web/ICacheService.cs similarity index 95% rename from src/Spark/ICacheService.cs rename to src/Spark.Web/ICacheService.cs index 1ff56bfb..e4937080 100644 --- a/src/Spark/ICacheService.cs +++ b/src/Spark.Web/ICacheService.cs @@ -1,10 +1,10 @@ -using System; - -namespace Spark -{ - public interface ICacheService - { - object Get(string identifier); - void Store(string identifier, CacheExpires expires, ICacheSignal signal, object item); - } -} +using System; + +namespace Spark +{ + public interface ICacheService + { + object Get(string identifier); + void Store(string identifier, CacheExpires expires, ICacheSignal signal, object item); + } +} diff --git a/src/Spark/NullCacheService.cs b/src/Spark.Web/NullCacheService.cs similarity index 95% rename from src/Spark/NullCacheService.cs rename to src/Spark.Web/NullCacheService.cs index 499d23d7..f32b55a2 100644 --- a/src/Spark/NullCacheService.cs +++ b/src/Spark.Web/NullCacheService.cs @@ -1,14 +1,14 @@ -namespace Spark -{ - public class NullCacheService : ICacheService - { - public object Get(string identifier) - { - return null; - } - - public void Store(string identifier, CacheExpires expires, ICacheSignal signal, object item) - { - } - } +namespace Spark +{ + public class NullCacheService : ICacheService + { + public object Get(string identifier) + { + return null; + } + + public void Store(string identifier, CacheExpires expires, ICacheSignal signal, object item) + { + } + } } \ No newline at end of file diff --git a/src/Spark.Web/Spark.Web.csproj b/src/Spark.Web/Spark.Web.csproj new file mode 100644 index 00000000..50189593 --- /dev/null +++ b/src/Spark.Web/Spark.Web.csproj @@ -0,0 +1,41 @@ + + + Library + net481 + AllRules.ruleset + Spark + Spark.Web + RobertTheGrey + Louis DeJardin + https://github.com/SparkViewEngine/ + README.md + https://github.com/SparkViewEngine/spark + git + 1.8 + 1.8.1.0 + True + snupkg + license.txt + True + spark;view engine + Copyright (c) Louis DeJardin 2008-2022 + Spark is a view engine allowing the HTML to dominate the flow and any code to fit seamlessly. + + + + + + + + + + + True + \ + + + True + \ + + + \ No newline at end of file diff --git a/src/Spark/SparkViewBase.cs b/src/Spark.Web/SparkViewBase.cs similarity index 96% rename from src/Spark/SparkViewBase.cs rename to src/Spark.Web/SparkViewBase.cs index 496b86f5..bcd7fe4f 100644 --- a/src/Spark/SparkViewBase.cs +++ b/src/Spark.Web/SparkViewBase.cs @@ -1,250 +1,250 @@ -// Copyright 2008 Louis DeJardin - http://whereslou.com -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// -using System; -using System.Collections.Generic; -using System.IO; -using System.Threading; -using Spark.Caching; -using Spark.Spool; -using Spark.Utilities; - -namespace Spark -{ - public class SparkViewContext - { - public SparkViewContext() - { - Content = new Dictionary(); - Globals = new Dictionary(); - OnceTable = new Dictionary(); - } - - public TextWriter Output { get; set; } - public Dictionary Content { get; set; } - public Dictionary Globals { get; set; } - public Dictionary OnceTable { get; set; } - } - - public abstract class SparkViewBase : ISparkView - { - private SparkViewContext _sparkViewContext; - - public abstract Guid GeneratedViewId { get; } - - public virtual bool TryGetViewData(string name, out object value) - { - value = null; - return false; - } - - public virtual SparkViewContext SparkViewContext - { - get - { - return _sparkViewContext ?? - Interlocked.CompareExchange(ref _sparkViewContext, new SparkViewContext(), null) ?? - _sparkViewContext; - } - set { _sparkViewContext = value; } - } - - - public TextWriter Output { get { return SparkViewContext.Output; } set { SparkViewContext.Output = value; } } - public Dictionary Content { get { return SparkViewContext.Content; } set { SparkViewContext.Content = value; } } - public Dictionary Globals { get { return SparkViewContext.Globals; } set { SparkViewContext.Globals = value; } } - public Dictionary OnceTable { get { return SparkViewContext.OnceTable; } set { SparkViewContext.OnceTable = value; } } - - public IDisposable OutputScope(string name) - { - TextWriter writer; - if (!Content.TryGetValue(name, out writer)) - { - writer = new SpoolWriter(); - Content.Add(name, writer); - } - return new OutputScopeImpl(this, writer); - } - - public IDisposable OutputScope(TextWriter writer) - { - return new OutputScopeImpl(this, writer); - } - - public IDisposable OutputScope() - { - return new OutputScopeImpl(this, new SpoolWriter()); - } - - public IDisposable MarkdownOutputScope() - { - return new MarkdownOutputScopeImpl(this, new SpoolWriter()); - } - - - public bool Once(object flag) - { - var flagString = Convert.ToString(flag); - if (SparkViewContext.OnceTable.ContainsKey(flagString)) - return false; - - SparkViewContext.OnceTable.Add(flagString, null); - return true; - } - - - public class OutputScopeImpl : IDisposable - { - private readonly SparkViewBase view; - private readonly TextWriter previous; - - public OutputScopeImpl(SparkViewBase view, TextWriter writer) - { - this.view = view; - previous = view.Output; - view.Output = writer; - } - - public void Dispose() - { - view.Output = previous; - } - } - - public class MarkdownOutputScopeImpl : IDisposable - { - private readonly SparkViewBase view; - private readonly TextWriter previous; - - public MarkdownOutputScopeImpl(SparkViewBase view, TextWriter writer) - { - this.view = view; - previous = view.Output; - view.Output = writer; - } - - public void Dispose() - { - var source = view.Output.ToString(); - view.Output = previous; - - var markdown = new Markdown(); - - view.Output.Write(markdown.Transform(source)); - } - } - - protected bool BeginCachedContent(string site, CacheExpires expires, params object[] key) - { - _currentCacheScope = new CacheScopeImpl(this, CacheUtilities.ToIdentifier(site, key), expires); - if (_currentCacheScope.Begin()) - return true; - - EndCachedContent(); - return false; - } - - protected void EndCachedContent() - { - _currentCacheScope = _currentCacheScope.End(null); - } - - protected void EndCachedContent(ICacheSignal signal) - { - _currentCacheScope = _currentCacheScope.End(signal); - } - - private CacheScopeImpl _currentCacheScope; - public ICacheService CacheService { get; set; } - - - private class CacheScopeImpl - { - private readonly CacheScopeImpl _previousCacheScope; - - private readonly ICacheService _cacheService; - private readonly CacheOriginator _originator; - private readonly string _identifier; - private readonly CacheExpires _expires; - private bool _recording; - - private static readonly ICacheService _nullCacheService = new NullCacheService(); - - public CacheScopeImpl(SparkViewBase view, string identifier, CacheExpires expires) - { - _identifier = identifier; - _expires = expires; - _previousCacheScope = view._currentCacheScope; - _cacheService = view.CacheService ?? _nullCacheService; - _originator = new CacheOriginator(view.SparkViewContext); - } - - - public bool Begin() - { - var memento = _cacheService.Get(_identifier) as CacheMemento; - if (memento == null) - { - _recording = true; - _originator.BeginMemento(); - } - else - { - _recording = false; - _originator.DoMemento(memento); - } - - return _recording; - } - - public CacheScopeImpl End(ICacheSignal signal) - { - if (_recording) - { - var memento = _originator.EndMemento(); - _cacheService.Store(_identifier, _expires, signal, memento); - } - return _previousCacheScope; - } - - - private class NullCacheService : ICacheService - { - public object Get(string identifier) - { - return null; - } - - public void Store(string identifier, CacheExpires expires, ICacheSignal signal, object item) - { - } - } - } - - public virtual void RenderView(TextWriter writer) - { - using (OutputScope(writer)) - { - Render(); - } - } - - public abstract void Render(); - protected virtual void DelegateFirstRender(Action render) - { - render(); - } - } - -} +// Copyright 2008 Louis DeJardin - http://whereslou.com +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +using System; +using System.Collections.Generic; +using System.IO; +using System.Threading; +using Spark.Caching; +using Spark.Spool; +using Spark.Utilities; + +namespace Spark +{ + public class SparkViewContext + { + public SparkViewContext() + { + Content = new Dictionary(); + Globals = new Dictionary(); + OnceTable = new Dictionary(); + } + + public TextWriter Output { get; set; } + public Dictionary Content { get; set; } + public Dictionary Globals { get; set; } + public Dictionary OnceTable { get; set; } + } + + public abstract class SparkViewBase : ISparkView + { + private SparkViewContext _sparkViewContext; + + public abstract Guid GeneratedViewId { get; } + + public virtual bool TryGetViewData(string name, out object value) + { + value = null; + return false; + } + + public virtual SparkViewContext SparkViewContext + { + get + { + return _sparkViewContext ?? + Interlocked.CompareExchange(ref _sparkViewContext, new SparkViewContext(), null) ?? + _sparkViewContext; + } + set { _sparkViewContext = value; } + } + + + public TextWriter Output { get { return SparkViewContext.Output; } set { SparkViewContext.Output = value; } } + public Dictionary Content { get { return SparkViewContext.Content; } set { SparkViewContext.Content = value; } } + public Dictionary Globals { get { return SparkViewContext.Globals; } set { SparkViewContext.Globals = value; } } + public Dictionary OnceTable { get { return SparkViewContext.OnceTable; } set { SparkViewContext.OnceTable = value; } } + + public IDisposable OutputScope(string name) + { + TextWriter writer; + if (!Content.TryGetValue(name, out writer)) + { + writer = new SpoolWriter(); + Content.Add(name, writer); + } + return new OutputScopeImpl(this, writer); + } + + public IDisposable OutputScope(TextWriter writer) + { + return new OutputScopeImpl(this, writer); + } + + public IDisposable OutputScope() + { + return new OutputScopeImpl(this, new SpoolWriter()); + } + + public IDisposable MarkdownOutputScope() + { + return new MarkdownOutputScopeImpl(this, new SpoolWriter()); + } + + + public bool Once(object flag) + { + var flagString = Convert.ToString(flag); + if (SparkViewContext.OnceTable.ContainsKey(flagString)) + return false; + + SparkViewContext.OnceTable.Add(flagString, null); + return true; + } + + + public class OutputScopeImpl : IDisposable + { + private readonly SparkViewBase view; + private readonly TextWriter previous; + + public OutputScopeImpl(SparkViewBase view, TextWriter writer) + { + this.view = view; + previous = view.Output; + view.Output = writer; + } + + public void Dispose() + { + view.Output = previous; + } + } + + public class MarkdownOutputScopeImpl : IDisposable + { + private readonly SparkViewBase view; + private readonly TextWriter previous; + + public MarkdownOutputScopeImpl(SparkViewBase view, TextWriter writer) + { + this.view = view; + previous = view.Output; + view.Output = writer; + } + + public void Dispose() + { + var source = view.Output.ToString(); + view.Output = previous; + + var markdown = new Markdown(); + + view.Output.Write(markdown.Transform(source)); + } + } + + protected bool BeginCachedContent(string site, CacheExpires expires, params object[] key) + { + _currentCacheScope = new CacheScopeImpl(this, CacheUtilities.ToIdentifier(site, key), expires); + if (_currentCacheScope.Begin()) + return true; + + EndCachedContent(); + return false; + } + + protected void EndCachedContent() + { + _currentCacheScope = _currentCacheScope.End(null); + } + + protected void EndCachedContent(ICacheSignal signal) + { + _currentCacheScope = _currentCacheScope.End(signal); + } + + private CacheScopeImpl _currentCacheScope; + public ICacheService CacheService { get; set; } + + + private class CacheScopeImpl + { + private readonly CacheScopeImpl _previousCacheScope; + + private readonly ICacheService _cacheService; + private readonly CacheOriginator _originator; + private readonly string _identifier; + private readonly CacheExpires _expires; + private bool _recording; + + private static readonly ICacheService _nullCacheService = new NullCacheService(); + + public CacheScopeImpl(SparkViewBase view, string identifier, CacheExpires expires) + { + _identifier = identifier; + _expires = expires; + _previousCacheScope = view._currentCacheScope; + _cacheService = view.CacheService ?? _nullCacheService; + _originator = new CacheOriginator(view.SparkViewContext); + } + + + public bool Begin() + { + var memento = _cacheService.Get(_identifier) as CacheMemento; + if (memento == null) + { + _recording = true; + _originator.BeginMemento(); + } + else + { + _recording = false; + _originator.DoMemento(memento); + } + + return _recording; + } + + public CacheScopeImpl End(ICacheSignal signal) + { + if (_recording) + { + var memento = _originator.EndMemento(); + _cacheService.Store(_identifier, _expires, signal, memento); + } + return _previousCacheScope; + } + + + private class NullCacheService : ICacheService + { + public object Get(string identifier) + { + return null; + } + + public void Store(string identifier, CacheExpires expires, ICacheSignal signal, object item) + { + } + } + } + + public virtual void RenderView(TextWriter writer) + { + using (OutputScope(writer)) + { + Render(); + } + } + + public abstract void Render(); + protected virtual void DelegateFirstRender(Action render) + { + render(); + } + } + +} diff --git a/src/Spark/SparkViewDecorator.cs b/src/Spark.Web/SparkViewDecorator.cs similarity index 87% rename from src/Spark/SparkViewDecorator.cs rename to src/Spark.Web/SparkViewDecorator.cs index 4ce53f84..1f2fb1a1 100644 --- a/src/Spark/SparkViewDecorator.cs +++ b/src/Spark.Web/SparkViewDecorator.cs @@ -1,44 +1,40 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using Spark.Spool; - -namespace Spark -{ - public abstract class SparkViewDecorator : SparkViewBase - { - private readonly SparkViewBase _decorated; - - protected SparkViewDecorator(SparkViewBase decorated) - { - _decorated = decorated; - } - - public override SparkViewContext SparkViewContext - { - get - { - return _decorated != null ? _decorated.SparkViewContext : base.SparkViewContext; - } - set - { - if (_decorated != null) - _decorated.SparkViewContext = value; - else - base.SparkViewContext = value; - } - } - - public override void RenderView(System.IO.TextWriter writer) - { - if (_decorated != null) - { - var spooled = new SpoolWriter(); - _decorated.RenderView(spooled); - Content["view"] = spooled; - } - base.RenderView(writer); - } - } -} +using Spark.Spool; + +namespace Spark +{ + public abstract class SparkViewDecorator : SparkViewBase + { + private readonly SparkViewBase _decorated; + + protected SparkViewDecorator(SparkViewBase decorated) + { + _decorated = decorated; + } + + public override SparkViewContext SparkViewContext + { + get + { + return _decorated != null ? _decorated.SparkViewContext : base.SparkViewContext; + } + set + { + if (_decorated != null) + _decorated.SparkViewContext = value; + else + base.SparkViewContext = value; + } + } + + public override void RenderView(System.IO.TextWriter writer) + { + if (_decorated != null) + { + var spooled = new SpoolWriter(); + _decorated.RenderView(spooled); + Content["view"] = spooled; + } + base.RenderView(writer); + } + } +} diff --git a/src/Spark.sln b/src/Spark.sln index dcc3becb..cfbad182 100644 --- a/src/Spark.sln +++ b/src/Spark.sln @@ -54,6 +54,10 @@ Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Castle.MonoRail.Pdf", "Cast EndProject Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Castle.MonoRail.Pdf.Tests", "Castle.Monorail.Pdf.Tests\Castle.MonoRail.Pdf.Tests.csproj", "{0FEC123E-DFD8-4DB0-9FC7-6C2EF2897FAD}" EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Spark.Web", "Spark.Web\Spark.Web.csproj", "{4A68431B-ADD3-4F99-9121-2DF0C5C93BC3}" +EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Spark.Web.Tests", "Spark.Web.Tests\Spark.Web.Tests.csproj", "{58EE303C-D806-4917-9CA8-C2B10594A1AA}" +EndProject Global GlobalSection(SolutionConfigurationPlatforms) = preSolution Debug|Any CPU = Debug|Any CPU @@ -136,6 +140,14 @@ Global {0FEC123E-DFD8-4DB0-9FC7-6C2EF2897FAD}.Debug|Any CPU.Build.0 = Debug|Any CPU {0FEC123E-DFD8-4DB0-9FC7-6C2EF2897FAD}.Release|Any CPU.ActiveCfg = Release|Any CPU {0FEC123E-DFD8-4DB0-9FC7-6C2EF2897FAD}.Release|Any CPU.Build.0 = Release|Any CPU + {4A68431B-ADD3-4F99-9121-2DF0C5C93BC3}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {4A68431B-ADD3-4F99-9121-2DF0C5C93BC3}.Debug|Any CPU.Build.0 = Debug|Any CPU + {4A68431B-ADD3-4F99-9121-2DF0C5C93BC3}.Release|Any CPU.ActiveCfg = Release|Any CPU + {4A68431B-ADD3-4F99-9121-2DF0C5C93BC3}.Release|Any CPU.Build.0 = Release|Any CPU + {58EE303C-D806-4917-9CA8-C2B10594A1AA}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {58EE303C-D806-4917-9CA8-C2B10594A1AA}.Debug|Any CPU.Build.0 = Debug|Any CPU + {58EE303C-D806-4917-9CA8-C2B10594A1AA}.Release|Any CPU.ActiveCfg = Release|Any CPU + {58EE303C-D806-4917-9CA8-C2B10594A1AA}.Release|Any CPU.Build.0 = Release|Any CPU EndGlobalSection GlobalSection(SolutionProperties) = preSolution HideSolutionNode = FALSE @@ -160,6 +172,8 @@ Global {0799EE7A-58D3-467F-8DE6-8F3FFDDEF4A1} = {F4E1F2B2-2BA6-4EFC-8082-ADBC14ECC179} {D5796359-FF68-4444-809D-C7A8DAA92E41} = {CE293579-4889-4D6D-A1A0-BBBE8CBB9343} {0FEC123E-DFD8-4DB0-9FC7-6C2EF2897FAD} = {CE293579-4889-4D6D-A1A0-BBBE8CBB9343} + {4A68431B-ADD3-4F99-9121-2DF0C5C93BC3} = {F606A062-1BD5-40E2-8E8A-BCC4F374BFBF} + {58EE303C-D806-4917-9CA8-C2B10594A1AA} = {F606A062-1BD5-40E2-8E8A-BCC4F374BFBF} EndGlobalSection GlobalSection(ExtensibilityGlobals) = postSolution SolutionGuid = {B9FB0A1C-BC73-4CE6-95F0-9D33AE572BED} diff --git a/src/Spark/FileSystem/ViewFolderType.cs b/src/Spark/FileSystem/ViewFolderExtensions.cs similarity index 74% rename from src/Spark/FileSystem/ViewFolderType.cs rename to src/Spark/FileSystem/ViewFolderExtensions.cs index 75027959..ac910cd7 100644 --- a/src/Spark/FileSystem/ViewFolderType.cs +++ b/src/Spark/FileSystem/ViewFolderExtensions.cs @@ -1,24 +1,25 @@ -// Copyright 2008-2009 Louis DeJardin - http://whereslou.com -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// -namespace Spark.FileSystem -{ - public enum ViewFolderType - { - FileSystem, - VirtualPathProvider, - EmbeddedResource, - Custom, - } -} \ No newline at end of file +// Copyright 2008-2009 Louis DeJardin - http://whereslou.com +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +namespace Spark.FileSystem +{ + public static class ViewFolderExtensions + { + public static IViewFolder Append(this IViewFolder viewFolder, IViewFolder additional) + { + return new CombinedViewFolder(viewFolder, additional); + } + } +} diff --git a/src/Spark/ISparkSettings.cs b/src/Spark/ISparkSettings.cs index 2088c201..81ea4968 100644 --- a/src/Spark/ISparkSettings.cs +++ b/src/Spark/ISparkSettings.cs @@ -14,7 +14,6 @@ // using System; using System.Collections.Generic; -using Spark.FileSystem; using Spark.Parser; namespace Spark @@ -68,12 +67,10 @@ public interface IResourceMapping public class SimpleResourceMapping : IResourceMapping { - public string Match { get; set; } public string Location { get; set; } public bool Stop { get; set; } - - + public bool IsMatch(string path) { return path.StartsWith(Match, StringComparison.InvariantCultureIgnoreCase); @@ -83,14 +80,11 @@ public string Map(string path) { return Location + path.Substring(Match.Length); } - - } public interface IViewFolderSettings { string Name { get; set; } - ViewFolderType FolderType { get; set; } string Type { get; set; } string Subfolder { get; set; } IDictionary Parameters { get; set; } @@ -99,7 +93,6 @@ public interface IViewFolderSettings internal class ViewFolderSettings : IViewFolderSettings { public string Name { get; set; } - public ViewFolderType FolderType { get; set; } public string Type { get; set; } public string Subfolder { get; set; } public IDictionary Parameters { get; set; } diff --git a/src/Spark/Spark.csproj b/src/Spark/Spark.csproj index 30ca14a7..bec0ae34 100644 --- a/src/Spark/Spark.csproj +++ b/src/Spark/Spark.csproj @@ -41,6 +41,5 @@ - \ No newline at end of file diff --git a/src/Spark/SparkServiceContainer.cs b/src/Spark/SparkServiceContainer.cs index a3dee7bc..70b3ae91 100644 --- a/src/Spark/SparkServiceContainer.cs +++ b/src/Spark/SparkServiceContainer.cs @@ -16,9 +16,6 @@ using System.Collections.Generic; using System.Configuration; using System.IO; -using System.Linq; -using System.Text; -using System.Web.Hosting; using Spark.Bindings; using Spark.FileSystem; using Spark.Parser.Syntax; @@ -29,7 +26,6 @@ public class SparkServiceContainer : ISparkServiceContainer { public SparkServiceContainer() { - } public SparkServiceContainer(ISparkSettings settings) @@ -37,24 +33,28 @@ public SparkServiceContainer(ISparkSettings settings) _services[typeof(ISparkSettings)] = settings; } - readonly Dictionary _services = new Dictionary(); - readonly Dictionary> _defaults = + private readonly Dictionary> _defaults = new Dictionary> { - {typeof (ISparkSettings), c => ConfigurationManager.GetSection("spark") ?? new SparkSettings()}, - {typeof (ISparkViewEngine), c => new SparkViewEngine(c.GetService())}, - {typeof (ISparkLanguageFactory), c => new DefaultLanguageFactory()}, - {typeof (ISparkSyntaxProvider), c => new DefaultSyntaxProvider(c.GetService())}, - {typeof (IViewActivatorFactory), c => new DefaultViewActivator()}, - {typeof (IResourcePathManager), c => new DefaultResourcePathManager(c.GetService())}, - {typeof (ITemplateLocator), c => new DefaultTemplateLocator()}, - {typeof (IBindingProvider), c => new DefaultBindingProvider()}, - {typeof (IViewFolder), CreateDefaultViewFolder}, - {typeof (ICompiledViewHolder), c => new CompiledViewHolder()}, - {typeof (IPartialProvider), c => new DefaultPartialProvider()}, - {typeof (IPartialReferenceProvider), c => new DefaultPartialReferenceProvider(c.GetService())}, + {typeof(ISparkSettings), c => ConfigurationManager.GetSection("spark") ?? new SparkSettings()}, + {typeof(ISparkViewEngine), c => new SparkViewEngine(c.GetService())}, + {typeof(ISparkLanguageFactory), c => new DefaultLanguageFactory()}, + {typeof(ISparkSyntaxProvider), c => new DefaultSyntaxProvider(c.GetService())}, + {typeof(IViewActivatorFactory), c => new DefaultViewActivator()}, + {typeof(IResourcePathManager), c => new DefaultResourcePathManager(c.GetService())}, + {typeof(ITemplateLocator), c => new DefaultTemplateLocator()}, + {typeof(IBindingProvider), c => new DefaultBindingProvider()}, + {typeof(IViewFolder), c => + { + var appBase = AppDomain.CurrentDomain.SetupInformation.ApplicationBase; + return new FileSystemViewFolder(Path.Combine(appBase, "Views")); + } + }, + {typeof(ICompiledViewHolder), c => new CompiledViewHolder()}, + {typeof(IPartialProvider), c => new DefaultPartialProvider()}, + {typeof(IPartialReferenceProvider), c => new DefaultPartialReferenceProvider(c.GetService())}, }; @@ -84,7 +84,6 @@ public object GetService(Type serviceType) } } - public void SetService(TService service) { SetService(typeof(TService), service); @@ -93,9 +92,9 @@ public void SetService(TService service) public void SetService(Type serviceType, object service) { if (_services.ContainsKey(serviceType)) - throw new ApplicationException(string.Format("A service of type {0} has already been created", serviceType)); + throw new ApplicationException($"A service of type {serviceType} has already been created"); if (!serviceType.IsInterface) - throw new ApplicationException(string.Format("Only an interface may be used as service type. {0}", serviceType)); + throw new ApplicationException($"Only an interface may be used as service type. {serviceType}"); lock (_services) { @@ -113,22 +112,14 @@ public void SetServiceBuilder(Func ser public void SetServiceBuilder(Type serviceType, Func serviceBuilder) { if (_services.ContainsKey(serviceType)) - throw new ApplicationException(string.Format("A service of type {0} has already been created", serviceType)); + throw new ApplicationException($"A service of type {serviceType} has already been created"); if (!serviceType.IsInterface) - throw new ApplicationException(string.Format("Only an interface may be used as service type. {0}", serviceType)); + throw new ApplicationException($"Only an interface may be used as service type. {serviceType}"); lock (_services) { _defaults[serviceType] = serviceBuilder; } } - - private static object CreateDefaultViewFolder(ISparkServiceContainer arg) - { - if (HostingEnvironment.IsHosted && HostingEnvironment.VirtualPathProvider != null) - return new VirtualPathProviderViewFolder("~/Views"); - var appBase = AppDomain.CurrentDomain.SetupInformation.ApplicationBase; - return new FileSystemViewFolder(Path.Combine(appBase, "Views")); - } } } diff --git a/src/Spark/SparkSettings.cs b/src/Spark/SparkSettings.cs index 73b5a255..23a769f4 100644 --- a/src/Spark/SparkSettings.cs +++ b/src/Spark/SparkSettings.cs @@ -15,7 +15,6 @@ using System; using System.Collections.Generic; using System.Reflection; -using Spark.FileSystem; using Spark.Parser; namespace Spark @@ -28,14 +27,14 @@ public SparkSettings() _useAssemblies = new List(); _resourceMappings = new List(); _viewFolders = new List(); - NullBehaviour = NullBehaviour.Lenient; + NullBehaviour = NullBehaviour.Lenient; AttributeBehaviour = AttributeBehaviour.CodeOriented; AutomaticEncoding = ParserSettings.DefaultAutomaticEncoding; } public bool Debug { get; set; } - public NullBehaviour NullBehaviour { get; set; } + public NullBehaviour NullBehaviour { get; set; } public bool AutomaticEncoding { get; set; } public string StatementMarker { get; set; } public string Prefix { get; set; } @@ -46,28 +45,16 @@ public SparkSettings() public AttributeBehaviour AttributeBehaviour { get; set; } private readonly IList _useNamespaces; - public IEnumerable UseNamespaces - { - get { return _useNamespaces; } - } + public IEnumerable UseNamespaces => _useNamespaces; private readonly IList _useAssemblies; - public IEnumerable UseAssemblies - { - get { return _useAssemblies; } - } + public IEnumerable UseAssemblies => _useAssemblies; private readonly IList _resourceMappings; - public IEnumerable ResourceMappings - { - get { return _resourceMappings; } - } + public IEnumerable ResourceMappings => _resourceMappings; private readonly IList _viewFolders; - public IEnumerable ViewFolders - { - get { return _viewFolders; } - } + public IEnumerable ViewFolders => _viewFolders; public SparkSettings SetDebug(bool debug) { @@ -87,11 +74,11 @@ public SparkSettings SetStatementMarker(string statementMarker) return this; } - public SparkSettings SetNullBehaviour(NullBehaviour nullBehaviour) - { + public SparkSettings SetNullBehaviour(NullBehaviour nullBehaviour) + { NullBehaviour = nullBehaviour; - return this; - } + return this; + } public SparkSettings SetPageBaseType(string typeName) { @@ -148,34 +135,24 @@ public SparkSettings SetAttributeBehaviour(AttributeBehaviour attributeBehaviour } public SparkSettings AddResourceMapping(string match, string replace) - { - return AddResourceMapping(match, replace, true); - } - - public SparkSettings AddResourceMapping(string match, string replace, bool stopProcess) { - _resourceMappings.Add(new SimpleResourceMapping { Match = match, Location = replace, Stop = stopProcess}); - return this; + return AddResourceMapping(match, replace, true); } - public SparkSettings AddViewFolder(ViewFolderType type, IDictionary parameters) + public SparkSettings AddResourceMapping(string match, string replace, bool stopProcess) { - _viewFolders.Add(new ViewFolderSettings - { - FolderType = type, - Parameters = parameters - }); + _resourceMappings.Add(new SimpleResourceMapping { Match = match, Location = replace, Stop = stopProcess }); return this; } public SparkSettings AddViewFolder(Type customType, IDictionary parameters) { _viewFolders.Add(new ViewFolderSettings - { - FolderType = ViewFolderType.Custom, - Type = customType.AssemblyQualifiedName, - Parameters = parameters - }); + { + Name = customType.Name, + Type = customType.AssemblyQualifiedName, + Parameters = parameters + }); return this; } } diff --git a/src/Spark/SparkViewEngine.cs b/src/Spark/SparkViewEngine.cs index 6a0405a5..34722d3b 100644 --- a/src/Spark/SparkViewEngine.cs +++ b/src/Spark/SparkViewEngine.cs @@ -18,7 +18,6 @@ using System.Configuration; using System.IO; using System.Reflection; -using System.Web.Hosting; using Spark.Bindings; using Spark.Compiler; using Spark.Compiler.CSharp; @@ -28,7 +27,6 @@ namespace Spark { - public class SparkViewEngine : ISparkViewEngine, ISparkServiceInitialize { public SparkViewEngine() @@ -121,8 +119,6 @@ public IPartialReferenceProvider PartialReferenceProvider private static IViewFolder CreateDefaultViewFolder() { - if (HostingEnvironment.IsHosted && HostingEnvironment.VirtualPathProvider != null) - return new VirtualPathProviderViewFolder("~/Views"); var appBase = AppDomain.CurrentDomain.SetupInformation.ApplicationBase; return new FileSystemViewFolder(Path.Combine(appBase, "Views")); } @@ -130,38 +126,29 @@ private static IViewFolder CreateDefaultViewFolder() private void SetViewFolder(IViewFolder value) { var aggregateViewFolder = value; - foreach (var viewFolderSettings in Settings.ViewFolders) + + if (this.Settings.ViewFolders != null) { - IViewFolder viewFolder = ActivateViewFolder(viewFolderSettings); - if (!string.IsNullOrEmpty(viewFolderSettings.Subfolder)) - viewFolder = new SubViewFolder(viewFolder, viewFolderSettings.Subfolder); - aggregateViewFolder = aggregateViewFolder.Append(viewFolder); + foreach (var viewFolderSettings in this.Settings.ViewFolders) + { + IViewFolder viewFolder = this.ActivateViewFolder(viewFolderSettings); + + if (!string.IsNullOrEmpty(viewFolderSettings.Subfolder)) + { + viewFolder = new SubViewFolder(viewFolder, viewFolderSettings.Subfolder); + } + aggregateViewFolder = aggregateViewFolder.Append(viewFolder); + } } + _viewFolder = aggregateViewFolder; } private IViewFolder ActivateViewFolder(IViewFolderSettings viewFolderSettings) { - Type type; - switch (viewFolderSettings.FolderType) - { - case ViewFolderType.FileSystem: - type = typeof(FileSystemViewFolder); - break; - case ViewFolderType.EmbeddedResource: - type = typeof(EmbeddedViewFolder); - break; - case ViewFolderType.VirtualPathProvider: - type = typeof(VirtualPathProviderViewFolder); - break; - case ViewFolderType.Custom: - type = Type.GetType(viewFolderSettings.Type); - break; - default: - throw new ArgumentException("Unknown value for view folder type"); - } - + var type = Type.GetType(viewFolderSettings.Type); + ConstructorInfo bestConstructor = null; foreach (var constructor in type.GetConstructors()) { @@ -173,11 +160,16 @@ private IViewFolder ActivateViewFolder(IViewFolderSettings viewFolderSettings) } } } + if (bestConstructor == null) - throw new MissingMethodException(string.Format("No suitable constructor for {0} located", type.FullName)); + { + throw new MissingMethodException($"No suitable constructor for {type.FullName} located"); + } + var args = bestConstructor.GetParameters() .Select(param => ChangeType(viewFolderSettings, param)) .ToArray(); + return (IViewFolder)Activator.CreateInstance(type, args); } diff --git a/src/Xpark/SparkView.cs b/src/Xpark/SparkView.cs index e69a2d3d..2ea8f38c 100644 --- a/src/Xpark/SparkView.cs +++ b/src/Xpark/SparkView.cs @@ -1,6 +1,5 @@ using System.Xml.Linq; using Spark; -using System.Xml.XPath ; namespace Xpark { diff --git a/src/Xpark/Xpark.csproj b/src/Xpark/Xpark.csproj index eda7ab14..a2a9145d 100644 --- a/src/Xpark/Xpark.csproj +++ b/src/Xpark/Xpark.csproj @@ -20,6 +20,9 @@ Copyright (c) Louis DeJardin 2008-2022 Spark is a view engine allowing the HTML to dominate the flow and any code to fit seamlessly. + + + Always @@ -48,7 +51,4 @@ Always - - - \ No newline at end of file