Populating initial tree

--HG--
extra : convert_revision : svn%3A5ff7c347-ad56-4c35-b696-ccb81de16e03/trunk%4038902
This commit is contained in:
rpaquay
2009-11-07 22:49:58 +00:00
parent 4bbf4167c2
commit 2d3cd1b304
700 changed files with 222319 additions and 0 deletions

View File

@@ -0,0 +1,12 @@
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<system.diagnostics>
<sources>
<source name="Orchard.Tests.Logging.Thing" switchValue="Warning">
<listeners>
<add name="loopback" type="Orchard.Tests.Logging.InMemoryCapture,Orchard.Tests" />
</listeners>
</source>
</sources>
</system.diagnostics>
</configuration>

View File

@@ -0,0 +1,240 @@
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using NHibernate;
using NUnit.Framework;
using Orchard.Data;
using Orchard.Tests.Models;
namespace Orchard.Tests.Data {
[TestFixture]
public class RepositoryTests {
#region Setup/Teardown
[TestFixtureSetUp]
public void InitFixture() {
_databaseFilePath = Path.GetTempFileName();
}
[SetUp]
public void Init() {
_sessionFactory = DataUtility.CreateSessionFactory(_databaseFilePath, typeof(Foo));
_session = _sessionFactory.OpenSession();
_fooRepos = new Repository<Foo>(new StubLocator(_session));
}
[TearDown]
public void Term() {
_session.Close();
}
[TestFixtureTearDown]
public void TermFixture() {
File.Delete(_databaseFilePath);
}
#endregion
private IRepository<Foo> _fooRepos;
private ISession _session;
private string _databaseFilePath;
private ISessionFactory _sessionFactory;
private void CreateThreeFoos() {
_fooRepos.Create(new Foo { Name = "one" });
_fooRepos.Create(new Foo { Name = "two" });
_fooRepos.Create(new Foo { Name = "three" });
}
[Test]
public void GetByIdShouldReturnNullIfValueNotFound() {
CreateThreeFoos();
var nofoo = _fooRepos.Get(6655321);
Assert.That(nofoo, Is.Null);
}
[Test]
public void GetCanSelectSingleBasedOnFields() {
CreateThreeFoos();
var two = _fooRepos.Get(f => f.Name == "two");
Assert.That(two.Name, Is.EqualTo("two"));
}
[Test]
[ExpectedException(typeof(InvalidOperationException),
ExpectedMessage = "Sequence contains more than one element")]
public void GetThatReturnsTwoOrMoreShouldThrowException() {
CreateThreeFoos();
_fooRepos.Get(f => f.Name == "one" || f.Name == "three");
}
[Test]
public void GetWithZeroMatchesShouldReturnNull() {
CreateThreeFoos();
var nofoo = _fooRepos.Get(f => f.Name == "four");
Assert.That(nofoo, Is.Null);
}
[Test]
public void LinqCanBeUsedToSelectObjects() {
CreateThreeFoos();
var foos = from f in _fooRepos.Table
where f.Name == "one" || f.Name == "two"
select f;
Assert.That(foos.Count(), Is.EqualTo(2));
Assert.That(foos, Has.Some.Property("Name").EqualTo("one"));
Assert.That(foos, Has.Some.Property("Name").EqualTo("two"));
}
[Test]
public void LinqExtensionMethodsCanAlsoBeUsedToSelectObjects() {
CreateThreeFoos();
var foos = _fooRepos.Table
.Where(f => f.Name == "one" || f.Name == "two");
Assert.That(foos.Count(), Is.EqualTo(2));
Assert.That(foos, Has.Some.Property("Name").EqualTo("one"));
Assert.That(foos, Has.Some.Property("Name").EqualTo("two"));
}
[Test]
public void OrderShouldControlResults() {
CreateThreeFoos();
var foos = _fooRepos.Fetch(
f => f.Name == "two" || f.Name == "three",
o => o.Asc(f => f.Name, f => f.Id));
Assert.That(foos.Count(), Is.EqualTo(2));
Assert.That(foos.First().Name, Is.EqualTo("three"));
Assert.That(foos.Skip(1).First().Name, Is.EqualTo("two"));
}
[Test]
public void LinqOrderByCanBeUsedToControlResultsBug() {
CreateThreeFoos();
// If look at the "LinqOrderByCanBeUsedToControlResults", you will see this query
// works fine is the static type of "foos" is "IEnumerable<Foo>"...
IOrderedQueryable<Foo> foos =
from f in _fooRepos.Table
where f.Name == "two" || f.Name == "three"
orderby f.Name, f.Id ascending
select f;
Assert.That(foos.Count(), Is.EqualTo(2));
Assert.That(foos.First().Name, Is.EqualTo("three"));
// Looks like a bug in NHib implementation of IOrderedQueryable<T>
Assert.Throws<AssertionException>(() => Assert.That(foos.Skip(1).First().Name, Is.EqualTo("two")));
}
[Test]
public void LinqOrderByCanBeUsedToControlResults() {
CreateThreeFoos();
IEnumerable<Foo> foos =
from f in _fooRepos.Table
where f.Name == "two" || f.Name == "three"
orderby f.Name, f.Id ascending
select f;
Assert.That(foos.Count(), Is.EqualTo(2));
Assert.That(foos.First().Name, Is.EqualTo("three"));
Assert.That(foos.Skip(1).First().Name, Is.EqualTo("two"));
}
[Test]
public void RangeShouldSliceResults() {
for (var x = 0; x != 40; ++x) {
_fooRepos.Create(new Foo { Name = x.ToString().PadLeft(8, '0') });
}
var foos = _fooRepos.Fetch(
f => f.Name.StartsWith("000"),
o => o.Asc(f => f.Name),
10, 20);
Assert.That(foos.Count(), Is.EqualTo(20));
Assert.That(foos.First().Name, Is.EqualTo("00000010"));
Assert.That(foos.Last().Name, Is.EqualTo("00000029"));
}
[Test]
public void RepositoryCanCreateFetchUpdateAndDelete() {
var foo1 = new Foo { Name = "yadda" };
_fooRepos.Create(foo1);
var foo2 = _fooRepos.Get(foo1.Id);
foo2.Name = "blah";
_fooRepos.Update(foo2);
Assert.That(foo1, Is.SameAs(foo2));
_fooRepos.Delete(foo2);
}
[Test]
public void RepositoryFetchTakesCompoundLambdaPredicate() {
CreateThreeFoos();
var foos = _fooRepos.Fetch(f => f.Name == "three" || f.Name == "two");
Assert.That(foos.Count(), Is.EqualTo(2));
Assert.That(foos, Has.Some.Property("Name").EqualTo("two"));
Assert.That(foos, Has.Some.Property("Name").EqualTo("three"));
}
[Test]
public void RepositoryFetchTakesSimpleLambdaPredicate() {
CreateThreeFoos();
var one = _fooRepos.Fetch(f => f.Name == "one").Single();
var two = _fooRepos.Fetch(f => f.Name == "two").Single();
Assert.That(one.Name, Is.EqualTo("one"));
Assert.That(two.Name, Is.EqualTo("two"));
}
[Test]
public void TransactionShouldCallActionAndCommitWhenSuccessful() {
CreateThreeFoos();
_fooRepos.Transaction(() => { _fooRepos.Get(f => f.Name == "one").Name = "uno"; });
// need to evict all entities from session - otherwise modified class instances are selected
_session.Clear();
var foos = _fooRepos.Fetch(f => f.Name == "one" || f.Name == "uno");
Assert.That(foos.Count(), Is.EqualTo(1));
Assert.That(foos, Has.Some.Property("Name").EqualTo("uno"));
Assert.That(foos, Has.None.Property("Name").EqualTo("one"));
}
[Test]
public void ExceptionsShouldRollbackTransactionAndRethrowOutOfMethod() {
CreateThreeFoos();
try {
_fooRepos.Transaction(() => {
_fooRepos.Get(f => f.Name == "one").Name = "uno";
throw new ApplicationException("boom");
});
}
catch (Exception ex) {
Assert.That(ex.Message, Is.EqualTo("boom"));
}
// need to evict all entities from session - otherwise modified class instances are selected
_session.Clear();
var foos = _fooRepos.Fetch(f => f.Name == "one" || f.Name == "uno");
Assert.That(foos.Count(), Is.EqualTo(1));
Assert.That(foos, Has.None.Property("Name").EqualTo("uno"));
Assert.That(foos, Has.Some.Property("Name").EqualTo("one"));
}
}
}

