Browse Source

Tests fixed and some adaptions to C# 7... yeah, less code

pull/1/head
Sebastian 10 years ago
parent
commit
36f393965d
  1. 24
      src/Squidex.Core/Schemas/Validators/PatternValidator.cs
  2. 26
      src/Squidex.Core/Schemas/Validators/StringLengthValidator.cs
  3. 4
      src/Squidex.Infrastructure/CQRS/Commands/EnrichWithTimestampHandler.cs
  4. 4
      src/Squidex.Infrastructure/Reflection/PropertyAccessor.cs
  5. 17
      src/Squidex.Read.MongoDb/Utils/EntityMapper.cs
  6. 22
      src/Squidex.Read/Schemas/SchemaHistoryEventsCreator.cs
  7. 13
      src/Squidex/Pipeline/CommandHandlers/EnrichWithActorHandler.cs
  8. 4
      src/Squidex/Pipeline/CommandHandlers/EnrichWithAppIdHandler.cs
  9. 4
      src/Squidex/Pipeline/CommandHandlers/EnrichWithSchemaIdHandler.cs
  10. 4
      src/Squidex/Pipeline/CommandHandlers/SetVersionAsETagHandler.cs
  11. 24
      tests/Squidex.Infrastructure.Tests/CQRS/Commands/DefaultDomainObjectFactoryTests.cs
  12. 4
      tests/Squidex.Infrastructure.Tests/CQRS/Commands/DefaultDomainObjectRepositoryTests.cs
  13. 2
      tests/Squidex.Infrastructure.Tests/Json/ConverterContractResolverTests.cs
  14. 5
      tests/Squidex.Write.Tests/TestHelpers/HandlerTestBase.cs

24
src/Squidex.Core/Schemas/Validators/PatternValidator.cs

