using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using System.Reflection; using System.Runtime.CompilerServices; using System.Threading.Tasks; using XFEExtension.ArrayExtension; using XFEExtension.AttributeExtension; using XFEExtension.ReflectionExtension; using XFEExtension.StringExtension; using XFEExtension.TaskExtension; namespace XFEExtension { #region 异常 /// /// XFEExtension的异常 /// public class XFEExtensionException : Exception { /// /// XFEExtension的异常 /// /// internal XFEExtensionException(string message) : base(message) { } /// /// XFEExtension的异常 /// /// /// internal XFEExtensionException(string message, Exception innerException) : base(message, innerException) { } } /// /// XFEJson转换的异常 /// public class XFEJsonTransformException : XFEExtensionException { /// /// XFEJson转换的异常 /// /// internal XFEJsonTransformException(string message) : base(message) { } /// /// XFEJson转换的异常 /// /// /// internal XFEJsonTransformException(string message, Exception innerException) : base(message, innerException) { } } /// /// XFEChatGPT的异常 /// public class XFEChatGPTException : XFEExtensionException { /// /// XFEChatGPT的异常 /// /// internal XFEChatGPTException(string message) : base(message) { } internal XFEChatGPTException(string message, Exception innerException) : base(message, innerException) { } } /// /// XFE网络通信的异常 /// public class XFECyberCommException : XFEExtensionException { /// /// XFE网络通信的异常 /// /// internal XFECyberCommException(string message) : base(message) { } internal XFECyberCommException(string message, Exception innerException) : base(message, innerException) { } } /// /// XFE邮件的异常 /// public class XFEMailException : XFEExtensionException { internal XFEMailException(string message) : base(message) { } internal XFEMailException(string message, Exception innerException) : base(message, innerException) { } } /// /// XFE字典的异常 /// public class XFEDictionaryException : XFEExtensionException { internal XFEDictionaryException(string message) : base(message) { } internal XFEDictionaryException(string message, Exception innerException) : base(message, innerException) { } } #endregion /// /// XFEExtension编写 /// public abstract class XFECode { private static int CTimeCounter = 0; private static bool CurrentMethodIsAsserted = false; private static string CurrentAssertMessage = string.Empty; #region 暂停 /// /// 暂停 /// /// 是否显示提示 protected static void Pause(bool ShowText = true) { if (ShowText) { Console.WriteLine("按任意键继续..."); } Console.ReadKey(); } /// /// 暂停 /// /// 显示的文字 protected static void Pause(string ShowText) { Console.WriteLine(ShowText); Console.ReadKey(); } /// /// 暂停,按下指定按键继续 /// /// 指定的按键 protected static void Pause(ConsoleKey consoleKey) { Console.WriteLine($"按 {consoleKey} 键继续"); while (Console.ReadKey().Key != consoleKey) ; } /// /// 暂停,按下指定按键继续 /// /// 指定的按键 /// 显示的文字 protected static void Pause(ConsoleKey consoleKey, string ShowText) { Console.WriteLine(ShowText); while (Console.ReadKey().Key != consoleKey) ; } #endregion /// /// 并行循环指定次数 /// /// 执行的操作 /// 循环次数 /// 自动等待所有线程执行完毕 protected static async Task> Circle(Action action, int count, bool autoWaitAll = false) { var taskList = new List(); for (int i = 0; i < count; i++) { taskList.Add(action.StartNewTask()); } if (autoWaitAll) await Task.WhenAll(taskList); return taskList; } /// /// 并行循环指定次数 /// /// 执行的操作 /// 循环次数 protected static async void CircleOrderly(Action action, int count) { for (int i = 0; i < count; i++) { await action.StartNewTask(); } } /// /// 计算一段代码执行所需时间 /// /// /// 自动输出 /// 该次计时标识名 /// public static TimeSpan CTime(Action action, bool autoOutPut = true, string timerName = "无标识名计时器") { var timeCounter = new Stopwatch(); timeCounter.Start(); action?.Invoke(); timeCounter.Stop(); CTimeCounter++; var elapsedTime = timeCounter.Elapsed; if (autoOutPut) if (elapsedTime.TotalHours >= 1) Console.WriteLine($"标识名:{timerName}\t执行批次:{CTimeCounter}\t执行时间:{elapsedTime}"); else if (elapsedTime.TotalMinutes >= 1) Console.WriteLine($"标识名:{timerName}\t执行批次:{CTimeCounter}\t执行时间: {Math.Floor(elapsedTime.TotalMinutes)} 分 {elapsedTime.Seconds} 秒"); else if (elapsedTime.TotalSeconds >= 1) Console.WriteLine($"标识名:{timerName}\t执行批次:{CTimeCounter}\t执行时间: {elapsedTime.TotalSeconds:F3} 秒"); else if (elapsedTime.TotalMilliseconds >= 1) Console.WriteLine($"标识名:{timerName}\t执行批次:{CTimeCounter}\t执行时间: {elapsedTime.TotalMilliseconds:F3} 毫秒"); else Console.WriteLine($"标识名:{timerName}\t执行批次:{CTimeCounter}\t执行时间: {elapsedTime.TotalMilliseconds * 1000:F3} 纳秒"); return elapsedTime; } /// /// 计算一段代码执行所需时间 /// /// /// 自动输出 /// 该次计时标识名 /// public static async Task CTimeAsync(Func action, bool autoOutPut = true, string timerName = "无标识名计时器") { var timeCounter = new Stopwatch(); timeCounter.Start(); await action?.Invoke(); timeCounter.Stop(); CTimeCounter++; var elapsedTime = timeCounter.Elapsed; if (autoOutPut) if (elapsedTime.TotalHours >= 1) Console.WriteLine($"标识名:{timerName}\t执行批次:{CTimeCounter}\t执行时间:{elapsedTime}"); else if (elapsedTime.TotalMinutes >= 1) Console.WriteLine($"标识名:{timerName}\t执行批次:{CTimeCounter}\t执行时间: {Math.Floor(elapsedTime.TotalMinutes)} 分 {elapsedTime.Seconds} 秒"); else if (elapsedTime.TotalSeconds >= 1) Console.WriteLine($"标识名:{timerName}\t执行批次:{CTimeCounter}\t执行时间: {elapsedTime.TotalSeconds:F3} 秒"); else if (elapsedTime.TotalMilliseconds >= 1) Console.WriteLine($"标识名:{timerName}\t执行批次:{CTimeCounter}\t执行时间: {elapsedTime.TotalMilliseconds:F3} 毫秒"); else Console.WriteLine($"标识名:{timerName}\t执行批次:{CTimeCounter}\t执行时间: {elapsedTime.TotalMilliseconds * 1000:F3} 纳秒"); return elapsedTime; } /// /// 计算一段代码执行所需时间 /// /// /// protected static async Task RunTest() { var isFirstClass = true; var subClasses = Assembly.GetEntryAssembly().GetTypes() .Where(type => type.IsSubclassOf(typeof(XFECode))); foreach (var subClass in subClasses) { var mainColor = ConsoleColor.Blue; var classColor = ConsoleColor.Green; var classBorderColor = ConsoleColor.DarkGreen; var methodColor = ConsoleColor.Yellow; var methodBorderColor = ConsoleColor.DarkYellow; var successColor = ConsoleColor.Green; var failColor = ConsoleColor.Red; var timeColor = ConsoleColor.Cyan; var counterColor = ConsoleColor.Gray; if (subClass.GetCustomAttributes(typeof(TestThemeAttribute), false).FirstOrDefault() is TestThemeAttribute themeAttribute) { mainColor = themeAttribute.MainColor; classColor = themeAttribute.ClassColor; classBorderColor = themeAttribute.ClassBorderColor; methodColor = themeAttribute.MethodColor; methodBorderColor = themeAttribute.MethodBorderColor; successColor = themeAttribute.SuccessColor; failColor = themeAttribute.FailColor; timeColor = themeAttribute.TimeColor; counterColor = themeAttribute.CounterColor; } var singleRunMethods = subClass.GetMethods(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.Static).Where(m => m.IsDefined(typeof(SMTestAttribute))); #region 静态测试 var isFirstStaticMethod = true; foreach (var method in singleRunMethods) { var attributes = method.GetCustomAttributes(typeof(SMTestAttribute)); foreach (var likeAttribute in attributes) { if (likeAttribute is SMTestAttribute attribute) { string timerName = "方法名:" + method.Name; if (likeAttribute is SMNTestAttribute subAttribute) { timerName = "标识名:" + subAttribute.TimerName; } if (attribute is SMNRTestAttribute resultAttribute) { timerName = "标识名:" + resultAttribute.TimerName; } object[] paramsForMethod = null; if (attribute.Params != null) { paramsForMethod = attribute.Params; } else { paramsForMethod = method.GetDefaultParameters(); } var timeCounter = new Stopwatch(); var selfTimeCounter = new Stopwatch(); var elapsedTime = new TimeSpan(); var isSuccessful = true; var isResultEqual = true; var failedMessage = string.Empty; Console.BackgroundColor = ConsoleColor.Black; Console.ForegroundColor = methodBorderColor; if (isFirstStaticMethod) { isFirstStaticMethod = false; } else { Console.WriteLine("\n\n\n\n\n"); } var borderCount = (Console.BufferWidth - timerName.DisplayLength()) / 2; if (timerName != null) { for (int i = 0; i < borderCount; i++) { Console.Write("="); } if ((Console.BufferWidth - timerName.DisplayLength()) % 2 == 1) Console.Write("="); Console.ForegroundColor = mainColor; Console.Write(timerName.Substring(0, 4)); Console.ForegroundColor = methodColor; Console.Write(timerName.Substring(4)); Console.ForegroundColor = methodBorderColor; for (int i = 0; i < borderCount; i++) { Console.Write("="); } } else { for (int i = 0; i < Console.BufferWidth; i++) { Console.Write("="); } } Console.WriteLine("\n"); Console.BackgroundColor = mainColor; Console.ForegroundColor = ConsoleColor.Black; Console.Write("开始执行"); Console.BackgroundColor = ConsoleColor.Black; Console.ForegroundColor = mainColor; Console.Write($"\t方法:"); Console.ForegroundColor = methodColor; Console.Write(method.Name); Console.ForegroundColor = mainColor; Console.Write($"\t类:"); Console.ForegroundColor = classColor; Console.WriteLine($"{subClass.Name}\n"); Console.ResetColor(); selfTimeCounter.Start(); selfTimeCounter.Stop(); try { CurrentMethodIsAsserted = false; if (method.ReturnType == typeof(Task)) { timeCounter.Start(); await (Task)method.Invoke(Activator.CreateInstance(subClass), paramsForMethod); timeCounter.Stop(); } else { timeCounter.Start(); var result = method.Invoke(Activator.CreateInstance(subClass), paramsForMethod); timeCounter.Stop(); if (attribute is SMRTestAttribute resultAttribute2) { isResultEqual = result.Equals(resultAttribute2.ReturnValue); if (!isResultEqual) { isSuccessful = false; failedMessage = $"预期结果:{resultAttribute2.ReturnValue}\t实际结果:{result}"; } } } if (CurrentMethodIsAsserted) { isSuccessful = false; if (failedMessage == string.Empty) failedMessage = CurrentAssertMessage; else failedMessage += $"\n{CurrentAssertMessage}"; CurrentMethodIsAsserted = false; CurrentAssertMessage = string.Empty; } } catch (Exception e) { isSuccessful = false; failedMessage = e.Message; } elapsedTime = timeCounter.Elapsed - selfTimeCounter.Elapsed; CTimeCounter++; Console.BackgroundColor = ConsoleColor.Black; Console.WriteLine(); Console.BackgroundColor = mainColor; Console.ForegroundColor = ConsoleColor.Black; Console.Write("执行完成"); Console.BackgroundColor = ConsoleColor.Black; Console.ForegroundColor = mainColor; Console.Write("\t执行批次:"); Console.ForegroundColor = counterColor; Console.Write(CTimeCounter); Console.ForegroundColor = mainColor; Console.Write("\t执行时间:"); Console.ForegroundColor = timeColor; if (elapsedTime.TotalHours >= 1) Console.WriteLine(elapsedTime); else if (elapsedTime.TotalMinutes >= 1) Console.WriteLine($"{elapsedTime.Minutes} 分 {elapsedTime.Seconds} 秒 {elapsedTime.Milliseconds} 毫秒"); else if (elapsedTime.TotalSeconds >= 1) Console.WriteLine($"{elapsedTime.TotalSeconds:F3} 秒"); else if (elapsedTime.TotalMilliseconds >= 1) Console.WriteLine($"{elapsedTime.TotalMilliseconds:F3} 毫秒"); else Console.WriteLine($"{elapsedTime.TotalMilliseconds * 1000:F2} 纳秒"); Console.ForegroundColor = ConsoleColor.Black; Console.WriteLine(); if (isSuccessful && isResultEqual) { Console.BackgroundColor = successColor; Console.Write("测试通过"); } else { Console.BackgroundColor = failColor; Console.Write("测试失败"); Console.BackgroundColor = ConsoleColor.Black; Console.ForegroundColor = failColor; Console.WriteLine($"\t失败原因:{failedMessage}"); } Console.BackgroundColor = ConsoleColor.Black; Console.Write("\n"); Console.ForegroundColor = methodBorderColor; Console.Write("\n"); for (int i = 0; i < Console.BufferWidth; i++) { Console.Write("="); } Console.ResetColor(); Console.WriteLine("\n"); Console.WriteLine("\n"); } } } #endregion var classAttributes = subClass.GetCustomAttributes(typeof(CTestAttribute)); var classRunMethods = subClass.GetMethods(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.Static).Where(m => m.IsDefined(typeof(MTestAttribute))); foreach (var classAttribute in classAttributes.Cast()) { var isFirstMethod = true; var failedList = new List(); object classInstance = classAttribute.Params is null; if (classAttribute.Params is null) { classInstance = subClass.GetConstructor(BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Instance, null, new Type[0], null).Invoke(classAttribute.Params); } else { classInstance = subClass.GetConstructor(BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Instance, null, classAttribute.Params.GetTypes(), null).Invoke(classAttribute.Params); } var setUpAttribute = subClass.GetAttribute(); if (setUpAttribute != null) { var setUpMethod = subClass.GetMethods(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.Static).Where(m => m.IsDefined(typeof(TSetUpAttribute))).FirstOrDefault(); if (setUpMethod != null) { setUpMethod.Invoke(classInstance, setUpMethod.GetDefaultParameters()); } } string classOtherName = "类名:" + subClass.Name; if (classAttribute is CNTestAttribute subClassAttribute) { classOtherName = "标识名:" + subClassAttribute.ClassOtherName; } var classTimeCounter = new Stopwatch(); Console.BackgroundColor = ConsoleColor.Black; Console.ForegroundColor = classBorderColor; if (isFirstClass) { isFirstClass = false; } else { Console.WriteLine("\n\n\n\n\n\n\n\n"); } var borderCount = (Console.BufferWidth - classOtherName.DisplayLength()) / 2; if (classOtherName != null) { for (int i = 0; i < borderCount; i++) { Console.Write("="); } if ((Console.BufferWidth - classOtherName.DisplayLength()) % 2 == 1) Console.Write("="); Console.ForegroundColor = mainColor; if (classOtherName.Substring(0, 4) == "标识名:") { Console.Write(classOtherName.Substring(0, 4)); Console.ForegroundColor = classColor; Console.Write(classOtherName.Substring(4)); } else { Console.Write(classOtherName.Substring(0, 3)); Console.ForegroundColor = classColor; Console.Write(classOtherName.Substring(3)); } Console.ForegroundColor = classBorderColor; for (int i = 0; i < borderCount; i++) { Console.Write("="); } } else { for (int i = 0; i < Console.BufferWidth; i++) { Console.Write("="); } } Console.WriteLine("\n"); Console.BackgroundColor = mainColor; Console.ForegroundColor = ConsoleColor.Black; Console.Write("开始执行"); Console.BackgroundColor = ConsoleColor.Black; Console.ForegroundColor = mainColor; Console.Write("\t类名:"); Console.ForegroundColor = classColor; Console.WriteLine($"{subClass.Name}\n\n\n\n\n"); Console.ResetColor(); classTimeCounter.Start(); foreach (var method in classRunMethods) { var attributes = method.GetCustomAttributes(typeof(MTestAttribute)); foreach (MTestAttribute attribute in attributes) { if (attribute is MTestAttribute methodAttribute) { string methodOtherName = "方法名:" + method.Name; if (attribute is MNTestAttribute subAttribute) { methodOtherName = "标识名:" + subAttribute.MethodOtherName; } if (attribute is MNRTestAttribute resultAttribute) { methodOtherName = "标识名:" + resultAttribute.MethodOtherName; } object[] paramsForMethod = null; if (attribute.Params != null) { paramsForMethod = attribute.Params; } else { paramsForMethod = method.GetDefaultParameters(); } var timeCounter = new Stopwatch(); var selfTimeCounter = new Stopwatch(); var elapsedTime = new TimeSpan(); var isSuccessful = true; var isResultEqual = true; var failedMessage = string.Empty; Console.BackgroundColor = ConsoleColor.Black; Console.ForegroundColor = methodBorderColor; if (isFirstMethod) { isFirstMethod = false; } else { Console.WriteLine("\n\n\n\n\n"); } borderCount = (Console.BufferWidth - methodOtherName.DisplayLength()) / 2; if (methodOtherName != null) { for (int i = 0; i < borderCount; i++) { Console.Write("="); } if ((Console.BufferWidth - methodOtherName.DisplayLength()) % 2 == 1) Console.Write("="); Console.ForegroundColor = mainColor; Console.Write(methodOtherName.Substring(0, 4)); Console.ForegroundColor = methodColor; Console.Write(methodOtherName.Substring(4)); Console.ForegroundColor = methodBorderColor; for (int i = 0; i < borderCount; i++) { Console.Write("="); } } else { for (int i = 0; i < Console.BufferWidth; i++) { Console.Write("="); } } Console.WriteLine("\n"); Console.BackgroundColor = mainColor; Console.ForegroundColor = ConsoleColor.Black; Console.Write("开始执行"); Console.BackgroundColor = ConsoleColor.Black; Console.ForegroundColor = mainColor; Console.Write($"\t方法:"); Console.ForegroundColor = methodColor; Console.Write(method.Name); Console.ForegroundColor = mainColor; Console.Write($"\t类:"); Console.ForegroundColor = classColor; Console.WriteLine($"{subClass.Name}\n"); Console.ResetColor(); selfTimeCounter.Start(); selfTimeCounter.Stop(); try { CurrentMethodIsAsserted = false; if (method.ReturnType == typeof(Task)) { timeCounter.Start(); await (Task)method.Invoke(classInstance, paramsForMethod); timeCounter.Stop(); } else { timeCounter.Start(); var result = method.Invoke(classInstance, paramsForMethod); timeCounter.Stop(); if (methodAttribute is MRTestAttribute resultAttribute2) { isResultEqual = result.Equals(resultAttribute2.ReturnValue); if (!isResultEqual) { isSuccessful = false; failedMessage = $"预期结果:{resultAttribute2.ReturnValue}\t实际结果:{result}"; } } } if (CurrentMethodIsAsserted) { isSuccessful = false; if (failedMessage == string.Empty) failedMessage = CurrentAssertMessage; else failedMessage += $"\n{CurrentAssertMessage}"; CurrentMethodIsAsserted = false; CurrentAssertMessage = string.Empty; } } catch (Exception e) { isSuccessful = false; failedMessage = e.Message; } elapsedTime = timeCounter.Elapsed - selfTimeCounter.Elapsed; CTimeCounter++; Console.BackgroundColor = ConsoleColor.Black; Console.WriteLine(); Console.BackgroundColor = mainColor; Console.ForegroundColor = ConsoleColor.Black; Console.Write("执行完成"); Console.BackgroundColor = ConsoleColor.Black; Console.ForegroundColor = mainColor; Console.Write("\t执行批次:"); Console.ForegroundColor = counterColor; Console.Write(CTimeCounter); Console.ForegroundColor = mainColor; Console.Write("\t执行时间:"); Console.ForegroundColor = timeColor; if (elapsedTime.TotalHours >= 1) Console.WriteLine(elapsedTime); else if (elapsedTime.TotalMinutes >= 1) Console.WriteLine($"{elapsedTime.Minutes} 分 {elapsedTime.Seconds} 秒 {elapsedTime.Milliseconds} 毫秒"); else if (elapsedTime.TotalSeconds >= 1) Console.WriteLine($"{elapsedTime.TotalSeconds:F3} 秒"); else if (elapsedTime.TotalMilliseconds >= 1) Console.WriteLine($"{elapsedTime.TotalMilliseconds:F3} 毫秒"); else Console.WriteLine($"{elapsedTime.TotalMilliseconds * 1000:F2} 纳秒"); Console.ForegroundColor = ConsoleColor.Black; Console.WriteLine(); if (isSuccessful && isResultEqual) { Console.BackgroundColor = successColor; Console.Write("测试通过"); } else { Console.BackgroundColor = failColor; Console.Write("测试失败"); Console.BackgroundColor = ConsoleColor.Black; Console.ForegroundColor = failColor; Console.WriteLine($"\t失败原因:{failedMessage}"); failedList.Add(new MethodAndCounter(method, CTimeCounter, failedMessage)); } Console.BackgroundColor = ConsoleColor.Black; Console.Write("\n"); Console.ForegroundColor = methodBorderColor; Console.Write("\n"); for (int i = 0; i < Console.BufferWidth; i++) { Console.Write("="); } Console.ResetColor(); } } } classTimeCounter.Stop(); CTimeCounter++; Console.WriteLine("\n\n\n\n\n"); Console.BackgroundColor = mainColor; Console.ForegroundColor = ConsoleColor.Black; Console.Write("执行完成"); Console.BackgroundColor = ConsoleColor.Black; Console.ForegroundColor = mainColor; Console.Write("\t执行批次:"); Console.ForegroundColor = counterColor; Console.Write(CTimeCounter); Console.ForegroundColor = mainColor; Console.Write("\t执行时间:"); Console.ForegroundColor = timeColor; if (classTimeCounter.Elapsed.TotalHours >= 1) Console.WriteLine(classTimeCounter.Elapsed); else if (classTimeCounter.Elapsed.TotalMinutes >= 1) Console.WriteLine($"{classTimeCounter.Elapsed.Minutes} 分 {classTimeCounter.Elapsed.Seconds} 秒 {classTimeCounter.Elapsed.Milliseconds} 毫秒"); else if (classTimeCounter.Elapsed.TotalSeconds >= 1) Console.WriteLine($"{classTimeCounter.Elapsed.TotalSeconds:F3} 秒"); else if (classTimeCounter.Elapsed.TotalMilliseconds >= 1) Console.WriteLine($"{classTimeCounter.Elapsed.TotalMilliseconds:F3} 毫秒"); else Console.WriteLine($"{classTimeCounter.Elapsed.TotalMilliseconds * 1000:F2} 纳秒"); Console.ForegroundColor = ConsoleColor.Black; Console.WriteLine(); if (failedList.Count == 0) { Console.BackgroundColor = successColor; Console.Write("测试通过"); Console.BackgroundColor = ConsoleColor.Black; Console.WriteLine(); } else { Console.BackgroundColor = failColor; Console.Write("测试失败"); Console.BackgroundColor = ConsoleColor.Black; Console.ForegroundColor = failColor; Console.WriteLine("\t未通过的方法:"); foreach (var failedMethod in failedList) { Console.ForegroundColor = mainColor; Console.Write("\t\t方法名:"); Console.ForegroundColor = methodColor; Console.Write(failedMethod.Method.Name); Console.ForegroundColor = mainColor; Console.Write("\t执行批次:"); Console.ForegroundColor = counterColor; Console.Write(failedMethod.Counter); Console.ForegroundColor = mainColor; Console.Write("\t失败原因:"); Console.ForegroundColor = failColor; Console.WriteLine(failedMethod.FailMessage); } } Console.BackgroundColor = ConsoleColor.Black; Console.ForegroundColor = classBorderColor; Console.Write("\n"); for (int i = 0; i < Console.BufferWidth; i++) { Console.Write("="); } Console.ResetColor(); } } } /// /// 断言:判断条件为真 /// /// 判断条件 protected static bool Assert(bool condition) { if (!condition) { CurrentMethodIsAsserted = true; CurrentAssertMessage = "断言失败:期望为真,实际为假"; return false; } return true; } /// /// 断言:判断条件为真 /// /// 判断条件 /// 消息 protected static bool Assert(bool condition, string message) { if (!condition) { CurrentMethodIsAsserted = true; CurrentAssertMessage = message; return false; } return true; } /// /// 断言:判断条件为假 /// /// 判断条件 protected static bool AssertF(bool condition) { if (condition) { CurrentMethodIsAsserted = true; CurrentAssertMessage = "断言失败:期望为假,实际为真"; return false; } return true; } /// /// 断言:判断条件为假 /// /// 判断条件 /// 消息 protected static bool AssertF(bool condition, string message) { if (condition) { CurrentMethodIsAsserted = true; CurrentAssertMessage = message; return false; } return true; } /// /// 断言:判断两个值是否相等 /// /// 值的类型 /// 期望值 /// 实际值 protected static bool AssertE(T expected, T actual) { var result = !EqualityComparer.Default.Equals(expected, actual); if (result) { CurrentMethodIsAsserted = true; CurrentAssertMessage = $"断言失败:期望 {expected},实际 {actual}"; return false; } return true; } /// /// 断言:判断两个值是否相等 /// /// 值的类型 /// 期望值 /// 实际值 /// 消息 protected static bool AssertE(T expected, T actual, string message) { var result = !EqualityComparer.Default.Equals(expected, actual); if (result) { CurrentMethodIsAsserted = true; CurrentAssertMessage = message; return false; } return true; } static XFECode() { new Action(async () => await RunTest()).StartNewTask(); } } #region 特性 /// /// 测试颜色主题 /// [AttributeUsage(AttributeTargets.Class)] public sealed class TestThemeAttribute : Attribute { /// /// 主色 /// public ConsoleColor MainColor { get; set; } /// /// 类颜色 /// public ConsoleColor ClassColor { get; set; } /// /// 类边框颜色 /// public ConsoleColor ClassBorderColor { get; set; } /// /// 方法颜色 /// public ConsoleColor MethodColor { get; set; } /// /// 方法边框颜色 /// public ConsoleColor MethodBorderColor { get; set; } /// /// 成功颜色 /// public ConsoleColor SuccessColor { get; set; } /// /// 失败颜色 /// public ConsoleColor FailColor { get; set; } /// /// 时间颜色 /// public ConsoleColor TimeColor { get; set; } /// /// 计数器颜色 /// public ConsoleColor CounterColor { get; set; } /// /// 测试颜色主题 /// /// 主色 /// 类颜色 /// 类边框颜色 /// 方法颜色 /// 方法边框颜色 /// 成功颜色 /// 失败颜色 /// 时间颜色 /// 计数器颜色 public TestThemeAttribute(ConsoleColor mainColor = ConsoleColor.Blue, ConsoleColor classColor = ConsoleColor.Green, ConsoleColor classBorderColor = ConsoleColor.DarkGreen, ConsoleColor methodColor = ConsoleColor.Yellow, ConsoleColor methodBorderColor = ConsoleColor.DarkYellow, ConsoleColor successColor = ConsoleColor.Green, ConsoleColor failColor = ConsoleColor.Red, ConsoleColor timeColor = ConsoleColor.Cyan, ConsoleColor counterColor = ConsoleColor.Gray) { MainColor = mainColor; ClassColor = classColor; ClassBorderColor = classBorderColor; MethodColor = methodColor; MethodBorderColor = methodBorderColor; SuccessColor = successColor; FailColor = failColor; TimeColor = timeColor; CounterColor = counterColor; } } /// /// 测试特性基类 /// [AttributeUsage(AttributeTargets.Assembly, AllowMultiple = true)] public class XFETestAttributeBase : Attribute { /// /// 参数 /// public object[] Params { get; set; } } /// /// 用于计时的特性 /// [AttributeUsage(AttributeTargets.Method, AllowMultiple = true)] public class SMTestAttribute : XFETestAttributeBase { /// /// 计算执行一段代码所需时间 /// /// 传参 public SMTestAttribute(params object[] values) { Params = values; } /// /// 计算执行一段代码所需时间 /// public SMTestAttribute() { } } /// /// 用于计时的特性,可自定义名称 /// [AttributeUsage(AttributeTargets.Method, AllowMultiple = true)] public sealed class SMNTestAttribute : SMTestAttribute { /// /// 该次计时标识名 /// public string TimerName { get; set; } /// /// 计算执行一段代码所需时间 /// /// 计时器名称 /// 传参 public SMNTestAttribute(string timerName, params object[] values) { TimerName = timerName; Params = values; } /// /// 计算执行一段代码所需时间 /// public SMNTestAttribute(string timerName) { TimerName = timerName; } } /// /// 用于计时的特性,可绑定返回值 /// [AttributeUsage(AttributeTargets.Method, AllowMultiple = true)] public class SMRTestAttribute : SMTestAttribute { /// /// 返回值 /// public object ReturnValue { get; set; } /// /// 计算执行一段代码所需时间 /// /// 传参 public SMRTestAttribute(params object[] valuesAndResult) { ReturnValue = valuesAndResult[valuesAndResult.Length - 1]; Params = valuesAndResult.Take(valuesAndResult.Length - 1).ToArray(); } /// /// 计算执行一段代码所需时间 /// public SMRTestAttribute() { } } /// /// 用于计时的特性,可自定义名称和返回值 /// [AttributeUsage(AttributeTargets.Method, AllowMultiple = true)] public sealed class SMNRTestAttribute : SMRTestAttribute { /// /// 该次计时标识名 /// public string TimerName { get; set; } /// /// 计算执行一段代码所需时间 /// /// 计时器名称 /// 传参 public SMNRTestAttribute(string timerName, params object[] valuesAndResult) { TimerName = timerName; ReturnValue = valuesAndResult[valuesAndResult.Length - 1]; Params = valuesAndResult.Take(valuesAndResult.Length - 1).ToArray(); } /// /// 计算执行一段代码所需时间 /// public SMNRTestAttribute() { } } /// /// 方法测试 /// [AttributeUsage(AttributeTargets.Method, AllowMultiple = true)] public class MTestAttribute : XFETestAttributeBase { /// /// 方法测试 /// /// 传参 public MTestAttribute(params object[] values) { Params = values; } /// /// 方法测试 /// public MTestAttribute() { } } /// /// 方法测试,可自定义名称 /// [AttributeUsage(AttributeTargets.Method, AllowMultiple = true)] public sealed class MNTestAttribute : MTestAttribute { /// /// 方法别名 /// public string MethodOtherName { get; set; } /// /// 方法测试 /// /// 方法别名 /// 传参 public MNTestAttribute(string methodOtherName, params object[] values) { MethodOtherName = methodOtherName; Params = values; } /// /// 方法测试 /// /// 方法别名 public MNTestAttribute(string methodOtherName) { MethodOtherName = methodOtherName; } /// /// 方法测试 /// public MNTestAttribute() { } } /// /// 方法测试,可自定义返回值 /// [AttributeUsage(AttributeTargets.Method, AllowMultiple = true)] public class MRTestAttribute : MTestAttribute { /// /// 返回值 /// public object ReturnValue { get; set; } /// /// 方法测试 /// /// 传参 public MRTestAttribute(params object[] valuesAndResult) { ReturnValue = valuesAndResult[valuesAndResult.Length - 1]; Params = valuesAndResult.Take(valuesAndResult.Length - 1).ToArray(); } /// /// 方法测试 /// public MRTestAttribute() { } } /// /// 方法测试,可自定义名称和返回值 /// [AttributeUsage(AttributeTargets.Method, AllowMultiple = true)] public sealed class MNRTestAttribute : MRTestAttribute { /// /// 方法别名 /// public string MethodOtherName { get; set; } /// /// 方法测试 /// /// 方法别名 /// 传参 public MNRTestAttribute(string methodOtherName, params object[] valuesAndResult) { MethodOtherName = methodOtherName; ReturnValue = valuesAndResult[valuesAndResult.Length - 1]; Params = valuesAndResult.Take(valuesAndResult.Length - 1).ToArray(); } /// /// 方法测试 /// public MNRTestAttribute() { } } /// /// 类测试 /// [AttributeUsage(AttributeTargets.Class, AllowMultiple = true)] public class CTestAttribute : XFETestAttributeBase { /// /// 类测试 /// /// 创建类时构造方法的传参 public CTestAttribute(params object[] values) { Params = values; } /// /// 类测试 /// public CTestAttribute() { } } /// /// 类测试 /// [AttributeUsage(AttributeTargets.Class, AllowMultiple = true)] public sealed class CNTestAttribute : CTestAttribute { /// /// 类别名 /// public string ClassOtherName { get; set; } /// /// 类测试 /// /// 创建类时构造方法的传参 /// 类别名 public CNTestAttribute(string classOtherName, params object[] values) { Params = values; ClassOtherName = classOtherName; } } /// /// 用于标记测试类初始函数的特性 /// [AttributeUsage(AttributeTargets.Method)] public sealed class TSetUpAttribute : XFETestAttributeBase { /// /// 用于标记测试类构造函数的特性 /// /// public TSetUpAttribute(params object[] values) { Params = values; } } #endregion /// /// 对代码整体书写习惯的拓展 /// public static class XFEExtension { /// /// 使得计时器可以直接调用(单位:秒) /// /// /// public static TaskAwaiter GetAwaiter(this int waitTime) => Task.Delay(TimeSpan.FromSeconds(waitTime)).GetAwaiter(); /// /// 使得计时器可以直接调用(单位:秒) /// /// /// public static TaskAwaiter GetAwaiter(this double waitTime) => Task.Delay(TimeSpan.FromSeconds(waitTime)).GetAwaiter(); } class MethodAndCounter { public MethodInfo Method { get; set; } public int Counter { get; set; } public string FailMessage { get; set; } public MethodAndCounter(MethodInfo method, int counter, string failMessage) { Method = method; Counter = counter; FailMessage = failMessage; } } }