View File

@@ -0,0 +1,21 @@
using System;
using NHibernate;
using Orchard.Data;
namespace Orchard.Tests.Data {
public class StubLocator : ISessionLocator {
private readonly ISession _session;
public StubLocator(ISession session) {
_session = session;
}
#region ISessionLocator Members
public ISession For(Type entityType) {
return _session;
}
#endregion
}
}

View File

@@ -0,0 +1,60 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using FluentNHibernate.Automapping;
using FluentNHibernate.Automapping.Alterations;
using FluentNHibernate.Cfg;
using FluentNHibernate.Cfg.Db;
using NHibernate;
using NHibernate.Tool.hbm2ddl;
using Orchard.Data;
namespace Orchard.Tests {
public static class DataUtility {
public static ISessionFactory CreateSessionFactory(string fileName, params Type[] types) {
var persistenceModel = AutoMap.Source(new Types(types))
.Alterations(alt => AddAlterations(alt, types))
.Conventions.AddFromAssemblyOf<DataModule>();
return Fluently.Configure()
.Database(SQLiteConfiguration.Standard.UsingFile(fileName).ShowSql())
.Mappings(m => m.AutoMappings.Add(persistenceModel))
.ExposeConfiguration(c => new SchemaExport(c).Create(false /*script*/, true /*export*/))
.BuildSessionFactory();
}
private static void AddAlterations(AutoMappingAlterationCollection alterations, Type[] types) {
foreach (var assembly in types.Select(t => t.Assembly).Distinct()) {
alterations.Add(new AutoMappingOverrideAlteration(assembly));
}
}
public static ISessionFactory CreateSessionFactory(params Type[] types) {
return CreateSessionFactory(
types.Aggregate("db", (n, t) => t.FullName + "." + n),
types);
}
#region Nested type: Types
private class Types : ITypeSource {
private readonly IEnumerable<Type> _types;
public Types(params Type[] types) {
_types = types;
}
#region ITypeSource Members
public IEnumerable<Type> GetTypes() {
return _types;
}
#endregion
}
#endregion
}
}

View File

@@ -0,0 +1,77 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Web;
using System.Web.Mvc;
using System.Web.Routing;
using Autofac;
using Autofac.Builder;
using Autofac.Integration.Web;
using Autofac.Modules;
using NUnit.Framework;
using Orchard.Environment;
using Orchard.Mvc;
using Orchard.Tests.Stubs;
namespace Orchard.Tests.Environment {
[TestFixture]
public class DefaultOrchardHostTests {
private IContainer _container;
private RouteCollection _routeCollection;
private ModelBinderDictionary _modelBinderDictionary;
private ControllerBuilder _controllerBuilder;
[SetUp]
public void Init() {
_controllerBuilder = new ControllerBuilder();
_routeCollection = new RouteCollection();
_modelBinderDictionary = new ModelBinderDictionary();
_container = OrchardStarter.CreateHostContainer(
builder => {
builder.RegisterModule(new ImplicitCollectionSupportModule());
builder.Register<StubContainerProvider>().As<IContainerProvider>().ContainerScoped();
builder.Register<StubCompositionStrategy>().As<ICompositionStrategy>().ContainerScoped();
builder.Register<DefaultOrchardHost>().As<IOrchardHost>();
builder.Register<RoutePublisher>().As<IRoutePublisher>();
builder.Register<ModelBinderPublisher>().As<IModelBinderPublisher>();
builder.Register(_controllerBuilder);
builder.Register(_routeCollection);
builder.Register(_modelBinderDictionary);
});
}
[Test]
public void HostShouldSetControllerFactory() {
var host = _container.Resolve<IOrchardHost>();
Assert.That(_controllerBuilder.GetControllerFactory(), Is.TypeOf<DefaultControllerFactory>());
host.Initialize();
Assert.That(_controllerBuilder.GetControllerFactory(), Is.TypeOf<OrchardControllerFactory>());
}
public class StubCompositionStrategy : ICompositionStrategy {
public IEnumerable<Assembly> GetAssemblies() {
return Enumerable.Empty<Assembly>();
}
public IEnumerable<Type> GetModuleTypes() {
return Enumerable.Empty<Type>();
}
public IEnumerable<Type> GetDependencyTypes() {
return Enumerable.Empty<Type>();
}
}
[Test]
public void DifferentRuntimeInstanceShouldBeReturnedAfterEachCreate() {
var host = _container.Resolve<IOrchardHost>();
var runtime1 = host.CreateRuntime();
var runtime2 = host.CreateRuntime();
Assert.That(runtime1, Is.Not.SameAs(runtime2));
}
}
}

