Browse Source

RuleGrainTests

pull/249/head
Sebastian Stehle 8 years ago
parent
commit
1a562da782
  1. 13
      src/Squidex.Domain.Apps.Entities/Rules/RuleGrain.cs
  2. 580
      tests/Squidex.Domain.Apps.Entities.Tests/Apps/AppCommandMiddlewareTests.cs
  3. 798
      tests/Squidex.Domain.Apps.Entities.Tests/Apps/AppDomainObjectTests.cs
  4. 290
      tests/Squidex.Domain.Apps.Entities.Tests/Assets/AssetCommandMiddlewareTests.cs
  5. 440
      tests/Squidex.Domain.Apps.Entities.Tests/Assets/AssetDomainObjectTests.cs
  6. 464
      tests/Squidex.Domain.Apps.Entities.Tests/Contents/ContentCommandMiddlewareTests.cs
  7. 608
      tests/Squidex.Domain.Apps.Entities.Tests/Contents/ContentDomainObjectTests.cs
  8. 118
      tests/Squidex.Domain.Apps.Entities.Tests/Rules/RuleCommandMiddlewareTests.cs
  9. 2
      tests/Squidex.Domain.Apps.Entities.Tests/Rules/RuleDequeuerTests.cs
  10. 256
      tests/Squidex.Domain.Apps.Entities.Tests/Rules/RuleDomainObjectTests.cs
  11. 227
      tests/Squidex.Domain.Apps.Entities.Tests/Rules/RuleGrainTests.cs
  12. 560
      tests/Squidex.Domain.Apps.Entities.Tests/Schemas/SchemaCommandMiddlewareTests.cs
  13. 1330
      tests/Squidex.Domain.Apps.Entities.Tests/Schemas/SchemaDomainObjectTests.cs
  14. 136
      tests/Squidex.Domain.Apps.Entities.Tests/TestHelpers/HandlerTestBase.cs

13
src/Squidex.Domain.Apps.Entities/Rules/RuleGrain.cs

