Fix warnings (#5517)

Co-authored-by: Dennis Reimann <mail@dennisreimann.de>
This commit is contained in:
Nicolas Dorier 2023-11-28 23:20:03 +09:00 committed by GitHub
parent 4023b24209
commit 1081eab9db
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
19 changed files with 43 additions and 44 deletions

View File

@ -1,6 +1,7 @@
<Project Sdk="Microsoft.NET.Sdk.Web">
<Project Sdk="Microsoft.NET.Sdk.Web">
<Import Project="../Build/Common.csproj" />
<PropertyGroup>
<NoWarn>$(NoWarn),xUnit1031</NoWarn>
<IsPackable>false</IsPackable>
<UserSecretsId>AB0AC1DD-9D26-485B-9416-56A33F268117</UserSecretsId>
<!--https://devblogs.microsoft.com/aspnet/testing-asp-net-core-mvc-web-apps-in-memory/-->

View File

@ -98,7 +98,7 @@ retry:
}
Thread.Sleep(50);
}
Assert.False(true, "Elements was found");
Assert.Fail("Elements was found");
}
public static void UntilJsIsReady(this WebDriverWait wait)

View File

@ -131,7 +131,7 @@ namespace BTCPayServer.Tests
var tags = new HashSet<String>(g.Select(o => o.Tag));
if (tags.Count != 1)
{
Assert.False(true, $"All docker images '{g.Key}' in docker-compose.yml and docker-compose.altcoins.yml should have the same tags. (Found {string.Join(',', tags)})");
Assert.Fail($"All docker images '{g.Key}' in docker-compose.yml and docker-compose.altcoins.yml should have the same tags. (Found {string.Join(',', tags)})");
}
}
}
@ -964,7 +964,7 @@ namespace BTCPayServer.Tests
}
[Fact]
public void CheckRatesProvider()
public async Task CheckRatesProvider()
{
var spy = new SpyRateProvider();
RateRules.TryParse("X_X = bittrex(X_X);", out var rateRules);
@ -976,23 +976,22 @@ namespace BTCPayServer.Tests
var fetch = new BackgroundFetcherRateProvider(spy);
fetch.DoNotAutoFetchIfExpired = true;
factory.Providers.Add("bittrex", fetch);
var fetchedRate = fetcher.FetchRate(CurrencyPair.Parse("BTC_USD"), rateRules, default).GetAwaiter()
.GetResult();
var fetchedRate = await fetcher.FetchRate(CurrencyPair.Parse("BTC_USD"), rateRules, default);
spy.AssertHit();
fetchedRate = fetcher.FetchRate(CurrencyPair.Parse("BTC_USD"), rateRules, default).GetAwaiter().GetResult();
fetchedRate = await fetcher.FetchRate(CurrencyPair.Parse("BTC_USD"), rateRules, default);
spy.AssertNotHit();
fetch.UpdateIfNecessary(default).GetAwaiter().GetResult();
await fetch.UpdateIfNecessary(default);
spy.AssertNotHit();
fetch.RefreshRate = TimeSpan.FromSeconds(1.0);
Thread.Sleep(1020);
fetchedRate = fetcher.FetchRate(CurrencyPair.Parse("BTC_USD"), rateRules, default).GetAwaiter().GetResult();
fetchedRate = await fetcher.FetchRate(CurrencyPair.Parse("BTC_USD"), rateRules, default);
spy.AssertNotHit();
fetch.ValidatyTime = TimeSpan.FromSeconds(1.0);
fetch.UpdateIfNecessary(default).GetAwaiter().GetResult();
await fetch.UpdateIfNecessary(default);
spy.AssertHit();
fetch.GetRatesAsync(default).GetAwaiter().GetResult();
await fetch.GetRatesAsync(default);
Thread.Sleep(1000);
Assert.Throws<InvalidOperationException>(() => fetch.GetRatesAsync(default).GetAwaiter().GetResult());
await Assert.ThrowsAsync<InvalidOperationException>(() => fetch.GetRatesAsync(default));
}
public static RateProviderFactory CreateBTCPayRateFactory()