View File

@@ -0,0 +1,83 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web.Mvc;
using System.Web.Routing;
using NUnit.Framework;
using Orchard.Environment;
using Orchard.Mvc;
namespace Orchard.Tests.Environment {
[TestFixture]
public class DefaultOrchardRuntimeTests {
static RouteDescriptor Desc(string name, string url) {
return new RouteDescriptor { Name = name, Route = new Route(url, new MvcRouteHandler()) };
}
static ModelBinderDescriptor BinderDesc(Type type, IModelBinder modelBinder) {
return new ModelBinderDescriptor { Type = type, ModelBinder = modelBinder };
}
[Test]
public void ActivatingRuntimeCausesRoutesAndModelBindersToBePublished() {
var provider1 = new StubRouteProvider(new[] { Desc("foo1", "foo1"), Desc("foo2", "foo2") });
var provider2 = new StubRouteProvider(new[] { Desc("foo1", "foo1"), Desc("foo2", "foo2") });
var publisher = new StubRoutePublisher();
var modelBinderProvider1 = new StubModelBinderProvider(new[] { BinderDesc(typeof(object), null), BinderDesc(typeof(string), null) });
var modelBinderProvider2 = new StubModelBinderProvider(new[] { BinderDesc(typeof(int), null), BinderDesc(typeof(long), null) });
var modelBinderPublisher = new StubModelBinderPublisher();
var runtime = new DefaultOrchardRuntime(
new[] { provider1, provider2 },
publisher,
new[] { modelBinderProvider1, modelBinderProvider2 },
modelBinderPublisher);
runtime.Activate();
Assert.That(publisher.Routes.Count(), Is.EqualTo(4));
Assert.That(modelBinderPublisher.ModelBinders.Count(), Is.EqualTo(4));
}
public class StubRouteProvider : IRouteProvider {
private readonly IEnumerable<RouteDescriptor> _routes;
public StubRouteProvider(IEnumerable<RouteDescriptor> routes) {
_routes = routes;
}
public IEnumerable<RouteDescriptor> GetRoutes() {
return _routes;
}
}
public class StubRoutePublisher : IRoutePublisher {
public void Publish(IEnumerable<RouteDescriptor> routes) {
Routes = routes;
}
public IEnumerable<RouteDescriptor> Routes { get; set; }
}
public class StubModelBinderProvider : IModelBinderProvider {
private readonly IEnumerable<ModelBinderDescriptor> _binders;
public StubModelBinderProvider(IEnumerable<ModelBinderDescriptor> routes) {
_binders = routes;
}
public IEnumerable<ModelBinderDescriptor> GetModelBinders() {
return _binders;
}
}
public class StubModelBinderPublisher : IModelBinderPublisher {
public void Publish(IEnumerable<ModelBinderDescriptor> modelBinders) {
ModelBinders = modelBinders;
}
public IEnumerable<ModelBinderDescriptor> ModelBinders { get; set; }
}
}
}

View File

@@ -0,0 +1,18 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web.Mvc;
using NUnit.Framework;
using Orchard.Environment;
namespace Orchard.Tests.Environment {
[TestFixture]
public class OrchardStarterTests {
[Test]
public void DefaultOrchardHostInstanceReturnedByCreateHost() {
var host = OrchardStarter.CreateHost(b => b.Register(new ControllerBuilder()));
Assert.That(host, Is.TypeOf<DefaultOrchardHost>());
}
}
}

View File

@@ -0,0 +1,29 @@
using System;
using NUnit.Framework;
namespace Orchard.Tests {
[TestFixture]
public class FakeTests {
#region Setup/Teardown
[SetUp]
public void Init() {
_x = 5;
}
#endregion
private int _x;
[Test]
[ExpectedException(typeof (ApplicationException), ExpectedMessage = "Boom")]
public void ExceptionsCanBeVerified() {
throw new ApplicationException("Boom");
}
[Test]
public void TestShouldRunFromResharper() {
Assert.That(_x, Is.EqualTo(5));
}
}
}

View File

@@ -0,0 +1,84 @@
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using FluentNHibernate.Automapping;
using FluentNHibernate.Cfg;
using FluentNHibernate.Cfg.Db;
using NHibernate;
using NHibernate.Criterion;
using NHibernate.Tool.hbm2ddl;
using NUnit.Framework;
using Orchard.Tests.Models;
namespace Orchard.Tests {
[TestFixture]
public class FluentDbTests {
public class Types : ITypeSource {
private readonly IEnumerable<Type> _types;
public Types(params Type[] types) {
_types = types;
}
#region ITypeSource Members
public IEnumerable<Type> GetTypes() {
return _types;
}
#endregion
}
[Test]
public void CreatingSchemaForStatedClassesInTempFile() {
var types = new Types(typeof (Foo), typeof (Bar));
var sessionFactory = Fluently.Configure()
.Database(SQLiteConfiguration.Standard.UsingFile("temp"))
.Mappings(m => m.AutoMappings.Add(AutoMap.Source(types)))
.ExposeConfiguration(c => new SchemaExport(c).Create(false, true))
.BuildSessionFactory();
var session = sessionFactory.OpenSession();
session.Save(new Foo {Name = "Hello"});
session.Save(new Bar {Height = 3, Width = 4.5m});
session.Close();
session = sessionFactory.OpenSession();
var foos = session.CreateCriteria<Foo>().List();
Assert.That(foos.Count, Is.EqualTo(1));
Assert.That(foos, Has.All.Property("Name").EqualTo("Hello"));
session.Close();
}
[Test]
public void InMemorySQLiteCanBeUsedInSessionFactory() {
var sessionFactory = Fluently.Configure()
.Database(SQLiteConfiguration.Standard.InMemory())
.BuildSessionFactory();
var session = sessionFactory.OpenSession();
session.Close();
}
[Test]
public void UsingDataUtilityToBuildSessionFactory() {
var factory = DataUtility.CreateSessionFactory(typeof (Foo), typeof (Bar));
var session = factory.OpenSession();
var foo1 = new Foo {Name = "world"};
session.Save(foo1);
session.Close();
session = factory.OpenSession();
var foo2 = session.CreateCriteria<Foo>()
.Add(Restrictions.Eq("Name", "world"))
.List<Foo>().Single();
session.Close();
Assert.That(foo1, Is.Not.SameAs(foo2));
Assert.That(foo1.Id, Is.EqualTo(foo2.Id));
}
}
}

