Adding support for .NET 8.0 LTS, renaming private fields to start with underscore
This commit is contained in:
@@ -22,28 +22,28 @@ namespace UnitTests.AspNetCore.Attributes
|
||||
[System.Diagnostics.CodeAnalysis.ExcludeFromCodeCoverage]
|
||||
public class BasicAuthenticationAttributeTests
|
||||
{
|
||||
private Mock<IHeaderDictionary> requestHeaderMock;
|
||||
private Mock<IHeaderDictionary> responseHeaderMock;
|
||||
private Mock<IHeaderDictionary> _requestHeaderMock;
|
||||
private Mock<IHeaderDictionary> _responseHeaderMock;
|
||||
|
||||
private Mock<HttpRequest> requestMock;
|
||||
private Mock<HttpResponse> responseMock;
|
||||
private Mock<HttpRequest> _requestMock;
|
||||
private Mock<HttpResponse> _responseMock;
|
||||
|
||||
private Mock<HttpContext> contextMock;
|
||||
private Mock<HttpContext> _contextMock;
|
||||
|
||||
private Dictionary<string, string> requestHeaders;
|
||||
private string validatorRealm;
|
||||
private ClaimsPrincipal validatorResult;
|
||||
private Dictionary<string, string> _requestHeaders;
|
||||
private string _validatorRealm;
|
||||
private ClaimsPrincipal _validatorResult;
|
||||
|
||||
private string responseHeaderAuthCallback;
|
||||
private string _responseHeaderAuthCallback;
|
||||
|
||||
[TestInitialize]
|
||||
public void InitializeTest()
|
||||
{
|
||||
requestHeaders = new Dictionary<string, string>();
|
||||
validatorRealm = null;
|
||||
validatorResult = null;
|
||||
_requestHeaders = [];
|
||||
_validatorRealm = null;
|
||||
_validatorResult = null;
|
||||
|
||||
responseHeaderAuthCallback = null;
|
||||
_responseHeaderAuthCallback = null;
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
@@ -55,7 +55,7 @@ namespace UnitTests.AspNetCore.Attributes
|
||||
Username = "user",
|
||||
Password = "password"
|
||||
};
|
||||
requestHeaders.Add("Authorization", $"Basic {Convert.ToBase64String(Encoding.UTF8.GetBytes($"{attribute.Username}:{attribute.Password}"))}");
|
||||
_requestHeaders.Add("Authorization", $"Basic {Convert.ToBase64String(Encoding.UTF8.GetBytes($"{attribute.Username}:{attribute.Password}"))}");
|
||||
|
||||
var context = GetContext();
|
||||
|
||||
@@ -64,7 +64,7 @@ namespace UnitTests.AspNetCore.Attributes
|
||||
|
||||
// assert
|
||||
Assert.IsNull(context.Result);
|
||||
Assert.IsTrue(string.IsNullOrWhiteSpace(responseHeaderAuthCallback));
|
||||
Assert.IsTrue(string.IsNullOrWhiteSpace(_responseHeaderAuthCallback));
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
@@ -72,8 +72,8 @@ namespace UnitTests.AspNetCore.Attributes
|
||||
{
|
||||
// arrange
|
||||
var attribute = new BasicAuthenticationAttribute();
|
||||
requestHeaders.Add("Authorization", $"Basic {Convert.ToBase64String(Encoding.UTF8.GetBytes($"{attribute.Username}:{attribute.Password}"))}");
|
||||
validatorResult = new ClaimsPrincipal();
|
||||
_requestHeaders.Add("Authorization", $"Basic {Convert.ToBase64String(Encoding.UTF8.GetBytes($"{attribute.Username}:{attribute.Password}"))}");
|
||||
_validatorResult = new ClaimsPrincipal();
|
||||
|
||||
var context = GetContext(hasValidator: true);
|
||||
|
||||
@@ -82,7 +82,7 @@ namespace UnitTests.AspNetCore.Attributes
|
||||
|
||||
// assert
|
||||
Assert.IsNull(context.Result);
|
||||
Assert.IsTrue(string.IsNullOrWhiteSpace(responseHeaderAuthCallback));
|
||||
Assert.IsTrue(string.IsNullOrWhiteSpace(_responseHeaderAuthCallback));
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
@@ -101,7 +101,7 @@ namespace UnitTests.AspNetCore.Attributes
|
||||
|
||||
// assert
|
||||
Assert.IsNull(context.Result);
|
||||
Assert.IsTrue(string.IsNullOrWhiteSpace(responseHeaderAuthCallback));
|
||||
Assert.IsTrue(string.IsNullOrWhiteSpace(_responseHeaderAuthCallback));
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
@@ -123,8 +123,8 @@ namespace UnitTests.AspNetCore.Attributes
|
||||
Assert.IsTrue(context.Result is StatusCodeResult);
|
||||
Assert.AreEqual(401, ((StatusCodeResult)context.Result).StatusCode);
|
||||
|
||||
Assert.IsFalse(string.IsNullOrWhiteSpace(responseHeaderAuthCallback));
|
||||
Assert.AreEqual("Basic", responseHeaderAuthCallback);
|
||||
Assert.IsFalse(string.IsNullOrWhiteSpace(_responseHeaderAuthCallback));
|
||||
Assert.AreEqual("Basic", _responseHeaderAuthCallback);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
@@ -147,8 +147,8 @@ namespace UnitTests.AspNetCore.Attributes
|
||||
Assert.IsTrue(context.Result is StatusCodeResult);
|
||||
Assert.AreEqual(401, ((StatusCodeResult)context.Result).StatusCode);
|
||||
|
||||
Assert.IsFalse(string.IsNullOrWhiteSpace(responseHeaderAuthCallback));
|
||||
Assert.AreEqual("Basic realm=\"re:alm\"", responseHeaderAuthCallback);
|
||||
Assert.IsFalse(string.IsNullOrWhiteSpace(_responseHeaderAuthCallback));
|
||||
Assert.AreEqual("Basic realm=\"re:alm\"", _responseHeaderAuthCallback);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
@@ -160,7 +160,7 @@ namespace UnitTests.AspNetCore.Attributes
|
||||
Username = "user",
|
||||
Password = "password"
|
||||
};
|
||||
requestHeaders.Add("Authorization", $"Basic {Convert.ToBase64String(Encoding.UTF8.GetBytes($"{attribute.Username}a:{attribute.Password}"))}");
|
||||
_requestHeaders.Add("Authorization", $"Basic {Convert.ToBase64String(Encoding.UTF8.GetBytes($"{attribute.Username}a:{attribute.Password}"))}");
|
||||
var context = GetContext();
|
||||
|
||||
// act
|
||||
@@ -171,8 +171,8 @@ namespace UnitTests.AspNetCore.Attributes
|
||||
Assert.IsTrue(context.Result is StatusCodeResult);
|
||||
Assert.AreEqual(401, ((StatusCodeResult)context.Result).StatusCode);
|
||||
|
||||
Assert.IsFalse(string.IsNullOrWhiteSpace(responseHeaderAuthCallback));
|
||||
Assert.AreEqual("Basic", responseHeaderAuthCallback);
|
||||
Assert.IsFalse(string.IsNullOrWhiteSpace(_responseHeaderAuthCallback));
|
||||
Assert.AreEqual("Basic", _responseHeaderAuthCallback);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
@@ -184,7 +184,7 @@ namespace UnitTests.AspNetCore.Attributes
|
||||
Username = "user",
|
||||
Password = "password"
|
||||
};
|
||||
requestHeaders.Add("Authorization", $"Basic {Convert.ToBase64String(Encoding.UTF8.GetBytes($"{attribute.Username}:{attribute.Password}a"))}");
|
||||
_requestHeaders.Add("Authorization", $"Basic {Convert.ToBase64String(Encoding.UTF8.GetBytes($"{attribute.Username}:{attribute.Password}a"))}");
|
||||
var context = GetContext();
|
||||
|
||||
// act
|
||||
@@ -195,8 +195,8 @@ namespace UnitTests.AspNetCore.Attributes
|
||||
Assert.IsTrue(context.Result is StatusCodeResult);
|
||||
Assert.AreEqual(401, ((StatusCodeResult)context.Result).StatusCode);
|
||||
|
||||
Assert.IsFalse(string.IsNullOrWhiteSpace(responseHeaderAuthCallback));
|
||||
Assert.AreEqual("Basic", responseHeaderAuthCallback);
|
||||
Assert.IsFalse(string.IsNullOrWhiteSpace(_responseHeaderAuthCallback));
|
||||
Assert.AreEqual("Basic", _responseHeaderAuthCallback);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
@@ -207,7 +207,7 @@ namespace UnitTests.AspNetCore.Attributes
|
||||
{
|
||||
Realm = "attribute"
|
||||
};
|
||||
requestHeaders.Add("Authorization", $"Basic {Convert.ToBase64String(Encoding.UTF8.GetBytes($"{attribute.Username}:{attribute.Password}"))}");
|
||||
_requestHeaders.Add("Authorization", $"Basic {Convert.ToBase64String(Encoding.UTF8.GetBytes($"{attribute.Username}:{attribute.Password}"))}");
|
||||
var context = GetContext(hasValidator: true);
|
||||
|
||||
// act
|
||||
@@ -218,17 +218,17 @@ namespace UnitTests.AspNetCore.Attributes
|
||||
Assert.IsTrue(context.Result is StatusCodeResult);
|
||||
Assert.AreEqual(401, ((StatusCodeResult)context.Result).StatusCode);
|
||||
|
||||
Assert.IsFalse(string.IsNullOrWhiteSpace(responseHeaderAuthCallback));
|
||||
Assert.AreEqual("Basic realm=\"attribute\"", responseHeaderAuthCallback);
|
||||
Assert.IsFalse(string.IsNullOrWhiteSpace(_responseHeaderAuthCallback));
|
||||
Assert.AreEqual("Basic realm=\"attribute\"", _responseHeaderAuthCallback);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public async Task ShouldAskOnValidatorWithRealmOnValidator()
|
||||
{
|
||||
// arrange
|
||||
validatorRealm = "validator";
|
||||
_validatorRealm = "validator";
|
||||
var attribute = new BasicAuthenticationAttribute();
|
||||
requestHeaders.Add("Authorization", $"Basic {Convert.ToBase64String(Encoding.UTF8.GetBytes($"{attribute.Username}:{attribute.Password}"))}");
|
||||
_requestHeaders.Add("Authorization", $"Basic {Convert.ToBase64String(Encoding.UTF8.GetBytes($"{attribute.Username}:{attribute.Password}"))}");
|
||||
var context = GetContext(hasValidator: true);
|
||||
|
||||
// act
|
||||
@@ -239,8 +239,8 @@ namespace UnitTests.AspNetCore.Attributes
|
||||
Assert.IsTrue(context.Result is StatusCodeResult);
|
||||
Assert.AreEqual(401, ((StatusCodeResult)context.Result).StatusCode);
|
||||
|
||||
Assert.IsFalse(string.IsNullOrWhiteSpace(responseHeaderAuthCallback));
|
||||
Assert.AreEqual("Basic realm=\"validator\"", responseHeaderAuthCallback);
|
||||
Assert.IsFalse(string.IsNullOrWhiteSpace(_responseHeaderAuthCallback));
|
||||
Assert.AreEqual("Basic realm=\"validator\"", _responseHeaderAuthCallback);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
@@ -248,7 +248,7 @@ namespace UnitTests.AspNetCore.Attributes
|
||||
{
|
||||
// arrange
|
||||
var attribute = new BasicAuthenticationAttribute();
|
||||
requestHeaders.Add("Authorization", $"Basic {Convert.ToBase64String(Encoding.UTF8.GetBytes($"{attribute.Username}"))}");
|
||||
_requestHeaders.Add("Authorization", $"Basic {Convert.ToBase64String(Encoding.UTF8.GetBytes($"{attribute.Username}"))}");
|
||||
var context = GetContext();
|
||||
|
||||
// act
|
||||
@@ -262,34 +262,38 @@ namespace UnitTests.AspNetCore.Attributes
|
||||
|
||||
private AuthorizationFilterContext GetContext(bool isAnonymousAllowed = false, bool hasValidator = false)
|
||||
{
|
||||
requestHeaderMock = new Mock<IHeaderDictionary>();
|
||||
foreach (var header in requestHeaders)
|
||||
_requestHeaderMock = new Mock<IHeaderDictionary>();
|
||||
foreach (var header in _requestHeaders)
|
||||
{
|
||||
requestHeaderMock
|
||||
StringValues outVal = header.Value;
|
||||
_requestHeaderMock
|
||||
.Setup(h => h.ContainsKey(header.Key))
|
||||
.Returns(true);
|
||||
requestHeaderMock
|
||||
_requestHeaderMock
|
||||
.Setup(h => h[header.Key])
|
||||
.Returns(header.Value);
|
||||
_requestHeaderMock
|
||||
.Setup(h => h.TryGetValue(header.Key, out outVal))
|
||||
.Returns(true);
|
||||
}
|
||||
|
||||
responseHeaderMock = new Mock<IHeaderDictionary>();
|
||||
responseHeaderMock
|
||||
.SetupSet(h => h["WWW-Authenticate"] = It.IsAny<StringValues>())
|
||||
.Callback<string, StringValues>((key, value) =>
|
||||
_responseHeaderMock = new Mock<IHeaderDictionary>();
|
||||
_responseHeaderMock
|
||||
.SetupSet(h => h.WWWAuthenticate = It.IsAny<StringValues>())
|
||||
.Callback<StringValues>((value) =>
|
||||
{
|
||||
responseHeaderAuthCallback = value;
|
||||
_responseHeaderAuthCallback = value;
|
||||
});
|
||||
|
||||
requestMock = new Mock<HttpRequest>();
|
||||
requestMock
|
||||
_requestMock = new Mock<HttpRequest>();
|
||||
_requestMock
|
||||
.Setup(r => r.Headers)
|
||||
.Returns(requestHeaderMock.Object);
|
||||
.Returns(_requestHeaderMock.Object);
|
||||
|
||||
responseMock = new Mock<HttpResponse>();
|
||||
responseMock
|
||||
_responseMock = new Mock<HttpResponse>();
|
||||
_responseMock
|
||||
.Setup(r => r.Headers)
|
||||
.Returns(responseHeaderMock.Object);
|
||||
.Returns(_responseHeaderMock.Object);
|
||||
|
||||
var requestServicesMock = new Mock<IServiceProvider>();
|
||||
|
||||
@@ -298,10 +302,10 @@ namespace UnitTests.AspNetCore.Attributes
|
||||
var validatorMock = new Mock<IBasicAuthenticationValidator>();
|
||||
validatorMock
|
||||
.Setup(v => v.Realm)
|
||||
.Returns(validatorRealm);
|
||||
.Returns(_validatorRealm);
|
||||
validatorMock
|
||||
.Setup(v => v.ValidateAsync(It.IsAny<string>(), It.IsAny<string>(), It.IsAny<IPAddress>(), It.IsAny<CancellationToken>()))
|
||||
.ReturnsAsync(validatorResult);
|
||||
.ReturnsAsync(_validatorResult);
|
||||
|
||||
requestServicesMock
|
||||
.Setup(rs => rs.GetService(typeof(IBasicAuthenticationValidator)))
|
||||
@@ -313,20 +317,20 @@ namespace UnitTests.AspNetCore.Attributes
|
||||
.Setup(ci => ci.RemoteIpAddress)
|
||||
.Returns(IPAddress.Loopback);
|
||||
|
||||
contextMock = new Mock<HttpContext>();
|
||||
contextMock
|
||||
_contextMock = new Mock<HttpContext>();
|
||||
_contextMock
|
||||
.Setup(c => c.Request)
|
||||
.Returns(requestMock.Object);
|
||||
contextMock
|
||||
.Returns(_requestMock.Object);
|
||||
_contextMock
|
||||
.Setup(c => c.Response)
|
||||
.Returns(responseMock.Object);
|
||||
contextMock
|
||||
.Returns(_responseMock.Object);
|
||||
_contextMock
|
||||
.Setup(c => c.RequestServices)
|
||||
.Returns(requestServicesMock.Object);
|
||||
contextMock
|
||||
_contextMock
|
||||
.Setup(c => c.Connection)
|
||||
.Returns(connectionInfoMock.Object);
|
||||
contextMock
|
||||
_contextMock
|
||||
.Setup(c => c.RequestAborted)
|
||||
.Returns(CancellationToken.None);
|
||||
|
||||
@@ -341,7 +345,7 @@ namespace UnitTests.AspNetCore.Attributes
|
||||
|
||||
return new AuthorizationFilterContext(new ActionContext
|
||||
{
|
||||
HttpContext = contextMock.Object,
|
||||
HttpContext = _contextMock.Object,
|
||||
RouteData = routeDataMock.Object,
|
||||
ActionDescriptor = actionDescriptor,
|
||||
}, new List<IFilterMetadata>());
|
||||
|
||||
@@ -16,20 +16,20 @@ namespace UnitTests.AspNetCore.Attributes
|
||||
[System.Diagnostics.CodeAnalysis.ExcludeFromCodeCoverage]
|
||||
public class IPAllowListAttributeTests
|
||||
{
|
||||
private Dictionary<string, string> requestHeaders;
|
||||
private Dictionary<object, object> itemsCallback;
|
||||
private string configKey;
|
||||
private bool configExists;
|
||||
private List<string> allowedIpsConfig;
|
||||
private Dictionary<string, string> _requestHeaders;
|
||||
private Dictionary<object, object> _itemsCallback;
|
||||
private string _configKey;
|
||||
private bool _configExists;
|
||||
private List<string> _allowedIpsConfig;
|
||||
|
||||
[TestInitialize]
|
||||
public void InitializeTest()
|
||||
{
|
||||
requestHeaders = new Dictionary<string, string>();
|
||||
itemsCallback = new Dictionary<object, object>();
|
||||
configKey = null;
|
||||
configExists = false;
|
||||
allowedIpsConfig = new List<string>();
|
||||
_requestHeaders = [];
|
||||
_itemsCallback = [];
|
||||
_configKey = null;
|
||||
_configExists = false;
|
||||
_allowedIpsConfig = [];
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
@@ -48,8 +48,8 @@ namespace UnitTests.AspNetCore.Attributes
|
||||
Assert.IsTrue(context.Result is StatusCodeResult);
|
||||
Assert.AreEqual(403, ((StatusCodeResult)context.Result).StatusCode);
|
||||
|
||||
Assert.AreEqual(1, itemsCallback.Count);
|
||||
Assert.AreEqual(remote, itemsCallback["RemoteAddress"]);
|
||||
Assert.AreEqual(1, _itemsCallback.Count);
|
||||
Assert.AreEqual(remote, _itemsCallback["RemoteAddress"]);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
@@ -71,8 +71,8 @@ namespace UnitTests.AspNetCore.Attributes
|
||||
Assert.IsTrue(context.Result is StatusCodeResult);
|
||||
Assert.AreEqual(403, ((StatusCodeResult)context.Result).StatusCode);
|
||||
|
||||
Assert.AreEqual(1, itemsCallback.Count);
|
||||
Assert.AreEqual(remote, itemsCallback["RemoteAddress"]);
|
||||
Assert.AreEqual(1, _itemsCallback.Count);
|
||||
Assert.AreEqual(remote, _itemsCallback["RemoteAddress"]);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
@@ -87,8 +87,8 @@ namespace UnitTests.AspNetCore.Attributes
|
||||
|
||||
// assert
|
||||
Assert.IsNull(context.Result);
|
||||
Assert.AreEqual(1, itemsCallback.Count);
|
||||
Assert.AreEqual(IPAddress.Loopback, itemsCallback["RemoteAddress"]);
|
||||
Assert.AreEqual(1, _itemsCallback.Count);
|
||||
Assert.AreEqual(IPAddress.Loopback, _itemsCallback["RemoteAddress"]);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
@@ -109,8 +109,8 @@ namespace UnitTests.AspNetCore.Attributes
|
||||
Assert.IsTrue(context.Result is StatusCodeResult);
|
||||
Assert.AreEqual(403, ((StatusCodeResult)context.Result).StatusCode);
|
||||
|
||||
Assert.AreEqual(1, itemsCallback.Count);
|
||||
Assert.AreEqual(IPAddress.Loopback, itemsCallback["RemoteAddress"]);
|
||||
Assert.AreEqual(1, _itemsCallback.Count);
|
||||
Assert.AreEqual(IPAddress.Loopback, _itemsCallback["RemoteAddress"]);
|
||||
}
|
||||
|
||||
[DataTestMethod]
|
||||
@@ -142,22 +142,22 @@ namespace UnitTests.AspNetCore.Attributes
|
||||
Assert.AreEqual(403, ((StatusCodeResult)context.Result).StatusCode);
|
||||
}
|
||||
|
||||
Assert.AreEqual(1, itemsCallback.Count);
|
||||
Assert.AreEqual(remote, itemsCallback["RemoteAddress"]);
|
||||
Assert.AreEqual(1, _itemsCallback.Count);
|
||||
Assert.AreEqual(remote, _itemsCallback["RemoteAddress"]);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void ShouldAllowLocalAccessConfig()
|
||||
{
|
||||
// arrange
|
||||
configKey = "White:List";
|
||||
configExists = true;
|
||||
allowedIpsConfig.Add("127.0.0.0/8");
|
||||
allowedIpsConfig.Add("192.168.178.10");
|
||||
_configKey = "White:List";
|
||||
_configExists = true;
|
||||
_allowedIpsConfig.Add("127.0.0.0/8");
|
||||
_allowedIpsConfig.Add("192.168.178.10");
|
||||
var attribute = new IPAllowListAttribute
|
||||
{
|
||||
AllowLocalAccess = true,
|
||||
ConfigurationKey = configKey
|
||||
ConfigurationKey = _configKey
|
||||
};
|
||||
var context = GetContext();
|
||||
|
||||
@@ -166,22 +166,22 @@ namespace UnitTests.AspNetCore.Attributes
|
||||
|
||||
// assert
|
||||
Assert.IsNull(context.Result);
|
||||
Assert.AreEqual(1, itemsCallback.Count);
|
||||
Assert.AreEqual(IPAddress.Loopback, itemsCallback["RemoteAddress"]);
|
||||
Assert.AreEqual(1, _itemsCallback.Count);
|
||||
Assert.AreEqual(IPAddress.Loopback, _itemsCallback["RemoteAddress"]);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void ShouldDenyLocalAccessConfig()
|
||||
{
|
||||
// arrange
|
||||
configKey = "White:List";
|
||||
configExists = true;
|
||||
allowedIpsConfig.Add("");
|
||||
allowedIpsConfig.Add("192.168.178.10");
|
||||
_configKey = "White:List";
|
||||
_configExists = true;
|
||||
_allowedIpsConfig.Add("");
|
||||
_allowedIpsConfig.Add("192.168.178.10");
|
||||
var attribute = new IPAllowListAttribute
|
||||
{
|
||||
AllowLocalAccess = false,
|
||||
ConfigurationKey = configKey
|
||||
ConfigurationKey = _configKey
|
||||
};
|
||||
var context = GetContext();
|
||||
|
||||
@@ -193,8 +193,8 @@ namespace UnitTests.AspNetCore.Attributes
|
||||
Assert.IsTrue(context.Result is StatusCodeResult);
|
||||
Assert.AreEqual(403, ((StatusCodeResult)context.Result).StatusCode);
|
||||
|
||||
Assert.AreEqual(1, itemsCallback.Count);
|
||||
Assert.AreEqual(IPAddress.Loopback, itemsCallback["RemoteAddress"]);
|
||||
Assert.AreEqual(1, _itemsCallback.Count);
|
||||
Assert.AreEqual(IPAddress.Loopback, _itemsCallback["RemoteAddress"]);
|
||||
}
|
||||
|
||||
[DataTestMethod]
|
||||
@@ -203,13 +203,13 @@ namespace UnitTests.AspNetCore.Attributes
|
||||
public void ShouldAllowSpecificAddressConfig(string address)
|
||||
{
|
||||
// arrange
|
||||
configKey = "White:List";
|
||||
configExists = true;
|
||||
allowedIpsConfig.Add("192.168.178.10");
|
||||
_configKey = "White:List";
|
||||
_configExists = true;
|
||||
_allowedIpsConfig.Add("192.168.178.10");
|
||||
var attribute = new IPAllowListAttribute
|
||||
{
|
||||
AllowLocalAccess = false,
|
||||
ConfigurationKey = configKey
|
||||
ConfigurationKey = _configKey
|
||||
};
|
||||
var remote = IPAddress.Parse(address);
|
||||
var context = GetContext(remote);
|
||||
@@ -229,20 +229,20 @@ namespace UnitTests.AspNetCore.Attributes
|
||||
Assert.AreEqual(403, ((StatusCodeResult)context.Result).StatusCode);
|
||||
}
|
||||
|
||||
Assert.AreEqual(1, itemsCallback.Count);
|
||||
Assert.AreEqual(remote, itemsCallback["RemoteAddress"]);
|
||||
Assert.AreEqual(1, _itemsCallback.Count);
|
||||
Assert.AreEqual(remote, _itemsCallback["RemoteAddress"]);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void ShouldDenyOnMissingConfiguration()
|
||||
{
|
||||
// arrange
|
||||
configKey = "White:List";
|
||||
configExists = false;
|
||||
_configKey = "White:List";
|
||||
_configExists = false;
|
||||
var attribute = new IPAllowListAttribute
|
||||
{
|
||||
AllowLocalAccess = false,
|
||||
ConfigurationKey = configKey
|
||||
ConfigurationKey = _configKey
|
||||
};
|
||||
var context = GetContext();
|
||||
|
||||
@@ -254,14 +254,14 @@ namespace UnitTests.AspNetCore.Attributes
|
||||
Assert.IsTrue(context.Result is StatusCodeResult);
|
||||
Assert.AreEqual(403, ((StatusCodeResult)context.Result).StatusCode);
|
||||
|
||||
Assert.AreEqual(1, itemsCallback.Count);
|
||||
Assert.AreEqual(IPAddress.Loopback, itemsCallback["RemoteAddress"]);
|
||||
Assert.AreEqual(1, _itemsCallback.Count);
|
||||
Assert.AreEqual(IPAddress.Loopback, _itemsCallback["RemoteAddress"]);
|
||||
}
|
||||
|
||||
private ActionExecutingContext GetContext(IPAddress remote = null)
|
||||
{
|
||||
var requestHeaderMock = new Mock<IHeaderDictionary>();
|
||||
foreach (var header in requestHeaders)
|
||||
foreach (var header in _requestHeaders)
|
||||
{
|
||||
requestHeaderMock
|
||||
.Setup(h => h.ContainsKey(header.Key))
|
||||
@@ -287,11 +287,11 @@ namespace UnitTests.AspNetCore.Attributes
|
||||
var itemsMock = new Mock<IDictionary<object, object>>();
|
||||
itemsMock
|
||||
.SetupSet(i => i[It.IsAny<object>()] = It.IsAny<object>())
|
||||
.Callback<object, object>((key, val) => itemsCallback.Add(key, val));
|
||||
.Callback<object, object>((key, val) => _itemsCallback.Add(key, val));
|
||||
|
||||
var configurationMock = new Mock<IConfiguration>();
|
||||
var children = new List<IConfigurationSection>();
|
||||
foreach (string ipAddress in allowedIpsConfig)
|
||||
foreach (string ipAddress in _allowedIpsConfig)
|
||||
{
|
||||
var csm = new Mock<IConfigurationSection>();
|
||||
csm.Setup(cs => cs.Value).Returns(ipAddress);
|
||||
@@ -305,8 +305,8 @@ namespace UnitTests.AspNetCore.Attributes
|
||||
.Returns(children);
|
||||
|
||||
configurationMock
|
||||
.Setup(c => c.GetSection(configKey))
|
||||
.Returns(configExists ? configSectionMock.Object : null);
|
||||
.Setup(c => c.GetSection(_configKey))
|
||||
.Returns(_configExists ? configSectionMock.Object : null);
|
||||
|
||||
var requestServicesMock = new Mock<IServiceProvider>();
|
||||
requestServicesMock
|
||||
|
||||
@@ -16,20 +16,20 @@ namespace UnitTests.AspNetCore.Attributes
|
||||
[System.Diagnostics.CodeAnalysis.ExcludeFromCodeCoverage]
|
||||
public class IPBlockListAttributeTests
|
||||
{
|
||||
private Dictionary<string, string> requestHeaders;
|
||||
private Dictionary<object, object> itemsCallback;
|
||||
private string configKey;
|
||||
private bool configExists;
|
||||
private List<string> restrictedIpsConfig;
|
||||
private Dictionary<string, string> _requestHeaders;
|
||||
private Dictionary<object, object> _itemsCallback;
|
||||
private string _configKey;
|
||||
private bool _configExists;
|
||||
private List<string> _restrictedIpsConfig;
|
||||
|
||||
[TestInitialize]
|
||||
public void InitializeTest()
|
||||
{
|
||||
requestHeaders = new Dictionary<string, string>();
|
||||
itemsCallback = new Dictionary<object, object>();
|
||||
configKey = null;
|
||||
configExists = false;
|
||||
restrictedIpsConfig = new List<string>();
|
||||
_requestHeaders = [];
|
||||
_itemsCallback = [];
|
||||
_configKey = null;
|
||||
_configExists = false;
|
||||
_restrictedIpsConfig = [];
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
@@ -45,8 +45,8 @@ namespace UnitTests.AspNetCore.Attributes
|
||||
|
||||
// assert
|
||||
Assert.IsNull(context.Result);
|
||||
Assert.AreEqual(1, itemsCallback.Count);
|
||||
Assert.AreEqual(remote, itemsCallback["RemoteAddress"]);
|
||||
Assert.AreEqual(1, _itemsCallback.Count);
|
||||
Assert.AreEqual(remote, _itemsCallback["RemoteAddress"]);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
@@ -65,8 +65,8 @@ namespace UnitTests.AspNetCore.Attributes
|
||||
|
||||
// assert
|
||||
Assert.IsNull(context.Result);
|
||||
Assert.AreEqual(1, itemsCallback.Count);
|
||||
Assert.AreEqual(remote, itemsCallback["RemoteAddress"]);
|
||||
Assert.AreEqual(1, _itemsCallback.Count);
|
||||
Assert.AreEqual(remote, _itemsCallback["RemoteAddress"]);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
@@ -85,8 +85,8 @@ namespace UnitTests.AspNetCore.Attributes
|
||||
|
||||
// assert
|
||||
Assert.IsNull(context.Result);
|
||||
Assert.AreEqual(1, itemsCallback.Count);
|
||||
Assert.AreEqual(IPAddress.Loopback, itemsCallback["RemoteAddress"]);
|
||||
Assert.AreEqual(1, _itemsCallback.Count);
|
||||
Assert.AreEqual(IPAddress.Loopback, _itemsCallback["RemoteAddress"]);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
@@ -108,8 +108,8 @@ namespace UnitTests.AspNetCore.Attributes
|
||||
Assert.IsTrue(context.Result is StatusCodeResult);
|
||||
Assert.AreEqual(403, ((StatusCodeResult)context.Result).StatusCode);
|
||||
|
||||
Assert.AreEqual(1, itemsCallback.Count);
|
||||
Assert.AreEqual(IPAddress.Loopback, itemsCallback["RemoteAddress"]);
|
||||
Assert.AreEqual(1, _itemsCallback.Count);
|
||||
Assert.AreEqual(IPAddress.Loopback, _itemsCallback["RemoteAddress"]);
|
||||
}
|
||||
|
||||
[DataTestMethod]
|
||||
@@ -141,22 +141,22 @@ namespace UnitTests.AspNetCore.Attributes
|
||||
Assert.IsNull(context.Result);
|
||||
}
|
||||
|
||||
Assert.AreEqual(1, itemsCallback.Count);
|
||||
Assert.AreEqual(remote, itemsCallback["RemoteAddress"]);
|
||||
Assert.AreEqual(1, _itemsCallback.Count);
|
||||
Assert.AreEqual(remote, _itemsCallback["RemoteAddress"]);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void ShouldAllowLocalAccessConfig()
|
||||
{
|
||||
// arrange
|
||||
configKey = "Black:List";
|
||||
configExists = true;
|
||||
restrictedIpsConfig.Add("127.0.0.0/8");
|
||||
restrictedIpsConfig.Add("192.168.178.10");
|
||||
_configKey = "Black:List";
|
||||
_configExists = true;
|
||||
_restrictedIpsConfig.Add("127.0.0.0/8");
|
||||
_restrictedIpsConfig.Add("192.168.178.10");
|
||||
var attribute = new IPBlockListAttribute
|
||||
{
|
||||
BlockLocalAccess = false,
|
||||
ConfigurationKey = configKey
|
||||
ConfigurationKey = _configKey
|
||||
};
|
||||
var context = GetContext();
|
||||
|
||||
@@ -165,23 +165,23 @@ namespace UnitTests.AspNetCore.Attributes
|
||||
|
||||
// assert
|
||||
Assert.IsNull(context.Result);
|
||||
Assert.AreEqual(1, itemsCallback.Count);
|
||||
Assert.AreEqual(IPAddress.Loopback, itemsCallback["RemoteAddress"]);
|
||||
Assert.AreEqual(1, _itemsCallback.Count);
|
||||
Assert.AreEqual(IPAddress.Loopback, _itemsCallback["RemoteAddress"]);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void ShouldBlockLocalAccessConfig()
|
||||
{
|
||||
// arrange
|
||||
configKey = "Black:List";
|
||||
configExists = true;
|
||||
restrictedIpsConfig.Add("");
|
||||
restrictedIpsConfig.Add("127.0.0.0/8");
|
||||
restrictedIpsConfig.Add("192.168.178.10");
|
||||
_configKey = "Black:List";
|
||||
_configExists = true;
|
||||
_restrictedIpsConfig.Add("");
|
||||
_restrictedIpsConfig.Add("127.0.0.0/8");
|
||||
_restrictedIpsConfig.Add("192.168.178.10");
|
||||
var attribute = new IPBlockListAttribute
|
||||
{
|
||||
BlockLocalAccess = true,
|
||||
ConfigurationKey = configKey
|
||||
ConfigurationKey = _configKey
|
||||
};
|
||||
var context = GetContext();
|
||||
|
||||
@@ -193,8 +193,8 @@ namespace UnitTests.AspNetCore.Attributes
|
||||
Assert.IsTrue(context.Result is StatusCodeResult);
|
||||
Assert.AreEqual(403, ((StatusCodeResult)context.Result).StatusCode);
|
||||
|
||||
Assert.AreEqual(1, itemsCallback.Count);
|
||||
Assert.AreEqual(IPAddress.Loopback, itemsCallback["RemoteAddress"]);
|
||||
Assert.AreEqual(1, _itemsCallback.Count);
|
||||
Assert.AreEqual(IPAddress.Loopback, _itemsCallback["RemoteAddress"]);
|
||||
}
|
||||
|
||||
[DataTestMethod]
|
||||
@@ -203,14 +203,14 @@ namespace UnitTests.AspNetCore.Attributes
|
||||
public void ShouldBlockSpecificAddressConfig(string address)
|
||||
{
|
||||
// arrange
|
||||
configKey = "Black:List";
|
||||
configExists = true;
|
||||
restrictedIpsConfig.Add("127.0.0.0/8");
|
||||
restrictedIpsConfig.Add("192.168.178.10");
|
||||
_configKey = "Black:List";
|
||||
_configExists = true;
|
||||
_restrictedIpsConfig.Add("127.0.0.0/8");
|
||||
_restrictedIpsConfig.Add("192.168.178.10");
|
||||
var attribute = new IPBlockListAttribute
|
||||
{
|
||||
BlockLocalAccess = true,
|
||||
ConfigurationKey = configKey
|
||||
ConfigurationKey = _configKey
|
||||
};
|
||||
var remote = IPAddress.Parse(address);
|
||||
var context = GetContext(remote);
|
||||
@@ -230,20 +230,20 @@ namespace UnitTests.AspNetCore.Attributes
|
||||
Assert.IsNull(context.Result);
|
||||
}
|
||||
|
||||
Assert.AreEqual(1, itemsCallback.Count);
|
||||
Assert.AreEqual(remote, itemsCallback["RemoteAddress"]);
|
||||
Assert.AreEqual(1, _itemsCallback.Count);
|
||||
Assert.AreEqual(remote, _itemsCallback["RemoteAddress"]);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void ShouldAllowOnMissingConfiguration()
|
||||
{
|
||||
// arrange
|
||||
configKey = "Black:List";
|
||||
configExists = false;
|
||||
_configKey = "Black:List";
|
||||
_configExists = false;
|
||||
var attribute = new IPBlockListAttribute
|
||||
{
|
||||
BlockLocalAccess = true,
|
||||
ConfigurationKey = configKey
|
||||
ConfigurationKey = _configKey
|
||||
};
|
||||
var context = GetContext();
|
||||
|
||||
@@ -253,14 +253,14 @@ namespace UnitTests.AspNetCore.Attributes
|
||||
// assert
|
||||
Assert.IsNull(context.Result);
|
||||
|
||||
Assert.AreEqual(1, itemsCallback.Count);
|
||||
Assert.AreEqual(IPAddress.Loopback, itemsCallback["RemoteAddress"]);
|
||||
Assert.AreEqual(1, _itemsCallback.Count);
|
||||
Assert.AreEqual(IPAddress.Loopback, _itemsCallback["RemoteAddress"]);
|
||||
}
|
||||
|
||||
private ActionExecutingContext GetContext(IPAddress remote = null)
|
||||
{
|
||||
var requestHeaderMock = new Mock<IHeaderDictionary>();
|
||||
foreach (var header in requestHeaders)
|
||||
foreach (var header in _requestHeaders)
|
||||
{
|
||||
requestHeaderMock
|
||||
.Setup(h => h.ContainsKey(header.Key))
|
||||
@@ -286,11 +286,11 @@ namespace UnitTests.AspNetCore.Attributes
|
||||
var itemsMock = new Mock<IDictionary<object, object>>();
|
||||
itemsMock
|
||||
.SetupSet(i => i[It.IsAny<object>()] = It.IsAny<object>())
|
||||
.Callback<object, object>((key, val) => itemsCallback.Add(key, val));
|
||||
.Callback<object, object>((key, val) => _itemsCallback.Add(key, val));
|
||||
|
||||
var configurationMock = new Mock<IConfiguration>();
|
||||
var children = new List<IConfigurationSection>();
|
||||
foreach (string ipAddress in restrictedIpsConfig)
|
||||
foreach (string ipAddress in _restrictedIpsConfig)
|
||||
{
|
||||
var csm = new Mock<IConfigurationSection>();
|
||||
csm.Setup(cs => cs.Value).Returns(ipAddress);
|
||||
@@ -304,8 +304,8 @@ namespace UnitTests.AspNetCore.Attributes
|
||||
.Returns(children);
|
||||
|
||||
configurationMock
|
||||
.Setup(c => c.GetSection(configKey))
|
||||
.Returns(configExists ? configSectionMock.Object : null);
|
||||
.Setup(c => c.GetSection(_configKey))
|
||||
.Returns(_configExists ? configSectionMock.Object : null);
|
||||
|
||||
var requestServicesMock = new Mock<IServiceProvider>();
|
||||
requestServicesMock
|
||||
|
||||
@@ -12,30 +12,30 @@ namespace UnitTests.AspNetCore.Extensions
|
||||
[System.Diagnostics.CodeAnalysis.ExcludeFromCodeCoverage]
|
||||
public class HttpContextExtensionsTests
|
||||
{
|
||||
private Mock<ISession> sessionMock;
|
||||
private Mock<ISession> _sessionMock;
|
||||
|
||||
private string tokenFormName;
|
||||
private string tokenHeaderName;
|
||||
private string tokenValue;
|
||||
private string _tokenFormName;
|
||||
private string _tokenHeaderName;
|
||||
private string _tokenValue;
|
||||
|
||||
private Dictionary<string, string> requestHeaders;
|
||||
private Dictionary<string, string> requestQueries;
|
||||
private Dictionary<object, object> items;
|
||||
private Dictionary<string, string> _requestHeaders;
|
||||
private Dictionary<string, string> _requestQueries;
|
||||
private Dictionary<object, object> _items;
|
||||
|
||||
private IPAddress remote;
|
||||
private IPAddress _remote;
|
||||
|
||||
[TestInitialize]
|
||||
public void InitializeTests()
|
||||
{
|
||||
tokenFormName = null;
|
||||
tokenHeaderName = null;
|
||||
tokenValue = null;
|
||||
_tokenFormName = null;
|
||||
_tokenHeaderName = null;
|
||||
_tokenValue = null;
|
||||
|
||||
requestHeaders = new Dictionary<string, string>();
|
||||
requestQueries = new Dictionary<string, string>();
|
||||
items = new Dictionary<object, object>();
|
||||
_requestHeaders = [];
|
||||
_requestQueries = [];
|
||||
_items = [];
|
||||
|
||||
remote = IPAddress.Loopback;
|
||||
_remote = IPAddress.Loopback;
|
||||
}
|
||||
|
||||
#region Antiforgery
|
||||
@@ -44,9 +44,9 @@ namespace UnitTests.AspNetCore.Extensions
|
||||
public void ShouldReturnAntiforgery()
|
||||
{
|
||||
// arrange
|
||||
tokenFormName = "af-token";
|
||||
tokenHeaderName = "af-header";
|
||||
tokenValue = "security_first";
|
||||
_tokenFormName = "af-token";
|
||||
_tokenHeaderName = "af-header";
|
||||
_tokenValue = "security_first";
|
||||
|
||||
var context = GetContext();
|
||||
|
||||
@@ -54,18 +54,18 @@ namespace UnitTests.AspNetCore.Extensions
|
||||
var (formName, headerName, value) = context.GetAntiforgeryToken();
|
||||
|
||||
// assert
|
||||
Assert.AreEqual(tokenFormName, formName);
|
||||
Assert.AreEqual(tokenHeaderName, headerName);
|
||||
Assert.AreEqual(tokenValue, value);
|
||||
Assert.AreEqual(_tokenFormName, formName);
|
||||
Assert.AreEqual(_tokenHeaderName, headerName);
|
||||
Assert.AreEqual(_tokenValue, value);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void ShouldReturnAntiforgeryNullService()
|
||||
{
|
||||
// arrange
|
||||
tokenFormName = "af-token";
|
||||
tokenHeaderName = "af-header";
|
||||
tokenValue = "security_first";
|
||||
_tokenFormName = "af-token";
|
||||
_tokenHeaderName = "af-header";
|
||||
_tokenValue = "security_first";
|
||||
|
||||
var context = GetContext(hasAntiforgery: false);
|
||||
|
||||
@@ -101,7 +101,7 @@ namespace UnitTests.AspNetCore.Extensions
|
||||
public void ShouldReturnRemoteAddress()
|
||||
{
|
||||
// arrange
|
||||
remote = IPAddress.Parse("1.2.3.4");
|
||||
_remote = IPAddress.Parse("1.2.3.4");
|
||||
|
||||
var context = GetContext();
|
||||
|
||||
@@ -109,7 +109,7 @@ namespace UnitTests.AspNetCore.Extensions
|
||||
var result = context.GetRemoteIpAddress();
|
||||
|
||||
// assert
|
||||
Assert.AreEqual(remote, result);
|
||||
Assert.AreEqual(_remote, result);
|
||||
}
|
||||
|
||||
[DataTestMethod]
|
||||
@@ -119,9 +119,9 @@ namespace UnitTests.AspNetCore.Extensions
|
||||
public void ShouldReturnDefaultHeader(string headerName)
|
||||
{
|
||||
// arrange
|
||||
remote = IPAddress.Parse("1.2.3.4");
|
||||
_remote = IPAddress.Parse("1.2.3.4");
|
||||
var header = IPAddress.Parse("5.6.7.8");
|
||||
requestHeaders.Add(headerName, header.ToString());
|
||||
_requestHeaders.Add(headerName, header.ToString());
|
||||
|
||||
var context = GetContext();
|
||||
|
||||
@@ -129,7 +129,7 @@ namespace UnitTests.AspNetCore.Extensions
|
||||
var result = context.GetRemoteIpAddress();
|
||||
|
||||
// assert
|
||||
Assert.AreNotEqual(remote, result);
|
||||
Assert.AreNotEqual(_remote, result);
|
||||
Assert.AreEqual(header, result);
|
||||
}
|
||||
|
||||
@@ -137,12 +137,12 @@ namespace UnitTests.AspNetCore.Extensions
|
||||
public void ShouldReturnCustomHeader()
|
||||
{
|
||||
// arrange
|
||||
remote = IPAddress.Parse("1.2.3.4");
|
||||
_remote = IPAddress.Parse("1.2.3.4");
|
||||
string headerName = "FooBar";
|
||||
var headerIp = IPAddress.Parse("5.6.7.8");
|
||||
|
||||
requestHeaders.Add(headerName, headerIp.ToString());
|
||||
requestHeaders.Add("X-Forwarded-For", remote.ToString());
|
||||
_requestHeaders.Add(headerName, headerIp.ToString());
|
||||
_requestHeaders.Add("X-Forwarded-For", _remote.ToString());
|
||||
|
||||
var context = GetContext();
|
||||
|
||||
@@ -150,7 +150,7 @@ namespace UnitTests.AspNetCore.Extensions
|
||||
var result = context.GetRemoteIpAddress(ipHeaderName: headerName);
|
||||
|
||||
// assert
|
||||
Assert.AreNotEqual(remote, result);
|
||||
Assert.AreNotEqual(_remote, result);
|
||||
Assert.AreEqual(headerIp, result);
|
||||
}
|
||||
|
||||
@@ -158,8 +158,8 @@ namespace UnitTests.AspNetCore.Extensions
|
||||
public void ShouldReturnAddressInvalidHeader()
|
||||
{
|
||||
// arrange
|
||||
remote = IPAddress.Parse("1.2.3.4");
|
||||
requestHeaders.Add("X-Forwarded-For", "1.2.3:4");
|
||||
_remote = IPAddress.Parse("1.2.3.4");
|
||||
_requestHeaders.Add("X-Forwarded-For", "1.2.3:4");
|
||||
|
||||
var context = GetContext();
|
||||
|
||||
@@ -167,16 +167,16 @@ namespace UnitTests.AspNetCore.Extensions
|
||||
var result = context.GetRemoteIpAddress();
|
||||
|
||||
// assert
|
||||
Assert.AreEqual(remote, result);
|
||||
Assert.AreEqual(_remote, result);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void ShouldReturnFirstAddressOnMultipleProxies()
|
||||
{
|
||||
// arrange
|
||||
remote = IPAddress.Parse("1.2.3.4");
|
||||
_remote = IPAddress.Parse("1.2.3.4");
|
||||
var header = IPAddress.Parse("5.6.7.8");
|
||||
requestHeaders.Add("X-Forwarded-For", $"{header}, 111.222.111.222");
|
||||
_requestHeaders.Add("X-Forwarded-For", $"{header}, 111.222.111.222");
|
||||
|
||||
var context = GetContext();
|
||||
|
||||
@@ -184,7 +184,7 @@ namespace UnitTests.AspNetCore.Extensions
|
||||
var result = context.GetRemoteIpAddress();
|
||||
|
||||
// assert
|
||||
Assert.AreNotEqual(remote, result);
|
||||
Assert.AreNotEqual(_remote, result);
|
||||
Assert.AreEqual(header, result);
|
||||
}
|
||||
|
||||
@@ -192,9 +192,9 @@ namespace UnitTests.AspNetCore.Extensions
|
||||
public void ShouldReturnV4AddressOnMapped()
|
||||
{
|
||||
// arrange
|
||||
remote = IPAddress.Parse("1.2.3.4");
|
||||
_remote = IPAddress.Parse("1.2.3.4");
|
||||
var header = IPAddress.Parse("::ffff:127.0.0.1");
|
||||
requestHeaders.Add("X-Forwarded-For", "::ffff:127.0.0.1");
|
||||
_requestHeaders.Add("X-Forwarded-For", "::ffff:127.0.0.1");
|
||||
|
||||
var context = GetContext();
|
||||
|
||||
@@ -202,7 +202,7 @@ namespace UnitTests.AspNetCore.Extensions
|
||||
var result = context.GetRemoteIpAddress();
|
||||
|
||||
// assert
|
||||
Assert.AreNotEqual(remote, result);
|
||||
Assert.AreNotEqual(_remote, result);
|
||||
Assert.AreNotEqual(header, result);
|
||||
Assert.AreEqual(header.MapToIPv4(), result);
|
||||
}
|
||||
@@ -215,7 +215,7 @@ namespace UnitTests.AspNetCore.Extensions
|
||||
public void ShouldReturnTrueOnLocal()
|
||||
{
|
||||
// arrange
|
||||
remote = IPAddress.Loopback;
|
||||
_remote = IPAddress.Loopback;
|
||||
|
||||
var context = GetContext();
|
||||
|
||||
@@ -230,7 +230,7 @@ namespace UnitTests.AspNetCore.Extensions
|
||||
public void ShouldReturnFalseOnRemote()
|
||||
{
|
||||
// arrange
|
||||
remote = IPAddress.Parse("1.2.3.4");
|
||||
_remote = IPAddress.Parse("1.2.3.4");
|
||||
|
||||
var context = GetContext();
|
||||
|
||||
@@ -245,9 +245,9 @@ namespace UnitTests.AspNetCore.Extensions
|
||||
public void ShouldReturnTrueOnDefaultHeader()
|
||||
{
|
||||
// arrange
|
||||
remote = IPAddress.Parse("1.2.3.4");
|
||||
_remote = IPAddress.Parse("1.2.3.4");
|
||||
var headerIp = IPAddress.Loopback;
|
||||
requestHeaders.Add("X-Forwarded-For", headerIp.ToString());
|
||||
_requestHeaders.Add("X-Forwarded-For", headerIp.ToString());
|
||||
|
||||
var context = GetContext();
|
||||
|
||||
@@ -262,10 +262,10 @@ namespace UnitTests.AspNetCore.Extensions
|
||||
public void ShouldReturnTrueOnCustomHeader()
|
||||
{
|
||||
// arrange
|
||||
remote = IPAddress.Parse("1.2.3.4");
|
||||
_remote = IPAddress.Parse("1.2.3.4");
|
||||
string headerName = "FooBar";
|
||||
var headerIp = IPAddress.Loopback;
|
||||
requestHeaders.Add(headerName, headerIp.ToString());
|
||||
_requestHeaders.Add(headerName, headerIp.ToString());
|
||||
|
||||
var context = GetContext();
|
||||
|
||||
@@ -281,7 +281,7 @@ namespace UnitTests.AspNetCore.Extensions
|
||||
{
|
||||
// arrange
|
||||
var headerIp = IPAddress.Parse("1.2.3.4");
|
||||
requestHeaders.Add("X-Forwarded-For", headerIp.ToString());
|
||||
_requestHeaders.Add("X-Forwarded-For", headerIp.ToString());
|
||||
|
||||
var context = GetContext();
|
||||
|
||||
@@ -298,7 +298,7 @@ namespace UnitTests.AspNetCore.Extensions
|
||||
// arrange
|
||||
string headerName = "FooBar";
|
||||
var headerIp = IPAddress.Parse("1.2.3.4");
|
||||
requestHeaders.Add(headerName, headerIp.ToString());
|
||||
_requestHeaders.Add(headerName, headerIp.ToString());
|
||||
|
||||
var context = GetContext();
|
||||
|
||||
@@ -333,8 +333,8 @@ namespace UnitTests.AspNetCore.Extensions
|
||||
string request = "abc";
|
||||
string query = "def";
|
||||
|
||||
items.Add("OriginalRequest", request);
|
||||
requestQueries.Add("ReturnUrl", query);
|
||||
_items.Add("OriginalRequest", request);
|
||||
_requestQueries.Add("ReturnUrl", query);
|
||||
|
||||
var context = GetContext();
|
||||
|
||||
@@ -351,7 +351,7 @@ namespace UnitTests.AspNetCore.Extensions
|
||||
{
|
||||
// arrange
|
||||
string query = "def";
|
||||
requestQueries.Add("ReturnUrl", query);
|
||||
_requestQueries.Add("ReturnUrl", query);
|
||||
|
||||
var context = GetContext();
|
||||
|
||||
@@ -376,7 +376,7 @@ namespace UnitTests.AspNetCore.Extensions
|
||||
context.ClearSession();
|
||||
|
||||
// assert
|
||||
sessionMock.Verify(s => s.Clear(), Times.Once);
|
||||
_sessionMock.Verify(s => s.Clear(), Times.Once);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
@@ -389,7 +389,7 @@ namespace UnitTests.AspNetCore.Extensions
|
||||
context.ClearSession();
|
||||
|
||||
// assert
|
||||
sessionMock.Verify(s => s.Clear(), Times.Never);
|
||||
_sessionMock.Verify(s => s.Clear(), Times.Never);
|
||||
}
|
||||
|
||||
#endregion Session
|
||||
@@ -398,7 +398,7 @@ namespace UnitTests.AspNetCore.Extensions
|
||||
{
|
||||
// Request
|
||||
var requestHeaderMock = new Mock<IHeaderDictionary>();
|
||||
foreach (var header in requestHeaders)
|
||||
foreach (var header in _requestHeaders)
|
||||
{
|
||||
requestHeaderMock
|
||||
.Setup(h => h.ContainsKey(header.Key))
|
||||
@@ -409,7 +409,7 @@ namespace UnitTests.AspNetCore.Extensions
|
||||
}
|
||||
|
||||
var requestQueryMock = new Mock<IQueryCollection>();
|
||||
foreach (var query in requestQueries)
|
||||
foreach (var query in _requestQueries)
|
||||
{
|
||||
requestQueryMock
|
||||
.Setup(h => h.ContainsKey(query.Key))
|
||||
@@ -434,7 +434,7 @@ namespace UnitTests.AspNetCore.Extensions
|
||||
var antiforgeryMock = new Mock<IAntiforgery>();
|
||||
antiforgeryMock
|
||||
.Setup(af => af.GetAndStoreTokens(It.IsAny<HttpContext>()))
|
||||
.Returns(() => string.IsNullOrWhiteSpace(tokenValue) ? null : new AntiforgeryTokenSet(tokenValue, tokenValue, tokenFormName, tokenHeaderName));
|
||||
.Returns(() => string.IsNullOrWhiteSpace(_tokenValue) ? null : new AntiforgeryTokenSet(_tokenValue, _tokenValue, _tokenFormName, _tokenHeaderName));
|
||||
|
||||
requestServicesMock
|
||||
.Setup(rs => rs.GetService(typeof(IAntiforgery)))
|
||||
@@ -448,10 +448,10 @@ namespace UnitTests.AspNetCore.Extensions
|
||||
.Returns(IPAddress.Loopback);
|
||||
connectionInfoMock
|
||||
.Setup(ci => ci.RemoteIpAddress)
|
||||
.Returns(remote);
|
||||
.Returns(_remote);
|
||||
|
||||
// Session
|
||||
sessionMock = new Mock<ISession>();
|
||||
_sessionMock = new Mock<ISession>();
|
||||
|
||||
var contextMock = new Mock<HttpContext>();
|
||||
contextMock
|
||||
@@ -465,12 +465,12 @@ namespace UnitTests.AspNetCore.Extensions
|
||||
.Returns(connectionInfoMock.Object);
|
||||
contextMock
|
||||
.Setup(c => c.Items)
|
||||
.Returns(items);
|
||||
.Returns(_items);
|
||||
if (hasSession)
|
||||
{
|
||||
contextMock
|
||||
.Setup(c => c.Session)
|
||||
.Returns(sessionMock.Object);
|
||||
.Returns(_sessionMock.Object);
|
||||
}
|
||||
|
||||
return contextMock.Object;
|
||||
|
||||
@@ -9,12 +9,12 @@ namespace UnitTests.AspNetCore.Extensions
|
||||
[System.Diagnostics.CodeAnalysis.ExcludeFromCodeCoverage]
|
||||
public class ModelStateDictionaryExtensionsTests
|
||||
{
|
||||
private TestModel testModel;
|
||||
private TestModel _testModel;
|
||||
|
||||
[TestInitialize]
|
||||
public void InitializeTests()
|
||||
{
|
||||
testModel = new TestModel
|
||||
_testModel = new TestModel
|
||||
{
|
||||
ValueA = "A",
|
||||
ValueB = "B",
|
||||
@@ -33,7 +33,7 @@ namespace UnitTests.AspNetCore.Extensions
|
||||
var modelState = new ModelStateDictionary();
|
||||
|
||||
// act
|
||||
modelState.AddModelError(testModel, m => m.ValueA, "ShitHappens");
|
||||
modelState.AddModelError(_testModel, m => m.ValueA, "ShitHappens");
|
||||
|
||||
// assert
|
||||
Assert.AreEqual(1, modelState.Count);
|
||||
@@ -48,7 +48,7 @@ namespace UnitTests.AspNetCore.Extensions
|
||||
var modelState = new ModelStateDictionary();
|
||||
|
||||
// act
|
||||
modelState.AddModelError(testModel, m => m.SubModel.SubValueB, "ShitHappens");
|
||||
modelState.AddModelError(_testModel, m => m.SubModel.SubValueB, "ShitHappens");
|
||||
|
||||
// assert
|
||||
Assert.AreEqual(1, modelState.Count);
|
||||
@@ -64,7 +64,7 @@ namespace UnitTests.AspNetCore.Extensions
|
||||
ModelStateDictionary modelState = null;
|
||||
|
||||
// act
|
||||
modelState.AddModelError(testModel, m => m.SubModel.SubValueB, "ShitHappens");
|
||||
modelState.AddModelError(_testModel, m => m.SubModel.SubValueB, "ShitHappens");
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
@@ -75,7 +75,7 @@ namespace UnitTests.AspNetCore.Extensions
|
||||
var modelState = new ModelStateDictionary();
|
||||
|
||||
// act
|
||||
modelState.AddModelError(testModel, m => m, "ShitHappens");
|
||||
modelState.AddModelError(_testModel, m => m, "ShitHappens");
|
||||
}
|
||||
|
||||
internal class TestModel
|
||||
|
||||
@@ -10,12 +10,12 @@ namespace UnitTests.AspNetCore.Extensions
|
||||
[System.Diagnostics.CodeAnalysis.ExcludeFromCodeCoverage]
|
||||
public class SessionExtensionsTests
|
||||
{
|
||||
private Mock<ISession> sessionMock;
|
||||
private Mock<ISession> _sessionMock;
|
||||
|
||||
private string sessionKey;
|
||||
private byte[] sessionValue;
|
||||
private string _sessionKey;
|
||||
private byte[] _sessionValue;
|
||||
|
||||
private TestModel model;
|
||||
private TestModel _model;
|
||||
|
||||
internal class TestModel
|
||||
{
|
||||
@@ -27,10 +27,10 @@ namespace UnitTests.AspNetCore.Extensions
|
||||
[TestInitialize]
|
||||
public void InitializeTests()
|
||||
{
|
||||
sessionKey = null;
|
||||
sessionValue = null;
|
||||
_sessionKey = null;
|
||||
_sessionValue = null;
|
||||
|
||||
model = new TestModel
|
||||
_model = new TestModel
|
||||
{
|
||||
ValueA = "A",
|
||||
ValueB = "B"
|
||||
@@ -41,7 +41,7 @@ namespace UnitTests.AspNetCore.Extensions
|
||||
public void ShouldCheckKeyExists()
|
||||
{
|
||||
// arrange
|
||||
sessionKey = "exists";
|
||||
_sessionKey = "exists";
|
||||
var session = GetSession();
|
||||
|
||||
// act
|
||||
@@ -57,25 +57,25 @@ namespace UnitTests.AspNetCore.Extensions
|
||||
public void ShouldGetValue()
|
||||
{
|
||||
// arrange
|
||||
sessionKey = "test";
|
||||
sessionValue = Encoding.UTF8.GetBytes(JsonConvert.SerializeObject(model));
|
||||
_sessionKey = "test";
|
||||
_sessionValue = Encoding.UTF8.GetBytes(JsonConvert.SerializeObject(_model));
|
||||
var session = GetSession();
|
||||
|
||||
// act
|
||||
var result = session.GetValue<TestModel>(sessionKey);
|
||||
var result = session.GetValue<TestModel>(_sessionKey);
|
||||
|
||||
// assert
|
||||
Assert.IsNotNull(result);
|
||||
Assert.AreEqual(model.ValueA, result.ValueA);
|
||||
Assert.AreEqual(model.ValueB, result.ValueB);
|
||||
Assert.AreEqual(_model.ValueA, result.ValueA);
|
||||
Assert.AreEqual(_model.ValueB, result.ValueB);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void ShouldGetNull()
|
||||
{
|
||||
// arrange
|
||||
sessionKey = "foo";
|
||||
sessionValue = Encoding.UTF8.GetBytes(JsonConvert.SerializeObject(model));
|
||||
_sessionKey = "foo";
|
||||
_sessionValue = Encoding.UTF8.GetBytes(JsonConvert.SerializeObject(_model));
|
||||
var session = GetSession();
|
||||
|
||||
// act
|
||||
@@ -89,25 +89,25 @@ namespace UnitTests.AspNetCore.Extensions
|
||||
public void ShouldGetValueWithFallback()
|
||||
{
|
||||
// arrange
|
||||
sessionKey = "test";
|
||||
sessionValue = Encoding.UTF8.GetBytes(JsonConvert.SerializeObject(model));
|
||||
_sessionKey = "test";
|
||||
_sessionValue = Encoding.UTF8.GetBytes(JsonConvert.SerializeObject(_model));
|
||||
var session = GetSession();
|
||||
|
||||
// act
|
||||
var result = session.GetValue(sessionKey, new TestModel());
|
||||
var result = session.GetValue(_sessionKey, new TestModel());
|
||||
|
||||
// assert
|
||||
Assert.IsNotNull(result);
|
||||
Assert.AreEqual(model.ValueA, result.ValueA);
|
||||
Assert.AreEqual(model.ValueB, result.ValueB);
|
||||
Assert.AreEqual(_model.ValueA, result.ValueA);
|
||||
Assert.AreEqual(_model.ValueB, result.ValueB);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void ShouldGetFallback()
|
||||
{
|
||||
// arrange
|
||||
sessionKey = "foo";
|
||||
sessionValue = Encoding.UTF8.GetBytes(JsonConvert.SerializeObject(model));
|
||||
_sessionKey = "foo";
|
||||
_sessionValue = Encoding.UTF8.GetBytes(JsonConvert.SerializeObject(_model));
|
||||
var session = GetSession();
|
||||
|
||||
// act
|
||||
@@ -127,33 +127,33 @@ namespace UnitTests.AspNetCore.Extensions
|
||||
var session = GetSession();
|
||||
|
||||
// act
|
||||
session.SetValue(key, model);
|
||||
session.SetValue(key, _model);
|
||||
|
||||
// arrange
|
||||
Assert.AreEqual(key, sessionKey);
|
||||
Assert.AreEqual(JsonConvert.SerializeObject(model), Encoding.UTF8.GetString(sessionValue));
|
||||
Assert.AreEqual(key, _sessionKey);
|
||||
Assert.AreEqual(JsonConvert.SerializeObject(_model), Encoding.UTF8.GetString(_sessionValue));
|
||||
}
|
||||
|
||||
private ISession GetSession()
|
||||
{
|
||||
string[] keys = new[] { sessionKey };
|
||||
string[] keys = [_sessionKey];
|
||||
|
||||
sessionMock = new Mock<ISession>();
|
||||
sessionMock
|
||||
.Setup(s => s.TryGetValue(It.IsAny<string>(), out sessionValue))
|
||||
.Returns<string, byte[]>((key, value) => sessionKey == key);
|
||||
sessionMock
|
||||
_sessionMock = new Mock<ISession>();
|
||||
_sessionMock
|
||||
.Setup(s => s.TryGetValue(It.IsAny<string>(), out _sessionValue))
|
||||
.Returns<string, byte[]>((key, value) => _sessionKey == key);
|
||||
_sessionMock
|
||||
.Setup(s => s.Set(It.IsAny<string>(), It.IsAny<byte[]>()))
|
||||
.Callback<string, byte[]>((key, value) =>
|
||||
{
|
||||
sessionKey = key;
|
||||
sessionValue = value;
|
||||
_sessionKey = key;
|
||||
_sessionValue = value;
|
||||
});
|
||||
sessionMock
|
||||
_sessionMock
|
||||
.Setup(s => s.Keys)
|
||||
.Returns(keys);
|
||||
|
||||
return sessionMock.Object;
|
||||
return _sessionMock.Object;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -18,26 +18,26 @@ namespace UnitTests.AspNetCore.Security.BasicAuthentication
|
||||
[System.Diagnostics.CodeAnalysis.ExcludeFromCodeCoverage]
|
||||
public class BasicAuthenticationMiddlewareTests
|
||||
{
|
||||
private Dictionary<string, string> requestHeaders;
|
||||
private Dictionary<string, string> _requestHeaders;
|
||||
|
||||
private Dictionary<string, string> responseHeadersCallback;
|
||||
private int responseStatusCodeCallback;
|
||||
private Dictionary<string, string> _responseHeadersCallback;
|
||||
private int _responseStatusCodeCallback;
|
||||
|
||||
private string validatorRealm;
|
||||
private ClaimsPrincipal validatorResponse;
|
||||
private List<(string username, string password, IPAddress ipAddr)> validatorCallback;
|
||||
private string _validatorRealm;
|
||||
private ClaimsPrincipal _validatorResponse;
|
||||
private List<(string username, string password, IPAddress ipAddr)> _validatorCallback;
|
||||
|
||||
[TestInitialize]
|
||||
public void InitializeTests()
|
||||
{
|
||||
requestHeaders = new Dictionary<string, string>();
|
||||
_requestHeaders = [];
|
||||
|
||||
responseHeadersCallback = new Dictionary<string, string>();
|
||||
responseStatusCodeCallback = 0;
|
||||
_responseHeadersCallback = [];
|
||||
_responseStatusCodeCallback = 0;
|
||||
|
||||
validatorRealm = null;
|
||||
validatorResponse = null;
|
||||
validatorCallback = new List<(string username, string password, IPAddress ipAddr)>();
|
||||
_validatorRealm = null;
|
||||
_validatorResponse = null;
|
||||
_validatorCallback = [];
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
@@ -47,8 +47,8 @@ namespace UnitTests.AspNetCore.Security.BasicAuthentication
|
||||
string username = "user";
|
||||
string password = "pass:word";
|
||||
|
||||
requestHeaders.Add("Authorization", $"Basic {Convert.ToBase64String(Encoding.UTF8.GetBytes($"{username}:{password}"))}");
|
||||
validatorResponse = new ClaimsPrincipal();
|
||||
_requestHeaders.Add("Authorization", $"Basic {Convert.ToBase64String(Encoding.UTF8.GetBytes($"{username}:{password}"))}");
|
||||
_validatorResponse = new ClaimsPrincipal();
|
||||
|
||||
var middleware = GetMiddleware();
|
||||
var context = GetContext();
|
||||
@@ -57,13 +57,13 @@ namespace UnitTests.AspNetCore.Security.BasicAuthentication
|
||||
await middleware.InvokeAsync(context);
|
||||
|
||||
// assert
|
||||
Assert.AreEqual(0, responseStatusCodeCallback); // not triggered
|
||||
Assert.AreEqual(0, responseHeadersCallback.Count);
|
||||
Assert.AreEqual(1, validatorCallback.Count);
|
||||
Assert.AreEqual(0, _responseStatusCodeCallback); // not triggered
|
||||
Assert.AreEqual(0, _responseHeadersCallback.Count);
|
||||
Assert.AreEqual(1, _validatorCallback.Count);
|
||||
|
||||
Assert.AreEqual(username, validatorCallback.First().username);
|
||||
Assert.AreEqual(password, validatorCallback.First().password);
|
||||
Assert.AreEqual(IPAddress.Loopback, validatorCallback.First().ipAddr);
|
||||
Assert.AreEqual(username, _validatorCallback.First().username);
|
||||
Assert.AreEqual(password, _validatorCallback.First().password);
|
||||
Assert.AreEqual(IPAddress.Loopback, _validatorCallback.First().ipAddr);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
@@ -77,13 +77,13 @@ namespace UnitTests.AspNetCore.Security.BasicAuthentication
|
||||
await middleware.InvokeAsync(context);
|
||||
|
||||
// assert
|
||||
Assert.AreEqual(401, responseStatusCodeCallback);
|
||||
Assert.AreEqual(401, _responseStatusCodeCallback);
|
||||
|
||||
Assert.AreEqual(0, validatorCallback.Count);
|
||||
Assert.AreEqual(0, _validatorCallback.Count);
|
||||
|
||||
Assert.AreEqual(1, responseHeadersCallback.Count);
|
||||
Assert.AreEqual("WWW-Authenticate", responseHeadersCallback.Keys.First());
|
||||
Assert.AreEqual("Basic", responseHeadersCallback.Values.First());
|
||||
Assert.AreEqual(1, _responseHeadersCallback.Count);
|
||||
Assert.AreEqual("WWW-Authenticate", _responseHeadersCallback.Keys.First());
|
||||
Assert.AreEqual("Basic", _responseHeadersCallback.Values.First());
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
@@ -93,10 +93,10 @@ namespace UnitTests.AspNetCore.Security.BasicAuthentication
|
||||
string username = "user";
|
||||
string password = "pw";
|
||||
|
||||
validatorRealm = "TEST";
|
||||
_validatorRealm = "TEST";
|
||||
var remote = IPAddress.Parse("1.2.3.4");
|
||||
|
||||
requestHeaders.Add("Authorization", $"Basic {Convert.ToBase64String(Encoding.UTF8.GetBytes($"{username}:{password}"))}");
|
||||
_requestHeaders.Add("Authorization", $"Basic {Convert.ToBase64String(Encoding.UTF8.GetBytes($"{username}:{password}"))}");
|
||||
|
||||
var middleware = GetMiddleware();
|
||||
var context = GetContext(remote);
|
||||
@@ -105,16 +105,16 @@ namespace UnitTests.AspNetCore.Security.BasicAuthentication
|
||||
await middleware.InvokeAsync(context);
|
||||
|
||||
// assert
|
||||
Assert.AreEqual(401, responseStatusCodeCallback);
|
||||
Assert.AreEqual(401, _responseStatusCodeCallback);
|
||||
|
||||
Assert.AreEqual(1, responseHeadersCallback.Count);
|
||||
Assert.AreEqual("WWW-Authenticate", responseHeadersCallback.Keys.First());
|
||||
Assert.AreEqual($"Basic realm=\"{validatorRealm}\"", responseHeadersCallback.Values.First());
|
||||
Assert.AreEqual(1, _responseHeadersCallback.Count);
|
||||
Assert.AreEqual("WWW-Authenticate", _responseHeadersCallback.Keys.First());
|
||||
Assert.AreEqual($"Basic realm=\"{_validatorRealm}\"", _responseHeadersCallback.Values.First());
|
||||
|
||||
Assert.AreEqual(1, validatorCallback.Count);
|
||||
Assert.AreEqual(username, validatorCallback.First().username);
|
||||
Assert.AreEqual(password, validatorCallback.First().password);
|
||||
Assert.AreEqual(remote, validatorCallback.First().ipAddr);
|
||||
Assert.AreEqual(1, _validatorCallback.Count);
|
||||
Assert.AreEqual(username, _validatorCallback.First().username);
|
||||
Assert.AreEqual(password, _validatorCallback.First().password);
|
||||
Assert.AreEqual(remote, _validatorCallback.First().ipAddr);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
@@ -123,7 +123,7 @@ namespace UnitTests.AspNetCore.Security.BasicAuthentication
|
||||
// arrange
|
||||
string username = "user";
|
||||
|
||||
requestHeaders.Add("Authorization", $"Basic {Convert.ToBase64String(Encoding.UTF8.GetBytes($"{username}"))}");
|
||||
_requestHeaders.Add("Authorization", $"Basic {Convert.ToBase64String(Encoding.UTF8.GetBytes($"{username}"))}");
|
||||
|
||||
var middleware = GetMiddleware();
|
||||
var context = GetContext();
|
||||
@@ -132,7 +132,7 @@ namespace UnitTests.AspNetCore.Security.BasicAuthentication
|
||||
await middleware.InvokeAsync(context);
|
||||
|
||||
// assert
|
||||
Assert.AreEqual(500, responseStatusCodeCallback);
|
||||
Assert.AreEqual(500, _responseStatusCodeCallback);
|
||||
}
|
||||
|
||||
private BasicAuthenticationMiddleware GetMiddleware()
|
||||
@@ -141,11 +141,11 @@ namespace UnitTests.AspNetCore.Security.BasicAuthentication
|
||||
var validatorMock = new Mock<IBasicAuthenticationValidator>();
|
||||
validatorMock
|
||||
.Setup(v => v.Realm)
|
||||
.Returns(validatorRealm);
|
||||
.Returns(_validatorRealm);
|
||||
validatorMock
|
||||
.Setup(v => v.ValidateAsync(It.IsAny<string>(), It.IsAny<string>(), It.IsAny<IPAddress>(), It.IsAny<CancellationToken>()))
|
||||
.Callback<string, string, IPAddress, CancellationToken>((username, password, ipAddress, _) => validatorCallback.Add((username, password, ipAddress)))
|
||||
.ReturnsAsync(validatorResponse);
|
||||
.Callback<string, string, IPAddress, CancellationToken>((username, password, ipAddress, _) => _validatorCallback.Add((username, password, ipAddress)))
|
||||
.ReturnsAsync(_validatorResponse);
|
||||
|
||||
return new BasicAuthenticationMiddleware(nextMock.Object, validatorMock.Object);
|
||||
}
|
||||
@@ -154,7 +154,7 @@ namespace UnitTests.AspNetCore.Security.BasicAuthentication
|
||||
{
|
||||
// Request
|
||||
var requestHeaderMock = new Mock<IHeaderDictionary>();
|
||||
foreach (var header in requestHeaders)
|
||||
foreach (var header in _requestHeaders)
|
||||
{
|
||||
requestHeaderMock
|
||||
.Setup(h => h.ContainsKey(header.Key))
|
||||
@@ -173,7 +173,7 @@ namespace UnitTests.AspNetCore.Security.BasicAuthentication
|
||||
var responseHeaderMock = new Mock<IHeaderDictionary>();
|
||||
responseHeaderMock
|
||||
.SetupSet(h => h[It.IsAny<string>()] = It.IsAny<StringValues>())
|
||||
.Callback<string, StringValues>((key, value) => responseHeadersCallback[key] = value);
|
||||
.Callback<string, StringValues>((key, value) => _responseHeadersCallback[key] = value);
|
||||
|
||||
var responseMock = new Mock<HttpResponse>();
|
||||
responseMock
|
||||
@@ -181,7 +181,7 @@ namespace UnitTests.AspNetCore.Security.BasicAuthentication
|
||||
.Returns(responseHeaderMock.Object);
|
||||
responseMock
|
||||
.SetupSet(r => r.StatusCode = It.IsAny<int>())
|
||||
.Callback<int>((code) => responseStatusCodeCallback = code);
|
||||
.Callback<int>((code) => _responseStatusCodeCallback = code);
|
||||
|
||||
// Connection
|
||||
var connectionInfoMock = new Mock<ConnectionInfo>();
|
||||
|
||||
@@ -14,17 +14,17 @@ namespace UnitTests.AspNetCore.Security.PathProtection
|
||||
[System.Diagnostics.CodeAnalysis.ExcludeFromCodeCoverage]
|
||||
public class ProtectedPathMiddlewareTests
|
||||
{
|
||||
private Mock<RequestDelegate> nextMock;
|
||||
private Mock<HttpContext> httpContextMock;
|
||||
private Mock<IAuthorizationService> authorizationServiceMock;
|
||||
private Mock<IAuthenticationService> authenticationServiceMock;
|
||||
private Mock<RequestDelegate> _nextMock;
|
||||
private Mock<HttpContext> _httpContextMock;
|
||||
private Mock<IAuthorizationService> _authorizationServiceMock;
|
||||
private Mock<IAuthenticationService> _authenticationServiceMock;
|
||||
|
||||
private ProtectedPathOptions options;
|
||||
private ProtectedPathOptions _options;
|
||||
|
||||
[TestInitialize]
|
||||
public void InitializeTest()
|
||||
{
|
||||
options = new ProtectedPathOptions
|
||||
_options = new ProtectedPathOptions
|
||||
{
|
||||
Path = "/secure/protected",
|
||||
PolicyName = "Protection"
|
||||
@@ -36,21 +36,21 @@ namespace UnitTests.AspNetCore.Security.PathProtection
|
||||
{
|
||||
// arrange
|
||||
var middleware = GetMiddleware();
|
||||
var context = GetHttpContext(options.Path);
|
||||
var context = GetHttpContext(_options.Path);
|
||||
var auth = GetAuthService(true);
|
||||
|
||||
// act
|
||||
await middleware.InvokeAsync(context, auth);
|
||||
|
||||
// assert
|
||||
authorizationServiceMock.Verify(s => s.AuthorizeAsync(It.IsAny<ClaimsPrincipal>(), It.IsAny<object>(), options.PolicyName), Times.Once);
|
||||
authorizationServiceMock.VerifyNoOtherCalls();
|
||||
_authorizationServiceMock.Verify(s => s.AuthorizeAsync(It.IsAny<ClaimsPrincipal>(), It.IsAny<object>(), _options.PolicyName), Times.Once);
|
||||
_authorizationServiceMock.VerifyNoOtherCalls();
|
||||
|
||||
authenticationServiceMock.Verify(s => s.ChallengeAsync(It.IsAny<HttpContext>(), It.IsAny<string>(), It.IsAny<AuthenticationProperties>()), Times.Never);
|
||||
authenticationServiceMock.VerifyNoOtherCalls();
|
||||
_authenticationServiceMock.Verify(s => s.ChallengeAsync(It.IsAny<HttpContext>(), It.IsAny<string>(), It.IsAny<AuthenticationProperties>()), Times.Never);
|
||||
_authenticationServiceMock.VerifyNoOtherCalls();
|
||||
|
||||
nextMock.Verify(n => n.Invoke(It.IsAny<HttpContext>()), Times.Once);
|
||||
nextMock.VerifyNoOtherCalls();
|
||||
_nextMock.Verify(n => n.Invoke(It.IsAny<HttpContext>()), Times.Once);
|
||||
_nextMock.VerifyNoOtherCalls();
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
@@ -65,14 +65,14 @@ namespace UnitTests.AspNetCore.Security.PathProtection
|
||||
await middleware.InvokeAsync(context, auth);
|
||||
|
||||
// assert
|
||||
authorizationServiceMock.Verify(s => s.AuthorizeAsync(It.IsAny<ClaimsPrincipal>(), It.IsAny<object>(), options.PolicyName), Times.Never);
|
||||
authorizationServiceMock.VerifyNoOtherCalls();
|
||||
_authorizationServiceMock.Verify(s => s.AuthorizeAsync(It.IsAny<ClaimsPrincipal>(), It.IsAny<object>(), _options.PolicyName), Times.Never);
|
||||
_authorizationServiceMock.VerifyNoOtherCalls();
|
||||
|
||||
authenticationServiceMock.Verify(s => s.ChallengeAsync(It.IsAny<HttpContext>(), It.IsAny<string>(), It.IsAny<AuthenticationProperties>()), Times.Never);
|
||||
authenticationServiceMock.VerifyNoOtherCalls();
|
||||
_authenticationServiceMock.Verify(s => s.ChallengeAsync(It.IsAny<HttpContext>(), It.IsAny<string>(), It.IsAny<AuthenticationProperties>()), Times.Never);
|
||||
_authenticationServiceMock.VerifyNoOtherCalls();
|
||||
|
||||
nextMock.Verify(n => n.Invoke(It.IsAny<HttpContext>()), Times.Once);
|
||||
nextMock.VerifyNoOtherCalls();
|
||||
_nextMock.Verify(n => n.Invoke(It.IsAny<HttpContext>()), Times.Once);
|
||||
_nextMock.VerifyNoOtherCalls();
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
@@ -80,27 +80,27 @@ namespace UnitTests.AspNetCore.Security.PathProtection
|
||||
{
|
||||
// arrange
|
||||
var middleware = GetMiddleware();
|
||||
var context = GetHttpContext(options.Path);
|
||||
var context = GetHttpContext(_options.Path);
|
||||
var auth = GetAuthService(false);
|
||||
|
||||
// act
|
||||
await middleware.InvokeAsync(context, auth);
|
||||
|
||||
// assert
|
||||
authorizationServiceMock.Verify(s => s.AuthorizeAsync(It.IsAny<ClaimsPrincipal>(), It.IsAny<object>(), options.PolicyName), Times.Once);
|
||||
authorizationServiceMock.VerifyNoOtherCalls();
|
||||
_authorizationServiceMock.Verify(s => s.AuthorizeAsync(It.IsAny<ClaimsPrincipal>(), It.IsAny<object>(), _options.PolicyName), Times.Once);
|
||||
_authorizationServiceMock.VerifyNoOtherCalls();
|
||||
|
||||
authenticationServiceMock.Verify(s => s.ChallengeAsync(It.IsAny<HttpContext>(), It.IsAny<string>(), It.IsAny<AuthenticationProperties>()), Times.Once);
|
||||
authenticationServiceMock.VerifyNoOtherCalls();
|
||||
_authenticationServiceMock.Verify(s => s.ChallengeAsync(It.IsAny<HttpContext>(), It.IsAny<string>(), It.IsAny<AuthenticationProperties>()), Times.Once);
|
||||
_authenticationServiceMock.VerifyNoOtherCalls();
|
||||
|
||||
nextMock.Verify(n => n.Invoke(It.IsAny<HttpContext>()), Times.Never);
|
||||
nextMock.VerifyNoOtherCalls();
|
||||
_nextMock.Verify(n => n.Invoke(It.IsAny<HttpContext>()), Times.Never);
|
||||
_nextMock.VerifyNoOtherCalls();
|
||||
}
|
||||
|
||||
private ProtectedPathMiddleware GetMiddleware()
|
||||
{
|
||||
nextMock = new Mock<RequestDelegate>();
|
||||
return new ProtectedPathMiddleware(nextMock.Object, options);
|
||||
_nextMock = new Mock<RequestDelegate>();
|
||||
return new ProtectedPathMiddleware(_nextMock.Object, _options);
|
||||
}
|
||||
|
||||
private HttpContext GetHttpContext(string requestPath)
|
||||
@@ -110,32 +110,32 @@ namespace UnitTests.AspNetCore.Security.PathProtection
|
||||
.Setup(r => r.Path)
|
||||
.Returns(new PathString(requestPath));
|
||||
|
||||
authenticationServiceMock = new Mock<IAuthenticationService>();
|
||||
_authenticationServiceMock = new Mock<IAuthenticationService>();
|
||||
|
||||
var requestServicesMock = new Mock<IServiceProvider>();
|
||||
requestServicesMock
|
||||
.Setup(s => s.GetService(typeof(IAuthenticationService)))
|
||||
.Returns(authenticationServiceMock.Object);
|
||||
.Returns(_authenticationServiceMock.Object);
|
||||
|
||||
httpContextMock = new Mock<HttpContext>();
|
||||
httpContextMock
|
||||
_httpContextMock = new Mock<HttpContext>();
|
||||
_httpContextMock
|
||||
.Setup(c => c.Request)
|
||||
.Returns(requestMock.Object);
|
||||
httpContextMock
|
||||
_httpContextMock
|
||||
.Setup(c => c.RequestServices)
|
||||
.Returns(requestServicesMock.Object);
|
||||
|
||||
return httpContextMock.Object;
|
||||
return _httpContextMock.Object;
|
||||
}
|
||||
|
||||
private IAuthorizationService GetAuthService(bool success)
|
||||
{
|
||||
authorizationServiceMock = new Mock<IAuthorizationService>();
|
||||
authorizationServiceMock
|
||||
_authorizationServiceMock = new Mock<IAuthorizationService>();
|
||||
_authorizationServiceMock
|
||||
.Setup(service => service.AuthorizeAsync(It.IsAny<ClaimsPrincipal>(), It.IsAny<object>(), It.IsAny<string>()))
|
||||
.ReturnsAsync(() => success ? AuthorizationResult.Success() : AuthorizationResult.Failed());
|
||||
|
||||
return authorizationServiceMock.Object;
|
||||
return _authorizationServiceMock.Object;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,9 +1,4 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Reflection;
|
||||
using System.Text;
|
||||
using System.Threading.Tasks;
|
||||
using System.Reflection;
|
||||
using Microsoft.AspNetCore.Identity;
|
||||
using Microsoft.VisualStudio.TestTools.UnitTesting;
|
||||
|
||||
|
||||
@@ -41,7 +41,7 @@ namespace UnitTests.Common.Cli
|
||||
|
||||
// act
|
||||
parser.ReadArgs("Option1 \"Option 2\"");
|
||||
string[] args = parser.GetType().GetField("args", BindingFlags.NonPublic | BindingFlags.Instance).GetValue(parser) as string[];
|
||||
string[] args = parser.GetType().GetField("_args", BindingFlags.NonPublic | BindingFlags.Instance).GetValue(parser) as string[];
|
||||
|
||||
// assert
|
||||
Assert.IsNotNull(args);
|
||||
@@ -63,7 +63,7 @@ namespace UnitTests.Common.Cli
|
||||
parser.RegisterOption("opt3", 2).Required().Single();
|
||||
parser.RegisterOption("opt4").Alias("option4");
|
||||
|
||||
var options = parser.GetType().GetField("options", BindingFlags.NonPublic | BindingFlags.Instance).GetValue(parser) as List<Option>;
|
||||
var options = parser.GetType().GetField("_options", BindingFlags.NonPublic | BindingFlags.Instance).GetValue(parser) as List<Option>;
|
||||
|
||||
// assert
|
||||
Assert.IsNotNull(options);
|
||||
@@ -163,7 +163,7 @@ namespace UnitTests.Common.Cli
|
||||
// arrange
|
||||
Argument actionArgument = null;
|
||||
|
||||
string[] args = new[] { "/run", "--opt" };
|
||||
string[] args = ["/run", "--opt"];
|
||||
var parser = new CommandLineParser();
|
||||
parser.RegisterOption("opt").Required();
|
||||
parser.RegisterOption("run").Do(arg => actionArgument = arg);
|
||||
@@ -219,7 +219,7 @@ namespace UnitTests.Common.Cli
|
||||
public void ShouldThrowExceptionOnMultipleAutocomplete()
|
||||
{
|
||||
// arrange
|
||||
string[] args = new[] { "/Opt:on" };
|
||||
string[] args = ["/Opt:on"];
|
||||
var parser = new CommandLineParser
|
||||
{
|
||||
IsCaseSensitive = true
|
||||
@@ -239,7 +239,7 @@ namespace UnitTests.Common.Cli
|
||||
public void ShouldThrowExceptionOnMissingOption()
|
||||
{
|
||||
// arrange
|
||||
string[] args = new[] { "/Option:on" };
|
||||
string[] args = ["/Option:on"];
|
||||
var parser = new CommandLineParser
|
||||
{
|
||||
AutoCompleteOptions = false
|
||||
@@ -259,7 +259,7 @@ namespace UnitTests.Common.Cli
|
||||
public void ShouldTrhowExceptionOnDuplicateOption()
|
||||
{
|
||||
// arrange
|
||||
string[] args = new[] { "/Opt:on", "--opt=off" };
|
||||
string[] args = ["/Opt:on", "--opt=off"];
|
||||
var parser = new CommandLineParser();
|
||||
parser.RegisterOption("opt", 1).Single();
|
||||
|
||||
@@ -275,7 +275,7 @@ namespace UnitTests.Common.Cli
|
||||
public void ShouldThrowExceptionOnMissingArgument()
|
||||
{
|
||||
// arrange
|
||||
string[] args = new[] { "/Option" };
|
||||
string[] args = ["/Option"];
|
||||
var parser = new CommandLineParser();
|
||||
parser.RegisterOption("option", 1);
|
||||
|
||||
@@ -291,7 +291,7 @@ namespace UnitTests.Common.Cli
|
||||
public void ShouldThrowExceptionForMissingRequiredOption()
|
||||
{
|
||||
// arrange
|
||||
string[] args = new[] { "/opt" };
|
||||
string[] args = ["/opt"];
|
||||
var parser = new CommandLineParser();
|
||||
parser.RegisterOption("opt").Required();
|
||||
parser.RegisterOption("foo").Required();
|
||||
|
||||
@@ -8,18 +8,12 @@ namespace UnitTests.Common.Cli
|
||||
[TestClass]
|
||||
public class EnumerableWalkerTests
|
||||
{
|
||||
private List<string> list;
|
||||
private List<string> _list;
|
||||
|
||||
[TestInitialize]
|
||||
public void Initialize()
|
||||
{
|
||||
list = new List<string>
|
||||
{
|
||||
"one",
|
||||
"two",
|
||||
"three",
|
||||
"four",
|
||||
};
|
||||
_list = ["one", "two", "three", "four"];
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
@@ -39,7 +33,7 @@ namespace UnitTests.Common.Cli
|
||||
public void ShouldReturnEnumerator()
|
||||
{
|
||||
// arrange
|
||||
var walker = new EnumerableWalker<string>(list);
|
||||
var walker = new EnumerableWalker<string>(_list);
|
||||
|
||||
// act
|
||||
var enumerator = walker.GetEnumerator();
|
||||
@@ -52,7 +46,7 @@ namespace UnitTests.Common.Cli
|
||||
public void ShouldReturnGenericEnumerator()
|
||||
{
|
||||
// arrange
|
||||
var walker = new EnumerableWalker<string>(list);
|
||||
var walker = new EnumerableWalker<string>(_list);
|
||||
|
||||
// act
|
||||
var enumerator = ((IEnumerable<string>)walker).GetEnumerator();
|
||||
@@ -65,18 +59,18 @@ namespace UnitTests.Common.Cli
|
||||
public void ShouldReturnItems()
|
||||
{
|
||||
// arrange
|
||||
var walker = new EnumerableWalker<string>(list);
|
||||
var walker = new EnumerableWalker<string>(_list);
|
||||
_ = walker.GetEnumerator();
|
||||
|
||||
string[] items = new string[list.Count];
|
||||
string[] items = new string[_list.Count];
|
||||
|
||||
// act
|
||||
for (int i = 0; i < list.Count; i++)
|
||||
for (int i = 0; i < _list.Count; i++)
|
||||
items[i] = walker.GetNext();
|
||||
|
||||
// assert
|
||||
for (int i = 0; i < list.Count; i++)
|
||||
Assert.AreEqual(list[i], items[i], $"Position {i} failed");
|
||||
for (int i = 0; i < _list.Count; i++)
|
||||
Assert.AreEqual(_list[i], items[i], $"Position {i} failed");
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
@@ -90,7 +84,7 @@ namespace UnitTests.Common.Cli
|
||||
string item = walker.GetNext();
|
||||
|
||||
// assert
|
||||
Assert.AreEqual(default(string), item);
|
||||
Assert.AreEqual(default, item);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -12,7 +12,7 @@ namespace UnitTests.Common.Extensions
|
||||
{
|
||||
// arrange
|
||||
string str = "Hello World!";
|
||||
byte[] bytes = new byte[] { 0xaf, 0xfe };
|
||||
byte[] bytes = [0xaf, 0xfe];
|
||||
|
||||
// act
|
||||
string strHash = str.Md5();
|
||||
@@ -28,7 +28,7 @@ namespace UnitTests.Common.Extensions
|
||||
{
|
||||
// arrange
|
||||
string str = "Hello World!";
|
||||
byte[] bytes = new byte[] { 0xaf, 0xfe };
|
||||
byte[] bytes = [0xaf, 0xfe];
|
||||
|
||||
// act
|
||||
string strHash = str.Sha1();
|
||||
@@ -44,7 +44,7 @@ namespace UnitTests.Common.Extensions
|
||||
{
|
||||
// arrange
|
||||
string str = "Hello World!";
|
||||
byte[] bytes = new byte[] { 0xaf, 0xfe };
|
||||
byte[] bytes = [0xaf, 0xfe];
|
||||
|
||||
// act
|
||||
string strHash = str.Sha256();
|
||||
@@ -60,7 +60,7 @@ namespace UnitTests.Common.Extensions
|
||||
{
|
||||
// arrange
|
||||
string str = "Hello World!";
|
||||
byte[] bytes = new byte[] { 0xaf, 0xfe };
|
||||
byte[] bytes = [0xaf, 0xfe];
|
||||
|
||||
// act
|
||||
string strHash = str.Sha512();
|
||||
|
||||
@@ -56,11 +56,11 @@ namespace UnitTests.Common.Extensions
|
||||
// arrange
|
||||
var innerExceptions = new List<Exception>
|
||||
{
|
||||
new Exception("Inner Exception 1."),
|
||||
new Exception("Inner Exception 2. See the inner exception for details.", new Exception("Inner Exception of Exception 2.")),
|
||||
new Exception("Inner Exception 3."),
|
||||
new Exception("Inner Exception 4."),
|
||||
new Exception("Inner Exception 5.")
|
||||
new("Inner Exception 1."),
|
||||
new("Inner Exception 2. See the inner exception for details.", new Exception("Inner Exception of Exception 2.")),
|
||||
new("Inner Exception 3."),
|
||||
new("Inner Exception 4."),
|
||||
new("Inner Exception 5.")
|
||||
};
|
||||
var aggregateException = new AggregateException("Lots of exceptions.", innerExceptions);
|
||||
string expectedMessage = "Inner Exception 1. Inner Exception 2. Inner Exception of Exception 2. Inner Exception 3.";
|
||||
|
||||
@@ -224,7 +224,7 @@ namespace UnitTests.Common.Extensions
|
||||
public void ShouldConvertToJArray()
|
||||
{
|
||||
// arrange
|
||||
string[] stringArray = new[] { "one", "two", "three" };
|
||||
string[] stringArray = ["one", "two", "three"];
|
||||
var objectArray = new[]
|
||||
{
|
||||
new JsonTestClass { StringValue = "One" },
|
||||
|
||||
@@ -154,7 +154,7 @@ namespace UnitTests.Common.Extensions
|
||||
catch (Exception)
|
||||
{ /* keep it quiet */ }
|
||||
});
|
||||
Task.WaitAll(awaitableTask);
|
||||
awaitableTask.Wait();
|
||||
|
||||
// assert
|
||||
Assert.IsTrue(isTimeout);
|
||||
@@ -183,7 +183,7 @@ namespace UnitTests.Common.Extensions
|
||||
catch (Exception)
|
||||
{ /* keep it quiet */ }
|
||||
});
|
||||
Task.WaitAll(awaitableTask);
|
||||
awaitableTask.Wait();
|
||||
|
||||
// assert
|
||||
Assert.IsTrue(isTimeout);
|
||||
@@ -212,7 +212,7 @@ namespace UnitTests.Common.Extensions
|
||||
catch (Exception)
|
||||
{ /* keep it quiet */ }
|
||||
});
|
||||
Task.WaitAll(awaitableTask);
|
||||
awaitableTask.Wait();
|
||||
|
||||
// assert
|
||||
Assert.IsTrue(isTimeout);
|
||||
|
||||
@@ -87,7 +87,7 @@ namespace UnitTests.Common.Extensions
|
||||
{
|
||||
// arrange
|
||||
byte[] bytes1 = null;
|
||||
byte[] bytes2 = Array.Empty<byte>();
|
||||
byte[] bytes2 = [];
|
||||
|
||||
// act
|
||||
string hex1 = bytes1.BytesToHex();
|
||||
@@ -102,7 +102,7 @@ namespace UnitTests.Common.Extensions
|
||||
public void ShouldReturnHexString()
|
||||
{
|
||||
// arrange
|
||||
byte[] bytes = new byte[] { 0xaf, 0xfe };
|
||||
byte[] bytes = [0xaf, 0xfe];
|
||||
|
||||
// act
|
||||
string hex = bytes.BytesToHex();
|
||||
@@ -116,7 +116,7 @@ namespace UnitTests.Common.Extensions
|
||||
public void ShouldReturnHexStringWithDelimiter()
|
||||
{
|
||||
// arrange
|
||||
byte[] bytes = new byte[] { 0xde, 0xad, 0xbe, 0xef };
|
||||
byte[] bytes = [0xde, 0xad, 0xbe, 0xef];
|
||||
|
||||
// act
|
||||
string hex = bytes.BytesToHex("_");
|
||||
|
||||
@@ -15,14 +15,14 @@ namespace UnitTests.Common.Logging
|
||||
[TestClass]
|
||||
public class FileLoggerTests
|
||||
{
|
||||
private Mock<StreamWriter> streamWriterMock;
|
||||
private Mock<StreamWriter> _streamWriterMock;
|
||||
|
||||
private List<string> lines;
|
||||
private List<string> _lines;
|
||||
|
||||
[TestInitialize]
|
||||
public void Initialize()
|
||||
{
|
||||
lines = new List<string>();
|
||||
_lines = [];
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
@@ -157,14 +157,14 @@ namespace UnitTests.Common.Logging
|
||||
|
||||
// act
|
||||
logger.Log(LogLevel.Information, "Test Message");
|
||||
SpinWait.SpinUntil(() => lines.Count == 1);
|
||||
SpinWait.SpinUntil(() => _lines.Count == 1);
|
||||
|
||||
// assert
|
||||
Assert.AreEqual("INFO | Test Message", lines.First());
|
||||
Assert.AreEqual("INFO | Test Message", _lines.First());
|
||||
|
||||
streamWriterMock.Verify(sw => sw.WriteLineAsync(It.IsAny<string>()), Times.Once);
|
||||
streamWriterMock.Verify(sw => sw.FlushAsync(), Times.Once);
|
||||
streamWriterMock.VerifyNoOtherCalls();
|
||||
_streamWriterMock.Verify(sw => sw.WriteLineAsync(It.IsAny<string>()), Times.Once);
|
||||
_streamWriterMock.Verify(sw => sw.FlushAsync(), Times.Once);
|
||||
_streamWriterMock.VerifyNoOtherCalls();
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
@@ -177,18 +177,18 @@ namespace UnitTests.Common.Logging
|
||||
foreach (LogLevel level in Enum.GetValues<LogLevel>())
|
||||
logger.Log(level, "Test Message");
|
||||
|
||||
SpinWait.SpinUntil(() => lines.Count == 7);
|
||||
SpinWait.SpinUntil(() => _lines.Count == 7);
|
||||
|
||||
// assert
|
||||
streamWriterMock.Verify(sw => sw.WriteLineAsync("TRCE | Test Message"), Times.Once);
|
||||
streamWriterMock.Verify(sw => sw.WriteLineAsync("DBUG | Test Message"), Times.Once);
|
||||
streamWriterMock.Verify(sw => sw.WriteLineAsync("INFO | Test Message"), Times.Once);
|
||||
streamWriterMock.Verify(sw => sw.WriteLineAsync("WARN | Test Message"), Times.Once);
|
||||
streamWriterMock.Verify(sw => sw.WriteLineAsync("FAIL | Test Message"), Times.Once);
|
||||
streamWriterMock.Verify(sw => sw.WriteLineAsync("CRIT | Test Message"), Times.Once);
|
||||
streamWriterMock.Verify(sw => sw.WriteLineAsync(" | Test Message"), Times.Once);
|
||||
streamWriterMock.Verify(sw => sw.FlushAsync(), Times.AtLeastOnce);
|
||||
streamWriterMock.VerifyNoOtherCalls();
|
||||
_streamWriterMock.Verify(sw => sw.WriteLineAsync("TRCE | Test Message"), Times.Once);
|
||||
_streamWriterMock.Verify(sw => sw.WriteLineAsync("DBUG | Test Message"), Times.Once);
|
||||
_streamWriterMock.Verify(sw => sw.WriteLineAsync("INFO | Test Message"), Times.Once);
|
||||
_streamWriterMock.Verify(sw => sw.WriteLineAsync("WARN | Test Message"), Times.Once);
|
||||
_streamWriterMock.Verify(sw => sw.WriteLineAsync("FAIL | Test Message"), Times.Once);
|
||||
_streamWriterMock.Verify(sw => sw.WriteLineAsync("CRIT | Test Message"), Times.Once);
|
||||
_streamWriterMock.Verify(sw => sw.WriteLineAsync(" | Test Message"), Times.Once);
|
||||
_streamWriterMock.Verify(sw => sw.FlushAsync(), Times.AtLeastOnce);
|
||||
_streamWriterMock.VerifyNoOtherCalls();
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
@@ -202,14 +202,14 @@ namespace UnitTests.Common.Logging
|
||||
foreach (LogLevel level in Enum.GetValues<LogLevel>())
|
||||
logger.Log(level, "Test Message");
|
||||
|
||||
SpinWait.SpinUntil(() => lines.Count == 3);
|
||||
SpinWait.SpinUntil(() => _lines.Count == 3);
|
||||
|
||||
// assert
|
||||
streamWriterMock.Verify(sw => sw.WriteLineAsync("FAIL | Test Message"), Times.Once);
|
||||
streamWriterMock.Verify(sw => sw.WriteLineAsync("CRIT | Test Message"), Times.Once);
|
||||
streamWriterMock.Verify(sw => sw.WriteLineAsync(" | Test Message"), Times.Once);
|
||||
streamWriterMock.Verify(sw => sw.FlushAsync(), Times.AtLeastOnce);
|
||||
streamWriterMock.VerifyNoOtherCalls();
|
||||
_streamWriterMock.Verify(sw => sw.WriteLineAsync("FAIL | Test Message"), Times.Once);
|
||||
_streamWriterMock.Verify(sw => sw.WriteLineAsync("CRIT | Test Message"), Times.Once);
|
||||
_streamWriterMock.Verify(sw => sw.WriteLineAsync(" | Test Message"), Times.Once);
|
||||
_streamWriterMock.Verify(sw => sw.FlushAsync(), Times.AtLeastOnce);
|
||||
_streamWriterMock.VerifyNoOtherCalls();
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
@@ -222,13 +222,13 @@ namespace UnitTests.Common.Logging
|
||||
|
||||
// act
|
||||
logger.LogWarning("Some Warning");
|
||||
SpinWait.SpinUntil(() => lines.Count == 1);
|
||||
SpinWait.SpinUntil(() => _lines.Count == 1);
|
||||
|
||||
// assert
|
||||
|
||||
streamWriterMock.Verify(sw => sw.WriteLineAsync($"{DateTime.Now:yyyy-MM-dd HH:mm} | WARN | Some Warning"), Times.Once);
|
||||
streamWriterMock.Verify(sw => sw.FlushAsync(), Times.Once);
|
||||
streamWriterMock.VerifyNoOtherCalls();
|
||||
_streamWriterMock.Verify(sw => sw.WriteLineAsync($"{DateTime.Now:yyyy-MM-dd HH:mm} | WARN | Some Warning"), Times.Once);
|
||||
_streamWriterMock.Verify(sw => sw.FlushAsync(), Times.Once);
|
||||
_streamWriterMock.VerifyNoOtherCalls();
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
@@ -241,12 +241,12 @@ namespace UnitTests.Common.Logging
|
||||
|
||||
// act
|
||||
logger.LogWarning("Some Warning");
|
||||
SpinWait.SpinUntil(() => lines.Count == 1);
|
||||
SpinWait.SpinUntil(() => _lines.Count == 1);
|
||||
|
||||
// assert
|
||||
streamWriterMock.Verify(sw => sw.WriteLineAsync($"{DateTime.UtcNow:yyyy-MM-dd HH:mm} | WARN | Some Warning"), Times.Once);
|
||||
streamWriterMock.Verify(sw => sw.FlushAsync(), Times.Once);
|
||||
streamWriterMock.VerifyNoOtherCalls();
|
||||
_streamWriterMock.Verify(sw => sw.WriteLineAsync($"{DateTime.UtcNow:yyyy-MM-dd HH:mm} | WARN | Some Warning"), Times.Once);
|
||||
_streamWriterMock.Verify(sw => sw.FlushAsync(), Times.Once);
|
||||
_streamWriterMock.VerifyNoOtherCalls();
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
@@ -264,12 +264,12 @@ namespace UnitTests.Common.Logging
|
||||
|
||||
// act
|
||||
logger.LogWarning("Some Warning");
|
||||
SpinWait.SpinUntil(() => lines.Count == 1);
|
||||
SpinWait.SpinUntil(() => _lines.Count == 1);
|
||||
|
||||
// assert
|
||||
streamWriterMock.Verify(sw => sw.WriteLineAsync($"{DateTime.Now:yyyy-MM-dd HH:mm} | WARN | [NamedInstance] Some Warning"), Times.Once);
|
||||
streamWriterMock.Verify(sw => sw.FlushAsync(), Times.Once);
|
||||
streamWriterMock.VerifyNoOtherCalls();
|
||||
_streamWriterMock.Verify(sw => sw.WriteLineAsync($"{DateTime.Now:yyyy-MM-dd HH:mm} | WARN | [NamedInstance] Some Warning"), Times.Once);
|
||||
_streamWriterMock.Verify(sw => sw.FlushAsync(), Times.Once);
|
||||
_streamWriterMock.VerifyNoOtherCalls();
|
||||
|
||||
Assert.AreEqual(0, new FileInfo(file).Length);
|
||||
}
|
||||
@@ -290,13 +290,13 @@ namespace UnitTests.Common.Logging
|
||||
using (var scope = logger.BeginScope("scope"))
|
||||
{
|
||||
logger.LogError("Test");
|
||||
SpinWait.SpinUntil(() => lines.Count == 1);
|
||||
SpinWait.SpinUntil(() => _lines.Count == 1);
|
||||
}
|
||||
|
||||
// assert
|
||||
streamWriterMock.Verify(sw => sw.WriteLineAsync("FAIL | [NamedInstance] Test"), Times.Once);
|
||||
streamWriterMock.Verify(sw => sw.FlushAsync(), Times.Once);
|
||||
streamWriterMock.VerifyNoOtherCalls();
|
||||
_streamWriterMock.Verify(sw => sw.WriteLineAsync("FAIL | [NamedInstance] Test"), Times.Once);
|
||||
_streamWriterMock.Verify(sw => sw.FlushAsync(), Times.Once);
|
||||
_streamWriterMock.VerifyNoOtherCalls();
|
||||
|
||||
scopeProvider.Verify(sp => sp.Push("scope"), Times.Once);
|
||||
scopeProvider.Verify(sp => sp.ForEachScope(It.IsAny<Action<object, It.IsAnyType>>(), It.IsAny<It.IsAnyType>()), Times.Once);
|
||||
@@ -311,12 +311,12 @@ namespace UnitTests.Common.Logging
|
||||
|
||||
// act
|
||||
logger.LogCritical(new Exception("TestException"), "");
|
||||
SpinWait.SpinUntil(() => lines.Count == 1);
|
||||
SpinWait.SpinUntil(() => _lines.Count == 1);
|
||||
|
||||
// assert
|
||||
streamWriterMock.Verify(sw => sw.WriteLineAsync("CRIT | System.Exception: TestException"), Times.Once);
|
||||
streamWriterMock.Verify(sw => sw.FlushAsync(), Times.Once);
|
||||
streamWriterMock.VerifyNoOtherCalls();
|
||||
_streamWriterMock.Verify(sw => sw.WriteLineAsync("CRIT | System.Exception: TestException"), Times.Once);
|
||||
_streamWriterMock.Verify(sw => sw.FlushAsync(), Times.Once);
|
||||
_streamWriterMock.VerifyNoOtherCalls();
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
@@ -327,12 +327,12 @@ namespace UnitTests.Common.Logging
|
||||
|
||||
// act
|
||||
logger.LogCritical(new Exception("TestException"), "Bad things happen...");
|
||||
SpinWait.SpinUntil(() => lines.Count == 1);
|
||||
SpinWait.SpinUntil(() => _lines.Count == 1);
|
||||
|
||||
// assert
|
||||
streamWriterMock.Verify(sw => sw.WriteLineAsync($"CRIT | Bad things happen...{Environment.NewLine} System.Exception: TestException"), Times.Once);
|
||||
streamWriterMock.Verify(sw => sw.FlushAsync(), Times.Once);
|
||||
streamWriterMock.VerifyNoOtherCalls();
|
||||
_streamWriterMock.Verify(sw => sw.WriteLineAsync($"CRIT | Bad things happen...{Environment.NewLine} System.Exception: TestException"), Times.Once);
|
||||
_streamWriterMock.Verify(sw => sw.FlushAsync(), Times.Once);
|
||||
_streamWriterMock.VerifyNoOtherCalls();
|
||||
}
|
||||
|
||||
private FileLogger GetFileLogger(string name = null, IExternalScopeProvider scopeProvider = null)
|
||||
@@ -340,10 +340,10 @@ namespace UnitTests.Common.Logging
|
||||
string tmpFilePath = Path.GetTempFileName();
|
||||
try
|
||||
{
|
||||
streamWriterMock = new Mock<StreamWriter>(Stream.Null);
|
||||
streamWriterMock
|
||||
_streamWriterMock = new Mock<StreamWriter>(Stream.Null);
|
||||
_streamWriterMock
|
||||
.Setup(sw => sw.WriteLineAsync(It.IsAny<string>()))
|
||||
.Callback<string>(line => lines.Add(line))
|
||||
.Callback<string>(line => _lines.Add(line))
|
||||
.Returns(Task.CompletedTask);
|
||||
|
||||
FileLogger fileLogger;
|
||||
@@ -356,9 +356,9 @@ namespace UnitTests.Common.Logging
|
||||
fileLogger = new FileLogger(tmpFilePath, name, scopeProvider);
|
||||
}
|
||||
|
||||
var fieldInfo = fileLogger.GetType().GetField("fileWriter", BindingFlags.NonPublic | BindingFlags.Instance);
|
||||
var fieldInfo = fileLogger.GetType().GetField("_fileWriter", BindingFlags.NonPublic | BindingFlags.Instance);
|
||||
(fieldInfo.GetValue(fileLogger) as StreamWriter).Dispose();
|
||||
fieldInfo.SetValue(fileLogger, streamWriterMock.Object);
|
||||
fieldInfo.SetValue(fileLogger, _streamWriterMock.Object);
|
||||
|
||||
return fileLogger;
|
||||
}
|
||||
|
||||
@@ -10,35 +10,35 @@ namespace UnitTests.Common.Utilities
|
||||
[System.Diagnostics.CodeAnalysis.ExcludeFromCodeCoverage]
|
||||
public class AsyncQueueTests
|
||||
{
|
||||
private Queue<TestElement> internalQueue;
|
||||
private Queue<TestElement> _internalQueue;
|
||||
|
||||
private TestElement queueElement1;
|
||||
private TestElement queueElement2;
|
||||
private TestElement queueElement3;
|
||||
private TestElement _queueElement1;
|
||||
private TestElement _queueElement2;
|
||||
private TestElement _queueElement3;
|
||||
|
||||
[TestInitialize]
|
||||
public void InitializeTest()
|
||||
{
|
||||
queueElement1 = new TestElement
|
||||
_queueElement1 = new TestElement
|
||||
{
|
||||
Number = 111,
|
||||
Text = "one"
|
||||
};
|
||||
queueElement2 = new TestElement
|
||||
_queueElement2 = new TestElement
|
||||
{
|
||||
Number = 222,
|
||||
Text = "two"
|
||||
};
|
||||
queueElement3 = new TestElement
|
||||
_queueElement3 = new TestElement
|
||||
{
|
||||
Number = 333,
|
||||
Text = "three"
|
||||
};
|
||||
|
||||
internalQueue = new Queue<TestElement>();
|
||||
internalQueue.Enqueue(queueElement1);
|
||||
internalQueue.Enqueue(queueElement2);
|
||||
internalQueue.Enqueue(queueElement3);
|
||||
_internalQueue = new Queue<TestElement>();
|
||||
_internalQueue.Enqueue(_queueElement1);
|
||||
_internalQueue.Enqueue(_queueElement2);
|
||||
_internalQueue.Enqueue(_queueElement3);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
@@ -47,15 +47,15 @@ namespace UnitTests.Common.Utilities
|
||||
// arrange
|
||||
var element = new TestElement { Number = 1, Text = "Hello" };
|
||||
|
||||
internalQueue.Clear();
|
||||
_internalQueue.Clear();
|
||||
var queue = GetQueue();
|
||||
|
||||
// act
|
||||
queue.Enqueue(element);
|
||||
|
||||
// assert
|
||||
Assert.AreEqual(1, internalQueue.Count);
|
||||
Assert.AreEqual(internalQueue.Count, queue.Count);
|
||||
Assert.AreEqual(1, _internalQueue.Count);
|
||||
Assert.AreEqual(_internalQueue.Count, queue.Count);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
@@ -65,7 +65,7 @@ namespace UnitTests.Common.Utilities
|
||||
var element = new TestElement { Number = 1, Text = "Hello" };
|
||||
bool available = false;
|
||||
|
||||
internalQueue.Clear();
|
||||
_internalQueue.Clear();
|
||||
var queue = GetQueue();
|
||||
|
||||
// act
|
||||
@@ -88,7 +88,7 @@ namespace UnitTests.Common.Utilities
|
||||
var element = new TestElement { Number = 1, Text = "Hello" };
|
||||
TestElement callback = null;
|
||||
|
||||
internalQueue.Clear();
|
||||
_internalQueue.Clear();
|
||||
var queue = GetQueue();
|
||||
|
||||
// act
|
||||
@@ -110,18 +110,18 @@ namespace UnitTests.Common.Utilities
|
||||
// arrange
|
||||
var elements = new TestElement[]
|
||||
{
|
||||
new TestElement { Number = 1, Text = "Hello" },
|
||||
new TestElement { Number = 2, Text = "World" },
|
||||
new() { Number = 1, Text = "Hello" },
|
||||
new() { Number = 2, Text = "World" },
|
||||
};
|
||||
internalQueue.Clear();
|
||||
_internalQueue.Clear();
|
||||
var queue = GetQueue();
|
||||
|
||||
// act
|
||||
queue.Enqueue(elements);
|
||||
|
||||
// assert
|
||||
Assert.AreEqual(2, internalQueue.Count);
|
||||
Assert.AreEqual(queue.Count, internalQueue.Count);
|
||||
Assert.AreEqual(2, _internalQueue.Count);
|
||||
Assert.AreEqual(queue.Count, _internalQueue.Count);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
@@ -136,7 +136,7 @@ namespace UnitTests.Common.Utilities
|
||||
// assert
|
||||
Assert.IsTrue(isSuccess);
|
||||
Assert.IsNotNull(item);
|
||||
Assert.AreEqual(queueElement1, item);
|
||||
Assert.AreEqual(_queueElement1, item);
|
||||
Assert.AreEqual(3, queue.Count);
|
||||
}
|
||||
|
||||
@@ -144,7 +144,7 @@ namespace UnitTests.Common.Utilities
|
||||
public void ShouldNotPeekAValue()
|
||||
{
|
||||
// arrange
|
||||
internalQueue.Clear();
|
||||
_internalQueue.Clear();
|
||||
var queue = GetQueue();
|
||||
|
||||
// act
|
||||
@@ -167,7 +167,7 @@ namespace UnitTests.Common.Utilities
|
||||
// assert
|
||||
Assert.IsTrue(isSuccess);
|
||||
Assert.IsNotNull(item);
|
||||
Assert.AreEqual(queueElement1, item);
|
||||
Assert.AreEqual(_queueElement1, item);
|
||||
Assert.AreEqual(2, queue.Count);
|
||||
}
|
||||
|
||||
@@ -175,7 +175,7 @@ namespace UnitTests.Common.Utilities
|
||||
public void ShouldNotDequeueAValue()
|
||||
{
|
||||
// arrange
|
||||
internalQueue.Clear();
|
||||
_internalQueue.Clear();
|
||||
var queue = GetQueue();
|
||||
|
||||
// act
|
||||
@@ -193,14 +193,14 @@ namespace UnitTests.Common.Utilities
|
||||
var queue = GetQueue();
|
||||
|
||||
// act
|
||||
queue.Remove(queueElement2);
|
||||
queue.Remove(_queueElement2);
|
||||
var item1 = queue.Dequeue();
|
||||
var item2 = queue.Dequeue();
|
||||
|
||||
// assert
|
||||
Assert.AreEqual(0, queue.Count);
|
||||
Assert.AreEqual(queueElement1, item1);
|
||||
Assert.AreEqual(queueElement3, item2);
|
||||
Assert.AreEqual(_queueElement1, item1);
|
||||
Assert.AreEqual(_queueElement3, item2);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
@@ -217,22 +217,22 @@ namespace UnitTests.Common.Utilities
|
||||
|
||||
// assert
|
||||
Assert.AreEqual(0, queue.Count);
|
||||
Assert.AreEqual(queueElement1, item1);
|
||||
Assert.AreEqual(queueElement2, item2);
|
||||
Assert.AreEqual(queueElement3, item3);
|
||||
Assert.AreEqual(_queueElement1, item1);
|
||||
Assert.AreEqual(_queueElement2, item2);
|
||||
Assert.AreEqual(_queueElement3, item3);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public async Task ShouldAwaitOneDequeue()
|
||||
{
|
||||
// arrange
|
||||
internalQueue.Clear();
|
||||
_internalQueue.Clear();
|
||||
var queue = GetQueue();
|
||||
|
||||
var task = Task.Run(async () =>
|
||||
{
|
||||
await Task.Delay(1000);
|
||||
queue.Enqueue(new[] { queueElement1, queueElement2, queueElement3 });
|
||||
queue.Enqueue(new[] { _queueElement1, _queueElement2, _queueElement3 });
|
||||
});
|
||||
|
||||
// act
|
||||
@@ -241,20 +241,20 @@ namespace UnitTests.Common.Utilities
|
||||
// assert
|
||||
Assert.AreEqual(2, queue.Count);
|
||||
Assert.IsNotNull(item);
|
||||
Assert.AreEqual(queueElement1, item);
|
||||
Assert.AreEqual(_queueElement1, item);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public async Task ShouldAwaitManyDequeue()
|
||||
{
|
||||
// arrange
|
||||
internalQueue.Clear();
|
||||
_internalQueue.Clear();
|
||||
var queue = GetQueue();
|
||||
|
||||
var task = Task.Run(async () =>
|
||||
{
|
||||
await Task.Delay(1000);
|
||||
queue.Enqueue(new[] { queueElement1, queueElement2, queueElement3 });
|
||||
queue.Enqueue(new[] { _queueElement1, _queueElement2, _queueElement3 });
|
||||
});
|
||||
|
||||
// act
|
||||
@@ -264,21 +264,21 @@ namespace UnitTests.Common.Utilities
|
||||
Assert.AreEqual(1, queue.Count);
|
||||
Assert.IsNotNull(items);
|
||||
Assert.AreEqual(2, items.Length);
|
||||
Assert.AreEqual(queueElement1, items[0]);
|
||||
Assert.AreEqual(queueElement2, items[1]);
|
||||
Assert.AreEqual(_queueElement1, items[0]);
|
||||
Assert.AreEqual(_queueElement2, items[1]);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public async Task ShouldAwaitAllDequeue()
|
||||
{
|
||||
// arrange
|
||||
internalQueue.Clear();
|
||||
_internalQueue.Clear();
|
||||
var queue = GetQueue();
|
||||
|
||||
var task = Task.Run(async () =>
|
||||
{
|
||||
await Task.Delay(1000);
|
||||
queue.Enqueue(new[] { queueElement1, queueElement2, queueElement3 });
|
||||
queue.Enqueue(new[] { _queueElement1, _queueElement2, _queueElement3 });
|
||||
});
|
||||
|
||||
// act
|
||||
@@ -288,22 +288,22 @@ namespace UnitTests.Common.Utilities
|
||||
Assert.AreEqual(0, queue.Count);
|
||||
Assert.IsNotNull(items);
|
||||
Assert.AreEqual(3, items.Length);
|
||||
Assert.AreEqual(queueElement1, items[0]);
|
||||
Assert.AreEqual(queueElement2, items[1]);
|
||||
Assert.AreEqual(queueElement3, items[2]);
|
||||
Assert.AreEqual(_queueElement1, items[0]);
|
||||
Assert.AreEqual(_queueElement2, items[1]);
|
||||
Assert.AreEqual(_queueElement3, items[2]);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public async Task ShouldAwaitAvailableDequeue()
|
||||
{
|
||||
// arrange
|
||||
internalQueue.Clear();
|
||||
_internalQueue.Clear();
|
||||
var queue = GetQueue();
|
||||
|
||||
var task = Task.Run(async () =>
|
||||
{
|
||||
await Task.Delay(1000);
|
||||
queue.Enqueue(new[] { queueElement1, queueElement2, queueElement3 });
|
||||
queue.Enqueue(new[] { _queueElement1, _queueElement2, _queueElement3 });
|
||||
});
|
||||
|
||||
// act
|
||||
@@ -313,8 +313,8 @@ namespace UnitTests.Common.Utilities
|
||||
Assert.AreEqual(1, queue.Count);
|
||||
Assert.IsNotNull(items);
|
||||
Assert.AreEqual(2, items.Length);
|
||||
Assert.AreEqual(queueElement1, items[0]);
|
||||
Assert.AreEqual(queueElement2, items[1]);
|
||||
Assert.AreEqual(_queueElement1, items[0]);
|
||||
Assert.AreEqual(_queueElement2, items[1]);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
@@ -322,7 +322,7 @@ namespace UnitTests.Common.Utilities
|
||||
public async Task ShouldThrowArumentOutOfRangeException()
|
||||
{
|
||||
// arrange
|
||||
internalQueue.Clear();
|
||||
_internalQueue.Clear();
|
||||
var queue = GetQueue();
|
||||
|
||||
// act
|
||||
@@ -336,8 +336,8 @@ namespace UnitTests.Common.Utilities
|
||||
{
|
||||
var asyncQueue = new AsyncQueue<TestElement>();
|
||||
|
||||
var field = asyncQueue.GetType().GetField("queue", BindingFlags.Instance | BindingFlags.NonPublic);
|
||||
field.SetValue(asyncQueue, internalQueue);
|
||||
var field = asyncQueue.GetType().GetField("_queue", BindingFlags.Instance | BindingFlags.NonPublic);
|
||||
field.SetValue(asyncQueue, _internalQueue);
|
||||
|
||||
return asyncQueue;
|
||||
}
|
||||
|
||||
@@ -10,22 +10,22 @@ namespace UnitTests.Common.Utilities
|
||||
{
|
||||
[TestClass]
|
||||
[System.Diagnostics.CodeAnalysis.ExcludeFromCodeCoverage]
|
||||
public class CryptographyHelperTests
|
||||
public partial class CryptographyHelperTests
|
||||
{
|
||||
private string keyFile;
|
||||
private CryptographyHelper cryptoHelper;
|
||||
private string _keyFile;
|
||||
private CryptographyHelper _cryptoHelper;
|
||||
|
||||
[TestInitialize]
|
||||
public void Initialize()
|
||||
{
|
||||
keyFile = Path.GetTempFileName();
|
||||
cryptoHelper = new CryptographyHelper(keyFile);
|
||||
_keyFile = Path.GetTempFileName();
|
||||
_cryptoHelper = new CryptographyHelper(_keyFile);
|
||||
}
|
||||
|
||||
[TestCleanup]
|
||||
public void Cleanup()
|
||||
{
|
||||
File.Delete(keyFile);
|
||||
File.Delete(_keyFile);
|
||||
}
|
||||
|
||||
#region Static
|
||||
@@ -40,12 +40,12 @@ namespace UnitTests.Common.Utilities
|
||||
// arrange
|
||||
using var _ = CryptographyHelperSaltMock.Create(0);
|
||||
|
||||
byte[] bytes = new byte[] { 0xaf, 0xfe };
|
||||
byte[] bytes = [0xaf, 0xfe];
|
||||
string str = "ABC";
|
||||
string password1 = "P@ssw0rd!";
|
||||
string password2 = "P@ssw0rd";
|
||||
|
||||
byte[] expectedBytes = new byte[] { 0x7c, 0x7b, 0x77, 0x56, 0x91, 0x1a, 0xd9, 0xc0, 0x72, 0x70, 0x36, 0x88, 0x9f, 0xb4, 0xb5, 0xbc };
|
||||
byte[] expectedBytes = [0x7c, 0x7b, 0x77, 0x56, 0x91, 0x1a, 0xd9, 0xc0, 0x72, 0x70, 0x36, 0x88, 0x9f, 0xb4, 0xb5, 0xbc];
|
||||
|
||||
// act
|
||||
byte[] cipherBytes1 = CryptographyHelper.AesEncrypt(bytes, password1);
|
||||
@@ -68,12 +68,12 @@ namespace UnitTests.Common.Utilities
|
||||
using var _ = CryptographyHelperSaltMock.Create(0);
|
||||
|
||||
string cipherStr = "ueLuhFNpCuYmx8v3hczHtg==";
|
||||
byte[] cipherBytes = new byte[] { 0x7c, 0x7b, 0x77, 0x56, 0x91, 0x1a, 0xd9, 0xc0, 0x72, 0x70, 0x36, 0x88, 0x9f, 0xb4, 0xb5, 0xbc };
|
||||
byte[] cipherBytes = [0x7c, 0x7b, 0x77, 0x56, 0x91, 0x1a, 0xd9, 0xc0, 0x72, 0x70, 0x36, 0x88, 0x9f, 0xb4, 0xb5, 0xbc];
|
||||
|
||||
string password1 = "P@ssw0rd!";
|
||||
string password2 = "P@ssw0rd";
|
||||
|
||||
byte[] expectedBytes = new byte[] { 0xaf, 0xfe };
|
||||
byte[] expectedBytes = [0xaf, 0xfe];
|
||||
|
||||
// act
|
||||
byte[] plainBytes1 = CryptographyHelper.AesDecrypt(cipherBytes, password1);
|
||||
@@ -104,7 +104,7 @@ namespace UnitTests.Common.Utilities
|
||||
public void ShouldEncryptDecryptAesBytes()
|
||||
{
|
||||
// arrange
|
||||
byte[] plain = new byte[] { 0xaf, 0xfe };
|
||||
byte[] plain = [0xaf, 0xfe];
|
||||
string password = "P@ssw0rd!";
|
||||
|
||||
// act
|
||||
@@ -154,12 +154,12 @@ namespace UnitTests.Common.Utilities
|
||||
// arrange
|
||||
using var _ = CryptographyHelperSaltMock.Create(0);
|
||||
|
||||
byte[] bytes = new byte[] { 0xaf, 0xfe };
|
||||
byte[] bytes = [0xaf, 0xfe];
|
||||
string str = "ABC";
|
||||
string password1 = "P@ssw0rd!";
|
||||
string password2 = "P@ssw0rd";
|
||||
|
||||
byte[] expectedBytes = new byte[] { 0xbf, 0x59, 0x1f, 0x48, 0x69, 0xab, 0x18, 0xc7 };
|
||||
byte[] expectedBytes = [0xbf, 0x59, 0x1f, 0x48, 0x69, 0xab, 0x18, 0xc7];
|
||||
|
||||
// act
|
||||
byte[] cipherBytes1 = CryptographyHelper.TripleDesEncrypt(bytes, password1);
|
||||
@@ -182,12 +182,12 @@ namespace UnitTests.Common.Utilities
|
||||
using var _ = CryptographyHelperSaltMock.Create(0);
|
||||
|
||||
string cipherStr = "1l74soBuuEI=";
|
||||
byte[] cipherBytes = new byte[] { 0xbf, 0x59, 0x1f, 0x48, 0x69, 0xab, 0x18, 0xc7 };
|
||||
byte[] cipherBytes = [0xbf, 0x59, 0x1f, 0x48, 0x69, 0xab, 0x18, 0xc7];
|
||||
|
||||
string password1 = "P@ssw0rd!";
|
||||
string password2 = "P@ssw0rd";
|
||||
|
||||
byte[] expectedBytes = new byte[] { 0xaf, 0xfe };
|
||||
byte[] expectedBytes = [0xaf, 0xfe];
|
||||
|
||||
// act
|
||||
byte[] plainBytes1 = CryptographyHelper.TripleDesDecrypt(cipherBytes, password1);
|
||||
@@ -218,7 +218,7 @@ namespace UnitTests.Common.Utilities
|
||||
public void ShouldEncryptDecryptTdesBytes()
|
||||
{
|
||||
// arrange
|
||||
byte[] plain = new byte[] { 0xaf, 0xfe };
|
||||
byte[] plain = [0xaf, 0xfe];
|
||||
string password = "P@ssw0rd!";
|
||||
|
||||
// act
|
||||
@@ -269,7 +269,7 @@ namespace UnitTests.Common.Utilities
|
||||
{
|
||||
// arrange
|
||||
string text = "Hello World!";
|
||||
byte[] bytes = new byte[] { 0xde, 0xad, 0xbe, 0xef };
|
||||
byte[] bytes = [0xde, 0xad, 0xbe, 0xef];
|
||||
string fileName = Path.GetTempFileName();
|
||||
|
||||
// act
|
||||
@@ -291,7 +291,7 @@ namespace UnitTests.Common.Utilities
|
||||
{
|
||||
// arrange
|
||||
string text = "Hello World!";
|
||||
byte[] bytes = new byte[] { 0xde, 0xad, 0xbe, 0xef };
|
||||
byte[] bytes = [0xde, 0xad, 0xbe, 0xef];
|
||||
string fileName = Path.GetTempFileName();
|
||||
|
||||
// act
|
||||
@@ -313,7 +313,7 @@ namespace UnitTests.Common.Utilities
|
||||
{
|
||||
// arrange
|
||||
string text = "Hello World!";
|
||||
byte[] bytes = new byte[] { 0xde, 0xad, 0xbe, 0xef };
|
||||
byte[] bytes = [0xde, 0xad, 0xbe, 0xef];
|
||||
string fileName = Path.GetTempFileName();
|
||||
|
||||
// act
|
||||
@@ -335,7 +335,7 @@ namespace UnitTests.Common.Utilities
|
||||
{
|
||||
// arrange
|
||||
string text = "Hello World!";
|
||||
byte[] bytes = new byte[] { 0xde, 0xad, 0xbe, 0xef };
|
||||
byte[] bytes = [0xde, 0xad, 0xbe, 0xef];
|
||||
string fileName = Path.GetTempFileName();
|
||||
|
||||
// act
|
||||
@@ -415,8 +415,8 @@ namespace UnitTests.Common.Utilities
|
||||
Assert.AreEqual(length, str1.Length);
|
||||
Assert.AreEqual(length, str2.Length);
|
||||
Assert.IsFalse(str1 == str2);
|
||||
Assert.IsFalse(Regex.IsMatch(str1, "[^0-9a-f]"));
|
||||
Assert.IsFalse(Regex.IsMatch(str2, "[^0-9a-f]"));
|
||||
Assert.IsFalse(RandomStringWithPoolRegex().IsMatch(str1));
|
||||
Assert.IsFalse(RandomStringWithPoolRegex().IsMatch(str2));
|
||||
}
|
||||
|
||||
#endregion Random
|
||||
@@ -537,7 +537,6 @@ namespace UnitTests.Common.Utilities
|
||||
Assert.IsTrue(!string.IsNullOrWhiteSpace(content));
|
||||
}
|
||||
|
||||
|
||||
[TestMethod]
|
||||
public void ShouldEncryptAesUsingKeyFile()
|
||||
{
|
||||
@@ -545,11 +544,11 @@ namespace UnitTests.Common.Utilities
|
||||
string str = "Hello World!";
|
||||
byte[] bytes = CryptographyHelper.GetRandomBytes(32);
|
||||
|
||||
string password = File.ReadAllText(keyFile);
|
||||
string password = File.ReadAllText(_keyFile);
|
||||
|
||||
// act
|
||||
string cipherStr = cryptoHelper.EncryptAes(str);
|
||||
byte[] cipherBytes = cryptoHelper.EncryptAes(bytes);
|
||||
string cipherStr = _cryptoHelper.EncryptAes(str);
|
||||
byte[] cipherBytes = _cryptoHelper.EncryptAes(bytes);
|
||||
|
||||
string plainStr = CryptographyHelper.AesDecrypt(cipherStr, password);
|
||||
byte[] plainBytes = CryptographyHelper.AesDecrypt(cipherBytes, password);
|
||||
@@ -568,14 +567,14 @@ namespace UnitTests.Common.Utilities
|
||||
string str = "Hello World!";
|
||||
byte[] bytes = CryptographyHelper.GetRandomBytes(32);
|
||||
|
||||
string password = File.ReadAllText(keyFile);
|
||||
string password = File.ReadAllText(_keyFile);
|
||||
|
||||
// act
|
||||
string cipherStr = CryptographyHelper.AesEncrypt(str, password);
|
||||
byte[] cipherBytes = CryptographyHelper.AesEncrypt(bytes, password);
|
||||
|
||||
string plainStr = cryptoHelper.DecryptAes(cipherStr);
|
||||
byte[] plainBytes = cryptoHelper.DecryptAes(cipherBytes);
|
||||
string plainStr = _cryptoHelper.DecryptAes(cipherStr);
|
||||
byte[] plainBytes = _cryptoHelper.DecryptAes(cipherBytes);
|
||||
|
||||
// assert
|
||||
Assert.AreNotEqual(str, cipherStr);
|
||||
@@ -591,11 +590,11 @@ namespace UnitTests.Common.Utilities
|
||||
string str = "Hello World!";
|
||||
byte[] bytes = CryptographyHelper.GetRandomBytes(32);
|
||||
|
||||
string password = File.ReadAllText(keyFile);
|
||||
string password = File.ReadAllText(_keyFile);
|
||||
|
||||
// act
|
||||
string cipherStr = cryptoHelper.EncryptTripleDes(str);
|
||||
byte[] cipherBytes = cryptoHelper.EncryptTripleDes(bytes);
|
||||
string cipherStr = _cryptoHelper.EncryptTripleDes(str);
|
||||
byte[] cipherBytes = _cryptoHelper.EncryptTripleDes(bytes);
|
||||
|
||||
string plainStr = CryptographyHelper.TripleDesDecrypt(cipherStr, password);
|
||||
byte[] plainBytes = CryptographyHelper.TripleDesDecrypt(cipherBytes, password);
|
||||
@@ -614,14 +613,14 @@ namespace UnitTests.Common.Utilities
|
||||
string str = "Hello World!";
|
||||
byte[] bytes = CryptographyHelper.GetRandomBytes(32);
|
||||
|
||||
string password = File.ReadAllText(keyFile);
|
||||
string password = File.ReadAllText(_keyFile);
|
||||
|
||||
// act
|
||||
string cipherStr = CryptographyHelper.TripleDesEncrypt(str, password);
|
||||
byte[] cipherBytes = CryptographyHelper.TripleDesEncrypt(bytes, password);
|
||||
|
||||
string plainStr = cryptoHelper.DecryptTripleDes(cipherStr);
|
||||
byte[] plainBytes = cryptoHelper.DecryptTripleDes(cipherBytes);
|
||||
string plainStr = _cryptoHelper.DecryptTripleDes(cipherStr);
|
||||
byte[] plainBytes = _cryptoHelper.DecryptTripleDes(cipherBytes);
|
||||
|
||||
// assert
|
||||
Assert.AreNotEqual(str, cipherStr);
|
||||
@@ -630,6 +629,9 @@ namespace UnitTests.Common.Utilities
|
||||
CollectionAssert.AreEqual(bytes, plainBytes);
|
||||
}
|
||||
|
||||
[GeneratedRegex("[^0-9a-f]")]
|
||||
private static partial Regex RandomStringWithPoolRegex();
|
||||
|
||||
#endregion Instance
|
||||
}
|
||||
}
|
||||
|
||||
@@ -17,11 +17,11 @@ namespace UnitTests.Common.Utilities
|
||||
// arrange
|
||||
int executionCount = 0;
|
||||
var delay = TimeSpan.FromMilliseconds(100);
|
||||
var action = () => { executionCount++; };
|
||||
void Action() { executionCount++; }
|
||||
|
||||
// act
|
||||
var cts = new CancellationTokenSource(delay.Add(TimeSpan.FromSeconds(1)));
|
||||
var delayedTask = DelayedTask.Create(action, delay);
|
||||
var delayedTask = DelayedTask.Create(Action, delay);
|
||||
SpinWait.SpinUntil(() => executionCount > 0 || cts.IsCancellationRequested);
|
||||
|
||||
// assert
|
||||
@@ -39,11 +39,11 @@ namespace UnitTests.Common.Utilities
|
||||
// arrange
|
||||
int executionCount = 0;
|
||||
var delay = TimeSpan.FromMilliseconds(100);
|
||||
var action = () => { executionCount++; };
|
||||
void Action() { executionCount++; }
|
||||
|
||||
// act
|
||||
var cts = new CancellationTokenSource(delay.Add(TimeSpan.FromSeconds(1)));
|
||||
var delayedTask = DelayedTask.Run(action, delay);
|
||||
var delayedTask = DelayedTask.Run(Action, delay);
|
||||
SpinWait.SpinUntil(() => executionCount > 0 || cts.IsCancellationRequested);
|
||||
|
||||
// assert
|
||||
@@ -61,11 +61,11 @@ namespace UnitTests.Common.Utilities
|
||||
// arrange
|
||||
int executionCount = 0;
|
||||
var delay = TimeSpan.FromMilliseconds(100);
|
||||
var action = () => { executionCount++; };
|
||||
void Action() { executionCount++; }
|
||||
|
||||
// act
|
||||
var cts = new CancellationTokenSource(delay.Add(TimeSpan.FromSeconds(1)));
|
||||
var delayedTask = DelayedTask.Create(action, delay);
|
||||
var delayedTask = DelayedTask.Create(Action, delay);
|
||||
delayedTask.Reset();
|
||||
SpinWait.SpinUntil(() => executionCount > 0 || cts.IsCancellationRequested);
|
||||
|
||||
@@ -84,11 +84,11 @@ namespace UnitTests.Common.Utilities
|
||||
// arrange
|
||||
int executionCount = 0;
|
||||
var delay = TimeSpan.FromMilliseconds(100);
|
||||
var action = () => { executionCount++; };
|
||||
void Action() { executionCount++; }
|
||||
|
||||
// act
|
||||
var cts = new CancellationTokenSource(delay.Add(TimeSpan.FromSeconds(1)));
|
||||
var delayedTask = DelayedTask.Run(action, delay);
|
||||
var delayedTask = DelayedTask.Run(Action, delay);
|
||||
delayedTask.Cancel();
|
||||
SpinWait.SpinUntil(() => executionCount > 0 || cts.IsCancellationRequested);
|
||||
|
||||
@@ -109,12 +109,12 @@ namespace UnitTests.Common.Utilities
|
||||
var sw = new Stopwatch();
|
||||
|
||||
var delay = TimeSpan.FromMilliseconds(200);
|
||||
var action = () => { sw.Stop(); executionCount++; };
|
||||
void Action() { sw.Stop(); executionCount++; }
|
||||
|
||||
// act
|
||||
var cts = new CancellationTokenSource(delay.Add(TimeSpan.FromSeconds(1)));
|
||||
sw.Start();
|
||||
var delayedTask = DelayedTask.Run(action, delay);
|
||||
var delayedTask = DelayedTask.Run(Action, delay);
|
||||
await Task.Delay(50);
|
||||
delayedTask.Reset();
|
||||
SpinWait.SpinUntil(() => executionCount > 0 || cts.IsCancellationRequested);
|
||||
@@ -138,12 +138,12 @@ namespace UnitTests.Common.Utilities
|
||||
var sw = new Stopwatch();
|
||||
|
||||
var delay = TimeSpan.FromMilliseconds(200);
|
||||
var action = () => { sw.Stop(); executionCount++; };
|
||||
void Action() { sw.Stop(); executionCount++; }
|
||||
|
||||
// act
|
||||
var cts = new CancellationTokenSource(delay.Add(TimeSpan.FromSeconds(1)));
|
||||
sw.Start();
|
||||
var delayedTask = DelayedTask.Create(action, delay);
|
||||
var delayedTask = DelayedTask.Create(Action, delay);
|
||||
await Task.Delay(50);
|
||||
bool isSuccess = delayedTask.ExecutePending();
|
||||
SpinWait.SpinUntil(() => executionCount > 0 || cts.IsCancellationRequested);
|
||||
@@ -169,12 +169,12 @@ namespace UnitTests.Common.Utilities
|
||||
var sw = new Stopwatch();
|
||||
|
||||
var delay = TimeSpan.FromMilliseconds(200);
|
||||
var action = () => { sw.Stop(); executionCount++; };
|
||||
void Action() { sw.Stop(); executionCount++; }
|
||||
|
||||
// act
|
||||
var cts = new CancellationTokenSource(delay.Add(TimeSpan.FromSeconds(1)));
|
||||
sw.Start();
|
||||
var delayedTask = DelayedTask.Run(action, delay);
|
||||
var delayedTask = DelayedTask.Run(Action, delay);
|
||||
await Task.Delay(50);
|
||||
bool isSuccess = delayedTask.ExecutePending();
|
||||
SpinWait.SpinUntil(() => executionCount > 0 || cts.IsCancellationRequested);
|
||||
@@ -197,8 +197,8 @@ namespace UnitTests.Common.Utilities
|
||||
// arrange
|
||||
int executionCount = 0;
|
||||
var delay = TimeSpan.FromMilliseconds(100);
|
||||
var action = () => { executionCount++; };
|
||||
var delayedTask = DelayedTask.Create(action, delay);
|
||||
void Action() { executionCount++; }
|
||||
var delayedTask = DelayedTask.Create(Action, delay);
|
||||
|
||||
// act
|
||||
delayedTask.Reset();
|
||||
@@ -219,10 +219,10 @@ namespace UnitTests.Common.Utilities
|
||||
{
|
||||
// arrange
|
||||
var delay = TimeSpan.FromMilliseconds(100);
|
||||
var action = () => { throw new Exception("TEST :D"); };
|
||||
static void Action() { throw new Exception("TEST :D"); }
|
||||
|
||||
// act
|
||||
var delayedTask = DelayedTask.Run(action, delay);
|
||||
var delayedTask = DelayedTask.Run(Action, delay);
|
||||
|
||||
var awaiter = delayedTask.GetAwaiter();
|
||||
SpinWait.SpinUntil(() => awaiter.IsCompleted);
|
||||
@@ -240,15 +240,12 @@ namespace UnitTests.Common.Utilities
|
||||
// arrange
|
||||
string exceptionText = null;
|
||||
var delay = TimeSpan.FromMilliseconds(100);
|
||||
var action = () => { throw new Exception("TEST :D"); };
|
||||
var exceptionHandler = (Exception ex) =>
|
||||
{
|
||||
exceptionText = ex.Message;
|
||||
};
|
||||
void Action() { throw new Exception("TEST :D"); }
|
||||
void ExceptionHandler(Exception ex) { exceptionText = ex.Message; }
|
||||
|
||||
// act
|
||||
var delayedTask = DelayedTask.Run(action, delay)
|
||||
.WithExceptionHandler(exceptionHandler);
|
||||
var delayedTask = DelayedTask.Run(Action, delay)
|
||||
.WithExceptionHandler(ExceptionHandler);
|
||||
|
||||
var awaiter = delayedTask.GetAwaiter();
|
||||
SpinWait.SpinUntil(() => awaiter.IsCompleted);
|
||||
@@ -267,8 +264,8 @@ namespace UnitTests.Common.Utilities
|
||||
// arrange
|
||||
int executionCount = 0;
|
||||
var delay = TimeSpan.FromMilliseconds(100);
|
||||
var action = () => { executionCount++; };
|
||||
var delayedTask = DelayedTask.Create(action, delay);
|
||||
void Action() { executionCount++; }
|
||||
var delayedTask = DelayedTask.Create(Action, delay);
|
||||
|
||||
// act
|
||||
delayedTask.Reset();
|
||||
|
||||
@@ -1,5 +1,4 @@
|
||||
using System;
|
||||
using System.Diagnostics;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
using AMWD.Common.Utilities;
|
||||
@@ -17,11 +16,11 @@ namespace UnitTests.Common.Utilities
|
||||
// arrange
|
||||
int executionCount = 0;
|
||||
var delay = TimeSpan.FromMilliseconds(100);
|
||||
var function = () => { executionCount++; return new[] { 42, 21 }; };
|
||||
int[] Function() { executionCount++; return [42, 21]; }
|
||||
|
||||
// act
|
||||
var cts = new CancellationTokenSource(delay.Add(TimeSpan.FromSeconds(1)));
|
||||
var delayedTaskWithResult = DelayedTask.Create(function, delay);
|
||||
var delayedTaskWithResult = DelayedTask.Create(Function, delay);
|
||||
SpinWait.SpinUntil(() => executionCount > 0 || cts.IsCancellationRequested);
|
||||
|
||||
// assert
|
||||
@@ -34,15 +33,16 @@ namespace UnitTests.Common.Utilities
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
[System.Diagnostics.CodeAnalysis.SuppressMessage("Performance", "CA1861")]
|
||||
public async Task ShouldCreateNewDelayedTaskStarting()
|
||||
{
|
||||
// arrange
|
||||
int executionCount = 0;
|
||||
var delay = TimeSpan.FromMilliseconds(100);
|
||||
var function = () => { executionCount++; return new[] { 42, 21 }; };
|
||||
int[] Function() { executionCount++; return [42, 21]; }
|
||||
|
||||
// act
|
||||
var delayedTaskWithResult = DelayedTask.Run(function, delay);
|
||||
var delayedTaskWithResult = DelayedTask.Run(Function, delay);
|
||||
int[] result = await delayedTaskWithResult;
|
||||
|
||||
// assert
|
||||
@@ -61,11 +61,11 @@ namespace UnitTests.Common.Utilities
|
||||
// arrange
|
||||
var delay = TimeSpan.FromMilliseconds(100);
|
||||
#pragma warning disable CS0162 // Unreachable Code detected.
|
||||
var function = () => { throw new Exception("TEST :D"); return new[] { 42, 21 }; };
|
||||
static int[] Function() { throw new Exception("TEST :D"); return [42, 21]; }
|
||||
#pragma warning restore CS0162 // Unreachable Code detected
|
||||
|
||||
// act
|
||||
var delayedTaskWithResult = DelayedTask.Run(function, delay);
|
||||
var delayedTaskWithResult = DelayedTask.Run(Function, delay);
|
||||
|
||||
var awaiter = delayedTaskWithResult.GetAwaiter();
|
||||
SpinWait.SpinUntil(() => awaiter.IsCompleted);
|
||||
@@ -84,16 +84,13 @@ namespace UnitTests.Common.Utilities
|
||||
string exceptionText = null;
|
||||
var delay = TimeSpan.FromMilliseconds(100);
|
||||
#pragma warning disable CS0162 // Unreachable Code detected.
|
||||
var function = () => { throw new Exception("TEST :D"); return new[] { 42, 21 }; };
|
||||
static int[] Function() { throw new Exception("TEST :D"); return [42, 21]; }
|
||||
#pragma warning restore CS0162 // Unreachable Code detected
|
||||
var exceptionHandler = (Exception ex) =>
|
||||
{
|
||||
exceptionText = ex.Message;
|
||||
};
|
||||
void ExceptionHandler(Exception ex) { exceptionText = ex.Message; }
|
||||
|
||||
// act
|
||||
var delayedTaskWithResult = DelayedTask.Run(function, delay)
|
||||
.WithExceptionHandler(exceptionHandler);
|
||||
var delayedTaskWithResult = DelayedTask.Run(Function, delay)
|
||||
.WithExceptionHandler(ExceptionHandler);
|
||||
|
||||
var awaiter = delayedTaskWithResult.GetAwaiter();
|
||||
SpinWait.SpinUntil(() => awaiter.IsCompleted);
|
||||
@@ -107,13 +104,14 @@ namespace UnitTests.Common.Utilities
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
[System.Diagnostics.CodeAnalysis.SuppressMessage("Performance", "CA1861")]
|
||||
public async Task ShouldReturnNormalTask()
|
||||
{
|
||||
// arrange
|
||||
int executionCount = 0;
|
||||
var delay = TimeSpan.FromMilliseconds(100);
|
||||
var function = () => { executionCount++; return new[] { 42, 21 }; };
|
||||
var delayedTaskWithResult = DelayedTask.Create(function, delay);
|
||||
int[] Function() { executionCount++; return [42, 21]; }
|
||||
var delayedTaskWithResult = DelayedTask.Create(Function, delay);
|
||||
|
||||
// act
|
||||
delayedTaskWithResult.Reset();
|
||||
|
||||
@@ -7,11 +7,11 @@ namespace UnitTests.Common.Utils
|
||||
[System.Diagnostics.CodeAnalysis.ExcludeFromCodeCoverage]
|
||||
internal class CryptographyHelperSaltMock : IDisposable
|
||||
{
|
||||
private readonly int saltLength;
|
||||
private readonly int _saltLength;
|
||||
|
||||
private CryptographyHelperSaltMock(int saltLength)
|
||||
{
|
||||
this.saltLength = typeof(CryptographyHelper).AsDynamicType().saltLength;
|
||||
_saltLength = typeof(CryptographyHelper).AsDynamicType()._saltLength;
|
||||
SetSaltLength(saltLength);
|
||||
}
|
||||
|
||||
@@ -19,9 +19,9 @@ namespace UnitTests.Common.Utils
|
||||
=> new CryptographyHelperSaltMock(saltLength);
|
||||
|
||||
public void Dispose()
|
||||
=> SetSaltLength(saltLength);
|
||||
=> SetSaltLength(_saltLength);
|
||||
|
||||
private static void SetSaltLength(int length)
|
||||
=> typeof(CryptographyHelper).AsDynamicType().saltLength = length;
|
||||
=> typeof(CryptographyHelper).AsDynamicType()._saltLength = length;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -4,13 +4,8 @@ namespace UnitTests.Common.Utils
|
||||
{
|
||||
[System.Diagnostics.CodeAnalysis.ExcludeFromCodeCoverage]
|
||||
[AttributeUsage(AttributeTargets.All, AllowMultiple = true)]
|
||||
internal class CustomMultipleAttribute : Attribute
|
||||
internal class CustomMultipleAttribute(string name) : Attribute
|
||||
{
|
||||
public CustomMultipleAttribute(string name)
|
||||
{
|
||||
Name = name;
|
||||
}
|
||||
|
||||
public string Name { get; set; }
|
||||
public string Name { get; set; } = name;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -33,18 +33,21 @@ namespace UnitTests.Common.Utils
|
||||
[System.Diagnostics.CodeAnalysis.ExcludeFromCodeCoverage]
|
||||
internal class JsonErrorClass
|
||||
{
|
||||
private int? number;
|
||||
private int? _number;
|
||||
|
||||
public int Number
|
||||
{
|
||||
get
|
||||
{
|
||||
if (number.HasValue)
|
||||
return number.Value;
|
||||
if (_number.HasValue)
|
||||
return _number.Value;
|
||||
|
||||
throw new Exception("Null value");
|
||||
}
|
||||
set { number = value; }
|
||||
set
|
||||
{
|
||||
_number = value;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -6,11 +6,11 @@ namespace UnitTests.Common.Utils
|
||||
[System.Diagnostics.CodeAnalysis.ExcludeFromCodeCoverage]
|
||||
internal class TimeZoneInfoLocalMock : IDisposable
|
||||
{
|
||||
private readonly TimeZoneInfo localTimeZoneInfo;
|
||||
private readonly TimeZoneInfo _localTimeZoneInfo;
|
||||
|
||||
private TimeZoneInfoLocalMock(TimeZoneInfo timeZoneInfo)
|
||||
{
|
||||
localTimeZoneInfo = TimeZoneInfo.Local;
|
||||
_localTimeZoneInfo = TimeZoneInfo.Local;
|
||||
SetLocalTimeZone(timeZoneInfo);
|
||||
}
|
||||
|
||||
@@ -18,7 +18,7 @@ namespace UnitTests.Common.Utils
|
||||
=> new TimeZoneInfoLocalMock(mockTimeZoneInfo);
|
||||
|
||||
public void Dispose()
|
||||
=> SetLocalTimeZone(localTimeZoneInfo);
|
||||
=> SetLocalTimeZone(_localTimeZoneInfo);
|
||||
|
||||
private static void SetLocalTimeZone(TimeZoneInfo timeZoneInfo)
|
||||
=> typeof(TimeZoneInfo).AsDynamicType().s_cachedData._localTimeZone = timeZoneInfo;
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
<Project Sdk="Microsoft.NET.Sdk">
|
||||
|
||||
<PropertyGroup>
|
||||
<TargetFramework>net6.0</TargetFramework>
|
||||
<TargetFramework>net8.0</TargetFramework>
|
||||
<IsPackable>false</IsPackable>
|
||||
<CollectCoverage>true</CollectCoverage>
|
||||
<GenerateDocumentationFile>false</GenerateDocumentationFile>
|
||||
|
||||
Reference in New Issue
Block a user