From d987cb721cb5cd470eef6b0224efcf0432e19456 Mon Sep 17 00:00:00 2001 From: Egil Hansen Date: Sat, 19 Dec 2020 15:53:42 +0000 Subject: [PATCH 1/7] Switched from using FakeIdentity and FakePrincipal to using built in types --- .../FakeAuthenticationStateProvider.cs | 17 ++-- .../TestDoubles/Authorization/FakeIdentity.cs | 47 ---------- .../Authorization/FakePrincipal.cs | 36 -------- .../SampleComponents/AuthCascading.razor | 17 ++++ .../Authorization/AuthorizationTest.cs | 90 +++++++++---------- .../FakeAuthorizationServiceTest.cs | 13 ++- .../Authorization/FakeIdentityTest.cs | 36 -------- .../Authorization/FakePrincipalTest.cs | 44 --------- 8 files changed, 79 insertions(+), 221 deletions(-) delete mode 100644 src/bunit.web/TestDoubles/Authorization/FakeIdentity.cs delete mode 100644 src/bunit.web/TestDoubles/Authorization/FakePrincipal.cs create mode 100644 tests/bunit.testassets/SampleComponents/AuthCascading.razor delete mode 100644 tests/bunit.web.tests/TestDoubles/Authorization/FakeIdentityTest.cs delete mode 100644 tests/bunit.web.tests/TestDoubles/Authorization/FakePrincipalTest.cs diff --git a/src/bunit.web/TestDoubles/Authorization/FakeAuthenticationStateProvider.cs b/src/bunit.web/TestDoubles/Authorization/FakeAuthenticationStateProvider.cs index d8d9c724a..c6023a8fd 100644 --- a/src/bunit.web/TestDoubles/Authorization/FakeAuthenticationStateProvider.cs +++ b/src/bunit.web/TestDoubles/Authorization/FakeAuthenticationStateProvider.cs @@ -99,14 +99,15 @@ private static AuthenticationState CreateAuthenticationState( IEnumerable? roles = null, IEnumerable? claims = null) { - var identity = new FakeIdentity { Name = username }; - var testPrincipal = new FakePrincipal { Identity = identity, Roles = roles ?? Array.Empty() }; - var principal = new ClaimsPrincipal(testPrincipal); + roles = roles ?? Array.Empty(); + claims = claims ?? Array.Empty(); - if (claims is not null && claims.Any()) - { - principal.AddIdentity(new ClaimsIdentity(claims)); - } + var usernameClaim = new Claim(ClaimsIdentity.DefaultNameClaimType, username); + var roleClaims = roles.Select(x => new Claim(ClaimsIdentity.DefaultRoleClaimType, x)); + var allClaims = roleClaims.Concat(claims).Prepend(usernameClaim); + + var identity = new ClaimsIdentity(claims: allClaims, authenticationType: "bUnit Fake Authentication"); + var principal = new ClaimsPrincipal(identity); return new AuthenticationState(principal); } @@ -117,7 +118,7 @@ private static AuthenticationState CreateAuthenticationState( /// Instance of AuthenticationState for an unauthenticated user. private static AuthenticationState CreateUnauthenticationState() { - var principal = new ClaimsPrincipal(new FakePrincipal()); + var principal = new ClaimsPrincipal(new ClaimsIdentity()); return new AuthenticationState(principal); } } diff --git a/src/bunit.web/TestDoubles/Authorization/FakeIdentity.cs b/src/bunit.web/TestDoubles/Authorization/FakeIdentity.cs deleted file mode 100644 index 6dd01e959..000000000 --- a/src/bunit.web/TestDoubles/Authorization/FakeIdentity.cs +++ /dev/null @@ -1,47 +0,0 @@ -using System; -using System.Security.Principal; - -namespace Bunit.TestDoubles -{ - /// - /// Identity class to use in tests where you specify a user identity. - /// - internal class FakeIdentity : IIdentity - { - private string _authType = "Test"; - private string _name = string.Empty; - - /// - /// Gets the test authentication type. - /// - public string AuthenticationType - { - get => _authType; - set - { - if (string.IsNullOrEmpty(value)) - throw new ArgumentNullException(nameof(value)); - _authType = value; - } - } - - /// - /// Gets whether the identity is set to authenticated. - /// - public bool IsAuthenticated => true; - - /// - /// Gets or sets the name of the Identity user (maps to the PrincipalUser.Name). - /// - public string Name - { - get => _name; - set - { - if (string.IsNullOrEmpty(value)) - throw new ArgumentNullException(nameof(value)); - _name = value; - } - } - } -} diff --git a/src/bunit.web/TestDoubles/Authorization/FakePrincipal.cs b/src/bunit.web/TestDoubles/Authorization/FakePrincipal.cs deleted file mode 100644 index 6ad0eb1d1..000000000 --- a/src/bunit.web/TestDoubles/Authorization/FakePrincipal.cs +++ /dev/null @@ -1,36 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Security.Principal; - -namespace Bunit.TestDoubles -{ - /// - /// A fake Principal implementation that represents an authenticated user. - /// - internal class FakePrincipal : IPrincipal - { - private IEnumerable _roles = Array.Empty(); - - /// - /// Gets or sets the identity for this authenticated principal. - /// - public IIdentity? Identity { get; set; } - - /// - /// Gets or sets the set of roles this user is authorized for. - /// - public IEnumerable Roles - { - get => _roles; - set => _roles = value ?? throw new ArgumentNullException(nameof(value)); - } - - /// - /// Default non-authenticated principal returns false for IsInRole check. - /// - /// Role name - /// Returns that this principal is not in any role. - public bool IsInRole(string role) => Roles.Any(x => x.Equals(role, StringComparison.Ordinal)); - } -} diff --git a/tests/bunit.testassets/SampleComponents/AuthCascading.razor b/tests/bunit.testassets/SampleComponents/AuthCascading.razor new file mode 100644 index 000000000..525701c65 --- /dev/null +++ b/tests/bunit.testassets/SampleComponents/AuthCascading.razor @@ -0,0 +1,17 @@ +@using Microsoft.AspNetCore.Components.Authorization + +

@isInRole

+ +@code { + private bool isInRole; + + [Parameter] public string ExpectedRole { get; set; } = string.Empty; + + [CascadingParameter] public Task AuthenticationStateTask { get; set; } = default!; + + protected override async Task OnInitializedAsync() + { + var authenticationState = await AuthenticationStateTask; + isInRole = authenticationState.User.IsInRole(ExpectedRole); + } +} diff --git a/tests/bunit.web.tests/TestDoubles/Authorization/AuthorizationTest.cs b/tests/bunit.web.tests/TestDoubles/Authorization/AuthorizationTest.cs index e0d05e8fc..94714f61f 100644 --- a/tests/bunit.web.tests/TestDoubles/Authorization/AuthorizationTest.cs +++ b/tests/bunit.web.tests/TestDoubles/Authorization/AuthorizationTest.cs @@ -5,17 +5,16 @@ namespace Bunit.TestDoubles.Authorization { - public class AuthorizationTest + public class AuthorizationTest : TestContext { [Fact(DisplayName = "AuthorizeView with unauthenticated user")] public void Test001() { // Arrange - using var ctx = new TestContext(); - ctx.AddTestAuthorization(); + this.AddTestAuthorization(); // Act - var cut = ctx.RenderComponent(); + var cut = RenderComponent(); // Assert cut.MarkupMatches("Not authorized?"); @@ -25,12 +24,11 @@ public void Test001() public void Test002() { // arrange - using var ctx = new TestContext(); - var authContext = ctx.AddTestAuthorization(); + var authContext = this.AddTestAuthorization(); authContext.SetAuthorized("TestUser", AuthorizationState.Authorized); // act - var cut = ctx.RenderComponent(); + var cut = RenderComponent(); // assert cut.MarkupMatches("Authorized!"); @@ -40,12 +38,11 @@ public void Test002() public void Test003() { // arrange - using var ctx = new TestContext(); - var authContext = ctx.AddTestAuthorization(); + var authContext = this.AddTestAuthorization(); authContext.SetAuthorized("TestUser", AuthorizationState.Unauthorized); // act - var cut = ctx.RenderComponent(); + var cut = RenderComponent(); // assert cut.MarkupMatches("Not authorized?"); @@ -55,11 +52,10 @@ public void Test003() public void Test004() { // arrange - using var ctx = new TestContext(); - var authContext = ctx.AddTestAuthorization(); + var authContext = this.AddTestAuthorization(); // start off unauthenticated. - var cut = ctx.RenderComponent(); + var cut = RenderComponent(); cut.MarkupMatches("Not authorized?"); // act @@ -75,12 +71,11 @@ public void Test004() public void Test005() { // arrange - using var ctx = new TestContext(); - var authContext = ctx.AddTestAuthorization(); + var authContext = this.AddTestAuthorization(); authContext.SetAuthorized("TestUser005", AuthorizationState.Authorized); // start off unauthenticated. - var cut = ctx.RenderComponent(); + var cut = RenderComponent(); cut.MarkupMatches("Authorized!"); // act @@ -95,11 +90,8 @@ public void Test005() [Fact(DisplayName = "AuthorizeView rendering without authorization services registered")] public void Test006() { - // arrange - using var ctx = new TestContext(); - // act - var ex = Assert.Throws(() => ctx.RenderComponent()); + var ex = Assert.Throws(() => RenderComponent()); // assert Assert.Equal("AuthenticationStateProvider", ex.ServiceName); @@ -110,12 +102,11 @@ public void Test006() public void Test007() { // arrange - using var ctx = new TestContext(); - var authContext = ctx.AddTestAuthorization(); + var authContext = this.AddTestAuthorization(); authContext.SetAuthorized("TestUser").SetPolicies("ContentViewer"); // act - var cut = ctx.RenderComponent(); + var cut = RenderComponent(); // assert cut.MarkupMatches("Authorized for content viewers."); @@ -125,11 +116,10 @@ public void Test007() public void Test008() { // arrange - using var ctx = new TestContext(); - var authContext = ctx.AddTestAuthorization(); + var authContext = this.AddTestAuthorization(); authContext.SetAuthorized("TestUser"); // act - var cut = ctx.RenderComponent(); + var cut = RenderComponent(); // assert cut.MarkupMatches(""); @@ -139,12 +129,11 @@ public void Test008() public void Test0081() { // arrange - using var ctx = new TestContext(); - var authContext = ctx.AddTestAuthorization(); + var authContext = this.AddTestAuthorization(); authContext.SetAuthorized("TestUser").SetPolicies("OtherPolicy"); // act - var cut = ctx.RenderComponent(); + var cut = RenderComponent(); // assert cut.MarkupMatches(""); @@ -154,12 +143,11 @@ public void Test0081() public void Test009() { // arrange - using var ctx = new TestContext(); - var authContext = ctx.AddTestAuthorization(); + var authContext = this.AddTestAuthorization(); authContext.SetAuthorized("TestUser").SetRoles("Admin"); // act - var cut = ctx.RenderComponent(); + var cut = RenderComponent(); // assert cut.MarkupMatches("Authorized content for admins."); @@ -169,12 +157,11 @@ public void Test009() public void Test010() { // arrange - using var ctx = new TestContext(); - var authContext = ctx.AddTestAuthorization(); + var authContext = this.AddTestAuthorization(); authContext.SetAuthorized("TestUser"); // act - var cut = ctx.RenderComponent(); + var cut = RenderComponent(); // assert cut.MarkupMatches(""); @@ -184,12 +171,11 @@ public void Test010() public void Test011() { // arrange - using var ctx = new TestContext(); - var authContext = ctx.AddTestAuthorization(); + var authContext = this.AddTestAuthorization(); authContext.SetAuthorized("TestUser").SetRoles("NotAdmin"); // act - var cut = ctx.RenderComponent(); + var cut = RenderComponent(); // assert cut.MarkupMatches(""); @@ -199,12 +185,11 @@ public void Test011() public void Test012() { // arrange - using var ctx = new TestContext(); - var authContext = ctx.AddTestAuthorization(); + var authContext = this.AddTestAuthorization(); authContext.SetAuthorizing(); // act - var cut = ctx.RenderComponent(); + var cut = RenderComponent(); // assert cut.MarkupMatches("Authorizing..."); @@ -215,14 +200,13 @@ public void Test013() { // arrange var userId = new Guid("{5d5fa9c1-abf9-4ed6-8fb0-3365382b629c}"); - using var ctx = new TestContext(); - var authContext = ctx.AddTestAuthorization(); + var authContext = this.AddTestAuthorization(); var emailClaim = new Claim(ClaimTypes.Email, "user@test.com"); var uuidClaim = new Claim(ClaimTypes.Sid, userId.ToString()); authContext.SetAuthorized("TestUser").SetClaims(uuidClaim, emailClaim); // act - var cut = ctx.RenderComponent(); + var cut = RenderComponent(); // assert cut.MarkupMatches(@$"
Authorized!
@@ -236,16 +220,28 @@ public void Test013() public void Test014() { // arrange - using var ctx = new TestContext(); - var authContext = ctx.AddTestAuthorization(); + var authContext = this.AddTestAuthorization(); authContext.SetAuthorized("TestUser"); // act - var cut = ctx.RenderComponent(); + var cut = RenderComponent(); // assert cut.MarkupMatches(@$"
Authorized!
Name: TestUser
"); } + + [Fact(DisplayName = "IsInRole can resolve role assigned to auth context")] + public void Test020() + { + var role = "myTestRole"; + var authCtx = this.AddTestAuthorization(); + authCtx.SetAuthorized("FooBar"); + authCtx.SetRoles(role); + + var cut = RenderComponent(ps => ps.Add(p => p.ExpectedRole, role)); + + cut.MarkupMatches("

True

"); + } } } diff --git a/tests/bunit.web.tests/TestDoubles/Authorization/FakeAuthorizationServiceTest.cs b/tests/bunit.web.tests/TestDoubles/Authorization/FakeAuthorizationServiceTest.cs index cb70e4343..aa6b1588c 100644 --- a/tests/bunit.web.tests/TestDoubles/Authorization/FakeAuthorizationServiceTest.cs +++ b/tests/bunit.web.tests/TestDoubles/Authorization/FakeAuthorizationServiceTest.cs @@ -10,12 +10,19 @@ namespace Bunit.TestDoubles.Authorization { public class FakeAuthorizationServiceTest { + private ClaimsPrincipal CreateUserPrincipal(string username) + { + var usernameClaim = new Claim(ClaimsIdentity.DefaultNameClaimType, username); + var identity = new ClaimsIdentity(claims: new[] { usernameClaim }, authenticationType: "bUnit Fake Authentication"); + return new ClaimsPrincipal(identity); + } + [Fact(DisplayName = "Get AuthorizeAsync with an authorized result.")] public async Task Test002() { // arrange var service = new FakeAuthorizationService(AuthorizationState.Unauthorized); - var user = new ClaimsPrincipal(new FakeIdentity { Name = "DarthPedro" }); + var user = CreateUserPrincipal("FooBar"); var requirements = new List(); // act @@ -31,7 +38,7 @@ public async Task Test003() { // arrange var service = new FakeAuthorizationService(); - var user = new ClaimsPrincipal(new FakeIdentity { Name = "DarthPedro" }); + var user = CreateUserPrincipal("FooBar"); var requirements = new List(); // act @@ -47,7 +54,7 @@ public async Task Test004() { // arrange var service = new FakeAuthorizationService(AuthorizationState.Unauthorized); - var user = new ClaimsPrincipal(new FakeIdentity { Name = "DarthPedro" }); + var user = CreateUserPrincipal("FooBar"); // act var result = await service.AuthorizeAsync(user, "testResource", "testPolicy"); diff --git a/tests/bunit.web.tests/TestDoubles/Authorization/FakeIdentityTest.cs b/tests/bunit.web.tests/TestDoubles/Authorization/FakeIdentityTest.cs deleted file mode 100644 index b49cc73fa..000000000 --- a/tests/bunit.web.tests/TestDoubles/Authorization/FakeIdentityTest.cs +++ /dev/null @@ -1,36 +0,0 @@ -using System; -using Xunit; - -namespace Bunit.TestDoubles.Authorization -{ - public class FakeIdentityTest - { - [Fact(DisplayName = "Identity simple test")] - public void Test001() - { - // act - var identity = new FakeIdentity { Name = "TestUser", AuthenticationType = "AnotherTestType" }; - - // assert - Assert.Equal("TestUser", identity.Name); - Assert.Equal("AnotherTestType", identity.AuthenticationType); - Assert.True(identity.IsAuthenticated); - } - - [Theory(DisplayName = "Identity with null/empty Name set")] - [InlineData(null)] - [InlineData("")] - public void Test002(string name) - { - Assert.Throws(() => new FakeIdentity { Name = name, AuthenticationType = "AnotherTestType" }); - } - - [Theory(DisplayName = "Identity with null/empty AuthenticationType set")] - [InlineData(null)] - [InlineData("")] - public void Test003(string authType) - { - Assert.Throws(() => new FakeIdentity { Name = "TestUser", AuthenticationType = authType }); - } - } -} diff --git a/tests/bunit.web.tests/TestDoubles/Authorization/FakePrincipalTest.cs b/tests/bunit.web.tests/TestDoubles/Authorization/FakePrincipalTest.cs deleted file mode 100644 index 1b825df85..000000000 --- a/tests/bunit.web.tests/TestDoubles/Authorization/FakePrincipalTest.cs +++ /dev/null @@ -1,44 +0,0 @@ -using System.Collections.Generic; -using Shouldly; -using Xunit; - -namespace Bunit.TestDoubles.Authorization -{ - public class FakePrincipalTest - { - [Fact(DisplayName = "Principal is in role")] - public void Test001() - { - // arrange - var identity = new FakeIdentity { Name = "TestUser" }; - var roles = new List { "User", "Admin", "Test" }; - var principal = new FakePrincipal { Identity = identity, Roles = roles }; - - // act - principal.IsInRole("User").ShouldBeTrue(); - } - - [Fact(DisplayName = "Principal is not in role")] - public void Test002() - { - // arrange - var identity = new FakeIdentity { Name = "TestUser" }; - var roles = new List { "User", "Test" }; - var principal = new FakePrincipal { Identity = identity, Roles = roles }; - - // act - principal.IsInRole("Admin").ShouldBeFalse(); - } - - [Fact(DisplayName = "Principal has no roles")] - public void Test003() - { - // arrange - var identity = new FakeIdentity { Name = "TestUser" }; - var principal = new FakePrincipal { Identity = identity }; - - // act - principal.IsInRole("User").ShouldBeFalse(); - } - } -} From 3b3fbcdee07179e474a93c177258252109005ca4 Mon Sep 17 00:00:00 2001 From: Egil Hansen Date: Sat, 19 Dec 2020 16:02:13 +0000 Subject: [PATCH 2/7] Updated changelog --- CHANGELOG.md | 2 ++ 1 file changed, 2 insertions(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index e74c53fc0..99ac8f817 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -132,6 +132,8 @@ List of any bug fixes. - When an element, found in the DOM tree using the `Find()`, method was removed because of an event handler trigger on it, e.g. an `cut.Find("button").Click()` event trigger method, an `ElementNotFoundException` was thrown. Reported by [@nickmuller](https://github.com/nickmuller) in [#251](https://github.com/egil/bUnit/issues/251). +- In the built-in fake authentication system in bUnit, roles and claims were not available in components through the a cascading parameter of type `Task`. Reported by [@AFAde](https://github.com/AFAde) in [#253](https://github.com/egil/bUnit/discussions/253) and fixed in [#291](https://github.com/egil/bUnit/pull/291) by [@egil](https://github.com/egil). + ## [1.0.0-beta 11] - 2020-10-26 The following section list all changes in beta-11. From 4e519cae0d6d25c03b886b742d951351a8ba7159 Mon Sep 17 00:00:00 2001 From: Egil Hansen Date: Sat, 19 Dec 2020 17:06:26 +0000 Subject: [PATCH 3/7] Code cleanup --- .editorconfig | 13 ++++++++++--- src/Directory.Build.props | 8 ++++++-- src/bunit.core/ComponentParameter.cs | 2 -- src/bunit.core/GlobalSuppressions.cs | 13 ------------- src/bunit.web/GlobalSuppressions.cs | 6 ------ src/bunit.web/JSInterop/BunitJSInterop.cs | 6 ++++-- src/bunit.xunit/GlobalSuppressions.cs | 10 ---------- tests/Directory.Build.props | 4 ++++ .../ComponentParameterCollectionTest.cs | 1 - tests/bunit.core.tests/GlobalSuppressions.cs | 18 ------------------ .../RazorTesting/FixtureBaseTest.cs | 3 +++ .../Rendering/ComponentParameterTest.cs | 6 +++--- tests/bunit.testassets/GlobalSuppressions.cs | 9 --------- .../SampleComponents/WrapperDiv.cs | 1 - .../Asserting/DiffAssertExtensionsTest.cs | 4 ++-- ...ailsElementEventDispatcherExtensionsTest.cs | 2 -- .../EventDispatchExtensions/KeyTest.cs | 11 +++-------- .../Extensions/RefreshingWrappedElementTest.cs | 2 +- tests/bunit.web.tests/GlobalSuppressions.cs | 10 ---------- .../JSInterop/BunitJSInteropTest.cs | 2 -- ...VirtualizeJSRuntimeInvocationHandlerTest.cs | 2 +- tests/bunit.web.tests/TestContextTest.cs | 11 +---------- .../GenericCollectionAssertExtensionsTest.cs | 11 +++++++---- tests/bunit.xunit.tests/GlobalSuppressions.cs | 10 ---------- .../RazorTesting/RazorTestDiscovererTest.cs | 2 -- 25 files changed, 45 insertions(+), 122 deletions(-) delete mode 100644 src/bunit.core/GlobalSuppressions.cs delete mode 100644 src/bunit.web/GlobalSuppressions.cs delete mode 100644 src/bunit.xunit/GlobalSuppressions.cs delete mode 100644 tests/bunit.core.tests/GlobalSuppressions.cs delete mode 100644 tests/bunit.testassets/GlobalSuppressions.cs delete mode 100644 tests/bunit.web.tests/GlobalSuppressions.cs delete mode 100644 tests/bunit.xunit.tests/GlobalSuppressions.cs diff --git a/.editorconfig b/.editorconfig index c554ed090..2b455bd32 100644 --- a/.editorconfig +++ b/.editorconfig @@ -44,13 +44,20 @@ dotnet_diagnostic.BL0006.severity = none [*.cs] +dotnet_diagnostic.IDE0022.severity = silent # IDE0022: Use block body for methods +dotnet_diagnostic.IDE0090.severity = silent # IDE0090: Use 'new(...)' dotnet_diagnostic.S125.severity = suggestion # S125: Sections of code should not be commented out dotnet_diagnostic.S927.severity = suggestion # S927: Parameter names should match base declaration and other partial definitions dotnet_diagnostic.S1075.severity = suggestion # S1075: URIs should not be hardcoded -dotnet_diagnostic.S1186.severity = suggestion # S1186: Methods should not be empty +dotnet_diagnostic.S1186.severity = silent # S1186: Methods should not be empty dotnet_diagnostic.S1199.severity = suggestion # S1199: Nested code blocks should not be used dotnet_diagnostic.S3925.severity = suggestion # S3925: "ISerializable" should be implemented correctly -[tests/**.cs] +[src/bunit.web/EventDispatchExtensions/**.cs] +dotnet_diagnostic.S107.severity = none # S107: Methods should not have too many parameters -dotnet_diagnostic.S3459.severity = suggestion # S3459: Unassigned members should be removed +[tests/**.cs] +dotnet_diagnostic.S125.severity = none # S125: Sections of code should not be commented out +dotnet_diagnostic.CA2012.severity = none # CA2012: Use ValueTasks correctly +dotnet_diagnostic.S3459.severity = none # S3459: Unassigned members should be removed +dotnet_diagnostic.S1186.severity = none # S1186: Methods should not be empty diff --git a/src/Directory.Build.props b/src/Directory.Build.props index 5ff3f3250..446c78307 100644 --- a/src/Directory.Build.props +++ b/src/Directory.Build.props @@ -46,9 +46,13 @@ - + - + + all + runtime; build; native; contentfiles; analyzers + + diff --git a/src/bunit.core/ComponentParameter.cs b/src/bunit.core/ComponentParameter.cs index 9c64aeef7..f16186f10 100644 --- a/src/bunit.core/ComponentParameter.cs +++ b/src/bunit.core/ComponentParameter.cs @@ -1,5 +1,4 @@ using System; -using System.Diagnostics.CodeAnalysis; namespace Bunit { @@ -7,7 +6,6 @@ namespace Bunit /// Represents a single parameter supplied to an /// component under test. /// - [SuppressMessage("Usage", "CA2225:Operator overloads have named alternates", Justification = "")] public readonly struct ComponentParameter : IEquatable { /// diff --git a/src/bunit.core/GlobalSuppressions.cs b/src/bunit.core/GlobalSuppressions.cs deleted file mode 100644 index 257dad9bc..000000000 --- a/src/bunit.core/GlobalSuppressions.cs +++ /dev/null @@ -1,13 +0,0 @@ -// This file is used by Code Analysis to maintain SuppressMessage -// attributes that are applied to this project. -// Project-level suppressions either have no target or are given -// a specific target and scoped to a namespace, type, member, etc. - -using System.Diagnostics.CodeAnalysis; - -[assembly: SuppressMessage("Usage", "BL0006:Do not use RenderTree types")] -[assembly: SuppressMessage("Design", "CA1063:Implement IDisposable Correctly")] -[assembly: SuppressMessage("Design", "CA1031:Do not catch general exception types")] -[assembly: SuppressMessage("Globalization", "CA1303:Do not pass literals as localized parameters")] -[assembly: SuppressMessage("Usage", "CA1816:Dispose methods should call SuppressFinalize")] -[assembly: SuppressMessage("Design", "CA1032:Implement standard exception constructors")] diff --git a/src/bunit.web/GlobalSuppressions.cs b/src/bunit.web/GlobalSuppressions.cs deleted file mode 100644 index f1941869f..000000000 --- a/src/bunit.web/GlobalSuppressions.cs +++ /dev/null @@ -1,6 +0,0 @@ -using System.Diagnostics.CodeAnalysis; -[assembly: SuppressMessage("Usage", "BL0006:Do not use RenderTree types")] -[assembly: SuppressMessage("Globalization", "CA1303:Do not pass literals as localized parameters", Justification = "No localization planned")] -[assembly: SuppressMessage("Design", "CA1033:Interface methods should be callable by child types", Justification = "")] -[assembly: SuppressMessage("Globalization", "CA1308:Normalize strings to uppercase")] -[assembly: SuppressMessage("Design", "CA1032:Implement standard exception constructors")] diff --git a/src/bunit.web/JSInterop/BunitJSInterop.cs b/src/bunit.web/JSInterop/BunitJSInterop.cs index ae3146559..ae11a708b 100644 --- a/src/bunit.web/JSInterop/BunitJSInterop.cs +++ b/src/bunit.web/JSInterop/BunitJSInterop.cs @@ -41,7 +41,9 @@ public BunitJSInterop() { Mode = JSRuntimeMode.Strict; JSRuntime = new BunitJSRuntime(this); +#if NET5_0 AddCustomHandlers(); +#endif } /// @@ -83,13 +85,13 @@ internal virtual void RegisterInvocation(JSRuntimeInvocation invocation) return result; } +#if NET5_0 private void AddCustomHandlers() { -#if NET5_0 AddInvocationHandler(new FocusAsyncInvocationHandler()); AddInvocationHandler(new VirtualizeJSRuntimeInvocationHandler()); AddInvocationHandler(new LooseModeJSObjectReferenceInvocationHandler(this)); -#endif } +#endif } } diff --git a/src/bunit.xunit/GlobalSuppressions.cs b/src/bunit.xunit/GlobalSuppressions.cs deleted file mode 100644 index 815c47760..000000000 --- a/src/bunit.xunit/GlobalSuppressions.cs +++ /dev/null @@ -1,10 +0,0 @@ -// This file is used by Code Analysis to maintain SuppressMessage -// attributes that are applied to this project. -// Project-level suppressions either have no target or are given -// a specific target and scoped to a namespace, type, member, etc. - -using System.Diagnostics.CodeAnalysis; - -[assembly: SuppressMessage("Design", "CA1031:Do not catch general exception types")] -[assembly: SuppressMessage("Globalization", "CA1303:Do not pass literals as localized parameters")] -[assembly: SuppressMessage("Design", "CA1033:Interface methods should be callable by child types")] diff --git a/tests/Directory.Build.props b/tests/Directory.Build.props index 51dc6420a..811af52da 100644 --- a/tests/Directory.Build.props +++ b/tests/Directory.Build.props @@ -36,5 +36,9 @@ + + all + runtime; build; native; contentfiles; analyzers + diff --git a/tests/bunit.core.tests/ComponentParameterCollectionTest.cs b/tests/bunit.core.tests/ComponentParameterCollectionTest.cs index cd80914db..614ed22a9 100644 --- a/tests/bunit.core.tests/ComponentParameterCollectionTest.cs +++ b/tests/bunit.core.tests/ComponentParameterCollectionTest.cs @@ -1,6 +1,5 @@ using System; using System.Collections.Generic; -using Bunit.TestDoubles; using Microsoft.AspNetCore.Components; using Microsoft.AspNetCore.Components.Rendering; using Shouldly; diff --git a/tests/bunit.core.tests/GlobalSuppressions.cs b/tests/bunit.core.tests/GlobalSuppressions.cs deleted file mode 100644 index 4df2fd4e4..000000000 --- a/tests/bunit.core.tests/GlobalSuppressions.cs +++ /dev/null @@ -1,18 +0,0 @@ -// This file is used by Code Analysis to maintain SuppressMessage -// attributes that are applied to this project. -// Project-level suppressions either have no target or are given -// a specific target and scoped to a namespace, type, member, etc. - -using System.Diagnostics.CodeAnalysis; - -[assembly: SuppressMessage("Usage", "BL0006:Do not use RenderTree types")] -[assembly: SuppressMessage("Reliability", "CA2007:Consider calling ConfigureAwait on the awaited task", Justification = "not in tests")] -[assembly: SuppressMessage("Globalization", "CA1303:Do not pass literals as localized parameters", Justification = "")] -[assembly: SuppressMessage("Reliability", "CA2007:Consider calling ConfigureAwait on the awaited task", Justification = "")] -[assembly: SuppressMessage("Globalization", "CA1308:Normalize strings to uppercase", Justification = "")] -[assembly: SuppressMessage("Design", "CA1031:Do not catch general exception types", Justification = "In tests its ok to catch the general exception type")] -[assembly: SuppressMessage("Usage", "CA2234:Pass system uri objects instead of strings", Justification = "")] -[assembly: SuppressMessage("Usage", "BL0006:Do not use RenderTree types", Justification = "")] -[assembly: SuppressMessage("Naming", "CA1707:Identifiers should not contain underscores")] -[assembly: SuppressMessage("Performance", "CA1812:Avoid uninstantiated internal classes")] -[assembly: SuppressMessage("Performance", "CA1822:Mark members as static", Justification = "")] diff --git a/tests/bunit.core.tests/RazorTesting/FixtureBaseTest.cs b/tests/bunit.core.tests/RazorTesting/FixtureBaseTest.cs index 24b630174..6e34fa4e4 100644 --- a/tests/bunit.core.tests/RazorTesting/FixtureBaseTest.cs +++ b/tests/bunit.core.tests/RazorTesting/FixtureBaseTest.cs @@ -1,5 +1,6 @@ using System; using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; using System.Threading.Tasks; using Shouldly; using Xunit; @@ -14,6 +15,7 @@ private class FixtureComponent : FixtureBase } [Fact(DisplayName = "Setup, SetupAsync and Test methods are called in the correct order")] + [SuppressMessage("Minor Bug", "S4158:Empty collections should not be accessed or iterated", Justification = "False positive!")] public async Task Test001() { var callLog = new List(3); @@ -40,6 +42,7 @@ Task SetupAsync(FixtureComponent fixture) } [Fact(DisplayName = "Setup, SetupAsync and TestAsync methods are called in the correct order")] + [SuppressMessage("Minor Bug", "S4158:Empty collections should not be accessed or iterated", Justification = "False positive!")] public async Task Test002() { var callLog = new List(3); diff --git a/tests/bunit.core.tests/Rendering/ComponentParameterTest.cs b/tests/bunit.core.tests/Rendering/ComponentParameterTest.cs index bab74fe37..5921d600a 100644 --- a/tests/bunit.core.tests/Rendering/ComponentParameterTest.cs +++ b/tests/bunit.core.tests/Rendering/ComponentParameterTest.cs @@ -25,18 +25,18 @@ public static IEnumerable GetEqualsTestData() yield return new object[] { p1, p5, false }; } - [Fact(DisplayName = "Creating a cascading value throws")] + [Fact(DisplayName = "Creating a cascading value with null throws")] public void Test001() { Should.Throw(() => ComponentParameter.CreateCascadingValue(null, null!)); - Should.Throw(() => { ComponentParameter p = (null, null, true); }); + Should.Throw(() => (ComponentParameter)(null, null, true)); } [Fact(DisplayName = "Creating a regular parameter without a name throws")] public void Test002() { Should.Throw(() => ComponentParameter.CreateParameter(null!, null)); - Should.Throw(() => { ComponentParameter p = (null, null, false); }); + Should.Throw(() => (ComponentParameter)(null, null, false)); } [Theory(DisplayName = "Equals compares correctly")] diff --git a/tests/bunit.testassets/GlobalSuppressions.cs b/tests/bunit.testassets/GlobalSuppressions.cs deleted file mode 100644 index 5f13243ae..000000000 --- a/tests/bunit.testassets/GlobalSuppressions.cs +++ /dev/null @@ -1,9 +0,0 @@ -// This file is used by Code Analysis to maintain SuppressMessage -// attributes that are applied to this project. -// Project-level suppressions either have no target or are given -// a specific target and scoped to a namespace, type, member, etc. - -using System.Diagnostics.CodeAnalysis; - -[assembly: SuppressMessage("Globalization", "CA1303:Do not pass literals as localized parameters")] -[assembly: SuppressMessage("Design", "CA1062:Validate arguments of public methods")] diff --git a/tests/bunit.testassets/SampleComponents/WrapperDiv.cs b/tests/bunit.testassets/SampleComponents/WrapperDiv.cs index 5f88ed192..136c79f99 100644 --- a/tests/bunit.testassets/SampleComponents/WrapperDiv.cs +++ b/tests/bunit.testassets/SampleComponents/WrapperDiv.cs @@ -1,4 +1,3 @@ -using System.Threading.Tasks; using Microsoft.AspNetCore.Components; using Microsoft.AspNetCore.Components.Rendering; diff --git a/tests/bunit.web.tests/Asserting/DiffAssertExtensionsTest.cs b/tests/bunit.web.tests/Asserting/DiffAssertExtensionsTest.cs index b07ab98d1..1cbdeb10a 100644 --- a/tests/bunit.web.tests/Asserting/DiffAssertExtensionsTest.cs +++ b/tests/bunit.web.tests/Asserting/DiffAssertExtensionsTest.cs @@ -23,7 +23,7 @@ public void Test001() catch (Exception ex) { exception = ex; - }; + } exception.ShouldBeOfType(); } @@ -41,7 +41,7 @@ public void Test002(IReadOnlyList diffs) catch (Exception ex) { exception = ex; - }; + } exception.ShouldBeOfType(); } diff --git a/tests/bunit.web.tests/EventDispatchExtensions/DetailsElementEventDispatcherExtensionsTest.cs b/tests/bunit.web.tests/EventDispatchExtensions/DetailsElementEventDispatcherExtensionsTest.cs index eef3e4c66..293892e89 100644 --- a/tests/bunit.web.tests/EventDispatchExtensions/DetailsElementEventDispatcherExtensionsTest.cs +++ b/tests/bunit.web.tests/EventDispatchExtensions/DetailsElementEventDispatcherExtensionsTest.cs @@ -1,6 +1,4 @@ #if NET5_0 -using System.Collections.Generic; -using System.Threading.Tasks; using Bunit.TestAssets.SampleComponents; using Shouldly; using Xunit; diff --git a/tests/bunit.web.tests/EventDispatchExtensions/KeyTest.cs b/tests/bunit.web.tests/EventDispatchExtensions/KeyTest.cs index 98c83ef99..4edaadfc5 100644 --- a/tests/bunit.web.tests/EventDispatchExtensions/KeyTest.cs +++ b/tests/bunit.web.tests/EventDispatchExtensions/KeyTest.cs @@ -1,6 +1,5 @@ using System; using System.Collections.Generic; -using System.Diagnostics.CodeAnalysis; using System.Linq; using System.Reflection; using Microsoft.AspNetCore.Components.Web; @@ -8,8 +7,7 @@ using Xunit; namespace Bunit -{ - [SuppressMessage("Microsoft.Design", "CA1062:Validate arguments of public methods", Justification = "Arguments are provided from test data")] +{ public class KeyTest { public static IEnumerable KeyValueTestData { get; } = GetKeyValueTestData().Select(c => new object[] { c }).ToList(); @@ -69,15 +67,12 @@ public void CanCastFromString(string value) key.CommandKey.ShouldBeFalse(); } - [Theory(DisplayName = "Custing from null or empty string throws ArgumentNullException")] + [Theory(DisplayName = "Casting from null or empty string throws ArgumentNullException")] [InlineData(null)] [InlineData("")] public void CastingFromNullStringThrowsException(string value) { - Should.Throw(() => - { - Key key = value; - }); + Should.Throw(() => (Key)value); } [Theory(DisplayName = "Get method with value and code parameters should return initialized Key object")] diff --git a/tests/bunit.web.tests/Extensions/RefreshingWrappedElementTest.cs b/tests/bunit.web.tests/Extensions/RefreshingWrappedElementTest.cs index 8eb2781e5..64937b2a2 100644 --- a/tests/bunit.web.tests/Extensions/RefreshingWrappedElementTest.cs +++ b/tests/bunit.web.tests/Extensions/RefreshingWrappedElementTest.cs @@ -70,7 +70,7 @@ public void Test030() var btn = cut.Find("button"); - btn.Click(); // remove from dom + Should.NotThrow(() => btn.Click()); } [Fact(DisplayName = "Found element throws when its properties or methods are used after it's removed from DOM")] diff --git a/tests/bunit.web.tests/GlobalSuppressions.cs b/tests/bunit.web.tests/GlobalSuppressions.cs deleted file mode 100644 index 8a2d60dcd..000000000 --- a/tests/bunit.web.tests/GlobalSuppressions.cs +++ /dev/null @@ -1,10 +0,0 @@ -using System.Diagnostics.CodeAnalysis; - -[assembly: SuppressMessage("Globalization", "CA1303:Do not pass literals as localized parameters", Justification = "")] -[assembly: SuppressMessage("Reliability", "CA2007:Consider calling ConfigureAwait on the awaited task", Justification = "")] -[assembly: SuppressMessage("Globalization", "CA1308:Normalize strings to uppercase", Justification = "")] -[assembly: SuppressMessage("Design", "CA1031:Do not catch general exception types", Justification = "In tests its ok to catch the general exception type")] -[assembly: SuppressMessage("Usage", "CA2234:Pass system uri objects instead of strings", Justification = "")] -[assembly: SuppressMessage("Usage", "BL0006:Do not use RenderTree types", Justification = "")] -[assembly: SuppressMessage("Naming", "CA1707:Identifiers should not contain underscores")] -[assembly: SuppressMessage("Performance", "CA1812:Avoid uninstantiated internal classes")] diff --git a/tests/bunit.web.tests/JSInterop/BunitJSInteropTest.cs b/tests/bunit.web.tests/JSInterop/BunitJSInteropTest.cs index 1169bb17e..6cd5b8467 100644 --- a/tests/bunit.web.tests/JSInterop/BunitJSInteropTest.cs +++ b/tests/bunit.web.tests/JSInterop/BunitJSInteropTest.cs @@ -1,5 +1,4 @@ using System; -using System.Diagnostics.CodeAnalysis; using System.Linq; using System.Threading; using System.Threading.Tasks; @@ -414,7 +413,6 @@ public async Task Test022() plannedCatchall.Invocations.Count.ShouldBe(0); } - [SuppressMessage("Reliability", "CA2012:Use ValueTasks correctly", Justification = "Not relevant for test")] [Fact(DisplayName = "The last handler matching an invocation receives the invocation")] public void Test030() { diff --git a/tests/bunit.web.tests/JSInterop/InvocationHandlers/VirtualizeJSRuntimeInvocationHandlerTest.cs b/tests/bunit.web.tests/JSInterop/InvocationHandlers/VirtualizeJSRuntimeInvocationHandlerTest.cs index 63bd0cc74..3cbbae3f2 100644 --- a/tests/bunit.web.tests/JSInterop/InvocationHandlers/VirtualizeJSRuntimeInvocationHandlerTest.cs +++ b/tests/bunit.web.tests/JSInterop/InvocationHandlers/VirtualizeJSRuntimeInvocationHandlerTest.cs @@ -108,7 +108,7 @@ public void Test040(int itemsInDataSource) private static ICollection CreateItems(int itemsToCreate) => Enumerable.Range(0, itemsToCreate).Select(x => Guid.NewGuid().ToString()).ToArray(); - private ItemsProviderDelegate CreateItemsProvider(int itemsInCollection) + private static ItemsProviderDelegate CreateItemsProvider(int itemsInCollection) { return request => { diff --git a/tests/bunit.web.tests/TestContextTest.cs b/tests/bunit.web.tests/TestContextTest.cs index a08cef12b..c71adc182 100644 --- a/tests/bunit.web.tests/TestContextTest.cs +++ b/tests/bunit.web.tests/TestContextTest.cs @@ -8,13 +8,6 @@ namespace Bunit { public class TestContextTest : TestContext { - [Fact(DisplayName = "The placeholder IJSRuntime is overridden by a supplied mock and does not throw")] - public void Test022() - { - JSInterop.Mode = JSRuntimeMode.Loose; - RenderComponent(); - } - [Fact(DisplayName = "The test service provider should register a placeholder NavigationManager which throws exceptions")] public void Test023() { @@ -89,9 +82,7 @@ public void Test033() [Fact(DisplayName = "Can raise events from markup rendered with TestContext")] public void Test040() { - RenderComponent() - .Find("button") - .Click(); + Should.NotThrow(() => RenderComponent().Find("button").Click()); } class ReceivesCascadinValue : ComponentBase diff --git a/tests/bunit.xunit.tests/Asserting/GenericCollectionAssertExtensionsTest.cs b/tests/bunit.xunit.tests/Asserting/GenericCollectionAssertExtensionsTest.cs index 0c47918b3..4c504402f 100644 --- a/tests/bunit.xunit.tests/Asserting/GenericCollectionAssertExtensionsTest.cs +++ b/tests/bunit.xunit.tests/Asserting/GenericCollectionAssertExtensionsTest.cs @@ -1,4 +1,5 @@ using System; +using System.Diagnostics.CodeAnalysis; using Shouldly; using Xunit; using Xunit.Sdk; @@ -22,7 +23,7 @@ public void Test001() catch (Exception ex) { exception = ex; - }; + } var actual = exception.ShouldBeOfType(); actual.ActualCount.ShouldBe(collection.Length); @@ -31,6 +32,7 @@ public void Test001() [Fact(DisplayName = "ShouldAllBe for Action throws CollectionException if one of " + "the element inspectors throws")] + [SuppressMessage("Minor Code Smell", "S3626:Jump statements should not be redundant", Justification = "Necessary for testing purposes.")] public void Test002() { Exception? exception = null; @@ -43,7 +45,7 @@ public void Test002() catch (Exception ex) { exception = ex; - }; + } var actual = exception.ShouldBeOfType(); actual.IndexFailurePoint.ShouldBe(1); @@ -64,7 +66,7 @@ public void Test003() catch (Exception ex) { exception = ex; - }; + } var actual = exception.ShouldBeOfType(); actual.ActualCount.ShouldBe(collection.Length); @@ -73,6 +75,7 @@ public void Test003() [Fact(DisplayName = "ShouldAllBe for Action throws CollectionException if one of " + "the element inspectors throws")] + [SuppressMessage("Minor Code Smell", "S3626:Jump statements should not be redundant", Justification = "Necessary for testing purposes.")] public void Test004() { Exception? exception = null; @@ -85,7 +88,7 @@ public void Test004() catch (Exception ex) { exception = ex; - }; + } var actual = exception.ShouldBeOfType(); actual.IndexFailurePoint.ShouldBe(1); diff --git a/tests/bunit.xunit.tests/GlobalSuppressions.cs b/tests/bunit.xunit.tests/GlobalSuppressions.cs deleted file mode 100644 index 66ba39338..000000000 --- a/tests/bunit.xunit.tests/GlobalSuppressions.cs +++ /dev/null @@ -1,10 +0,0 @@ -// This file is used by Code Analysis to maintain SuppressMessage -// attributes that are applied to this project. -// Project-level suppressions either have no target or are given -// a specific target and scoped to a namespace, type, member, etc. - -using System.Diagnostics.CodeAnalysis; - -[assembly: SuppressMessage("Usage", "BL0006:Do not use RenderTree types")] -[assembly: SuppressMessage("Design", "CA1062:Validate arguments of public methods")] -[assembly: SuppressMessage("Design", "CA1031:Do not catch general exception types")] diff --git a/tests/bunit.xunit.tests/RazorTesting/RazorTestDiscovererTest.cs b/tests/bunit.xunit.tests/RazorTesting/RazorTestDiscovererTest.cs index 68aef4b61..7637307ce 100644 --- a/tests/bunit.xunit.tests/RazorTesting/RazorTestDiscovererTest.cs +++ b/tests/bunit.xunit.tests/RazorTesting/RazorTestDiscovererTest.cs @@ -11,14 +11,12 @@ namespace Bunit.RazorTesting { public class RazorTestDiscovererTest { - private readonly ExceptionAggregator _aggregator; private readonly IMessageSink _messageBus; private readonly ITestFrameworkDiscoveryOptions _options; private readonly IReflectionAttributeInfo _attribute; public RazorTestDiscovererTest() { - _aggregator = new ExceptionAggregator(); _options = TestFrameworkOptions.ForDiscovery(); _messageBus = Mock.Of(); _attribute = Mock.Of(); From f426998854126a29290a74e774f3441e2af0d4c0 Mon Sep 17 00:00:00 2001 From: Egil Hansen Date: Sat, 19 Dec 2020 18:02:51 +0000 Subject: [PATCH 4/7] Added IAsyncDisposable to TestServiceProvider (#292) --- CHANGELOG.md | 2 ++ src/bunit.core/TestServiceProvider.cs | 11 ++++++-- .../TestServiceProviderTest.cs | 2 +- .../TestServiceProviderTest.net5.cs | 28 +++++++++++++++++++ 4 files changed, 40 insertions(+), 3 deletions(-) create mode 100644 tests/bunit.core.tests/TestServiceProviderTest.net5.cs diff --git a/CHANGELOG.md b/CHANGELOG.md index 99ac8f817..84fdd9e72 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -98,6 +98,8 @@ List of new features. By [@egil](https://github.com/egil) in [#288](https://github.com/egil/bUnit/pull/288). +- Added support for registering services in bUnits `Services` collection that implements `IAsyncDisposable`. Suggested by [@jmaillet](https://github.com/jmaillet) in [#249](https://github.com/egil/bUnit/issues/249). + ### Changed List of changes in existing functionality. diff --git a/src/bunit.core/TestServiceProvider.cs b/src/bunit.core/TestServiceProvider.cs index 870e5a1ac..10b105f07 100644 --- a/src/bunit.core/TestServiceProvider.cs +++ b/src/bunit.core/TestServiceProvider.cs @@ -13,7 +13,7 @@ public sealed class TestServiceProvider : IServiceProvider, IServiceCollection, { private readonly IServiceCollection _serviceCollection; private ServiceProvider? _serviceProvider; - + /// /// Gets whether this has been initialized, and /// no longer will accept calls to the AddService's methods. @@ -78,7 +78,14 @@ public object GetService(Type serviceType) /// public void Dispose() { - _serviceProvider?.Dispose(); + if (_serviceProvider is null) return; + + var disposedTask = _serviceProvider.DisposeAsync().AsTask(); + + if (!disposedTask.IsCompleted) + disposedTask.GetAwaiter().GetResult(); + + _serviceProvider.Dispose(); } /// diff --git a/tests/bunit.core.tests/TestServiceProviderTest.cs b/tests/bunit.core.tests/TestServiceProviderTest.cs index 8947479c7..153117a49 100644 --- a/tests/bunit.core.tests/TestServiceProviderTest.cs +++ b/tests/bunit.core.tests/TestServiceProviderTest.cs @@ -7,7 +7,7 @@ namespace Bunit { - public class TestServiceProviderTest + public partial class TestServiceProviderTest { class DummyService { } class AnotherDummyService { } diff --git a/tests/bunit.core.tests/TestServiceProviderTest.net5.cs b/tests/bunit.core.tests/TestServiceProviderTest.net5.cs new file mode 100644 index 000000000..5b0d43c6e --- /dev/null +++ b/tests/bunit.core.tests/TestServiceProviderTest.net5.cs @@ -0,0 +1,28 @@ +#if NET5_0 +using System; +using System.Threading.Tasks; +using Microsoft.Extensions.DependencyInjection; +using Shouldly; +using Xunit; + +namespace Bunit +{ + public partial class TestServiceProviderTest + { + [Fact(DisplayName = "Can correctly dispose of async disposable service")] + public void Net5Test001() + { + var sut = new TestServiceProvider(); + sut.AddScoped(); + sut.GetService(); + + Should.NotThrow(() => sut.Dispose()); + } + + class AsyncDisposableService : IAsyncDisposable + { + public ValueTask DisposeAsync() => ValueTask.CompletedTask; + } + } +} +#endif From b80bb0d76da3686a96baca357e2560fbd59c513c Mon Sep 17 00:00:00 2001 From: Egil Hansen Date: Sat, 19 Dec 2020 21:00:25 +0000 Subject: [PATCH 5/7] Update main.yml --- .github/workflows/main.yml | 10 +--------- 1 file changed, 1 insertion(+), 9 deletions(-) diff --git a/.github/workflows/main.yml b/.github/workflows/main.yml index 249432f69..b8a4a4753 100644 --- a/.github/workflows/main.yml +++ b/.github/workflows/main.yml @@ -234,16 +234,8 @@ jobs: dotnet pack src/bunit.template/ -c Release -o ${GITHUB_WORKSPACE}/packages -p:RepositoryBranch=main -p:ContinuousIntegrationBuild=true /p:PublicRelease=true - name: Push packages to GitHub Package Registry - run: | - for f in ${GITHUB_WORKSPACE}/packages/*.nupkg - do - curl -vX PUT -u "egil:${{ secrets.GITHUB_TOKEN }}" -F package=@$f https://nuget.pkg.github.com/egil/ - done - shell: bash + run: dotnet nuget push ${GITHUB_WORKSPACE}/packages/'*.nupkg' -k ${{ secrets.GITHUB_TOKEN }} -s https://nuget.pkg.github.com/OWNER/index.json --skip-duplicate --no-symbols true - name: Push packages to NuGet if: github.event_name == 'release' run: dotnet nuget push ${GITHUB_WORKSPACE}/packages/'*.nupkg' -k ${{ secrets.NUGET_KEY }} -s https://api.nuget.org/v3/index.json --skip-duplicate --no-symbols true - -# - name: Push packages to GitHub Package Registry -# run: dotnet nuget push ${GITHUB_WORKSPACE}/packages/'*.nupkg' --skip-duplicate From 3bdd4ce47394a0e6e2348a2b92303d0c332e5765 Mon Sep 17 00:00:00 2001 From: Egil Hansen Date: Sat, 19 Dec 2020 23:02:17 +0000 Subject: [PATCH 6/7] Updated SourceFileFinder dependency version --- .github/workflows/main.yml | 8 ++++---- src/bunit.xunit/bunit.xunit.csproj | 4 ++-- tests/bunit.xunit.tests/bunit.xunit.tests.csproj | 2 +- 3 files changed, 7 insertions(+), 7 deletions(-) diff --git a/.github/workflows/main.yml b/.github/workflows/main.yml index b8a4a4753..5df4b1626 100644 --- a/.github/workflows/main.yml +++ b/.github/workflows/main.yml @@ -229,12 +229,12 @@ jobs: - name: Creating library package for release if: github.event_name == 'release' run: | - dotnet pack -c Release -o ${GITHUB_WORKSPACE}/packages -p:RepositoryBranch=main -p:ContinuousIntegrationBuild=true /p:PublicRelease=true - dotnet pack src/bunit/ -c Release -o ${GITHUB_WORKSPACE}/packages -p:RepositoryBranch=main -p:ContinuousIntegrationBuild=true /p:PublicRelease=true - dotnet pack src/bunit.template/ -c Release -o ${GITHUB_WORKSPACE}/packages -p:RepositoryBranch=main -p:ContinuousIntegrationBuild=true /p:PublicRelease=true + dotnet pack -c Release -o ${GITHUB_WORKSPACE}/packages -p:RepositoryBranch=$BRANCH -p:ContinuousIntegrationBuild=true /p:PublicRelease=true + dotnet pack src/bunit/ -c Release -o ${GITHUB_WORKSPACE}/packages -p:RepositoryBranch=$BRANCH -p:ContinuousIntegrationBuild=true /p:PublicRelease=true + dotnet pack src/bunit.template/ -c Release -o ${GITHUB_WORKSPACE}/packages -p:RepositoryBranch=$BRANCH -p:ContinuousIntegrationBuild=true /p:PublicRelease=true - name: Push packages to GitHub Package Registry - run: dotnet nuget push ${GITHUB_WORKSPACE}/packages/'*.nupkg' -k ${{ secrets.GITHUB_TOKEN }} -s https://nuget.pkg.github.com/OWNER/index.json --skip-duplicate --no-symbols true + run: dotnet nuget push ${GITHUB_WORKSPACE}/packages/'*.nupkg' -k ${{ secrets.GITHUB_TOKEN }} -s https://nuget.pkg.github.com/egilx`/index.json --skip-duplicate --no-symbols true - name: Push packages to NuGet if: github.event_name == 'release' diff --git a/src/bunit.xunit/bunit.xunit.csproj b/src/bunit.xunit/bunit.xunit.csproj index 415538322..a4fc96f0f 100644 --- a/src/bunit.xunit/bunit.xunit.csproj +++ b/src/bunit.xunit/bunit.xunit.csproj @@ -15,8 +15,8 @@ - - + + diff --git a/tests/bunit.xunit.tests/bunit.xunit.tests.csproj b/tests/bunit.xunit.tests/bunit.xunit.tests.csproj index 4c31ab7b6..a1f4e5d1c 100644 --- a/tests/bunit.xunit.tests/bunit.xunit.tests.csproj +++ b/tests/bunit.xunit.tests/bunit.xunit.tests.csproj @@ -6,7 +6,7 @@ - + From 5f11b6f64f101bc8ff94256110b9ce642c403008 Mon Sep 17 00:00:00 2001 From: Egil Hansen Date: Sun, 20 Dec 2020 10:44:25 +0000 Subject: [PATCH 7/7] workflow updates --- .github/workflows/main.yml | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/.github/workflows/main.yml b/.github/workflows/main.yml index 5df4b1626..4ec995821 100644 --- a/.github/workflows/main.yml +++ b/.github/workflows/main.yml @@ -2,6 +2,9 @@ name: "CI/CD" on: pull_request: + branches: + - dev + - main types: - opened - synchronize @@ -234,7 +237,7 @@ jobs: dotnet pack src/bunit.template/ -c Release -o ${GITHUB_WORKSPACE}/packages -p:RepositoryBranch=$BRANCH -p:ContinuousIntegrationBuild=true /p:PublicRelease=true - name: Push packages to GitHub Package Registry - run: dotnet nuget push ${GITHUB_WORKSPACE}/packages/'*.nupkg' -k ${{ secrets.GITHUB_TOKEN }} -s https://nuget.pkg.github.com/egilx`/index.json --skip-duplicate --no-symbols true + run: dotnet nuget push ${GITHUB_WORKSPACE}/packages/'*.nupkg' -k ${{ secrets.GITHUB_TOKEN }} -s https://nuget.pkg.github.com/egil/index.json --skip-duplicate --no-symbols true - name: Push packages to NuGet if: github.event_name == 'release'