View File

@@ -0,0 +1,42 @@
using System.Linq;
using NHibernate;
using NHibernate.Linq;
using NUnit.Framework;
using Orchard.Tests.Models;
namespace Orchard.Tests {
[TestFixture]
public class LinqToNHibernateTests {
#region Setup/Teardown
[SetUp]
public void Init() {
var sessionFactory = DataUtility.CreateSessionFactory(typeof (Foo));
using (var session = sessionFactory.OpenSession()) {
session.Save(new Foo {Name = "one"});
session.Save(new Foo {Name = "two"});
session.Save(new Foo {Name = "three"});
}
_session = sessionFactory.OpenSession();
}
[TearDown]
public void Term() {
_session.Close();
}
#endregion
private ISession _session;
[Test]
public void WhereClauseShouldLimitResults() {
var foos = from f in _session.Linq<Foo>() where f.Name == "two" || f.Name == "one" select f;
Assert.That(foos.Count(), Is.EqualTo(2));
Assert.That(foos, Has.Some.Property("Name").EqualTo("one"));
Assert.That(foos, Has.Some.Property("Name").EqualTo("two"));
Assert.That(foos, Has.None.Property("Name").EqualTo("three"));
}
}
}

View File

@@ -0,0 +1,86 @@
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text;
using Autofac.Builder;
using NUnit.Framework;
using Orchard.Logging;
namespace Orchard.Tests.Logging {
[TestFixture]
public class LoggingModuleTests {
[Test]
public void LoggingModuleWillSetLoggerProperty() {
var builder = new ContainerBuilder();
builder.RegisterModule(new LoggingModule());
builder.Register<Thing>();
var container = builder.Build();
var thing = container.Resolve<Thing>();
Assert.That(thing.Logger, Is.Not.Null);
}
[Test]
public void LoggerFactoryIsPassedTheTypeOfTheContainingInstance() {
var builder = new ContainerBuilder();
builder.RegisterModule(new LoggingModule());
builder.Register<Thing>();
var stubFactory = new StubFactory();
builder.Register(stubFactory).As<ILoggerFactory>();
var container = builder.Build();
var thing = container.Resolve<Thing>();
Assert.That(thing.Logger, Is.Not.Null);
Assert.That(stubFactory.CalledType, Is.EqualTo(typeof(Thing)));
}
public class StubFactory : ILoggerFactory {
public ILogger CreateLogger(Type type) {
CalledType = type;
return NullLogger.Instance;
}
public Type CalledType { get; set; }
}
[Test]
public void DefaultLoggerConfigurationUsesCastleLoggerFactoryOverTraceSource() {
var builder = new ContainerBuilder();
builder.RegisterModule(new LoggingModule());
builder.Register<Thing>();
var container = builder.Build();
var thing = container.Resolve<Thing>();
Assert.That(thing.Logger, Is.Not.Null);
InMemoryCapture.Messages.Clear();
thing.Logger.Error("-boom{0}-", 42);
Assert.That(InMemoryCapture.Messages, Has.Some.StringContaining("-boom42-"));
InMemoryCapture.Messages.Clear();
thing.Logger.Warning(new ApplicationException("problem"), "crash");
Assert.That(InMemoryCapture.Messages, Has.Some.StringContaining("problem"));
Assert.That(InMemoryCapture.Messages, Has.Some.StringContaining("crash"));
Assert.That(InMemoryCapture.Messages, Has.Some.StringContaining("ApplicationException"));
}
}
public class Thing {
public ILogger Logger { get; set; }
}
public class InMemoryCapture : TraceListener {
static InMemoryCapture() {
Messages = new List<string>();
}
public static List<string> Messages { get; set; }
public override void Write(string message) {
lock (Messages) Messages.Add(message);
}
public override void WriteLine(string message) {
lock (Messages) Messages.Add(message + System.Environment.NewLine);
}
}
}

View File

@@ -0,0 +1,7 @@
namespace Orchard.Tests.Models {
public class Bar {
public virtual int Id { get; set; }
public virtual decimal Height { get; set; }
public virtual decimal Width { get; set; }
}
}

View File

@@ -0,0 +1,6 @@
namespace Orchard.Tests.Models {
public class Foo {
public virtual int Id { get; set; }
public virtual string Name { get; set; }
}
}

View File

@@ -0,0 +1,51 @@
using System;
using System.Collections.Generic;
using System.Web.Mvc;
using NUnit.Framework;
using Orchard.Mvc.ModelBinders;
using Orchard.Utility;
namespace Orchard.Tests.Mvc.ModelBinders {
[TestFixture]
public class KeyedListModelBinderTests {
private class Foo {
public string Name { get; set; }
public string Value { get; set; }
}
[Test]
public void BinderShouldBindValues() {
var controllerContext = new ControllerContext();
var binders = new ModelBinderDictionary {
{ typeof(Foo), new DefaultModelBinder() }
};
var input = new FormCollection {
{ "fooInstance[Bar1].Value", "bar1value" },
{ "fooInstance[Bar2].Value", "bar2value" }
};
var foos = new[] {
new Foo {Name = "Bar1", Value = "uno"},
new Foo {Name = "Bar2", Value = "dos"},
new Foo {Name = "Bar3", Value = "tres"},
};
var providers = new EmptyModelMetadataProvider();
var bindingContext = new ModelBindingContext {
ModelMetadata = providers.GetMetadataForType(() => foos, foos.GetType()),
ModelName = "fooInstance",
ValueProvider = input.ToValueProvider()
};
var binder = new KeyedListModelBinder<Foo>(binders, providers, foo => foo.Name);
var result = (IList<Foo>)binder.BindModel(controllerContext, bindingContext);
Assert.That(result.Count, Is.EqualTo(3));
Assert.That(result[0].Value, Is.EqualTo("bar1value"));
Assert.That(result[1].Value, Is.EqualTo("bar2value"));
}
}
}

View File

