From b9176fc6b02863aa6cac19cfaf12fc6ac361a199 Mon Sep 17 00:00:00 2001 From: Sebastian Stehle Date: Wed, 16 Aug 2017 17:30:22 +0200 Subject: [PATCH] Some tests fixed --- .../Webhooks/WebhookSender.cs | 85 ++++---- .../Webhooks/Commands/WebhookEditCommand.cs | 5 - .../Assets/AssetDomainObjectTests.cs | 2 +- .../Webhooks/WebhookCommandMiddlewareTests.cs | 133 +++++++++++++ .../Webhooks/WebhookDomainObjectTests.cs | 181 ++++++++++++++++++ .../Http/DumpFormatterTests.cs | 6 +- .../Log/SemanticLogTests.cs | 36 ++-- 7 files changed, 382 insertions(+), 66 deletions(-) create mode 100644 tests/Squidex.Domain.Apps.Write.Tests/Webhooks/WebhookCommandMiddlewareTests.cs create mode 100644 tests/Squidex.Domain.Apps.Write.Tests/Webhooks/WebhookDomainObjectTests.cs diff --git a/src/Squidex.Domain.Apps.Read/Webhooks/WebhookSender.cs b/src/Squidex.Domain.Apps.Read/Webhooks/WebhookSender.cs index 622895f1d..319285f80 100644 --- a/src/Squidex.Domain.Apps.Read/Webhooks/WebhookSender.cs +++ b/src/Squidex.Domain.Apps.Read/Webhooks/WebhookSender.cs @@ -23,58 +23,65 @@ namespace Squidex.Domain.Apps.Read.Webhooks public virtual async Task<(string Dump, WebhookResult Result, TimeSpan Elapsed)> SendAsync(WebhookJob job) { - HttpRequestMessage request = BuildRequest(job); - HttpResponseMessage response = null; + try + { + HttpRequestMessage request = BuildRequest(job); + HttpResponseMessage response = null; - var responseString = string.Empty; + var responseString = string.Empty; - var isTimeout = false; + var isTimeout = false; - var watch = Stopwatch.StartNew(); + var watch = Stopwatch.StartNew(); - try - { - using (var client = new HttpClient { Timeout = Timeout }) + try { - response = await client.SendAsync(request); + using (var client = new HttpClient { Timeout = Timeout }) + { + response = await client.SendAsync(request); + } + } + catch (TimeoutException) + { + isTimeout = true; + } + catch (OperationCanceledException) + { + isTimeout = true; + } + catch (Exception ex) + { + responseString = ex.Message; + } + finally + { + watch.Stop(); } - } - catch (TimeoutException) - { - isTimeout = true; - } - catch (OperationCanceledException) - { - isTimeout = true; - } - catch (Exception ex) - { - responseString = ex.Message; - } - finally - { - watch.Stop(); - } - if (response != null) - { - responseString = await response.Content.ReadAsStringAsync(); - } + if (response != null) + { + responseString = await response.Content.ReadAsStringAsync(); + } - var dump = DumpFormatter.BuildDump(request, response, job.RequestBody, responseString, watch.Elapsed, isTimeout); + var dump = DumpFormatter.BuildDump(request, response, job.RequestBody, responseString, watch.Elapsed, isTimeout); - var result = WebhookResult.Failed; + var result = WebhookResult.Failed; - if (isTimeout) - { - result = WebhookResult.Timeout; + if (isTimeout) + { + result = WebhookResult.Timeout; + } + else if (response?.IsSuccessStatusCode == true) + { + result = WebhookResult.Success; + } + + return (dump, result, watch.Elapsed); } - else if (response?.IsSuccessStatusCode == true) + catch (Exception ex) { - result = WebhookResult.Success; + return (ex.Message, WebhookResult.Failed, TimeSpan.Zero); } - - return (dump, result, watch.Elapsed); } private static HttpRequestMessage BuildRequest(WebhookJob job) diff --git a/src/Squidex.Domain.Apps.Write/Webhooks/Commands/WebhookEditCommand.cs b/src/Squidex.Domain.Apps.Write/Webhooks/Commands/WebhookEditCommand.cs index 9936917ab..139bd743c 100644 --- a/src/Squidex.Domain.Apps.Write/Webhooks/Commands/WebhookEditCommand.cs +++ b/src/Squidex.Domain.Apps.Write/Webhooks/Commands/WebhookEditCommand.cs @@ -37,11 +37,6 @@ namespace Squidex.Domain.Apps.Write.Webhooks.Commands { errors.Add(new ValidationError("Url must be specified and absolute", nameof(Url))); } - - if (Schemas == null) - { - errors.Add(new ValidationError("Schemas must be specified.", nameof(Schemas))); - } } } } diff --git a/tests/Squidex.Domain.Apps.Write.Tests/Assets/AssetDomainObjectTests.cs b/tests/Squidex.Domain.Apps.Write.Tests/Assets/AssetDomainObjectTests.cs index eb8bdc07a..b7993e4cb 100644 --- a/tests/Squidex.Domain.Apps.Write.Tests/Assets/AssetDomainObjectTests.cs +++ b/tests/Squidex.Domain.Apps.Write.Tests/Assets/AssetDomainObjectTests.cs @@ -184,7 +184,7 @@ namespace Squidex.Domain.Apps.Write.Assets } [Fact] - public void Delete_should_update_properties_create_events() + public void Delete_should_create_events_with_total_file_size() { CreateAsset(); UpdateAsset(); diff --git a/tests/Squidex.Domain.Apps.Write.Tests/Webhooks/WebhookCommandMiddlewareTests.cs b/tests/Squidex.Domain.Apps.Write.Tests/Webhooks/WebhookCommandMiddlewareTests.cs new file mode 100644 index 000000000..039a32b38 --- /dev/null +++ b/tests/Squidex.Domain.Apps.Write.Tests/Webhooks/WebhookCommandMiddlewareTests.cs @@ -0,0 +1,133 @@ +// ========================================================================== +// WebhookCommandMiddlewareTests.cs +// Squidex Headless CMS +// ========================================================================== +// Copyright (c) Squidex Group +// All rights reserved. +// ========================================================================== + +using System; +using System.Collections.Generic; +using System.Threading.Tasks; +using FakeItEasy; +using Squidex.Domain.Apps.Core.Webhooks; +using Squidex.Domain.Apps.Read.Schemas; +using Squidex.Domain.Apps.Read.Schemas.Services; +using Squidex.Domain.Apps.Write.Webhooks.Commands; +using Squidex.Domain.Apps.Write.TestHelpers; +using Squidex.Infrastructure; +using Squidex.Infrastructure.CQRS.Commands; +using Xunit; + +// ReSharper disable ImplicitlyCapturedClosure +// ReSharper disable ConvertToConstant.Local + +namespace Squidex.Domain.Apps.Write.Webhooks +{ + public class WebhookCommandMiddlewareTests : HandlerTestBase + { + private readonly ISchemaProvider schemaProvider = A.Fake(); + private readonly WebhookCommandMiddleware sut; + private readonly WebhookDomainObject webhook; + private readonly Uri url = new Uri("http://squidex.io"); + private readonly Guid schemaId = Guid.NewGuid(); + private readonly Guid webhookId = Guid.NewGuid(); + private readonly List schemas; + + public WebhookCommandMiddlewareTests() + { + webhook = new WebhookDomainObject(webhookId, -1); + + schemas = new List + { + new WebhookSchema { SchemaId = schemaId } + }; + + sut = new WebhookCommandMiddleware(Handler, schemaProvider); + } + + [Fact] + public async Task Create_should_create_webhook() + { + var context = CreateContextForCommand(new CreateWebhook { Schemas = schemas, Url = url, WebhookId = webhookId }); + + A.CallTo(() => schemaProvider.FindSchemaByIdAsync(schemaId, false)).Returns(Task.FromResult(A.Fake())); + + await TestCreate(webhook, async _ => + { + await sut.HandleAsync(context); + }); + + A.CallTo(() => schemaProvider.FindSchemaByIdAsync(schemaId, false)).MustHaveHappened(); + } + + [Fact] + public async Task Create_should_throw_exception_when_schema_is_not_found() + { + var context = CreateContextForCommand(new CreateWebhook { Schemas = schemas, Url = url, WebhookId = webhookId }); + + A.CallTo(() => schemaProvider.FindSchemaByIdAsync(schemaId, false)).Returns(Task.FromResult(null)); + + await Assert.ThrowsAsync(async () => + { + await TestCreate(webhook, async _ => + { + await sut.HandleAsync(context); + }); + }); + } + + [Fact] + public async Task Update_should_update_domain_object() + { + var context = CreateContextForCommand(new UpdateWebhook { Schemas = schemas, Url = url, WebhookId = webhookId }); + + A.CallTo(() => schemaProvider.FindSchemaByIdAsync(schemaId, false)).Returns(Task.FromResult(A.Fake())); + + CreateWebhook(); + + await TestUpdate(webhook, async _ => + { + await sut.HandleAsync(context); + }); + + A.CallTo(() => schemaProvider.FindSchemaByIdAsync(schemaId, false)).MustHaveHappened(); + } + + [Fact] + public async Task Update_should_throw_exception_when_schema_is_not_found() + { + var context = CreateContextForCommand(new UpdateWebhook { Schemas = schemas, Url = url, WebhookId = webhookId }); + + A.CallTo(() => schemaProvider.FindSchemaByIdAsync(schemaId, false)).Returns(Task.FromResult(null)); + + CreateWebhook(); + + await Assert.ThrowsAsync(async () => + { + await TestCreate(webhook, async _ => + { + await sut.HandleAsync(context); + }); + }); + } + + [Fact] + public async Task Delete_should_update_domain_object() + { + CreateWebhook(); + + var command = CreateContextForCommand(new DeleteWebhook { WebhookId = webhookId }); + + await TestUpdate(webhook, async _ => + { + await sut.HandleAsync(command); + }); + } + + private void CreateWebhook() + { + webhook.Create(new CreateWebhook { Url = url }); + } + } +} diff --git a/tests/Squidex.Domain.Apps.Write.Tests/Webhooks/WebhookDomainObjectTests.cs b/tests/Squidex.Domain.Apps.Write.Tests/Webhooks/WebhookDomainObjectTests.cs new file mode 100644 index 000000000..6bcc88e35 --- /dev/null +++ b/tests/Squidex.Domain.Apps.Write.Tests/Webhooks/WebhookDomainObjectTests.cs @@ -0,0 +1,181 @@ +// ========================================================================== +// WebhookDomainObjectTests.cs +// Squidex Headless CMS +// ========================================================================== +// Copyright (c) Squidex Group +// All rights reserved. +// ========================================================================== + +using System; +using Squidex.Domain.Apps.Events.Webhooks; +using Squidex.Domain.Apps.Write.Webhooks.Commands; +using Squidex.Domain.Apps.Write.TestHelpers; +using Squidex.Infrastructure; +using Squidex.Infrastructure.CQRS; +using Xunit; + +// ReSharper disable ConvertToConstant.Local + +namespace Squidex.Domain.Apps.Write.Webhooks +{ + public class WebhookDomainObjectTests : HandlerTestBase + { + private readonly Uri url = new Uri("http://squidex.io"); + private readonly WebhookDomainObject sut; + + public Guid WebhookId { get; } = Guid.NewGuid(); + + public WebhookDomainObjectTests() + { + sut = new WebhookDomainObject(WebhookId, 0); + } + + [Fact] + public void Create_should_throw_exception_if_created() + { + sut.Create(new CreateWebhook { Url = url }); + + Assert.Throws(() => + { + sut.Create(CreateWebhookCommand(new CreateWebhook { Url = url })); + }); + } + + [Fact] + public void Create_should_throw_exception_if_command_is_not_valid() + { + Assert.Throws(() => + { + sut.Create(CreateWebhookCommand(new CreateWebhook { Url = new Uri("/invalid", UriKind.Relative) })); + }); + } + + [Fact] + public void Create_should_create_events() + { + var command = new CreateWebhook { Url = url }; + + sut.Create(CreateWebhookCommand(command)); + + sut.GetUncomittedEvents() + .ShouldHaveSameEvents( + CreateWebhookEvent(new WebhookCreated + { + Url = url, + Schemas = command.Schemas, + SharedSecret = command.SharedSecret, + WebhookId = command.WebhookId + }) + ); + } + + [Fact] + public void Update_should_throw_exception_if_not_created() + { + Assert.Throws(() => + { + sut.Update(CreateWebhookCommand(new UpdateWebhook { Url = url })); + }); + } + + [Fact] + public void Update_should_throw_exception_if_webhook_is_deleted() + { + CreateWebhook(); + DeleteWebhook(); + + Assert.Throws(() => + { + sut.Update(CreateWebhookCommand(new UpdateWebhook { Url = url })); + }); + } + + [Fact] + public void Update_should_throw_exception_if_command_is_not_valid() + { + CreateWebhook(); + + Assert.Throws(() => + { + sut.Update(CreateWebhookCommand(new UpdateWebhook { Url = new Uri("/invalid", UriKind.Relative) })); + }); + } + + [Fact] + public void Update_should_create_events() + { + CreateWebhook(); + + var command = new UpdateWebhook { Url = url }; + + sut.Update(CreateWebhookCommand(command)); + + sut.GetUncomittedEvents() + .ShouldHaveSameEvents( + CreateWebhookEvent(new WebhookUpdated { Url = url, Schemas = command.Schemas }) + ); + } + + [Fact] + public void Delete_should_throw_exception_if_not_created() + { + Assert.Throws(() => + { + sut.Delete(CreateWebhookCommand(new DeleteWebhook())); + }); + } + + [Fact] + public void Delete_should_throw_exception_if_already_deleted() + { + CreateWebhook(); + DeleteWebhook(); + + Assert.Throws(() => + { + sut.Delete(CreateWebhookCommand(new DeleteWebhook())); + }); + } + + [Fact] + public void Delete_should_update_properties_create_events() + { + CreateWebhook(); + + sut.Delete(CreateWebhookCommand(new DeleteWebhook())); + + sut.GetUncomittedEvents() + .ShouldHaveSameEvents( + CreateWebhookEvent(new WebhookDeleted()) + ); + } + + private void CreateWebhook() + { + sut.Create(CreateWebhookCommand(new CreateWebhook { Url = url })); + + ((IAggregate)sut).ClearUncommittedEvents(); + } + + private void DeleteWebhook() + { + sut.Delete(CreateWebhookCommand(new DeleteWebhook())); + + ((IAggregate)sut).ClearUncommittedEvents(); + } + + protected T CreateWebhookEvent(T @event) where T : WebhookEvent + { + @event.WebhookId = WebhookId; + + return CreateEvent(@event); + } + + protected T CreateWebhookCommand(T command) where T : WebhookAggregateCommand + { + command.WebhookId = WebhookId; + + return CreateCommand(command); + } + } +} diff --git a/tests/Squidex.Infrastructure.Tests/Http/DumpFormatterTests.cs b/tests/Squidex.Infrastructure.Tests/Http/DumpFormatterTests.cs index 782a9c98a..8ca2c2b48 100644 --- a/tests/Squidex.Infrastructure.Tests/Http/DumpFormatterTests.cs +++ b/tests/Squidex.Infrastructure.Tests/Http/DumpFormatterTests.cs @@ -26,7 +26,7 @@ namespace Squidex.Infrastructure.Http request.Headers.AcceptLanguage.Add(new StringWithQualityHeaderValue("en")); request.Headers.AcceptEncoding.Add(new StringWithQualityHeaderValue("UTF-8")); - var dump = DumpFormatter.BuildDump(request, null, null, null, TimeSpan.FromMinutes(1)); + var dump = DumpFormatter.BuildDump(request, null, null, null, TimeSpan.FromMinutes(1), true); var expected = MakeDump( "Request:", @@ -55,7 +55,7 @@ namespace Squidex.Infrastructure.Http response.Headers.TransferEncoding.Add(new TransferCodingHeaderValue("UTF-8")); response.Headers.Trailer.Add("Expires"); - var dump = DumpFormatter.BuildDump(request, response, null, null, TimeSpan.FromMinutes(1)); + var dump = DumpFormatter.BuildDump(request, response, null, null, TimeSpan.FromMinutes(1), false); var expected = MakeDump( "Request:", @@ -90,7 +90,7 @@ namespace Squidex.Infrastructure.Http response.Headers.Trailer.Add("Expires"); response.Content = new StringContent("Hello Back", Encoding.UTF8, "text/plain"); - var dump = DumpFormatter.BuildDump(request, response, "Hello Squidex", "Hello Back", TimeSpan.FromMinutes(1)); + var dump = DumpFormatter.BuildDump(request, response, "Hello Squidex", "Hello Back", TimeSpan.FromMinutes(1), true); var expected = MakeDump( "Request:", diff --git a/tests/Squidex.Infrastructure.Tests/Log/SemanticLogTests.cs b/tests/Squidex.Infrastructure.Tests/Log/SemanticLogTests.cs index f02ef02d5..17dfc315e 100644 --- a/tests/Squidex.Infrastructure.Tests/Log/SemanticLogTests.cs +++ b/tests/Squidex.Infrastructure.Tests/Log/SemanticLogTests.cs @@ -51,7 +51,7 @@ namespace Squidex.Infrastructure.Log Log.LogFatal(w => {}); var expected = - MakeTestCall(w => w + LogTest(w => w .WriteProperty("logLevel", "Fatal") .WriteProperty("timestamp", now)); @@ -66,7 +66,7 @@ namespace Squidex.Infrastructure.Log Log.LogFatal(m => { }); var expected = - MakeTestCall(w => w + LogTest(w => w .WriteProperty("logLevel", "Fatal") .WriteProperty("logValue", 1500)); @@ -83,7 +83,7 @@ namespace Squidex.Infrastructure.Log Log.LogFatal(m => { }); var expected = - MakeTestCall(w => w + LogTest(w => w .WriteProperty("logLevel", "Fatal") .WriteObject("app", a => a .WriteProperty("name", "Squidex.Infrastructure.Tests") @@ -99,7 +99,7 @@ namespace Squidex.Infrastructure.Log Log.LogTrace(w => w.WriteProperty("logValue", 1500)); var expected = - MakeTestCall(w => w + LogTest(w => w .WriteProperty("logLevel", "Trace") .WriteProperty("logValue", 1500)); @@ -112,7 +112,7 @@ namespace Squidex.Infrastructure.Log Log.LogDebug(w => w.WriteProperty("logValue", 1500)); var expected = - MakeTestCall(w => w + LogTest(w => w .WriteProperty("logLevel", "Debug") .WriteProperty("logValue", 1500)); @@ -125,7 +125,7 @@ namespace Squidex.Infrastructure.Log Log.LogInformation(w => w.WriteProperty("logValue", 1500)); var expected = - MakeTestCall(w => w + LogTest(w => w .WriteProperty("logLevel", "Information") .WriteProperty("logValue", 1500)); @@ -138,7 +138,7 @@ namespace Squidex.Infrastructure.Log Log.LogWarning(w => w.WriteProperty("logValue", 1500)); var expected = - MakeTestCall(w => w + LogTest(w => w .WriteProperty("logLevel", "Warning") .WriteProperty("logValue", 1500)); @@ -153,7 +153,7 @@ namespace Squidex.Infrastructure.Log Log.LogWarning(exception); var expected = - MakeTestCall(w => w + LogTest(w => w .WriteProperty("logLevel", "Warning") .WriteException(exception)); @@ -166,7 +166,7 @@ namespace Squidex.Infrastructure.Log Log.LogError(w => w.WriteProperty("logValue", 1500)); var expected = - MakeTestCall(w => w + LogTest(w => w .WriteProperty("logLevel", "Error") .WriteProperty("logValue", 1500)); @@ -181,7 +181,7 @@ namespace Squidex.Infrastructure.Log Log.LogError(exception); var expected = - MakeTestCall(w => w + LogTest(w => w .WriteProperty("logLevel", "Error") .WriteException(exception)); @@ -194,7 +194,7 @@ namespace Squidex.Infrastructure.Log Log.LogFatal(w => w.WriteProperty("logValue", 1500)); var expected = - MakeTestCall(w => w + LogTest(w => w .WriteProperty("logLevel", "Fatal") .WriteProperty("logValue", 1500)); @@ -209,7 +209,7 @@ namespace Squidex.Infrastructure.Log Log.LogFatal(exception); var expected = - MakeTestCall(w => w + LogTest(w => w .WriteProperty("logLevel", "Fatal") .WriteException(exception)); @@ -222,7 +222,7 @@ namespace Squidex.Infrastructure.Log Log.LogFatal((Exception)null); var expected = - MakeTestCall(w => w + LogTest(w => w .WriteProperty("logLevel", "Fatal")); Assert.Equal(expected, output); @@ -234,7 +234,7 @@ namespace Squidex.Infrastructure.Log Log.MeasureTrace(w => w.WriteProperty("message", "My Message")).Dispose(); var expected = - MakeTestCall(w => w + LogTest(w => w .WriteProperty("logLevel", "Trace") .WriteProperty("message", "My Message") .WriteProperty("elapsedMs", 0)); @@ -248,7 +248,7 @@ namespace Squidex.Infrastructure.Log Log.MeasureDebug(w => w.WriteProperty("message", "My Message")).Dispose(); var expected = - MakeTestCall(w => w + LogTest(w => w .WriteProperty("logLevel", "Debug") .WriteProperty("message", "My Message") .WriteProperty("elapsedMs", 0)); @@ -262,7 +262,7 @@ namespace Squidex.Infrastructure.Log Log.MeasureInformation(w => w.WriteProperty("message", "My Message")).Dispose(); var expected = - MakeTestCall(w => w + LogTest(w => w .WriteProperty("logLevel", "Information") .WriteProperty("message", "My Message") .WriteProperty("elapsedMs", 0)); @@ -281,7 +281,7 @@ namespace Squidex.Infrastructure.Log loggerInstance.LogCritical(new EventId(123, "EventName"), exception, "Log {0}", 123); var expected = - MakeTestCall(w => w + LogTest(w => w .WriteProperty("logLevel", "Fatal") .WriteProperty("message", "Log 123") .WriteObject("eventId", e => e @@ -293,7 +293,7 @@ namespace Squidex.Infrastructure.Log Assert.Equal(expected, output); } - private static string MakeTestCall(Action writer) + private static string LogTest(Action writer) { IObjectWriter sut = new JsonLogWriter();