View File

@ -298,7 +298,7 @@ namespace BTCPayServer.Tests
AddLightningNode(null, true);
}
public void AddLightningNode(string? connectionType = null, bool test = true)
public void AddLightningNode(string connectionType = null, bool test = true)
{
var cryptoCode = "BTC";
if (!Driver.PageSource.Contains("Connect to a Lightning node"))

View File

@ -2710,7 +2710,7 @@ namespace BTCPayServer.Tests
callbacks.Add(request.Callback);
break;
default:
Assert.False(true, "Should have matched");
Assert.Fail("Should have matched");
break;
}
}

View File

@ -105,7 +105,7 @@ namespace BTCPayServer.Tests
PayTester.UseLightning = true;
PayTester.IntegratedLightning = GetLightningConnectionString(internalNode, true);
}
public string GetLightningConnectionString(string? connectionType, bool isMerchant)
public string GetLightningConnectionString(string connectionType, bool isMerchant)
{
string connectionString = null;
if (connectionType is null)

View File

@ -278,7 +278,7 @@ namespace BTCPayServer.Tests
public bool IsAdmin { get; internal set; }
public void RegisterLightningNode(string cryptoCode, string? connectionType = null, bool isMerchant = true)
public void RegisterLightningNode(string cryptoCode, string connectionType = null, bool isMerchant = true)
{
RegisterLightningNodeAsync(cryptoCode, connectionType, isMerchant).GetAwaiter().GetResult();
}
@ -286,7 +286,7 @@ namespace BTCPayServer.Tests
{
return RegisterLightningNodeAsync(cryptoCode, null, isMerchant, storeId);
}
public async Task RegisterLightningNodeAsync(string cryptoCode, string? connectionType, bool isMerchant = true, string storeId = null)
public async Task RegisterLightningNodeAsync(string cryptoCode, string connectionType, bool isMerchant = true, string storeId = null)
{
var storeController = GetController<UIStoresController>();
@ -297,7 +297,7 @@ namespace BTCPayServer.Tests
await storeController.SetupLightningNode(storeId ?? StoreId,
vm, "save", cryptoCode);
if (storeController.ModelState.ErrorCount != 0)
Assert.False(true, storeController.ModelState.FirstOrDefault().Value.Errors[0].ErrorMessage);
Assert.Fail(storeController.ModelState.FirstOrDefault().Value.Errors[0].ErrorMessage);
}
public async Task RegisterInternalLightningNodeAsync(string cryptoCode, string storeId = null)
@ -307,7 +307,7 @@ namespace BTCPayServer.Tests
await storeController.SetupLightningNode(storeId ?? StoreId,
vm, "save", cryptoCode);
if (storeController.ModelState.ErrorCount != 0)
Assert.False(true, storeController.ModelState.FirstOrDefault().Value.Errors[0].ErrorMessage);
Assert.Fail(storeController.ModelState.FirstOrDefault().Value.Errors[0].ErrorMessage);
}
public async Task<Coin> ReceiveUTXO(Money value, BTCPayNetwork network = null)
@ -432,8 +432,7 @@ namespace BTCPayServer.Tests
if (!response.IsSuccessStatusCode)
{
var error = JObject.Parse(await response.Content.ReadAsStringAsync());
Assert.True(false,
$"Error: {error["errorCode"].Value<string>()}: {error["message"].Value<string>()}");
Assert.Fail($"Error: {error["errorCode"].Value<string>()}: {error["message"].Value<string>()}");
}
}
@ -516,7 +515,7 @@ retry:
retry++;
goto retry;
}
Assert.True(false, "No webhook event match the assertion");
Assert.Fail("No webhook event match the assertion");
return null;
}
public async Task SetupWebhook()

View File