@@ -0,0 +1,131 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Web;
using System.Web.Mvc;
using System.Web.Routing;
using Autofac.Builder;
using NUnit.Framework;
using Orchard.Mvc;
using Orchard.Tests.Stubs;
namespace Orchard.Tests.Mvc {
[TestFixture]
public class OrchardControllerFactoryTests {
private OrchardControllerFactory _controllerFactory;
private StubContainerProvider _containerProvider;
[SetUp]
public void Init() {
var builder = new ContainerBuilder();
builder.Register<ReplacementFooController>().As<IController>()
.Named("controller.orchard.web.foo")
.FactoryScoped();
var container = builder.Build();
_containerProvider = new StubContainerProvider(container, container.CreateInnerContainer());
_controllerFactory = new OrchardControllerFactory();
InjectKnownControllerTypes(_controllerFactory, typeof (FooController), typeof (BarController));
}
[Test]
public void IContainerProvidersRequestContainerFromRouteDataShouldUseTokenWhenPresent() {
var requestContext = GetRequestContext(_containerProvider);
var controller = _controllerFactory.CreateController(requestContext, "foo");
Assert.That(controller, Is.TypeOf<ReplacementFooController>());
}
[Test]
public void WhenNullOrMissingContainerNormalControllerFactoryRulesShouldBeUsedAsFallback() {
var requestContext = GetRequestContext(null);
var controller = _controllerFactory.CreateController(requestContext, "foo");
Assert.That(controller, Is.TypeOf<FooController>());
}
[Test]
public void
WhenContainerIsPresentButNamedControllerIsNotResolvedNormalControllerFactoryRulesShouldBeUsedAsFallback() {
var requestContext = GetRequestContext(_containerProvider);
var controller = _controllerFactory.CreateController(requestContext, "bar");
Assert.That(controller, Is.TypeOf<BarController>());
}
[Test]
public void DisposingControllerThatCameFromContainerShouldNotCauseProblemWhenContainerIsDisposed() {
var requestContext = GetRequestContext(_containerProvider);
var controller = _controllerFactory.CreateController(requestContext, "foo");
Assert.That(controller, Is.TypeOf<ReplacementFooController>());
_controllerFactory.ReleaseController(controller);
_containerProvider.DisposeRequestContainer();
// explicitly dispose a few more, just to make sure it's getting hit from all different directions
((IDisposable) controller).Dispose();
((ReplacementFooController) controller).Dispose();
Assert.That(((ReplacementFooController) controller).Disposals, Is.EqualTo(4));
}
private static RequestContext GetRequestContext(StubContainerProvider containerProvider) {
var handler = new MvcRouteHandler();
var route = new Route("yadda", handler) {
DataTokens =
new RouteValueDictionary
{{"IContainerProvider", containerProvider}}
};
var httpContext = new StubHttpContext();
var routeData = route.GetRouteData(httpContext);
return new RequestContext(httpContext, routeData);
}
public class FooController : Controller { }
public class BarController : Controller { }
public class ReplacementFooController : Controller {
protected override void Dispose(bool disposing) {
++Disposals;
base.Dispose(disposing);
}
public int Disposals { get; set; }
}
private static void InjectKnownControllerTypes(DefaultControllerFactory controllerFactory,
params Type[] controllerTypes) {
// D'oh!!! Hey MVC people, how is this testable? ;)
// locate the appropriate reflection member info
var controllerTypeCacheProperty = controllerFactory.GetType()
.GetProperty("ControllerTypeCache", BindingFlags.Instance | BindingFlags.NonPublic);
var cacheField = controllerTypeCacheProperty.PropertyType.GetField("_cache",
BindingFlags.NonPublic |
BindingFlags.Instance);
// turn the array into the correct collection
var cache = controllerTypes
.GroupBy(t => t.Name.Substring(0, t.Name.Length - "Controller".Length), StringComparer.OrdinalIgnoreCase)
.ToDictionary(g => g.Key,
g => g.ToLookup(t => t.Namespace ?? string.Empty, StringComparer.OrdinalIgnoreCase),
StringComparer.OrdinalIgnoreCase);
// execute: controllerFactory.ControllerTypeCache._cache = cache;
cacheField.SetValue(
controllerTypeCacheProperty.GetValue(controllerFactory, null),
cache);
}
}
}

View File

@@ -0,0 +1,23 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web.Mvc;
using Autofac;
using NUnit.Framework;
using Orchard.Mvc;
namespace Orchard.Tests.Mvc {
[TestFixture] public class OrchardControllerIdentificationStrategyTests {
[Test]
public void IdentificationStrategyAddsAssemblyNameAsAreaPrefixToControllerNames() {
var strategy = new OrchardControllerIdentificationStrategy();
var service = strategy.ServiceForControllerType(typeof (StrategyTestingController));
Assert.That(service, Is.TypeOf<NamedService>());
Assert.That(((NamedService)service).ServiceName, Is.EqualTo("controller.orchard.tests.strategytesting"));
}
}
public class StrategyTestingController:Controller {
}
}

View File

@@ -0,0 +1,110 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Web.Mvc;
using System.Web.Routing;
using NUnit.Framework;
using Orchard.Mvc;
using Orchard.Tests.Stubs;
namespace Orchard.Tests.Mvc {
[TestFixture]
public class RouteCollectionPublisherTests {
static RouteDescriptor Desc(string name, string url) {
return new RouteDescriptor {Name = name, Route = new Route(url, new MvcRouteHandler())};
}
[Test]
public void PublisherShouldReplaceRoutes() {
var routes = new RouteCollection();
routes.MapRoute("foo", "{controller}");
IRoutePublisher publisher = new RoutePublisher(routes, new StubContainerProvider(null, null));
publisher.Publish(new[] {Desc("barname", "bar"), Desc("quuxname", "quux")});
Assert.That(routes.Count(), Is.EqualTo(2));
}
[Test]
public void RoutesCanHaveNullOrEmptyNames() {
var routes = new RouteCollection();
routes.MapRoute("foo", "{controller}");
IRoutePublisher publisher = new RoutePublisher(routes, new StubContainerProvider(null, null));
publisher.Publish(new[] { Desc(null, "bar"), Desc(string.Empty, "quux") });
Assert.That(routes.Count(), Is.EqualTo(2));
}
[Test]
[ExpectedException(typeof(ArgumentException))]
public void SameNameTwiceCausesExplosion() {
var routes = new RouteCollection();
routes.MapRoute("foo", "{controller}");
IRoutePublisher publisher = new RoutePublisher(routes, new StubContainerProvider(null, null));
publisher.Publish(new[] {Desc("yarg", "bar"), Desc("yarg", "quux")});
Assert.That(routes.Count(), Is.EqualTo(2));
}
[Test]
public void ExplosionLeavesOriginalRoutesIntact() {
var routes = new RouteCollection();
routes.MapRoute("foo", "{controller}");
IRoutePublisher publisher = new RoutePublisher(routes, new StubContainerProvider(null, null));
try {
publisher.Publish(new[] { Desc("yarg", "bar"), Desc("yarg", "quux") });
}
catch (ArgumentException) {
Assert.That(routes.Count(), Is.EqualTo(1));
Assert.That(routes.OfType<Route>().Single().Url, Is.EqualTo("{controller}"));
}
}
[Test]
public void RoutesArePaintedWithConainerProviderAsTheyAreApplied() {
var routes = new RouteCollection();
routes.MapRoute("foo", "{controller}");
var containerProvider = new StubContainerProvider(null, null);
IRoutePublisher publisher = new RoutePublisher(routes, containerProvider);
publisher.Publish(new[] { Desc("barname", "bar"), Desc("quuxname", "quux") });
Assert.That(routes.OfType<Route>().Count(), Is.EqualTo(2));
Assert.That(routes.OfType<Route>().SelectMany(r => r.DataTokens.Values).Count(), Is.EqualTo(2));
Assert.That(routes.OfType<Route>().SelectMany(r => r.DataTokens.Values), Has.All.SameAs(containerProvider));
}
[Test]
public void WriteBlocksWhileReadIsInEffect() {
var routes = new RouteCollection();
routes.MapRoute("foo", "{controller}");
var containerProvider = new StubContainerProvider(null, null);
IRoutePublisher publisher = new RoutePublisher(routes, containerProvider);
var readLock = routes.GetReadLock();
string where = "init";
var action = new Action(() => {
where = "before";
publisher.Publish(new[] { Desc("barname", "bar"), Desc("quuxname", "quux") });
where = "after";
});
Assert.That(where, Is.EqualTo("init"));
var async = action.BeginInvoke(null, null);
Thread.Sleep(75);
Assert.That(where, Is.EqualTo("before"));
readLock.Dispose();
Thread.Sleep(75);
Assert.That(where, Is.EqualTo("after"));
action.EndInvoke(async);
}
}
}