@ -7,6 +7,8 @@
using System; using System;
using System.Threading.Tasks; using System.Threading.Tasks;
using Orleans.Core;
using Orleans.Runtime;
using Squidex.Domain.Apps.Entities.Rules.Commands; using Squidex.Domain.Apps.Entities.Rules.Commands;
using Squidex.Domain.Apps.Entities.Rules.Guards; using Squidex.Domain.Apps.Entities.Rules.Guards;
using Squidex.Domain.Apps.Entities.Rules.State; using Squidex.Domain.Apps.Entities.Rules.State;
@ -21,12 +23,17 @@ using Squidex.Infrastructure.States;
namespace Squidex.Domain.Apps.Entities.Rules namespace Squidex.Domain.Apps.Entities.Rules
{ {
public sealed class RuleGrain : DomainObjectGrain<RuleState>, IRuleGrain public class RuleGrain : DomainObjectGrain<RuleState>, IRuleGrain
{ {
private readonly IAppProvider appProvider; private readonly IAppProvider appProvider;
public RuleGrain(IStore<Guid> store, IAppProvider appProvider) public RuleGrain(IStore<Guid> store, IAppProvider appProvider)
: base(store) : this(store, appProvider, null, null)
{
}
protected RuleGrain(IStore<Guid> store, IAppProvider appProvider, IGrainIdentity identity, IGrainRuntime runtime)
: base(store, identity, runtime)
{ {
Guard.NotNull(appProvider, nameof(appProvider)); Guard.NotNull(appProvider, nameof(appProvider));
@ -116,7 +123,7 @@ namespace Squidex.Domain.Apps.Entities.Rules
private void VerifyNotDeleted() private void VerifyNotDeleted()
{ {
if (Snapshot.IsDeleted || Snapshot.RuleDef == null) if (Snapshot.IsDeleted)
{ {
throw new DomainException("Webhook has already been deleted."); throw new DomainException("Webhook has already been deleted.");
} }

580
tests/Squidex.Domain.Apps.Entities.Tests/Apps/AppCommandMiddlewareTests.cs

@ -1,291 +1,291 @@
// ========================================================================== //// ==========================================================================
// Squidex Headless CMS //// Squidex Headless CMS
// ========================================================================== //// ==========================================================================
// Copyright (c) Squidex UG (haftungsbeschränkt) //// Copyright (c) Squidex UG (haftungsbeschränkt)
// All rights reserved. Licensed under the MIT license. //// All rights reserved. Licensed under the MIT license.
// ========================================================================== //// ==========================================================================
using System; //using System;
using System.Threading.Tasks; //using System.Threading.Tasks;
using FakeItEasy; //using FakeItEasy;
using Squidex.Domain.Apps.Entities.Apps.Commands; //using Squidex.Domain.Apps.Entities.Apps.Commands;
using Squidex.Domain.Apps.Entities.Apps.Services; //using Squidex.Domain.Apps.Entities.Apps.Services;
using Squidex.Domain.Apps.Entities.Apps.Services.Implementations; //using Squidex.Domain.Apps.Entities.Apps.Services.Implementations;
using Squidex.Domain.Apps.Entities.TestHelpers; //using Squidex.Domain.Apps.Entities.TestHelpers;
using Squidex.Infrastructure; //using Squidex.Infrastructure;
using Squidex.Infrastructure.Commands; //using Squidex.Infrastructure.Commands;
using Squidex.Infrastructure.States; //using Squidex.Infrastructure.States;
using Squidex.Shared.Users; //using Squidex.Shared.Users;
using Xunit; //using Xunit;
namespace Squidex.Domain.Apps.Entities.Apps //namespace Squidex.Domain.Apps.Entities.Apps
{ //{
public class AppCommandMiddlewareTests : HandlerTestBase<AppDomainObject> // public class AppCommandMiddlewareTests : HandlerTestBase<AppDomainObject>
{ // {
private readonly IAppProvider appProvider = A.Fake<IAppProvider>(); // private readonly IAppProvider appProvider = A.Fake<IAppProvider>();
private readonly IAppPlansProvider appPlansProvider = A.Fake<IAppPlansProvider>(); // private readonly IAppPlansProvider appPlansProvider = A.Fake<IAppPlansProvider>();
private readonly IAppPlanBillingManager appPlansBillingManager = A.Fake<IAppPlanBillingManager>(); // private readonly IAppPlanBillingManager appPlansBillingManager = A.Fake<IAppPlanBillingManager>();
private readonly IUserResolver userResolver = A.Fake<IUserResolver>(); // private readonly IUserResolver userResolver = A.Fake<IUserResolver>();
private readonly Language language = Language.DE; // private readonly Language language = Language.DE;
private readonly string contributorId = Guid.NewGuid().ToString(); // private readonly string contributorId = Guid.NewGuid().ToString();
private readonly string clientName = "client"; // private readonly string clientName = "client";
private readonly Guid patternId = Guid.NewGuid(); // private readonly Guid patternId = Guid.NewGuid();
private readonly AppDomainObject app = new AppDomainObject(new InitialPatterns()); // private readonly AppDomainObject app = new AppDomainObject(new InitialPatterns());
private readonly AppCommandMiddleware sut; // private readonly AppCommandMiddleware sut;
protected override Guid Id // protected override Guid Id
{ // {
get { return AppId; } // get { return AppId; }
} // }
public AppCommandMiddlewareTests() // public AppCommandMiddlewareTests()
{ // {
A.CallTo(() => appProvider.GetAppAsync(AppName)) // A.CallTo(() => appProvider.GetAppAsync(AppName))
.Returns((IAppEntity)null); // .Returns((IAppEntity)null);
A.CallTo(() => userResolver.FindByIdAsync(contributorId)) // A.CallTo(() => userResolver.FindByIdAsync(contributorId))
.Returns(A.Fake<IUser>()); // .Returns(A.Fake<IUser>());
sut = new AppCommandMiddleware(Handler, appProvider, appPlansProvider, appPlansBillingManager, userResolver); // sut = new AppCommandMiddleware(Handler, appProvider, appPlansProvider, appPlansBillingManager, userResolver);
app.ActivateAsync(Id, A.Fake<IStore<Guid>>()); // app.ActivateAsync(Id, A.Fake<IStore<Guid>>());
} // }
[Fact] // [Fact]
public async Task Create_should_create_domain_object() // public async Task Create_should_create_domain_object()
{ // {
var context = CreateContextForCommand(new CreateApp { Name = AppName, AppId = AppId }); // var context = CreateContextForCommand(new CreateApp { Name = AppName, AppId = AppId });
await TestCreate(app, async _ => // await TestCreate(app, async _ =>
{ // {
await sut.HandleAsync(context); // await sut.HandleAsync(context);
}); // });
Assert.Equal(AppId, context.Result<EntityCreatedResult<Guid>>().IdOrValue); // Assert.Equal(AppId, context.Result<EntityCreatedResult<Guid>>().IdOrValue);
} // }
[Fact] // [Fact]
public async Task AssignContributor_should_update_domain_object_if_user_found() // public async Task AssignContributor_should_update_domain_object_if_user_found()
{ // {
A.CallTo(() => appPlansProvider.GetPlan(null)) // A.CallTo(() => appPlansProvider.GetPlan(null))
.Returns(new ConfigAppLimitsPlan { MaxContributors = -1 }); // .Returns(new ConfigAppLimitsPlan { MaxContributors = -1 });
CreateApp(); // CreateApp();
var context = CreateContextForCommand(new AssignContributor { ContributorId = contributorId }); // var context = CreateContextForCommand(new AssignContributor { ContributorId = contributorId });
await TestUpdate(app, async _ => // await TestUpdate(app, async _ =>
{ // {
await sut.HandleAsync(context); // await sut.HandleAsync(context);
}); // });
} // }
[Fact] // [Fact]
public async Task RemoveContributor_should_update_domain_object() // public async Task RemoveContributor_should_update_domain_object()
{ // {
CreateApp() // CreateApp()
.AssignContributor(CreateCommand(new AssignContributor { ContributorId = contributorId })); // .AssignContributor(CreateCommand(new AssignContributor { ContributorId = contributorId }));
var context = CreateContextForCommand(new RemoveContributor { ContributorId = contributorId }); // var context = CreateContextForCommand(new RemoveContributor { ContributorId = contributorId });
await TestUpdate(app, async _ => // await TestUpdate(app, async _ =>
{ // {
await sut.HandleAsync(context); // await sut.HandleAsync(context);
}); // });
} // }
[Fact] // [Fact]
public async Task AttachClient_should_update_domain_object() // public async Task AttachClient_should_update_domain_object()
{ // {
CreateApp(); // CreateApp();
var context = CreateContextForCommand(new AttachClient { Id = clientName }); // var context = CreateContextForCommand(new AttachClient { Id = clientName });
await TestUpdate(app, async _ => // await TestUpdate(app, async _ =>
{ // {
await sut.HandleAsync(context); // await sut.HandleAsync(context);
}); // });
} // }
[Fact] // [Fact]
public async Task RenameClient_should_update_domain_object() // public async Task RenameClient_should_update_domain_object()
{ // {
CreateApp() // CreateApp()
.AttachClient(CreateCommand(new AttachClient { Id = clientName })); // .AttachClient(CreateCommand(new AttachClient { Id = clientName }));
var context = CreateContextForCommand(new UpdateClient { Id = clientName, Name = "New Name" }); // var context = CreateContextForCommand(new UpdateClient { Id = clientName, Name = "New Name" });
await TestUpdate(app, async _ => // await TestUpdate(app, async _ =>
{ // {
await sut.HandleAsync(context); // await sut.HandleAsync(context);
}); // });
} // }
[Fact] // [Fact]
public async Task RevokeClient_should_update_domain_object() // public async Task RevokeClient_should_update_domain_object()
{ // {
CreateApp() // CreateApp()
.AttachClient(CreateCommand(new AttachClient { Id = clientName })); // .AttachClient(CreateCommand(new AttachClient { Id = clientName }));
var context = CreateContextForCommand(new RevokeClient { Id = clientName }); // var context = CreateContextForCommand(new RevokeClient { Id = clientName });
await TestUpdate(app, async _ => // await TestUpdate(app, async _ =>
{ // {
await sut.HandleAsync(context); // await sut.HandleAsync(context);
}); // });
} // }
[Fact] // [Fact]
public async Task ChangePlan_should_update_domain_object() // public async Task ChangePlan_should_update_domain_object()
{ // {
A.CallTo(() => appPlansProvider.IsConfiguredPlan("my-plan")) // A.CallTo(() => appPlansProvider.IsConfiguredPlan("my-plan"))
.Returns(true); // .Returns(true);
CreateApp(); // CreateApp();
var context = CreateContextForCommand(new ChangePlan { PlanId = "my-plan" }); // var context = CreateContextForCommand(new ChangePlan { PlanId = "my-plan" });
await TestUpdate(app, async _ => // await TestUpdate(app, async _ =>
{ // {
await sut.HandleAsync(context); // await sut.HandleAsync(context);
}); // });
A.CallTo(() => appPlansBillingManager.ChangePlanAsync(User.Identifier, AppId, AppName, "my-plan")) // A.CallTo(() => appPlansBillingManager.ChangePlanAsync(User.Identifier, AppId, AppName, "my-plan"))
.MustHaveHappened(); // .MustHaveHappened();
} // }
[Fact] // [Fact]
public async Task ChangePlan_should_not_make_update_for_redirect_result() // public async Task ChangePlan_should_not_make_update_for_redirect_result()
{ // {
A.CallTo(() => appPlansProvider.IsConfiguredPlan("my-plan")) // A.CallTo(() => appPlansProvider.IsConfiguredPlan("my-plan"))
.Returns(true); // .Returns(true);
A.CallTo(() => appPlansBillingManager.ChangePlanAsync(User.Identifier, AppId, AppName, "my-plan")) // A.CallTo(() => appPlansBillingManager.ChangePlanAsync(User.Identifier, AppId, AppName, "my-plan"))
.Returns(CreateRedirectResult()); // .Returns(CreateRedirectResult());
CreateApp(); // CreateApp();
var context = CreateContextForCommand(new ChangePlan { PlanId = "my-plan" }); // var context = CreateContextForCommand(new ChangePlan { PlanId = "my-plan" });
await TestUpdate(app, async _ => // await TestUpdate(app, async _ =>
{ // {
await sut.HandleAsync(context); // await sut.HandleAsync(context);
}); // });
Assert.Null(app.Snapshot.Plan); // Assert.Null(app.Snapshot.Plan);
} // }
[Fact] // [Fact]
public async Task ChangePlan_should_not_call_billing_manager_for_callback() // public async Task ChangePlan_should_not_call_billing_manager_for_callback()
{ // {
A.CallTo(() => appPlansProvider.IsConfiguredPlan("my-plan")) // A.CallTo(() => appPlansProvider.IsConfiguredPlan("my-plan"))
.Returns(true); // .Returns(true);
CreateApp(); // CreateApp();
var context = CreateContextForCommand(new ChangePlan { PlanId = "my-plan", FromCallback = true }); // var context = CreateContextForCommand(new ChangePlan { PlanId = "my-plan", FromCallback = true });
await TestUpdate(app, async _ => // await TestUpdate(app, async _ =>
{ // {
await sut.HandleAsync(context); // await sut.HandleAsync(context);
}); // });
A.CallTo(() => appPlansBillingManager.ChangePlanAsync(User.Identifier, AppId, AppName, "my-plan")) // A.CallTo(() => appPlansBillingManager.ChangePlanAsync(User.Identifier, AppId, AppName, "my-plan"))
.MustNotHaveHappened(); // .MustNotHaveHappened();
} // }
[Fact] // [Fact]
public async Task AddLanguage_should_update_domain_object() // public async Task AddLanguage_should_update_domain_object()
{ // {
CreateApp(); // CreateApp();
var context = CreateContextForCommand(new AddLanguage { Language = language }); // var context = CreateContextForCommand(new AddLanguage { Language = language });
await TestUpdate(app, async _ => // await TestUpdate(app, async _ =>
{ // {
await sut.HandleAsync(context); // await sut.HandleAsync(context);
}); // });
} // }
[Fact] // [Fact]
public async Task RemoveLanguage_should_update_domain_object() // public async Task RemoveLanguage_should_update_domain_object()
{ // {
CreateApp() // CreateApp()
.AddLanguage(CreateCommand(new AddLanguage { Language = language })); // .AddLanguage(CreateCommand(new AddLanguage { Language = language }));
var context = CreateContextForCommand(new RemoveLanguage { Language = language }); // var context = CreateContextForCommand(new RemoveLanguage { Language = language });
await TestUpdate(app, async _ => // await TestUpdate(app, async _ =>
{ // {
await sut.HandleAsync(context); // await sut.HandleAsync(context);
}); // });
} // }
[Fact] // [Fact]
public async Task UpdateLanguage_should_update_domain_object() // public async Task UpdateLanguage_should_update_domain_object()
{ // {
CreateApp() // CreateApp()
.AddLanguage(CreateCommand(new AddLanguage { Language = language })); // .AddLanguage(CreateCommand(new AddLanguage { Language = language }));
var context = CreateContextForCommand(new UpdateLanguage { Language = language }); // var context = CreateContextForCommand(new UpdateLanguage { Language = language });
await TestUpdate(app, async _ => // await TestUpdate(app, async _ =>
{ // {
await sut.HandleAsync(context); // await sut.HandleAsync(context);
}); // });
} // }
[Fact] // [Fact]
public async Task AddPattern_should_update_domain_object() // public async Task AddPattern_should_update_domain_object()
{ // {
CreateApp(); // CreateApp();
var context = CreateContextForCommand(new AddPattern { Name = "Any", Pattern = ".*" }); // var context = CreateContextForCommand(new AddPattern { Name = "Any", Pattern = ".*" });
await TestUpdate(app, async _ => // await TestUpdate(app, async _ =>
{ // {
await sut.HandleAsync(context); // await sut.HandleAsync(context);
}); // });
} // }
[Fact] // [Fact]
public async Task UpdatePattern_should_update_domain() // public async Task UpdatePattern_should_update_domain()
{ // {
CreateApp() // CreateApp()
.AddPattern(CreateCommand(new AddPattern { PatternId = patternId, Name = "Any", Pattern = "." })); // .AddPattern(CreateCommand(new AddPattern { PatternId = patternId, Name = "Any", Pattern = "." }));
var context = CreateContextForCommand(new UpdatePattern { PatternId = patternId, Name = "Number", Pattern = "[0-9]" }); // var context = CreateContextForCommand(new UpdatePattern { PatternId = patternId, Name = "Number", Pattern = "[0-9]" });
await TestUpdate(app, async _ => // await TestUpdate(app, async _ =>
{ // {
await sut.HandleAsync(context); // await sut.HandleAsync(context);
}); // });
} // }
[Fact] // [Fact]
public async Task DeletePattern_should_update_domain_object() // public async Task DeletePattern_should_update_domain_object()
{ // {
CreateApp() // CreateApp()
.AddPattern(CreateCommand(new AddPattern { PatternId = patternId, Name = "Any", Pattern = "." })); // .AddPattern(CreateCommand(new AddPattern { PatternId = patternId, Name = "Any", Pattern = "." }));
var context = CreateContextForCommand(new DeletePattern { PatternId = patternId }); // var context = CreateContextForCommand(new DeletePattern { PatternId = patternId });
await TestUpdate(app, async _ => // await TestUpdate(app, async _ =>
{ // {
await sut.HandleAsync(context); // await sut.HandleAsync(context);
}); // });
} // }
private AppDomainObject CreateApp() // private AppDomainObject CreateApp()
{ // {
app.Create(CreateCommand(new CreateApp { AppId = AppId, Name = AppName })); // app.Create(CreateCommand(new CreateApp { AppId = AppId, Name = AppName }));
return app; // return app;
} // }
private static Task<IChangePlanResult> CreateRedirectResult() // private static Task<IChangePlanResult> CreateRedirectResult()
{ // {
return Task.FromResult<IChangePlanResult>(new RedirectToCheckoutResult(new Uri("http://squidex.io"))); // return Task.FromResult<IChangePlanResult>(new RedirectToCheckoutResult(new Uri("http://squidex.io")));
} // }
} // }
} //}

798
tests/Squidex.Domain.Apps.Entities.Tests/Apps/AppDomainObjectTests.cs

@ -1,399 +1,399 @@
// ========================================================================== //// ==========================================================================
// Squidex Headless CMS //// Squidex Headless CMS
// ========================================================================== //// ==========================================================================
// Copyright (c) Squidex UG (haftungsbeschränkt) //// Copyright (c) Squidex UG (haftungsbeschränkt)
// All rights reserved. Licensed under the MIT license. //// All rights reserved. Licensed under the MIT license.
// ========================================================================== //// ==========================================================================
using System; //using System;
using System.Collections.Generic; //using System.Collections.Generic;
using System.Linq; //using System.Linq;
using FakeItEasy; //using FakeItEasy;
using Squidex.Domain.Apps.Core.Apps; //using Squidex.Domain.Apps.Core.Apps;
using Squidex.Domain.Apps.Entities.Apps.Commands; //using Squidex.Domain.Apps.Entities.Apps.Commands;
using Squidex.Domain.Apps.Entities.TestHelpers; //using Squidex.Domain.Apps.Entities.TestHelpers;
using Squidex.Domain.Apps.Events.Apps; //using Squidex.Domain.Apps.Events.Apps;
using Squidex.Infrastructure; //using Squidex.Infrastructure;
using Squidex.Infrastructure.States; //using Squidex.Infrastructure.States;
using Xunit; //using Xunit;
namespace Squidex.Domain.Apps.Entities.Apps //namespace Squidex.Domain.Apps.Entities.Apps
{ //{
public class AppDomainObjectTests : HandlerTestBase<AppDomainObject> // public class AppDomainObjectTests : HandlerTestBase<AppDomainObject>
{ // {
private readonly string contributorId = Guid.NewGuid().ToString(); // private readonly string contributorId = Guid.NewGuid().ToString();
private readonly string clientId = "client"; // private readonly string clientId = "client";
private readonly string clientNewName = "My Client"; // private readonly string clientNewName = "My Client";
private readonly string planId = "premium"; // private readonly string planId = "premium";
private readonly Guid patternId = Guid.NewGuid(); // private readonly Guid patternId = Guid.NewGuid();
private readonly AppDomainObject sut = new AppDomainObject(new InitialPatterns()); // private readonly AppDomainObject sut = new AppDomainObject(new InitialPatterns());
protected override Guid Id // protected override Guid Id
{ // {
get { return AppId; } // get { return AppId; }
} // }
public AppDomainObjectTests() // public AppDomainObjectTests()
{ // {
sut.ActivateAsync(Id, A.Fake<IStore<Guid>>()); // sut.ActivateAsync(Id, A.Fake<IStore<Guid>>());
} // }
[Fact] // [Fact]
public void Create_should_throw_exception_if_created() // public void Create_should_throw_exception_if_created()
{ // {
CreateApp(); // CreateApp();
Assert.Throws<DomainException>(() => // Assert.Throws<DomainException>(() =>
{ // {
sut.Create(CreateCommand(new CreateApp { Name = AppName })); // sut.Create(CreateCommand(new CreateApp { Name = AppName }));
}); // });
} // }
[Fact] // [Fact]
public void Create_should_specify_name_and_owner() // public void Create_should_specify_name_and_owner()
{ // {
var id1 = Guid.NewGuid(); // var id1 = Guid.NewGuid();
var id2 = Guid.NewGuid(); // var id2 = Guid.NewGuid();
var initialPatterns = new InitialPatterns // var initialPatterns = new InitialPatterns
{ // {
{ id1, new AppPattern("Number", "[0-9]") }, // { id1, new AppPattern("Number", "[0-9]") },
{ id2, new AppPattern("Numbers", "[0-9]*") } // { id2, new AppPattern("Numbers", "[0-9]*") }
}; // };
var app = new AppDomainObject(initialPatterns); // var app = new AppDomainObject(initialPatterns);
app.Create(CreateCommand(new CreateApp { Name = AppName, Actor = User, AppId = AppId })); // app.Create(CreateCommand(new CreateApp { Name = AppName, Actor = User, AppId = AppId }));
Assert.Equal(AppName, app.Snapshot.Name); // Assert.Equal(AppName, app.Snapshot.Name);
app.GetUncomittedEvents() // app.GetUncomittedEvents()
.ShouldHaveSameEvents( // .ShouldHaveSameEvents(
CreateEvent(new AppCreated { Name = AppName }), // CreateEvent(new AppCreated { Name = AppName }),
CreateEvent(new AppContributorAssigned { ContributorId = User.Identifier, Permission = AppContributorPermission.Owner }), // CreateEvent(new AppContributorAssigned { ContributorId = User.Identifier, Permission = AppContributorPermission.Owner }),
CreateEvent(new AppLanguageAdded { Language = Language.EN }), // CreateEvent(new AppLanguageAdded { Language = Language.EN }),
CreateEvent(new AppPatternAdded { PatternId = id1, Name = "Number", Pattern = "[0-9]" }), // CreateEvent(new AppPatternAdded { PatternId = id1, Name = "Number", Pattern = "[0-9]" }),
CreateEvent(new AppPatternAdded { PatternId = id2, Name = "Numbers", Pattern = "[0-9]*" }) // CreateEvent(new AppPatternAdded { PatternId = id2, Name = "Numbers", Pattern = "[0-9]*" })
); // );
} // }
[Fact] // [Fact]
public void ChangePlan_should_throw_exception_if_not_created() // public void ChangePlan_should_throw_exception_if_not_created()
{ // {
Assert.Throws<DomainException>(() => // Assert.Throws<DomainException>(() =>
{ // {
sut.ChangePlan(CreateCommand(new ChangePlan { PlanId = planId })); // sut.ChangePlan(CreateCommand(new ChangePlan { PlanId = planId }));
}); // });
} // }
[Fact] // [Fact]
public void ChangePlan_should_create_events() // public void ChangePlan_should_create_events()
{ // {
CreateApp(); // CreateApp();
sut.ChangePlan(CreateCommand(new ChangePlan { PlanId = planId })); // sut.ChangePlan(CreateCommand(new ChangePlan { PlanId = planId }));
Assert.Equal(planId, sut.Snapshot.Plan.PlanId); // Assert.Equal(planId, sut.Snapshot.Plan.PlanId);
sut.GetUncomittedEvents() // sut.GetUncomittedEvents()
.ShouldHaveSameEvents( // .ShouldHaveSameEvents(
CreateEvent(new AppPlanChanged { PlanId = planId }) // CreateEvent(new AppPlanChanged { PlanId = planId })
); // );
} // }
[Fact] // [Fact]
public void AssignContributor_should_throw_exception_if_not_created() // public void AssignContributor_should_throw_exception_if_not_created()
{ // {
Assert.Throws<DomainException>(() => // Assert.Throws<DomainException>(() =>
{ // {
sut.AssignContributor(CreateCommand(new AssignContributor { ContributorId = contributorId })); // sut.AssignContributor(CreateCommand(new AssignContributor { ContributorId = contributorId }));
}); // });
} // }
[Fact] // [Fact]
public void AssignContributor_should_create_events() // public void AssignContributor_should_create_events()
{ // {
CreateApp(); // CreateApp();
sut.AssignContributor(CreateCommand(new AssignContributor { ContributorId = contributorId, Permission = AppContributorPermission.Editor })); // sut.AssignContributor(CreateCommand(new AssignContributor { ContributorId = contributorId, Permission = AppContributorPermission.Editor }));
Assert.Equal(AppContributorPermission.Editor, sut.Snapshot.Contributors[contributorId]); // Assert.Equal(AppContributorPermission.Editor, sut.Snapshot.Contributors[contributorId]);
sut.GetUncomittedEvents() // sut.GetUncomittedEvents()
.ShouldHaveSameEvents( // .ShouldHaveSameEvents(
CreateEvent(new AppContributorAssigned { ContributorId = contributorId, Permission = AppContributorPermission.Editor }) // CreateEvent(new AppContributorAssigned { ContributorId = contributorId, Permission = AppContributorPermission.Editor })
); // );
} // }
[Fact] // [Fact]
public void RemoveContributor_should_throw_exception_if_not_created() // public void RemoveContributor_should_throw_exception_if_not_created()
{ // {
Assert.Throws<DomainException>(() => // Assert.Throws<DomainException>(() =>
{ // {
sut.RemoveContributor(CreateCommand(new RemoveContributor { ContributorId = contributorId })); // sut.RemoveContributor(CreateCommand(new RemoveContributor { ContributorId = contributorId }));
}); // });
} // }
[Fact] // [Fact]
public void RemoveContributor_should_create_events_and_remove_contributor() // public void RemoveContributor_should_create_events_and_remove_contributor()
{ // {
CreateApp(); // CreateApp();
sut.AssignContributor(CreateCommand(new AssignContributor { ContributorId = contributorId, Permission = AppContributorPermission.Editor })); // sut.AssignContributor(CreateCommand(new AssignContributor { ContributorId = contributorId, Permission = AppContributorPermission.Editor }));
sut.RemoveContributor(CreateCommand(new RemoveContributor { ContributorId = contributorId })); // sut.RemoveContributor(CreateCommand(new RemoveContributor { ContributorId = contributorId }));
Assert.False(sut.Snapshot.Contributors.ContainsKey(contributorId)); // Assert.False(sut.Snapshot.Contributors.ContainsKey(contributorId));
sut.GetUncomittedEvents().Skip(1) // sut.GetUncomittedEvents().Skip(1)
.ShouldHaveSameEvents( // .ShouldHaveSameEvents(
CreateEvent(new AppContributorRemoved { ContributorId = contributorId }) // CreateEvent(new AppContributorRemoved { ContributorId = contributorId })
); // );
} // }
[Fact] // [Fact]
public void AttachClient_should_throw_exception_if_not_created() // public void AttachClient_should_throw_exception_if_not_created()
{ // {
Assert.Throws<DomainException>(() => // Assert.Throws<DomainException>(() =>
{ // {
sut.AttachClient(CreateCommand(new AttachClient { Id = clientId })); // sut.AttachClient(CreateCommand(new AttachClient { Id = clientId }));
}); // });
} // }
[Fact] // [Fact]
public void AttachClient_should_create_events() // public void AttachClient_should_create_events()
{ // {
var command = new AttachClient { Id = clientId }; // var command = new AttachClient { Id = clientId };
CreateApp(); // CreateApp();
sut.AttachClient(CreateCommand(command)); // sut.AttachClient(CreateCommand(command));
Assert.True(sut.Snapshot.Clients.ContainsKey(clientId)); // Assert.True(sut.Snapshot.Clients.ContainsKey(clientId));
sut.GetUncomittedEvents() // sut.GetUncomittedEvents()
.ShouldHaveSameEvents( // .ShouldHaveSameEvents(
CreateEvent(new AppClientAttached { Id = clientId, Secret = command.Secret }) // CreateEvent(new AppClientAttached { Id = clientId, Secret = command.Secret })
); // );
} // }
[Fact] // [Fact]
public void RevokeClient_should_throw_exception_if_not_created() // public void RevokeClient_should_throw_exception_if_not_created()
{ // {
Assert.Throws<DomainException>(() => // Assert.Throws<DomainException>(() =>
{ // {
sut.RevokeClient(CreateCommand(new RevokeClient { Id = "not-found" })); // sut.RevokeClient(CreateCommand(new RevokeClient { Id = "not-found" }));
}); // });
} // }
[Fact] // [Fact]
public void RevokeClient_should_create_events() // public void RevokeClient_should_create_events()
{ // {
CreateApp(); // CreateApp();
CreateClient(); // CreateClient();
sut.RevokeClient(CreateCommand(new RevokeClient { Id = clientId })); // sut.RevokeClient(CreateCommand(new RevokeClient { Id = clientId }));
Assert.False(sut.Snapshot.Clients.ContainsKey(clientId)); // Assert.False(sut.Snapshot.Clients.ContainsKey(clientId));
sut.GetUncomittedEvents() // sut.GetUncomittedEvents()
.ShouldHaveSameEvents( // .ShouldHaveSameEvents(
CreateEvent(new AppClientRevoked { Id = clientId }) // CreateEvent(new AppClientRevoked { Id = clientId })
); // );
} // }
[Fact] // [Fact]
public void UpdateClient_should_throw_exception_if_not_created() // public void UpdateClient_should_throw_exception_if_not_created()
{ // {
Assert.Throws<DomainException>(() => // Assert.Throws<DomainException>(() =>
{ // {
sut.UpdateClient(CreateCommand(new UpdateClient { Id = "not-found", Name = clientNewName })); // sut.UpdateClient(CreateCommand(new UpdateClient { Id = "not-found", Name = clientNewName }));
}); // });
} // }
[Fact] // [Fact]
public void UpdateClient_should_create_events() // public void UpdateClient_should_create_events()
{ // {
CreateApp(); // CreateApp();
CreateClient(); // CreateClient();
sut.UpdateClient(CreateCommand(new UpdateClient { Id = clientId, Name = clientNewName, Permission = AppClientPermission.Developer })); // sut.UpdateClient(CreateCommand(new UpdateClient { Id = clientId, Name = clientNewName, Permission = AppClientPermission.Developer }));
Assert.Equal(clientNewName, sut.Snapshot.Clients[clientId].Name); // Assert.Equal(clientNewName, sut.Snapshot.Clients[clientId].Name);
sut.GetUncomittedEvents() // sut.GetUncomittedEvents()
.ShouldHaveSameEvents( // .ShouldHaveSameEvents(
CreateEvent(new AppClientRenamed { Id = clientId, Name = clientNewName }), // CreateEvent(new AppClientRenamed { Id = clientId, Name = clientNewName }),
CreateEvent(new AppClientUpdated { Id = clientId, Permission = AppClientPermission.Developer }) // CreateEvent(new AppClientUpdated { Id = clientId, Permission = AppClientPermission.Developer })
); // );
} // }
[Fact] // [Fact]
public void AddLanguage_should_throw_exception_if_not_created() // public void AddLanguage_should_throw_exception_if_not_created()
{ // {
Assert.Throws<DomainException>(() => // Assert.Throws<DomainException>(() =>
{ // {
sut.AddLanguage(CreateCommand(new AddLanguage { Language = Language.DE })); // sut.AddLanguage(CreateCommand(new AddLanguage { Language = Language.DE }));
}); // });
} // }
[Fact] // [Fact]
public void AddLanguage_should_create_events() // public void AddLanguage_should_create_events()
{ // {
CreateApp(); // CreateApp();
sut.AddLanguage(CreateCommand(new AddLanguage { Language = Language.DE })); // sut.AddLanguage(CreateCommand(new AddLanguage { Language = Language.DE }));
Assert.True(sut.Snapshot.LanguagesConfig.Contains(Language.DE)); // Assert.True(sut.Snapshot.LanguagesConfig.Contains(Language.DE));
sut.GetUncomittedEvents() // sut.GetUncomittedEvents()
.ShouldHaveSameEvents( // .ShouldHaveSameEvents(
CreateEvent(new AppLanguageAdded { Language = Language.DE }) // CreateEvent(new AppLanguageAdded { Language = Language.DE })
); // );
} // }
[Fact] // [Fact]
public void RemoveLanguage_should_throw_exception_if_not_created() // public void RemoveLanguage_should_throw_exception_if_not_created()
{ // {
Assert.Throws<DomainException>(() => // Assert.Throws<DomainException>(() =>
{ // {
sut.RemoveLanguage(CreateCommand(new RemoveLanguage { Language = Language.EN })); // sut.RemoveLanguage(CreateCommand(new RemoveLanguage { Language = Language.EN }));
}); // });
} // }
[Fact] // [Fact]
public void RemoveLanguage_should_create_events() // public void RemoveLanguage_should_create_events()
{ // {
CreateApp(); // CreateApp();
CreateLanguage(Language.DE); // CreateLanguage(Language.DE);
sut.RemoveLanguage(CreateCommand(new RemoveLanguage { Language = Language.DE })); // sut.RemoveLanguage(CreateCommand(new RemoveLanguage { Language = Language.DE }));
Assert.False(sut.Snapshot.LanguagesConfig.Contains(Language.DE)); // Assert.False(sut.Snapshot.LanguagesConfig.Contains(Language.DE));
sut.GetUncomittedEvents() // sut.GetUncomittedEvents()
.ShouldHaveSameEvents( // .ShouldHaveSameEvents(
CreateEvent(new AppLanguageRemoved { Language = Language.DE }) // CreateEvent(new AppLanguageRemoved { Language = Language.DE })
); // );
} // }
[Fact] // [Fact]
public void UpdateLanguage_should_throw_exception_if_not_created() // public void UpdateLanguage_should_throw_exception_if_not_created()
{ // {
Assert.Throws<DomainException>(() => // Assert.Throws<DomainException>(() =>
{ // {
sut.UpdateLanguage(CreateCommand(new UpdateLanguage { Language = Language.EN })); // sut.UpdateLanguage(CreateCommand(new UpdateLanguage { Language = Language.EN }));
}); // });
} // }
[Fact] // [Fact]
public void UpdateLanguage_should_create_events() // public void UpdateLanguage_should_create_events()
{ // {
CreateApp(); // CreateApp();
CreateLanguage(Language.DE); // CreateLanguage(Language.DE);
sut.UpdateLanguage(CreateCommand(new UpdateLanguage { Language = Language.DE, Fallback = new List<Language> { Language.EN } })); // sut.UpdateLanguage(CreateCommand(new UpdateLanguage { Language = Language.DE, Fallback = new List<Language> { Language.EN } }));
Assert.True(sut.Snapshot.LanguagesConfig.Contains(Language.DE)); // Assert.True(sut.Snapshot.LanguagesConfig.Contains(Language.DE));
sut.GetUncomittedEvents() // sut.GetUncomittedEvents()
.ShouldHaveSameEvents( // .ShouldHaveSameEvents(
CreateEvent(new AppLanguageUpdated { Language = Language.DE, Fallback = new List<Language> { Language.EN } }) // CreateEvent(new AppLanguageUpdated { Language = Language.DE, Fallback = new List<Language> { Language.EN } })
); // );
} // }
[Fact] // [Fact]
public void AddPattern_should_throw_exception_if_app_not_created() // public void AddPattern_should_throw_exception_if_app_not_created()
{ // {
Assert.Throws<DomainException>(() => sut.AddPattern(CreateCommand(new AddPattern { PatternId = patternId, Name = "Any", Pattern = ".*" }))); // Assert.Throws<DomainException>(() => sut.AddPattern(CreateCommand(new AddPattern { PatternId = patternId, Name = "Any", Pattern = ".*" })));
} // }
[Fact] // [Fact]
public void AddPattern_should_create_events() // public void AddPattern_should_create_events()
{ // {
CreateApp(); // CreateApp();
sut.AddPattern(CreateCommand(new AddPattern { PatternId = patternId, Name = "Any", Pattern = ".*", Message = "Msg" })); // sut.AddPattern(CreateCommand(new AddPattern { PatternId = patternId, Name = "Any", Pattern = ".*", Message = "Msg" }));
Assert.Single(sut.Snapshot.Patterns); // Assert.Single(sut.Snapshot.Patterns);
sut.GetUncomittedEvents() // sut.GetUncomittedEvents()
.ShouldHaveSameEvents( // .ShouldHaveSameEvents(
CreateEvent(new AppPatternAdded { PatternId = patternId, Name = "Any", Pattern = ".*", Message = "Msg" }) // CreateEvent(new AppPatternAdded { PatternId = patternId, Name = "Any", Pattern = ".*", Message = "Msg" })
); // );
} // }
[Fact] // [Fact]
public void DeletePattern_should_throw_exception_if_app_not_created() // public void DeletePattern_should_throw_exception_if_app_not_created()
{ // {
Assert.Throws<DomainException>(() => // Assert.Throws<DomainException>(() =>
{ // {
sut.DeletePattern(CreateCommand(new DeletePattern // sut.DeletePattern(CreateCommand(new DeletePattern
{ // {
PatternId = Guid.NewGuid() // PatternId = Guid.NewGuid()
})); // }));
}); // });
} // }
[Fact] // [Fact]
public void DeletePattern_should_create_events() // public void DeletePattern_should_create_events()
{ // {
CreateApp(); // CreateApp();
CreatePattern(); // CreatePattern();
sut.DeletePattern(CreateCommand(new DeletePattern { PatternId = patternId })); // sut.DeletePattern(CreateCommand(new DeletePattern { PatternId = patternId }));
Assert.Empty(sut.Snapshot.Patterns); // Assert.Empty(sut.Snapshot.Patterns);
sut.GetUncomittedEvents() // sut.GetUncomittedEvents()
.ShouldHaveSameEvents( // .ShouldHaveSameEvents(
CreateEvent(new AppPatternDeleted { PatternId = patternId }) // CreateEvent(new AppPatternDeleted { PatternId = patternId })
); // );
} // }
[Fact] // [Fact]
public void UpdatePattern_should_throw_exception_if_app_not_created() // public void UpdatePattern_should_throw_exception_if_app_not_created()
{ // {
Assert.Throws<DomainException>(() => sut.UpdatePattern(CreateCommand(new UpdatePattern { PatternId = patternId, Name = "Any", Pattern = ".*" }))); // Assert.Throws<DomainException>(() => sut.UpdatePattern(CreateCommand(new UpdatePattern { PatternId = patternId, Name = "Any", Pattern = ".*" })));
} // }
[Fact] // [Fact]
public void UpdatePattern_should_create_events() // public void UpdatePattern_should_create_events()
{ // {
CreateApp(); // CreateApp();
CreatePattern(); // CreatePattern();
sut.UpdatePattern(CreateCommand(new UpdatePattern { PatternId = patternId, Name = "Any", Pattern = ".*", Message = "Msg" })); // sut.UpdatePattern(CreateCommand(new UpdatePattern { PatternId = patternId, Name = "Any", Pattern = ".*", Message = "Msg" }));
Assert.Single(sut.Snapshot.Patterns); // Assert.Single(sut.Snapshot.Patterns);
sut.GetUncomittedEvents() // sut.GetUncomittedEvents()
.ShouldHaveSameEvents( // .ShouldHaveSameEvents(
CreateEvent(new AppPatternUpdated { PatternId = patternId, Name = "Any", Pattern = ".*", Message = "Msg" }) // CreateEvent(new AppPatternUpdated { PatternId = patternId, Name = "Any", Pattern = ".*", Message = "Msg" })
); // );
} // }
private void CreatePattern() // private void CreatePattern()
{ // {
sut.AddPattern(CreateCommand(new AddPattern { PatternId = patternId, Name = "Name", Pattern = ".*" })); // sut.AddPattern(CreateCommand(new AddPattern { PatternId = patternId, Name = "Name", Pattern = ".*" }));
sut.ClearUncommittedEvents(); // sut.ClearUncommittedEvents();
} // }
private void CreateApp() // private void CreateApp()
{ // {
sut.Create(CreateCommand(new CreateApp { Name = AppName })); // sut.Create(CreateCommand(new CreateApp { Name = AppName }));
sut.ClearUncommittedEvents(); // sut.ClearUncommittedEvents();
} // }
private void CreateClient() // private void CreateClient()
{ // {
sut.AttachClient(CreateCommand(new AttachClient { Id = clientId })); // sut.AttachClient(CreateCommand(new AttachClient { Id = clientId }));
sut.ClearUncommittedEvents(); // sut.ClearUncommittedEvents();
} // }
private void CreateLanguage(Language language) // private void CreateLanguage(Language language)
{ // {
sut.AddLanguage(CreateCommand(new AddLanguage { Language = language })); // sut.AddLanguage(CreateCommand(new AddLanguage { Language = language }));
sut.ClearUncommittedEvents(); // sut.ClearUncommittedEvents();
} // }
} // }
} //}

290
tests/Squidex.Domain.Apps.Entities.Tests/Assets/AssetCommandMiddlewareTests.cs

@ -1,145 +1,145 @@
// ========================================================================== //// ==========================================================================
// Squidex Headless CMS //// Squidex Headless CMS
// ========================================================================== //// ==========================================================================
// Copyright (c) Squidex UG (haftungsbeschränkt) //// Copyright (c) Squidex UG (haftungsbeschränkt)
// All rights reserved. Licensed under the MIT license. //// All rights reserved. Licensed under the MIT license.
// ========================================================================== //// ==========================================================================
using System; //using System;
using System.IO; //using System.IO;
using System.Threading.Tasks; //using System.Threading.Tasks;
using FakeItEasy; //using FakeItEasy;
using Squidex.Domain.Apps.Entities.Assets.Commands; //using Squidex.Domain.Apps.Entities.Assets.Commands;
using Squidex.Domain.Apps.Entities.TestHelpers; //using Squidex.Domain.Apps.Entities.TestHelpers;
using Squidex.Infrastructure.Assets; //using Squidex.Infrastructure.Assets;
using Squidex.Infrastructure.Commands; //using Squidex.Infrastructure.Commands;
using Squidex.Infrastructure.Tasks; //using Squidex.Infrastructure.Tasks;
using Xunit; //using Xunit;
namespace Squidex.Domain.Apps.Entities.Assets //namespace Squidex.Domain.Apps.Entities.Assets
{ //{
public class AssetCommandMiddlewareTests : HandlerTestBase<AssetDomainObject> // public class AssetCommandMiddlewareTests : HandlerTestBase<AssetDomainObject>
{ // {
private readonly IAssetThumbnailGenerator assetThumbnailGenerator = A.Fake<IAssetThumbnailGenerator>(); // private readonly IAssetThumbnailGenerator assetThumbnailGenerator = A.Fake<IAssetThumbnailGenerator>();
private readonly IAssetStore assetStore = A.Fake<IAssetStore>(); // private readonly IAssetStore assetStore = A.Fake<IAssetStore>();
private readonly Guid assetId = Guid.NewGuid(); // private readonly Guid assetId = Guid.NewGuid();
private readonly Stream stream = new MemoryStream(); // private readonly Stream stream = new MemoryStream();
private readonly ImageInfo image = new ImageInfo(2048, 2048); // private readonly ImageInfo image = new ImageInfo(2048, 2048);
private readonly AssetDomainObject asset = new AssetDomainObject(); // private readonly AssetDomainObject asset = new AssetDomainObject();
private readonly AssetFile file; // private readonly AssetFile file;
private readonly AssetCommandMiddleware sut; // private readonly AssetCommandMiddleware sut;
protected override Guid Id // protected override Guid Id
{ // {
get { return assetId; } // get { return assetId; }
} // }
public AssetCommandMiddlewareTests() // public AssetCommandMiddlewareTests()
{ // {
file = new AssetFile("my-image.png", "image/png", 1024, () => stream); // file = new AssetFile("my-image.png", "image/png", 1024, () => stream);
sut = new AssetCommandMiddleware(Handler, assetStore, assetThumbnailGenerator); // sut = new AssetCommandMiddleware(Handler, assetStore, assetThumbnailGenerator);
} // }
[Fact] // [Fact]
public async Task Create_should_create_domain_object() // public async Task Create_should_create_domain_object()
{ // {
var context = CreateContextForCommand(new CreateAsset { AssetId = assetId, File = file }); // var context = CreateContextForCommand(new CreateAsset { AssetId = assetId, File = file });
SetupStore(0, context.ContextId); // SetupStore(0, context.ContextId);
SetupImageInfo(); // SetupImageInfo();
await TestCreate(asset, async _ => // await TestCreate(asset, async _ =>
{ // {
await sut.HandleAsync(context); // await sut.HandleAsync(context);
}); // });
Assert.Equal(assetId, context.Result<EntityCreatedResult<Guid>>().IdOrValue); // Assert.Equal(assetId, context.Result<EntityCreatedResult<Guid>>().IdOrValue);
AssertAssetHasBeenUploaded(0, context.ContextId); // AssertAssetHasBeenUploaded(0, context.ContextId);
AssertAssetImageChecked(); // AssertAssetImageChecked();
} // }
[Fact] // [Fact]
public async Task Update_should_update_domain_object() // public async Task Update_should_update_domain_object()
{ // {
var context = CreateContextForCommand(new UpdateAsset { AssetId = assetId, File = file }); // var context = CreateContextForCommand(new UpdateAsset { AssetId = assetId, File = file });
SetupStore(1, context.ContextId); // SetupStore(1, context.ContextId);
SetupImageInfo(); // SetupImageInfo();
CreateAsset(); // CreateAsset();
await TestUpdate(asset, async _ => // await TestUpdate(asset, async _ =>
{ // {
await sut.HandleAsync(context); // await sut.HandleAsync(context);
}); // });
AssertAssetHasBeenUploaded(1, context.ContextId); // AssertAssetHasBeenUploaded(1, context.ContextId);
AssertAssetImageChecked(); // AssertAssetImageChecked();
} // }
[Fact] // [Fact]
public async Task Rename_should_update_domain_object() // public async Task Rename_should_update_domain_object()
{ // {
CreateAsset(); // CreateAsset();
var context = CreateContextForCommand(new RenameAsset { AssetId = assetId, FileName = "my-new-image.png" }); // var context = CreateContextForCommand(new RenameAsset { AssetId = assetId, FileName = "my-new-image.png" });
await TestUpdate(asset, async _ => // await TestUpdate(asset, async _ =>
{ // {
await sut.HandleAsync(context); // await sut.HandleAsync(context);
}); // });
} // }
[Fact] // [Fact]
public async Task Delete_should_update_domain_object() // public async Task Delete_should_update_domain_object()
{ // {
CreateAsset(); // CreateAsset();
var command = CreateContextForCommand(new DeleteAsset { AssetId = assetId }); // var command = CreateContextForCommand(new DeleteAsset { AssetId = assetId });
await TestUpdate(asset, async _ => // await TestUpdate(asset, async _ =>
{ // {
await sut.HandleAsync(command); // await sut.HandleAsync(command);
}); // });
} // }
private void CreateAsset() // private void CreateAsset()
{ // {
asset.Create(CreateCommand(new CreateAsset { File = file })); // asset.Create(CreateCommand(new CreateAsset { File = file }));
} // }
private void SetupImageInfo() // private void SetupImageInfo()
{ // {
A.CallTo(() => assetThumbnailGenerator.GetImageInfoAsync(stream)) // A.CallTo(() => assetThumbnailGenerator.GetImageInfoAsync(stream))
.Returns(image); // .Returns(image);
} // }
private void SetupStore(long version, Guid commitId) // private void SetupStore(long version, Guid commitId)
{ // {
A.CallTo(() => assetStore.UploadTemporaryAsync(commitId.ToString(), stream)) // A.CallTo(() => assetStore.UploadTemporaryAsync(commitId.ToString(), stream))
.Returns(TaskHelper.Done); // .Returns(TaskHelper.Done);
A.CallTo(() => assetStore.CopyTemporaryAsync(commitId.ToString(), assetId.ToString(), version, null)) // A.CallTo(() => assetStore.CopyTemporaryAsync(commitId.ToString(), assetId.ToString(), version, null))
.Returns(TaskHelper.Done); // .Returns(TaskHelper.Done);
A.CallTo(() => assetStore.DeleteTemporaryAsync(commitId.ToString())) // A.CallTo(() => assetStore.DeleteTemporaryAsync(commitId.ToString()))
.Returns(TaskHelper.Done); // .Returns(TaskHelper.Done);
} // }
private void AssertAssetImageChecked() // private void AssertAssetImageChecked()
{ // {
A.CallTo(() => assetThumbnailGenerator.GetImageInfoAsync(stream)) // A.CallTo(() => assetThumbnailGenerator.GetImageInfoAsync(stream))
.MustHaveHappened(); // .MustHaveHappened();
} // }
private void AssertAssetHasBeenUploaded(long version, Guid commitId) // private void AssertAssetHasBeenUploaded(long version, Guid commitId)
{ // {
A.CallTo(() => assetStore.UploadTemporaryAsync(commitId.ToString(), stream)) // A.CallTo(() => assetStore.UploadTemporaryAsync(commitId.ToString(), stream))
.MustHaveHappened(); // .MustHaveHappened();
A.CallTo(() => assetStore.CopyTemporaryAsync(commitId.ToString(), assetId.ToString(), version, null)) // A.CallTo(() => assetStore.CopyTemporaryAsync(commitId.ToString(), assetId.ToString(), version, null))
.MustHaveHappened(); // .MustHaveHappened();
A.CallTo(() => assetStore.DeleteTemporaryAsync(commitId.ToString())) // A.CallTo(() => assetStore.DeleteTemporaryAsync(commitId.ToString()))
.MustHaveHappened(); // .MustHaveHappened();
} // }
} // }
} //}

440
tests/Squidex.Domain.Apps.Entities.Tests/Assets/AssetDomainObjectTests.cs

@ -1,220 +1,220 @@
// ========================================================================== //// ==========================================================================
// Squidex Headless CMS //// Squidex Headless CMS
// ========================================================================== //// ==========================================================================
// Copyright (c) Squidex UG (haftungsbeschränkt) //// Copyright (c) Squidex UG (haftungsbeschränkt)
// All rights reserved. Licensed under the MIT license. //// All rights reserved. Licensed under the MIT license.
// ========================================================================== //// ==========================================================================
using System; //using System;
using System.IO; //using System.IO;
using FakeItEasy; //using FakeItEasy;
using Squidex.Domain.Apps.Entities.Assets.Commands; //using Squidex.Domain.Apps.Entities.Assets.Commands;
using Squidex.Domain.Apps.Entities.TestHelpers; //using Squidex.Domain.Apps.Entities.TestHelpers;
using Squidex.Domain.Apps.Events.Assets; //using Squidex.Domain.Apps.Events.Assets;
using Squidex.Infrastructure; //using Squidex.Infrastructure;
using Squidex.Infrastructure.Assets; //using Squidex.Infrastructure.Assets;
using Squidex.Infrastructure.States; //using Squidex.Infrastructure.States;
using Xunit; //using Xunit;
namespace Squidex.Domain.Apps.Entities.Assets //namespace Squidex.Domain.Apps.Entities.Assets
{ //{
public class AssetDomainObjectTests : HandlerTestBase<AssetDomainObject> // public class AssetDomainObjectTests : HandlerTestBase<AssetDomainObject>
{ // {
private readonly ImageInfo image = new ImageInfo(2048, 2048); // private readonly ImageInfo image = new ImageInfo(2048, 2048);
private readonly Guid assetId = Guid.NewGuid(); // private readonly Guid assetId = Guid.NewGuid();
private readonly AssetFile file = new AssetFile("my-image.png", "image/png", 1024, () => new MemoryStream()); // private readonly AssetFile file = new AssetFile("my-image.png", "image/png", 1024, () => new MemoryStream());
private readonly AssetDomainObject sut = new AssetDomainObject(); // private readonly AssetDomainObject sut = new AssetDomainObject();
protected override Guid Id // protected override Guid Id
{ // {
get { return assetId; } // get { return assetId; }
} // }
public AssetDomainObjectTests() // public AssetDomainObjectTests()
{ // {
sut.ActivateAsync(Id, A.Fake<IStore<Guid>>()); // sut.ActivateAsync(Id, A.Fake<IStore<Guid>>());
} // }
[Fact] // [Fact]
public void Create_should_throw_exception_if_created() // public void Create_should_throw_exception_if_created()
{ // {
CreateAsset(); // CreateAsset();
Assert.Throws<DomainException>(() => // Assert.Throws<DomainException>(() =>
{ // {
sut.Create(CreateAssetCommand(new CreateAsset { File = file })); // sut.Create(CreateAssetCommand(new CreateAsset { File = file }));
}); // });
} // }
[Fact] // [Fact]
public void Create_should_create_events() // public void Create_should_create_events()
{ // {
sut.Create(CreateAssetCommand(new CreateAsset { File = file, ImageInfo = image })); // sut.Create(CreateAssetCommand(new CreateAsset { File = file, ImageInfo = image }));
Assert.Equal(0, sut.Snapshot.FileVersion); // Assert.Equal(0, sut.Snapshot.FileVersion);
sut.GetUncomittedEvents() // sut.GetUncomittedEvents()
.ShouldHaveSameEvents( // .ShouldHaveSameEvents(
CreateAssetEvent(new AssetCreated // CreateAssetEvent(new AssetCreated
{ // {
IsImage = true, // IsImage = true,
FileName = file.FileName, // FileName = file.FileName,
FileSize = file.FileSize, // FileSize = file.FileSize,
FileVersion = 0, // FileVersion = 0,
MimeType = file.MimeType, // MimeType = file.MimeType,
PixelWidth = image.PixelWidth, // PixelWidth = image.PixelWidth,
PixelHeight = image.PixelHeight // PixelHeight = image.PixelHeight
}) // })
); // );
} // }
[Fact] // [Fact]
public void Update_should_throw_exception_if_not_created() // public void Update_should_throw_exception_if_not_created()
{ // {
Assert.Throws<DomainException>(() => // Assert.Throws<DomainException>(() =>
{ // {
sut.Update(CreateAssetCommand(new UpdateAsset { File = file })); // sut.Update(CreateAssetCommand(new UpdateAsset { File = file }));
}); // });
} // }
[Fact] // [Fact]
public void Update_should_throw_exception_if_asset_is_deleted() // public void Update_should_throw_exception_if_asset_is_deleted()
{ // {
CreateAsset(); // CreateAsset();
DeleteAsset(); // DeleteAsset();
Assert.Throws<DomainException>(() => // Assert.Throws<DomainException>(() =>
{ // {
sut.Update(CreateAssetCommand(new UpdateAsset())); // sut.Update(CreateAssetCommand(new UpdateAsset()));
}); // });
} // }
[Fact] // [Fact]
public void Update_should_create_events() // public void Update_should_create_events()
{ // {
CreateAsset(); // CreateAsset();
sut.Update(CreateAssetCommand(new UpdateAsset { File = file, ImageInfo = image })); // sut.Update(CreateAssetCommand(new UpdateAsset { File = file, ImageInfo = image }));
Assert.Equal(1, sut.Snapshot.FileVersion); // Assert.Equal(1, sut.Snapshot.FileVersion);
sut.GetUncomittedEvents() // sut.GetUncomittedEvents()
.ShouldHaveSameEvents( // .ShouldHaveSameEvents(
CreateAssetEvent(new AssetUpdated // CreateAssetEvent(new AssetUpdated
{ // {
IsImage = true, // IsImage = true,
FileSize = file.FileSize, // FileSize = file.FileSize,
FileVersion = 1, // FileVersion = 1,
MimeType = file.MimeType, // MimeType = file.MimeType,
PixelWidth = image.PixelWidth, // PixelWidth = image.PixelWidth,
PixelHeight = image.PixelHeight // PixelHeight = image.PixelHeight
}) // })
); // );
} // }
[Fact] // [Fact]
public void Rename_should_throw_exception_if_not_created() // public void Rename_should_throw_exception_if_not_created()
{ // {
Assert.Throws<DomainException>(() => // Assert.Throws<DomainException>(() =>
{ // {
sut.Rename(CreateAssetCommand(new RenameAsset { FileName = "new-file.png" })); // sut.Rename(CreateAssetCommand(new RenameAsset { FileName = "new-file.png" }));
}); // });
} // }
[Fact] // [Fact]
public void Rename_should_throw_exception_if_asset_is_deleted() // public void Rename_should_throw_exception_if_asset_is_deleted()
{ // {
CreateAsset(); // CreateAsset();
DeleteAsset(); // DeleteAsset();
Assert.Throws<DomainException>(() => // Assert.Throws<DomainException>(() =>
{ // {
sut.Update(CreateAssetCommand(new UpdateAsset())); // sut.Update(CreateAssetCommand(new UpdateAsset()));
}); // });
} // }
[Fact] // [Fact]
public void Rename_should_create_events() // public void Rename_should_create_events()
{ // {
CreateAsset(); // CreateAsset();
sut.Rename(CreateAssetCommand(new RenameAsset { FileName = "my-new-image.png" })); // sut.Rename(CreateAssetCommand(new RenameAsset { FileName = "my-new-image.png" }));
Assert.Equal("my-new-image.png", sut.Snapshot.FileName); // Assert.Equal("my-new-image.png", sut.Snapshot.FileName);
sut.GetUncomittedEvents() // sut.GetUncomittedEvents()
.ShouldHaveSameEvents( // .ShouldHaveSameEvents(
CreateAssetEvent(new AssetRenamed { FileName = "my-new-image.png" }) // CreateAssetEvent(new AssetRenamed { FileName = "my-new-image.png" })
); // );
} // }
[Fact] // [Fact]
public void Delete_should_throw_exception_if_not_created() // public void Delete_should_throw_exception_if_not_created()
{ // {
Assert.Throws<DomainException>(() => // Assert.Throws<DomainException>(() =>
{ // {
sut.Delete(CreateAssetCommand(new DeleteAsset())); // sut.Delete(CreateAssetCommand(new DeleteAsset()));
}); // });
} // }
[Fact] // [Fact]
public void Delete_should_throw_exception_if_already_deleted() // public void Delete_should_throw_exception_if_already_deleted()
{ // {
CreateAsset(); // CreateAsset();
DeleteAsset(); // DeleteAsset();
Assert.Throws<DomainException>(() => // Assert.Throws<DomainException>(() =>
{ // {
sut.Delete(CreateAssetCommand(new DeleteAsset())); // sut.Delete(CreateAssetCommand(new DeleteAsset()));
}); // });
} // }
[Fact] // [Fact]
public void Delete_should_create_events_with_total_file_size() // public void Delete_should_create_events_with_total_file_size()
{ // {
CreateAsset(); // CreateAsset();
UpdateAsset(); // UpdateAsset();
sut.Delete(CreateAssetCommand(new DeleteAsset())); // sut.Delete(CreateAssetCommand(new DeleteAsset()));
Assert.True(sut.Snapshot.IsDeleted); // Assert.True(sut.Snapshot.IsDeleted);
sut.GetUncomittedEvents() // sut.GetUncomittedEvents()
.ShouldHaveSameEvents( // .ShouldHaveSameEvents(
CreateAssetEvent(new AssetDeleted { DeletedSize = 2048 }) // CreateAssetEvent(new AssetDeleted { DeletedSize = 2048 })
); // );
} // }
private void CreateAsset() // private void CreateAsset()
{ // {
sut.Create(CreateAssetCommand(new CreateAsset { File = file })); // sut.Create(CreateAssetCommand(new CreateAsset { File = file }));
sut.ClearUncommittedEvents(); // sut.ClearUncommittedEvents();
} // }
private void UpdateAsset() // private void UpdateAsset()
{ // {
sut.Update(CreateAssetCommand(new UpdateAsset { File = file })); // sut.Update(CreateAssetCommand(new UpdateAsset { File = file }));
sut.ClearUncommittedEvents(); // sut.ClearUncommittedEvents();
} // }
private void DeleteAsset() // private void DeleteAsset()
{ // {
sut.Delete(CreateAssetCommand(new DeleteAsset())); // sut.Delete(CreateAssetCommand(new DeleteAsset()));
sut.ClearUncommittedEvents(); // sut.ClearUncommittedEvents();
} // }
protected T CreateAssetEvent<T>(T @event) where T : AssetEvent // protected T CreateAssetEvent<T>(T @event) where T : AssetEvent
{ // {
@event.AssetId = assetId; // @event.AssetId = assetId;
return CreateEvent(@event); // return CreateEvent(@event);
} // }
protected T CreateAssetCommand<T>(T command) where T : AssetCommand // protected T CreateAssetCommand<T>(T command) where T : AssetCommand
{ // {
command.AssetId = assetId; // command.AssetId = assetId;
return CreateCommand(command); // return CreateCommand(command);
} // }
} // }
} //}

464
tests/Squidex.Domain.Apps.Entities.Tests/Contents/ContentCommandMiddlewareTests.cs

@ -1,264 +1,264 @@
// ========================================================================== //// ==========================================================================
// Squidex Headless CMS //// Squidex Headless CMS
// ========================================================================== //// ==========================================================================
// Copyright (c) Squidex UG (haftungsbeschränkt) //// Copyright (c) Squidex UG (haftungsbeschränkt)
// All rights reserved. Licensed under the MIT license. //// All rights reserved. Licensed under the MIT license.
// ========================================================================== //// ==========================================================================
using System; //using System;
using System.Security.Claims; //using System.Security.Claims;
using System.Threading.Tasks; //using System.Threading.Tasks;
using FakeItEasy; //using FakeItEasy;
using NodaTime; //using NodaTime;
using Squidex.Domain.Apps.Core; //using Squidex.Domain.Apps.Core;
using Squidex.Domain.Apps.Core.Apps; //using Squidex.Domain.Apps.Core.Apps;
using Squidex.Domain.Apps.Core.Contents; //using Squidex.Domain.Apps.Core.Contents;
using Squidex.Domain.Apps.Core.Schemas; //using Squidex.Domain.Apps.Core.Schemas;
using Squidex.Domain.Apps.Core.Scripting; //using Squidex.Domain.Apps.Core.Scripting;
using Squidex.Domain.Apps.Entities.Apps; //using Squidex.Domain.Apps.Entities.Apps;
using Squidex.Domain.Apps.Entities.Assets.Repositories; //using Squidex.Domain.Apps.Entities.Assets.Repositories;
using Squidex.Domain.Apps.Entities.Contents.Commands; //using Squidex.Domain.Apps.Entities.Contents.Commands;
using Squidex.Domain.Apps.Entities.Contents.Repositories; //using Squidex.Domain.Apps.Entities.Contents.Repositories;
using Squidex.Domain.Apps.Entities.Schemas; //using Squidex.Domain.Apps.Entities.Schemas;
using Squidex.Domain.Apps.Entities.TestHelpers; //using Squidex.Domain.Apps.Entities.TestHelpers;
using Squidex.Infrastructure; //using Squidex.Infrastructure;
using Squidex.Infrastructure.Commands; //using Squidex.Infrastructure.Commands;
using Xunit; //using Xunit;
namespace Squidex.Domain.Apps.Entities.Contents //namespace Squidex.Domain.Apps.Entities.Contents
{ //{
public class ContentCommandMiddlewareTests : HandlerTestBase<ContentDomainObject> // public class ContentCommandMiddlewareTests : HandlerTestBase<ContentDomainObject>
{ // {
private readonly ISchemaEntity schema = A.Fake<ISchemaEntity>(); // private readonly ISchemaEntity schema = A.Fake<ISchemaEntity>();
private readonly IScriptEngine scriptEngine = A.Fake<IScriptEngine>(); // private readonly IScriptEngine scriptEngine = A.Fake<IScriptEngine>();
private readonly IAppProvider appProvider = A.Fake<IAppProvider>(); // private readonly IAppProvider appProvider = A.Fake<IAppProvider>();
private readonly IAppEntity app = A.Fake<IAppEntity>(); // private readonly IAppEntity app = A.Fake<IAppEntity>();
private readonly ClaimsPrincipal user = new ClaimsPrincipal(); // private readonly ClaimsPrincipal user = new ClaimsPrincipal();
private readonly LanguagesConfig languagesConfig = LanguagesConfig.Build(Language.DE); // private readonly LanguagesConfig languagesConfig = LanguagesConfig.Build(Language.DE);
private readonly Guid contentId = Guid.NewGuid(); // private readonly Guid contentId = Guid.NewGuid();
private readonly ContentDomainObject content = new ContentDomainObject(); // private readonly ContentDomainObject content = new ContentDomainObject();
private readonly ContentCommandMiddleware sut; // private readonly ContentCommandMiddleware sut;
protected override Guid Id // protected override Guid Id
{ // {
get { return contentId; } // get { return contentId; }
} // }
private readonly NamedContentData invalidData = // private readonly NamedContentData invalidData =
new NamedContentData() // new NamedContentData()
.AddField("my-field1", new ContentFieldData() // .AddField("my-field1", new ContentFieldData()
.AddValue(null)) // .AddValue(null))
.AddField("my-field2", new ContentFieldData() // .AddField("my-field2", new ContentFieldData()
.AddValue(1)); // .AddValue(1));
private readonly NamedContentData data = // private readonly NamedContentData data =
new NamedContentData() // new NamedContentData()
.AddField("my-field1", new ContentFieldData() // .AddField("my-field1", new ContentFieldData()
.AddValue(1)) // .AddValue(1))
.AddField("my-field2", new ContentFieldData() // .AddField("my-field2", new ContentFieldData()
.AddValue(1)); // .AddValue(1));
private readonly NamedContentData patch = // private readonly NamedContentData patch =
new NamedContentData() // new NamedContentData()
.AddField("my-field1", new ContentFieldData() // .AddField("my-field1", new ContentFieldData()
.AddValue(1)); // .AddValue(1));
public ContentCommandMiddlewareTests() // public ContentCommandMiddlewareTests()
{ // {
var schemaDef = // var schemaDef =
new Schema("my-schema") // new Schema("my-schema")
.AddField(new NumberField(1, "my-field1", Partitioning.Invariant, // .AddField(new NumberField(1, "my-field1", Partitioning.Invariant,
new NumberFieldProperties { IsRequired = true })) // new NumberFieldProperties { IsRequired = true }))
.AddField(new NumberField(2, "my-field2", Partitioning.Invariant, // .AddField(new NumberField(2, "my-field2", Partitioning.Invariant,
new NumberFieldProperties { IsRequired = false })); // new NumberFieldProperties { IsRequired = false }));
sut = new ContentCommandMiddleware(Handler, appProvider, A.Dummy<IAssetRepository>(), scriptEngine, A.Dummy<IContentRepository>()); // sut = new ContentCommandMiddleware(Handler, appProvider, A.Dummy<IAssetRepository>(), scriptEngine, A.Dummy<IContentRepository>());
A.CallTo(() => app.LanguagesConfig).Returns(languagesConfig); // A.CallTo(() => app.LanguagesConfig).Returns(languagesConfig);
A.CallTo(() => appProvider.GetAppAsync(AppName)).Returns(app); // A.CallTo(() => appProvider.GetAppAsync(AppName)).Returns(app);
A.CallTo(() => schema.SchemaDef).Returns(schemaDef); // A.CallTo(() => schema.SchemaDef).Returns(schemaDef);
A.CallTo(() => schema.ScriptCreate).Returns("<create-script>"); // A.CallTo(() => schema.ScriptCreate).Returns("<create-script>");
A.CallTo(() => schema.ScriptChange).Returns("<change-script>"); // A.CallTo(() => schema.ScriptChange).Returns("<change-script>");
A.CallTo(() => schema.ScriptUpdate).Returns("<update-script>"); // A.CallTo(() => schema.ScriptUpdate).Returns("<update-script>");
A.CallTo(() => schema.ScriptDelete).Returns("<delete-script>"); // A.CallTo(() => schema.ScriptDelete).Returns("<delete-script>");
A.CallTo(() => appProvider.GetAppWithSchemaAsync(AppId, SchemaId)).Returns((app, schema)); // A.CallTo(() => appProvider.GetAppWithSchemaAsync(AppId, SchemaId)).Returns((app, schema));
} // }
[Fact] // [Fact]
public async Task Create_should_throw_exception_if_data_is_not_valid() // public async Task Create_should_throw_exception_if_data_is_not_valid()
{ // {
A.CallTo(() => scriptEngine.ExecuteAndTransform(A<ScriptContext>.Ignored, A<string>.Ignored)) // A.CallTo(() => scriptEngine.ExecuteAndTransform(A<ScriptContext>.Ignored, A<string>.Ignored))
.Returns(invalidData); // .Returns(invalidData);
var context = CreateContextForCommand(new CreateContent { ContentId = contentId, Data = invalidData, User = user }); // var context = CreateContextForCommand(new CreateContent { ContentId = contentId, Data = invalidData, User = user });
await TestCreate(content, async _ => // await TestCreate(content, async _ =>
{ // {
await Assert.ThrowsAsync<ValidationException>(() => sut.HandleAsync(context)); // await Assert.ThrowsAsync<ValidationException>(() => sut.HandleAsync(context));
}, false); // }, false);
} // }
[Fact] // [Fact]
public async Task Create_should_create_content() // public async Task Create_should_create_content()
{ // {
A.CallTo(() => scriptEngine.ExecuteAndTransform(A<ScriptContext>.Ignored, A<string>.Ignored)) // A.CallTo(() => scriptEngine.ExecuteAndTransform(A<ScriptContext>.Ignored, A<string>.Ignored))
.Returns(data); // .Returns(data);
var context = CreateContextForCommand(new CreateContent { ContentId = contentId, Data = data, User = user }); // var context = CreateContextForCommand(new CreateContent { ContentId = contentId, Data = data, User = user });
await TestCreate(content, async _ => // await TestCreate(content, async _ =>
{ // {
await sut.HandleAsync(context); // await sut.HandleAsync(context);
}); // });
Assert.Equal(data, context.Result<EntityCreatedResult<NamedContentData>>().IdOrValue); // Assert.Equal(data, context.Result<EntityCreatedResult<NamedContentData>>().IdOrValue);
A.CallTo(() => scriptEngine.ExecuteAndTransform(A<ScriptContext>.Ignored, "<create-script>")).MustHaveHappened(); // A.CallTo(() => scriptEngine.ExecuteAndTransform(A<ScriptContext>.Ignored, "<create-script>")).MustHaveHappened();
A.CallTo(() => scriptEngine.Execute(A<ScriptContext>.Ignored, "<change-script>")).MustNotHaveHappened(); // A.CallTo(() => scriptEngine.Execute(A<ScriptContext>.Ignored, "<change-script>")).MustNotHaveHappened();
} // }
[Fact] // [Fact]
public async Task Create_should_also_invoke_publish_script_when_publishing() // public async Task Create_should_also_invoke_publish_script_when_publishing()
{ // {
A.CallTo(() => scriptEngine.ExecuteAndTransform(A<ScriptContext>.Ignored, A<string>.Ignored)) // A.CallTo(() => scriptEngine.ExecuteAndTransform(A<ScriptContext>.Ignored, A<string>.Ignored))
.Returns(data); // .Returns(data);
var context = CreateContextForCommand(new CreateContent { ContentId = contentId, Data = data, User = user, Publish = true }); // var context = CreateContextForCommand(new CreateContent { ContentId = contentId, Data = data, User = user, Publish = true });
await TestCreate(content, async _ => // await TestCreate(content, async _ =>
{ // {
await sut.HandleAsync(context); // await sut.HandleAsync(context);
}); // });
Assert.Equal(data, context.Result<EntityCreatedResult<NamedContentData>>().IdOrValue); // Assert.Equal(data, context.Result<EntityCreatedResult<NamedContentData>>().IdOrValue);
A.CallTo(() => scriptEngine.ExecuteAndTransform(A<ScriptContext>.Ignored, "<create-script>")).MustHaveHappened(); // A.CallTo(() => scriptEngine.ExecuteAndTransform(A<ScriptContext>.Ignored, "<create-script>")).MustHaveHappened();
A.CallTo(() => scriptEngine.Execute(A<ScriptContext>.Ignored, "<change-script>")).MustHaveHappened(); // A.CallTo(() => scriptEngine.Execute(A<ScriptContext>.Ignored, "<change-script>")).MustHaveHappened();
} // }
[Fact] // [Fact]
public async Task Update_should_throw_exception_if_data_is_not_valid() // public async Task Update_should_throw_exception_if_data_is_not_valid()
{ // {
A.CallTo(() => scriptEngine.ExecuteAndTransform(A<ScriptContext>.Ignored, A<string>.Ignored)) // A.CallTo(() => scriptEngine.ExecuteAndTransform(A<ScriptContext>.Ignored, A<string>.Ignored))
.Returns(invalidData); // .Returns(invalidData);
CreateContent(); // CreateContent();
var context = CreateContextForCommand(new UpdateContent { ContentId = contentId, Data = invalidData, User = user }); // var context = CreateContextForCommand(new UpdateContent { ContentId = contentId, Data = invalidData, User = user });
await TestUpdate(content, async _ => // await TestUpdate(content, async _ =>
{ // {
await Assert.ThrowsAsync<ValidationException>(() => sut.HandleAsync(context)); // await Assert.ThrowsAsync<ValidationException>(() => sut.HandleAsync(context));
}, false); // }, false);
} // }
[Fact] // [Fact]
public async Task Update_should_update_domain_object() // public async Task Update_should_update_domain_object()
{ // {
A.CallTo(() => scriptEngine.ExecuteAndTransform(A<ScriptContext>.Ignored, A<string>.Ignored)) // A.CallTo(() => scriptEngine.ExecuteAndTransform(A<ScriptContext>.Ignored, A<string>.Ignored))
.Returns(data); // .Returns(data);
CreateContent(); // CreateContent();
var context = CreateContextForCommand(new UpdateContent { ContentId = contentId, Data = data, User = user }); // var context = CreateContextForCommand(new UpdateContent { ContentId = contentId, Data = data, User = user });
await TestUpdate(content, async _ => // await TestUpdate(content, async _ =>
{ // {
await sut.HandleAsync(context); // await sut.HandleAsync(context);
}); // });
Assert.Equal(data, context.Result<ContentDataChangedResult>().Data); // Assert.Equal(data, context.Result<ContentDataChangedResult>().Data);
A.CallTo(() => scriptEngine.ExecuteAndTransform(A<ScriptContext>.Ignored, "<update-script>")).MustHaveHappened(); // A.CallTo(() => scriptEngine.ExecuteAndTransform(A<ScriptContext>.Ignored, "<update-script>")).MustHaveHappened();
} // }
[Fact] // [Fact]
public async Task Patch_should_throw_exception_if_data_is_not_valid() // public async Task Patch_should_throw_exception_if_data_is_not_valid()
{ // {
A.CallTo(() => scriptEngine.ExecuteAndTransform(A<ScriptContext>.Ignored, A<string>.Ignored)) // A.CallTo(() => scriptEngine.ExecuteAndTransform(A<ScriptContext>.Ignored, A<string>.Ignored))
.Returns(invalidData); // .Returns(invalidData);
CreateContent(); // CreateContent();
var context = CreateContextForCommand(new PatchContent { ContentId = contentId, Data = invalidData, User = user }); // var context = CreateContextForCommand(new PatchContent { ContentId = contentId, Data = invalidData, User = user });
await TestUpdate(content, async _ => // await TestUpdate(content, async _ =>
{ // {
await Assert.ThrowsAsync<ValidationException>(() => sut.HandleAsync(context)); // await Assert.ThrowsAsync<ValidationException>(() => sut.HandleAsync(context));
}, false); // }, false);
} // }
[Fact] // [Fact]
public async Task Patch_should_update_domain_object() // public async Task Patch_should_update_domain_object()
{ // {
A.CallTo(() => scriptEngine.ExecuteAndTransform(A<ScriptContext>.Ignored, A<string>.Ignored)) // A.CallTo(() => scriptEngine.ExecuteAndTransform(A<ScriptContext>.Ignored, A<string>.Ignored))
.Returns(data); // .Returns(data);
A.CallTo(() => scriptEngine.ExecuteAndTransform(A<ScriptContext>.Ignored, A<string>.Ignored)).Returns(patch); // A.CallTo(() => scriptEngine.ExecuteAndTransform(A<ScriptContext>.Ignored, A<string>.Ignored)).Returns(patch);
CreateContent(); // CreateContent();
var context = CreateContextForCommand(new PatchContent { ContentId = contentId, Data = patch, User = user }); // var context = CreateContextForCommand(new PatchContent { ContentId = contentId, Data = patch, User = user });
await TestUpdate(content, async _ => // await TestUpdate(content, async _ =>
{ // {
await sut.HandleAsync(context); // await sut.HandleAsync(context);
}); // });
Assert.NotNull(context.Result<ContentDataChangedResult>().Data); // Assert.NotNull(context.Result<ContentDataChangedResult>().Data);
A.CallTo(() => scriptEngine.ExecuteAndTransform(A<ScriptContext>.Ignored, "<update-script>")).MustHaveHappened(); // A.CallTo(() => scriptEngine.ExecuteAndTransform(A<ScriptContext>.Ignored, "<update-script>")).MustHaveHappened();
} // }
[Fact] // [Fact]
public async Task ChangeStatus_should_publish_domain_object() // public async Task ChangeStatus_should_publish_domain_object()
{ // {
CreateContent(); // CreateContent();
var context = CreateContextForCommand(new ChangeContentStatus { ContentId = contentId, User = user, Status = Status.Published }); // var context = CreateContextForCommand(new ChangeContentStatus { ContentId = contentId, User = user, Status = Status.Published });
await TestUpdate(content, async _ => // await TestUpdate(content, async _ =>
{ // {
await sut.HandleAsync(context); // await sut.HandleAsync(context);
}); // });
A.CallTo(() => scriptEngine.Execute(A<ScriptContext>.Ignored, "<change-script>")).MustHaveHappened(); // A.CallTo(() => scriptEngine.Execute(A<ScriptContext>.Ignored, "<change-script>")).MustHaveHappened();
} // }
[Fact] // [Fact]
public async Task ChangeStatus_should_not_invoke_scripts_when_scheduled() // public async Task ChangeStatus_should_not_invoke_scripts_when_scheduled()
{ // {
CreateContent(); // CreateContent();
var context = CreateContextForCommand(new ChangeContentStatus { ContentId = contentId, User = user, Status = Status.Published, DueTime = Instant.MaxValue }); // var context = CreateContextForCommand(new ChangeContentStatus { ContentId = contentId, User = user, Status = Status.Published, DueTime = Instant.MaxValue });
await TestUpdate(content, async _ => // await TestUpdate(content, async _ =>
{ // {
await sut.HandleAsync(context); // await sut.HandleAsync(context);
}); // });
A.CallTo(() => scriptEngine.Execute(A<ScriptContext>.Ignored, "<change-script>")).MustNotHaveHappened(); // A.CallTo(() => scriptEngine.Execute(A<ScriptContext>.Ignored, "<change-script>")).MustNotHaveHappened();
} // }
[Fact] // [Fact]
public async Task Delete_should_update_domain_object() // public async Task Delete_should_update_domain_object()
{ // {
CreateContent(); // CreateContent();
var command = CreateContextForCommand(new DeleteContent { ContentId = contentId, User = user }); // var command = CreateContextForCommand(new DeleteContent { ContentId = contentId, User = user });
await TestUpdate(content, async _ => // await TestUpdate(content, async _ =>
{ // {
await sut.HandleAsync(command); // await sut.HandleAsync(command);
}); // });
A.CallTo(() => scriptEngine.Execute(A<ScriptContext>.Ignored, "<delete-script>")).MustHaveHappened(); // A.CallTo(() => scriptEngine.Execute(A<ScriptContext>.Ignored, "<delete-script>")).MustHaveHappened();
} // }
private void CreateContent() // private void CreateContent()
{ // {
content.Create(CreateCommand(new CreateContent { Data = data })); // content.Create(CreateCommand(new CreateContent { Data = data }));
} // }
} // }
} //}

608
tests/Squidex.Domain.Apps.Entities.Tests/Contents/ContentDomainObjectTests.cs

@ -1,304 +1,304 @@
// ========================================================================== //// ==========================================================================
// Squidex Headless CMS //// Squidex Headless CMS
// ========================================================================== //// ==========================================================================
// Copyright (c) Squidex UG (haftungsbeschränkt) //// Copyright (c) Squidex UG (haftungsbeschränkt)
// All rights reserved. Licensed under the MIT license. //// All rights reserved. Licensed under the MIT license.
// ========================================================================== //// ==========================================================================
using System; //using System;
using FakeItEasy; //using FakeItEasy;
using FluentAssertions; //using FluentAssertions;
using NodaTime; //using NodaTime;
using Squidex.Domain.Apps.Core.Contents; //using Squidex.Domain.Apps.Core.Contents;
using Squidex.Domain.Apps.Entities.Contents.Commands; //using Squidex.Domain.Apps.Entities.Contents.Commands;
using Squidex.Domain.Apps.Entities.TestHelpers; //using Squidex.Domain.Apps.Entities.TestHelpers;
using Squidex.Domain.Apps.Events.Contents; //using Squidex.Domain.Apps.Events.Contents;
using Squidex.Infrastructure; //using Squidex.Infrastructure;
using Squidex.Infrastructure.States; //using Squidex.Infrastructure.States;
using Xunit; //using Xunit;
namespace Squidex.Domain.Apps.Entities.Contents //namespace Squidex.Domain.Apps.Entities.Contents
{ //{
public class ContentDomainObjectTests : HandlerTestBase<ContentDomainObject> // public class ContentDomainObjectTests : HandlerTestBase<ContentDomainObject>
{ // {
private readonly NamedContentData data = // private readonly NamedContentData data =
new NamedContentData() // new NamedContentData()
.AddField("field1", // .AddField("field1",
new ContentFieldData() // new ContentFieldData()
.AddValue("iv", 1)); // .AddValue("iv", 1));
private readonly NamedContentData otherData = // private readonly NamedContentData otherData =
new NamedContentData() // new NamedContentData()
.AddField("field2", // .AddField("field2",
new ContentFieldData() // new ContentFieldData()
.AddValue("iv", 2)); // .AddValue("iv", 2));
private readonly NamedContentData patched; // private readonly NamedContentData patched;
private readonly Guid contentId = Guid.NewGuid(); // private readonly Guid contentId = Guid.NewGuid();
private readonly ContentDomainObject sut = new ContentDomainObject(); // private readonly ContentDomainObject sut = new ContentDomainObject();
protected override Guid Id // protected override Guid Id
{ // {
get { return contentId; } // get { return contentId; }
} // }
public ContentDomainObjectTests() // public ContentDomainObjectTests()
{ // {
patched = otherData.MergeInto(data); // patched = otherData.MergeInto(data);
sut.ActivateAsync(Id, A.Fake<IStore<Guid>>()); // sut.ActivateAsync(Id, A.Fake<IStore<Guid>>());
} // }
[Fact] // [Fact]
public void Create_should_throw_exception_if_created() // public void Create_should_throw_exception_if_created()
{ // {
sut.Create(CreateCommand(new CreateContent { Data = data })); // sut.Create(CreateCommand(new CreateContent { Data = data }));
Assert.Throws<DomainException>(() => // Assert.Throws<DomainException>(() =>
{ // {
sut.Create(CreateContentCommand(new CreateContent { Data = data })); // sut.Create(CreateContentCommand(new CreateContent { Data = data }));
}); // });
} // }
[Fact] // [Fact]
public void Create_should_create_events() // public void Create_should_create_events()
{ // {
sut.Create(CreateContentCommand(new CreateContent { Data = data })); // sut.Create(CreateContentCommand(new CreateContent { Data = data }));
sut.GetUncomittedEvents() // sut.GetUncomittedEvents()
.ShouldHaveSameEvents( // .ShouldHaveSameEvents(
CreateContentEvent(new ContentCreated { Data = data }) // CreateContentEvent(new ContentCreated { Data = data })
); // );
} // }
[Fact] // [Fact]
public void Create_should_also_publish_if_set_to_true() // public void Create_should_also_publish_if_set_to_true()
{ // {
sut.Create(CreateContentCommand(new CreateContent { Data = data, Publish = true })); // sut.Create(CreateContentCommand(new CreateContent { Data = data, Publish = true }));
sut.GetUncomittedEvents() // sut.GetUncomittedEvents()
.ShouldHaveSameEvents( // .ShouldHaveSameEvents(
CreateContentEvent(new ContentCreated { Data = data }), // CreateContentEvent(new ContentCreated { Data = data }),
CreateContentEvent(new ContentStatusChanged { Status = Status.Published }) // CreateContentEvent(new ContentStatusChanged { Status = Status.Published })
); // );
} // }
[Fact] // [Fact]
public void Update_should_throw_exception_if_not_created() // public void Update_should_throw_exception_if_not_created()
{ // {
Assert.Throws<DomainException>(() => // Assert.Throws<DomainException>(() =>
{ // {
sut.Update(CreateContentCommand(new UpdateContent { Data = data })); // sut.Update(CreateContentCommand(new UpdateContent { Data = data }));
}); // });
} // }
[Fact] // [Fact]
public void Update_should_throw_exception_if_content_is_deleted() // public void Update_should_throw_exception_if_content_is_deleted()
{ // {
CreateContent(); // CreateContent();
DeleteContent(); // DeleteContent();
Assert.Throws<DomainException>(() => // Assert.Throws<DomainException>(() =>
{ // {
sut.Update(CreateContentCommand(new UpdateContent())); // sut.Update(CreateContentCommand(new UpdateContent()));
}); // });
} // }
[Fact] // [Fact]
public void Update_should_create_events() // public void Update_should_create_events()
{ // {
CreateContent(); // CreateContent();
sut.Update(CreateContentCommand(new UpdateContent { Data = otherData })); // sut.Update(CreateContentCommand(new UpdateContent { Data = otherData }));
sut.GetUncomittedEvents() // sut.GetUncomittedEvents()
.ShouldHaveSameEvents( // .ShouldHaveSameEvents(
CreateContentEvent(new ContentUpdated { Data = otherData }) // CreateContentEvent(new ContentUpdated { Data = otherData })
); // );
} // }
[Fact] // [Fact]
public void Update_should_not_create_event_for_same_data() // public void Update_should_not_create_event_for_same_data()
{ // {
CreateContent(); // CreateContent();
UpdateContent(); // UpdateContent();
sut.Update(CreateContentCommand(new UpdateContent { Data = data })); // sut.Update(CreateContentCommand(new UpdateContent { Data = data }));
sut.GetUncomittedEvents().Should().BeEmpty(); // sut.GetUncomittedEvents().Should().BeEmpty();
} // }
[Fact] // [Fact]
public void Patch_should_throw_exception_if_not_created() // public void Patch_should_throw_exception_if_not_created()
{ // {
Assert.Throws<DomainException>(() => // Assert.Throws<DomainException>(() =>
{ // {
sut.Patch(CreateContentCommand(new PatchContent { Data = data })); // sut.Patch(CreateContentCommand(new PatchContent { Data = data }));
}); // });
} // }
[Fact] // [Fact]
public void Patch_should_throw_exception_if_content_is_deleted() // public void Patch_should_throw_exception_if_content_is_deleted()
{ // {
CreateContent(); // CreateContent();
DeleteContent(); // DeleteContent();
Assert.Throws<DomainException>(() => // Assert.Throws<DomainException>(() =>
{ // {
sut.Patch(CreateContentCommand(new PatchContent())); // sut.Patch(CreateContentCommand(new PatchContent()));
}); // });
} // }
[Fact] // [Fact]
public void Patch_should_create_events() // public void Patch_should_create_events()
{ // {
CreateContent(); // CreateContent();
UpdateContent(); // UpdateContent();
sut.Patch(CreateContentCommand(new PatchContent { Data = otherData })); // sut.Patch(CreateContentCommand(new PatchContent { Data = otherData }));
sut.GetUncomittedEvents() // sut.GetUncomittedEvents()
.ShouldHaveSameEvents( // .ShouldHaveSameEvents(
CreateContentEvent(new ContentUpdated { Data = patched }) // CreateContentEvent(new ContentUpdated { Data = patched })
); // );
} // }
[Fact] // [Fact]
public void Patch_should_not_create_event_for_same_data() // public void Patch_should_not_create_event_for_same_data()
{ // {
CreateContent(); // CreateContent();
UpdateContent(); // UpdateContent();
sut.Patch(CreateContentCommand(new PatchContent { Data = data })); // sut.Patch(CreateContentCommand(new PatchContent { Data = data }));
sut.GetUncomittedEvents().Should().BeEmpty(); // sut.GetUncomittedEvents().Should().BeEmpty();
} // }
[Fact] // [Fact]
public void ChangeStatus_should_throw_exception_if_not_created() // public void ChangeStatus_should_throw_exception_if_not_created()
{ // {
Assert.Throws<DomainException>(() => // Assert.Throws<DomainException>(() =>
{ // {
sut.ChangeStatus(CreateContentCommand(new ChangeContentStatus())); // sut.ChangeStatus(CreateContentCommand(new ChangeContentStatus()));
}); // });
} // }
[Fact] // [Fact]
public void ChangeStatus_should_throw_exception_if_content_is_deleted() // public void ChangeStatus_should_throw_exception_if_content_is_deleted()
{ // {
CreateContent(); // CreateContent();
DeleteContent(); // DeleteContent();
Assert.Throws<DomainException>(() => // Assert.Throws<DomainException>(() =>
{ // {
sut.ChangeStatus(CreateContentCommand(new ChangeContentStatus())); // sut.ChangeStatus(CreateContentCommand(new ChangeContentStatus()));
}); // });
} // }
[Fact] // [Fact]
public void ChangeStatus_should_refresh_properties_and_create_events() // public void ChangeStatus_should_refresh_properties_and_create_events()
{ // {
CreateContent(); // CreateContent();
sut.ChangeStatus(CreateContentCommand(new ChangeContentStatus { Status = Status.Published })); // sut.ChangeStatus(CreateContentCommand(new ChangeContentStatus { Status = Status.Published }));
Assert.Equal(Status.Published, sut.Snapshot.Status); // Assert.Equal(Status.Published, sut.Snapshot.Status);
sut.GetUncomittedEvents() // sut.GetUncomittedEvents()
.ShouldHaveSameEvents( // .ShouldHaveSameEvents(
CreateContentEvent(new ContentStatusChanged { Status = Status.Published }) // CreateContentEvent(new ContentStatusChanged { Status = Status.Published })
); // );
} // }
[Fact] // [Fact]
public void ChangeStatus_should_refresh_properties_and_create_scheduled_events_when_command_has_due_time() // public void ChangeStatus_should_refresh_properties_and_create_scheduled_events_when_command_has_due_time()
{ // {
CreateContent(); // CreateContent();
var dueTime = Instant.MaxValue; // var dueTime = Instant.MaxValue;
sut.ChangeStatus(CreateContentCommand(new ChangeContentStatus { Status = Status.Published, DueTime = dueTime })); // sut.ChangeStatus(CreateContentCommand(new ChangeContentStatus { Status = Status.Published, DueTime = dueTime }));
Assert.Equal(Status.Draft, sut.Snapshot.Status); // Assert.Equal(Status.Draft, sut.Snapshot.Status);
Assert.Equal(Status.Published, sut.Snapshot.ScheduledTo); // Assert.Equal(Status.Published, sut.Snapshot.ScheduledTo);
Assert.Equal(dueTime, sut.Snapshot.ScheduledAt); // Assert.Equal(dueTime, sut.Snapshot.ScheduledAt);
sut.GetUncomittedEvents() // sut.GetUncomittedEvents()
.ShouldHaveSameEvents( // .ShouldHaveSameEvents(
CreateContentEvent(new ContentStatusScheduled { Status = Status.Published, DueTime = dueTime }) // CreateContentEvent(new ContentStatusScheduled { Status = Status.Published, DueTime = dueTime })
); // );
} // }
[Fact] // [Fact]
public void Delete_should_throw_exception_if_not_created() // public void Delete_should_throw_exception_if_not_created()
{ // {
Assert.Throws<DomainException>(() => // Assert.Throws<DomainException>(() =>
{ // {
sut.Delete(CreateContentCommand(new DeleteContent())); // sut.Delete(CreateContentCommand(new DeleteContent()));
}); // });
} // }
[Fact] // [Fact]
public void Delete_should_throw_exception_if_already_deleted() // public void Delete_should_throw_exception_if_already_deleted()
{ // {
CreateContent(); // CreateContent();
DeleteContent(); // DeleteContent();
Assert.Throws<DomainException>(() => // Assert.Throws<DomainException>(() =>
{ // {
sut.Delete(CreateContentCommand(new DeleteContent())); // sut.Delete(CreateContentCommand(new DeleteContent()));
}); // });
} // }
[Fact] // [Fact]
public void Delete_should_update_properties_and_create_events() // public void Delete_should_update_properties_and_create_events()
{ // {
CreateContent(); // CreateContent();
sut.Delete(CreateContentCommand(new DeleteContent())); // sut.Delete(CreateContentCommand(new DeleteContent()));
Assert.True(sut.Snapshot.IsDeleted); // Assert.True(sut.Snapshot.IsDeleted);
sut.GetUncomittedEvents() // sut.GetUncomittedEvents()
.ShouldHaveSameEvents( // .ShouldHaveSameEvents(
CreateContentEvent(new ContentDeleted()) // CreateContentEvent(new ContentDeleted())
); // );
} // }
private void CreateContent() // private void CreateContent()
{ // {
sut.Create(CreateContentCommand(new CreateContent { Data = data })); // sut.Create(CreateContentCommand(new CreateContent { Data = data }));
sut.ClearUncommittedEvents(); // sut.ClearUncommittedEvents();
} // }
private void UpdateContent() // private void UpdateContent()
{ // {
sut.Update(CreateContentCommand(new UpdateContent { Data = data })); // sut.Update(CreateContentCommand(new UpdateContent { Data = data }));
sut.ClearUncommittedEvents(); // sut.ClearUncommittedEvents();
} // }
private void ChangeStatus(Status status) // private void ChangeStatus(Status status)
{ // {
sut.ChangeStatus(CreateContentCommand(new ChangeContentStatus { Status = status })); // sut.ChangeStatus(CreateContentCommand(new ChangeContentStatus { Status = status }));
sut.ClearUncommittedEvents(); // sut.ClearUncommittedEvents();
} // }
private void DeleteContent() // private void DeleteContent()
{ // {
sut.Delete(CreateContentCommand(new DeleteContent())); // sut.Delete(CreateContentCommand(new DeleteContent()));
sut.ClearUncommittedEvents(); // sut.ClearUncommittedEvents();
} // }
protected T CreateContentEvent<T>(T @event) where T : ContentEvent // protected T CreateContentEvent<T>(T @event) where T : ContentEvent
{ // {
@event.ContentId = contentId; // @event.ContentId = contentId;
return CreateEvent(@event); // return CreateEvent(@event);
} // }
protected T CreateContentCommand<T>(T command) where T : ContentCommand // protected T CreateContentCommand<T>(T command) where T : ContentCommand
{ // {
command.ContentId = contentId; // command.ContentId = contentId;
return CreateCommand(command); // return CreateCommand(command);
} // }
} // }
} //}

118
tests/Squidex.Domain.Apps.Entities.Tests/Rules/RuleCommandMiddlewareTests.cs

@ -1,118 +0,0 @@
// ==========================================================================
// Squidex Headless CMS
// ==========================================================================
// Copyright (c) Squidex UG (haftungsbeschränkt)
// All rights reserved. Licensed under the MIT license.
// ==========================================================================
using System;
using System.Threading.Tasks;
using FakeItEasy;
using Squidex.Domain.Apps.Core.Rules;
using Squidex.Domain.Apps.Core.Rules.Actions;
using Squidex.Domain.Apps.Core.Rules.Triggers;
using Squidex.Domain.Apps.Entities.Rules.Commands;
using Squidex.Domain.Apps.Entities.Schemas;
using Squidex.Domain.Apps.Entities.TestHelpers;
using Squidex.Infrastructure.Commands;
using Xunit;
namespace Squidex.Domain.Apps.Entities.Rules
{
public class RuleCommandMiddlewareTests : HandlerTestBase<RuleDomainObject>
{
private readonly IAppProvider appProvider = A.Fake<IAppProvider>();
private readonly RuleDomainObject rule = new RuleDomainObject();
private readonly RuleTrigger ruleTrigger = new ContentChangedTrigger();
private readonly RuleAction ruleAction = new WebhookAction { Url = new Uri("https://squidex.io") };
private readonly Guid ruleId = Guid.NewGuid();
private readonly RuleCommandMiddleware sut;
protected override Guid Id
{
get { return ruleId; }
}
public RuleCommandMiddlewareTests()
{
A.CallTo(() => appProvider.GetSchemaAsync(A<Guid>.Ignored, A<Guid>.Ignored, false))
.Returns(A.Fake<ISchemaEntity>());
sut = new RuleCommandMiddleware(Handler, appProvider);
}
[Fact]
public async Task Create_should_create_domain_object()
{
var context = CreateContextForCommand(new CreateRule { Trigger = ruleTrigger, Action = ruleAction });
await TestCreate(rule, async _ =>
{
await sut.HandleAsync(context);
});
}
[Fact]
public async Task Update_should_update_domain_object()
{
var context = CreateContextForCommand(new UpdateRule { Trigger = ruleTrigger, Action = ruleAction });
CreateRule();
await TestUpdate(rule, async _ =>
{
await sut.HandleAsync(context);
});
}
[Fact]
public async Task Enable_should_update_domain_object()
{
CreateRule();
DisableRule();
var command = CreateContextForCommand(new EnableRule { RuleId = ruleId });
await TestUpdate(rule, async _ =>
{
await sut.HandleAsync(command);
});
}
[Fact]
public async Task Disable_should_update_domain_object()
{
CreateRule();
var command = CreateContextForCommand(new DisableRule { RuleId = ruleId });
await TestUpdate(rule, async _ =>
{
await sut.HandleAsync(command);
});
}
[Fact]
public async Task Delete_should_update_domain_object()
{
CreateRule();
var command = CreateContextForCommand(new DeleteRule { RuleId = ruleId });
await TestUpdate(rule, async _ =>
{
await sut.HandleAsync(command);
});
}
private void DisableRule()
{
rule.Disable(CreateCommand(new DisableRule()));
}
private void CreateRule()
{
rule.Create(CreateCommand(new CreateRule { Trigger = ruleTrigger, Action = ruleAction }));
}
}
}

2
tests/Squidex.Domain.Apps.Entities.Tests/Rules/RuleDequeuerTests.cs

@ -69,8 +69,6 @@ namespace Squidex.Domain.Apps.Entities.Rules
await sut.HandleAsync(@event); await sut.HandleAsync(@event);
sut.Dispose();
A.CallTo(() => ruleEventRepository.MarkSentAsync(@event.Id, requestDump, result, jobResult, requestElapsed, nextCall)) A.CallTo(() => ruleEventRepository.MarkSentAsync(@event.Id, requestDump, result, jobResult, requestElapsed, nextCall))
.MustHaveHappened(); .MustHaveHappened();
} }

256
tests/Squidex.Domain.Apps.Entities.Tests/Rules/RuleDomainObjectTests.cs

@ -1,256 +0,0 @@
// ==========================================================================
// Squidex Headless CMS
// ==========================================================================
// Copyright (c) Squidex UG (haftungsbeschränkt)
// All rights reserved. Licensed under the MIT license.
// ==========================================================================
using System;
using System.Collections.Immutable;
using FakeItEasy;
using Squidex.Domain.Apps.Core.Rules;
using Squidex.Domain.Apps.Core.Rules.Actions;
using Squidex.Domain.Apps.Core.Rules.Triggers;
using Squidex.Domain.Apps.Entities.Rules.Commands;
using Squidex.Domain.Apps.Entities.TestHelpers;
using Squidex.Domain.Apps.Events.Rules;
using Squidex.Infrastructure;
using Squidex.Infrastructure.States;
using Xunit;
namespace Squidex.Domain.Apps.Entities.Rules
{
public class RuleDomainObjectTests : HandlerTestBase<RuleDomainObject>
{
private readonly Guid ruleId = Guid.NewGuid();
private readonly RuleTrigger ruleTrigger = new ContentChangedTrigger();
private readonly RuleAction ruleAction = new WebhookAction { Url = new Uri("https://squidex.io") };
private readonly RuleDomainObject sut = new RuleDomainObject();
protected override Guid Id
{
get { return ruleId; }
}
public RuleDomainObjectTests()
{
sut.ActivateAsync(Id, A.Fake<IStore<Guid>>());
}
[Fact]
public void Create_should_throw_exception_if_created()
{
sut.Create(CreateRuleCommand(new CreateRule { Trigger = ruleTrigger, Action = ruleAction }));
Assert.Throws<DomainException>(() =>
{
sut.Create(CreateRuleCommand(new CreateRule { Trigger = ruleTrigger, Action = ruleAction }));
});
}
[Fact]
public void Create_should_create_events()
{
var command = new CreateRule { Trigger = ruleTrigger, Action = ruleAction };
sut.Create(CreateRuleCommand(command));
Assert.Equal(AppId, sut.Snapshot.AppId.Id);
Assert.Same(ruleTrigger, sut.Snapshot.RuleDef.Trigger);
Assert.Same(ruleAction, sut.Snapshot.RuleDef.Action);
sut.GetUncomittedEvents()
.ShouldHaveSameEvents(
CreateRuleEvent(new RuleCreated { Trigger = ruleTrigger, Action = ruleAction })
);
}
[Fact]
public void Update_should_throw_exception_if_not_created()
{
Assert.Throws<DomainException>(() =>
{
sut.Update(CreateRuleCommand(new UpdateRule { Trigger = ruleTrigger, Action = ruleAction }));
});
}
[Fact]
public void Update_should_throw_exception_if_rule_is_deleted()
{
CreateRule();
DeleteRule();
Assert.Throws<DomainException>(() =>
{
sut.Update(CreateRuleCommand(new UpdateRule { Trigger = ruleTrigger, Action = ruleAction }));
});
}
[Fact]
public void Update_should_create_events()
{
var newTrigger = new ContentChangedTrigger
{
Schemas = ImmutableList<ContentChangedTriggerSchema>.Empty
};
var newAction = new WebhookAction
{
Url = new Uri("https://squidex.io/v2")
};
CreateRule();
var command = new UpdateRule { Trigger = newTrigger, Action = newAction };
sut.Update(CreateRuleCommand(command));
Assert.Same(newTrigger, sut.Snapshot.RuleDef.Trigger);
Assert.Same(newAction, sut.Snapshot.RuleDef.Action);
sut.GetUncomittedEvents()
.ShouldHaveSameEvents(
CreateRuleEvent(new RuleUpdated { Trigger = newTrigger, Action = newAction })
);
}
[Fact]
public void Enable_should_throw_exception_if_not_created()
{
Assert.Throws<DomainException>(() =>
{
sut.Enable(CreateRuleCommand(new EnableRule()));
});
}
[Fact]
public void Enable_should_throw_exception_if_rule_is_deleted()
{
CreateRule();
DeleteRule();
Assert.Throws<DomainException>(() =>
{
sut.Enable(CreateRuleCommand(new EnableRule()));
});
}
[Fact]
public void Enable_should_create_events()
{
CreateRule();
var command = new EnableRule();
sut.Enable(CreateRuleCommand(command));
Assert.True(sut.Snapshot.RuleDef.IsEnabled);
sut.GetUncomittedEvents()
.ShouldHaveSameEvents(
CreateRuleEvent(new RuleEnabled())
);
}
[Fact]
public void Disable_should_throw_exception_if_not_created()
{
Assert.Throws<DomainException>(() =>
{
sut.Disable(CreateRuleCommand(new DisableRule()));
});
}
[Fact]
public void Disable_should_throw_exception_if_rule_is_deleted()
{
CreateRule();
DeleteRule();
Assert.Throws<DomainException>(() =>
{
sut.Disable(CreateRuleCommand(new DisableRule()));
});
}
[Fact]
public void Disable_should_create_events()
{
CreateRule();
var command = new DisableRule();
sut.Disable(CreateRuleCommand(command));
Assert.False(sut.Snapshot.RuleDef.IsEnabled);
sut.GetUncomittedEvents()
.ShouldHaveSameEvents(
CreateRuleEvent(new RuleDisabled())
);
}
[Fact]
public void Delete_should_throw_exception_if_not_created()
{
Assert.Throws<DomainException>(() =>
{
sut.Delete(CreateRuleCommand(new DeleteRule()));
});
}
[Fact]
public void Delete_should_throw_exception_if_already_deleted()
{
CreateRule();
DeleteRule();
Assert.Throws<DomainException>(() =>
{
sut.Delete(CreateRuleCommand(new DeleteRule()));
});
}
[Fact]
public void Delete_should_update_create_events()
{
CreateRule();
sut.Delete(CreateRuleCommand(new DeleteRule()));
Assert.True(sut.Snapshot.IsDeleted);
sut.GetUncomittedEvents()
.ShouldHaveSameEvents(
CreateRuleEvent(new RuleDeleted())
);
}
private void CreateRule()
{
sut.Create(CreateRuleCommand(new CreateRule { Trigger = ruleTrigger, Action = ruleAction }));
sut.ClearUncommittedEvents();
}
private void DeleteRule()
{
sut.Delete(CreateRuleCommand(new DeleteRule()));
sut.ClearUncommittedEvents();
}
protected T CreateRuleEvent<T>(T @event) where T : RuleEvent
{
@event.RuleId = ruleId;
return CreateEvent(@event);
}
protected T CreateRuleCommand<T>(T command) where T : RuleCommand
{
command.RuleId = ruleId;
return CreateCommand(command);
}
}
}

227
tests/Squidex.Domain.Apps.Entities.Tests/Rules/RuleGrainTests.cs

@ -0,0 +1,227 @@
// ==========================================================================
// Squidex Headless CMS
// ==========================================================================
// Copyright (c) Squidex UG (haftungsbeschränkt)
// All rights reserved. Licensed under the MIT license.
// ==========================================================================
using System;
using System.Collections.Immutable;
using System.Threading.Tasks;
using FakeItEasy;
using Orleans.Core;
using Orleans.Runtime;
using Squidex.Domain.Apps.Core.Rules.Actions;
using Squidex.Domain.Apps.Core.Rules.Triggers;
using Squidex.Domain.Apps.Entities.Rules.Commands;
using Squidex.Domain.Apps.Entities.Rules.State;
using Squidex.Domain.Apps.Entities.TestHelpers;
using Squidex.Domain.Apps.Events.Rules;
using Squidex.Infrastructure;
using Squidex.Infrastructure.Commands;
using Squidex.Infrastructure.States;
using Xunit;
namespace Squidex.Domain.Apps.Entities.Rules
{
public class RuleDomainObjectTests : HandlerTestBase<RuleGrain, RuleState>
{
private readonly IAppProvider appProvider = A.Fake<IAppProvider>();
private readonly Guid ruleId = Guid.NewGuid();
private readonly RuleGrain sut;
public sealed class MyRuleGrain : RuleGrain
{
public MyRuleGrain(IStore<Guid> store, IAppProvider appProvider, IGrainIdentity identity, IGrainRuntime runtime)
: base(store, appProvider, identity, runtime)
{
}
}
protected override Guid Id
{
get { return ruleId; }
}
public RuleDomainObjectTests()
{
sut = new MyRuleGrain(Store, appProvider, Identity, Runtime);
sut.OnActivateAsync().Wait();
}
[Fact]
public async Task Command_should_throw_exception_if_rule_is_deleted()
{
await CreateAsync();
await DeleteAsync();
await Assert.ThrowsAsync<DomainException>(() =>
{
return sut.ExecuteAsync(J(CreateRuleCommand(MakeUpdateCommand())));
});
}
[Fact]
public async Task Create_should_create_events()
{
var command = MakeCreateCommand();
var result = await sut.ExecuteAsync(J(CreateRuleCommand(command)));
Assert.True(result.Value is EntityCreatedResult<Guid>);
Assert.Equal(AppId, sut.Snapshot.AppId.Id);
Assert.Same(command.Trigger, sut.Snapshot.RuleDef.Trigger);
Assert.Same(command.Action, sut.Snapshot.RuleDef.Action);
LastEvents
.ShouldHaveSameEvents(
CreateRuleEvent(new RuleCreated { Trigger = command.Trigger, Action = command.Action })
);
}
[Fact]
public async Task Update_should_handle_command()
{
await sut.ExecuteAsync(J(CreateRuleCommand(MakeCreateCommand())));
var result = await sut.ExecuteAsync(J(CreateRuleCommand(MakeUpdateCommand())));
Assert.True(result.Value is EntitySavedResult);
}
[Fact]
public async Task Update_should_create_events()
{
var command = MakeUpdateCommand();
await CreateAsync();
var result = await sut.ExecuteAsync(J(CreateRuleCommand(command)));
Assert.True(result.Value is EntitySavedResult);
Assert.Same(command.Trigger, sut.Snapshot.RuleDef.Trigger);
Assert.Same(command.Action, sut.Snapshot.RuleDef.Action);
LastEvents
.ShouldHaveSameEvents(
CreateRuleEvent(new RuleUpdated { Trigger = command.Trigger, Action = command.Action })
);
}
[Fact]
public async Task Enable_should_handle_command()
{
await sut.ExecuteAsync(J(CreateRuleCommand(MakeCreateCommand())));
await sut.ExecuteAsync(J(CreateRuleCommand(new DisableRule())));
}
[Fact]
public async Task Enable_should_create_events()
{
await CreateAsync();
await sut.ExecuteAsync(J(CreateRuleCommand(new DisableRule())));
var result = await sut.ExecuteAsync(J(CreateRuleCommand(new EnableRule())));
Assert.True(result.Value is EntitySavedResult);
Assert.True(sut.Snapshot.RuleDef.IsEnabled);
LastEvents
.ShouldHaveSameEvents(
CreateRuleEvent(new RuleEnabled())
);
}
[Fact]
public async Task Disable_should_create_events()
{
await CreateAsync();
var result = await sut.ExecuteAsync(J(CreateRuleCommand(new DisableRule())));
Assert.True(result.Value is EntitySavedResult);
Assert.False(sut.Snapshot.RuleDef.IsEnabled);
LastEvents
.ShouldHaveSameEvents(
CreateRuleEvent(new RuleDisabled())
);
}
[Fact]
public async Task Delete_should_update_create_events()
{
await CreateAsync();
var result = await sut.ExecuteAsync(J(CreateRuleCommand(new DeleteRule())));
Assert.True(result.Value is EntitySavedResult);
Assert.True(sut.Snapshot.IsDeleted);
LastEvents
.ShouldHaveSameEvents(
CreateRuleEvent(new RuleDeleted())
);
}
private Task CreateAsync()
{
return sut.ExecuteAsync(J(CreateRuleCommand(MakeCreateCommand())));
}
private Task DeleteAsync()
{
return sut.ExecuteAsync(J(CreateRuleCommand(new DeleteRule())));
}
protected T CreateRuleEvent<T>(T @event) where T : RuleEvent
{
@event.RuleId = ruleId;
return CreateEvent(@event);
}
protected T CreateRuleCommand<T>(T command) where T : RuleCommand
{
command.RuleId = ruleId;
return CreateCommand(command);
}
private CreateRule MakeCreateCommand()
{
var newTrigger = new ContentChangedTrigger
{
Schemas = ImmutableList<ContentChangedTriggerSchema>.Empty
};
var newAction = new WebhookAction
{
Url = new Uri("https://squidex.io/v2")
};
return new CreateRule { Trigger = newTrigger, Action = newAction };
}
private static UpdateRule MakeUpdateCommand()
{
var newTrigger = new ContentChangedTrigger
{
Schemas = ImmutableList<ContentChangedTriggerSchema>.Empty
};
var newAction = new WebhookAction
{
Url = new Uri("https://squidex.io/v2")
};
return new UpdateRule { Trigger = newTrigger, Action = newAction };
}
}
}

560
tests/Squidex.Domain.Apps.Entities.Tests/Schemas/SchemaCommandMiddlewareTests.cs

@ -1,280 +1,280 @@
// ========================================================================== //// ==========================================================================
// Squidex Headless CMS //// Squidex Headless CMS
// ========================================================================== //// ==========================================================================
// Copyright (c) Squidex UG (haftungsbeschränkt) //// Copyright (c) Squidex UG (haftungsbeschränkt)
// All rights reserved. Licensed under the MIT license. //// All rights reserved. Licensed under the MIT license.
// ========================================================================== //// ==========================================================================
using System; //using System;
using System.Collections.Generic; //using System.Collections.Generic;
using System.Threading.Tasks; //using System.Threading.Tasks;
using FakeItEasy; //using FakeItEasy;
using Squidex.Domain.Apps.Core.Schemas; //using Squidex.Domain.Apps.Core.Schemas;
using Squidex.Domain.Apps.Entities.Schemas.Commands; //using Squidex.Domain.Apps.Entities.Schemas.Commands;
using Squidex.Domain.Apps.Entities.TestHelpers; //using Squidex.Domain.Apps.Entities.TestHelpers;
using Squidex.Infrastructure; //using Squidex.Infrastructure;
using Squidex.Infrastructure.Commands; //using Squidex.Infrastructure.Commands;
using Xunit; //using Xunit;
namespace Squidex.Domain.Apps.Entities.Schemas //namespace Squidex.Domain.Apps.Entities.Schemas
{ //{
public class SchemaCommandMiddlewareTests : HandlerTestBase<SchemaDomainObject> // public class SchemaCommandMiddlewareTests : HandlerTestBase<SchemaDomainObject>
{ // {
private readonly IAppProvider appProvider = A.Fake<IAppProvider>(); // private readonly IAppProvider appProvider = A.Fake<IAppProvider>();
private readonly SchemaCommandMiddleware sut; // private readonly SchemaCommandMiddleware sut;
private readonly SchemaDomainObject schema; // private readonly SchemaDomainObject schema;
private readonly FieldRegistry registry = new FieldRegistry(new TypeNameRegistry()); // private readonly FieldRegistry registry = new FieldRegistry(new TypeNameRegistry());
private readonly string fieldName = "age"; // private readonly string fieldName = "age";
protected override Guid Id // protected override Guid Id
{ // {
get { return SchemaId; } // get { return SchemaId; }
} // }
public SchemaCommandMiddlewareTests() // public SchemaCommandMiddlewareTests()
{ // {
schema = new SchemaDomainObject(registry); // schema = new SchemaDomainObject(registry);
sut = new SchemaCommandMiddleware(Handler, appProvider); // sut = new SchemaCommandMiddleware(Handler, appProvider);
A.CallTo(() => appProvider.GetSchemaAsync(AppId, SchemaName)) // A.CallTo(() => appProvider.GetSchemaAsync(AppId, SchemaName))
.Returns((ISchemaEntity)null); // .Returns((ISchemaEntity)null);
} // }
[Fact] // [Fact]
public async Task Create_should_create_schema_domain_object() // public async Task Create_should_create_schema_domain_object()
{ // {
var context = CreateContextForCommand(new CreateSchema { Name = SchemaName, SchemaId = SchemaId }); // var context = CreateContextForCommand(new CreateSchema { Name = SchemaName, SchemaId = SchemaId });
await TestCreate(schema, async _ => // await TestCreate(schema, async _ =>
{ // {
await sut.HandleAsync(context); // await sut.HandleAsync(context);
}); // });
Assert.Equal(SchemaId, context.Result<EntityCreatedResult<Guid>>().IdOrValue); // Assert.Equal(SchemaId, context.Result<EntityCreatedResult<Guid>>().IdOrValue);
A.CallTo(() => appProvider.GetSchemaAsync(AppId, SchemaName)).MustHaveHappened(); // A.CallTo(() => appProvider.GetSchemaAsync(AppId, SchemaName)).MustHaveHappened();
} // }
[Fact] // [Fact]
public async Task UpdateSchema_should_update_domain_object() // public async Task UpdateSchema_should_update_domain_object()
{ // {
CreateSchema(); // CreateSchema();
var context = CreateContextForCommand(new UpdateSchema { Properties = new SchemaProperties() }); // var context = CreateContextForCommand(new UpdateSchema { Properties = new SchemaProperties() });
await TestUpdate(schema, async _ => // await TestUpdate(schema, async _ =>
{ // {
await sut.HandleAsync(context); // await sut.HandleAsync(context);
}); // });
} // }
[Fact] // [Fact]
public async Task ReorderSchema_should_update_domain_object() // public async Task ReorderSchema_should_update_domain_object()
{ // {
CreateSchema(); // CreateSchema();
var context = CreateContextForCommand(new ReorderFields { FieldIds = new List<long>() }); // var context = CreateContextForCommand(new ReorderFields { FieldIds = new List<long>() });
await TestUpdate(schema, async _ => // await TestUpdate(schema, async _ =>
{ // {
await sut.HandleAsync(context); // await sut.HandleAsync(context);
}); // });
} // }
[Fact] // [Fact]
public async Task PublishSchema_should_update_domain_object() // public async Task PublishSchema_should_update_domain_object()
{ // {
CreateSchema(); // CreateSchema();
var context = CreateContextForCommand(new PublishSchema()); // var context = CreateContextForCommand(new PublishSchema());
await TestUpdate(schema, async _ => // await TestUpdate(schema, async _ =>
{ // {
await sut.HandleAsync(context); // await sut.HandleAsync(context);
}); // });
} // }
[Fact] // [Fact]
public async Task UnpublishSchema_should_update_domain_object() // public async Task UnpublishSchema_should_update_domain_object()
{ // {
CreateSchema(); // CreateSchema();
PublishSchema(); // PublishSchema();
var context = CreateContextForCommand(new UnpublishSchema()); // var context = CreateContextForCommand(new UnpublishSchema());
await TestUpdate(schema, async _ => // await TestUpdate(schema, async _ =>
{ // {
await sut.HandleAsync(context); // await sut.HandleAsync(context);
}); // });
} // }
[Fact] // [Fact]
public async Task ConfigureScripts_should_update_domain_object() // public async Task ConfigureScripts_should_update_domain_object()
{ // {
CreateSchema(); // CreateSchema();
var context = CreateContextForCommand(new ConfigureScripts()); // var context = CreateContextForCommand(new ConfigureScripts());
await TestUpdate(schema, async _ => // await TestUpdate(schema, async _ =>
{ // {
await sut.HandleAsync(context); // await sut.HandleAsync(context);
}); // });
} // }
[Fact] // [Fact]
public async Task DeleteSchema_should_update_domain_object() // public async Task DeleteSchema_should_update_domain_object()
{ // {
CreateSchema(); // CreateSchema();
var context = CreateContextForCommand(new DeleteSchema()); // var context = CreateContextForCommand(new DeleteSchema());
await TestUpdate(schema, async _ => // await TestUpdate(schema, async _ =>
{ // {
await sut.HandleAsync(context); // await sut.HandleAsync(context);
}); // });
} // }
[Fact] // [Fact]
public async Task Add_should_update_domain_object() // public async Task Add_should_update_domain_object()
{ // {
CreateSchema(); // CreateSchema();
var context = CreateContextForCommand(new AddField { Name = fieldName, Properties = new NumberFieldProperties() }); // var context = CreateContextForCommand(new AddField { Name = fieldName, Properties = new NumberFieldProperties() });
await TestUpdate(schema, async _ => // await TestUpdate(schema, async _ =>
{ // {
await sut.HandleAsync(context); // await sut.HandleAsync(context);
}); // });
Assert.Equal(1, context.Result<EntityCreatedResult<long>>().IdOrValue); // Assert.Equal(1, context.Result<EntityCreatedResult<long>>().IdOrValue);
} // }
[Fact] // [Fact]
public async Task UpdateField_should_update_domain_object() // public async Task UpdateField_should_update_domain_object()
{ // {
CreateSchema(); // CreateSchema();
CreateField(); // CreateField();
var context = CreateContextForCommand(new UpdateField { FieldId = 1, Properties = new NumberFieldProperties() }); // var context = CreateContextForCommand(new UpdateField { FieldId = 1, Properties = new NumberFieldProperties() });
await TestUpdate(schema, async _ => // await TestUpdate(schema, async _ =>
{ // {
await sut.HandleAsync(context); // await sut.HandleAsync(context);
}); // });
} // }
[Fact] // [Fact]
public async Task LockField_should_update_domain_object() // public async Task LockField_should_update_domain_object()
{ // {
CreateSchema(); // CreateSchema();
CreateField(); // CreateField();
var context = CreateContextForCommand(new LockField { FieldId = 1 }); // var context = CreateContextForCommand(new LockField { FieldId = 1 });
await TestUpdate(schema, async _ => // await TestUpdate(schema, async _ =>
{ // {
await sut.HandleAsync(context); // await sut.HandleAsync(context);
}); // });
} // }
[Fact] // [Fact]
public async Task HideField_should_update_domain_object() // public async Task HideField_should_update_domain_object()
{ // {
CreateSchema(); // CreateSchema();
CreateField(); // CreateField();
var context = CreateContextForCommand(new HideField { FieldId = 1 }); // var context = CreateContextForCommand(new HideField { FieldId = 1 });
await TestUpdate(schema, async _ => // await TestUpdate(schema, async _ =>
{ // {
await sut.HandleAsync(context); // await sut.HandleAsync(context);
}); // });
} // }
[Fact] // [Fact]
public async Task ShowField_should_update_domain_object() // public async Task ShowField_should_update_domain_object()
{ // {
CreateSchema(); // CreateSchema();
CreateField(); // CreateField();
HideField(); // HideField();
var context = CreateContextForCommand(new ShowField { FieldId = 1 }); // var context = CreateContextForCommand(new ShowField { FieldId = 1 });
await TestUpdate(schema, async _ => // await TestUpdate(schema, async _ =>
{ // {
await sut.HandleAsync(context); // await sut.HandleAsync(context);
}); // });
} // }
[Fact] // [Fact]
public async Task DisableField_should_update_domain_object() // public async Task DisableField_should_update_domain_object()
{ // {
CreateSchema(); // CreateSchema();
CreateField(); // CreateField();
var context = CreateContextForCommand(new DisableField { FieldId = 1 }); // var context = CreateContextForCommand(new DisableField { FieldId = 1 });
await TestUpdate(schema, async _ => // await TestUpdate(schema, async _ =>
{ // {
await sut.HandleAsync(context); // await sut.HandleAsync(context);
}); // });
} // }
[Fact] // [Fact]
public async Task EnableField_should_update_domain_object() // public async Task EnableField_should_update_domain_object()
{ // {
CreateSchema(); // CreateSchema();
CreateField(); // CreateField();
DisableField(); // DisableField();
var context = CreateContextForCommand(new EnableField { FieldId = 1 }); // var context = CreateContextForCommand(new EnableField { FieldId = 1 });
await TestUpdate(schema, async _ => // await TestUpdate(schema, async _ =>
{ // {
await sut.HandleAsync(context); // await sut.HandleAsync(context);
}); // });
} // }
[Fact] // [Fact]
public async Task DeleteField_should_update_domain_object() // public async Task DeleteField_should_update_domain_object()
{ // {
CreateSchema(); // CreateSchema();
CreateField(); // CreateField();
var context = CreateContextForCommand(new DeleteField { FieldId = 1 }); // var context = CreateContextForCommand(new DeleteField { FieldId = 1 });
await TestUpdate(schema, async _ => // await TestUpdate(schema, async _ =>
{ // {
await sut.HandleAsync(context); // await sut.HandleAsync(context);
}); // });
} // }
private void CreateSchema() // private void CreateSchema()
{ // {
schema.Create(CreateCommand(new CreateSchema { Name = SchemaName })); // schema.Create(CreateCommand(new CreateSchema { Name = SchemaName }));
} // }
private void PublishSchema() // private void PublishSchema()
{ // {
schema.Publish(CreateCommand(new PublishSchema())); // schema.Publish(CreateCommand(new PublishSchema()));
} // }
private void CreateField() // private void CreateField()
{ // {
schema.Add(CreateCommand(new AddField { Name = fieldName, Properties = new NumberFieldProperties() })); // schema.Add(CreateCommand(new AddField { Name = fieldName, Properties = new NumberFieldProperties() }));
} // }
private void HideField() // private void HideField()
{ // {
schema.HideField(CreateCommand(new HideField { FieldId = 1 })); // schema.HideField(CreateCommand(new HideField { FieldId = 1 }));
} // }
private void DisableField() // private void DisableField()
{ // {
schema.DisableField(CreateCommand(new DisableField { FieldId = 1 })); // schema.DisableField(CreateCommand(new DisableField { FieldId = 1 }));
} // }
} // }
} //}

1330
tests/Squidex.Domain.Apps.Entities.Tests/Schemas/SchemaDomainObjectTests.cs

File diff suppressed because it is too large

136
tests/Squidex.Domain.Apps.Entities.Tests/TestHelpers/HandlerTestBase.cs

@ -6,68 +6,29 @@
// ========================================================================== // ==========================================================================
using System; using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks; using System.Threading.Tasks;
using FakeItEasy; using FakeItEasy;
using Orleans.Core;
using Orleans.Runtime;
using Squidex.Domain.Apps.Events; using Squidex.Domain.Apps.Events;
using Squidex.Infrastructure; using Squidex.Infrastructure;
using Squidex.Infrastructure.Commands; using Squidex.Infrastructure.Commands;
using Squidex.Infrastructure.EventSourcing;
using Squidex.Infrastructure.Orleans;
using Squidex.Infrastructure.States; using Squidex.Infrastructure.States;
#pragma warning disable IDE0019 // Use pattern matching #pragma warning disable IDE0019 // Use pattern matching
namespace Squidex.Domain.Apps.Entities.TestHelpers namespace Squidex.Domain.Apps.Entities.TestHelpers
{ {
public abstract class HandlerTestBase<T> where T : IDomainObject public abstract class HandlerTestBase<T, TState> where T : IDomainObjectGrain
{ {
private sealed class MockupHandler : IAggregateHandler private readonly IGrainIdentity identity = A.Fake<IGrainIdentity>();
{ private readonly IGrainRuntime runtime = A.Fake<IGrainRuntime>();
private T domainObject; private readonly IStore<Guid> store = A.Fake<IStore<Guid>>();
private readonly IPersistence<TState> persistence = A.Fake<IPersistence<TState>>();
public bool IsCreated { get; private set; }
public bool IsUpdated { get; private set; }
public void Init(T newDomainObject)
{
domainObject = newDomainObject;
IsCreated = false;
IsUpdated = false;
}
public Task<V> CreateSyncedAsync<V>(CommandContext context, Func<V, Task> creator) where V : class, IDomainObject
{
return CreateAsync(context, creator);
}
public Task<V> UpdateSyncedAsync<V>(CommandContext context, Func<V, Task> creator) where V : class, IDomainObject
{
return UpdateAsync(context, creator);
}
public async Task<V> CreateAsync<V>(CommandContext context, Func<V, Task> creator) where V : class, IDomainObject
{
IsCreated = true;
var @do = domainObject as V;
await creator(domainObject as V);
return @do;
}
public async Task<V> UpdateAsync<V>(CommandContext context, Func<V, Task> updater) where V : class, IDomainObject
{
IsUpdated = true;
var @do = domainObject as V;
await updater(domainObject as V);
return @do;
}
}
private readonly MockupHandler handler = new MockupHandler();
protected RefToken User { get; } = new RefToken("subject", Guid.NewGuid().ToString()); protected RefToken User { get; } = new RefToken("subject", Guid.NewGuid().ToString());
@ -75,8 +36,6 @@ namespace Squidex.Domain.Apps.Entities.TestHelpers
protected Guid SchemaId { get; } = Guid.NewGuid(); protected Guid SchemaId { get; } = Guid.NewGuid();
protected abstract Guid Id { get; }
protected string AppName { get; } = "my-app"; protected string AppName { get; } = "my-app";
protected string SchemaName { get; } = "my-schema"; protected string SchemaName { get; } = "my-schema";
@ -91,44 +50,49 @@ namespace Squidex.Domain.Apps.Entities.TestHelpers
get { return new NamedId<Guid>(SchemaId, SchemaName); } get { return new NamedId<Guid>(SchemaId, SchemaName); }
} }
protected IAggregateHandler Handler protected abstract Guid Id { get; }
public IGrainIdentity Identity
{ {
get { return handler; } get { return identity; }
} }
protected CommandContext CreateContextForCommand<TCommand>(TCommand command) where TCommand : SquidexCommand public IGrainRuntime Runtime
{ {
return new CommandContext(CreateCommand(command), A.Dummy<ICommandBus>()); get { return runtime; }
} }
protected async Task TestCreate(T domainObject, Func<T, Task> action, bool shouldCreate = true) public IStore<Guid> Store
{ {
handler.Init(domainObject); get { return store; }
await domainObject.ActivateAsync(Id, A.Fake<IStore<Guid>>());
await action(domainObject);
if (!handler.IsCreated && shouldCreate)
{
throw new InvalidOperationException("Create not called.");
}
} }
protected async Task TestUpdate(T domainObject, Func<T, Task> action, bool shouldUpdate = true) public IEnumerable<Envelope<IEvent>> LastEvents { get; private set; } = Enumerable.Empty<Envelope<IEvent>>();
protected HandlerTestBase()
{ {
handler.Init(domainObject); A.CallTo(() => identity.PrimaryKey)
.Returns(Id);
await domainObject.ActivateAsync(Id, A.Fake<IStore<Guid>>()); A.CallTo(() => store.WithSnapshotsAndEventSourcing(A<Type>.Ignored, Id, A<Func<TState, Task>>.Ignored, A<Func<Envelope<IEvent>, Task>>.Ignored))
await action(domainObject); .Returns(persistence);
if (!handler.IsUpdated && shouldUpdate) A.CallTo(() => persistence.WriteEventsAsync(A<IEnumerable<Envelope<IEvent>>>.Ignored))
{ .Invokes(new Action<IEnumerable<Envelope<IEvent>>>(events =>
throw new InvalidOperationException("Update not called."); {
} LastEvents = events;
}));
}
protected CommandContext CreateContextForCommand<TCommand>(TCommand command) where TCommand : SquidexCommand
{
return new CommandContext(CreateCommand(command), A.Dummy<ICommandBus>());
} }
protected TCommand CreateCommand<TCommand>(TCommand command) where TCommand : SquidexCommand protected TCommand CreateCommand<TCommand>(TCommand command) where TCommand : SquidexCommand
{ {
command.ExpectedVersion = EtagVersion.Any;
if (command.Actor == null) if (command.Actor == null)
{ {
command.Actor = User; command.Actor = User;
@ -147,25 +111,35 @@ namespace Squidex.Domain.Apps.Entities.TestHelpers
return command; return command;
} }
protected static J<IAggregateCommand> J(IAggregateCommand command)
{
return command.AsJ();
}
protected TEvent CreateEvent<TEvent>(TEvent @event) where TEvent : SquidexEvent protected TEvent CreateEvent<TEvent>(TEvent @event) where TEvent : SquidexEvent
{ {
@event.Actor = User; @event.Actor = User;
var appEvent = @event as AppEvent; EnrichAppInfo(@event);
EnrichSchemaInfo(@event);
return @event;
}
if (appEvent != null) private void EnrichAppInfo(IEvent @event)
{
if (@event is AppEvent appEvent)
{ {
appEvent.AppId = AppNamedId; appEvent.AppId = AppNamedId;
} }
}
var schemaEvent = @event as SchemaEvent; private void EnrichSchemaInfo(IEvent @event)
{
if (schemaEvent != null) if (@event is SchemaEvent schemaEvent)
{ {
schemaEvent.SchemaId = SchemaNamedId; schemaEvent.SchemaId = SchemaNamedId;
} }
return @event;
} }
} }
} }

Loading…
Cancel
Save