@ -177,7 +177,7 @@ namespace BTCPayServer.Tests
// If this test fail, run `UpdateSwagger` once.
if (description != json["components"]["securitySchemes"]["API_Key"]["description"].Value<string>())
{
Assert.False(true, "Please run manually the test `UpdateSwagger` once");
Assert.Fail("Please run manually the test `UpdateSwagger` once");
}
}
@ -541,7 +541,7 @@ namespace BTCPayServer.Tests
var pairingCode = (string)token.RouteValues["pairingCode"];
acc.BitPay.AuthorizeClient(new PairingCode(pairingCode)).GetAwaiter().GetResult();
await acc.BitPay.AuthorizeClient(new PairingCode(pairingCode));
Assert.True(acc.BitPay.TestAccess(Facade.Merchant));
}
@ -605,7 +605,7 @@ namespace BTCPayServer.Tests
completed = true;
break;
default:
Assert.False(true, $"{evtName} was not expected");
Assert.Fail($"{evtName} was not expected");
break;
}
}
@ -1365,7 +1365,7 @@ namespace BTCPayServer.Tests
}
catch (JsonSerializationException)
{
Assert.False(true, "The bitpay's amount is not set");
Assert.Fail("The bitpay's amount is not set");
}
});
}

View File

@ -104,14 +104,14 @@ namespace BTCPayServer.Controllers.Greenfield
public async Task<ActionResult<ApplicationUserData>> GetCurrentUser()
{
var user = await _userManager.GetUserAsync(User);
return await FromModel(user);
return await FromModel(user!);
}
[Authorize(Policy = Policies.CanDeleteUser, AuthenticationSchemes = AuthenticationSchemes.Greenfield)]
[HttpDelete("~/api/v1/users/me")]
public async Task<IActionResult> DeleteCurrentUser()
{
return await DeleteUser(_userManager.GetUserId(User));
return await DeleteUser(_userManager.GetUserId(User)!);
}
[AllowAnonymous]

View File

@ -1388,7 +1388,7 @@ namespace BTCPayServer.Controllers
private InvoiceEntity GetCurrentInvoice() => HttpContext.GetInvoiceData();
private string GetUserId() => _UserManager.GetUserId(User);
private string GetUserId() => _UserManager.GetUserId(User)!;
public class PosDataParser
{

View File

@ -1473,7 +1473,7 @@ namespace BTCPayServer.Controllers
return Request.GetRelativePathOrAbsolute(res);
}
private string GetUserId() => _userManager.GetUserId(User);
private string GetUserId() => _userManager.GetUserId(User)!;
private StoreData GetCurrentStore() => HttpContext.GetStoreData();
}

View File

@ -131,7 +131,7 @@ namespace BTCPayServer.Payments.Lightning
var invoice = await _InvoiceRepository.GetInvoice(invoiceId);
cacheEntry.AbsoluteExpiration = GetExpiration(invoice);
return invoice;
});
})!;
}
private static DateTimeOffset GetExpiration(InvoiceEntity invoice)

View File

@ -25,7 +25,7 @@ namespace BTCPayServer.Security.Bitpay
public BitpayAuthenticationHandler(
TokenRepository tokenRepository,
StoreRepository storeRepository,
IOptionsMonitor<BitpayAuthenticationOptions> options, ILoggerFactory logger, UrlEncoder encoder, ISystemClock clock) : base(options, logger, encoder, clock)
IOptionsMonitor<BitpayAuthenticationOptions> options, ILoggerFactory logger, UrlEncoder encoder) : base(options, logger, encoder)
{
_TokenRepository = tokenRepository;
_StoreRepository = storeRepository;

View File

@ -27,8 +27,7 @@ namespace BTCPayServer.Security.Greenfield
IOptionsMonitor<GreenfieldAuthenticationOptions> options,
ILoggerFactory logger,
UrlEncoder encoder,
ISystemClock clock,
UserManager<ApplicationUser> userManager) : base(options, logger, encoder, clock)
UserManager<ApplicationUser> userManager) : base(options, logger, encoder)
{
_apiKeyRepository = apiKeyRepository;
_identityOptions = identityOptions;
@ -45,7 +44,7 @@ namespace BTCPayServer.Security.Greenfield
// the login page.
// But this isn't what we want when we call the API programmatically, instead we want an error 401 with a json error message.
// This hack modify a request's header to trick the CookieAuthenticationHandler to not do a redirection.
if (!Request.Headers.Accept.Any(s => s.StartsWith("text/html", StringComparison.OrdinalIgnoreCase)))
if (!Request.Headers.Accept.Any(s => s is string && s.StartsWith("text/html", StringComparison.OrdinalIgnoreCase)))
Request.Headers.XRequestedWith = new Microsoft.Extensions.Primitives.StringValues("XMLHttpRequest");
return base.HandleChallengeAsync(properties);
}

