1
0

Merge branch 'main' into packing

This commit is contained in:
2024-01-10 08:44:08 +01:00
84 changed files with 2742 additions and 1268 deletions

View File

@@ -0,0 +1,306 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using AMWD.Common.Cli;
using Microsoft.VisualStudio.TestTools.UnitTesting;
namespace UnitTests.Common.Cli
{
[TestClass]
public class CommandLineParserTests
{
[TestMethod]
public void ShouldParseStringToArgs()
{
// arrange
// act
string[] result = CommandLineParser.ParseArgsString("Option1 \"Option 2\" \"Some \"\" Option\" Foo=Bar \\ /help \\\\backslash \\\"escapedquote \\test");
// assert
Assert.IsNotNull(result);
Assert.AreEqual(9, result.Length);
Assert.AreEqual("Option1", result[0]);
Assert.AreEqual("Option 2", result[1]);
Assert.AreEqual("Some \" Option", result[2]);
Assert.AreEqual("Foo=Bar", result[3]);
Assert.AreEqual("\\", result[4]);
Assert.AreEqual("/help", result[5]);
Assert.AreEqual("\\backslash", result[6]);
Assert.AreEqual("\"escapedquote", result[7]);
Assert.AreEqual("\\test", result[8]);
}
[TestMethod]
public void ShouldReadArgs()
{
// arrange
var parser = new CommandLineParser();
// act
parser.ReadArgs("Option1 \"Option 2\"");
string[] args = parser.GetType().GetField("_args", BindingFlags.NonPublic | BindingFlags.Instance).GetValue(parser) as string[];
// assert
Assert.IsNotNull(args);
Assert.AreEqual(2, args.Length);
Assert.AreEqual("Option1", args[0]);
Assert.AreEqual("Option 2", args[1]);
}
[TestMethod]
public void ShouldRegisterOptions()
{
// arrange
var parser = new CommandLineParser();
// act
parser.RegisterOption("opt1");
parser.RegisterOption("opt2", 1);
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>;
// assert
Assert.IsNotNull(options);
Assert.AreEqual(4, options.Count);
Assert.AreEqual(1, options.ElementAt(0).Names.Count);
Assert.AreEqual("opt1", options.ElementAt(0).Names.First());
Assert.AreEqual(0, options.ElementAt(0).ParameterCount);
Assert.IsFalse(options.ElementAt(0).IsSingle);
Assert.IsFalse(options.ElementAt(0).IsRequired);
Assert.AreEqual(1, options.ElementAt(1).Names.Count);
Assert.AreEqual("opt2", options.ElementAt(1).Names.First());
Assert.AreEqual(1, options.ElementAt(1).ParameterCount);
Assert.IsFalse(options.ElementAt(1).IsSingle);
Assert.IsFalse(options.ElementAt(1).IsRequired);
Assert.AreEqual(1, options.ElementAt(2).Names.Count);
Assert.AreEqual("opt3", options.ElementAt(2).Names.First());
Assert.AreEqual(2, options.ElementAt(2).ParameterCount);
Assert.IsTrue(options.ElementAt(2).IsSingle);
Assert.IsTrue(options.ElementAt(2).IsRequired);
Assert.AreEqual(2, options.ElementAt(3).Names.Count);
Assert.AreEqual("opt4", options.ElementAt(3).Names.First());
Assert.AreEqual("option4", options.ElementAt(3).Names.Last());
Assert.AreEqual(0, options.ElementAt(3).ParameterCount);
Assert.IsFalse(options.ElementAt(3).IsSingle);
Assert.IsFalse(options.ElementAt(3).IsRequired);
}
[TestMethod]
public void ShouldParse()
{
// arrange
string argString = "/opt1 /opt2:two -opt3=three1 three2 --opt4:four /test:done -- foo bar";
var parser = new CommandLineParser();
parser.RegisterOption("opt1");
parser.RegisterOption("opt2", 1);
parser.RegisterOption("opt3", 2);
parser.RegisterOption("opt4", 1);
var opt = parser.RegisterOption("notUsed");
parser.RegisterOption("testing", 1);
parser.ReadArgs(argString);
// act
parser.Parse();
// assert
Assert.IsFalse(opt.IsSet);
Assert.AreEqual(7, parser.Arguments.Length);
Assert.AreEqual(2, parser.FreeArguments.Length);
Assert.AreEqual("foo", parser.FreeArguments.First());
Assert.AreEqual("bar", parser.FreeArguments.Last());
Assert.IsTrue(parser.Arguments.ElementAt(0).Option.IsSet);
Assert.IsNull(parser.Arguments.ElementAt(0).Option.Value);
Assert.AreEqual(0, parser.Arguments.ElementAt(0).Values.Length);
Assert.IsTrue(parser.Arguments.ElementAt(1).Option.IsSet);
Assert.AreEqual("two", parser.Arguments.ElementAt(1).Option.Value);
Assert.AreEqual(1, parser.Arguments.ElementAt(1).Values.Length);
Assert.AreEqual("two", parser.Arguments.ElementAt(1).Values.First());
Assert.IsTrue(parser.Arguments.ElementAt(2).Option.IsSet);
Assert.AreEqual("three1", parser.Arguments.ElementAt(2).Option.Value);
Assert.AreEqual(2, parser.Arguments.ElementAt(2).Values.Length);
Assert.AreEqual("three1", parser.Arguments.ElementAt(2).Values.First());
Assert.AreEqual("three2", parser.Arguments.ElementAt(2).Values.Last());
Assert.IsTrue(parser.Arguments.ElementAt(3).Option.IsSet);
Assert.AreEqual("four", parser.Arguments.ElementAt(3).Option.Value);
Assert.AreEqual(1, parser.Arguments.ElementAt(3).Values.Length);
Assert.AreEqual("four", parser.Arguments.ElementAt(3).Values.First());
Assert.IsTrue(parser.Arguments.ElementAt(4).Option.IsSet);
Assert.AreEqual("testing", parser.Arguments.ElementAt(4).Option.Names.First());
Assert.AreEqual("done", parser.Arguments.ElementAt(4).Option.Value);
Assert.AreEqual(1, parser.Arguments.ElementAt(4).Values.Length);
Assert.AreEqual("done", parser.Arguments.ElementAt(4).Values.First());
Assert.IsNull(parser.Arguments.ElementAt(5).Option);
Assert.AreEqual("foo", parser.Arguments.ElementAt(5).Value);
Assert.AreEqual(1, parser.Arguments.ElementAt(5).Values.Length);
Assert.IsNull(parser.Arguments.ElementAt(6).Option);
Assert.AreEqual("bar", parser.Arguments.ElementAt(6).Value);
Assert.AreEqual(1, parser.Arguments.ElementAt(6).Values.Length);
}
[TestMethod]
public void ShouldExecuteOptionActionOnParse()
{
// arrange
Argument actionArgument = null;
string[] args = ["/run", "--opt"];
var parser = new CommandLineParser();
parser.RegisterOption("opt").Required();
parser.RegisterOption("run").Do(arg => actionArgument = arg);
// act
parser.Parse(args);
// assert
Assert.IsNotNull(actionArgument);
Assert.IsNotNull(actionArgument.Option);
Assert.AreEqual("run", actionArgument.Option.Names.First());
}
[TestMethod]
public void ShouldReturnSetOptions()
{
// arrange
string argString = "/Opt1 --opt3";
var parser = new CommandLineParser();
parser.ReadArgs(argString);
parser.RegisterOption("opt1");
parser.RegisterOption("opt2");
parser.RegisterOption("opt3");
// act
var opts = parser.SetOptions;
// assert
Assert.AreEqual(2, opts.Length);
Assert.AreEqual("opt1", opts.First().Names.First());
Assert.AreEqual("opt3", opts.Last().Names.First());
}
[TestMethod]
[ExpectedException(typeof(ArgumentNullException))]
public void ShouldThrowExceptionOnNullArgs()
{
string[] args = null;
var parser = new CommandLineParser();
// act
parser.Parse(args);
// assert - ArgumentNullException
Assert.Fail();
}
[TestMethod]
[ExpectedException(typeof(Exception))]
public void ShouldThrowExceptionOnMultipleAutocomplete()
{
// arrange
string[] args = ["/Opt:on"];
var parser = new CommandLineParser
{
IsCaseSensitive = true
};
parser.RegisterOption("Option1", 1);
parser.RegisterOption("Option2", 1);
// act
parser.Parse(args);
// assert - Exception
Assert.Fail();
}
[TestMethod]
[ExpectedException(typeof(Exception))]
public void ShouldThrowExceptionOnMissingOption()
{
// arrange
string[] args = ["/Option:on"];
var parser = new CommandLineParser
{
AutoCompleteOptions = false
};
parser.RegisterOption("Opt1", 1);
parser.RegisterOption("Opt2", 1);
// act
parser.Parse(args);
// assert - Exception
Assert.Fail();
}
[TestMethod]
[ExpectedException(typeof(Exception))]
public void ShouldTrhowExceptionOnDuplicateOption()
{
// arrange
string[] args = ["/Opt:on", "--opt=off"];
var parser = new CommandLineParser();
parser.RegisterOption("opt", 1).Single();
// act
parser.Parse(args);
// assert - Exception
Assert.Fail();
}
[TestMethod]
[ExpectedException(typeof(Exception))]
public void ShouldThrowExceptionOnMissingArgument()
{
// arrange
string[] args = ["/Option"];
var parser = new CommandLineParser();
parser.RegisterOption("option", 1);
// act
parser.Parse(args);
// assert - Exception
Assert.Fail();
}
[TestMethod]
[ExpectedException(typeof(Exception))]
public void ShouldThrowExceptionForMissingRequiredOption()
{
// arrange
string[] args = ["/opt"];
var parser = new CommandLineParser();
parser.RegisterOption("opt").Required();
parser.RegisterOption("foo").Required();
// act
parser.Parse(args);
// assert - Exception
Assert.Fail();
}
}
}

