diff --git a/Directory.Packages.props b/Directory.Packages.props index efb48fcc4..f0f5f5b79 100644 --- a/Directory.Packages.props +++ b/Directory.Packages.props @@ -7,7 +7,6 @@ - @@ -43,6 +42,7 @@ + diff --git a/test/Dapr.AI.Test/Dapr.AI.Test.csproj b/test/Dapr.AI.Test/Dapr.AI.Test.csproj index f937f64e2..b4a07c1fb 100644 --- a/test/Dapr.AI.Test/Dapr.AI.Test.csproj +++ b/test/Dapr.AI.Test/Dapr.AI.Test.csproj @@ -7,7 +7,6 @@ runtime; build; native; contentfiles; analyzers; buildtransitive all - diff --git a/test/Dapr.Actors.AspNetCore.IntegrationTest/Dapr.Actors.AspNetCore.IntegrationTest.csproj b/test/Dapr.Actors.AspNetCore.IntegrationTest/Dapr.Actors.AspNetCore.IntegrationTest.csproj index 921e2dda4..394cc9def 100644 --- a/test/Dapr.Actors.AspNetCore.IntegrationTest/Dapr.Actors.AspNetCore.IntegrationTest.csproj +++ b/test/Dapr.Actors.AspNetCore.IntegrationTest/Dapr.Actors.AspNetCore.IntegrationTest.csproj @@ -4,7 +4,6 @@ runtime; build; native; contentfiles; analyzers; buildtransitive all - diff --git a/test/Dapr.Actors.AspNetCore.Test/Dapr.Actors.AspNetCore.Test.csproj b/test/Dapr.Actors.AspNetCore.Test/Dapr.Actors.AspNetCore.Test.csproj index c448e915c..9f9e43119 100644 --- a/test/Dapr.Actors.AspNetCore.Test/Dapr.Actors.AspNetCore.Test.csproj +++ b/test/Dapr.Actors.AspNetCore.Test/Dapr.Actors.AspNetCore.Test.csproj @@ -9,7 +9,6 @@ runtime; build; native; contentfiles; analyzers; buildtransitive all - diff --git a/test/Dapr.Actors.Test/ActorCodeBuilderTests.cs b/test/Dapr.Actors.Test/ActorCodeBuilderTests.cs index 2f2bb67db..b82c56fc5 100644 --- a/test/Dapr.Actors.Test/ActorCodeBuilderTests.cs +++ b/test/Dapr.Actors.Test/ActorCodeBuilderTests.cs @@ -11,44 +11,43 @@ // limitations under the License. // ------------------------------------------------------------------------ -namespace Dapr.Actors.Test -{ - using System.Threading.Tasks; - using Dapr.Actors.Builder; - using Dapr.Actors.Communication; - using Dapr.Actors.Description; - using Dapr.Actors.Runtime; - using Xunit; +namespace Dapr.Actors.Test; + +using System.Threading.Tasks; +using Dapr.Actors.Builder; +using Dapr.Actors.Communication; +using Dapr.Actors.Description; +using Dapr.Actors.Runtime; +using Xunit; +/// +/// Test class for Actor Code builder. +/// +public class ActorCodeBuilderTests +{ /// - /// Test class for Actor Code builder. + /// Tests Proxy Generation. /// - public class ActorCodeBuilderTests + [Fact] + public void TestBuildActorProxyGenerator() { - /// - /// Tests Proxy Generation. - /// - [Fact] - public void TestBuildActorProxyGenerator() - { - ActorCodeBuilder.GetOrCreateProxyGenerator(typeof(ITestActor)); - } + ActorCodeBuilder.GetOrCreateProxyGenerator(typeof(ITestActor)); + } - [Fact] - public async Task ActorCodeBuilder_BuildDispatcher() - { - var host = ActorHost.CreateForTest(); + [Fact] + public async Task ActorCodeBuilder_BuildDispatcher() + { + var host = ActorHost.CreateForTest(); - var dispatcher = ActorCodeBuilder.GetOrCreateMethodDispatcher(typeof(ITestActor)); - var methodId = MethodDescription.Create("test", typeof(ITestActor).GetMethod("GetCountAsync"), true).Id; + var dispatcher = ActorCodeBuilder.GetOrCreateMethodDispatcher(typeof(ITestActor)); + var methodId = MethodDescription.Create("test", typeof(ITestActor).GetMethod("GetCountAsync"), true).Id; - var impl = new TestActor(host); - var request = new ActorRequestMessageBody(0); - var response = new WrappedRequestMessageFactory(); + var impl = new TestActor(host); + var request = new ActorRequestMessageBody(0); + var response = new WrappedRequestMessageFactory(); - var body = (WrappedMessage)await dispatcher.DispatchAsync(impl, methodId, request, response, default); - dynamic bodyValue = body.Value; - Assert.Equal(5, (int)bodyValue.retVal); - } + var body = (WrappedMessage)await dispatcher.DispatchAsync(impl, methodId, request, response, default); + dynamic bodyValue = body.Value; + Assert.Equal(5, (int)bodyValue.retVal); } } diff --git a/test/Dapr.Actors.Test/ActorIdTests.cs b/test/Dapr.Actors.Test/ActorIdTests.cs index c54f4c351..dc1f87942 100644 --- a/test/Dapr.Actors.Test/ActorIdTests.cs +++ b/test/Dapr.Actors.Test/ActorIdTests.cs @@ -11,194 +11,193 @@ // limitations under the License. // ------------------------------------------------------------------------ -namespace Dapr.Actors.Test -{ - using System; - using System.Collections.Generic; - using Xunit; +namespace Dapr.Actors.Test; - /// - /// Contains tests for Actor ID. - /// - public class ActorIdTests +using System; +using System.Collections.Generic; +using Xunit; + +/// +/// Contains tests for Actor ID. +/// +public class ActorIdTests +{ + public static readonly IEnumerable CompareToValues = new List { - public static readonly IEnumerable CompareToValues = new List + new object[] { - new object[] - { - new ActorId("1"), - null, - 1, - }, - new object[] - { - new ActorId("1"), - new ActorId("1"), - 0, - }, - new object[] - { - new ActorId("1"), - new ActorId("2"), - -1, - }, - new object[] - { - new ActorId("2"), - new ActorId("1"), - 1, - }, - }; - - public static readonly IEnumerable EqualsValues = new List + new ActorId("1"), + null, + 1, + }, + new object[] { - new object[] - { - new ActorId("1"), - null, - false, - }, - new object[] - { - new ActorId("1"), - new ActorId("1"), - true, - }, - new object[] - { - new ActorId("1"), - new ActorId("2"), - false, - }, - }; - - public static readonly IEnumerable EqualsOperatorValues = new List + new ActorId("1"), + new ActorId("1"), + 0, + }, + new object[] { - new object[] - { - null, - null, - true, - }, - new object[] - { - new ActorId("1"), - null, - false, - }, - new object[] - { - null, - new ActorId("1"), - false, - }, - new object[] - { - new ActorId("1"), - new ActorId("1"), - true, - }, - new object[] - { - new ActorId("1"), - new ActorId("2"), - false, - }, - }; - - /// - /// Throw exception if id is null. - /// - [Theory] - [InlineData(null)] - [InlineData("")] - [InlineData(" ")] - public void Initialize_New_ActorId_Object_With_Null_Or_Whitespace_Id(string id) + new ActorId("1"), + new ActorId("2"), + -1, + }, + new object[] { - Assert.Throws(() => new ActorId(id)); - } + new ActorId("2"), + new ActorId("1"), + 1, + }, + }; - [Theory] - [InlineData("one")] - [InlineData("123")] - public void Get_Id(string id) + public static readonly IEnumerable EqualsValues = new List + { + new object[] { - ActorId actorId = new ActorId(id); - Assert.Equal(id, actorId.GetId()); - } - - [Theory] - [InlineData("one")] - [InlineData("123")] - public void Verify_ToString(string id) + new ActorId("1"), + null, + false, + }, + new object[] { - ActorId actorId = new ActorId(id); - Assert.Equal(id, actorId.ToString()); - } - - /// - /// Verify Equals method by comparing two actorIds. - /// - /// The first actorId to compare. - /// The second actorId to compare, or null. - /// Expected value from comparison. - [Theory] - [MemberData(nameof(EqualsValues))] - public void Verify_Equals_By_Object(object id1, object id2, bool expectedValue) + new ActorId("1"), + new ActorId("1"), + true, + }, + new object[] { - Assert.Equal(expectedValue, id1.Equals(id2)); - } + new ActorId("1"), + new ActorId("2"), + false, + }, + }; - /// - /// Verify Equals method by comparing two actorIds. - /// - /// The first actorId to compare. - /// The second actorId to compare, or null. - /// Expected value from comparison. - [Theory] - [MemberData(nameof(EqualsValues))] - public void Verify_Equals_By_ActorId(ActorId id1, ActorId id2, bool expectedValue) + public static readonly IEnumerable EqualsOperatorValues = new List + { + new object[] { - Assert.Equal(expectedValue, id1.Equals(id2)); - } - - /// - /// Verify equals operator by comparing two actorIds. - /// - /// The first actorId to compare, or null. - /// The second actorId to compare, or null. - /// Expected value from comparison. - [Theory] - [MemberData(nameof(EqualsOperatorValues))] - public void Verify_Equals_Operator(ActorId id1, ActorId id2, bool expectedValue) + null, + null, + true, + }, + new object[] { - Assert.Equal(expectedValue, id1 == id2); - } - - /// - /// Verify not equals operator by comparing two actorIds. - /// - /// The first actorId to compare, or null. - /// The second actorId to compare, or null. - /// Expected value from comparison. - [Theory] - [MemberData(nameof(EqualsOperatorValues))] - public void Verify_Not_Equals_Operator(ActorId id1, ActorId id2, bool expectedValue) + new ActorId("1"), + null, + false, + }, + new object[] { - Assert.Equal(!expectedValue, id1 != id2); - } - - /// - /// Verify CompareTo method by comparing two actorIds. - /// - /// The first actorId to compare. - /// The second actorId to compare, or null. - /// Expected value from comparison. - [Theory] - [MemberData(nameof(CompareToValues))] - public void Verify_CompareTo(ActorId id1, ActorId id2, int expectedValue) + null, + new ActorId("1"), + false, + }, + new object[] { - Assert.Equal(expectedValue, id1.CompareTo(id2)); - } + new ActorId("1"), + new ActorId("1"), + true, + }, + new object[] + { + new ActorId("1"), + new ActorId("2"), + false, + }, + }; + + /// + /// Throw exception if id is null. + /// + [Theory] + [InlineData(null)] + [InlineData("")] + [InlineData(" ")] + public void Initialize_New_ActorId_Object_With_Null_Or_Whitespace_Id(string id) + { + Assert.Throws(() => new ActorId(id)); + } + + [Theory] + [InlineData("one")] + [InlineData("123")] + public void Get_Id(string id) + { + ActorId actorId = new ActorId(id); + Assert.Equal(id, actorId.GetId()); + } + + [Theory] + [InlineData("one")] + [InlineData("123")] + public void Verify_ToString(string id) + { + ActorId actorId = new ActorId(id); + Assert.Equal(id, actorId.ToString()); + } + + /// + /// Verify Equals method by comparing two actorIds. + /// + /// The first actorId to compare. + /// The second actorId to compare, or null. + /// Expected value from comparison. + [Theory] + [MemberData(nameof(EqualsValues))] + public void Verify_Equals_By_Object(object id1, object id2, bool expectedValue) + { + Assert.Equal(expectedValue, id1.Equals(id2)); + } + + /// + /// Verify Equals method by comparing two actorIds. + /// + /// The first actorId to compare. + /// The second actorId to compare, or null. + /// Expected value from comparison. + [Theory] + [MemberData(nameof(EqualsValues))] + public void Verify_Equals_By_ActorId(ActorId id1, ActorId id2, bool expectedValue) + { + Assert.Equal(expectedValue, id1.Equals(id2)); + } + + /// + /// Verify equals operator by comparing two actorIds. + /// + /// The first actorId to compare, or null. + /// The second actorId to compare, or null. + /// Expected value from comparison. + [Theory] + [MemberData(nameof(EqualsOperatorValues))] + public void Verify_Equals_Operator(ActorId id1, ActorId id2, bool expectedValue) + { + Assert.Equal(expectedValue, id1 == id2); + } + + /// + /// Verify not equals operator by comparing two actorIds. + /// + /// The first actorId to compare, or null. + /// The second actorId to compare, or null. + /// Expected value from comparison. + [Theory] + [MemberData(nameof(EqualsOperatorValues))] + public void Verify_Not_Equals_Operator(ActorId id1, ActorId id2, bool expectedValue) + { + Assert.Equal(!expectedValue, id1 != id2); + } + + /// + /// Verify CompareTo method by comparing two actorIds. + /// + /// The first actorId to compare. + /// The second actorId to compare, or null. + /// Expected value from comparison. + [Theory] + [MemberData(nameof(CompareToValues))] + public void Verify_CompareTo(ActorId id1, ActorId id2, int expectedValue) + { + Assert.Equal(expectedValue, id1.CompareTo(id2)); } } diff --git a/test/Dapr.Actors.Test/ActorMethodInvocationExceptionTests.cs b/test/Dapr.Actors.Test/ActorMethodInvocationExceptionTests.cs index 1311a9394..b34d1dedc 100644 --- a/test/Dapr.Actors.Test/ActorMethodInvocationExceptionTests.cs +++ b/test/Dapr.Actors.Test/ActorMethodInvocationExceptionTests.cs @@ -11,51 +11,50 @@ // limitations under the License. // ------------------------------------------------------------------------ -namespace Dapr.Actors.Test -{ - using System; - using System.IO; - using FluentAssertions; - using Xunit; +namespace Dapr.Actors.Test; + +using System; +using System.IO; +using Shouldly; +using Xunit; +/// +/// Contains tests for Actor method invocation exceptions. +/// +public class ActorMethodInvocationExceptionTests +{ /// - /// Contains tests for Actor method invocation exceptions. + /// This test will verify: + /// 1) the path for serialization and deserialization of the remote exception + /// 2) and validating the inner exception. /// - public class ActorMethodInvocationExceptionTests + [Fact] + public void TestThrowActorMethodInvocationException() { - /// - /// This test will verify: - /// 1) the path for serialization and deserialization of the remote exception - /// 2) and validating the inner exception. - /// - [Fact] - public void TestThrowActorMethodInvocationException() - { - // Create Remote Actor Method test Exception - var message = "Remote Actor encountered an exception"; - var innerMessage = "Bad time zone"; - var exception = new InvalidOperationException(message, new InvalidTimeZoneException(innerMessage)); + // Create Remote Actor Method test Exception + var message = "Remote Actor encountered an exception"; + var innerMessage = "Bad time zone"; + var exception = new InvalidOperationException(message, new InvalidTimeZoneException(innerMessage)); - // Create Serialized Exception - var serializedException = ActorInvokeException.FromException(exception); + // Create Serialized Exception + var serializedException = ActorInvokeException.FromException(exception); - // De Serialize Exception - var isDeserialzied = ActorInvokeException.ToException( - new MemoryStream(serializedException), - out var remoteMethodException); - isDeserialzied.Should().BeTrue(); - var ex = this.ThrowRemoteException(message, remoteMethodException); - ex.Should().BeOfType(); - ex.InnerException.Should().BeOfType(); - ((ActorInvokeException)ex.InnerException).ActualExceptionType.Should().Be("System.InvalidOperationException"); - ex.InnerException.InnerException.Should().BeNull(); - ex.Message.Should().Be(message); - ex.InnerException.Message.Should().Be(message); - } + // De Serialize Exception + var isDeserialzied = ActorInvokeException.ToException( + new MemoryStream(serializedException), + out var remoteMethodException); + isDeserialzied.ShouldBeTrue(); + var ex = this.ThrowRemoteException(message, remoteMethodException); + ex.ShouldBeOfType(); + ex.InnerException.ShouldBeOfType(); + ((ActorInvokeException)ex.InnerException).ActualExceptionType.ShouldBe("System.InvalidOperationException"); + ex.InnerException.InnerException.ShouldBeNull(); + ex.Message.ShouldBe(message); + ex.InnerException.Message.ShouldBe(message); + } - private Exception ThrowRemoteException(string message, Exception exception) - { - return new ActorMethodInvocationException(message, exception, false); - } + private Exception ThrowRemoteException(string message, Exception exception) + { + return new ActorMethodInvocationException(message, exception, false); } } diff --git a/test/Dapr.Actors.Test/ActorProxyOptionsTests.cs b/test/Dapr.Actors.Test/ActorProxyOptionsTests.cs index 9fab1c32c..3a156c785 100644 --- a/test/Dapr.Actors.Test/ActorProxyOptionsTests.cs +++ b/test/Dapr.Actors.Test/ActorProxyOptionsTests.cs @@ -11,31 +11,30 @@ // limitations under the License. // ------------------------------------------------------------------------ -namespace Dapr.Actors.Client -{ - using System; - using FluentAssertions; - using Xunit; +namespace Dapr.Actors.Client; + +using System; +using Shouldly; +using Xunit; - /// - /// Test class for Actor Code builder. - /// - public class ActorProxyOptionsTests +/// +/// Test class for Actor Code builder. +/// +public class ActorProxyOptionsTests +{ + [Fact] + public void DefaultConstructor_Succeeds() { - [Fact] - public void DefaultConstructor_Succeeds() - { - var options = new ActorProxyOptions(); - Assert.NotNull(options); - } + var options = new ActorProxyOptions(); + Assert.NotNull(options); + } - [Fact] - public void SerializerOptionsCantBeNull_Fails() - { - var options = new ActorProxyOptions(); - Action action = () => options.JsonSerializerOptions = null; + [Fact] + public void SerializerOptionsCantBeNull_Fails() + { + var options = new ActorProxyOptions(); + Action action = () => options.JsonSerializerOptions = null; - action.Should().Throw(); - } + action.ShouldThrow(); } } diff --git a/test/Dapr.Actors.Test/ActorProxyTests.cs b/test/Dapr.Actors.Test/ActorProxyTests.cs index 078f4b5f6..4290b02c9 100644 --- a/test/Dapr.Actors.Test/ActorProxyTests.cs +++ b/test/Dapr.Actors.Test/ActorProxyTests.cs @@ -11,113 +11,112 @@ // limitations under the License. // ------------------------------------------------------------------------ -namespace Dapr.Actors.Client +namespace Dapr.Actors.Client; + +using System; +using System.Text.Json; +using Dapr.Actors.Test; +using Shouldly; +using Xunit; + +/// +/// Test class for Actor Code builder. +/// +public class ActorProxyTests { - using System; - using System.Text.Json; - using Dapr.Actors.Test; - using FluentAssertions; - using Xunit; - /// - /// Test class for Actor Code builder. + /// Tests Proxy Creation. /// - public class ActorProxyTests + [Fact] + public void Create_WithIdAndActorTypeString_Succeeds() { - /// - /// Tests Proxy Creation. - /// - [Fact] - public void Create_WithIdAndActorTypeString_Succeeds() - { - var actorId = new ActorId("abc"); - var proxy = ActorProxy.Create(actorId, "TestActor"); - Assert.NotNull(proxy); - } + var actorId = new ActorId("abc"); + var proxy = ActorProxy.Create(actorId, "TestActor"); + Assert.NotNull(proxy); + } - [Fact] - public void Create_WithValidActorInterface_Succeeds() - { - var actorId = new ActorId("abc"); - var proxy = ActorProxy.Create(actorId, typeof(ITestActor), "TestActor"); - Assert.NotNull(proxy); - } + [Fact] + public void Create_WithValidActorInterface_Succeeds() + { + var actorId = new ActorId("abc"); + var proxy = ActorProxy.Create(actorId, typeof(ITestActor), "TestActor"); + Assert.NotNull(proxy); + } - [Fact] - public void Create_WithInvalidType_ThrowsArgumentException() - { - var actorId = new ActorId("abc"); - Action action = () => ActorProxy.Create(actorId, typeof(ActorId), "TestActor"); - action.Should().Throw(); - } + [Fact] + public void Create_WithInvalidType_ThrowsArgumentException() + { + var actorId = new ActorId("abc"); + Action action = () => ActorProxy.Create(actorId, typeof(ActorId), "TestActor"); + action.ShouldThrow(); + } - [Fact] - public void Create_WithCustomSerializerOnDefaultActorProxyFactory_Succeeds() - { - var factory = new ActorProxyFactory(); - factory.DefaultOptions.JsonSerializerOptions = new JsonSerializerOptions(); + [Fact] + public void Create_WithCustomSerializerOnDefaultActorProxyFactory_Succeeds() + { + var factory = new ActorProxyFactory(); + factory.DefaultOptions.JsonSerializerOptions = new JsonSerializerOptions(); - var actorId = new ActorId("abc"); - var proxy = (ActorProxy)factory.Create(actorId, "TestActor"); + var actorId = new ActorId("abc"); + var proxy = (ActorProxy)factory.Create(actorId, "TestActor"); - Assert.Same(factory.DefaultOptions.JsonSerializerOptions, proxy.JsonSerializerOptions); - } + Assert.Same(factory.DefaultOptions.JsonSerializerOptions, proxy.JsonSerializerOptions); + } - [Fact] - public void Create_WithCustomSerializerArgument_Succeeds() + [Fact] + public void Create_WithCustomSerializerArgument_Succeeds() + { + var options = new ActorProxyOptions() { - var options = new ActorProxyOptions() - { - JsonSerializerOptions = new JsonSerializerOptions() - }; + JsonSerializerOptions = new JsonSerializerOptions() + }; - var actorId = new ActorId("abc"); - var proxy = (ActorProxy)ActorProxy.Create(actorId, typeof(ITestActor), "TestActor", options); + var actorId = new ActorId("abc"); + var proxy = (ActorProxy)ActorProxy.Create(actorId, typeof(ITestActor), "TestActor", options); - Assert.Same(options.JsonSerializerOptions, proxy.JsonSerializerOptions); - } + Assert.Same(options.JsonSerializerOptions, proxy.JsonSerializerOptions); + } - [Fact] - public void CreateGeneric_WithValidActorInterface_Succeeds() - { - var actorId = new ActorId("abc"); - var proxy = ActorProxy.Create(actorId, "TestActor"); - Assert.NotNull(proxy); - } + [Fact] + public void CreateGeneric_WithValidActorInterface_Succeeds() + { + var actorId = new ActorId("abc"); + var proxy = ActorProxy.Create(actorId, "TestActor"); + Assert.NotNull(proxy); + } - [Fact] - public void CreateGeneric_WithCustomSerializerOnDefaultActorProxyFactory_Succeeds() - { - var factory = new ActorProxyFactory(); - factory.DefaultOptions.JsonSerializerOptions = new JsonSerializerOptions(); + [Fact] + public void CreateGeneric_WithCustomSerializerOnDefaultActorProxyFactory_Succeeds() + { + var factory = new ActorProxyFactory(); + factory.DefaultOptions.JsonSerializerOptions = new JsonSerializerOptions(); - var actorId = new ActorId("abc"); - var proxy = (ActorProxy)factory.CreateActorProxy(actorId, "TestActor"); + var actorId = new ActorId("abc"); + var proxy = (ActorProxy)factory.CreateActorProxy(actorId, "TestActor"); - Assert.Same(factory.DefaultOptions.JsonSerializerOptions, proxy.JsonSerializerOptions); - } + Assert.Same(factory.DefaultOptions.JsonSerializerOptions, proxy.JsonSerializerOptions); + } - [Fact] - public void CreateGeneric_WithCustomSerializerArgument_Succeeds() + [Fact] + public void CreateGeneric_WithCustomSerializerArgument_Succeeds() + { + var options = new ActorProxyOptions() { - var options = new ActorProxyOptions() - { - JsonSerializerOptions = new JsonSerializerOptions() - }; + JsonSerializerOptions = new JsonSerializerOptions() + }; - var actorId = new ActorId("abc"); - var proxy = (ActorProxy)ActorProxy.Create(actorId, "TestActor", options); + var actorId = new ActorId("abc"); + var proxy = (ActorProxy)ActorProxy.Create(actorId, "TestActor", options); - Assert.Same(options.JsonSerializerOptions, proxy.JsonSerializerOptions); - } + Assert.Same(options.JsonSerializerOptions, proxy.JsonSerializerOptions); + } - [Fact] - public void SetActorProxyFactoryDefaultOptions_ToNull_ThrowsArgumentNullException() - { - var factory = new ActorProxyFactory(); - Action action = () => factory.DefaultOptions = null; + [Fact] + public void SetActorProxyFactoryDefaultOptions_ToNull_ThrowsArgumentNullException() + { + var factory = new ActorProxyFactory(); + Action action = () => factory.DefaultOptions = null; - action.Should().Throw(); - } + action.ShouldThrow(); } } diff --git a/test/Dapr.Actors.Test/ActorReferenceTests.cs b/test/Dapr.Actors.Test/ActorReferenceTests.cs index 7450f616c..b244ad8e4 100644 --- a/test/Dapr.Actors.Test/ActorReferenceTests.cs +++ b/test/Dapr.Actors.Test/ActorReferenceTests.cs @@ -1,93 +1,105 @@ -using System; +// ------------------------------------------------------------------------ +// Copyright 2021 The Dapr Authors +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// http://www.apache.org/licenses/LICENSE-2.0 +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// ------------------------------------------------------------------------ + +using System; using System.Threading.Tasks; using Dapr.Actors.Client; using Dapr.Actors.Runtime; using Dapr.Actors.Test; using Xunit; -namespace Dapr.Actors +namespace Dapr.Actors; + +public class ActorReferenceTests { - public class ActorReferenceTests + [Fact] + public void Get_WhenActorIsNull_ReturnsNull() + { + // Arrange + object actor = null; + + // Act + var result = ActorReference.Get(actor); + + // Assert + Assert.Null(result); + } + + [Fact] + public void Get_FromActorProxy_ReturnsActorReference() + { + // Arrange + var expectedActorId = new ActorId("abc"); + var expectedActorType = "TestActor"; + var proxy = ActorProxy.Create(expectedActorId, typeof(ITestActor), expectedActorType); + + // Act + var actorReference = ActorReference.Get(proxy); + + // Assert + Assert.NotNull(actorReference); + Assert.Equal(expectedActorId, actorReference.ActorId); + Assert.Equal(expectedActorType, actorReference.ActorType); + } + + [Fact] + public async Task Get_FromActorImplementation_ReturnsActorReference() { - [Fact] - public void Get_WhenActorIsNull_ReturnsNull() - { - // Arrange - object actor = null; - - // Act - var result = ActorReference.Get(actor); - - // Assert - Assert.Null(result); - } - - [Fact] - public void Get_FromActorProxy_ReturnsActorReference() - { - // Arrange - var expectedActorId = new ActorId("abc"); - var expectedActorType = "TestActor"; - var proxy = ActorProxy.Create(expectedActorId, typeof(ITestActor), expectedActorType); - - // Act - var actorReference = ActorReference.Get(proxy); - - // Assert - Assert.NotNull(actorReference); - Assert.Equal(expectedActorId, actorReference.ActorId); - Assert.Equal(expectedActorType, actorReference.ActorType); - } - - [Fact] - public async Task Get_FromActorImplementation_ReturnsActorReference() - { - // Arrange - var expectedActorId = new ActorId("abc"); - var expectedActorType = nameof(ActorReferenceTestActor); - var host = ActorHost.CreateForTest(new ActorTestOptions() { ActorId = expectedActorId }); - var actor = new ActorReferenceTestActor(host); - - // Act - var actorReference = await actor.GetActorReference(); - - // Assert - Assert.NotNull(actorReference); - Assert.Equal(expectedActorId, actorReference.ActorId); - Assert.Equal(expectedActorType, actorReference.ActorType); - } - - [Fact] - public void Get_WithInvalidObjectType_ThrowArgumentOutOfRangeException() - { - // Arrange - var actor = new object(); - - // Act - var act = () => ActorReference.Get(actor); - - // Assert - var exception = Assert.Throws(act); - Assert.Equal("actor", exception.ParamName); - Assert.Equal("Invalid actor object type. (Parameter 'actor')", exception.Message); - } + // Arrange + var expectedActorId = new ActorId("abc"); + var expectedActorType = nameof(ActorReferenceTestActor); + var host = ActorHost.CreateForTest(new ActorTestOptions() { ActorId = expectedActorId }); + var actor = new ActorReferenceTestActor(host); + + // Act + var actorReference = await actor.GetActorReference(); + + // Assert + Assert.NotNull(actorReference); + Assert.Equal(expectedActorId, actorReference.ActorId); + Assert.Equal(expectedActorType, actorReference.ActorType); + } + + [Fact] + public void Get_WithInvalidObjectType_ThrowArgumentOutOfRangeException() + { + // Arrange + var actor = new object(); + + // Act + var act = () => ActorReference.Get(actor); + + // Assert + var exception = Assert.Throws(act); + Assert.Equal("actor", exception.ParamName); + Assert.Equal("Invalid actor object type. (Parameter 'actor')", exception.Message); } +} + +public interface IActorReferenceTestActor : IActor +{ + Task GetActorReference(); +} - public interface IActorReferenceTestActor : IActor +public class ActorReferenceTestActor : Actor, IActorReferenceTestActor +{ + public ActorReferenceTestActor(ActorHost host) + : base(host) { - Task GetActorReference(); } - public class ActorReferenceTestActor : Actor, IActorReferenceTestActor + public Task GetActorReference() { - public ActorReferenceTestActor(ActorHost host) - : base(host) - { - } - - public Task GetActorReference() - { - return Task.FromResult(ActorReference.Get(this)); - } + return Task.FromResult(ActorReference.Get(this)); } } diff --git a/test/Dapr.Actors.Test/ApiTokenTests.cs b/test/Dapr.Actors.Test/ApiTokenTests.cs index 29ee955c7..6e5860be2 100644 --- a/test/Dapr.Actors.Test/ApiTokenTests.cs +++ b/test/Dapr.Actors.Test/ApiTokenTests.cs @@ -15,7 +15,7 @@ using System.Threading; using System.Threading.Tasks; using Dapr.Actors.Client; -using FluentAssertions; +using Shouldly; using Xunit; namespace Dapr.Actors.Test @@ -43,7 +43,7 @@ public async Task CreateProxyWithRemoting_WithApiToken() request.Dismiss(); var headerValues = request.Request.Headers.GetValues("dapr-api-token"); - headerValues.Should().Contain("test_token"); + headerValues.ShouldContain("test_token"); } [Fact(Skip = "https://github.com/dapr/dotnet-sdk/issues/596")] @@ -89,7 +89,7 @@ public async Task CreateProxyWithNoRemoting_WithApiToken() request.Dismiss(); var headerValues = request.Request.Headers.GetValues("dapr-api-token"); - headerValues.Should().Contain("test_token"); + headerValues.ShouldContain("test_token"); } [Fact] diff --git a/test/Dapr.Actors.Test/Dapr.Actors.Test.csproj b/test/Dapr.Actors.Test/Dapr.Actors.Test.csproj index 9ef26cd13..f28cbaef5 100644 --- a/test/Dapr.Actors.Test/Dapr.Actors.Test.csproj +++ b/test/Dapr.Actors.Test/Dapr.Actors.Test.csproj @@ -9,10 +9,10 @@ runtime; build; native; contentfiles; analyzers; buildtransitive all - + all diff --git a/test/Dapr.Actors.Test/DaprHttpInteractorTest.cs b/test/Dapr.Actors.Test/DaprHttpInteractorTest.cs index 9c42b8fc0..a978933a0 100644 --- a/test/Dapr.Actors.Test/DaprHttpInteractorTest.cs +++ b/test/Dapr.Actors.Test/DaprHttpInteractorTest.cs @@ -21,7 +21,7 @@ namespace Dapr.Actors.Test using System.Security.Authentication; using System.Text.Json; using System.Threading.Tasks; - using FluentAssertions; + using Shouldly; using Xunit; /// @@ -48,8 +48,8 @@ public async Task GetState_ValidateRequest() var actualPath = request.Request.RequestUri.LocalPath.TrimStart('/'); var expectedPath = string.Format(CultureInfo.InvariantCulture, Constants.ActorStateKeyRelativeUrlFormat, actorType, actorId, keyName); - actualPath.Should().Be(expectedPath); - request.Request.Method.Should().Be(HttpMethod.Get); + actualPath.ShouldBe(expectedPath); + request.Request.Method.ShouldBe(HttpMethod.Get); } [Fact] @@ -71,8 +71,8 @@ public async Task SaveStateTransactionally_ValidateRequest() var actualPath = request.Request.RequestUri.LocalPath.TrimStart('/'); var expectedPath = string.Format(CultureInfo.InvariantCulture, Constants.ActorStateRelativeUrlFormat, actorType, actorId); - actualPath.Should().Be(expectedPath); - request.Request.Method.Should().Be(HttpMethod.Put); + actualPath.ShouldBe(expectedPath); + request.Request.Method.ShouldBe(HttpMethod.Put); } [Fact] @@ -95,8 +95,8 @@ public async Task InvokeActorMethodWithoutRemoting_ValidateRequest() var actualPath = request.Request.RequestUri.LocalPath.TrimStart('/'); var expectedPath = string.Format(CultureInfo.InvariantCulture, Constants.ActorMethodRelativeUrlFormat, actorType, actorId, methodName); - actualPath.Should().Be(expectedPath); - request.Request.Method.Should().Be(HttpMethod.Put); + actualPath.ShouldBe(expectedPath); + request.Request.Method.ShouldBe(HttpMethod.Put); } [Fact] @@ -119,8 +119,8 @@ public async Task RegisterReminder_ValidateRequest() var actualPath = request.Request.RequestUri.LocalPath.TrimStart('/'); var expectedPath = string.Format(CultureInfo.InvariantCulture, Constants.ActorReminderRelativeUrlFormat, actorType, actorId, reminderName); - actualPath.Should().Be(expectedPath); - request.Request.Method.Should().Be(HttpMethod.Put); + actualPath.ShouldBe(expectedPath); + request.Request.Method.ShouldBe(HttpMethod.Put); } [Fact] @@ -142,8 +142,8 @@ public async Task UnregisterReminder_ValidateRequest() var actualPath = request.Request.RequestUri.LocalPath.TrimStart('/'); var expectedPath = string.Format(CultureInfo.InvariantCulture, Constants.ActorReminderRelativeUrlFormat, actorType, actorId, reminderName); - actualPath.Should().Be(expectedPath); - request.Request.Method.Should().Be(HttpMethod.Delete); + actualPath.ShouldBe(expectedPath); + request.Request.Method.ShouldBe(HttpMethod.Delete); } [Fact] @@ -166,8 +166,8 @@ public async Task RegisterTimer_ValidateRequest() var actualPath = request.Request.RequestUri.LocalPath.TrimStart('/'); var expectedPath = string.Format(CultureInfo.InvariantCulture, Constants.ActorTimerRelativeUrlFormat, actorType, actorId, timerName); - actualPath.Should().Be(expectedPath); - request.Request.Method.Should().Be(HttpMethod.Put); + actualPath.ShouldBe(expectedPath); + request.Request.Method.ShouldBe(HttpMethod.Put); } [Fact] @@ -189,8 +189,8 @@ public async Task UnregisterTimer_ValidateRequest() var actualPath = request.Request.RequestUri.LocalPath.TrimStart('/'); var expectedPath = string.Format(CultureInfo.InvariantCulture, Constants.ActorTimerRelativeUrlFormat, actorType, actorId, timerName); - actualPath.Should().Be(expectedPath); - request.Request.Method.Should().Be(HttpMethod.Delete); + actualPath.ShouldBe(expectedPath); + request.Request.Method.ShouldBe(HttpMethod.Delete); } [Fact] @@ -210,8 +210,8 @@ public async Task Call_WithApiTokenSet() request.Dismiss(); request.Request.Headers.TryGetValues("dapr-api-token", out var headerValues); - headerValues.Count().Should().Be(1); - headerValues.First().Should().Be("test_token"); + headerValues.Count().ShouldBe(1); + headerValues.First().ShouldBe("test_token"); } [Fact] @@ -231,7 +231,7 @@ public async Task Call_WithoutApiToken() request.Dismiss(); request.Request.Headers.TryGetValues("dapr-api-token", out var headerValues); - headerValues.Should().BeNull(); + headerValues.ShouldBeNull(); } [Fact] diff --git a/test/Dapr.Actors.Test/Description/ActorInterfaceDescriptionTests.cs b/test/Dapr.Actors.Test/Description/ActorInterfaceDescriptionTests.cs index 23579188f..3193a7957 100644 --- a/test/Dapr.Actors.Test/Description/ActorInterfaceDescriptionTests.cs +++ b/test/Dapr.Actors.Test/Description/ActorInterfaceDescriptionTests.cs @@ -1,20 +1,19 @@ -// ------------------------------------------------------------------------ -// Copyright 2021 The Dapr Authors -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// http://www.apache.org/licenses/LICENSE-2.0 -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// ------------------------------------------------------------------------ - -using System; +// ------------------------------------------------------------------------ +// Copyright 2021 The Dapr Authors +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// http://www.apache.org/licenses/LICENSE-2.0 +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// ------------------------------------------------------------------------ + +using System; using System.Threading.Tasks; -using FluentAssertions; -using FluentAssertions.Execution; +using Shouldly; using Xunit; namespace Dapr.Actors.Description @@ -31,13 +30,12 @@ public void ActorInterfaceDescription_CreateActorInterfaceDescription() var description = ActorInterfaceDescription.Create(type); // Assert - description.Should().NotBeNull(); + description.ShouldNotBeNull(); - using var _ = new AssertionScope(); - description.InterfaceType.Should().Be(type); - description.Id.Should().NotBe(0); - description.V1Id.Should().Be(0); - description.Methods.Should().HaveCount(2); + description.InterfaceType.ShouldBe(type); + description.Id.ShouldNotBe(0); + description.V1Id.ShouldBe(0); + description.Methods.Length.ShouldBe(2); } [Fact] @@ -50,10 +48,9 @@ public void ActorInterfaceDescription_CreateThrowsArgumentException_WhenTypeIsNo Action action = () => ActorInterfaceDescription.Create(type); // Assert - action.Should().ThrowExactly() - .WithMessage("The type 'System.Object' is not an Actor interface as it is not an interface.*") - .And.ParamName.Should().Be("actorInterfaceType"); - + var exception = Should.Throw(action); + exception.Message.ShouldMatch(@"The type 'System.Object' is not an Actor interface as it is not an interface.*"); + exception.ParamName.ShouldBe("actorInterfaceType"); } [Fact] @@ -66,9 +63,9 @@ public void ActorInterfaceDescription_CreateThrowsArgumentException_WhenTypeIsNo Action action = () => ActorInterfaceDescription.Create(type); // Assert - action.Should().ThrowExactly() - .WithMessage("The type 'System.ICloneable' is not an actor interface as it does not derive from the interface 'Dapr.Actors.IActor'.*") - .And.ParamName.Should().Be("actorInterfaceType"); + var exception = Should.Throw(action); + exception.Message.ShouldMatch(@"The type 'System.ICloneable' is not an actor interface as it does not derive from the interface 'Dapr.Actors.IActor'.*"); + exception.ParamName.ShouldBe("actorInterfaceType"); } [Fact] @@ -81,9 +78,9 @@ public void ActorInterfaceDescription_CreateThrowsArgumentException_WhenActorInt Action action = () => ActorInterfaceDescription.Create(type); // Assert - action.Should().ThrowExactly() - .WithMessage("The type '*+IClonableActor' is not an actor interface as it derive from a non actor interface 'System.ICloneable'. All actor interfaces must derive from 'Dapr.Actors.IActor'.*") - .And.ParamName.Should().Be("actorInterfaceType"); + var exception = Should.Throw(action); + exception.Message.ShouldMatch(@"The type '.*\+IClonableActor' is not an actor interface as it derive from a non actor interface 'System.ICloneable'. All actor interfaces must derive from 'Dapr.Actors.IActor'.*"); + exception.ParamName.ShouldBe("actorInterfaceType"); } [Fact] @@ -96,13 +93,12 @@ public void ActorInterfaceDescription_CreateUsingCRCIdActorInterfaceDescription( var description = ActorInterfaceDescription.CreateUsingCRCId(type); // Assert - description.Should().NotBeNull(); + description.ShouldNotBeNull(); - using var _ = new AssertionScope(); - description.InterfaceType.Should().Be(type); - description.Id.Should().Be(-934188464); - description.V1Id.Should().NotBe(0); - description.Methods.Should().HaveCount(2); + description.InterfaceType.ShouldBe(type); + description.Id.ShouldBe(-934188464); + description.V1Id.ShouldNotBe(0); + description.Methods.Length.ShouldBe(2); } [Fact] @@ -115,9 +111,9 @@ public void ActorInterfaceDescription_CreateUsingCRCIdThrowsArgumentException_Wh Action action = () => ActorInterfaceDescription.CreateUsingCRCId(type); // Assert - action.Should().ThrowExactly() - .WithMessage("The type 'System.Object' is not an Actor interface as it is not an interface.*") - .And.ParamName.Should().Be("actorInterfaceType"); + var exception = Should.Throw(action); + exception.Message.ShouldMatch(@"The type 'System.Object' is not an Actor interface as it is not an interface.*"); + exception.ParamName.ShouldBe("actorInterfaceType"); } [Fact] @@ -130,9 +126,9 @@ public void ActorInterfaceDescription_CreateUsingCRCIdThrowsArgumentException_Wh Action action = () => ActorInterfaceDescription.CreateUsingCRCId(type); // Assert - action.Should().ThrowExactly() - .WithMessage("The type 'System.ICloneable' is not an actor interface as it does not derive from the interface 'Dapr.Actors.IActor'.*") - .And.ParamName.Should().Be("actorInterfaceType"); + var exception = Should.Throw(action); + exception.Message.ShouldMatch(@"The type 'System.ICloneable' is not an actor interface as it does not derive from the interface 'Dapr.Actors.IActor'.*"); + exception.ParamName.ShouldBe("actorInterfaceType"); } [Fact] @@ -145,9 +141,9 @@ public void ActorInterfaceDescription_CreateUsingCRCIdThrowsArgumentException_Wh Action action = () => ActorInterfaceDescription.CreateUsingCRCId(type); // Assert - action.Should().ThrowExactly() - .WithMessage("The type '*+IClonableActor' is not an actor interface as it derive from a non actor interface 'System.ICloneable'. All actor interfaces must derive from 'Dapr.Actors.IActor'.*") - .And.ParamName.Should().Be("actorInterfaceType"); + var exception = Should.Throw(action); + exception.Message.ShouldMatch(@"The type '.*\+IClonableActor' is not an actor interface as it derive from a non actor interface 'System.ICloneable'. All actor interfaces must derive from 'Dapr.Actors.IActor'.*"); + exception.ParamName.ShouldBe("actorInterfaceType"); } internal interface IClonableActor : ICloneable, IActor diff --git a/test/Dapr.Actors.Test/Description/InterfaceDescriptionTests.cs b/test/Dapr.Actors.Test/Description/InterfaceDescriptionTests.cs index dbd44d55c..83f4de018 100644 --- a/test/Dapr.Actors.Test/Description/InterfaceDescriptionTests.cs +++ b/test/Dapr.Actors.Test/Description/InterfaceDescriptionTests.cs @@ -1,20 +1,20 @@ -// ------------------------------------------------------------------------ -// Copyright 2021 The Dapr Authors -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// http://www.apache.org/licenses/LICENSE-2.0 -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// ------------------------------------------------------------------------ - -using System; +// ------------------------------------------------------------------------ +// Copyright 2021 The Dapr Authors +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// http://www.apache.org/licenses/LICENSE-2.0 +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// ------------------------------------------------------------------------ + +using System; +using System.Linq; using System.Threading.Tasks; -using FluentAssertions; -using FluentAssertions.Execution; +using Shouldly; using Xunit; namespace Dapr.Actors.Description @@ -31,13 +31,12 @@ public void InterfaceDescription_CreateInterfaceDescription() TestDescription description = new(type); // Assert - description.Should().NotBeNull(); + description.ShouldNotBeNull(); - using var _ = new AssertionScope(); - description.InterfaceType.Should().Be(type); - description.Id.Should().NotBe(0); - description.V1Id.Should().Be(0); - description.Methods.Should().BeEmpty(); + description.InterfaceType.ShouldBe(type); + description.Id.ShouldNotBe(0); + description.V1Id.ShouldBe(0); + description.Methods.ShouldBeEmpty(); } [Fact] @@ -50,9 +49,8 @@ public void InterfaceDescription_CreateCrcIdAndV1Id_WhenUseCrcIdGenerationIsSet( TestDescription description = new(type, useCRCIdGeneration: true); // Assert - using var _ = new AssertionScope(); - description.Id.Should().Be(-934188464); - description.V1Id.Should().NotBe(0); + description.Id.ShouldBe(-934188464); + description.V1Id.ShouldNotBe(0); } [Fact] @@ -65,9 +63,9 @@ public void InterfaceDescription_CreateThrowsArgumentException_WhenTypeIsGeneric Action action = () => { TestDescription _ = new(type); }; // Assert - action.Should().ThrowExactly() - .WithMessage("The actor interface '*+IGenericActor`1' is using generics. Generic interfaces cannot be remoted.*") - .And.ParamName.Should().Be("actorInterfaceType"); + var exception = Should.Throw(action); + exception.Message.ShouldMatch(@"The actor interface '.*\+IGenericActor`1' is using generics. Generic interfaces cannot be remoted.*"); + exception.ParamName.ShouldBe("actorInterfaceType"); } [Fact] @@ -80,9 +78,9 @@ public void InterfaceDescription_CreateThrowsArgumentException_WhenTypeIsGeneric Action action = () => { TestDescription _ = new(type); }; // Assert - action.Should().ThrowExactly() - .WithMessage("The actor interface '*+IGenericActor`1[*IActor*]' is using generics. Generic interfaces cannot be remoted.*") - .And.ParamName.Should().Be("actorInterfaceType"); + var exception = Should.Throw(action); + exception.Message.ShouldMatch(@"The actor interface '.*\+IGenericActor`1\[.*IActor.*\]' is using generics. Generic interfaces cannot be remoted.*"); + exception.ParamName.ShouldBe("actorInterfaceType"); } [Fact] @@ -95,12 +93,9 @@ public void InterfaceDescription_CreateGeneratesMethodDescriptions_WhenTypeHasTa TestDescription description = new(type); // Assert - using var _ = new AssertionScope(); - description.Methods.Should().NotContainNulls(); - description.Methods.Should().AllBeOfType(); - description.Methods.Should().BeEquivalentTo( - new { Name = "GetInt" } - ); + description.Methods.ShouldNotBeNull(); + description.Methods.ShouldBeOfType(); + description.Methods.Select(m => new {m.Name}).ShouldBe(new[] {new {Name = "GetInt"}}); } [Fact] @@ -113,12 +108,9 @@ public void InterfaceDescription_CreateGeneratesMethodDescriptions_WhenTypeHasVo TestDescription description = new(type, methodReturnCheck: MethodReturnCheck.EnsureReturnsVoid); // Assert - using var _ = new AssertionScope(); - description.Methods.Should().NotContainNulls(); - description.Methods.Should().AllBeOfType(); - description.Methods.Should().BeEquivalentTo( - new { Name = "GetString" }, - new { Name = "MethodWithArguments" }); + description.Methods.ShouldNotBeNull(); + description.Methods.ShouldBeOfType(); + description.Methods.Select(m => new {m.Name}).ShouldBe(new[] {new {Name = "GetString"}, new {Name="MethodWithArguments"}}); } [Fact] @@ -128,12 +120,15 @@ public void InterfaceDescription_CreateThrowsArgumentException_WhenMethodsAreNot Type type = typeof(IVoidActor); // Act - Action action = () => { TestDescription _ = new(type); }; + Action action = () => + { + TestDescription _ = new(type); + }; // Assert - action.Should().ThrowExactly() - .WithMessage("Method 'GetString' of actor interface '*+IVoidActor' does not return Task or Task<>. The actor interface methods must be async and must return either Task or Task<>.*") - .And.ParamName.Should().Be("actorInterfaceType"); + var exception = Should.Throw(action); + exception.Message.ShouldMatch(@"Method 'GetString' of actor interface '.*\+IVoidActor' does not return Task or Task<>. The actor interface methods must be async and must return either Task or Task<>.*"); + exception.ParamName.ShouldBe("actorInterfaceType"); } [Fact] @@ -146,9 +141,9 @@ public void InterfaceDescription_CreateThrowsArgumentException_WhenMethodsAreNot Action action = () => { TestDescription _ = new(type, methodReturnCheck: MethodReturnCheck.EnsureReturnsVoid); }; // Assert - action.Should().ThrowExactly() - .WithMessage("Method 'GetString' of actor interface '*+IMethodActor' returns '*.Task`1[*System.String*]'*") - .And.ParamName.Should().Be("actorInterfaceType"); + var exception = Should.Throw(action); + exception.Message.ShouldMatch(@"Method 'GetString' of actor interface '.*\+IMethodActor' returns '.*\.Task`1\[.*System.String.*\]'.*"); + exception.ParamName.ShouldBe("actorInterfaceType"); } [Fact] @@ -161,9 +156,9 @@ public void InterfaceDescription_CreateThrowsArgumentException_WhenMethodsAreOve Action action = () => { TestDescription _ = new(type); }; // Assert - action.Should().ThrowExactly() - .WithMessage("Method 'GetString' of actor interface '*+IOverloadedMethodActor' is overloaded. The actor interface methods cannot be overloaded.*") - .And.ParamName.Should().Be("actorInterfaceType"); + var exception = Should.Throw(action); + exception.Message.ShouldMatch(@"Method 'GetString' of actor interface '.*\+IOverloadedMethodActor' is overloaded. The actor interface methods cannot be overloaded.*"); + exception.ParamName.ShouldBe("actorInterfaceType"); } [Fact] @@ -176,9 +171,9 @@ public void InterfaceDescription_CreateThrowsArgumentException_WhenMethodIsGener Action action = () => { TestDescription _ = new(type); }; // Assert - action.Should().ThrowExactly() - .WithMessage("Method 'Get' of actor interface '*+IGenericMethodActor' is using generics. The actor interface methods cannot use generics.*") - .And.ParamName.Should().Be("actorInterfaceType"); + var exception = Should.Throw(action); + exception.Message.ShouldMatch(@"Method 'Get' of actor interface '.*\+IGenericMethodActor' is using generics. The actor interface methods cannot use generics.*"); + exception.ParamName.ShouldBe("actorInterfaceType"); } [Fact] @@ -191,9 +186,9 @@ public void InterfaceDescription_CreateThrowsArgumentException_WhenMethodHasVari Action action = () => { TestDescription _ = new(type); }; // Assert - action.Should().ThrowExactly() - .WithMessage("Method 'MethodWithVarArgs' of actor interface '*+IVariableActor' is using a variable argument list. The actor interface methods cannot have a variable argument list.*") - .And.ParamName.Should().Be("actorInterfaceType"); + var exception = Should.Throw(action); + exception.Message.ShouldMatch(@"Method 'MethodWithVarArgs' of actor interface '.*\+IVariableActor' is using a variable argument list. The actor interface methods cannot have a variable argument list.*"); + exception.ParamName.ShouldBe("actorInterfaceType"); } internal interface ITestActor : IActor diff --git a/test/Dapr.Actors.Test/Description/MethodArgumentDescriptionTests.cs b/test/Dapr.Actors.Test/Description/MethodArgumentDescriptionTests.cs index 3a6f211cf..0841298a9 100644 --- a/test/Dapr.Actors.Test/Description/MethodArgumentDescriptionTests.cs +++ b/test/Dapr.Actors.Test/Description/MethodArgumentDescriptionTests.cs @@ -1,21 +1,20 @@ -// ------------------------------------------------------------------------ -// Copyright 2021 The Dapr Authors -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// http://www.apache.org/licenses/LICENSE-2.0 -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// ------------------------------------------------------------------------ - -using System; +// ------------------------------------------------------------------------ +// Copyright 2021 The Dapr Authors +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// http://www.apache.org/licenses/LICENSE-2.0 +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// ------------------------------------------------------------------------ + +using System; using System.Reflection; using System.Threading.Tasks; -using FluentAssertions; -using FluentAssertions.Execution; +using Shouldly; using Xunit; namespace Dapr.Actors.Description @@ -33,11 +32,10 @@ public void MethodArgumentDescription_CreatMethodArgumentDescription() var description = MethodArgumentDescription.Create("actor", methodInfo, parameterInfo); // Assert - description.Should().NotBeNull(); + description.ShouldNotBeNull(); - using var _ = new AssertionScope(); - description.Name.Should().Be("number"); - description.ArgumentType.Should().Be(); + description.Name.ShouldBe("number"); + description.ArgumentType.ShouldBe(typeof(int)); } [Fact] @@ -52,9 +50,9 @@ public void MethodDescription_CreateThrowsArgumentException_WhenParameterHasVari Action action = () => MethodArgumentDescription.Create("actor", methodInfo, parameterInfo); // Assert - action.Should().ThrowExactly() - .WithMessage("Method 'MethodWithParams' of actor interface '*ITestActor' has variable length parameter 'values'. The actor interface methods must not have variable length parameters.*") - .And.ParamName.Should().Be("actorInterfaceType"); + var exception = Should.Throw(action); + exception.Message.ShouldMatch(@"Method 'MethodWithParams' of actor interface '.*\+ITestActor' has variable length parameter 'values'. The actor interface methods must not have variable length parameters.*"); + exception.ParamName.ShouldBe("actorInterfaceType"); } [Fact] @@ -69,9 +67,9 @@ public void MethodDescription_CreateThrowsArgumentException_WhenParameterIsInput Action action = () => MethodArgumentDescription.Create("actor", methodInfo, parameterInfo); // Assert - action.Should().ThrowExactly() - .WithMessage("Method 'MethodWithIn' of actor interface '*ITestActor' has out/ref/optional parameter 'value'. The actor interface methods must not have out, ref or optional parameters.*") - .And.ParamName.Should().Be("actorInterfaceType"); + var exception = Should.Throw(action); + exception.Message.ShouldMatch(@"Method 'MethodWithIn' of actor interface '.*\+ITestActor' has out/ref/optional parameter 'value'. The actor interface methods must not have out, ref or optional parameters.*"); + exception.ParamName.ShouldBe("actorInterfaceType"); } [Fact] @@ -86,9 +84,9 @@ public void MethodDescription_CreateThrowsArgumentException_WhenParameterIsOutpu Action action = () => MethodArgumentDescription.Create("actor", methodInfo, parameterInfo); // Assert - action.Should().ThrowExactly() - .WithMessage("Method 'MethodWithOut' of actor interface '*ITestActor' has out/ref/optional parameter 'value'. The actor interface methods must not have out, ref or optional parameters.*") - .And.ParamName.Should().Be("actorInterfaceType"); + var exception = Should.Throw(action); + exception.Message.ShouldMatch(@"Method 'MethodWithOut' of actor interface '.*\+ITestActor' has out/ref/optional parameter 'value'. The actor interface methods must not have out, ref or optional parameters.*"); + exception.ParamName.ShouldBe("actorInterfaceType"); } [Fact] @@ -103,9 +101,9 @@ public void MethodDescription_CreateThrowsArgumentException_WhenParameterIsOptio Action action = () => MethodArgumentDescription.Create("actor", methodInfo, parameterInfo); // Assert - action.Should().ThrowExactly() - .WithMessage("Method 'MethodWithOptional' of actor interface '*ITestActor' has out/ref/optional parameter 'value'. The actor interface methods must not have out, ref or optional parameters.*") - .And.ParamName.Should().Be("actorInterfaceType"); + var exception = Should.Throw(action); + exception.Message.ShouldMatch(@"Method 'MethodWithOptional' of actor interface '.*\+ITestActor' has out/ref/optional parameter 'value'. The actor interface methods must not have out, ref or optional parameters.*"); + exception.ParamName.ShouldBe("actorInterfaceType"); } internal interface ITestActor : IActor diff --git a/test/Dapr.Actors.Test/Description/MethodDescriptionTests.cs b/test/Dapr.Actors.Test/Description/MethodDescriptionTests.cs index 8f11595e2..c8162f5f0 100644 --- a/test/Dapr.Actors.Test/Description/MethodDescriptionTests.cs +++ b/test/Dapr.Actors.Test/Description/MethodDescriptionTests.cs @@ -1,22 +1,22 @@ -// ------------------------------------------------------------------------ -// Copyright 2021 The Dapr Authors -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// http://www.apache.org/licenses/LICENSE-2.0 -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// ------------------------------------------------------------------------ - +// ------------------------------------------------------------------------ +// Copyright 2021 The Dapr Authors +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// http://www.apache.org/licenses/LICENSE-2.0 +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// ------------------------------------------------------------------------ + using System; +using System.Linq; using System.Reflection; using System.Threading; using System.Threading.Tasks; -using FluentAssertions; -using FluentAssertions.Execution; +using Shouldly; using Xunit; namespace Dapr.Actors.Description @@ -33,15 +33,14 @@ public void MethodDescription_CreatMethodDescription() var description = MethodDescription.Create("actor", methodInfo, false); // Assert - description.Should().NotBeNull(); - - using var _ = new AssertionScope(); - description.MethodInfo.Should().BeSameAs(methodInfo); - description.Name.Should().Be("GetString"); - description.ReturnType.Should().Be>(); - description.Id.Should().NotBe(0); - description.Arguments.Should().BeEmpty(); - description.HasCancellationToken.Should().BeFalse(); + description.ShouldNotBeNull(); + + description.MethodInfo.ShouldBeSameAs(methodInfo); + description.Name.ShouldBe("GetString"); + description.ReturnType.ShouldBe(typeof(Task)); + description.Id.ShouldNotBe(0); + description.Arguments.ShouldBeEmpty(); + description.HasCancellationToken.ShouldBeFalse(); } [Fact] @@ -54,7 +53,7 @@ public void MethodDescription_CreateCrcId_WhenUseCrcIdGenerationIsSet() var description = MethodDescription.Create("actor", methodInfo, true); // Assert - description.Id.Should().Be(70257263); + description.Id.ShouldBe(70257263); } [Fact] @@ -67,13 +66,9 @@ public void MethodDescription_CreateGeneratesArgumentDescriptions_WhenMethodHasA var description = MethodDescription.Create("actor", methodInfo, false); // Assert - using var _ = new AssertionScope(); - description.Arguments.Should().NotContainNulls(); - description.Arguments.Should().AllBeOfType(); - description.Arguments.Should().BeEquivalentTo( - new { Name = "number" }, - new { Name = "choice" }, - new { Name = "information" }); + description.Arguments.ShouldNotBeNull(); + description.Arguments.ShouldBeOfType(); + description.Arguments.Select(m => new {m.Name}).ShouldBe(new[] {new {Name = "number"}, new {Name = "choice"}, new {Name = "information"}}); } [Fact] @@ -86,7 +81,7 @@ public void MethodDescription_CreateSetsHasCancellationTokenToTrue_WhenMethodHas var description = MethodDescription.Create("actor", methodInfo, false); // Assert - description.HasCancellationToken.Should().BeTrue(); + description.HasCancellationToken.ShouldBeTrue(); } [Fact] @@ -100,9 +95,9 @@ public void MethodDescription_CreateThrowsArgumentException_WhenMethodHasTokenAs Action action = () => MethodDescription.Create("actor", methodInfo, false); // Assert - action.Should().ThrowExactly() - .WithMessage("Method 'MethodWithTokenNotLast' of actor interface '*+ITestActor' has a '*.CancellationToken' parameter that is not the last parameter. If an actor method accepts a '*.CancellationToken' parameter, it must be the last parameter.*") - .And.ParamName.Should().Be("actorInterfaceType"); + var exception = Should.Throw(action); + exception.Message.ShouldMatch(@"Method 'MethodWithTokenNotLast' of actor interface '.*\+ITestActor' has a '.*\.CancellationToken' parameter that is not the last parameter. If an actor method accepts a '.*\.CancellationToken' parameter, it must be the last parameter\..*"); + exception.ParamName.ShouldBe("actorInterfaceType"); } [Fact] @@ -116,9 +111,9 @@ public void MethodDescription_CreateThrowsArgumentException_WhenMethodHasMultipl Action action = () => MethodDescription.Create("actor", methodInfo, false); // Assert - action.Should().ThrowExactly() - .WithMessage("Method 'MethodWithMultipleTokens' of actor interface '*+ITestActor' has a '*.CancellationToken' parameter that is not the last parameter. If an actor method accepts a '*.CancellationToken' parameter, it must be the last parameter.*") - .And.ParamName.Should().Be("actorInterfaceType"); + var exception = Should.Throw(action); + exception.Message.ShouldMatch(@"Method 'MethodWithMultipleTokens' of actor interface '.*\+ITestActor' has a '.*\.CancellationToken' parameter that is not the last parameter. If an actor method accepts a '.*\.CancellationToken' parameter, it must be the last parameter.*"); + exception.ParamName.ShouldBe("actorInterfaceType"); } internal interface ITestActor : IActor diff --git a/test/Dapr.Actors.Test/ITestActor.cs b/test/Dapr.Actors.Test/ITestActor.cs index 4fa611e7c..847342c1d 100644 --- a/test/Dapr.Actors.Test/ITestActor.cs +++ b/test/Dapr.Actors.Test/ITestActor.cs @@ -11,118 +11,117 @@ // limitations under the License. // ------------------------------------------------------------------------ -namespace Dapr.Actors.Test -{ - using System; - using System.Threading; - using System.Threading.Tasks; - using Dapr.Actors.Runtime; +namespace Dapr.Actors.Test; + +using System; +using System.Threading; +using System.Threading.Tasks; +using Dapr.Actors.Runtime; +/// +/// Interface for test actor. +/// +public interface ITestActor : IActor +{ /// - /// Interface for test actor. + /// GetCount method for TestActor. /// - public interface ITestActor : IActor - { - /// - /// GetCount method for TestActor. - /// - /// Cancellation token to cancel the operation. - /// The current count as stored in actor. - Task GetCountAsync(CancellationToken cancellationToken); - - /// - /// SetCount method for test actor. - /// - /// Count to set for the actor. - /// Cancellation token to cancel the operation. - /// Task. - Task SetCountAsync(int count, CancellationToken cancellationToken); - } + /// Cancellation token to cancel the operation. + /// The current count as stored in actor. + Task GetCountAsync(CancellationToken cancellationToken); /// - /// Test Actor Class. + /// SetCount method for test actor. /// - public class TestActor : Actor, ITestActor + /// Count to set for the actor. + /// Cancellation token to cancel the operation. + /// Task. + Task SetCountAsync(int count, CancellationToken cancellationToken); +} + +/// +/// Test Actor Class. +/// +public class TestActor : Actor, ITestActor +{ + public TestActor(ActorHost host, IActorStateManager stateManager = null) + : base(host) { - public TestActor(ActorHost host, IActorStateManager stateManager = null) - : base(host) + if (stateManager != null) { - if (stateManager != null) - { - this.StateManager = stateManager; - } + this.StateManager = stateManager; } + } - /// - public Task GetCountAsync(CancellationToken cancellationToken) - { - return Task.FromResult(5); - } + /// + public Task GetCountAsync(CancellationToken cancellationToken) + { + return Task.FromResult(5); + } - /// - public Task SetCountAsync(int count, CancellationToken cancellationToken) - { - return Task.CompletedTask; - } + /// + public Task SetCountAsync(int count, CancellationToken cancellationToken) + { + return Task.CompletedTask; + } - public Task SaveTestState() - { - return this.SaveStateAsync(); - } + public Task SaveTestState() + { + return this.SaveStateAsync(); + } - public Task ResetTestStateAsync() - { - return this.ResetStateAsync(); - } + public Task ResetTestStateAsync() + { + return this.ResetStateAsync(); + } - public void TimerCallbackNonTaskReturnType() - { - } + public void TimerCallbackNonTaskReturnType() + { + } - public Task TimerCallbackTwoArguments(int i, int j) - { - Console.WriteLine(i + j); - return default; - } + public Task TimerCallbackTwoArguments(int i, int j) + { + Console.WriteLine(i + j); + return default; + } - private Task TimerCallbackPrivate() - { - return default; - } + private Task TimerCallbackPrivate() + { + return default; + } - protected Task TimerCallbackProtected() - { - return default; - } + protected Task TimerCallbackProtected() + { + return default; + } - internal Task TimerCallbackInternal() - { - return default; - } + internal Task TimerCallbackInternal() + { + return default; + } - public Task TimerCallbackPublicWithNoArguments() - { - return default; - } + public Task TimerCallbackPublicWithNoArguments() + { + return default; + } - public Task TimerCallbackPublicWithOneArgument(int i) - { - return default; - } + public Task TimerCallbackPublicWithOneArgument(int i) + { + return default; + } - public Task TimerCallbackOverloaded() - { - return default; - } + public Task TimerCallbackOverloaded() + { + return default; + } - public Task TimerCallbackOverloaded(int i) - { - return default; - } + public Task TimerCallbackOverloaded(int i) + { + return default; + } - public static Task TimerCallbackStatic() - { - return default; - } + public static Task TimerCallbackStatic() + { + return default; } } diff --git a/test/Dapr.Actors.Test/Runtime/ActorRuntimeOptionsTests.cs b/test/Dapr.Actors.Test/Runtime/ActorRuntimeOptionsTests.cs index b68eda5ce..6701535fc 100644 --- a/test/Dapr.Actors.Test/Runtime/ActorRuntimeOptionsTests.cs +++ b/test/Dapr.Actors.Test/Runtime/ActorRuntimeOptionsTests.cs @@ -17,7 +17,7 @@ namespace Dapr.Actors.Test.Runtime using Moq; using Xunit; using System; - using FluentAssertions; + using Shouldly; public sealed class ActorRuntimeOptionsTests { @@ -59,7 +59,7 @@ public void SettingActorIdleTimeoutToLessThanZero_Fails() var options = new ActorRuntimeOptions(); Action action = () => options.ActorIdleTimeout = TimeSpan.FromSeconds(-1); - action.Should().Throw(); + action.ShouldThrow(); } @@ -78,7 +78,7 @@ public void SettingActorScanIntervalToLessThanZero_Fails() var options = new ActorRuntimeOptions(); Action action = () => options.ActorScanInterval = TimeSpan.FromSeconds(-1); - action.Should().Throw(); + action.ShouldThrow(); } [Fact] @@ -96,7 +96,7 @@ public void SettingDrainOngoingCallTimeoutToLessThanZero_Fails() var options = new ActorRuntimeOptions(); Action action = () => options.DrainOngoingCallTimeout = TimeSpan.FromSeconds(-1); - action.Should().Throw(); + action.ShouldThrow(); } [Fact] @@ -115,7 +115,7 @@ public void SettingJsonSerializerOptionsToNull_Fails() var options = new ActorRuntimeOptions(); Action action = () => options.JsonSerializerOptions = null; - action.Should().Throw(); + action.ShouldThrow(); } [Fact] @@ -124,7 +124,7 @@ public void SettingRemindersStoragePartitionsToLessThanZero_Fails() var options = new ActorRuntimeOptions(); Action action = () => options.RemindersStoragePartitions = -1; - action.Should().Throw(); + action.ShouldThrow(); } [Fact] diff --git a/test/Dapr.Actors.Test/Runtime/ActorTests.cs b/test/Dapr.Actors.Test/Runtime/ActorTests.cs index f88b4e03f..d08f42a01 100644 --- a/test/Dapr.Actors.Test/Runtime/ActorTests.cs +++ b/test/Dapr.Actors.Test/Runtime/ActorTests.cs @@ -11,119 +11,112 @@ // limitations under the License. // ------------------------------------------------------------------------ -namespace Dapr.Actors.Test.Runtime -{ - using System; - using System.Threading; - using System.Threading.Tasks; - using Dapr.Actors.Runtime; - using FluentAssertions; - using Moq; - using Xunit; +namespace Dapr.Actors.Test.Runtime; - public sealed class ActorTests - { - [Fact] - public void TestNewActorWithMockStateManager() - { - var mockStateManager = new Mock(); - var testDemoActor = this.CreateTestDemoActor(mockStateManager.Object); - testDemoActor.Host.Should().NotBeNull(); - testDemoActor.Id.Should().NotBeNull(); - } +using System; +using System.Threading; +using System.Threading.Tasks; +using Dapr.Actors.Runtime; +using Shouldly; +using Moq; +using Xunit; - [Fact] - public async Task TestSaveState() - { - var mockStateManager = new Mock(); - mockStateManager.Setup(manager => manager.SaveStateAsync(It.IsAny())); - var testDemoActor = this.CreateTestDemoActor(mockStateManager.Object); - await testDemoActor.SaveTestState(); - mockStateManager.Verify(manager => manager.SaveStateAsync(It.IsAny()), Times.Once); - } +public sealed class ActorTests +{ + [Fact] + public void TestNewActorWithMockStateManager() + { + var mockStateManager = new Mock(); + var testDemoActor = this.CreateTestDemoActor(mockStateManager.Object); + testDemoActor.Host.ShouldNotBeNull(); + testDemoActor.Id.ShouldNotBeNull(); + } - [Fact] - public async Task TestResetStateAsync() - { - var mockStateManager = new Mock(); - mockStateManager.Setup(manager => manager.ClearCacheAsync(It.IsAny())); - var testDemoActor = this.CreateTestDemoActor(mockStateManager.Object); - await testDemoActor.ResetTestStateAsync(); - mockStateManager.Verify(manager => manager.ClearCacheAsync(It.IsAny()), Times.Once); - } + [Fact] + public async Task TestSaveState() + { + var mockStateManager = new Mock(); + mockStateManager.Setup(manager => manager.SaveStateAsync(It.IsAny())); + var testDemoActor = this.CreateTestDemoActor(mockStateManager.Object); + await testDemoActor.SaveTestState(); + mockStateManager.Verify(manager => manager.SaveStateAsync(It.IsAny()), Times.Once); + } - [Theory] - [InlineData("NonExistentMethod", "Timer callback method: NonExistentMethod does not exist in the Actor class: TestActor")] - [InlineData("TimerCallbackTwoArguments", "Timer callback can accept only zero or one parameters")] - [InlineData("TimerCallbackNonTaskReturnType", "Timer callback can only return type Task")] - [InlineData("TimerCallbackOverloaded", "Timer callback method: TimerCallbackOverloaded cannot be overloaded.")] - public void ValidateTimerCallback_CallbackMethodDoesNotMeetRequirements(string callback, string expectedErrorMessage) - { - var mockStateManager = new Mock(); - mockStateManager.Setup(manager => manager.ClearCacheAsync(It.IsAny())); - var testDemoActor = this.CreateTestDemoActor(mockStateManager.Object); + [Fact] + public async Task TestResetStateAsync() + { + var mockStateManager = new Mock(); + mockStateManager.Setup(manager => manager.ClearCacheAsync(It.IsAny())); + var testDemoActor = this.CreateTestDemoActor(mockStateManager.Object); + await testDemoActor.ResetTestStateAsync(); + mockStateManager.Verify(manager => manager.ClearCacheAsync(It.IsAny()), Times.Once); + } - ; - FluentActions.Invoking(() => - testDemoActor.ValidateTimerCallback(testDemoActor.Host, callback)) - .Should().Throw() - .WithMessage(expectedErrorMessage); - } + [Theory] + [InlineData("NonExistentMethod", "Timer callback method: NonExistentMethod does not exist in the Actor class: TestActor")] + [InlineData("TimerCallbackTwoArguments", "Timer callback can accept only zero or one parameters")] + [InlineData("TimerCallbackNonTaskReturnType", "Timer callback can only return type Task")] + [InlineData("TimerCallbackOverloaded", "Timer callback method: TimerCallbackOverloaded cannot be overloaded.")] + public void ValidateTimerCallback_CallbackMethodDoesNotMeetRequirements(string callback, string expectedErrorMessage) + { + var mockStateManager = new Mock(); + mockStateManager.Setup(manager => manager.ClearCacheAsync(It.IsAny())); + var testDemoActor = this.CreateTestDemoActor(mockStateManager.Object); - [Theory] - [InlineData("TimerCallbackPrivate")] - [InlineData("TimerCallbackProtected")] - [InlineData("TimerCallbackInternal")] - [InlineData("TimerCallbackPublicWithNoArguments")] - [InlineData("TimerCallbackPublicWithOneArgument")] - [InlineData("TimerCallbackStatic")] - public void ValidateTimerCallback_CallbackMethodMeetsRequirements(string callback) - { - var mockStateManager = new Mock(); - mockStateManager.Setup(manager => manager.ClearCacheAsync(It.IsAny())); - var testDemoActor = this.CreateTestDemoActor(mockStateManager.Object); + Should.Throw(() => testDemoActor.ValidateTimerCallback(testDemoActor.Host, callback)) + .Message.ShouldBe(expectedErrorMessage); + } - ; - FluentActions.Invoking(() => - testDemoActor.ValidateTimerCallback(testDemoActor.Host, callback)) - .Should().NotThrow(); - } + [Theory] + [InlineData("TimerCallbackPrivate")] + [InlineData("TimerCallbackProtected")] + [InlineData("TimerCallbackInternal")] + [InlineData("TimerCallbackPublicWithNoArguments")] + [InlineData("TimerCallbackPublicWithOneArgument")] + [InlineData("TimerCallbackStatic")] + public void ValidateTimerCallback_CallbackMethodMeetsRequirements(string callback) + { + var mockStateManager = new Mock(); + mockStateManager.Setup(manager => manager.ClearCacheAsync(It.IsAny())); + var testDemoActor = this.CreateTestDemoActor(mockStateManager.Object); - [Theory] - [InlineData("TimerCallbackPrivate")] - [InlineData("TimerCallbackPublicWithOneArgument")] - [InlineData("TimerCallbackStatic")] - public void GetMethodInfoUsingReflection_MethodsMatchingBindingFlags(string callback) - { - var mockStateManager = new Mock(); - mockStateManager.Setup(manager => manager.ClearCacheAsync(It.IsAny())); - var testDemoActor = this.CreateTestDemoActor(mockStateManager.Object); - var methodInfo = testDemoActor.GetMethodInfoUsingReflection(testDemoActor.Host.ActorTypeInfo.ImplementationType, callback); - Assert.NotNull(methodInfo); - } + Should.NotThrow(() => testDemoActor.ValidateTimerCallback(testDemoActor.Host, callback)); + } - [Theory] - [InlineData("TestActor")] // Constructor - public void GetMethodInfoUsingReflection_MethodsNotMatchingBindingFlags(string callback) - { - var mockStateManager = new Mock(); - mockStateManager.Setup(manager => manager.ClearCacheAsync(It.IsAny())); - var testDemoActor = this.CreateTestDemoActor(mockStateManager.Object); - var methodInfo = testDemoActor.GetMethodInfoUsingReflection(testDemoActor.Host.ActorTypeInfo.ImplementationType, callback); - Assert.Null(methodInfo); - } + [Theory] + [InlineData("TimerCallbackPrivate")] + [InlineData("TimerCallbackPublicWithOneArgument")] + [InlineData("TimerCallbackStatic")] + public void GetMethodInfoUsingReflection_MethodsMatchingBindingFlags(string callback) + { + var mockStateManager = new Mock(); + mockStateManager.Setup(manager => manager.ClearCacheAsync(It.IsAny())); + var testDemoActor = this.CreateTestDemoActor(mockStateManager.Object); + var methodInfo = testDemoActor.GetMethodInfoUsingReflection(testDemoActor.Host.ActorTypeInfo.ImplementationType, callback); + Assert.NotNull(methodInfo); + } - /// - /// On my test code I want to pass the mock statemanager all the time. - /// - /// Mock StateManager. - /// TestActor. - private TestActor CreateTestDemoActor(IActorStateManager actorStateManager) - { - var host = ActorHost.CreateForTest(); - var testActor = new TestActor(host, actorStateManager); - return testActor; - } + [Theory] + [InlineData("TestActor")] // Constructor + public void GetMethodInfoUsingReflection_MethodsNotMatchingBindingFlags(string callback) + { + var mockStateManager = new Mock(); + mockStateManager.Setup(manager => manager.ClearCacheAsync(It.IsAny())); + var testDemoActor = this.CreateTestDemoActor(mockStateManager.Object); + var methodInfo = testDemoActor.GetMethodInfoUsingReflection(testDemoActor.Host.ActorTypeInfo.ImplementationType, callback); + Assert.Null(methodInfo); + } + /// + /// On my test code I want to pass the mock statemanager all the time. + /// + /// Mock StateManager. + /// TestActor. + private TestActor CreateTestDemoActor(IActorStateManager actorStateManager) + { + var host = ActorHost.CreateForTest(); + var testActor = new TestActor(host, actorStateManager); + return testActor; } + } diff --git a/test/Dapr.Actors.Test/Serialization/ActorIdDataContractSerializationTest.cs b/test/Dapr.Actors.Test/Serialization/ActorIdDataContractSerializationTest.cs index dfaccbc19..7ac29505a 100644 --- a/test/Dapr.Actors.Test/Serialization/ActorIdDataContractSerializationTest.cs +++ b/test/Dapr.Actors.Test/Serialization/ActorIdDataContractSerializationTest.cs @@ -14,69 +14,68 @@ using System.IO; using System.Runtime.Serialization; using System.Xml; -using FluentAssertions; +using Shouldly; using Xunit; -namespace Dapr.Actors.Serialization +namespace Dapr.Actors.Serialization; + +public class ActorReferenceDataContractSerializationTest { - public class ActorReferenceDataContractSerializationTest + [Fact] + public void CanSerializeAndDeserializeActorId() { - [Fact] - public void CanSerializeAndDeserializeActorId() - { - var id = ActorId.CreateRandom(); - DataContractSerializer serializer = new DataContractSerializer(id.GetType()); - MemoryStream ms = new MemoryStream(); - serializer.WriteObject(ms, id); - ms.Position = 0; + var id = ActorId.CreateRandom(); + DataContractSerializer serializer = new DataContractSerializer(id.GetType()); + MemoryStream ms = new MemoryStream(); + serializer.WriteObject(ms, id); + ms.Position = 0; - XmlDocument xmlDoc = new XmlDocument(); - xmlDoc.Load(ms); - xmlDoc.DocumentElement.Name.Should().Be("ActorId"); - xmlDoc.DocumentElement.InnerText.Should().Be(id.ToString()); - ms.Position = 0; + XmlDocument xmlDoc = new XmlDocument(); + xmlDoc.Load(ms); + xmlDoc.DocumentElement.Name.ShouldBe("ActorId"); + xmlDoc.DocumentElement.InnerText.ShouldBe(id.ToString()); + ms.Position = 0; - var deserializedActorId = serializer.ReadObject(ms) as ActorId; - deserializedActorId.Should().Be(id); - } + var deserializedActorId = serializer.ReadObject(ms) as ActorId; + deserializedActorId.ShouldBe(id); + } - [Fact] - public void CanSerializeAndDeserializeNullActorId() - { - ActorId id = null; - DataContractSerializer serializer = new DataContractSerializer(typeof(ActorId)); - MemoryStream ms = new MemoryStream(); - serializer.WriteObject(ms, id); - ms.Position = 0; + [Fact] + public void CanSerializeAndDeserializeNullActorId() + { + ActorId id = null; + DataContractSerializer serializer = new DataContractSerializer(typeof(ActorId)); + MemoryStream ms = new MemoryStream(); + serializer.WriteObject(ms, id); + ms.Position = 0; - XmlDocument xmlDoc = new XmlDocument(); - xmlDoc.Load(ms); - xmlDoc.DocumentElement.Name.Should().Be("ActorId"); - xmlDoc.DocumentElement.InnerText.Should().Be(string.Empty); + XmlDocument xmlDoc = new XmlDocument(); + xmlDoc.Load(ms); + xmlDoc.DocumentElement.Name.ShouldBe("ActorId"); + xmlDoc.DocumentElement.InnerText.ShouldBe(string.Empty); - ms.Position = 0; - var deserializedActorId = serializer.ReadObject(ms) as ActorId; - deserializedActorId.Should().Be(id); - } + ms.Position = 0; + var deserializedActorId = serializer.ReadObject(ms) as ActorId; + deserializedActorId.ShouldBe(id); + } - [Fact] - public void CanRoundTripActorReference() + [Fact] + public void CanRoundTripActorReference() + { + var actorId = new ActorId("abc"); + var actorReference = new ActorReference() { - var actorId = new ActorId("abc"); - var actorReference = new ActorReference() - { - ActorId = actorId, - ActorType = "TestActor" - }; + ActorId = actorId, + ActorType = "TestActor" + }; - DataContractSerializer serializer = new DataContractSerializer(actorReference.GetType()); - MemoryStream ms = new MemoryStream(); - serializer.WriteObject(ms, actorReference); - ms.Position = 0; + DataContractSerializer serializer = new DataContractSerializer(actorReference.GetType()); + MemoryStream ms = new MemoryStream(); + serializer.WriteObject(ms, actorReference); + ms.Position = 0; - var deserializedActorRef = serializer.ReadObject(ms) as ActorReference; - deserializedActorRef.ActorId.Should().Be(actorId); - deserializedActorRef.ActorType.Should().Be("TestActor"); - } + var deserializedActorRef = serializer.ReadObject(ms) as ActorReference; + deserializedActorRef.ActorId.ShouldBe(actorId); + deserializedActorRef.ActorType.ShouldBe("TestActor"); } } diff --git a/test/Dapr.Actors.Test/Serialization/ActorIdJsonConverterTest.cs b/test/Dapr.Actors.Test/Serialization/ActorIdJsonConverterTest.cs index 9c4f22193..06615a1c4 100644 --- a/test/Dapr.Actors.Test/Serialization/ActorIdJsonConverterTest.cs +++ b/test/Dapr.Actors.Test/Serialization/ActorIdJsonConverterTest.cs @@ -15,101 +15,100 @@ using System.Text.Json.Serialization; using Xunit; -namespace Dapr.Actors.Serialization +namespace Dapr.Actors.Serialization; + +public class ActorIdJsonConverterTest { - public class ActorIdJsonConverterTest + [Fact] + public void CanSerializeActorId() { - [Fact] - public void CanSerializeActorId() - { - var id = ActorId.CreateRandom(); - var document = new { actor = id, }; + var id = ActorId.CreateRandom(); + var document = new { actor = id, }; - // We use strings for ActorId - the result should be the same as passing the Id directly. - var expected = JsonSerializer.Serialize(new { actor = id.GetId(), }); + // We use strings for ActorId - the result should be the same as passing the Id directly. + var expected = JsonSerializer.Serialize(new { actor = id.GetId(), }); - var serialized = JsonSerializer.Serialize(document); + var serialized = JsonSerializer.Serialize(document); - Assert.Equal(expected, serialized); - } + Assert.Equal(expected, serialized); + } - [Fact] - public void CanSerializeNullActorId() - { - var document = new { actor = (ActorId)null, }; + [Fact] + public void CanSerializeNullActorId() + { + var document = new { actor = (ActorId)null, }; - var expected = JsonSerializer.Serialize(new { actor = (string)null, }); + var expected = JsonSerializer.Serialize(new { actor = (string)null, }); - var serialized = JsonSerializer.Serialize(document); + var serialized = JsonSerializer.Serialize(document); - Assert.Equal(expected, serialized); - } + Assert.Equal(expected, serialized); + } - [Fact] - public void CanDeserializeActorId() - { - var id = ActorId.CreateRandom().GetId(); - var document = $@" + [Fact] + public void CanDeserializeActorId() + { + var id = ActorId.CreateRandom().GetId(); + var document = $@" {{ ""actor"": ""{id}"" }}"; - var deserialized = JsonSerializer.Deserialize(document); + var deserialized = JsonSerializer.Deserialize(document); - Assert.Equal(id, deserialized.Actor.GetId()); - } + Assert.Equal(id, deserialized.Actor.GetId()); + } - [Fact] - public void CanDeserializeNullActorId() - { - const string document = @" + [Fact] + public void CanDeserializeNullActorId() + { + const string document = @" { ""actor"": null }"; - var deserialized = JsonSerializer.Deserialize(document); - - Assert.Null(deserialized.Actor); - } - - [Theory] - [InlineData("{ \"actor\": ")] - [InlineData("{ \"actor\": \"hi")] - [InlineData("{ \"actor\": }")] - [InlineData("{ \"actor\": 3 }")] - [InlineData("{ \"actor\": \"\"}")] - [InlineData("{ \"actor\": \" \"}")] - public void CanReportErrorsFromInvalidData(string document) + var deserialized = JsonSerializer.Deserialize(document); + + Assert.Null(deserialized.Actor); + } + + [Theory] + [InlineData("{ \"actor\": ")] + [InlineData("{ \"actor\": \"hi")] + [InlineData("{ \"actor\": }")] + [InlineData("{ \"actor\": 3 }")] + [InlineData("{ \"actor\": \"\"}")] + [InlineData("{ \"actor\": \" \"}")] + public void CanReportErrorsFromInvalidData(string document) + { + // The error messages are provided by the serializer, don't test them here + // that would be fragile. + Assert.Throws(() => { - // The error messages are provided by the serializer, don't test them here - // that would be fragile. - Assert.Throws(() => - { - JsonSerializer.Deserialize(document); - }); - } + JsonSerializer.Deserialize(document); + }); + } - // Regression test for #444 - [Fact] - public void CanRoundTripActorReference() + // Regression test for #444 + [Fact] + public void CanRoundTripActorReference() + { + var reference = new ActorReference() { - var reference = new ActorReference() - { - ActorId = ActorId.CreateRandom(), - ActorType = "TestActor", - }; + ActorId = ActorId.CreateRandom(), + ActorType = "TestActor", + }; - var serialized = JsonSerializer.Serialize(reference); - var deserialized = JsonSerializer.Deserialize(serialized); + var serialized = JsonSerializer.Serialize(reference); + var deserialized = JsonSerializer.Deserialize(serialized); - Assert.Equal(reference.ActorId.GetId(), deserialized.ActorId.GetId()); - Assert.Equal(reference.ActorType, deserialized.ActorType); - } + Assert.Equal(reference.ActorId.GetId(), deserialized.ActorId.GetId()); + Assert.Equal(reference.ActorType, deserialized.ActorType); + } - private class ActorHolder - { - [JsonPropertyName("actor")] - public ActorId Actor { get; set; } - } + private class ActorHolder + { + [JsonPropertyName("actor")] + public ActorId Actor { get; set; } } } diff --git a/test/Dapr.Actors.Test/Serialization/TimerInfoJsonConverterTest.cs b/test/Dapr.Actors.Test/Serialization/TimerInfoJsonConverterTest.cs index 264fcb8a0..4cf4c58ae 100644 --- a/test/Dapr.Actors.Test/Serialization/TimerInfoJsonConverterTest.cs +++ b/test/Dapr.Actors.Test/Serialization/TimerInfoJsonConverterTest.cs @@ -16,30 +16,29 @@ using Xunit; #pragma warning disable 0618 -namespace Dapr.Actors.Runtime +namespace Dapr.Actors.Runtime; + +public class TimerInfoJsonConverterTest { - public class TimerInfoJsonConverterTest + [Theory] + [InlineData("test", new byte[] {1, 2, 3}, 2, 4)] + [InlineData(null, new byte[] {1}, 2, 4)] + [InlineData("test", null, 2, 4)] + [InlineData("test", new byte[] {1}, 0, 4)] + [InlineData("test", new byte[] {1}, 2, 0)] + public void CanSerializeAndDeserializeTimerInfo(string callback, byte[] state, int dueTime, int period) { - [Theory] - [InlineData("test", new byte[] {1, 2, 3}, 2, 4)] - [InlineData(null, new byte[] {1}, 2, 4)] - [InlineData("test", null, 2, 4)] - [InlineData("test", new byte[] {1}, 0, 4)] - [InlineData("test", new byte[] {1}, 2, 0)] - public void CanSerializeAndDeserializeTimerInfo(string callback, byte[] state, int dueTime, int period) - { - var timerInfo = new TimerInfo(callback, state, TimeSpan.FromSeconds(dueTime), TimeSpan.FromSeconds(period)); + var timerInfo = new TimerInfo(callback, state, TimeSpan.FromSeconds(dueTime), TimeSpan.FromSeconds(period)); - // We use strings for ActorId - the result should be the same as passing the Id directly. - var serializedTimerInfo = JsonSerializer.Serialize(timerInfo); + // We use strings for ActorId - the result should be the same as passing the Id directly. + var serializedTimerInfo = JsonSerializer.Serialize(timerInfo); - var deserializedTimerInfo = JsonSerializer.Deserialize(serializedTimerInfo); + var deserializedTimerInfo = JsonSerializer.Deserialize(serializedTimerInfo); - Assert.Equal(timerInfo.Callback, deserializedTimerInfo.Callback); - Assert.Equal(timerInfo.Data, deserializedTimerInfo.Data); - Assert.Equal(timerInfo.DueTime, deserializedTimerInfo.DueTime); - Assert.Equal(timerInfo.Period, deserializedTimerInfo.Period); - } + Assert.Equal(timerInfo.Callback, deserializedTimerInfo.Callback); + Assert.Equal(timerInfo.Data, deserializedTimerInfo.Data); + Assert.Equal(timerInfo.DueTime, deserializedTimerInfo.DueTime); + Assert.Equal(timerInfo.Period, deserializedTimerInfo.Period); } } #pragma warning restore 0618 diff --git a/test/Dapr.Actors.Test/TestDaprInteractor.cs b/test/Dapr.Actors.Test/TestDaprInteractor.cs index 11f88e684..2d81f16d0 100644 --- a/test/Dapr.Actors.Test/TestDaprInteractor.cs +++ b/test/Dapr.Actors.Test/TestDaprInteractor.cs @@ -3,157 +3,156 @@ using System.Threading.Tasks; using Dapr.Actors.Communication; -namespace Dapr.Actors +namespace Dapr.Actors; + +/// +/// A Wrapper class for IDaprInteractor which is mainly created for testing. +/// +public class TestDaprInteractor : IDaprInteractor { + private TestDaprInteractor _testDaprInteractor; + /// - /// A Wrapper class for IDaprInteractor which is mainly created for testing. + /// The TestDaprInteractor constructor. /// - public class TestDaprInteractor : IDaprInteractor + /// + public TestDaprInteractor(TestDaprInteractor testDaprInteractor) { - private TestDaprInteractor _testDaprInteractor; - - /// - /// The TestDaprInteractor constructor. - /// - /// - public TestDaprInteractor(TestDaprInteractor testDaprInteractor) - { - _testDaprInteractor = testDaprInteractor; - } + _testDaprInteractor = testDaprInteractor; + } - /// - /// The TestDaprInteractor constructor. - /// - public TestDaprInteractor() - { + /// + /// The TestDaprInteractor constructor. + /// + public TestDaprInteractor() + { - } + } - /// - /// Register a reminder. - /// - /// Type of actor. - /// ActorId. - /// Name of reminder to register. - /// JSON reminder data as per the Dapr spec. - /// Cancels the operation. - /// A representing the result of the asynchronous operation. - public virtual async Task RegisterReminderAsync(string actorType, string actorId, string reminderName, string data, - CancellationToken cancellationToken = default) - { - await _testDaprInteractor.RegisterReminderAsync(actorType, actorId, reminderName, data); - } + /// + /// Register a reminder. + /// + /// Type of actor. + /// ActorId. + /// Name of reminder to register. + /// JSON reminder data as per the Dapr spec. + /// Cancels the operation. + /// A representing the result of the asynchronous operation. + public virtual async Task RegisterReminderAsync(string actorType, string actorId, string reminderName, string data, + CancellationToken cancellationToken = default) + { + await _testDaprInteractor.RegisterReminderAsync(actorType, actorId, reminderName, data); + } - /// - /// Invokes an Actor method on Dapr without remoting. - /// - /// Type of actor. - /// ActorId. - /// Method name to invoke. - /// Serialized body. - /// Cancels the operation. - /// A task that represents the asynchronous operation. - public Task InvokeActorMethodWithoutRemotingAsync(string actorType, string actorId, string methodName, - string jsonPayload, CancellationToken cancellationToken = default) - { - throw new System.NotImplementedException(); - } + /// + /// Invokes an Actor method on Dapr without remoting. + /// + /// Type of actor. + /// ActorId. + /// Method name to invoke. + /// Serialized body. + /// Cancels the operation. + /// A task that represents the asynchronous operation. + public Task InvokeActorMethodWithoutRemotingAsync(string actorType, string actorId, string methodName, + string jsonPayload, CancellationToken cancellationToken = default) + { + throw new System.NotImplementedException(); + } - /// - /// Saves state batch to Dapr. - /// - /// Type of actor. - /// ActorId. - /// JSON data with state changes as per the Dapr spec for transaction state update. - /// Cancels the operation. - /// A task that represents the asynchronous operation. - public virtual async Task SaveStateTransactionallyAsync(string actorType, string actorId, string data, - CancellationToken cancellationToken = default) - { - await _testDaprInteractor.SaveStateTransactionallyAsync(actorType, actorId, data); - } + /// + /// Saves state batch to Dapr. + /// + /// Type of actor. + /// ActorId. + /// JSON data with state changes as per the Dapr spec for transaction state update. + /// Cancels the operation. + /// A task that represents the asynchronous operation. + public virtual async Task SaveStateTransactionallyAsync(string actorType, string actorId, string data, + CancellationToken cancellationToken = default) + { + await _testDaprInteractor.SaveStateTransactionallyAsync(actorType, actorId, data); + } - /// - /// Saves a state to Dapr. - /// - /// Type of actor. - /// ActorId. - /// Name of key to get value for. - /// Cancels the operation. - /// A task that represents the asynchronous operation. - public virtual async Task> GetStateAsync(string actorType, string actorId, string keyName, CancellationToken cancellationToken = default) - { - return await _testDaprInteractor.GetStateAsync(actorType, actorId, keyName); - } + /// + /// Saves a state to Dapr. + /// + /// Type of actor. + /// ActorId. + /// Name of key to get value for. + /// Cancels the operation. + /// A task that represents the asynchronous operation. + public virtual async Task> GetStateAsync(string actorType, string actorId, string keyName, CancellationToken cancellationToken = default) + { + return await _testDaprInteractor.GetStateAsync(actorType, actorId, keyName); + } - /// - /// Invokes Actor method. - /// - /// Serializers manager for remoting calls. - /// Actor Request Message. - /// Cancels the operation. - /// A representing the result of the asynchronous operation. - Task IDaprInteractor.InvokeActorMethodWithRemotingAsync(ActorMessageSerializersManager serializersManager, - IActorRequestMessage remotingRequestRequestMessage, CancellationToken cancellationToken) - { - throw new System.NotImplementedException(); - } + /// + /// Invokes Actor method. + /// + /// Serializers manager for remoting calls. + /// Actor Request Message. + /// Cancels the operation. + /// A representing the result of the asynchronous operation. + Task IDaprInteractor.InvokeActorMethodWithRemotingAsync(ActorMessageSerializersManager serializersManager, + IActorRequestMessage remotingRequestRequestMessage, CancellationToken cancellationToken) + { + throw new System.NotImplementedException(); + } - /// - /// Gets a reminder. - /// - /// Type of actor. - /// ActorId. - /// Name of reminder to unregister. - /// Cancels the operation. - /// A representing the result of the asynchronous operation. - public Task GetReminderAsync(string actorType, string actorId, string reminderName, - CancellationToken cancellationToken = default) - { - throw new System.NotImplementedException(); - } + /// + /// Gets a reminder. + /// + /// Type of actor. + /// ActorId. + /// Name of reminder to unregister. + /// Cancels the operation. + /// A representing the result of the asynchronous operation. + public Task GetReminderAsync(string actorType, string actorId, string reminderName, + CancellationToken cancellationToken = default) + { + throw new System.NotImplementedException(); + } - /// - /// Unregisters a reminder. - /// - /// Type of actor. - /// ActorId. - /// Name of reminder to unregister. - /// Cancels the operation. - /// A representing the result of the asynchronous operation. - public Task UnregisterReminderAsync(string actorType, string actorId, string reminderName, - CancellationToken cancellationToken = default) - { - throw new System.NotImplementedException(); - } + /// + /// Unregisters a reminder. + /// + /// Type of actor. + /// ActorId. + /// Name of reminder to unregister. + /// Cancels the operation. + /// A representing the result of the asynchronous operation. + public Task UnregisterReminderAsync(string actorType, string actorId, string reminderName, + CancellationToken cancellationToken = default) + { + throw new System.NotImplementedException(); + } - /// - /// Registers a timer. - /// - /// Type of actor. - /// ActorId. - /// Name of timer to register. - /// JSON reminder data as per the Dapr spec. - /// Cancels the operation. - /// A representing the result of the asynchronous operation. - public Task RegisterTimerAsync(string actorType, string actorId, string timerName, string data, - CancellationToken cancellationToken = default) - { - throw new System.NotImplementedException(); - } + /// + /// Registers a timer. + /// + /// Type of actor. + /// ActorId. + /// Name of timer to register. + /// JSON reminder data as per the Dapr spec. + /// Cancels the operation. + /// A representing the result of the asynchronous operation. + public Task RegisterTimerAsync(string actorType, string actorId, string timerName, string data, + CancellationToken cancellationToken = default) + { + throw new System.NotImplementedException(); + } - /// - /// Unregisters a timer. - /// - /// Type of actor. - /// ActorId. - /// Name of timer to register. - /// Cancels the operation. - /// A representing the result of the asynchronous operation. - public Task UnregisterTimerAsync(string actorType, string actorId, string timerName, - CancellationToken cancellationToken = default) - { - throw new System.NotImplementedException(); - } + /// + /// Unregisters a timer. + /// + /// Type of actor. + /// ActorId. + /// Name of timer to register. + /// Cancels the operation. + /// A representing the result of the asynchronous operation. + public Task UnregisterTimerAsync(string actorType, string actorId, string timerName, + CancellationToken cancellationToken = default) + { + throw new System.NotImplementedException(); } } diff --git a/test/Dapr.AspNetCore.IntegrationTest/AuthenticationTest.cs b/test/Dapr.AspNetCore.IntegrationTest/AuthenticationTest.cs index 2712779e7..3684e709c 100644 --- a/test/Dapr.AspNetCore.IntegrationTest/AuthenticationTest.cs +++ b/test/Dapr.AspNetCore.IntegrationTest/AuthenticationTest.cs @@ -16,7 +16,7 @@ using System.Text; using System.Threading.Tasks; using Dapr.AspNetCore.IntegrationTest.App; -using FluentAssertions; +using Shouldly; using Newtonsoft.Json; using Xunit; @@ -43,7 +43,7 @@ public async Task ValidToken_ShouldBeAuthenticatedAndAuthorized() response.EnsureSuccessStatusCode(); var responseContent = await response.Content.ReadAsStringAsync(); var responseUserInfo = JsonConvert.DeserializeObject(responseContent); - responseUserInfo.Name.Should().Be(userInfo.Name); + responseUserInfo.Name.ShouldBe(userInfo.Name); } } @@ -64,7 +64,7 @@ public async Task InvalidToken_ShouldBeUnauthorized() request.Headers.Add("Dapr-Api-Token", "asdfgh"); var response = await httpClient.SendAsync(request); - response.StatusCode.Should().Be(HttpStatusCode.Unauthorized); + response.StatusCode.ShouldBe(HttpStatusCode.Unauthorized); } } } diff --git a/test/Dapr.AspNetCore.IntegrationTest/CloudEventsIntegrationTest.cs b/test/Dapr.AspNetCore.IntegrationTest/CloudEventsIntegrationTest.cs index 9b0b5d3a3..928286fb6 100644 --- a/test/Dapr.AspNetCore.IntegrationTest/CloudEventsIntegrationTest.cs +++ b/test/Dapr.AspNetCore.IntegrationTest/CloudEventsIntegrationTest.cs @@ -19,7 +19,7 @@ namespace Dapr.AspNetCore.IntegrationTest using System.Text.Json; using System.Threading.Tasks; using Dapr.AspNetCore.IntegrationTest.App; - using FluentAssertions; + using Shouldly; using Xunit; public class CloudEventsIntegrationTest @@ -48,6 +48,7 @@ public async Task CanSendEmptyStructuredCloudEvent() } } + [Fact] public async Task CanSendStructuredCloudEvent() { @@ -74,7 +75,7 @@ public async Task CanSendStructuredCloudEvent() response.EnsureSuccessStatusCode(); var userInfo = await JsonSerializer.DeserializeAsync(await response.Content.ReadAsStreamAsync(), this.options); - userInfo.Name.Should().Be("jimmy"); + userInfo.Name.ShouldBe("jimmy"); } } @@ -105,7 +106,7 @@ public async Task CanSendStructuredCloudEvent_WithContentType() response.EnsureSuccessStatusCode(); var userInfo = await JsonSerializer.DeserializeAsync(await response.Content.ReadAsStreamAsync(), this.options); - userInfo.Name.Should().Be("jimmy"); + userInfo.Name.ShouldBe("jimmy"); } } @@ -133,7 +134,7 @@ public async Task CanSendStructuredCloudEvent_WithNonJsonContentType() response.EnsureSuccessStatusCode(); var user = await response.Content.ReadAsStringAsync(); - user.Should().Be("jimmy \"the cool guy\" smith"); + user.ShouldBe("jimmy \"the cool guy\" smith"); } } @@ -163,7 +164,7 @@ public async Task CanSendBinaryCloudEvent_WithContentType() response.EnsureSuccessStatusCode(); var userInfo = await JsonSerializer.DeserializeAsync(await response.Content.ReadAsStreamAsync(), this.options); - userInfo.Name.Should().Be("jimmy"); + userInfo.Name.ShouldBe("jimmy"); } } } diff --git a/test/Dapr.AspNetCore.IntegrationTest/ControllerIntegrationTest.cs b/test/Dapr.AspNetCore.IntegrationTest/ControllerIntegrationTest.cs index 7735ec4fb..d3eb87cd6 100644 --- a/test/Dapr.AspNetCore.IntegrationTest/ControllerIntegrationTest.cs +++ b/test/Dapr.AspNetCore.IntegrationTest/ControllerIntegrationTest.cs @@ -16,7 +16,7 @@ namespace Dapr.AspNetCore.IntegrationTest using System.Net.Http; using System.Threading.Tasks; using Dapr.AspNetCore.IntegrationTest.App; - using FluentAssertions; + using Shouldly; using Newtonsoft.Json; using Xunit; @@ -37,7 +37,7 @@ public async Task ModelBinder_CanBindFromState() response.EnsureSuccessStatusCode(); var widget = await daprClient.GetStateAsync("testStore", "test"); - widget.Count.Should().Be(18); + widget.Count.ShouldBe(18); } } @@ -56,8 +56,8 @@ public async Task ModelBinder_GetFromStateEntryWithKeyPresentInStateStore_Return response.EnsureSuccessStatusCode(); var responseContent = await response.Content.ReadAsStringAsync(); var responseWidget = JsonConvert.DeserializeObject(responseContent); - responseWidget.Size.Should().Be(widget.Size); - responseWidget.Count.Should().Be(widget.Count); + responseWidget.Size.ShouldBe(widget.Size); + responseWidget.Count.ShouldBe(widget.Count); } } @@ -92,7 +92,7 @@ public async Task ModelBinder_CanBindFromState_WithStateEntry() response.EnsureSuccessStatusCode(); var widget = await daprClient.GetStateAsync("testStore", "test"); - widget.Count.Should().Be(18); + widget.Count.ShouldBe(18); } } @@ -111,7 +111,7 @@ public async Task ModelBinder_CanBindFromState_WithStateEntryAndCustomKey() response.EnsureSuccessStatusCode(); var widget = await daprClient.GetStateAsync("testStore", "test"); - widget.Count.Should().Be(18); + widget.Count.ShouldBe(18); } } @@ -130,8 +130,8 @@ public async Task ModelBinder_GetFromStateEntryWithStateEntry_WithKeyPresentInSt response.EnsureSuccessStatusCode(); var responseContent = await response.Content.ReadAsStringAsync(); var responseWidget = JsonConvert.DeserializeObject(responseContent); - responseWidget.Size.Should().Be(widget.Size); - responseWidget.Count.Should().Be(widget.Count); + responseWidget.Size.ShouldBe(widget.Size); + responseWidget.Count.ShouldBe(widget.Count); } } diff --git a/test/Dapr.AspNetCore.IntegrationTest/Dapr.AspNetCore.IntegrationTest.csproj b/test/Dapr.AspNetCore.IntegrationTest/Dapr.AspNetCore.IntegrationTest.csproj index d7dd6d52a..5772612b4 100644 --- a/test/Dapr.AspNetCore.IntegrationTest/Dapr.AspNetCore.IntegrationTest.csproj +++ b/test/Dapr.AspNetCore.IntegrationTest/Dapr.AspNetCore.IntegrationTest.csproj @@ -5,7 +5,7 @@ runtime; build; native; contentfiles; analyzers; buildtransitive all - + diff --git a/test/Dapr.AspNetCore.IntegrationTest/RoutingIntegrationTest.cs b/test/Dapr.AspNetCore.IntegrationTest/RoutingIntegrationTest.cs index c3129df9d..89130c3bd 100644 --- a/test/Dapr.AspNetCore.IntegrationTest/RoutingIntegrationTest.cs +++ b/test/Dapr.AspNetCore.IntegrationTest/RoutingIntegrationTest.cs @@ -16,7 +16,7 @@ namespace Dapr.AspNetCore.IntegrationTest using System.Net.Http; using System.Threading.Tasks; using Dapr.AspNetCore.IntegrationTest.App; - using FluentAssertions; + using Shouldly; using Xunit; public class RoutingIntegrationTest @@ -36,7 +36,7 @@ public async Task StateClient_CanBindFromState() response.EnsureSuccessStatusCode(); var widget = await daprClient.GetStateAsync("testStore", "test"); - widget.Count.Should().Be(18); + widget.Count.ShouldBe(18); } } } diff --git a/test/Dapr.AspNetCore.IntegrationTest/SubscribeEndpointTest.cs b/test/Dapr.AspNetCore.IntegrationTest/SubscribeEndpointTest.cs index 4cd0d4f1e..7354f6aa6 100644 --- a/test/Dapr.AspNetCore.IntegrationTest/SubscribeEndpointTest.cs +++ b/test/Dapr.AspNetCore.IntegrationTest/SubscribeEndpointTest.cs @@ -19,7 +19,7 @@ namespace Dapr.AspNetCore.IntegrationTest using System.Net.Http; using System.Text.Json; using System.Threading.Tasks; - using FluentAssertions; + using Shouldly; using Xunit; public class SubscribeEndpointTest @@ -39,8 +39,8 @@ public async Task SubscribeEndpoint_ReportsTopics() { var json = await JsonSerializer.DeserializeAsync(stream); - json.ValueKind.Should().Be(JsonValueKind.Array); - json.GetArrayLength().Should().Be(18); + json.ValueKind.ShouldBe(JsonValueKind.Array); + json.GetArrayLength().ShouldBe(18); var subscriptions = new List<(string PubsubName, string Topic, string Route, string rawPayload, string match, string metadata, string DeadLetterTopic, string bulkSubscribeMetadata)>(); @@ -109,34 +109,34 @@ public async Task SubscribeEndpoint_ReportsTopics() } } - subscriptions.Should().Contain(("testpubsub", "A", "topic-a", string.Empty, string.Empty, string.Empty, string.Empty, String.Empty)); - subscriptions.Should().Contain(("testpubsub", "A.1", "topic-a", string.Empty, string.Empty, string.Empty, string.Empty, String.Empty)); - subscriptions.Should().Contain(("pubsub", "B", "B", string.Empty, string.Empty, string.Empty, string.Empty, String.Empty)); - subscriptions.Should().Contain(("custom-pubsub", "custom-C", "C", string.Empty, string.Empty, string.Empty, string.Empty, String.Empty)); - subscriptions.Should().Contain(("pubsub", "register-user", "register-user", string.Empty, string.Empty, string.Empty, string.Empty, String.Empty)); - subscriptions.Should().Contain(("pubsub", "register-user-plaintext", "register-user-plaintext", string.Empty, string.Empty, string.Empty, string.Empty, String.Empty)); - subscriptions.Should().Contain(("pubsub", "D", "D", "true", string.Empty, string.Empty, string.Empty, String.Empty)); - subscriptions.Should().Contain(("pubsub", "E", "E", string.Empty, string.Empty, string.Empty, string.Empty, String.Empty)); - subscriptions.Should().Contain(("pubsub", "E", "E-Critical", string.Empty, "event.type == \"critical\"", string.Empty, string.Empty, String.Empty)); - subscriptions.Should().Contain(("pubsub", "E", "E-Important", string.Empty, "event.type == \"important\"", string.Empty, string.Empty, String.Empty)); - subscriptions.Should().Contain(("pubsub", "F", "multiTopicAttr", string.Empty, string.Empty, string.Empty, string.Empty, + subscriptions.ShouldContain(("testpubsub", "A", "topic-a", string.Empty, string.Empty, string.Empty, string.Empty, String.Empty)); + subscriptions.ShouldContain(("testpubsub", "A.1", "topic-a", string.Empty, string.Empty, string.Empty, string.Empty, String.Empty)); + subscriptions.ShouldContain(("pubsub", "B", "B", string.Empty, string.Empty, string.Empty, string.Empty, String.Empty)); + subscriptions.ShouldContain(("custom-pubsub", "custom-C", "C", string.Empty, string.Empty, string.Empty, string.Empty, String.Empty)); + subscriptions.ShouldContain(("pubsub", "register-user", "register-user", string.Empty, string.Empty, string.Empty, string.Empty, String.Empty)); + subscriptions.ShouldContain(("pubsub", "register-user-plaintext", "register-user-plaintext", string.Empty, string.Empty, string.Empty, string.Empty, String.Empty)); + subscriptions.ShouldContain(("pubsub", "D", "D", "true", string.Empty, string.Empty, string.Empty, String.Empty)); + subscriptions.ShouldContain(("pubsub", "E", "E", string.Empty, string.Empty, string.Empty, string.Empty, String.Empty)); + subscriptions.ShouldContain(("pubsub", "E", "E-Critical", string.Empty, "event.type == \"critical\"", string.Empty, string.Empty, String.Empty)); + subscriptions.ShouldContain(("pubsub", "E", "E-Important", string.Empty, "event.type == \"important\"", string.Empty, string.Empty, String.Empty)); + subscriptions.ShouldContain(("pubsub", "F", "multiTopicAttr", string.Empty, string.Empty, string.Empty, string.Empty, "{\"enabled\":true,\"maxMessagesCount\":100,\"maxAwaitDurationMs\":1000}")); - subscriptions.Should().Contain(("pubsub", "F.1", "multiTopicAttr", "true", string.Empty, string.Empty, string.Empty, String.Empty)); - subscriptions.Should().Contain(("pubsub", "G", "G", string.Empty, string.Empty, string.Empty, "deadLetterTopicName", + subscriptions.ShouldContain(("pubsub", "F.1", "multiTopicAttr", "true", string.Empty, string.Empty, string.Empty, String.Empty)); + subscriptions.ShouldContain(("pubsub", "G", "G", string.Empty, string.Empty, string.Empty, "deadLetterTopicName", "{\"enabled\":true,\"maxMessagesCount\":300,\"maxAwaitDurationMs\":1000}")); - subscriptions.Should().Contain(("pubsub", "splitTopicBuilder", "splitTopics", string.Empty, string.Empty, string.Empty, string.Empty, String.Empty)); - subscriptions.Should().Contain(("pubsub", "splitTopicAttr", "splitTopics", "true", string.Empty, string.Empty, string.Empty, String.Empty)); - subscriptions.Should().Contain(("pubsub", "metadata", "multiMetadataTopicAttr", string.Empty, string.Empty, "n1=v1;n2=v2,v3", string.Empty, String.Empty)); - subscriptions.Should().Contain(("pubsub", "metadata.1", "multiMetadataTopicAttr", "true", string.Empty, "n1=v1", string.Empty, + subscriptions.ShouldContain(("pubsub", "splitTopicBuilder", "splitTopics", string.Empty, string.Empty, string.Empty, string.Empty, String.Empty)); + subscriptions.ShouldContain(("pubsub", "splitTopicAttr", "splitTopics", "true", string.Empty, string.Empty, string.Empty, String.Empty)); + subscriptions.ShouldContain(("pubsub", "metadata", "multiMetadataTopicAttr", string.Empty, string.Empty, "n1=v1;n2=v2,v3", string.Empty, String.Empty)); + subscriptions.ShouldContain(("pubsub", "metadata.1", "multiMetadataTopicAttr", "true", string.Empty, "n1=v1", string.Empty, "{\"enabled\":true,\"maxMessagesCount\":500,\"maxAwaitDurationMs\":2000}")); - subscriptions.Should().Contain(("pubsub", "splitMetadataTopicBuilder", "splitMetadataTopics", string.Empty, string.Empty, "n1=v1;n2=v1", string.Empty, String.Empty)); - subscriptions.Should().Contain(("pubsub", "metadataseparatorbyemptytring", "topicmetadataseparatorattrbyemptytring", string.Empty, string.Empty, "n1=v1,", string.Empty, String.Empty)); + subscriptions.ShouldContain(("pubsub", "splitMetadataTopicBuilder", "splitMetadataTopics", string.Empty, string.Empty, "n1=v1;n2=v1", string.Empty, String.Empty)); + subscriptions.ShouldContain(("pubsub", "metadataseparatorbyemptytring", "topicmetadataseparatorattrbyemptytring", string.Empty, string.Empty, "n1=v1,", string.Empty, String.Empty)); // Test priority route sorting var eTopic = subscriptions.FindAll(e => e.Topic == "E"); - eTopic.Count.Should().Be(3); - eTopic[0].Route.Should().Be("E-Critical"); - eTopic[1].Route.Should().Be("E-Important"); - eTopic[2].Route.Should().Be("E"); + eTopic.Count.ShouldBe(3); + eTopic[0].Route.ShouldBe("E-Critical"); + eTopic[1].Route.ShouldBe("E-Important"); + eTopic[2].Route.ShouldBe("E"); } } } diff --git a/test/Dapr.AspNetCore.Test/CloudEventsMiddlewareTest.cs b/test/Dapr.AspNetCore.Test/CloudEventsMiddlewareTest.cs index 2f9fab936..ae8db689b 100644 --- a/test/Dapr.AspNetCore.Test/CloudEventsMiddlewareTest.cs +++ b/test/Dapr.AspNetCore.Test/CloudEventsMiddlewareTest.cs @@ -20,7 +20,7 @@ namespace Dapr.AspNetCore.Test using System.Text; using System.Text.Json; using System.Threading.Tasks; - using FluentAssertions; + using Shouldly; using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Http; using Xunit; @@ -44,8 +44,8 @@ public async Task InvokeAsync_IgnoresOtherContentTypes(string contentType) // Do verification in the scope of the middleware app.Run(httpContext => { - httpContext.Request.ContentType.Should().Be(contentType); - ReadBody(httpContext.Request.Body).Should().Be("Hello, world!"); + httpContext.Request.ContentType.ShouldBe(contentType); + ReadBody(httpContext.Request.Body).ShouldBe("Hello, world!"); return Task.CompletedTask; }); @@ -77,8 +77,8 @@ public async Task InvokeAsync_ReplacesBodyJson(string dataContentType, string ch // Do verification in the scope of the middleware app.Run(httpContext => { - httpContext.Request.ContentType.Should().Be(dataContentType ?? "application/json"); - ReadBody(httpContext.Request.Body).Should().Be("{\"name\":\"jimmy\"}"); + httpContext.Request.ContentType.ShouldBe(dataContentType ?? "application/json"); + ReadBody(httpContext.Request.Body).ShouldBe("{\"name\":\"jimmy\"}"); return Task.CompletedTask; }); @@ -117,8 +117,8 @@ public async Task InvokeAsync_ReplacesPascalCasedBodyJson(string dataContentType // Do verification in the scope of the middleware app.Run(httpContext => { - httpContext.Request.ContentType.Should().Be(dataContentType ?? "application/json"); - ReadBody(httpContext.Request.Body).Should().Be("{\"name\":\"jimmy\"}"); + httpContext.Request.ContentType.ShouldBe(dataContentType ?? "application/json"); + ReadBody(httpContext.Request.Body).ShouldBe("{\"name\":\"jimmy\"}"); return Task.CompletedTask; }); @@ -160,11 +160,13 @@ public async Task InvokeAsync_ForwardsJsonPropertiesAsHeaders(string dataContent // Do verification in the scope of the middleware app.Run(httpContext => { - httpContext.Request.ContentType.Should().Be(dataContentType ?? "application/json"); - ReadBody(httpContext.Request.Body).Should().Be("{\"name\":\"jimmy\"}"); + httpContext.Request.ContentType.ShouldBe(dataContentType ?? "application/json"); + ReadBody(httpContext.Request.Body).ShouldBe("{\"name\":\"jimmy\"}"); - httpContext.Request.Headers.Should().ContainKey("Cloudevent.type").WhichValue.Should().BeEquivalentTo("Test.Type"); - httpContext.Request.Headers.Should().ContainKey("Cloudevent.subject").WhichValue.Should().BeEquivalentTo("Test.Subject"); + httpContext.Request.Headers.ShouldContainKey("Cloudevent.type"); + httpContext.Request.Headers["Cloudevent.type"].ToString().ShouldBe("Test.Type"); + httpContext.Request.Headers.ShouldContainKey("Cloudevent.subject"); + httpContext.Request.Headers["Cloudevent.subject"].ToString().ShouldBe("Test.Subject"); return Task.CompletedTask; }); @@ -207,11 +209,12 @@ public async Task InvokeAsync_ForwardsIncludedJsonPropertiesAsHeaders(string dat // Do verification in the scope of the middleware app.Run(httpContext => { - httpContext.Request.ContentType.Should().Be(dataContentType ?? "application/json"); - ReadBody(httpContext.Request.Body).Should().Be("{\"name\":\"jimmy\"}"); + httpContext.Request.ContentType.ShouldBe(dataContentType ?? "application/json"); + ReadBody(httpContext.Request.Body).ShouldBe("{\"name\":\"jimmy\"}"); - httpContext.Request.Headers.Should().ContainKey("Cloudevent.type").WhichValue.Should().BeEquivalentTo("Test.Type"); - httpContext.Request.Headers.Should().NotContainKey("Cloudevent.subject"); + httpContext.Request.Headers.ShouldContainKey("Cloudevent.type"); + httpContext.Request.Headers["Cloudevent.type"].ToString().ShouldBe("Test.Type"); + httpContext.Request.Headers.ShouldNotContainKey("Cloudevent.subject"); return Task.CompletedTask; }); @@ -254,11 +257,12 @@ public async Task InvokeAsync_DoesNotForwardExcludedJsonPropertiesAsHeaders(stri // Do verification in the scope of the middleware app.Run(httpContext => { - httpContext.Request.ContentType.Should().Be(dataContentType ?? "application/json"); - ReadBody(httpContext.Request.Body).Should().Be("{\"name\":\"jimmy\"}"); + httpContext.Request.ContentType.ShouldBe(dataContentType ?? "application/json"); + ReadBody(httpContext.Request.Body).ShouldBe("{\"name\":\"jimmy\"}"); - httpContext.Request.Headers.Should().NotContainKey("Cloudevent.type"); - httpContext.Request.Headers.Should().ContainKey("Cloudevent.subject").WhichValue.Should().BeEquivalentTo("Test.Subject"); + httpContext.Request.Headers.ShouldNotContainKey("Cloudevent.type"); + httpContext.Request.Headers.ShouldContainKey("Cloudevent.subject"); + httpContext.Request.Headers["Cloudevent.subject"].ToString().ShouldBe("Test.Subject"); return Task.CompletedTask; }); @@ -297,8 +301,8 @@ public async Task InvokeAsync_ReplacesBodyNonJsonData() // Do verification in the scope of the middleware app.Run(httpContext => { - httpContext.Request.ContentType.Should().Be("text/plain"); - ReadBody(httpContext.Request.Body).Should().Be(expected); + httpContext.Request.ContentType.ShouldBe("text/plain"); + ReadBody(httpContext.Request.Body).ShouldBe(expected); return Task.CompletedTask; }); @@ -331,8 +335,8 @@ public async Task InvokeAsync_ReplacesBodyNonJsonData_ExceptWhenSuppressed() // Do verification in the scope of the middleware app.Run(httpContext => { - httpContext.Request.ContentType.Should().Be("text/plain"); - ReadBody(httpContext.Request.Body).Should().Be(expected); + httpContext.Request.ContentType.ShouldBe("text/plain"); + ReadBody(httpContext.Request.Body).ShouldBe(expected); return Task.CompletedTask; }); @@ -366,8 +370,8 @@ public async Task InvokeAsync_ReplacesBodyJson_NormalizesPayloadCharset() // Do verification in the scope of the middleware app.Run(httpContext => { - httpContext.Request.ContentType.Should().Be("application/person+json"); - ReadBody(httpContext.Request.Body).Should().Be("{\"name\":\"jimmy\"}"); + httpContext.Request.ContentType.ShouldBe("application/person+json"); + ReadBody(httpContext.Request.Body).ShouldBe("{\"name\":\"jimmy\"}"); return Task.CompletedTask; }); @@ -396,14 +400,14 @@ public async Task InvokeAsync_ReadsBinaryData() // Do verification in the scope of the middleware app.Run(httpContext => { - httpContext.Request.ContentType.Should().Be(dataContentType); + httpContext.Request.ContentType.ShouldBe(dataContentType); var bytes = new byte[httpContext.Request.Body.Length]; #if NET9_0 httpContext.Request.Body.ReadExactly(bytes, 0, bytes.Length); #else httpContext.Request.Body.Read(bytes, 0, bytes.Length); #endif - bytes.Should().Equal(data); + bytes.ShouldBe(data); return Task.CompletedTask; }); @@ -432,9 +436,9 @@ public async Task InvokeAsync_DataAndData64Set_ReturnsBadRequest() // Do verification in the scope of the middleware app.Run(httpContext => { - httpContext.Request.ContentType.Should().Be("application/json"); + httpContext.Request.ContentType.ShouldBe("application/json"); var body = ReadBody(httpContext.Request.Body); - body.Should().Equals(data); + body.ShouldBe(data); return Task.CompletedTask; }); @@ -447,7 +451,7 @@ public async Task InvokeAsync_DataAndData64Set_ReturnsBadRequest() MakeBody($"{{ \"datacontenttype\": \"{dataContentType}\", \"data_base64\": \"{base64Str}\", \"data\": {data} }}"); await pipeline.Invoke(context); - context.Response.StatusCode.Should().Be((int)HttpStatusCode.BadRequest); + context.Response.StatusCode.ShouldBe((int)HttpStatusCode.BadRequest); } private static Stream MakeBody(string text, Encoding encoding = null) diff --git a/test/Dapr.AspNetCore.Test/Dapr.AspNetCore.Test.csproj b/test/Dapr.AspNetCore.Test/Dapr.AspNetCore.Test.csproj index 9135e63d4..b25fcec6e 100644 --- a/test/Dapr.AspNetCore.Test/Dapr.AspNetCore.Test.csproj +++ b/test/Dapr.AspNetCore.Test/Dapr.AspNetCore.Test.csproj @@ -5,8 +5,8 @@ runtime; build; native; contentfiles; analyzers; buildtransitive all - + all diff --git a/test/Dapr.AspNetCore.Test/StateEntryApplicationModelProviderTest.cs b/test/Dapr.AspNetCore.Test/StateEntryApplicationModelProviderTest.cs index 06572caa5..243b60bb6 100644 --- a/test/Dapr.AspNetCore.Test/StateEntryApplicationModelProviderTest.cs +++ b/test/Dapr.AspNetCore.Test/StateEntryApplicationModelProviderTest.cs @@ -18,7 +18,7 @@ namespace Dapr.AspNetCore.Test using System.Linq; using System.Reflection; using Dapr.AspNetCore.Resources; - using FluentAssertions; + using Shouldly; using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Mvc.ApplicationModels; using Microsoft.AspNetCore.Mvc.ModelBinding; @@ -34,9 +34,7 @@ public void OnProvidersExecuted_NullActionsBindingSource() Action action = () => provider.OnProvidersExecuted(context); - action - .Should() - .NotThrow(); + action.ShouldNotThrow(); } [Fact] @@ -48,8 +46,7 @@ public void OnProvidersExecuted_StateEntryParameterThrows() Action action = () => provider.OnProvidersExecuted(context); action - .Should() - .Throw(SR.ErrorStateStoreNameNotProvidedForStateEntry); + .ShouldThrow(SR.ErrorStateStoreNameNotProvidedForStateEntry); } private ApplicationModelProviderContext CreateContext(string methodName) diff --git a/test/Dapr.AspNetCore.Test/StateEntryModelBinderTest.cs b/test/Dapr.AspNetCore.Test/StateEntryModelBinderTest.cs index e2d774397..8cdcd32dd 100644 --- a/test/Dapr.AspNetCore.Test/StateEntryModelBinderTest.cs +++ b/test/Dapr.AspNetCore.Test/StateEntryModelBinderTest.cs @@ -18,7 +18,7 @@ namespace Dapr.AspNetCore.Test using System.Threading.Tasks; using Dapr.Client; using Dapr.Client.Autogen.Grpc.v1; - using FluentAssertions; + using Shouldly; using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Mvc.ModelBinding; @@ -38,9 +38,9 @@ public async Task BindAsync_WithoutMatchingRouteValue_ReportsError() await binder.BindModelAsync(context); - context.Result.IsModelSet.Should().BeFalse(); - context.ModelState.ErrorCount.Should().Be(1); - context.ModelState["testParameter"].Errors.Count.Should().Be(1); + context.Result.IsModelSet.ShouldBeFalse(); + context.ModelState.ErrorCount.ShouldBe(1); + context.ModelState["testParameter"].Errors.Count.ShouldBe(1); // No request to state store, validated by disposing client } @@ -66,12 +66,12 @@ public async Task BindAsync_CanBindValue() await SendResponseWithState(state, request); // Get response and validate - context.Result.IsModelSet.Should().BeTrue(); - context.Result.Model.As().Size.Should().Be("small"); - context.Result.Model.As().Color.Should().Be("yellow"); + context.Result.IsModelSet.ShouldBeTrue(); + ((Widget)context.Result.Model).Size.ShouldBe("small"); + ((Widget)context.Result.Model).Color.ShouldBe("yellow"); - context.ValidationState.Count.Should().Be(1); - context.ValidationState[context.Result.Model].SuppressValidation.Should().BeTrue(); + context.ValidationState.Count.ShouldBe(1); + context.ValidationState[context.Result.Model].SuppressValidation.ShouldBeTrue(); } [Fact] @@ -95,13 +95,13 @@ public async Task BindAsync_CanBindStateEntry() await SendResponseWithState(state, request); // Get response and validate - context.Result.IsModelSet.Should().BeTrue(); - context.Result.Model.As>().Key.Should().Be("test"); - context.Result.Model.As>().Value.Size.Should().Be("small"); - context.Result.Model.As>().Value.Color.Should().Be("yellow"); + context.Result.IsModelSet.ShouldBeTrue(); + ((StateEntry)context.Result.Model).Key.ShouldBe("test"); + ((StateEntry)context.Result.Model).Value.Size.ShouldBe("small"); + ((StateEntry)context.Result.Model).Value.Color.ShouldBe("yellow"); - context.ValidationState.Count.Should().Be(1); - context.ValidationState[context.Result.Model].SuppressValidation.Should().BeTrue(); + context.ValidationState.Count.ShouldBe(1); + context.ValidationState[context.Result.Model].SuppressValidation.ShouldBeTrue(); } [Fact] @@ -122,9 +122,9 @@ public async Task BindAsync_ReturnsNullForNonExistentStateEntry() await SendResponseWithState(null, request); - context.ModelState.IsValid.Should().BeTrue(); - context.Result.IsModelSet.Should().BeFalse(); - context.Result.Should().Be(ModelBindingResult.Failed()); + context.ModelState.IsValid.ShouldBeTrue(); + context.Result.IsModelSet.ShouldBeFalse(); + context.Result.ShouldBe(ModelBindingResult.Failed()); } [Fact] @@ -145,9 +145,9 @@ public async Task BindAsync_WithStateEntry_ForNonExistentStateEntry() await SendResponseWithState(null, request); - context.ModelState.IsValid.Should().BeTrue(); - context.Result.IsModelSet.Should().BeTrue(); - ((StateEntry)context.Result.Model).Value.Should().BeNull(); + context.ModelState.IsValid.ShouldBeTrue(); + context.Result.IsModelSet.ShouldBeTrue(); + ((StateEntry)context.Result.Model).Value.ShouldBeNull(); } private static ModelBindingContext CreateContext(IServiceProvider services) diff --git a/test/Dapr.Client.Test/BulkPublishEventApiTest.cs b/test/Dapr.Client.Test/BulkPublishEventApiTest.cs index 74d617a20..14b946d66 100644 --- a/test/Dapr.Client.Test/BulkPublishEventApiTest.cs +++ b/test/Dapr.Client.Test/BulkPublishEventApiTest.cs @@ -19,7 +19,7 @@ namespace Dapr.Client.Test using System.Threading; using System.Threading.Tasks; using Autogenerated = Dapr.Client.Autogen.Grpc.v1; - using FluentAssertions; + using Shouldly; using Grpc.Core; using Moq; using Xunit; @@ -43,26 +43,24 @@ public async Task BulkPublishEventAsync_CanPublishTopicWithEvents() var envelope = await request.GetRequestEnvelopeAsync(); - envelope.Entries.Count.Should().Be(2); - envelope.PubsubName.Should().Be(TestPubsubName); - envelope.Topic.Should().Be(TestTopicName); - envelope.Metadata.Count.Should().Be(0); + envelope.Entries.Count.ShouldBe(2); + envelope.PubsubName.ShouldBe(TestPubsubName); + envelope.Topic.ShouldBe(TestTopicName); + envelope.Metadata.Count.ShouldBe(0); var firstEntry = envelope.Entries[0]; - firstEntry.EntryId.Should().Be("0"); - firstEntry.ContentType.Should().Be(TestContentType); - firstEntry.Event.ToStringUtf8().Should() - .Be(JsonSerializer.Serialize(bulkPublishData[0], client.InnerClient.JsonSerializerOptions)); - firstEntry.Metadata.Should().BeEmpty(); + firstEntry.EntryId.ShouldBe("0"); + firstEntry.ContentType.ShouldBe(TestContentType); + firstEntry.Event.ToStringUtf8().ShouldBe(JsonSerializer.Serialize(bulkPublishData[0], client.InnerClient.JsonSerializerOptions)); + firstEntry.Metadata.ShouldBeEmpty(); var secondEntry = envelope.Entries[1]; - secondEntry.EntryId.Should().Be("1"); - secondEntry.ContentType.Should().Be(TestContentType); - secondEntry.Event.ToStringUtf8().Should() - .Be(JsonSerializer.Serialize(bulkPublishData[1], client.InnerClient.JsonSerializerOptions)); - secondEntry.Metadata.Should().BeEmpty(); + secondEntry.EntryId.ShouldBe("1"); + secondEntry.ContentType.ShouldBe(TestContentType); + secondEntry.Event.ToStringUtf8().ShouldBe(JsonSerializer.Serialize(bulkPublishData[1], client.InnerClient.JsonSerializerOptions)); + secondEntry.Metadata.ShouldBeEmpty(); // Create Response & Respond var response = new Autogenerated.BulkPublishResponse @@ -72,7 +70,7 @@ public async Task BulkPublishEventAsync_CanPublishTopicWithEvents() var bulkPublishResponse = await request.CompleteWithMessageAsync(response); // Get response and validate - bulkPublishResponse.FailedEntries.Count.Should().Be(0); + bulkPublishResponse.FailedEntries.Count.ShouldBe(0); } [Fact] @@ -90,31 +88,29 @@ await daprClient.BulkPublishEventAsync(TestPubsubName, TestTopicName, bulkPublis var envelope = await request.GetRequestEnvelopeAsync(); - envelope.Entries.Count.Should().Be(2); - envelope.PubsubName.Should().Be(TestPubsubName); - envelope.Topic.Should().Be(TestTopicName); + envelope.Entries.Count.ShouldBe(2); + envelope.PubsubName.ShouldBe(TestPubsubName); + envelope.Topic.ShouldBe(TestTopicName); - envelope.Metadata.Count.Should().Be(2); - envelope.Metadata.Keys.Contains("key1").Should().BeTrue(); - envelope.Metadata.Keys.Contains("key2").Should().BeTrue(); - envelope.Metadata["key1"].Should().Be("value1"); - envelope.Metadata["key2"].Should().Be("value2"); + envelope.Metadata.Count.ShouldBe(2); + envelope.Metadata.Keys.Contains("key1").ShouldBeTrue(); + envelope.Metadata.Keys.Contains("key2").ShouldBeTrue(); + envelope.Metadata["key1"].ShouldBe("value1"); + envelope.Metadata["key2"].ShouldBe("value2"); var firstEntry = envelope.Entries[0]; - firstEntry.EntryId.Should().Be("0"); - firstEntry.ContentType.Should().Be(TestContentType); - firstEntry.Event.ToStringUtf8().Should() - .Be(JsonSerializer.Serialize(bulkPublishData[0], client.InnerClient.JsonSerializerOptions)); - firstEntry.Metadata.Should().BeEmpty(); + firstEntry.EntryId.ShouldBe("0"); + firstEntry.ContentType.ShouldBe(TestContentType); + firstEntry.Event.ToStringUtf8().ShouldBe(JsonSerializer.Serialize(bulkPublishData[0], client.InnerClient.JsonSerializerOptions)); + firstEntry.Metadata.ShouldBeEmpty(); var secondEntry = envelope.Entries[1]; - secondEntry.EntryId.Should().Be("1"); - secondEntry.ContentType.Should().Be(TestContentType); - secondEntry.Event.ToStringUtf8().Should() - .Be(JsonSerializer.Serialize(bulkPublishData[1], client.InnerClient.JsonSerializerOptions)); - secondEntry.Metadata.Should().BeEmpty(); + secondEntry.EntryId.ShouldBe("1"); + secondEntry.ContentType.ShouldBe(TestContentType); + secondEntry.Event.ToStringUtf8().ShouldBe(JsonSerializer.Serialize(bulkPublishData[1], client.InnerClient.JsonSerializerOptions)); + secondEntry.Metadata.ShouldBeEmpty(); // Create Response & Respond var response = new Autogenerated.BulkPublishResponse @@ -124,7 +120,7 @@ await daprClient.BulkPublishEventAsync(TestPubsubName, TestTopicName, bulkPublis var bulkPublishResponse = await request.CompleteWithMessageAsync(response); // Get response and validate - bulkPublishResponse.FailedEntries.Count.Should().Be(0); + bulkPublishResponse.FailedEntries.Count.ShouldBe(0); } [Fact] @@ -139,26 +135,24 @@ await daprClient.BulkPublishEventAsync(TestPubsubName, TestTopicName, bulkPublis request.Dismiss(); var envelope = await request.GetRequestEnvelopeAsync(); - envelope.Entries.Count.Should().Be(2); - envelope.PubsubName.Should().Be(TestPubsubName); - envelope.Topic.Should().Be(TestTopicName); - envelope.Metadata.Count.Should().Be(0); + envelope.Entries.Count.ShouldBe(2); + envelope.PubsubName.ShouldBe(TestPubsubName); + envelope.Topic.ShouldBe(TestTopicName); + envelope.Metadata.Count.ShouldBe(0); var firstEntry = envelope.Entries[0]; - firstEntry.EntryId.Should().Be("0"); - firstEntry.ContentType.Should().Be(TestContentType); - firstEntry.Event.ToStringUtf8().Should() - .Be(JsonSerializer.Serialize(bulkPublishData[0], client.InnerClient.JsonSerializerOptions)); - firstEntry.Metadata.Should().BeEmpty(); + firstEntry.EntryId.ShouldBe("0"); + firstEntry.ContentType.ShouldBe(TestContentType); + firstEntry.Event.ToStringUtf8().ShouldBe(JsonSerializer.Serialize(bulkPublishData[0], client.InnerClient.JsonSerializerOptions)); + firstEntry.Metadata.ShouldBeEmpty(); var secondEntry = envelope.Entries[1]; - secondEntry.EntryId.Should().Be("1"); - secondEntry.ContentType.Should().Be(TestContentType); - secondEntry.Event.ToStringUtf8().Should() - .Be(JsonSerializer.Serialize(bulkPublishData[1], client.InnerClient.JsonSerializerOptions)); - secondEntry.Metadata.Should().BeEmpty(); + secondEntry.EntryId.ShouldBe("1"); + secondEntry.ContentType.ShouldBe(TestContentType); + secondEntry.Event.ToStringUtf8().ShouldBe(JsonSerializer.Serialize(bulkPublishData[1], client.InnerClient.JsonSerializerOptions)); + secondEntry.Metadata.ShouldBeEmpty(); // Create Response & Respond var response = new Autogenerated.BulkPublishResponse @@ -168,7 +162,7 @@ await daprClient.BulkPublishEventAsync(TestPubsubName, TestTopicName, bulkPublis var bulkPublishResponse = await request.CompleteWithMessageAsync(response); // Get response and validate - bulkPublishResponse.FailedEntries.Count.Should().Be(0); + bulkPublishResponse.FailedEntries.Count.ShouldBe(0); } [Fact] @@ -185,31 +179,29 @@ await daprClient.BulkPublishEventAsync(TestPubsubName, TestTopicName, bulkPublis request.Dismiss(); var envelope = await request.GetRequestEnvelopeAsync(); - envelope.Entries.Count.Should().Be(2); - envelope.PubsubName.Should().Be(TestPubsubName); - envelope.Topic.Should().Be(TestTopicName); + envelope.Entries.Count.ShouldBe(2); + envelope.PubsubName.ShouldBe(TestPubsubName); + envelope.Topic.ShouldBe(TestTopicName); - envelope.Metadata.Count.Should().Be(2); - envelope.Metadata.Keys.Contains("key1").Should().BeTrue(); - envelope.Metadata.Keys.Contains("key2").Should().BeTrue(); - envelope.Metadata["key1"].Should().Be("value1"); - envelope.Metadata["key2"].Should().Be("value2"); + envelope.Metadata.Count.ShouldBe(2); + envelope.Metadata.Keys.Contains("key1").ShouldBeTrue(); + envelope.Metadata.Keys.Contains("key2").ShouldBeTrue(); + envelope.Metadata["key1"].ShouldBe("value1"); + envelope.Metadata["key2"].ShouldBe("value2"); var firstEntry = envelope.Entries[0]; - firstEntry.EntryId.Should().Be("0"); - firstEntry.ContentType.Should().Be(TestContentType); - firstEntry.Event.ToStringUtf8().Should() - .Be(JsonSerializer.Serialize(bulkPublishData[0], client.InnerClient.JsonSerializerOptions)); - firstEntry.Metadata.Should().BeEmpty(); + firstEntry.EntryId.ShouldBe("0"); + firstEntry.ContentType.ShouldBe(TestContentType); + firstEntry.Event.ToStringUtf8().ShouldBe(JsonSerializer.Serialize(bulkPublishData[0], client.InnerClient.JsonSerializerOptions)); + firstEntry.Metadata.ShouldBeEmpty(); var secondEntry = envelope.Entries[1]; - secondEntry.EntryId.Should().Be("1"); - secondEntry.ContentType.Should().Be(TestContentType); - secondEntry.Event.ToStringUtf8().Should() - .Be(JsonSerializer.Serialize(bulkPublishData[1], client.InnerClient.JsonSerializerOptions)); - secondEntry.Metadata.Should().BeEmpty(); + secondEntry.EntryId.ShouldBe("1"); + secondEntry.ContentType.ShouldBe(TestContentType); + secondEntry.Event.ToStringUtf8().ShouldBe(JsonSerializer.Serialize(bulkPublishData[1], client.InnerClient.JsonSerializerOptions)); + secondEntry.Metadata.ShouldBeEmpty(); // Create Response & Respond var response = new Autogenerated.BulkPublishResponse @@ -219,7 +211,7 @@ await daprClient.BulkPublishEventAsync(TestPubsubName, TestTopicName, bulkPublis var bulkPublishResponse = await request.CompleteWithMessageAsync(response); // Get response and validate - bulkPublishResponse.FailedEntries.Count.Should().Be(0); + bulkPublishResponse.FailedEntries.Count.ShouldBe(0); } [Fact] @@ -236,18 +228,17 @@ await daprClient.BulkPublishEventAsync(TestPubsubName, TestTopicName, request.Dismiss(); var envelope = await request.GetRequestEnvelopeAsync(); - envelope.Entries.Count.Should().Be(1); - envelope.PubsubName.Should().Be(TestPubsubName); - envelope.Topic.Should().Be(TestTopicName); - envelope.Metadata.Count.Should().Be(0); + envelope.Entries.Count.ShouldBe(1); + envelope.PubsubName.ShouldBe(TestPubsubName); + envelope.Topic.ShouldBe(TestTopicName); + envelope.Metadata.Count.ShouldBe(0); var firstEntry = envelope.Entries[0]; - firstEntry.EntryId.Should().Be("0"); - firstEntry.ContentType.Should().Be(TestContentType); - firstEntry.Event.ToStringUtf8().Should() - .Be(JsonSerializer.Serialize(bulkPublishDataObject, client.InnerClient.JsonSerializerOptions)); - firstEntry.Metadata.Should().BeEmpty(); + firstEntry.EntryId.ShouldBe("0"); + firstEntry.ContentType.ShouldBe(TestContentType); + firstEntry.Event.ToStringUtf8().ShouldBe(JsonSerializer.Serialize(bulkPublishDataObject, client.InnerClient.JsonSerializerOptions)); + firstEntry.Metadata.ShouldBeEmpty(); // Create Response & Respond var response = new Autogenerated.BulkPublishResponse @@ -257,7 +248,7 @@ await daprClient.BulkPublishEventAsync(TestPubsubName, TestTopicName, var bulkPublishResponse = await request.CompleteWithMessageAsync(response); // Get response and validate - bulkPublishResponse.FailedEntries.Count.Should().Be(0); + bulkPublishResponse.FailedEntries.Count.ShouldBe(0); } [Fact] @@ -333,11 +324,11 @@ public async Task BulkPublishEventAsync_FailureResponse() var bulkPublishResponse = await request.CompleteWithMessageAsync(response); // Get response and validate - bulkPublishResponse.FailedEntries[0].Entry.EntryId.Should().Be("0"); - bulkPublishResponse.FailedEntries[0].ErrorMessage.Should().Be("Failed to publish"); + bulkPublishResponse.FailedEntries[0].Entry.EntryId.ShouldBe("0"); + bulkPublishResponse.FailedEntries[0].ErrorMessage.ShouldBe("Failed to publish"); - bulkPublishResponse.FailedEntries[1].Entry.EntryId.Should().Be("1"); - bulkPublishResponse.FailedEntries[1].ErrorMessage.Should().Be("Failed to publish"); + bulkPublishResponse.FailedEntries[1].Entry.EntryId.ShouldBe("1"); + bulkPublishResponse.FailedEntries[1].ErrorMessage.ShouldBe("Failed to publish"); } private class Widget diff --git a/test/Dapr.Client.Test/ConfigurationApiTest.cs b/test/Dapr.Client.Test/ConfigurationApiTest.cs index 095024933..495026fc2 100644 --- a/test/Dapr.Client.Test/ConfigurationApiTest.cs +++ b/test/Dapr.Client.Test/ConfigurationApiTest.cs @@ -15,7 +15,7 @@ using System.Threading.Tasks; using Autogenerated = Dapr.Client.Autogen.Grpc.v1; using Xunit; -using FluentAssertions; +using Shouldly; namespace Dapr.Client.Test { @@ -37,13 +37,13 @@ public async Task GetConfigurationAsync_WithAllValues_ValidateRequest() // Get Request and validate var envelope = await request.GetRequestEnvelopeAsync(); - envelope.StoreName.Should().Be("testStore"); - envelope.Keys.Should().Contain("test_key"); - envelope.Metadata.Count.Should().Be(2); - envelope.Metadata.Keys.Contains("key1").Should().BeTrue(); - envelope.Metadata.Keys.Contains("key2").Should().BeTrue(); - envelope.Metadata["key1"].Should().Be("value1"); - envelope.Metadata["key2"].Should().Be("value2"); + envelope.StoreName.ShouldBe("testStore"); + envelope.Keys.ShouldContain("test_key"); + envelope.Metadata.Count.ShouldBe(2); + envelope.Metadata.Keys.Contains("key1").ShouldBeTrue(); + envelope.Metadata.Keys.Contains("key2").ShouldBeTrue(); + envelope.Metadata["key1"].ShouldBe("value1"); + envelope.Metadata["key2"].ShouldBe("value2"); // Get response and validate var invokeResponse = new Autogenerated.GetConfigurationResponse(); @@ -55,8 +55,8 @@ public async Task GetConfigurationAsync_WithAllValues_ValidateRequest() var domainResponse = await request.CompleteWithMessageAsync(invokeResponse); var configItem = domainResponse.Items["testKey"]; - configItem.Value.Should().Be("testValue"); - configItem.Version.Should().Be("v1"); + configItem.Value.ShouldBe("testValue"); + configItem.Version.ShouldBe("v1"); } [Fact] @@ -75,13 +75,13 @@ public async Task GetConfigurationAsync_WithNullKeys_ValidateRequest() // Get Request and validate var envelope = await request.GetRequestEnvelopeAsync(); - envelope.StoreName.Should().Be("testStore"); - envelope.Keys.Should().BeEmpty(); - envelope.Metadata.Count.Should().Be(2); - envelope.Metadata.Keys.Contains("key1").Should().BeTrue(); - envelope.Metadata.Keys.Contains("key2").Should().BeTrue(); - envelope.Metadata["key1"].Should().Be("value1"); - envelope.Metadata["key2"].Should().Be("value2"); + envelope.StoreName.ShouldBe("testStore"); + envelope.Keys.ShouldBeEmpty(); + envelope.Metadata.Count.ShouldBe(2); + envelope.Metadata.Keys.Contains("key1").ShouldBeTrue(); + envelope.Metadata.Keys.Contains("key2").ShouldBeTrue(); + envelope.Metadata["key1"].ShouldBe("value1"); + envelope.Metadata["key2"].ShouldBe("value2"); // Get response and validate var invokeResponse = new Autogenerated.GetConfigurationResponse(); @@ -93,8 +93,8 @@ public async Task GetConfigurationAsync_WithNullKeys_ValidateRequest() var domainResponse = await request.CompleteWithMessageAsync(invokeResponse); var configItem = domainResponse.Items["testKey"]; - configItem.Value.Should().Be("testValue"); - configItem.Version.Should().Be("v1"); + configItem.Value.ShouldBe("testValue"); + configItem.Version.ShouldBe("v1"); } [Fact] @@ -108,9 +108,9 @@ public async Task GetConfigurationAsync_WithNullMetadata_ValidateRequest() // Get Request and validate var envelope = await request.GetRequestEnvelopeAsync(); - envelope.StoreName.Should().Be("testStore"); - envelope.Keys.Should().Contain("test_key"); - envelope.Metadata.Count.Should().Be(0); + envelope.StoreName.ShouldBe("testStore"); + envelope.Keys.ShouldContain("test_key"); + envelope.Metadata.Count.ShouldBe(0); // Get response and validate var invokeResponse = new Autogenerated.GetConfigurationResponse(); @@ -122,8 +122,8 @@ public async Task GetConfigurationAsync_WithNullMetadata_ValidateRequest() var domainResponse = await request.CompleteWithMessageAsync(invokeResponse); var configItem = domainResponse.Items["testKey"]; - configItem.Value.Should().Be("testValue"); - configItem.Version.Should().Be("v1"); + configItem.Value.ShouldBe("testValue"); + configItem.Version.ShouldBe("v1"); } [Fact] @@ -136,8 +136,8 @@ public async Task UnsubscribeConfiguration_ValidateRequest() }); var envelope = await request.GetRequestEnvelopeAsync(); - envelope.StoreName.Should().Be("testStore"); - envelope.Id.Should().Be("testId"); + envelope.StoreName.ShouldBe("testStore"); + envelope.Id.ShouldBe("testId"); request.Dismiss(); } } diff --git a/test/Dapr.Client.Test/Dapr.Client.Test.csproj b/test/Dapr.Client.Test/Dapr.Client.Test.csproj index f0bea601f..17105cd16 100644 --- a/test/Dapr.Client.Test/Dapr.Client.Test.csproj +++ b/test/Dapr.Client.Test/Dapr.Client.Test.csproj @@ -5,7 +5,6 @@ runtime; build; native; contentfiles; analyzers; buildtransitive all - @@ -14,6 +13,7 @@ + all diff --git a/test/Dapr.Client.Test/DaprApiTokenTest.cs b/test/Dapr.Client.Test/DaprApiTokenTest.cs index cf9f422bc..e96d29d0d 100644 --- a/test/Dapr.Client.Test/DaprApiTokenTest.cs +++ b/test/Dapr.Client.Test/DaprApiTokenTest.cs @@ -15,7 +15,7 @@ namespace Dapr.Client.Test { using System.Linq; using System.Threading.Tasks; - using FluentAssertions; + using Shouldly; using Xunit; using Autogenerated = Dapr.Client.Autogen.Grpc.v1; @@ -38,8 +38,8 @@ public async Task DaprCall_WithApiTokenSet() await request.GetRequestEnvelopeAsync(); request.Request.Headers.TryGetValues("dapr-api-token", out var headerValues); - headerValues.Count().Should().Be(1); - headerValues.First().Should().Be("test_token"); + headerValues.Count().ShouldBe(1); + headerValues.First().ShouldBe("test_token"); } [Fact] @@ -59,7 +59,7 @@ public async Task DaprCall_WithoutApiToken() await request.GetRequestEnvelopeAsync(); request.Request.Headers.TryGetValues("dapr-api-token", out var headerValues); - headerValues.Should().BeNull(); + headerValues.ShouldBeNull(); } } } diff --git a/test/Dapr.Client.Test/DaprClientTest.InvokeMethodGrpcAsync.cs b/test/Dapr.Client.Test/DaprClientTest.InvokeMethodGrpcAsync.cs index 6ccbbe4c4..3ef0aed6a 100644 --- a/test/Dapr.Client.Test/DaprClientTest.InvokeMethodGrpcAsync.cs +++ b/test/Dapr.Client.Test/DaprClientTest.InvokeMethodGrpcAsync.cs @@ -16,7 +16,7 @@ using System.Threading.Tasks; using Dapr.Client.Autogen.Grpc.v1; using Dapr.Client.Autogen.Test.Grpc.v1; -using FluentAssertions; +using Shouldly; using Google.Protobuf.WellKnownTypes; using Grpc.Core; using Grpc.Net.Client; @@ -62,9 +62,9 @@ public async Task InvokeMethodGrpcAsync_CanInvokeMethodWithReturnTypeAndData() // Get Request and validate var envelope = await request.GetRequestEnvelopeAsync(); - envelope.Id.Should().Be("test"); - envelope.Message.Method.Should().Be("test"); - envelope.Message.ContentType.Should().Be(Constants.ContentTypeApplicationGrpc); + envelope.Id.ShouldBe("test"); + envelope.Message.Method.ShouldBe("test"); + envelope.Message.ContentType.ShouldBe(Constants.ContentTypeApplicationGrpc); // Create Response & Respond var data = new Response() { Name = "Look, I was invoked!" }; @@ -75,7 +75,7 @@ public async Task InvokeMethodGrpcAsync_CanInvokeMethodWithReturnTypeAndData() // Validate Response var invokedResponse = await request.CompleteWithMessageAsync(response); - invokedResponse.Name.Should().Be("Look, I was invoked!"); + invokedResponse.Name.ShouldBe("Look, I was invoked!"); } [Fact] @@ -126,9 +126,9 @@ public async Task InvokeMethodGrpcAsync_CanInvokeMethodWithReturnTypeNoData() // Get Request and validate var envelope = await request.GetRequestEnvelopeAsync(); - envelope.Id.Should().Be("test"); - envelope.Message.Method.Should().Be("test"); - envelope.Message.ContentType.Should().Be(string.Empty); + envelope.Id.ShouldBe("test"); + envelope.Message.Method.ShouldBe("test"); + envelope.Message.ContentType.ShouldBe(string.Empty); // Create Response & Respond var data = new Response() { Name = "Look, I was invoked!" }; @@ -139,7 +139,7 @@ public async Task InvokeMethodGrpcAsync_CanInvokeMethodWithReturnTypeNoData() // Validate Response var invokedResponse = await request.CompleteWithMessageAsync(response); - invokedResponse.Name.Should().Be("Look, I was invoked!"); + invokedResponse.Name.ShouldBe("Look, I was invoked!"); } [Fact] @@ -176,7 +176,7 @@ await client.Call() } [Fact] - public void InvokeMethodGrpcAsync_CanInvokeMethodWithNoReturnTypeAndData() + public async Task InvokeMethodGrpcAsync_CanInvokeMethodWithNoReturnTypeAndData() { var request = new Request() { RequestParameter = "Hello " }; var client = new MockClient(); @@ -195,7 +195,7 @@ public void InvokeMethodGrpcAsync_CanInvokeMethodWithNoReturnTypeAndData() .Setup(m => m.InvokeServiceAsync(It.IsAny(), It.IsAny())) .Returns(response); - FluentActions.Awaiting(async () => await client.DaprClient.InvokeMethodGrpcAsync("test", "test", request)).Should().NotThrowAsync(); + await Should.NotThrowAsync(async () => await client.DaprClient.InvokeMethodGrpcAsync("test", "test", request)); } [Fact] @@ -250,9 +250,9 @@ public async Task InvokeMethodGrpcAsync_WithNoReturnTypeAndData() // Get Request and validate var envelope = await request.GetRequestEnvelopeAsync(); - envelope.Id.Should().Be("test"); - envelope.Message.Method.Should().Be("test"); - envelope.Message.ContentType.Should().Be(Constants.ContentTypeApplicationGrpc); + envelope.Id.ShouldBe("test"); + envelope.Message.Method.ShouldBe("test"); + envelope.Message.ContentType.ShouldBe(Constants.ContentTypeApplicationGrpc); var actual = envelope.Message.Data.Unpack(); Assert.Equal(invokeRequest.RequestParameter, actual.RequestParameter); @@ -275,9 +275,9 @@ public async Task InvokeMethodGrpcAsync_WithReturnTypeAndData() // Get Request and validate var envelope = await request.GetRequestEnvelopeAsync(); - envelope.Id.Should().Be("test"); - envelope.Message.Method.Should().Be("test"); - envelope.Message.ContentType.Should().Be(Constants.ContentTypeApplicationGrpc); + envelope.Id.ShouldBe("test"); + envelope.Message.Method.ShouldBe("test"); + envelope.Message.ContentType.ShouldBe(Constants.ContentTypeApplicationGrpc); var actual = envelope.Message.Data.Unpack(); Assert.Equal(invokeRequest.RequestParameter, actual.RequestParameter); @@ -291,7 +291,7 @@ public async Task InvokeMethodGrpcAsync_WithReturnTypeAndData() // Validate Response var invokedResponse = await request.CompleteWithMessageAsync(response); - invokedResponse.Name.Should().Be(invokeResponse.Name); + invokedResponse.Name.ShouldBe(invokeResponse.Name); } [Fact] @@ -308,7 +308,7 @@ public async Task InvokeMethodGrpcAsync_AppCallback_SayHello() var response = await daprClient.InvokeMethodGrpcAsync("test", "SayHello", request); - response.Name.Should().Be("Hello Look, I was invoked!"); + response.Name.ShouldBe("Hello Look, I was invoked!"); } [Fact] @@ -328,10 +328,10 @@ public async Task InvokeMethodGrpcAsync_AppCallback_RepeatedField() var response = await daprClient.InvokeMethodGrpcAsync("test", "TestRun", testRun); - response.Tests.Count.Should().Be(3); - response.Tests[0].Name.Should().Be("test1"); - response.Tests[1].Name.Should().Be("test2"); - response.Tests[2].Name.Should().Be("test3"); + response.Tests.Count.ShouldBe(3); + response.Tests[0].Name.ShouldBe("test1"); + response.Tests[1].Name.ShouldBe("test2"); + response.Tests[2].Name.ShouldBe("test3"); } [Fact] @@ -348,7 +348,7 @@ public async Task InvokeMethodGrpcAsync_AppCallback_UnexpectedMethod() var response = await daprClient.InvokeMethodGrpcAsync("test", "not-existing", request); - response.Name.Should().Be("unexpected"); + response.Name.ShouldBe("unexpected"); } @@ -401,10 +401,10 @@ public async Task GetMetadataAsync_WithReturnTypeAndData() // Validate Response var metadata = await request.CompleteWithMessageAsync(response); - metadata.Id.Should().Be("testId"); - metadata.Extended.Should().Contain(new System.Collections.Generic.KeyValuePair("e1", "v1")); - metadata.Actors.Should().Contain(actors => actors.Count == 1 && actors.Type == "testType"); - metadata.Components.Should().Contain(components => components.Name == "testName" && components.Type == "testType" && components.Version == "V1" && components.Capabilities.Length == 0); + metadata.Id.ShouldBe("testId"); + metadata.Extended.ShouldContain(new System.Collections.Generic.KeyValuePair("e1", "v1")); + metadata.Actors.ShouldContain(actors => actors.Count == 1 && actors.Type == "testType"); + metadata.Components.ShouldContain(components => components.Name == "testName" && components.Type == "testType" && components.Version == "V1" && components.Capabilities.Length == 0); } [Fact] @@ -445,8 +445,8 @@ public async Task SetMetadataAsync_WithReturnTypeAndData() // Get Request and validate var envelope = await request.GetRequestEnvelopeAsync(); - envelope.Key.Should().Be("test"); - envelope.Value.Should().Be("testv"); + envelope.Key.ShouldBe("test"); + envelope.Value.ShouldBe("testv"); await request.CompleteWithMessageAsync(new Empty()); diff --git a/test/Dapr.Client.Test/DistributedLockApiTest.cs b/test/Dapr.Client.Test/DistributedLockApiTest.cs index a030586c5..1935a5431 100644 --- a/test/Dapr.Client.Test/DistributedLockApiTest.cs +++ b/test/Dapr.Client.Test/DistributedLockApiTest.cs @@ -14,7 +14,7 @@ using System.Threading.Tasks; using Autogenerated = Dapr.Client.Autogen.Grpc.v1; using Xunit; -using FluentAssertions; +using Shouldly; using System; namespace Dapr.Client.Test @@ -37,10 +37,10 @@ public async Task TryLockAsync_WithAllValues_ValidateRequest() // Get Request and validate var envelope = await request.GetRequestEnvelopeAsync(); - envelope.StoreName.Should().Be("redis"); - envelope.ResourceId.Should().Be("resourceId"); - envelope.LockOwner.Should().Be("owner1"); - envelope.ExpiryInSeconds.Should().Be(1000); + envelope.StoreName.ShouldBe("redis"); + envelope.ResourceId.ShouldBe("resourceId"); + envelope.LockOwner.ShouldBe("owner1"); + envelope.ExpiryInSeconds.ShouldBe(1000); // Get response and validate var invokeResponse = new Autogenerated.TryLockResponse{ @@ -48,7 +48,7 @@ public async Task TryLockAsync_WithAllValues_ValidateRequest() }; var domainResponse = await request.CompleteWithMessageAsync(invokeResponse); - domainResponse.Success.Should().Be(true); + domainResponse.Success.ShouldBe(true); } [Fact] @@ -80,9 +80,9 @@ public async Task UnLockAsync_WithAllValues_ValidateRequest() // Get Request and validate var envelope = await request.GetRequestEnvelopeAsync(); - envelope.StoreName.Should().Be("redis"); - envelope.ResourceId.Should().Be("resourceId"); - envelope.LockOwner.Should().Be("owner1"); + envelope.StoreName.ShouldBe("redis"); + envelope.ResourceId.ShouldBe("resourceId"); + envelope.LockOwner.ShouldBe("owner1"); // Get response and validate var invokeResponse = new Autogenerated.UnlockResponse{ @@ -90,7 +90,7 @@ public async Task UnLockAsync_WithAllValues_ValidateRequest() }; var domainResponse = await request.CompleteWithMessageAsync(invokeResponse); - domainResponse.status.Should().Be(LockStatus.LockDoesNotExist); + domainResponse.status.ShouldBe(LockStatus.LockDoesNotExist); } } -} \ No newline at end of file +} diff --git a/test/Dapr.Client.Test/InvokeBindingApiTest.cs b/test/Dapr.Client.Test/InvokeBindingApiTest.cs index c2ada7a11..c980e889f 100644 --- a/test/Dapr.Client.Test/InvokeBindingApiTest.cs +++ b/test/Dapr.Client.Test/InvokeBindingApiTest.cs @@ -20,7 +20,7 @@ namespace Dapr.Client.Test using System.Threading; using System.Threading.Tasks; using Dapr.Client.Autogen.Grpc.v1; - using FluentAssertions; + using Shouldly; using Google.Protobuf; using Grpc.Core; using Moq; @@ -43,11 +43,11 @@ public async Task InvokeBindingAsync_ValidateRequest() // Get Request and validate var envelope = await request.GetRequestEnvelopeAsync(); - envelope.Name.Should().Be("test"); - envelope.Metadata.Count.Should().Be(0); + envelope.Name.ShouldBe("test"); + envelope.Metadata.Count.ShouldBe(0); var json = envelope.Data.ToStringUtf8(); var typeFromRequest = JsonSerializer.Deserialize(json, client.InnerClient.JsonSerializerOptions); - typeFromRequest.RequestParameter.Should().Be("Hello "); + typeFromRequest.RequestParameter.ShouldBe("Hello "); } [Fact] @@ -70,15 +70,15 @@ public async Task InvokeBindingAsync_ValidateRequest_WithMetadata() // Get Request and validate var envelope = await request.GetRequestEnvelopeAsync(); - envelope.Name.Should().Be("test"); - envelope.Metadata.Count.Should().Be(2); - envelope.Metadata.Keys.Contains("key1").Should().BeTrue(); - envelope.Metadata.Keys.Contains("key2").Should().BeTrue(); - envelope.Metadata["key1"].Should().Be("value1"); - envelope.Metadata["key2"].Should().Be("value2"); + envelope.Name.ShouldBe("test"); + envelope.Metadata.Count.ShouldBe(2); + envelope.Metadata.Keys.Contains("key1").ShouldBeTrue(); + envelope.Metadata.Keys.Contains("key2").ShouldBeTrue(); + envelope.Metadata["key1"].ShouldBe("value1"); + envelope.Metadata["key2"].ShouldBe("value2"); var json = envelope.Data.ToStringUtf8(); var typeFromRequest = JsonSerializer.Deserialize(json, client.InnerClient.JsonSerializerOptions); - typeFromRequest.RequestParameter.Should().Be("Hello "); + typeFromRequest.RequestParameter.ShouldBe("Hello "); } [Fact] @@ -95,8 +95,8 @@ public async Task InvokeBindingAsync_WithNullPayload_ValidateRequest() // Get Request and validate var envelope = await request.GetRequestEnvelopeAsync(); - envelope.Name.Should().Be("test"); - envelope.Metadata.Count.Should().Be(0); + envelope.Name.ShouldBe("test"); + envelope.Metadata.Count.ShouldBe(0); var json = envelope.Data.ToStringUtf8(); Assert.Equal("null", json); } @@ -133,16 +133,16 @@ public async Task InvokeBindingAsync_WithRequest_ValidateRequest() var response = await request.CompleteWithMessageAsync(gRpcResponse); var envelope = await request.GetRequestEnvelopeAsync(); - envelope.Name.Should().Be("test"); - envelope.Metadata.Count.Should().Be(2); - envelope.Metadata.Keys.Contains("key1").Should().BeTrue(); - envelope.Metadata.Keys.Contains("key2").Should().BeTrue(); - envelope.Metadata["key1"].Should().Be("value1"); - envelope.Metadata["key2"].Should().Be("value2"); + envelope.Name.ShouldBe("test"); + envelope.Metadata.Count.ShouldBe(2); + envelope.Metadata.Keys.Contains("key1").ShouldBeTrue(); + envelope.Metadata.Keys.Contains("key2").ShouldBeTrue(); + envelope.Metadata["key1"].ShouldBe("value1"); + envelope.Metadata["key2"].ShouldBe("value2"); var json = envelope.Data.ToStringUtf8(); var typeFromRequest = JsonSerializer.Deserialize(json, client.InnerClient.JsonSerializerOptions); - typeFromRequest.RequestParameter.Should().Be("Hello "); + typeFromRequest.RequestParameter.ShouldBe("Hello "); Assert.Same(bindingRequest, response.Request); Assert.Equal("red", JsonSerializer.Deserialize(response.Data.Span, client.InnerClient.JsonSerializerOptions).Color); @@ -239,15 +239,15 @@ public async Task InvokeBindingRequest_WithCustomRequest_ValidateRequest() var response = await req.CompleteWithMessageAsync(resp); var envelope = await req.GetRequestEnvelopeAsync(); - envelope.Name.Should().Be("binding"); - envelope.Operation.Should().Be("operation"); - envelope.Metadata.Count.Should().Be(1); - envelope.Metadata.Keys.Contains("key1").Should().BeTrue(); - envelope.Metadata["key1"].Should().Be("value1"); + envelope.Name.ShouldBe("binding"); + envelope.Operation.ShouldBe("operation"); + envelope.Metadata.Count.ShouldBe(1); + envelope.Metadata.Keys.Contains("key1").ShouldBeTrue(); + envelope.Metadata["key1"].ShouldBe("value1"); var json = envelope.Data.ToStringUtf8(); var typeFromRequest = JsonSerializer.Deserialize(json, client.InnerClient.JsonSerializerOptions); - typeFromRequest.RequestParameter.Should().Be("Test"); + typeFromRequest.RequestParameter.ShouldBe("Test"); Assert.Equal("red", response.Color); } @@ -269,8 +269,8 @@ public async Task InvokeBindingRequest_WithNullData_ValidateRequest() var response = await req.CompleteWithMessageAsync(resp); var envelope = await req.GetRequestEnvelopeAsync(); - envelope.Name.Should().Be("binding"); - envelope.Operation.Should().Be("operation"); + envelope.Name.ShouldBe("binding"); + envelope.Operation.ShouldBe("operation"); Assert.Equal("red", response.Color); } diff --git a/test/Dapr.Client.Test/PublishEventApiTest.cs b/test/Dapr.Client.Test/PublishEventApiTest.cs index 6ba774e52..0dac474a3 100644 --- a/test/Dapr.Client.Test/PublishEventApiTest.cs +++ b/test/Dapr.Client.Test/PublishEventApiTest.cs @@ -24,7 +24,7 @@ namespace Dapr.Client.Test using System.Threading; using System.Threading.Tasks; using Dapr.Client.Autogen.Grpc.v1; - using FluentAssertions; + using Shouldly; using Grpc.Core; using Moq; using Xunit; @@ -49,11 +49,11 @@ public async Task PublishEventAsync_CanPublishTopicWithData() var envelope = await request.GetRequestEnvelopeAsync(); var jsonFromRequest = envelope.Data.ToStringUtf8(); - envelope.DataContentType.Should().Be("application/json"); - envelope.PubsubName.Should().Be(TestPubsubName); - envelope.Topic.Should().Be("test"); - jsonFromRequest.Should().Be(JsonSerializer.Serialize(publishData, client.InnerClient.JsonSerializerOptions)); - envelope.Metadata.Count.Should().Be(0); + envelope.DataContentType.ShouldBe("application/json"); + envelope.PubsubName.ShouldBe(TestPubsubName); + envelope.Topic.ShouldBe("test"); + jsonFromRequest.ShouldBe(JsonSerializer.Serialize(publishData, client.InnerClient.JsonSerializerOptions)); + envelope.Metadata.Count.ShouldBe(0); } [Fact] @@ -75,9 +75,8 @@ public async Task PublishEvent_ShouldRespectJsonStringEnumConverter() var client = new TestClient(clientBuilder.Build(), handler); //Ensure that the JsonStringEnumConverter is registered - client.InnerClient.JsonSerializerOptions.Converters.Count.Should().Be(1); - client.InnerClient.JsonSerializerOptions.Converters.First().GetType().Name.Should() - .Match(nameof(JsonStringEnumConverter)); + client.InnerClient.JsonSerializerOptions.Converters.Count.ShouldBe(1); + client.InnerClient.JsonSerializerOptions.Converters.First().GetType().Name.ShouldMatch(nameof(JsonStringEnumConverter)); var publishData = new Widget {Size = "Large", Color = WidgetColor.Red}; var request = await client.CaptureGrpcRequestAsync(async daprClient => @@ -89,9 +88,8 @@ public async Task PublishEvent_ShouldRespectJsonStringEnumConverter() var envelope = await request.GetRequestEnvelopeAsync(); var jsonFromRequest = envelope.Data.ToStringUtf8(); - jsonFromRequest.Should() - .Be(JsonSerializer.Serialize(publishData, client.InnerClient.JsonSerializerOptions)); - jsonFromRequest.Should().Match("{\"Size\":\"Large\",\"Color\":\"Red\"}"); + jsonFromRequest.ShouldBe(JsonSerializer.Serialize(publishData, client.InnerClient.JsonSerializerOptions)); + jsonFromRequest.ShouldMatch("{\"Size\":\"Large\",\"Color\":\"Red\"}"); } [Fact] @@ -116,16 +114,16 @@ public async Task PublishEventAsync_CanPublishTopicWithData_WithMetadata() var envelope = await request.GetRequestEnvelopeAsync(); var jsonFromRequest = envelope.Data.ToStringUtf8(); - envelope.DataContentType.Should().Be("application/json"); - envelope.PubsubName.Should().Be(TestPubsubName); - envelope.Topic.Should().Be("test"); - jsonFromRequest.Should().Be(JsonSerializer.Serialize(publishData, client.InnerClient.JsonSerializerOptions)); + envelope.DataContentType.ShouldBe("application/json"); + envelope.PubsubName.ShouldBe(TestPubsubName); + envelope.Topic.ShouldBe("test"); + jsonFromRequest.ShouldBe(JsonSerializer.Serialize(publishData, client.InnerClient.JsonSerializerOptions)); - envelope.Metadata.Count.Should().Be(2); - envelope.Metadata.Keys.Contains("key1").Should().BeTrue(); - envelope.Metadata.Keys.Contains("key2").Should().BeTrue(); - envelope.Metadata["key1"].Should().Be("value1"); - envelope.Metadata["key2"].Should().Be("value2"); + envelope.Metadata.Count.ShouldBe(2); + envelope.Metadata.Keys.Contains("key1").ShouldBeTrue(); + envelope.Metadata.Keys.Contains("key2").ShouldBeTrue(); + envelope.Metadata["key1"].ShouldBe("value1"); + envelope.Metadata["key2"].ShouldBe("value2"); } [Fact] @@ -142,10 +140,10 @@ public async Task PublishEventAsync_CanPublishTopicWithNoContent() var envelope = await request.GetRequestEnvelopeAsync(); - envelope.PubsubName.Should().Be(TestPubsubName); - envelope.Topic.Should().Be("test"); - envelope.Data.Length.Should().Be(0); - envelope.Metadata.Count.Should().Be(0); + envelope.PubsubName.ShouldBe(TestPubsubName); + envelope.Topic.ShouldBe("test"); + envelope.Data.Length.ShouldBe(0); + envelope.Metadata.Count.ShouldBe(0); } [Fact] @@ -167,15 +165,15 @@ public async Task PublishEventAsync_CanPublishTopicWithNoContent_WithMetadata() request.Dismiss(); var envelope = await request.GetRequestEnvelopeAsync(); - envelope.PubsubName.Should().Be(TestPubsubName); - envelope.Topic.Should().Be("test"); - envelope.Data.Length.Should().Be(0); - - envelope.Metadata.Count.Should().Be(2); - envelope.Metadata.Keys.Contains("key1").Should().BeTrue(); - envelope.Metadata.Keys.Contains("key2").Should().BeTrue(); - envelope.Metadata["key1"].Should().Be("value1"); - envelope.Metadata["key2"].Should().Be("value2"); + envelope.PubsubName.ShouldBe(TestPubsubName); + envelope.Topic.ShouldBe("test"); + envelope.Data.Length.ShouldBe(0); + + envelope.Metadata.Count.ShouldBe(2); + envelope.Metadata.Keys.Contains("key1").ShouldBeTrue(); + envelope.Metadata.Keys.Contains("key2").ShouldBeTrue(); + envelope.Metadata["key1"].ShouldBe("value1"); + envelope.Metadata["key2"].ShouldBe("value2"); } [Fact] @@ -200,11 +198,11 @@ public async Task PublishEventAsync_CanPublishCloudEventWithData() var envelope = await request.GetRequestEnvelopeAsync(); var jsonFromRequest = envelope.Data.ToStringUtf8(); - envelope.DataContentType.Should().Be("application/cloudevents+json"); - envelope.PubsubName.Should().Be(TestPubsubName); - envelope.Topic.Should().Be("test"); - jsonFromRequest.Should().Be(JsonSerializer.Serialize(cloudEvent, client.InnerClient.JsonSerializerOptions)); - envelope.Metadata.Count.Should().Be(0); + envelope.DataContentType.ShouldBe("application/cloudevents+json"); + envelope.PubsubName.ShouldBe(TestPubsubName); + envelope.Topic.ShouldBe("test"); + jsonFromRequest.ShouldBe(JsonSerializer.Serialize(cloudEvent, client.InnerClient.JsonSerializerOptions)); + envelope.Metadata.Count.ShouldBe(0); } [Fact] @@ -228,11 +226,11 @@ public async Task PublishEventAsync_CanPublishCloudEventWithNoContent() var envelope = await request.GetRequestEnvelopeAsync(); var jsonFromRequest = envelope.Data.ToStringUtf8(); - envelope.DataContentType.Should().Be("application/cloudevents+json"); - envelope.PubsubName.Should().Be(TestPubsubName); - envelope.Topic.Should().Be("test"); - jsonFromRequest.Should().Be(JsonSerializer.Serialize(cloudEvent, client.InnerClient.JsonSerializerOptions)); - envelope.Metadata.Count.Should().Be(0); + envelope.DataContentType.ShouldBe("application/cloudevents+json"); + envelope.PubsubName.ShouldBe(TestPubsubName); + envelope.Topic.ShouldBe("test"); + jsonFromRequest.ShouldBe(JsonSerializer.Serialize(cloudEvent, client.InnerClient.JsonSerializerOptions)); + envelope.Metadata.Count.ShouldBe(0); } [Fact] @@ -287,13 +285,13 @@ public async Task PublishEventAsync_CanPublishWithRawData() var envelope = await request.GetRequestEnvelopeAsync(); var jsonFromRequest = envelope.Data.ToStringUtf8(); - envelope.DataContentType.Should().Be("application/json"); - envelope.PubsubName.Should().Be(TestPubsubName); - envelope.Topic.Should().Be("test"); - jsonFromRequest.Should().Be(JsonSerializer.Serialize(publishData)); + envelope.DataContentType.ShouldBe("application/json"); + envelope.PubsubName.ShouldBe(TestPubsubName); + envelope.Topic.ShouldBe("test"); + jsonFromRequest.ShouldBe(JsonSerializer.Serialize(publishData)); // The default serializer forces camel case, so this should be different from our serialization above. - jsonFromRequest.Should().NotBe(JsonSerializer.Serialize(publishBytes, client.InnerClient.JsonSerializerOptions)); - envelope.Metadata.Count.Should().Be(0); + jsonFromRequest.ShouldNotBe(JsonSerializer.Serialize(publishBytes, client.InnerClient.JsonSerializerOptions)); + envelope.Metadata.Count.ShouldBe(0); } private class PublishData diff --git a/test/Dapr.Client.Test/SecretApiTest.cs b/test/Dapr.Client.Test/SecretApiTest.cs index 26048e2a4..4f7d8aa5c 100644 --- a/test/Dapr.Client.Test/SecretApiTest.cs +++ b/test/Dapr.Client.Test/SecretApiTest.cs @@ -17,7 +17,7 @@ namespace Dapr.Client.Test using System.Collections.Generic; using System.Threading; using System.Threading.Tasks; - using FluentAssertions; + using Shouldly; using Grpc.Core; using Moq; using Xunit; @@ -44,13 +44,13 @@ public async Task GetSecretAsync_ValidateRequest() // Get Request and validate var envelope = await request.GetRequestEnvelopeAsync(); - envelope.StoreName.Should().Be("testStore"); - envelope.Key.Should().Be("test_key"); - envelope.Metadata.Count.Should().Be(2); - envelope.Metadata.Keys.Contains("key1").Should().BeTrue(); - envelope.Metadata.Keys.Contains("key2").Should().BeTrue(); - envelope.Metadata["key1"].Should().Be("value1"); - envelope.Metadata["key2"].Should().Be("value2"); + envelope.StoreName.ShouldBe("testStore"); + envelope.Key.ShouldBe("test_key"); + envelope.Metadata.Count.ShouldBe(2); + envelope.Metadata.Keys.Contains("key1").ShouldBeTrue(); + envelope.Metadata.Keys.Contains("key2").ShouldBeTrue(); + envelope.Metadata["key1"].ShouldBe("value1"); + envelope.Metadata["key2"].ShouldBe("value2"); } [Fact] @@ -72,13 +72,13 @@ public async Task GetSecretAsync_ReturnSingleSecret() // Get Request and validate var envelope = await request.GetRequestEnvelopeAsync(); - envelope.StoreName.Should().Be("testStore"); - envelope.Key.Should().Be("test_key"); - envelope.Metadata.Count.Should().Be(2); - envelope.Metadata.Keys.Contains("key1").Should().BeTrue(); - envelope.Metadata.Keys.Contains("key2").Should().BeTrue(); - envelope.Metadata["key1"].Should().Be("value1"); - envelope.Metadata["key2"].Should().Be("value2"); + envelope.StoreName.ShouldBe("testStore"); + envelope.Key.ShouldBe("test_key"); + envelope.Metadata.Count.ShouldBe(2); + envelope.Metadata.Keys.Contains("key1").ShouldBeTrue(); + envelope.Metadata.Keys.Contains("key2").ShouldBeTrue(); + envelope.Metadata["key1"].ShouldBe("value1"); + envelope.Metadata["key2"].ShouldBe("value2"); // Create Response & Respond var secrets = new Dictionary @@ -88,9 +88,9 @@ public async Task GetSecretAsync_ReturnSingleSecret() var secretsResponse = await SendResponseWithSecrets(secrets, request); // Get response and validate - secretsResponse.Count.Should().Be(1); - secretsResponse.ContainsKey("redis_secret").Should().BeTrue(); - secretsResponse["redis_secret"].Should().Be("Guess_Redis"); + secretsResponse.Count.ShouldBe(1); + secretsResponse.ContainsKey("redis_secret").ShouldBeTrue(); + secretsResponse["redis_secret"].ShouldBe("Guess_Redis"); } [Fact] @@ -107,16 +107,16 @@ public async Task GetSecretAsync_WithSlashesInName() //Get Request and validate var envelope = await request.GetRequestEnvelopeAsync(); - envelope.StoreName.Should().Be("testStore"); - envelope.Key.Should().Be("us-west-1/org/xpto/secretabc"); + envelope.StoreName.ShouldBe("testStore"); + envelope.Key.ShouldBe("us-west-1/org/xpto/secretabc"); var secrets = new Dictionary { { "us-west-1/org/xpto/secretabc", "abc123" } }; var secretsResponse = await SendResponseWithSecrets(secrets, request); //Get response and validate - secretsResponse.Count.Should().Be(1); - secretsResponse.ContainsKey("us-west-1/org/xpto/secretabc").Should().BeTrue(); - secretsResponse["us-west-1/org/xpto/secretabc"].Should().Be("abc123"); + secretsResponse.Count.ShouldBe(1); + secretsResponse.ContainsKey("us-west-1/org/xpto/secretabc").ShouldBeTrue(); + secretsResponse["us-west-1/org/xpto/secretabc"].ShouldBe("abc123"); } [Fact] @@ -138,13 +138,13 @@ public async Task GetSecretAsync_ReturnMultipleSecrets() // Get Request and validate var envelope = await request.GetRequestEnvelopeAsync(); - envelope.StoreName.Should().Be("testStore"); - envelope.Key.Should().Be("test_key"); - envelope.Metadata.Count.Should().Be(2); - envelope.Metadata.Keys.Contains("key1").Should().BeTrue(); - envelope.Metadata.Keys.Contains("key2").Should().BeTrue(); - envelope.Metadata["key1"].Should().Be("value1"); - envelope.Metadata["key2"].Should().Be("value2"); + envelope.StoreName.ShouldBe("testStore"); + envelope.Key.ShouldBe("test_key"); + envelope.Metadata.Count.ShouldBe(2); + envelope.Metadata.Keys.Contains("key1").ShouldBeTrue(); + envelope.Metadata.Keys.Contains("key2").ShouldBeTrue(); + envelope.Metadata["key1"].ShouldBe("value1"); + envelope.Metadata["key2"].ShouldBe("value2"); // Create Response & Respond var secrets = new Dictionary @@ -155,11 +155,11 @@ public async Task GetSecretAsync_ReturnMultipleSecrets() var secretsResponse = await SendResponseWithSecrets(secrets, request); // Get response and validate - secretsResponse.Count.Should().Be(2); - secretsResponse.ContainsKey("redis_secret").Should().BeTrue(); - secretsResponse["redis_secret"].Should().Be("Guess_Redis"); - secretsResponse.ContainsKey("kafka_secret").Should().BeTrue(); - secretsResponse["kafka_secret"].Should().Be("Guess_Kafka"); + secretsResponse.Count.ShouldBe(2); + secretsResponse.ContainsKey("redis_secret").ShouldBeTrue(); + secretsResponse["redis_secret"].ShouldBe("Guess_Redis"); + secretsResponse.ContainsKey("kafka_secret").ShouldBeTrue(); + secretsResponse["kafka_secret"].ShouldBe("Guess_Kafka"); } [Fact] @@ -220,12 +220,12 @@ public async Task GetBulkSecretAsync_ValidateRequest() // Get Request and validate var envelope = await request.GetRequestEnvelopeAsync(); - envelope.StoreName.Should().Be("testStore"); - envelope.Metadata.Count.Should().Be(2); - envelope.Metadata.Keys.Contains("key1").Should().BeTrue(); - envelope.Metadata.Keys.Contains("key2").Should().BeTrue(); - envelope.Metadata["key1"].Should().Be("value1"); - envelope.Metadata["key2"].Should().Be("value2"); + envelope.StoreName.ShouldBe("testStore"); + envelope.Metadata.Count.ShouldBe(2); + envelope.Metadata.Keys.Contains("key1").ShouldBeTrue(); + envelope.Metadata.Keys.Contains("key2").ShouldBeTrue(); + envelope.Metadata["key1"].ShouldBe("value1"); + envelope.Metadata["key2"].ShouldBe("value2"); } [Fact] @@ -244,12 +244,12 @@ public async Task GetBulkSecretAsync_ReturnSingleSecret() // Get Request and validate var envelope = await request.GetRequestEnvelopeAsync(); - envelope.StoreName.Should().Be("testStore"); - envelope.Metadata.Count.Should().Be(2); - envelope.Metadata.Keys.Contains("key1").Should().BeTrue(); - envelope.Metadata.Keys.Contains("key2").Should().BeTrue(); - envelope.Metadata["key1"].Should().Be("value1"); - envelope.Metadata["key2"].Should().Be("value2"); + envelope.StoreName.ShouldBe("testStore"); + envelope.Metadata.Count.ShouldBe(2); + envelope.Metadata.Keys.Contains("key1").ShouldBeTrue(); + envelope.Metadata.Keys.Contains("key2").ShouldBeTrue(); + envelope.Metadata["key1"].ShouldBe("value1"); + envelope.Metadata["key2"].ShouldBe("value2"); // Create Response & Respond var secrets = new Dictionary(); @@ -257,9 +257,9 @@ public async Task GetBulkSecretAsync_ReturnSingleSecret() var secretsResponse = await SendBulkResponseWithSecrets(secrets, request); // Get response and validate - secretsResponse.Count.Should().Be(1); - secretsResponse.ContainsKey("redis_secret").Should().BeTrue(); - secretsResponse["redis_secret"]["redis_secret"].Should().Be("Guess_Redis"); + secretsResponse.Count.ShouldBe(1); + secretsResponse.ContainsKey("redis_secret").ShouldBeTrue(); + secretsResponse["redis_secret"]["redis_secret"].ShouldBe("Guess_Redis"); } [Fact] @@ -279,12 +279,12 @@ public async Task GetBulkSecretAsync_ReturnMultipleSecrets() // Get Request and validate var envelope = await request.GetRequestEnvelopeAsync(); - envelope.StoreName.Should().Be("testStore"); - envelope.Metadata.Count.Should().Be(2); - envelope.Metadata.Keys.Contains("key1").Should().BeTrue(); - envelope.Metadata.Keys.Contains("key2").Should().BeTrue(); - envelope.Metadata["key1"].Should().Be("value1"); - envelope.Metadata["key2"].Should().Be("value2"); + envelope.StoreName.ShouldBe("testStore"); + envelope.Metadata.Count.ShouldBe(2); + envelope.Metadata.Keys.Contains("key1").ShouldBeTrue(); + envelope.Metadata.Keys.Contains("key2").ShouldBeTrue(); + envelope.Metadata["key1"].ShouldBe("value1"); + envelope.Metadata["key2"].ShouldBe("value2"); // Create Response & Respond var secrets = new Dictionary(); @@ -293,11 +293,11 @@ public async Task GetBulkSecretAsync_ReturnMultipleSecrets() var secretsResponse = await SendBulkResponseWithSecrets(secrets, request); // Get response and validate - secretsResponse.Count.Should().Be(2); - secretsResponse.ContainsKey("redis_secret").Should().BeTrue(); - secretsResponse["redis_secret"]["redis_secret"].Should().Be("Guess_Redis"); - secretsResponse.ContainsKey("kafka_secret").Should().BeTrue(); - secretsResponse["kafka_secret"]["kafka_secret"].Should().Be("Guess_Kafka"); + secretsResponse.Count.ShouldBe(2); + secretsResponse.ContainsKey("redis_secret").ShouldBeTrue(); + secretsResponse["redis_secret"]["redis_secret"].ShouldBe("Guess_Redis"); + secretsResponse.ContainsKey("kafka_secret").ShouldBeTrue(); + secretsResponse["kafka_secret"]["kafka_secret"].ShouldBe("Guess_Kafka"); } [Fact] diff --git a/test/Dapr.Client.Test/StateApiTest.cs b/test/Dapr.Client.Test/StateApiTest.cs index 12fd0e3de..43c7f408b 100644 --- a/test/Dapr.Client.Test/StateApiTest.cs +++ b/test/Dapr.Client.Test/StateApiTest.cs @@ -18,12 +18,12 @@ using System.Text.Json; using System.Threading.Tasks; using Autogenerated = Dapr.Client.Autogen.Grpc.v1; -using FluentAssertions; using Google.Protobuf; using Grpc.Core; using Moq; using StateConsistency = Dapr.Client.Autogen.Grpc.v1.StateOptions.Types.StateConsistency; using StateConcurrency = Dapr.Client.Autogen.Grpc.v1.StateOptions.Types.StateConcurrency; +using Shouldly; using Xunit; using System.Threading; using System.Net.Http; @@ -48,8 +48,8 @@ public async Task GetStateAsync_CanReadState() var state = await request.CompleteWithMessageAsync(envelope); // Get response and validate - state.Size.Should().Be("small"); - state.Color.Should().Be("yellow"); + state.Size.ShouldBe("small"); + state.Color.ShouldBe("yellow"); } [Fact] @@ -66,7 +66,7 @@ public async Task GetBulkStateAsync_CanReadState() var state = await request.CompleteWithMessageAsync(envelope); // Get response and validate - state.Should().HaveCount(1); + state.Count.ShouldBe(1); } [Fact] @@ -85,9 +85,9 @@ public async Task GetBulkStateAsync_CanReadDeserializedState() var state = await request.CompleteWithMessageAsync(envelope); // Get response and validate - state.Should().HaveCount(1); - state[0].Value.Size.Should().Match(size); - state[0].Value.Color.Should().Match(color); + state.Count.ShouldBe(1); + state[0].Value.Size.ShouldMatch(size); + state[0].Value.Color.ShouldMatch(color); } [Fact] @@ -122,8 +122,8 @@ public async Task GetBulkStateAsync_ValidateRequest() // Create Response & Validate var envelope = await request.GetRequestEnvelopeAsync(); - envelope.StoreName.Should().Be("testStore"); - envelope.Metadata.Should().BeEquivalentTo(metadata); + envelope.StoreName.ShouldBe("testStore"); + envelope.Metadata.ShouldBe(metadata); } [Fact] @@ -139,9 +139,9 @@ public async Task GetStateAndEtagAsync_CanReadState() var (state, etag) = await request.CompleteWithMessageAsync(envelope); // Get response and validate - state.Size.Should().Be("small"); - state.Color.Should().Be("yellow"); - etag.Should().Be("Test_Etag"); + state.Size.ShouldBe("small"); + state.Color.ShouldBe("yellow"); + etag.ShouldBe("Test_Etag"); } [Fact] @@ -191,7 +191,7 @@ public async Task GetStateAsync_CanReadEmptyState_ReturnsDefault() var state = await request.CompleteWithMessageAsync(envelope); // Get response and validate - state.Should().BeNull(); + state.ShouldBeNull(); } [Theory] @@ -205,15 +205,15 @@ public async Task GetStateAsync_ValidateRequest(ConsistencyMode consistencyMode, // Get Request & Validate var envelope = await request.GetRequestEnvelopeAsync(); - envelope.StoreName.Should().Be("testStore"); - envelope.Key.Should().Be("test"); - envelope.Consistency.Should().Be(expectedConsistencyMode); + envelope.StoreName.ShouldBe("testStore"); + envelope.Key.ShouldBe("test"); + envelope.Consistency.ShouldBe(expectedConsistencyMode); // Create Response & Respond var state = await request.CompleteWithMessageAsync(MakeGetStateResponse(null)); // Get response and validate - state.Should().BeNull(); + state.ShouldBeNull(); } [Fact] @@ -229,15 +229,15 @@ public async Task GetStateAndEtagAsync_ValidateRequest() // Get Request & Validate var envelope = await request.GetRequestEnvelopeAsync(); - envelope.StoreName.Should().Be("testStore"); - envelope.Key.Should().Be("test"); - envelope.Metadata.Should().BeEquivalentTo(metadata); + envelope.StoreName.ShouldBe("testStore"); + envelope.Key.ShouldBe("test"); + envelope.Metadata.ShouldBe(metadata); // Create Response & Respond var state = await request.CompleteWithMessageAsync(MakeGetStateResponse(null)); // Get response and validate - state.Should().BeNull(); + state.ShouldBeNull(); } [Fact] @@ -291,15 +291,15 @@ public async Task SaveStateAsync_CanSaveState() // Get Request and validate var envelope = await request.GetRequestEnvelopeAsync(); - envelope.StoreName.Should().Be("testStore"); - envelope.States.Count.Should().Be(1); + envelope.StoreName.ShouldBe("testStore"); + envelope.States.Count.ShouldBe(1); var state = envelope.States[0]; - state.Key.Should().Be("test"); + state.Key.ShouldBe("test"); var stateJson = state.Value.ToStringUtf8(); var stateFromRequest = JsonSerializer.Deserialize(stateJson, client.InnerClient.JsonSerializerOptions); - stateFromRequest.Size.Should().Be(widget.Size); - stateFromRequest.Color.Should().Be(widget.Color); + stateFromRequest.Size.ShouldBe(widget.Size); + stateFromRequest.Color.ShouldBe(widget.Color); } [Fact] @@ -329,20 +329,20 @@ await daprClient.SaveBulkStateAsync("testStore", // Create Response & Validate var envelope = await request.GetRequestEnvelopeAsync(); - envelope.StoreName.Should().Be("testStore"); - envelope.States.Count.Should().Be(3); + envelope.StoreName.ShouldBe("testStore"); + envelope.States.Count.ShouldBe(3); - envelope.States[0].Key.Should().Be("testKey1"); - envelope.States[0].Value.Should().Equal(ByteString.CopyFromUtf8(JsonSerializer.Serialize("testValue1"))); - envelope.States[0].Metadata.Should().ContainKey("partitionKey1"); + envelope.States[0].Key.ShouldBe("testKey1"); + envelope.States[0].Value.ShouldBe(ByteString.CopyFromUtf8(JsonSerializer.Serialize("testValue1"))); + envelope.States[0].Metadata.ShouldContainKey("partitionKey1"); - envelope.States[1].Key.Should().Be("testKey2"); - envelope.States[1].Value.Should().Equal(ByteString.CopyFromUtf8(JsonSerializer.Serialize("testValue2"))); - envelope.States[1].Metadata.Should().ContainKey("partitionKey2"); + envelope.States[1].Key.ShouldBe("testKey2"); + envelope.States[1].Value.ShouldBe(ByteString.CopyFromUtf8(JsonSerializer.Serialize("testValue2"))); + envelope.States[1].Metadata.ShouldContainKey("partitionKey2"); - envelope.States[2].Key.Should().Be("testKey3"); - envelope.States[2].Value.Should().Equal(ByteString.CopyFromUtf8(JsonSerializer.Serialize("testValue3"))); - envelope.States[2].Metadata.Should().ContainKey("partitionKey3"); + envelope.States[2].Key.ShouldBe("testKey3"); + envelope.States[2].Value.ShouldBe(ByteString.CopyFromUtf8(JsonSerializer.Serialize("testValue3"))); + envelope.States[2].Metadata.ShouldContainKey("partitionKey3"); } [Fact] @@ -374,11 +374,11 @@ public async Task SaveStateAsync_CanClearState() // Get Request and validate var envelope = await request.GetRequestEnvelopeAsync(); - envelope.StoreName.Should().Be("testStore"); - envelope.States.Count.Should().Be(1); + envelope.StoreName.ShouldBe("testStore"); + envelope.States.Count.ShouldBe(1); var state = envelope.States[0]; - state.Key.Should().Be("test"); - state.Value.Should().Equal(ByteString.Empty); + state.Key.ShouldBe("test"); + state.Value.ShouldBe(ByteString.Empty); } [Fact] @@ -453,34 +453,34 @@ public async Task ExecuteStateTransactionAsync_CanSaveState() // Get Request and validate var envelope = await request.GetRequestEnvelopeAsync(); - envelope.StoreName.Should().Be("testStore"); - envelope.Operations.Count.Should().Be(3); + envelope.StoreName.ShouldBe("testStore"); + envelope.Operations.Count.ShouldBe(3); var req1 = envelope.Operations[0]; - req1.Request.Key.Should().Be("stateKey1"); - req1.OperationType.Should().Be(StateOperationType.Upsert.ToString().ToLower()); + req1.Request.Key.ShouldBe("stateKey1"); + req1.OperationType.ShouldBe(StateOperationType.Upsert.ToString().ToLower()); var valueJson1 = req1.Request.Value.ToStringUtf8(); var value1 = JsonSerializer.Deserialize(valueJson1, client.InnerClient.JsonSerializerOptions); - value1.Size.Should().Be(stateValue1.Size); - value1.Color.Should().Be(stateValue1.Color); - req1.Request.Etag.Value.Should().Be("testEtag"); - req1.Request.Metadata.Count.Should().Be(1); - req1.Request.Metadata["a"].Should().Be("b"); - req1.Request.Options.Concurrency.Should().Be(StateConcurrency.ConcurrencyLastWrite); + value1.Size.ShouldBe(stateValue1.Size); + value1.Color.ShouldBe(stateValue1.Color); + req1.Request.Etag.Value.ShouldBe("testEtag"); + req1.Request.Metadata.Count.ShouldBe(1); + req1.Request.Metadata["a"].ShouldBe("b"); + req1.Request.Options.Concurrency.ShouldBe(StateConcurrency.ConcurrencyLastWrite); var req2 = envelope.Operations[1]; - req2.Request.Key.Should().Be("stateKey2"); - req2.OperationType.Should().Be(StateOperationType.Delete.ToString().ToLower()); + req2.Request.Key.ShouldBe("stateKey2"); + req2.OperationType.ShouldBe(StateOperationType.Delete.ToString().ToLower()); var valueJson2 = req2.Request.Value.ToStringUtf8(); var value2 = JsonSerializer.Deserialize(valueJson2, client.InnerClient.JsonSerializerOptions); - value2.Should().Be(100); + value2.ShouldBe(100); var req3 = envelope.Operations[2]; - req3.Request.Key.Should().Be("stateKey3"); - req3.OperationType.Should().Be(StateOperationType.Upsert.ToString().ToLower()); + req3.Request.Key.ShouldBe("stateKey3"); + req3.OperationType.ShouldBe(StateOperationType.Upsert.ToString().ToLower()); var valueJson3 = req3.Request.Value.ToStringUtf8(); var value3 = JsonSerializer.Deserialize(valueJson3, client.InnerClient.JsonSerializerOptions); - value3.Should().Be("teststring"); + value3.ShouldBe("teststring"); } [Fact] @@ -541,8 +541,8 @@ public async Task DeleteStateAsync_CanDeleteState() request.Dismiss(); var envelope = await request.GetRequestEnvelopeAsync(); - envelope.StoreName.Should().Be("testStore"); - envelope.Key.Should().Be("test"); + envelope.StoreName.ShouldBe("testStore"); + envelope.Key.ShouldBe("test"); } [Fact] @@ -590,8 +590,8 @@ public async Task GetStateEntryAsync_CanReadState() var state = await request.CompleteWithMessageAsync(envelope); // Get response and validate - state.Value.Size.Should().Be("small"); - state.Value.Color.Should().Be("yellow"); + state.Value.Size.ShouldBe("small"); + state.Value.Color.ShouldBe("yellow"); } [Fact] @@ -605,8 +605,8 @@ public async Task GetStateEntryAsync_CanReadEmptyState_ReturnsDefault() var envelope = MakeGetStateResponse(null); var state = await request.CompleteWithMessageAsync(envelope); - state.Key.Should().Be("test"); - state.Value.Should().BeNull(); + state.Key.ShouldBe("test"); + state.Value.ShouldBeNull(); } [Fact] @@ -620,9 +620,9 @@ public async Task GetStateEntryAsync_CanSaveState() var data = new Widget() { Size = "small", Color = "yellow", }; var state = await request.CompleteWithMessageAsync(MakeGetStateResponse(data)); - state.Key.Should().Be("test"); - state.Value.Size.Should().Be("small"); - state.Value.Color.Should().Be("yellow"); + state.Key.ShouldBe("test"); + state.Value.Size.ShouldBe("small"); + state.Value.Color.ShouldBe("yellow"); // Modify the state and save it state.Value.Color = "green"; @@ -637,15 +637,15 @@ public async Task GetStateEntryAsync_CanSaveState() // Get Request and validate var envelope = await request2.GetRequestEnvelopeAsync(); - envelope.StoreName.Should().Be("testStore"); - envelope.States.Count.Should().Be(1); + envelope.StoreName.ShouldBe("testStore"); + envelope.States.Count.ShouldBe(1); var requestState = envelope.States[0]; - requestState.Key.Should().Be("test"); + requestState.Key.ShouldBe("test"); var stateJson = requestState.Value.ToStringUtf8(); var stateFromRequest = JsonSerializer.Deserialize(stateJson, client.InnerClient.JsonSerializerOptions); - stateFromRequest.Size.Should().Be("small"); - stateFromRequest.Color.Should().Be("green"); + stateFromRequest.Size.ShouldBe("small"); + stateFromRequest.Color.ShouldBe("green"); } [Fact] @@ -659,9 +659,9 @@ public async Task GetStateEntryAsync_CanDeleteState() var data = new Widget() { Size = "small", Color = "yellow", }; var state = await request.CompleteWithMessageAsync(MakeGetStateResponse(data)); - state.Key.Should().Be("test"); - state.Value.Size.Should().Be("small"); - state.Value.Color.Should().Be("yellow"); + state.Key.ShouldBe("test"); + state.Value.Size.ShouldBe("small"); + state.Value.Color.ShouldBe("yellow"); state.Value.Color = "green"; var request2 = await client.CaptureGrpcRequestAsync(async daprClient => @@ -673,8 +673,8 @@ public async Task GetStateEntryAsync_CanDeleteState() // Get Request and validate var envelope = await request.GetRequestEnvelopeAsync(); - envelope.StoreName.Should().Be("testStore"); - envelope.Key.Should().Be("test"); + envelope.StoreName.ShouldBe("testStore"); + envelope.Key.ShouldBe("test"); } @@ -713,22 +713,22 @@ public async Task SaveStateAsync_ValidateOptions( // Get Request and validate var envelope = await request.GetRequestEnvelopeAsync(); - envelope.StoreName.Should().Be("testStore"); - envelope.States.Count.Should().Be(1); + envelope.StoreName.ShouldBe("testStore"); + envelope.States.Count.ShouldBe(1); var state = envelope.States[0]; - state.Key.Should().Be("test"); - state.Metadata.Count.Should().Be(2); - state.Metadata.Keys.Contains("key1").Should().BeTrue(); - state.Metadata.Keys.Contains("key2").Should().BeTrue(); - state.Metadata["key1"].Should().Be("value1"); - state.Metadata["key2"].Should().Be("value2"); - state.Options.Concurrency.Should().Be(expectedConcurrency); - state.Options.Consistency.Should().Be(expectedConsistency); + state.Key.ShouldBe("test"); + state.Metadata.Count.ShouldBe(2); + state.Metadata.Keys.Contains("key1").ShouldBeTrue(); + state.Metadata.Keys.Contains("key2").ShouldBeTrue(); + state.Metadata["key1"].ShouldBe("value1"); + state.Metadata["key2"].ShouldBe("value2"); + state.Options.Concurrency.ShouldBe(expectedConcurrency); + state.Options.Consistency.ShouldBe(expectedConsistency); var stateJson = state.Value.ToStringUtf8(); var stateFromRequest = JsonSerializer.Deserialize(stateJson, client.InnerClient.JsonSerializerOptions); - stateFromRequest.Size.Should().Be(widget.Size); - stateFromRequest.Color.Should().Be(widget.Color); + stateFromRequest.Size.ShouldBe(widget.Size); + stateFromRequest.Color.ShouldBe(widget.Color); } [Theory] @@ -762,22 +762,22 @@ public async Task TrySaveStateAsync_ValidateOptions( // Get Request and validate var envelope = await request.GetRequestEnvelopeAsync(); - envelope.StoreName.Should().Be("testStore"); - envelope.States.Count.Should().Be(1); + envelope.StoreName.ShouldBe("testStore"); + envelope.States.Count.ShouldBe(1); var state = envelope.States[0]; - state.Etag.Value.Should().Be("Test_Etag"); - state.Metadata.Count.Should().Be(2); - state.Metadata.Keys.Contains("key1").Should().BeTrue(); - state.Metadata.Keys.Contains("key2").Should().BeTrue(); - state.Metadata["key1"].Should().Be("value1"); - state.Metadata["key2"].Should().Be("value2"); - state.Options.Concurrency.Should().Be(expectedConcurrency); - state.Options.Consistency.Should().Be(expectedConsistency); + state.Etag.Value.ShouldBe("Test_Etag"); + state.Metadata.Count.ShouldBe(2); + state.Metadata.Keys.Contains("key1").ShouldBeTrue(); + state.Metadata.Keys.Contains("key2").ShouldBeTrue(); + state.Metadata["key1"].ShouldBe("value1"); + state.Metadata["key2"].ShouldBe("value2"); + state.Options.Concurrency.ShouldBe(expectedConcurrency); + state.Options.Consistency.ShouldBe(expectedConsistency); var stateJson = state.Value.ToStringUtf8(); var stateFromRequest = JsonSerializer.Deserialize(stateJson, client.InnerClient.JsonSerializerOptions); - stateFromRequest.Size.Should().Be(widget.Size); - stateFromRequest.Color.Should().Be(widget.Color); + stateFromRequest.Size.ShouldBe(widget.Size); + stateFromRequest.Color.ShouldBe(widget.Color); } [Fact] @@ -827,8 +827,7 @@ public async Task TrySaveStateAsync_NullEtagThrowsArgumentException() await client.CallStateApi() .Build(); - await FluentActions.Awaiting(async () => await client.DaprClient.TrySaveStateAsync("test", "test", "testValue", null)) - .Should().ThrowAsync(); + await Should.ThrowAsync(async () => await client.DaprClient.TrySaveStateAsync("test", "test", "testValue", null)); } [Fact] @@ -877,8 +876,7 @@ public async Task TryDeleteStateAsync_NullEtagThrowsArgumentException() await client.CallStateApi() .Build(); - await FluentActions.Awaiting(async () => await client.DaprClient.TryDeleteStateAsync("test", "test", null)) - .Should().ThrowAsync(); + await Should.ThrowAsync(async () => await client.DaprClient.TryDeleteStateAsync("test", "test", null)); } [Fact] @@ -943,10 +941,10 @@ public async Task DeleteStateAsync_ValidateOptions( // Get Request and validate var envelope = await request.GetRequestEnvelopeAsync(); - envelope.StoreName.Should().Be("testStore"); - envelope.Key.Should().Be("test"); - envelope.Options.Concurrency.Should().Be(expectedConcurrency); - envelope.Options.Consistency.Should().Be(expectedConsistency); + envelope.StoreName.ShouldBe("testStore"); + envelope.Key.ShouldBe("test"); + envelope.Options.Concurrency.ShouldBe(expectedConcurrency); + envelope.Options.Consistency.ShouldBe(expectedConsistency); } @@ -975,11 +973,11 @@ public async Task TryDeleteStateAsync_ValidateOptions( // Get Request and validate var envelope = await request.GetRequestEnvelopeAsync(); - envelope.StoreName.Should().Be("testStore"); - envelope.Key.Should().Be("test"); - envelope.Etag.Value.Should().Be("Test_Etag"); - envelope.Options.Concurrency.Should().Be(expectedConcurrency); - envelope.Options.Consistency.Should().Be(expectedConsistency); + envelope.StoreName.ShouldBe("testStore"); + envelope.Key.ShouldBe("test"); + envelope.Etag.Value.ShouldBe("Test_Etag"); + envelope.Options.Concurrency.ShouldBe(expectedConcurrency); + envelope.Options.Consistency.ShouldBe(expectedConsistency); } [Fact] @@ -1003,10 +1001,10 @@ public async Task DeleteBulkStateAsync_ValidateRequest() // Create Response & Validate var envelope = await request.GetRequestEnvelopeAsync(); - envelope.StoreName.Should().Be("testStore"); - envelope.States.Count.Should().Be(1); - envelope.States[0].Key.Should().Be(key); - envelope.States[0].Metadata.Should().ContainKey("partitionKey"); + envelope.StoreName.ShouldBe("testStore"); + envelope.States.Count.ShouldBe(1); + envelope.States[0].Key.ShouldBe(key); + envelope.States[0].Metadata.ShouldContainKey("partitionKey"); } [Fact] @@ -1019,9 +1017,9 @@ public async Task QueryStateAsync_ValidateResult() // Validate request. var envelope = await request.GetRequestEnvelopeAsync(); - envelope.StoreName.Should().Be("testStore"); - envelope.Query.Should().Be(queryJson); - envelope.Metadata.Should().BeEmpty(); + envelope.StoreName.ShouldBe("testStore"); + envelope.Query.ShouldBe(queryJson); + envelope.Metadata.ShouldBeEmpty(); // Validate response. var testData = new Widget() { Color = "Green", Size = "Small" }; @@ -1029,11 +1027,11 @@ public async Task QueryStateAsync_ValidateResult() wireResponse.Results.Add(MakeQueryStateItem("test", testData, "an etag")); var response = await request.CompleteWithMessageAsync(wireResponse); - response.Results.Count.Should().Be(1); - response.Results[0].Key.Should().Be("test"); - response.Results[0].Data.Should().Be(testData); - response.Results[0].ETag.Should().Be("an etag"); - response.Results[0].Error.Should().BeNullOrEmpty(); + response.Results.Count.ShouldBe(1); + response.Results[0].Key.ShouldBe("test"); + response.Results[0].Data.ShouldBe(testData); + response.Results[0].ETag.ShouldBe("an etag"); + response.Results[0].Error.ShouldBeNullOrEmpty(); } [Fact] @@ -1046,9 +1044,9 @@ public async Task QueryStateAsync_EncountersError_ValidatePartialResult() // Validate request. var envelope = await request.GetRequestEnvelopeAsync(); - envelope.StoreName.Should().Be("testStore"); - envelope.Query.Should().Be(queryJson); - envelope.Metadata.Should().BeEmpty(); + envelope.StoreName.ShouldBe("testStore"); + envelope.Query.ShouldBe(queryJson); + envelope.Metadata.ShouldBeEmpty(); // Validate response, we expect to only get the first object as the 2nd will present an error. var testData1 = new Widget() { Color = "Green", Size = "Small" }; @@ -1061,21 +1059,21 @@ public async Task QueryStateAsync_EncountersError_ValidatePartialResult() wireResponse.Results.Add(MakeQueryStateItem("test3", testData3)); var ex = await Assert.ThrowsAsync>(() => request.CompleteWithMessageAsync(wireResponse)); - ex.Message.Should().Be("Encountered an error while processing state query results."); + ex.Message.ShouldBe("Encountered an error while processing state query results."); var response = ex.Response; - response.Results.Count.Should().Be(2); - response.Results[0].Key.Should().Be("test1"); - response.Results[0].Data.Should().Be(testData1); - response.Results[0].ETag.Should().BeNullOrEmpty(); - response.Results[0].Error.Should().BeNullOrEmpty(); - response.Results[1].Key.Should().Be("test3"); - response.Results[1].Data.Should().Be(testData3); - response.Results[1].ETag.Should().BeNullOrEmpty(); - response.Results[1].Error.Should().BeNullOrEmpty(); + response.Results.Count.ShouldBe(2); + response.Results[0].Key.ShouldBe("test1"); + response.Results[0].Data.ShouldBe(testData1); + response.Results[0].ETag.ShouldBeNullOrEmpty(); + response.Results[0].Error.ShouldBeNullOrEmpty(); + response.Results[1].Key.ShouldBe("test3"); + response.Results[1].Data.ShouldBe(testData3); + response.Results[1].ETag.ShouldBeNullOrEmpty(); + response.Results[1].Error.ShouldBeNullOrEmpty(); var failedKeys = ex.FailedKeys; - failedKeys.Count.Should().Be(1); - failedKeys[0].Should().Be("test2"); + failedKeys.Count.ShouldBe(1); + failedKeys[0].ShouldBe("test2"); } private Autogenerated.GetStateResponse MakeGetStateResponse(T state, string etag = null) @@ -1157,20 +1155,20 @@ public async Task SaveByteStateAsync_ValidateOptions( // Get Request and validate var envelope = await request.GetRequestEnvelopeAsync(); - envelope.StoreName.Should().Be("testStore"); - envelope.States.Count.Should().Be(1); + envelope.StoreName.ShouldBe("testStore"); + envelope.States.Count.ShouldBe(1); var state = envelope.States[0]; - state.Key.Should().Be("test"); - state.Metadata.Count.Should().Be(2); - state.Metadata.Keys.Contains("key1").Should().BeTrue(); - state.Metadata.Keys.Contains("key2").Should().BeTrue(); - state.Metadata["key1"].Should().Be("value1"); - state.Metadata["key2"].Should().Be("value2"); - state.Options.Concurrency.Should().Be(expectedConcurrency); - state.Options.Consistency.Should().Be(expectedConsistency); + state.Key.ShouldBe("test"); + state.Metadata.Count.ShouldBe(2); + state.Metadata.Keys.Contains("key1").ShouldBeTrue(); + state.Metadata.Keys.Contains("key2").ShouldBeTrue(); + state.Metadata["key1"].ShouldBe("value1"); + state.Metadata["key2"].ShouldBe("value2"); + state.Options.Concurrency.ShouldBe(expectedConcurrency); + state.Options.Consistency.ShouldBe(expectedConsistency); var stateBinaryData = state.Value.ToStringUtf8(); - stateBinaryData.Should().Be(data); + stateBinaryData.ShouldBe(data); } [Fact] @@ -1189,13 +1187,13 @@ public async Task SaveByteStateAsync_CanSaveState() // Get Request and validate var envelope = await request.GetRequestEnvelopeAsync(); - envelope.StoreName.Should().Be("testStore"); - envelope.States.Count.Should().Be(1); + envelope.StoreName.ShouldBe("testStore"); + envelope.States.Count.ShouldBe(1); var state = envelope.States[0]; - state.Key.Should().Be("test"); + state.Key.ShouldBe("test"); var stateBinaryData = state.Value.ToStringUtf8(); - stateBinaryData.Should().Be(data); + stateBinaryData.ShouldBe(data); } [Fact] @@ -1213,11 +1211,11 @@ public async Task SaveByteStateAsync_CanClearState() // Get Request and validate var envelope = await request.GetRequestEnvelopeAsync(); - envelope.StoreName.Should().Be("testStore"); - envelope.States.Count.Should().Be(1); + envelope.StoreName.ShouldBe("testStore"); + envelope.States.Count.ShouldBe(1); var state = envelope.States[0]; - state.Key.Should().Be("test"); - state.Value.Should().Equal(ByteString.Empty); + state.Key.ShouldBe("test"); + state.Value.ShouldBe(ByteString.Empty); } [Fact] @@ -1265,20 +1263,20 @@ public async Task TrySaveByteStateAsync_ValidateOptions( // Get Request and validate var envelope = await request.GetRequestEnvelopeAsync(); - envelope.StoreName.Should().Be("testStore"); - envelope.States.Count.Should().Be(1); + envelope.StoreName.ShouldBe("testStore"); + envelope.States.Count.ShouldBe(1); var state = envelope.States[0]; - state.Etag.Value.Should().Be("Test_Etag"); - state.Metadata.Count.Should().Be(2); - state.Metadata.Keys.Contains("key1").Should().BeTrue(); - state.Metadata.Keys.Contains("key2").Should().BeTrue(); - state.Metadata["key1"].Should().Be("value1"); - state.Metadata["key2"].Should().Be("value2"); - state.Options.Concurrency.Should().Be(expectedConcurrency); - state.Options.Consistency.Should().Be(expectedConsistency); + state.Etag.Value.ShouldBe("Test_Etag"); + state.Metadata.Count.ShouldBe(2); + state.Metadata.Keys.Contains("key1").ShouldBeTrue(); + state.Metadata.Keys.Contains("key2").ShouldBeTrue(); + state.Metadata["key1"].ShouldBe("value1"); + state.Metadata["key2"].ShouldBe("value2"); + state.Options.Concurrency.ShouldBe(expectedConcurrency); + state.Options.Consistency.ShouldBe(expectedConsistency); var stateBinaryData = state.Value.ToStringUtf8(); - stateBinaryData.Should().Be(data); + stateBinaryData.ShouldBe(data); } [Fact] @@ -1332,8 +1330,7 @@ public async Task TrySaveByteStateAsync_NullEtagThrowsArgumentException() var response = client.CallStateApi() .Build(); - await FluentActions.Awaiting(async () => await client.DaprClient.TrySaveByteStateAsync("test", "test", stateBytes.AsMemory(), null)) - .Should().ThrowAsync(); + await Should.ThrowAsync(async () => await client.DaprClient.TrySaveByteStateAsync("test", "test", stateBytes.AsMemory(), null)); } [Fact] @@ -1365,7 +1362,7 @@ public async Task GetByteStateAsync_CanReadEmptyState_ReturnsDefault() var state = await request.CompleteWithMessageAsync(envelope); // Get response and validate - state.ToArray().Should().BeNullOrEmpty(); + state.ToArray().ShouldBeEmpty(); } [Theory] @@ -1379,15 +1376,15 @@ public async Task GetByteStateAsync_ValidateRequest(ConsistencyMode consistencyM // Get Request & Validate var envelope = await request.GetRequestEnvelopeAsync(); - envelope.StoreName.Should().Be("testStore"); - envelope.Key.Should().Be("test"); - envelope.Consistency.Should().Be(expectedConsistencyMode); + envelope.StoreName.ShouldBe("testStore"); + envelope.Key.ShouldBe("test"); + envelope.Consistency.ShouldBe(expectedConsistencyMode); var binaryData = Encoding.ASCII.GetBytes("test data"); // Create Response & Respond var state = await request.CompleteWithMessageAsync(MakeGetByteStateResponse(binaryData.AsMemory())); var stateStr = ByteString.CopyFrom(state.Span).ToByteArray(); // Get response and validate - stateStr.Should().BeEquivalentTo(binaryData); + stateStr.ShouldBeEquivalentTo(binaryData); } [Fact] @@ -1400,18 +1397,17 @@ public async Task GetByteStateAndEtagAsync_ValidateRequest() { "partitionKey", "mypartition" } }; var request = await client.CaptureGrpcRequestAsync(async daprClient => await daprClient.GetByteStateAndETagAsync("testStore", "test", metadata: metadata)); - // Get Request & Validate var envelope = await request.GetRequestEnvelopeAsync(); - envelope.StoreName.Should().Be("testStore"); - envelope.Key.Should().Be("test"); - envelope.Metadata.Should().BeEquivalentTo(metadata); + envelope.StoreName.ShouldBe("testStore"); + envelope.Key.ShouldBe("test"); + envelope.Metadata.ShouldBe(metadata); var binaryData = Encoding.ASCII.GetBytes("test data"); // Create Response & Respond var (state, etag) = await request.CompleteWithMessageAsync((MakeGetByteStateResponse(binaryData.AsMemory()))); var stateStr = ByteString.CopyFrom(state.Span).ToByteArray(); // Get response and validate - stateStr.Should().BeEquivalentTo(binaryData); + stateStr.ShouldBe(binaryData); } [Fact] @@ -1442,8 +1438,8 @@ public async Task GetByteStateAndEtagAsync_CanReadState() var (state, etag) = await request.CompleteWithMessageAsync(envelope); var stateStr = ByteString.CopyFrom(state.Span).ToByteArray(); // Get response and validate - stateStr.Should().BeEquivalentTo(binaryData); - etag.Should().Be("Test_Etag"); + stateStr.ShouldBeEquivalentTo(binaryData); + etag.ShouldBe("Test_Etag"); } [Fact] diff --git a/test/Dapr.Client.Test/TryLockResponseTest.cs b/test/Dapr.Client.Test/TryLockResponseTest.cs index 3420dc233..f9b6f5247 100644 --- a/test/Dapr.Client.Test/TryLockResponseTest.cs +++ b/test/Dapr.Client.Test/TryLockResponseTest.cs @@ -14,7 +14,7 @@ using System.Threading.Tasks; using Autogenerated = Dapr.Client.Autogen.Grpc.v1; using Xunit; -using FluentAssertions; +using Shouldly; using System; namespace Dapr.Client.Test @@ -37,10 +37,10 @@ public async Task TryLockAsync_WithAllValues_ValidateRequest() // Get Request and validate var envelope = await request.GetRequestEnvelopeAsync(); - envelope.StoreName.Should().Be("redis"); - envelope.ResourceId.Should().Be("resourceId"); - envelope.LockOwner.Should().Be("owner1"); - envelope.ExpiryInSeconds.Should().Be(1000); + envelope.StoreName.ShouldBe("redis"); + envelope.ResourceId.ShouldBe("resourceId"); + envelope.LockOwner.ShouldBe("owner1"); + envelope.ExpiryInSeconds.ShouldBe(1000); // Get response and validate var invokeResponse = new Autogenerated.TryLockResponse{ @@ -56,16 +56,16 @@ public async Task TryLockAsync_WithAllValues_ValidateRequest() return await daprClient.Unlock(storeName, resourceId, lockOwner); }); var unlockEnvelope = await unlockRequest.GetRequestEnvelopeAsync(); - unlockEnvelope.StoreName.Should().Be("redis"); - unlockEnvelope.ResourceId.Should().Be("resourceId"); - unlockEnvelope.LockOwner.Should().Be("owner1"); + unlockEnvelope.StoreName.ShouldBe("redis"); + unlockEnvelope.ResourceId.ShouldBe("resourceId"); + unlockEnvelope.LockOwner.ShouldBe("owner1"); var invokeUnlockResponse = new Autogenerated.UnlockResponse{ Status = Autogenerated.UnlockResponse.Types.Status.LockDoesNotExist }; var domainUnlockResponse = await unlockRequest.CompleteWithMessageAsync(invokeUnlockResponse); - domainUnlockResponse.status.Should().Be(LockStatus.LockDoesNotExist); + domainUnlockResponse.status.ShouldBe(LockStatus.LockDoesNotExist); } } -} \ No newline at end of file +} diff --git a/test/Dapr.Client.Test/TypeConvertersTest.cs b/test/Dapr.Client.Test/TypeConvertersTest.cs index 1e6b57eab..ff73de4cb 100644 --- a/test/Dapr.Client.Test/TypeConvertersTest.cs +++ b/test/Dapr.Client.Test/TypeConvertersTest.cs @@ -14,7 +14,7 @@ namespace Dapr.Client.Test { using System.Text.Json; - using FluentAssertions; + using Shouldly; using Xunit; public class TypeConvertersTest @@ -32,9 +32,9 @@ public void AnyConversion_JSON_Serialization_Deserialization() var any = TypeConverters.ToJsonAny(response, options); var type = TypeConverters.FromJsonAny(any, options); - type.Should().BeEquivalentTo(response); - any.TypeUrl.Should().Be(string.Empty); - type.Name.Should().Be("test"); + type.ShouldBeEquivalentTo(response); + any.TypeUrl.ShouldBe(string.Empty); + type.Name.ShouldBe("test"); } private class Response diff --git a/test/Dapr.Common.Test/Dapr.Common.Test.csproj b/test/Dapr.Common.Test/Dapr.Common.Test.csproj index 6e34c3a7a..22120719c 100644 --- a/test/Dapr.Common.Test/Dapr.Common.Test.csproj +++ b/test/Dapr.Common.Test/Dapr.Common.Test.csproj @@ -5,7 +5,6 @@ runtime; build; native; contentfiles; analyzers; buildtransitive all - diff --git a/test/Dapr.E2E.Test/Actors/E2ETests.WeaklyTypedTests.cs b/test/Dapr.E2E.Test/Actors/E2ETests.WeaklyTypedTests.cs index b250d731e..5518f32b8 100644 --- a/test/Dapr.E2E.Test/Actors/E2ETests.WeaklyTypedTests.cs +++ b/test/Dapr.E2E.Test/Actors/E2ETests.WeaklyTypedTests.cs @@ -17,7 +17,7 @@ namespace Dapr.E2E.Test using System.Threading.Tasks; using Dapr.Actors; using Dapr.E2E.Test.Actors.WeaklyTypedTesting; - using FluentAssertions; + using Shouldly; using Xunit; public partial class E2ETests : IAsyncLifetime @@ -34,7 +34,7 @@ public async Task WeaklyTypedActorCanReturnPolymorphicResponse() var result = await proxy.InvokeMethodAsync(nameof(IWeaklyTypedTestingActor.GetPolymorphicResponse)); - result.Should().BeOfType().Which.DerivedProperty.Should().NotBeNullOrWhiteSpace(); + result.ShouldBeOfType().DerivedProperty.ShouldNotBeNullOrWhiteSpace(); } #else [Fact] @@ -48,7 +48,7 @@ public async Task WeaklyTypedActorCanReturnDerivedResponse() var result = await proxy.InvokeMethodAsync(nameof(IWeaklyTypedTestingActor.GetPolymorphicResponse)); - result.Should().BeOfType().Which.DerivedProperty.Should().NotBeNullOrWhiteSpace(); + result.ShouldBeOfType().DerivedProperty.ShouldNotBeNullOrWhiteSpace(); } #endif [Fact] @@ -62,7 +62,7 @@ public async Task WeaklyTypedActorCanReturnNullResponse() var result = await proxy.InvokeMethodAsync(nameof(IWeaklyTypedTestingActor.GetNullResponse)); - result.Should().BeNull(); + result.ShouldBeNull(); } } } diff --git a/test/Dapr.E2E.Test/Dapr.E2E.Test.csproj b/test/Dapr.E2E.Test/Dapr.E2E.Test.csproj index fc92396a6..503792239 100644 --- a/test/Dapr.E2E.Test/Dapr.E2E.Test.csproj +++ b/test/Dapr.E2E.Test/Dapr.E2E.Test.csproj @@ -1,10 +1,10 @@  - + all diff --git a/test/Dapr.Extensions.Configuration.Test/Dapr.Extensions.Configuration.Test.csproj b/test/Dapr.Extensions.Configuration.Test/Dapr.Extensions.Configuration.Test.csproj index ef6cfbcee..3900bd7e3 100644 --- a/test/Dapr.Extensions.Configuration.Test/Dapr.Extensions.Configuration.Test.csproj +++ b/test/Dapr.Extensions.Configuration.Test/Dapr.Extensions.Configuration.Test.csproj @@ -5,9 +5,9 @@ runtime; build; native; contentfiles; analyzers; buildtransitive all - + all diff --git a/test/Dapr.Extensions.Configuration.Test/DaprSecretStoreConfigurationProviderTest.cs b/test/Dapr.Extensions.Configuration.Test/DaprSecretStoreConfigurationProviderTest.cs index fd323f989..d92fc46b4 100644 --- a/test/Dapr.Extensions.Configuration.Test/DaprSecretStoreConfigurationProviderTest.cs +++ b/test/Dapr.Extensions.Configuration.Test/DaprSecretStoreConfigurationProviderTest.cs @@ -16,11 +16,10 @@ using System.Net; using System.Threading.Tasks; using Dapr.Client; -using Dapr; -using FluentAssertions; using Grpc.Net.Client; using Microsoft.Extensions.Configuration; using Moq; +using Shouldly; using Xunit; using Autogenerated = Dapr.Client.Autogen.Grpc.v1; @@ -163,7 +162,7 @@ public void LoadSecrets_FromSecretStoreThatReturnsOneValue() .AddDaprSecretStore(storeName, secretDescriptors, daprClient.Object) .Build(); - config["secretName"].Should().Be("secret"); + config["secretName"].ShouldBe("secret"); } [Fact] @@ -195,8 +194,8 @@ public void LoadSecrets_FromSecretStoreThatCanReturnsMultipleValues() .AddDaprSecretStore(storeName, secretDescriptors, daprClient.Object) .Build(); - config[firstSecretKey].Should().Be(firstSecretValue); - config[secondSecretKey].Should().Be(secondSecretValue); + config[firstSecretKey].ShouldBe(firstSecretValue); + config[secondSecretKey].ShouldBe(secondSecretValue); } [Fact] @@ -224,8 +223,8 @@ public void LoadSecrets_FromSecretStoreThatCanReturnsMultivaluedValues() .AddDaprSecretStore(storeName, secretDescriptors, daprClient.Object) .Build(); - config[firstSecretKey].Should().Be(firstSecretValue); - config[secondSecretKey].Should().Be(secondSecretValue); + config[firstSecretKey].ShouldBe(firstSecretValue); + config[secondSecretKey].ShouldBe(secondSecretValue); } [Fact] @@ -252,7 +251,7 @@ public void LoadSecrets_FromSecretStoreWithADifferentSecretKeyAndName() .AddDaprSecretStore(storeName, secretDescriptors, daprClient.Object) .Build(); - config[secretName].Should().Be(secretValue); + config[secretName].ShouldBe(secretValue); } [Fact] @@ -282,7 +281,7 @@ public void LoadSecrets_FromSecretStoreNotRequiredAndDoesNotExist_ShouldNotThrow .AddDaprSecretStore(storeName, secretDescriptors, daprClient) .Build(); - config[secretName].Should().BeNull(); + config[secretName].ShouldBeNull(); } [Fact] @@ -415,7 +414,7 @@ public void BulkLoadSecrets_FromSecretStoreThatReturnsOneValue() .AddDaprSecretStore("store", daprClient) .Build(); - config["secretName"].Should().Be("secret"); + config["secretName"].ShouldBe("secret"); } [Fact] @@ -442,8 +441,8 @@ public void BulkLoadSecrets_FromSecretStoreThatCanReturnsMultipleValues() .AddDaprSecretStore("store", daprClient) .Build(); - config["first_secret"].Should().Be("secret1"); - config["second_secret"].Should().Be("secret2"); + config["first_secret"].ShouldBe("secret1"); + config["second_secret"].ShouldBe("secret2"); } [Fact] @@ -468,7 +467,7 @@ public void LoadSecrets_FromSecretStoreThatReturnsNonNormalizedKey() .AddDaprSecretStore("store", new DaprSecretDescriptor[] { new DaprSecretDescriptor("secretName__value") }, daprClient) .Build(); - config["secretName:value"].Should().Be("secret"); + config["secretName:value"].ShouldBe("secret"); } [Fact] @@ -494,7 +493,7 @@ public void BulkLoadSecrets_FromSecretStoreThatReturnsNonNormalizedKey() .AddDaprSecretStore("store", daprClient) .Build(); - config["first_secret:value"].Should().Be("secret1"); + config["first_secret:value"].ShouldBe("secret1"); } [Fact] @@ -525,7 +524,7 @@ public void LoadSecrets_FromSecretStoreThatReturnsNonNormalizedKeyDisabledNormal }) .Build(); - config["secretName__value"].Should().Be("secret"); + config["secretName__value"].ShouldBe("secret"); } [Fact] @@ -556,7 +555,7 @@ public void BulkLoadSecrets_FromSecretStoreThatReturnsNonNormalizedKeyDisabledNo }) .Build(); - config["first_secret__value"].Should().Be("secret1"); + config["first_secret__value"].ShouldBe("secret1"); } [Fact] @@ -590,7 +589,7 @@ public void LoadSecrets_FromSecretStoreThatReturnsCustomDelimitedKey() }) .Build(); - config["secretName:value"].Should().Be("secret"); + config["secretName:value"].ShouldBe("secret"); } [Fact] @@ -624,7 +623,7 @@ public void LoadSecrets_FromSecretStoreThatReturnsCustomDelimitedKey_NullDelimit }) .Build(); - config["secretName--value"].Should().Be("secret"); + config["secretName--value"].ShouldBe("secret"); } [Fact] @@ -658,7 +657,7 @@ public void LoadSecrets_FromSecretStoreThatReturnsCustomDelimitedKey_EmptyDelimi }) .Build(); - config["secretName--value"].Should().Be("secret"); + config["secretName--value"].ShouldBe("secret"); } [Fact] @@ -714,8 +713,8 @@ await SendResponseWithSecrets(new Dictionary() }) .Build(); - config["secretName:value"].Should().Be("secret"); - config["otherSecretName:value"].Should().Be("secret"); + config["secretName:value"].ShouldBe("secret"); + config["otherSecretName:value"].ShouldBe("secret"); } [Fact] @@ -743,7 +742,7 @@ public void BulkLoadSecrets_FromSecretStoreThatReturnsCustomDelimitedKey() .AddDaprSecretStore("store", daprClient, new[] { "--" }) .Build(); - config["first_secret:value"].Should().Be("secret1"); + config["first_secret:value"].ShouldBe("secret1"); } [Fact] @@ -772,8 +771,8 @@ public void BulkLoadSecrets_FromSecretStoreThatReturnsDifferentCustomDelimitedKe .AddDaprSecretStore("store", daprClient, new[] { "--", "≡" }) .Build(); - config["first_secret:value"].Should().Be("secret1"); - config["second_secret:value"].Should().Be("secret2"); + config["first_secret:value"].ShouldBe("secret1"); + config["second_secret:value"].ShouldBe("secret2"); } [Fact] @@ -803,9 +802,9 @@ public void BulkLoadSecrets_FromSecretStoreThatReturnsPlainAndCustomDelimitedKey .AddDaprSecretStore("store", daprClient, new[] { "--", "≡" }) .Build(); - config["first_secret:value"].Should().Be("secret1"); - config["second_secret:value"].Should().Be("secret2"); - config["third_secret:value"].Should().Be("secret3"); + config["first_secret:value"].ShouldBe("secret1"); + config["second_secret:value"].ShouldBe("secret2"); + config["third_secret:value"].ShouldBe("secret3"); } [Fact] @@ -840,7 +839,7 @@ public void LoadSecrets_FromSecretStoreThatReturnsCustomDelimitedKeyDisabledNorm }) .Build(); - config["secretName--value"].Should().Be("secret"); + config["secretName--value"].ShouldBe("secret"); } [Fact] @@ -874,7 +873,7 @@ public void BulkLoadSecrets_FromSecretStoreThatReturnsCustomDelimitedKeyDisabled }) .Build(); - config["first_secret--value"].Should().Be("secret1"); + config["first_secret--value"].ShouldBe("secret1"); } [Fact] diff --git a/test/Dapr.Messaging.Test/Extensions/PublishSubscribeServiceCollectionExtensionsTests.cs b/test/Dapr.Messaging.Test/Extensions/PublishSubscribeServiceCollectionExtensionsTests.cs index d8e218d52..e51aa8374 100644 --- a/test/Dapr.Messaging.Test/Extensions/PublishSubscribeServiceCollectionExtensionsTests.cs +++ b/test/Dapr.Messaging.Test/Extensions/PublishSubscribeServiceCollectionExtensionsTests.cs @@ -15,7 +15,6 @@ using Dapr.Messaging.PublishSubscribe.Extensions; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; -using Moq; namespace Dapr.Messaging.Test.Extensions;