Skip to content

Commit 9ef9eb1

Browse files
linkdotnetegil
andauthored
refactor: Implemented analyzer suggestions and smaller refactorings (#937)
* refactor: Implemented analyzer suggestions and smaller refactorings * Use SuppressMessage instead of pragma * ToList to ToArray * fix: dont convert to array unnecessarily * fix of the fix Co-authored-by: Egil Hansen <[email protected]>
1 parent 0bdb54c commit 9ef9eb1

File tree

28 files changed

+106
-111
lines changed

28 files changed

+106
-111
lines changed

src/bunit.core/Extensions/WaitForHelpers/RenderedFragmentWaitForHelperExtensions.cs

Lines changed: 4 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -28,14 +28,9 @@ public static void WaitForState(this IRenderedFragmentBase renderedFragment, Fun
2828
{
2929
waiter.WaitTask.GetAwaiter().GetResult();
3030
}
31-
catch (Exception e)
31+
catch (AggregateException e) when (e.InnerExceptions.Count == 1)
3232
{
33-
if (e is AggregateException aggregateException && aggregateException.InnerExceptions.Count == 1)
34-
{
35-
ExceptionDispatchInfo.Capture(aggregateException.InnerExceptions[0]).Throw();
36-
}
37-
38-
throw;
33+
ExceptionDispatchInfo.Capture(e.InnerExceptions[0]).Throw();
3934
}
4035
}
4136

@@ -76,14 +71,9 @@ public static void WaitForAssertion(this IRenderedFragmentBase renderedFragment,
7671
{
7772
waiter.WaitTask.GetAwaiter().GetResult();
7873
}
79-
catch (Exception e)
74+
catch (AggregateException e) when (e.InnerExceptions.Count == 1)
8075
{
81-
if (e is AggregateException aggregateException && aggregateException.InnerExceptions.Count == 1)
82-
{
83-
ExceptionDispatchInfo.Capture(aggregateException.InnerExceptions[0]).Throw();
84-
}
85-
86-
throw;
76+
ExceptionDispatchInfo.Capture(e.InnerExceptions[0]).Throw();
8777
}
8878
}
8979

src/bunit.core/Rendering/RootRenderTree.cs

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,7 @@ namespace Bunit.Rendering;
77
/// Components added to the render tree must have either a <c>ChildContent</c> or
88
/// <c>Body</c> parameter.
99
/// </summary>
10+
[SuppressMessage("Naming", "CA1710:Identifiers should have correct suffix", Justification = "A tree is a collection by default.")]
1011
public sealed class RootRenderTree : IReadOnlyCollection<RootRenderTreeRegistration>
1112
{
1213
private readonly List<RootRenderTreeRegistration> registrations = new();

src/bunit.core/StringSyntaxAttribute.cs

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,8 @@
22
namespace System.Diagnostics.CodeAnalysis;
33

44
/// <summary>Fake version of the StringSyntaxAttribute, which was introduced in .NET 7</summary>
5-
[AttributeUsage(AttributeTargets.Parameter | AttributeTargets.Field | AttributeTargets.Property, AllowMultiple = false, Inherited = false)]
5+
[AttributeUsage(AttributeTargets.Parameter | AttributeTargets.Field | AttributeTargets.Property)]
6+
[SuppressMessage("Design", "CA1019:Define accessors for attribute arguments", Justification = "The sole purpose is to have the same public surface as the class in .NET7 and above.")]
67
public sealed class StringSyntaxAttribute : Attribute
78
{
89
/// <summary>

src/bunit.web/Asserting/DiffAssertExtensions.cs

Lines changed: 22 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -18,10 +18,18 @@ public static IDiff ShouldHaveSingleChange(this IEnumerable<IDiff> diffs)
1818
{
1919
if (diffs is null)
2020
throw new ArgumentNullException(nameof(diffs));
21-
if (diffs.Take(2).Count() != 1) // Optimized way of writing "diffs.Count() != 1"
22-
throw new ActualExpectedAssertException(diffs.Count().ToString(CultureInfo.InvariantCulture), "1", "Actual changes", "Expected changes", "There were more than one change");
2321

24-
return diffs.First();
22+
var diffsArray = diffs.ToArray();
23+
24+
if (diffsArray.Length != 1)
25+
throw new ActualExpectedAssertException(
26+
actual: diffsArray.Length.ToString(CultureInfo.InvariantCulture),
27+
expected: "1",
28+
actualText: "Actual changes",
29+
expectedText: "Expected changes",
30+
message: "There were more than one change");
31+
32+
return diffsArray.First();
2533
}
2634

2735
/// <summary>
@@ -38,11 +46,18 @@ public static void ShouldHaveChanges(this IEnumerable<IDiff> diffs, params Actio
3846
if (diffInspectors is null)
3947
throw new ArgumentNullException(nameof(diffInspectors));
4048

41-
if (diffs.Take(diffInspectors.Length + 1).Count() != diffInspectors.Length) // Optimized way of writing "diffs.Count() != diffInspectors.Length"
42-
throw new ActualExpectedAssertException(diffs.Count().ToString(CultureInfo.InvariantCulture), diffInspectors.Length.ToString(CultureInfo.InvariantCulture), "Actual changes", "Expected changes", "The actual number of changes does not match the expected.");
49+
var diffsArray = diffs.ToArray();
50+
51+
if (diffsArray.Length != diffInspectors.Length)
52+
throw new ActualExpectedAssertException(
53+
actual: diffsArray.Length.ToString(CultureInfo.InvariantCulture),
54+
expected: diffInspectors.Length.ToString(CultureInfo.InvariantCulture),
55+
actualText: "Actual changes",
56+
expectedText: "Expected changes",
57+
message: "The actual number of changes does not match the expected.");
4358

44-
int index = 0;
45-
foreach (var diff in diffs)
59+
var index = 0;
60+
foreach (var diff in diffsArray)
4661
{
4762
diffInspectors[index](diff);
4863
index++;

src/bunit.web/Extensions/WaitForHelpers/RenderedFragmentWaitForHelperExtensions.cs

Lines changed: 6 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -159,13 +159,11 @@ private static IElement WaitForElementCore(this IRenderedFragment renderedFragme
159159
{
160160
return waiter.WaitTask.GetAwaiter().GetResult();
161161
}
162-
catch (Exception e)
162+
catch (AggregateException e) when (e.InnerExceptions.Count == 1)
163163
{
164-
if (e is AggregateException aggregateException && aggregateException.InnerExceptions.Count == 1)
165-
{
166-
ExceptionDispatchInfo.Capture(aggregateException.InnerExceptions[0]).Throw();
167-
}
164+
ExceptionDispatchInfo.Capture(e.InnerExceptions[0]).Throw();
168165

166+
// Unreachable code
169167
throw;
170168
}
171169
}
@@ -189,13 +187,11 @@ private static IRefreshableElementCollection<IElement> WaitForElementsCore(
189187
{
190188
return waiter.WaitTask.GetAwaiter().GetResult();
191189
}
192-
catch (Exception e)
190+
catch (AggregateException e) when (e.InnerExceptions.Count == 1)
193191
{
194-
if (e is AggregateException aggregateException && aggregateException.InnerExceptions.Count == 1)
195-
{
196-
ExceptionDispatchInfo.Capture(aggregateException.InnerExceptions[0]).Throw();
197-
}
192+
ExceptionDispatchInfo.Capture(e.InnerExceptions[0]).Throw();
198193

194+
// Unreachable code
199195
throw;
200196
}
201197
}

src/bunit.web/JSInterop/JSRuntimeInvocationDictionary.cs

Lines changed: 1 addition & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -15,12 +15,7 @@ public sealed class JSRuntimeInvocationDictionary : IReadOnlyCollection<JSRuntim
1515
/// </summary>
1616
/// <param name="identifier">The identifier to get invocations for.</param>
1717
/// <returns>An <see cref="IReadOnlyList{JSRuntimeInvocation}"/>.</returns>
18-
public IReadOnlyList<JSRuntimeInvocation> this[string identifier]
19-
{
20-
get => invocations.ContainsKey(identifier)
21-
? invocations[identifier]
22-
: Array.Empty<JSRuntimeInvocation>();
23-
}
18+
public IReadOnlyList<JSRuntimeInvocation> this[string identifier] => invocations.TryGetValue(identifier, out var value) ? value : Array.Empty<JSRuntimeInvocation>();
2419

2520
/// <summary>
2621
/// Gets a read only collection of all the identifiers used in invocations in this dictionary.

src/bunit.web/TestDoubles/Authorization/FakeAuthorizationService.cs

Lines changed: 19 additions & 23 deletions
Original file line numberDiff line numberDiff line change
@@ -66,17 +66,20 @@ public Task<AuthorizationResult> AuthorizeAsync(ClaimsPrincipal user, object? re
6666

6767
AuthorizationResult result;
6868

69-
if (requirements.All(p => p is DenyAnonymousAuthorizationRequirement))
69+
var requirementsArray = requirements.ToArray();
70+
if (requirementsArray.All(p => p is DenyAnonymousAuthorizationRequirement))
7071
{
71-
result = (currentState == AuthorizationState.Authorized) ? AuthorizationResult.Success() : AuthorizationResult.Failed();
72+
result = currentState == AuthorizationState.Authorized
73+
? AuthorizationResult.Success()
74+
: AuthorizationResult.Failed();
7275
}
73-
else if (requirements.All(p => p is RolesAuthorizationRequirement))
76+
else if (requirementsArray.All(p => p is RolesAuthorizationRequirement))
7477
{
75-
result = VerifyRequiredRoles(requirements);
78+
result = VerifyRequiredRoles(requirementsArray);
7679
}
7780
else if (supportedPolicies is not null)
7881
{
79-
result = VerifyRequiredPolicies(requirements);
82+
result = VerifyRequiredPolicies(requirementsArray);
8083
}
8184
else
8285
{
@@ -103,35 +106,28 @@ public Task<AuthorizationResult> AuthorizeAsync(ClaimsPrincipal user, object? re
103106
return AuthorizeAsync(user, resource, requirements);
104107
}
105108

106-
private AuthorizationResult VerifyRequiredPolicies(IEnumerable<IAuthorizationRequirement> requirements)
109+
private AuthorizationResult VerifyRequiredPolicies(IReadOnlyCollection<IAuthorizationRequirement> requirements)
107110
{
108111
if (supportedPolicies.IsNullOrEmpty() || requirements.IsNullOrEmpty())
109112
{
110113
return AuthorizationResult.Failed();
111114
}
112115

113-
foreach (IAuthorizationRequirement req in requirements)
114-
{
115-
if (req is TestPolicyRequirement testReq && supportedPolicies.Contains(testReq.PolicyName, StringComparer.Ordinal))
116-
return AuthorizationResult.Success();
117-
}
118-
119-
return AuthorizationResult.Failed();
116+
return requirements.OfType<TestPolicyRequirement>().Any(req => supportedPolicies.Contains(req.PolicyName, StringComparer.Ordinal))
117+
? AuthorizationResult.Success()
118+
: AuthorizationResult.Failed();
120119
}
121120

122-
private AuthorizationResult VerifyRequiredRoles(IEnumerable<IAuthorizationRequirement> requirements)
121+
private AuthorizationResult VerifyRequiredRoles(IReadOnlyCollection<IAuthorizationRequirement> requirements)
123122
{
124-
AuthorizationResult result = AuthorizationResult.Failed();
125-
foreach (IAuthorizationRequirement req in requirements)
123+
var result = AuthorizationResult.Failed();
124+
foreach (var req in requirements.OfType<RolesAuthorizationRequirement>())
126125
{
127-
if (req is RolesAuthorizationRequirement testReq)
126+
var rolesFound = req.AllowedRoles.Intersect(supportedRoles, StringComparer.Ordinal);
127+
if (rolesFound.Any())
128128
{
129-
IEnumerable<string> rolesFound = testReq.AllowedRoles.Intersect(supportedRoles, StringComparer.Ordinal);
130-
if (rolesFound.Any())
131-
{
132-
result = AuthorizationResult.Success();
133-
break;
134-
}
129+
result = AuthorizationResult.Success();
130+
break;
135131
}
136132
}
137133

tests/bunit.core.tests/ComponentFactories/GenericComponentFactoryTest.cs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -25,7 +25,7 @@ public void Test002()
2525
cut.MarkupMatches(@"<div id=""ref-status"">Has ref = True</div>");
2626
}
2727

28-
private class FakeSimple1 : Simple1
28+
private sealed class FakeSimple1 : Simple1
2929
{
3030
protected override void OnInitialized() { }
3131
protected override Task OnInitializedAsync() => Task.CompletedTask;

tests/bunit.core.tests/ComponentParameterCollectionBuilderTests.cs

Lines changed: 9 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -720,9 +720,9 @@ private class Params : ComponentBase
720720
public void SomeMethod() { }
721721
}
722722

723-
private class NoParams : ComponentBase { }
724-
private class NonChildContentParameter : ComponentBase { public RenderFragment? ChildContent { get; set; } }
725-
private class InhertedParams : Params { }
723+
private sealed class NoParams : ComponentBase { }
724+
private sealed class NonChildContentParameter : ComponentBase { public RenderFragment? ChildContent { get; set; } }
725+
private sealed class InhertedParams : Params { }
726726
private abstract class ParamsBase<T> : ComponentBase
727727
{
728728
public abstract T Value { get; set; }
@@ -733,35 +733,35 @@ private class InheritedParamsWithOverride : ParamsBase<bool?>
733733
[Parameter] public override bool? Value { get; set; }
734734
}
735735

736-
private class InheritedParamsWithoutOverride : InheritedParamsWithOverride
736+
private sealed class InheritedParamsWithoutOverride : InheritedParamsWithOverride
737737
{ }
738738

739-
private class TemplatedChildContent : ComponentBase
739+
private sealed class TemplatedChildContent : ComponentBase
740740
{
741741
[Parameter] public RenderFragment<string>? ChildContent { get; set; }
742742
}
743743

744-
private class NoTwoWayBind : ComponentBase
744+
private sealed class NoTwoWayBind : ComponentBase
745745
{
746746
[Parameter]
747747
public string Value { get; set; }
748748
}
749749

750-
private class InvalidTwoWayBind : ComponentBase
750+
private sealed class InvalidTwoWayBind : ComponentBase
751751
{
752752
[Parameter]
753753
public string Value { get; set; }
754754

755755
public EventCallback<string> ValueChanged { get; set; }
756756
}
757757

758-
private class ComponentWithCascadingParameter : ComponentBase
758+
private sealed class ComponentWithCascadingParameter : ComponentBase
759759
{
760760
[CascadingParameter] public string Value { get; set; } = string.Empty;
761761
[Parameter] public EventCallback<string> ValueChanged { get; set; }
762762
}
763763

764-
private class ValidNamesComponent : ComponentBase
764+
private sealed class ValidNamesComponent : ComponentBase
765765
{
766766
[Parameter] public DateTime LastChanged { get; set; }
767767
[Parameter] public EventCallback<DateTime> LastChangedChanged { get; set; }

tests/bunit.core.tests/ComponentParameterCollectionTest.cs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -335,7 +335,7 @@ public void Test055()
335335
Should.Throw<ArgumentException>(() => sut.ToRenderFragment<Params>());
336336
}
337337

338-
private class Params : ComponentBase
338+
private sealed class Params : ComponentBase
339339
{
340340
public const string TemplateContent = "FOO";
341341

0 commit comments

Comments
 (0)