View File

@@ -0,0 +1,90 @@
using System;
using System.Collections.Generic;
using AMWD.Common.Cli;
using Microsoft.VisualStudio.TestTools.UnitTesting;
namespace UnitTests.Common.Cli
{
[TestClass]
public class EnumerableWalkerTests
{
private List<string> _list;
[TestInitialize]
public void Initialize()
{
_list = ["one", "two", "three", "four"];
}
[TestMethod]
[ExpectedException(typeof(ArgumentNullException))]
public void ShouldThrowExceptionOnNullReference()
{
// arrange
// act
_ = new EnumerableWalker<object>(null);
// assert - ArgumentNullException
Assert.Fail();
}
[TestMethod]
public void ShouldReturnEnumerator()
{
// arrange
var walker = new EnumerableWalker<string>(_list);
// act
var enumerator = walker.GetEnumerator();
// assert
Assert.IsNotNull(enumerator);
}
[TestMethod]
public void ShouldReturnGenericEnumerator()
{
// arrange
var walker = new EnumerableWalker<string>(_list);
// act
var enumerator = ((IEnumerable<string>)walker).GetEnumerator();
// assert
Assert.IsNotNull(enumerator);
}
[TestMethod]
public void ShouldReturnItems()
{
// arrange
var walker = new EnumerableWalker<string>(_list);
_ = walker.GetEnumerator();
string[] items = new string[_list.Count];
// act
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");
}
[TestMethod]
public void ShouldReturnDefaultWhenNothingLeft()
{
// arrange
var walker = new EnumerableWalker<string>(Array.Empty<string>());
_ = walker.GetEnumerator();
// act
string item = walker.GetNext();
// assert
Assert.AreEqual(default, item);
}
}
}