View File

@@ -0,0 +1,21 @@
using NUnit.Framework;
using Orchard.Notify;
namespace Orchard.Tests.Notify {
[TestFixture]
public class NotifierTests {
[Test]
public void MessageServiceCanAccumulateWarningsAndErrorsToReturn() {
INotifier notifier = new Notifier();
notifier.Warning("Hello world");
notifier.Information("More Info");
notifier.Error("Boom");
Assert.That(notifier.List(), Has.Count.EqualTo(3));
Assert.That(notifier.List(), Has.Some.Property("Message").EqualTo("Hello world"));
Assert.That(notifier.List(), Has.Some.Property("Message").EqualTo("More Info"));
Assert.That(notifier.List(), Has.Some.Property("Message").EqualTo("Boom"));
}
}
}

View File

@@ -0,0 +1,82 @@
using System.Web.Mvc;
using System.Web.Routing;
using Moq;
using NUnit.Framework;
using Orchard.Mvc.ViewModels;
using Orchard.Notify;
using Orchard.Tests.Stubs;
namespace Orchard.Tests.Notify {
[TestFixture]
public class NotifyFilterTests {
private static ActionExecutedContext BuildContext() {
var httpContext = new StubHttpContext();
var routeData = new RouteData();
var controllerContext = new ControllerContext(httpContext, routeData, new Mock<ControllerBase>().Object);
var actionDescriptor = new Mock<ActionDescriptor>().Object;
return new ActionExecutedContext(controllerContext, actionDescriptor, false/*cancelled*/, null/*exception*/);
}
[Test]
public void AfterActionExecutedMessagesShouldAppearInTempData() {
var sink = new Notifier();
var filter = new NotifyFilter(sink);
sink.Information("Hello world");
var executedContext = BuildContext();
filter.OnActionExecuted(executedContext);
Assert.That(executedContext.Controller.TempData.ContainsKey("messages"));
Assert.That(executedContext.Controller.TempData["messages"], Is.StringContaining("Hello world"));
}
[Test]
public void ExistingTempDataIsntModified() {
var sink = new Notifier();
var filter = new NotifyFilter(sink);
var executedContext = BuildContext();
executedContext.Controller.TempData.Add("messages", "dont-destroy");
filter.OnActionExecuted(executedContext);
Assert.That(executedContext.Controller.TempData["messages"], Is.EqualTo("dont-destroy"));
}
[Test]
public void NewMessagesAreConcatinated() {
var sink = new Notifier();
var filter = new NotifyFilter(sink);
sink.Error("Boom");
var executedContext = BuildContext();
executedContext.Controller.TempData.Add("messages", "dont-destroy");
filter.OnActionExecuted(executedContext);
Assert.That(executedContext.Controller.TempData["messages"], Is.StringContaining("dont-destroy"));
Assert.That(executedContext.Controller.TempData["messages"], Is.StringContaining("dont-destroy"));
}
[Test]
public void TempDataBuildsMessagesWhenResultExecutingIsBaseViewModel() {
var sink = new Notifier();
var filter = new NotifyFilter(sink);
sink.Information("Working");
var model = new AdminViewModel();
var context = BuildContext();
context.Controller.TempData.Add("messages", "dont-destroy" + System.Environment.NewLine);
context.Result = new ViewResult {
ViewData = new ViewDataDictionary<AdminViewModel>(model),
TempData = context.Controller.TempData
};
filter.OnActionExecuted(context);
filter.OnResultExecuting(new ResultExecutingContext(context, context.Result));
Assert.That(model.Messages, Is.Not.Null);
Assert.That(model.Messages, Has.Count.EqualTo(2));
Assert.That(model.Messages, Has.Some.Property("Message").EqualTo("dont-destroy"));
Assert.That(model.Messages, Has.Some.Property("Message").EqualTo("Working"));
}
}
}

View File