View File

@ -26,9 +26,8 @@ namespace BTCPayServer.Security.Greenfield
IOptionsMonitor<GreenfieldAuthenticationOptions> options,
ILoggerFactory logger,
UrlEncoder encoder,
ISystemClock clock,
SignInManager<ApplicationUser> signInManager,
UserManager<ApplicationUser> userManager) : base(options, logger, encoder, clock)
UserManager<ApplicationUser> userManager) : base(options, logger, encoder)
{
_identityOptions = identityOptions;
_signInManager = signInManager;

View File

@ -47,7 +47,7 @@ namespace BTCPayServer.Services
}
public static ApplicationUserData FromModel(ApplicationUser data, string[] roles)
public static ApplicationUserData FromModel(ApplicationUser data, string?[] roles)
{
return new ApplicationUserData()
{
@ -112,6 +112,8 @@ namespace BTCPayServer.Services
using var scope = _serviceProvider.CreateScope();
var userManager = scope.ServiceProvider.GetRequiredService<UserManager<ApplicationUser>>();
var user = await userManager.FindByIdAsync(userId);
if (user is null)
return false;
IdentityResult res;
if (enableAdmin)
{
@ -147,7 +149,9 @@ namespace BTCPayServer.Services
await Task.WhenAll(files.Select(file => _fileService.RemoveFile(file.Id, userId)));
user = await userManager.FindByIdAsync(userId);
user = (await userManager.FindByIdAsync(userId))!;
if (user is null)
return;
var res = await userManager.DeleteAsync(user);
if (res.Succeeded)
{

View File

@ -1,4 +1,3 @@
@using BTCPayServer.Lightning
@using BTCPayServer.Client
@using BTCPayServer.Services
@model LightningViewModel
@ -28,7 +27,7 @@
<span>(@uri.Host)</span>
}
}
catch (Exception e)
catch (Exception)
{
@Model.ConnectionString
}

View File

@ -1,4 +1,3 @@
@using BTCPayServer.Lightning
@using BTCPayServer.Services
@model LightningSettingsViewModel
@inject LightningClientFactoryService LightningClientFactoryService
@ -28,7 +27,7 @@
<span>(@uri.Host)</span>
}
}
catch (Exception e)
catch (Exception)
{
@Model.ConnectionString
}

View File

@ -2,7 +2,7 @@
<PropertyGroup>
<TargetFramework>net8.0</TargetFramework>
<TargetFramework Condition="'$(TargetFrameworkOverride)' != ''">$(TargetFrameworkOverride)</TargetFramework>
<NoWarn>NU1701,CA1816,CA1308,CA1810,CA2208,CA1303,CA2000,CA2016,CA1835,CA2249,CA9998,CA1704;CS8981</NoWarn>
<NoWarn>$(NoWarn),NU1701,CA1816,CA1308,CA1810,CA2208,CA1303,CA2000,CA2016,CA1835,CA2249,CA9998,CA1704;CS8981</NoWarn>
<LangVersion>12.0</LangVersion>
<EnableNETAnalyzers>True</EnableNETAnalyzers>
<AnalysisLevel>6.0</AnalysisLevel>