View File

@@ -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();

View File

@@ -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.";

View File

@@ -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" },
@@ -260,7 +260,7 @@ namespace UnitTests.Common.Extensions
// act
string topLevelString = jObj.GetValue<string>("stringValue");
decimal topLevelDecimal = jObj.GetValue<decimal>("decimalValue");
int subLevelInteger = jObj.GetValue<int>("object:integerValue");
int subLevelInteger = jObj.GetValue<int>("object:IntegerValue");
string subLevelString = jObj.GetValue<string>("object:stringValue");
string notExistingOnTopLevel = jObj.GetValue<string>("fancyValue");
@@ -288,7 +288,7 @@ namespace UnitTests.Common.Extensions
// act
string topLevelString = jObj.GetValue("stringValue", "Test String");
decimal topLevelDecimal = jObj.GetValue("decimalValue", 13.24m);
int subLevelInteger = jObj.GetValue("object:integerValue", 55);
int subLevelInteger = jObj.GetValue("object:IntegerValue", 55);
string subLevelString = jObj.GetValue("object:stringValue", "Yeah!");
string notExistingOnTopLevel = jObj.GetValue("fancyValue", "Party!");

View File

@@ -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);

View File

@@ -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("_");

View File

@@ -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;
}

View File

@@ -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;
}

View File

@@ -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
}
}

View File

@@ -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();

View File

@@ -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();

View File

@@ -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;
}
}

View File

@@ -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;
}
}

View File

@@ -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;
}
}
}
}

View File

@@ -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;