@@ -0,0 +1,142 @@
<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="3.5" DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<PropertyGroup>
<Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>
<Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform>
<ProductVersion>9.0.30729</ProductVersion>
<SchemaVersion>2.0</SchemaVersion>
<ProjectGuid>{ABC826D4-2FA1-4F2F-87DE-E6095F653810}</ProjectGuid>
<OutputType>Library</OutputType>
<AppDesignerFolder>Properties</AppDesignerFolder>
<RootNamespace>Orchard.Tests</RootNamespace>
<AssemblyName>Orchard.Tests</AssemblyName>
<TargetFrameworkVersion>v3.5</TargetFrameworkVersion>
<FileAlignment>512</FileAlignment>
<SccProjectName>SAK</SccProjectName>
<SccLocalPath>SAK</SccLocalPath>
<SccAuxPath>SAK</SccAuxPath>
<SccProvider>SAK</SccProvider>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ">
<DebugSymbols>true</DebugSymbols>
<DebugType>full</DebugType>
<Optimize>false</Optimize>
<OutputPath>bin\Debug\</OutputPath>
<DefineConstants>DEBUG;TRACE</DefineConstants>
<ErrorReport>prompt</ErrorReport>
<WarningLevel>4</WarningLevel>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' ">
<DebugType>pdbonly</DebugType>
<Optimize>true</Optimize>
<OutputPath>bin\Release\</OutputPath>
<DefineConstants>TRACE</DefineConstants>
<ErrorReport>prompt</ErrorReport>
<WarningLevel>4</WarningLevel>
</PropertyGroup>
<ItemGroup>
<Reference Include="Autofac, Version=1.4.4.561, Culture=neutral, PublicKeyToken=17863af14b0044da, processorArchitecture=MSIL">
<SpecificVersion>False</SpecificVersion>
<HintPath>..\..\lib\autofac\Autofac.dll</HintPath>
</Reference>
<Reference Include="Autofac.Integration.Web, Version=1.4.4.561, Culture=neutral, PublicKeyToken=17863af14b0044da, processorArchitecture=MSIL">
<SpecificVersion>False</SpecificVersion>
<HintPath>..\..\lib\autofac\Autofac.Integration.Web.dll</HintPath>
</Reference>
<Reference Include="FluentNHibernate, Version=1.0.0.593, Culture=neutral, PublicKeyToken=8aa435e3cb308880, processorArchitecture=MSIL">
<SpecificVersion>False</SpecificVersion>
<HintPath>..\..\lib\fluentnhibernate\FluentNHibernate.dll</HintPath>
</Reference>
<Reference Include="Moq, Version=4.0.812.4, Culture=neutral, PublicKeyToken=69f491c39445e920, processorArchitecture=MSIL">
<SpecificVersion>False</SpecificVersion>
<HintPath>..\..\lib\moq\Moq.dll</HintPath>
</Reference>
<Reference Include="NHibernate, Version=2.1.0.4000, Culture=neutral, PublicKeyToken=aa95f207798dfdb4, processorArchitecture=MSIL">
<SpecificVersion>False</SpecificVersion>
<HintPath>..\..\lib\fluentnhibernate\NHibernate.dll</HintPath>
</Reference>
<Reference Include="NHibernate.ByteCode.Castle, Version=2.1.0.4000, Culture=neutral, PublicKeyToken=aa95f207798dfdb4, processorArchitecture=MSIL">
<SpecificVersion>False</SpecificVersion>
<HintPath>..\..\lib\fluentnhibernate\NHibernate.ByteCode.Castle.dll</HintPath>
</Reference>
<Reference Include="NHibernate.Linq, Version=1.0.0.4000, Culture=neutral, PublicKeyToken=444cf6a87fdab271, processorArchitecture=MSIL">
<SpecificVersion>False</SpecificVersion>
<HintPath>..\..\lib\linqnhibernate\NHibernate.Linq.dll</HintPath>
</Reference>
<Reference Include="nunit.framework, Version=2.5.2.9222, Culture=neutral, PublicKeyToken=96d09a1eb7f44a77, processorArchitecture=MSIL">
<SpecificVersion>False</SpecificVersion>
<HintPath>..\..\lib\nunit\nunit.framework.dll</HintPath>
</Reference>
<Reference Include="System" />
<Reference Include="System.Core">
<RequiredTargetFramework>3.5</RequiredTargetFramework>
</Reference>
<Reference Include="System.Data.SQLite, Version=1.0.65.0, Culture=neutral, PublicKeyToken=db937bc2d44ff139, processorArchitecture=x86">
<SpecificVersion>False</SpecificVersion>
<HintPath>..\..\lib\sqlite\System.Data.SQLite.DLL</HintPath>
<Private>True</Private>
</Reference>
<Reference Include="System.Web" />
<Reference Include="System.Web.Abstractions">
<RequiredTargetFramework>3.5</RequiredTargetFramework>
</Reference>
<Reference Include="System.Web.Mvc, Version=2.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35, processorArchitecture=MSIL">
<SpecificVersion>False</SpecificVersion>
<HintPath>..\..\lib\aspnetmvc\System.Web.Mvc.dll</HintPath>
</Reference>
<Reference Include="System.Web.Routing">
<RequiredTargetFramework>3.5</RequiredTargetFramework>
</Reference>
<Reference Include="System.Xml.Linq">
<RequiredTargetFramework>3.5</RequiredTargetFramework>
</Reference>
<Reference Include="System.Data.DataSetExtensions">
<RequiredTargetFramework>3.5</RequiredTargetFramework>
</Reference>
<Reference Include="System.Data" />
<Reference Include="System.Xml" />
</ItemGroup>
<ItemGroup>
<Compile Include="DataUtility.cs" />
<Compile Include="Data\RepositoryTests.cs" />
<Compile Include="Data\StubLocator.cs" />
<Compile Include="Environment\DefaultOrchardHostTests.cs" />
<Compile Include="Environment\DefaultOrchardRuntimeTests.cs" />
<Compile Include="Environment\OrchardStarterTests.cs" />
<Compile Include="Logging\LoggingModuleTests.cs" />
<Compile Include="Mvc\ModelBinders\KeyedListModelBinderTests.cs" />
<Compile Include="Mvc\OrchardControllerFactoryTests.cs" />
<Compile Include="Mvc\OrchardControllerIdentificationStrategyTests.cs" />
<Compile Include="Mvc\RouteCollectionPublisherTests.cs" />
<Compile Include="Notify\NotifierTests.cs" />
<Compile Include="Notify\NotifyFilterTests.cs" />
<Compile Include="Services\ClockTests.cs" />
<Compile Include="Storage\FileSystemStorageProviderTests.cs" />
<Compile Include="Stubs\StubClock.cs" />
<Compile Include="Stubs\StubContainerProvider.cs" />
<Compile Include="FakeTests.cs" />
<Compile Include="FluentDbTests.cs" />
<Compile Include="LinqToNHibernateTests.cs" />
<Compile Include="Models\Bar.cs" />
<Compile Include="Models\Foo.cs" />
<Compile Include="Properties\AssemblyInfo.cs" />
<Compile Include="Stubs\StubHttpContext.cs" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\Orchard\Orchard.csproj">
<Project>{2D1D92BB-4555-4CBE-8D0E-63563D6CE4C6}</Project>
<Name>Orchard</Name>
</ProjectReference>
</ItemGroup>
<ItemGroup>
<None Include="App.config" />
</ItemGroup>
<Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" />
<!-- To modify your build process, add your task inside one of the targets below and uncomment it.
Other similar extension points exist, see Microsoft.Common.targets.
<Target Name="BeforeBuild">
</Target>
<Target Name="AfterBuild">
</Target>
-->
</Project>