@ -30,22 +30,18 @@ namespace Squidex.Core.Schemas.Validators
public Task ValidateAsync(object value, ICollection<string> errors) public Task ValidateAsync(object value, ICollection<string> errors)
{ {
var stringValue = value as string; if (value is string stringValue)
if (stringValue == null)
{
return TaskHelper.Done;
}
if (!regex.IsMatch(stringValue))
{ {
if (string.IsNullOrWhiteSpace(errorMessage)) if (!regex.IsMatch(stringValue))
{
errors.Add("<FIELD> is not valid");
}
else
{ {
errors.Add(errorMessage); if (string.IsNullOrWhiteSpace(errorMessage))
{
errors.Add("<FIELD> is not valid");
}
else
{
errors.Add(errorMessage);
}
} }
} }

26
src/Squidex.Core/Schemas/Validators/StringLengthValidator.cs

@ -11,6 +11,8 @@ using System.Collections.Generic;
using System.Threading.Tasks; using System.Threading.Tasks;
using Squidex.Infrastructure.Tasks; using Squidex.Infrastructure.Tasks;
// ReSharper disable InvertIf
namespace Squidex.Core.Schemas.Validators namespace Squidex.Core.Schemas.Validators
{ {
public class StringLengthValidator : IValidator public class StringLengthValidator : IValidator
@ -31,21 +33,17 @@ namespace Squidex.Core.Schemas.Validators
public Task ValidateAsync(object value, ICollection<string> errors) public Task ValidateAsync(object value, ICollection<string> errors)
{ {
var stringValue = value as string; if (value is string stringValue)
if (stringValue == null)
{
return TaskHelper.Done;
}
if (minLength.HasValue && stringValue.Length < minLength.Value)
{
errors.Add($"<FIELD> must have more than '{minLength}' characters");
}
if (maxLength.HasValue && stringValue.Length > maxLength.Value)
{ {
errors.Add($"<FIELD> must have less than '{maxLength}' characters"); if (minLength.HasValue && stringValue.Length < minLength.Value)
{
errors.Add($"<FIELD> must have more than '{minLength}' characters");
}
if (maxLength.HasValue && stringValue.Length > maxLength.Value)
{
errors.Add($"<FIELD> must have less than '{maxLength}' characters");
}
} }
return TaskHelper.Done; return TaskHelper.Done;

4
src/Squidex.Infrastructure/CQRS/Commands/EnrichWithTimestampHandler.cs

@ -25,9 +25,7 @@ namespace Squidex.Infrastructure.CQRS.Commands
public Task<bool> HandleAsync(CommandContext context) public Task<bool> HandleAsync(CommandContext context)
{ {
var timestampCommand = context.Command as ITimestampCommand; if (context.Command is ITimestampCommand timestampCommand)
if (timestampCommand != null)
{ {
timestampCommand.Timestamp = clock.GetCurrentInstant(); timestampCommand.Timestamp = clock.GetCurrentInstant();
} }

4
src/Squidex.Infrastructure/Reflection/PropertyAccessor.cs

@ -26,7 +26,7 @@ namespace Squidex.Infrastructure.Reflection
} }
else else
{ {
getMethod = x => throw new NotSupportedException(); getMethod = x => { throw new NotSupportedException(); };
} }
if (propertyInfo.CanWrite) if (propertyInfo.CanWrite)
@ -35,7 +35,7 @@ namespace Squidex.Infrastructure.Reflection
} }
else else
{ {
setMethod = (x, y) => throw new NotSupportedException(); setMethod = (x, y) => { throw new NotSupportedException(); };
} }
} }

17
src/Squidex.Read.MongoDb/Utils/EntityMapper.cs

@ -58,9 +58,7 @@ namespace Squidex.Read.MongoDb.Utils
private static void SetVersion(EnvelopeHeaders headers, MongoEntity entity) private static void SetVersion(EnvelopeHeaders headers, MongoEntity entity)
{ {
var withVersion = entity as IEntityWithVersion; if (entity is IEntityWithVersion withVersion)
if (withVersion != null)
{ {
withVersion.Version = headers.EventStreamNumber(); withVersion.Version = headers.EventStreamNumber();
} }
@ -68,9 +66,7 @@ namespace Squidex.Read.MongoDb.Utils
private static void SetCreatedBy(SquidexEvent @event, MongoEntity entity) private static void SetCreatedBy(SquidexEvent @event, MongoEntity entity)
{ {
var withCreatedBy = entity as IEntityWithCreatedBy; if (entity is IEntityWithCreatedBy withCreatedBy)
if (withCreatedBy != null)
{ {
withCreatedBy.CreatedBy = @event.Actor; withCreatedBy.CreatedBy = @event.Actor;
} }
@ -78,9 +74,7 @@ namespace Squidex.Read.MongoDb.Utils
private static void SetLastModifiedBy(SquidexEvent @event, MongoEntity entity) private static void SetLastModifiedBy(SquidexEvent @event, MongoEntity entity)
{ {
var withModifiedBy = entity as IEntityWithLastModifiedBy; if (entity is IEntityWithLastModifiedBy withModifiedBy)
if (withModifiedBy != null)
{ {
withModifiedBy.LastModifiedBy = @event.Actor; withModifiedBy.LastModifiedBy = @event.Actor;
} }
@ -88,10 +82,7 @@ namespace Squidex.Read.MongoDb.Utils
private static void SetAppId(SquidexEvent @event, MongoEntity entity) private static void SetAppId(SquidexEvent @event, MongoEntity entity)
{ {
var appEntity = entity as IAppRefEntity; if (entity is IAppRefEntity appEntity && @event is AppEvent appEvent)
var appEvent = @event as AppEvent;
if (appEntity != null && appEvent != null)
{ {
appEntity.AppId = appEvent.AppId.Id; appEntity.AppId = appEvent.AppId.Id;
} }

22
src/Squidex.Read/Schemas/SchemaHistoryEventsCreator.cs

@ -64,25 +64,21 @@ namespace Squidex.Read.Schemas
protected override Task<HistoryEventToStore> CreateEventCoreAsync(Envelope<IEvent> @event) protected override Task<HistoryEventToStore> CreateEventCoreAsync(Envelope<IEvent> @event)
{ {
var schemaEvent = @event.Payload as SchemaEvent; if (@event.Payload is SchemaEvent schemaEvent)
if (schemaEvent == null)
{ {
return Task.FromResult<HistoryEventToStore>(null); string channel = $"schemas.{schemaEvent.SchemaId.Name}";
}
string channel = $"schemas.{schemaEvent.SchemaId.Name}"; var result = ForEvent(@event.Payload, channel).AddParameter("Name", schemaEvent.SchemaId.Name);
var result = ForEvent(@event.Payload, channel).AddParameter("Name", schemaEvent.SchemaId.Name); if (schemaEvent is FieldEvent fieldEvent)
{
result.AddParameter("Field", fieldEvent.FieldId.Name);
}
var fieldEvent = schemaEvent as FieldEvent; return Task.FromResult(result);
if (fieldEvent != null)
{
result.AddParameter("Field", fieldEvent.FieldId.Name);
} }
return Task.FromResult(result); return Task.FromResult<HistoryEventToStore>(null);
} }
} }
} }

13
src/Squidex/Pipeline/CommandHandlers/EnrichWithActorHandler.cs

@ -30,15 +30,20 @@ namespace Squidex.Pipeline.CommandHandlers
public Task<bool> HandleAsync(CommandContext context) public Task<bool> HandleAsync(CommandContext context)
{ {
var squidexCommand = context.Command as SquidexCommand; if (context.Command is SquidexCommand squidexCommand)
if (squidexCommand != null)
{ {
var actorToken = var actorToken =
FindActorFromSubject() ?? FindActorFromSubject() ??
FindActorFromClient(); FindActorFromClient();
squidexCommand.Actor = actorToken ?? throw new SecurityException("No actor with subject or client id available"); #pragma warning disable
if (actorToken == null)
{
throw new SecurityException("No actor with subject or client id available");
}
#pragma warning enable
squidexCommand.Actor = actorToken;
} }
return TaskHelper.False; return TaskHelper.False;

4
src/Squidex/Pipeline/CommandHandlers/EnrichWithAppIdHandler.cs

@ -29,9 +29,7 @@ namespace Squidex.Pipeline.CommandHandlers
public Task<bool> HandleAsync(CommandContext context) public Task<bool> HandleAsync(CommandContext context)
{ {
var appCommand = context.Command as AppCommand; if (context.Command is AppCommand appCommand)
if (appCommand != null)
{ {
var appFeature = httpContextAccessor.HttpContext.Features.Get<IAppFeature>(); var appFeature = httpContextAccessor.HttpContext.Features.Get<IAppFeature>();

4
src/Squidex/Pipeline/CommandHandlers/EnrichWithSchemaIdHandler.cs

@ -33,9 +33,7 @@ namespace Squidex.Pipeline.CommandHandlers
public async Task<bool> HandleAsync(CommandContext context) public async Task<bool> HandleAsync(CommandContext context)
{ {
var schemaCommand = context.Command as SchemaCommand; if (context.Command is SchemaCommand schemaCommand)
if (schemaCommand != null)
{ {
var routeValues = actionContextAccessor.ActionContext.RouteData.Values; var routeValues = actionContextAccessor.ActionContext.RouteData.Values;

4
src/Squidex/Pipeline/CommandHandlers/SetVersionAsETagHandler.cs

@ -25,9 +25,7 @@ namespace Squidex.Pipeline.CommandHandlers
public Task<bool> HandleAsync(CommandContext context) public Task<bool> HandleAsync(CommandContext context)
{ {
var result = context.Result<object>() as EntitySavedResult; if (context.Result<object>() is EntitySavedResult result)
if (result != null)
{ {
httpContextAccessor.HttpContext.Response.Headers["ETag"] = new StringValues(result.Version.ToString()); httpContextAccessor.HttpContext.Response.Headers["ETag"] = new StringValues(result.Version.ToString());
} }

24
tests/Squidex.Infrastructure.Tests/CQRS/Commands/DefaultDomainObjectFactoryTests.cs

@ -19,7 +19,8 @@ namespace Squidex.Infrastructure.CQRS.Commands
{ {
private sealed class DO : DomainObjectBase private sealed class DO : DomainObjectBase
{ {
public DO(Guid id, int version) : base(id, version) public DO(Guid id, int version)
: base(id, version)
{ {
} }
@ -35,7 +36,7 @@ namespace Squidex.Infrastructure.CQRS.Commands
var factoryFunction = new DomainObjectFactoryFunction<DO>(passedId => var factoryFunction = new DomainObjectFactoryFunction<DO>(passedId =>
{ {
return new DO(passedId, 0); return new DO(passedId, -1);
}); });
serviceProvider.Setup(x => x.GetService(typeof(DomainObjectFactoryFunction<DO>))).Returns(factoryFunction); serviceProvider.Setup(x => x.GetService(typeof(DomainObjectFactoryFunction<DO>))).Returns(factoryFunction);
@ -47,7 +48,24 @@ namespace Squidex.Infrastructure.CQRS.Commands
var domainObject = sut.CreateNew(typeof(DO), id); var domainObject = sut.CreateNew(typeof(DO), id);
Assert.Equal(id, domainObject.Id); Assert.Equal(id, domainObject.Id);
Assert.Equal(0, domainObject.Version); Assert.Equal(-1, domainObject.Version);
}
[Fact]
public void Should_throw_if_new_entity_has_invalid_version()
{
var serviceProvider = new Mock<IServiceProvider>();
var factoryFunction = new DomainObjectFactoryFunction<DO>(passedId =>
{
return new DO(passedId, 0);
});
serviceProvider.Setup(x => x.GetService(typeof(DomainObjectFactoryFunction<DO>))).Returns(factoryFunction);
var sut = new DefaultDomainObjectFactory(serviceProvider.Object);
Assert.Throws<InvalidOperationException>(() => sut.CreateNew(typeof(DO), Guid.NewGuid()));
} }
} }
} }

4
tests/Squidex.Infrastructure.Tests/CQRS/Commands/DefaultDomainObjectRepositoryTests.cs

@ -141,7 +141,7 @@ namespace Squidex.Infrastructure.CQRS.Commands
eventDataFormatter.Setup(x => x.ToEventData(It.Is<Envelope<IEvent>>(e => e.Payload == event1), commitId)).Returns(eventData1); eventDataFormatter.Setup(x => x.ToEventData(It.Is<Envelope<IEvent>>(e => e.Payload == event1), commitId)).Returns(eventData1);
eventDataFormatter.Setup(x => x.ToEventData(It.Is<Envelope<IEvent>>(e => e.Payload == event2), commitId)).Returns(eventData2); eventDataFormatter.Setup(x => x.ToEventData(It.Is<Envelope<IEvent>>(e => e.Payload == event2), commitId)).Returns(eventData2);
eventStore.Setup(x => x.AppendEventsAsync(commitId, streamName, 122, It.Is<IEnumerable<EventData>>(e => e.Count() == 2))) eventStore.Setup(x => x.AppendEventsAsync(commitId, streamName, 123, It.Is<IEnumerable<EventData>>(e => e.Count() == 2)))
.Returns(TaskHelper.Done) .Returns(TaskHelper.Done)
.Verifiable(); .Verifiable();
@ -167,7 +167,7 @@ namespace Squidex.Infrastructure.CQRS.Commands
eventDataFormatter.Setup(x => x.ToEventData(It.Is<Envelope<IEvent>>(e => e.Payload == event1), commitId)).Returns(eventData1); eventDataFormatter.Setup(x => x.ToEventData(It.Is<Envelope<IEvent>>(e => e.Payload == event1), commitId)).Returns(eventData1);
eventDataFormatter.Setup(x => x.ToEventData(It.Is<Envelope<IEvent>>(e => e.Payload == event2), commitId)).Returns(eventData2); eventDataFormatter.Setup(x => x.ToEventData(It.Is<Envelope<IEvent>>(e => e.Payload == event2), commitId)).Returns(eventData2);
eventStore.Setup(x => x.AppendEventsAsync(commitId, streamName, 122, new List<EventData> { eventData1, eventData2 })) eventStore.Setup(x => x.AppendEventsAsync(commitId, streamName, 123, new List<EventData> { eventData1, eventData2 }))
.Throws(new WrongEventVersionException(1, 2)) .Throws(new WrongEventVersionException(1, 2))
.Verifiable(); .Verifiable();

2
tests/Squidex.Infrastructure.Tests/Json/ConverterContractResolverTests.cs

@ -52,7 +52,7 @@ namespace Squidex.Infrastructure.Json
var json = JsonConvert.SerializeObject(new MyClass { MyProperty = value }, serializerSettings); var json = JsonConvert.SerializeObject(new MyClass { MyProperty = value }, serializerSettings);
Assert.Equal(@"{ ""MyProperty"": ""TODAY"" }", json); Assert.Equal(@"{""myProperty"":""TODAY""}", json);
} }
[Fact] [Fact]

5
tests/Squidex.Write.Tests/TestHelpers/HandlerTestBase.cs

@ -13,6 +13,8 @@ using Squidex.Infrastructure;
using Squidex.Infrastructure.CQRS; using Squidex.Infrastructure.CQRS;
using Squidex.Infrastructure.CQRS.Commands; using Squidex.Infrastructure.CQRS.Commands;
#pragma warning disable IDE0019
namespace Squidex.Write.TestHelpers namespace Squidex.Write.TestHelpers
{ {
public abstract class HandlerTestBase<T> where T : DomainObjectBase public abstract class HandlerTestBase<T> where T : DomainObjectBase
@ -146,3 +148,6 @@ namespace Squidex.Write.TestHelpers
} }
} }
} }
#pragma warning restore IDE0019
Loading…
Cancel
Save