View File

@@ -0,0 +1,10 @@
""
{
"FILE_VERSION" = "9237"
"ENLISTMENT_CHOICE" = "NEVER"
"PROJECT_FILE_RELATIVE_PATH" = ""
"NUMBER_OF_EXCLUDED_FILES" = "0"
"ORIGINAL_PROJECT_FILE_PATH" = ""
"NUMBER_OF_NESTED_PROJECTS" = "0"
"SOURCE_CONTROL_SETTINGS_PROVIDER" = "PROVIDER"
}

View File

@@ -0,0 +1,37 @@
using System.Reflection;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("Orchard.Tests")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyProduct("Orchard.Tests")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("2a721221-b81c-47fa-8a29-4673cd0182b7")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]

View File

@@ -0,0 +1,55 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using NUnit.Framework;
using Orchard.Services;
using Orchard.Tests.Stubs;
namespace Orchard.Tests.Services {
[TestFixture]
public class ClockTests {
[Test, Ignore("At the moment the default clock is using DateTime.Now until a user-time-zone corrected display is in effect.")]
public void DefaultClockShouldComeFromSystemUtc() {
IClock clock = new Clock();
var before = DateTime.UtcNow;
Thread.Sleep(2);
var mark = clock.UtcNow;
Thread.Sleep(2);
var after = DateTime.UtcNow;
Assert.That(mark.Kind, Is.EqualTo(DateTimeKind.Utc));
Assert.That(mark, Is.InRange(before, after));
}
[Test]
public void StubClockShouldComeFromSystemUtcAndDoesNotComeFromSystemTime() {
var clock = new StubClock();
var before = DateTime.UtcNow;
Thread.Sleep(2);
var mark = clock.UtcNow;
Thread.Sleep(2);
var after = DateTime.UtcNow;
Assert.That(mark.Kind, Is.EqualTo(DateTimeKind.Utc));
Assert.That(mark, Is.Not.InRange(before, after));
}
[Test]
public void StubClockCanBeManuallyAdvanced() {
var clock = new StubClock();
var before = clock.UtcNow;
clock.Advance(TimeSpan.FromMilliseconds(2));
var mark = clock.UtcNow;
clock.Advance(TimeSpan.FromMilliseconds(2));
var after = clock.UtcNow;
Assert.That(mark.Kind, Is.EqualTo(DateTimeKind.Utc));
Assert.That(mark, Is.InRange(before, after));
Assert.That(after.Subtract(before), Is.EqualTo(TimeSpan.FromMilliseconds(4)));
}
}
}

View File

@@ -0,0 +1,45 @@
using System.Collections.Generic;
using System.IO;
using System.Linq;
using NUnit.Framework;
using System;
using Orchard.Storage;
namespace Orchard.Tests.Storage {
[TestFixture]
public class FileSystemStorageProviderTests {
#region Setup/Teardown
[TestFixtureSetUp]
public void InitFixture() {
_folderPath = Directory.CreateDirectory(Path.GetTempPath() + "filesystemstorageprovidertests").FullName;
_filePath = _folderPath + "\\testfile.txt";
FileStream fileStream = File.Create(_filePath);
fileStream.Close();
_fileSystemStorageProvider = new FileSystemStorageProvider();
}
[TestFixtureTearDown]
public void TermFixture() {
Directory.Delete(_folderPath, true);
}
#endregion
private string _filePath;
private string _folderPath;
private FileSystemStorageProvider _fileSystemStorageProvider;
[Test]
[ExpectedException(typeof(ArgumentException))]
public void GetFileThatDoesNotExistShouldThrow() {
_fileSystemStorageProvider.GetFile("notexisting");
}
[Test]
public void ListFilesShouldReturnFilesFromFilesystem() {
IEnumerable<IStorageFile> files = _fileSystemStorageProvider.ListFiles(_folderPath);
Assert.That(files.Count(), Is.EqualTo(1));
}
}
}

View File

@@ -0,0 +1,20 @@
using System;
using Orchard.Services;
namespace Orchard.Tests.Stubs {
public class StubClock : IClock {
public StubClock() {
UtcNow = new DateTime(2009, 10, 14, 12, 34, 56, DateTimeKind.Utc);
}
public DateTime UtcNow { get; private set; }
public void Advance(TimeSpan span) {
UtcNow = UtcNow.Add(span);
}
public DateTime FutureMoment(TimeSpan span) {
return UtcNow.Add(span);
}
}
}

View File

@@ -0,0 +1,19 @@
using Autofac;
using Autofac.Integration.Web;
namespace Orchard.Tests.Stubs {
public class StubContainerProvider : IContainerProvider {
public StubContainerProvider(IContainer applicationContainer, IContainer requestContainer) {
ApplicationContainer = applicationContainer;
RequestContainer = requestContainer;
}
public void DisposeRequestContainer() {
RequestContainer.Dispose();
}
public IContainer ApplicationContainer { get; set; }
public IContainer RequestContainer { get; set; }
}
}

View File

@@ -0,0 +1,35 @@
using System.Web;
namespace Orchard.Tests.Stubs {
public class StubHttpContext : HttpContextBase {
private readonly string _appRelativeCurrentExecutionFilePath;
public StubHttpContext() {
_appRelativeCurrentExecutionFilePath = "~/yadda";
}
public StubHttpContext(string appRelativeCurrentExecutionFilePath) {
_appRelativeCurrentExecutionFilePath = appRelativeCurrentExecutionFilePath;
}
public override HttpRequestBase Request {
get { return new StupHttpRequest(_appRelativeCurrentExecutionFilePath); }
}
public class StupHttpRequest : HttpRequestBase {
private readonly string _appRelativeCurrentExecutionFilePath;
public StupHttpRequest(string appRelativeCurrentExecutionFilePath) {
_appRelativeCurrentExecutionFilePath = appRelativeCurrentExecutionFilePath;
}
public override string AppRelativeCurrentExecutionFilePath {
get { return _appRelativeCurrentExecutionFilePath; }
}
public override string PathInfo {
get { return ""; }
}
}
}
}