2
0

TestUtils.cs 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950
  1. namespace MeloongCore.Tests;
  2. /// <summary>
  3. /// 所有测试的基类。
  4. /// 会初始化 MeloongCore 并重定向日志输出。
  5. /// </summary>
  6. public abstract class TestBase {
  7. public TestBase() {
  8. MeloongCore.Main.Init("MeloongCoreTest");
  9. Logger.Instance = new TestLogger();
  10. }
  11. private class TestLogger : BaseLogger {
  12. public override void HandleBehavior(string? rawMessage, string formattedMessage, LogBehavior behavior, Exception? ex)
  13. => TestContext.Current!.OutputWriter.WriteLine(formattedMessage);
  14. }
  15. }
  16. /// <summary>
  17. /// 用于带文件测试的基类。
  18. /// 会在极端路径下创建测试用的临时文件夹。
  19. /// </summary>
  20. public abstract class TestWithFolder : TestBase {
  21. /// <summary>
  22. /// 测试用的临时文件夹路径。
  23. /// 这是一个包含特殊字符的长路径,不以 \\?\ 开头,以 \ 结尾。
  24. /// </summary>
  25. public readonly string tempFolder;
  26. public TestWithFolder() : base() {
  27. tempFolder = Path.Combine(
  28. Path.GetTempPath(), "PCL", "Tests",
  29. $"{GetType().Name}-{Guid.NewGuid()}",
  30. "文件夹 Dir_!@#$%^&()_+={}[];',_",
  31. new string('X', 200), new string('X', 200)) + @"\";
  32. DirectoryUtils.Create(tempFolder);
  33. }
  34. /// <summary>
  35. /// 输出指定的测试用文件,返回文件路径。
  36. /// </summary>
  37. public string GetTestFile(string fileName) {
  38. var sourceFilePath = Path.Combine(Paths.Base, "TestFiles", GetType().Name.Replace("Test", ""), fileName);
  39. var distPath = Path.Combine(tempFolder, PathUtils.GetLastPart(sourceFilePath));
  40. FileUtils.Copy(sourceFilePath, distPath);
  41. return distPath;
  42. }
  43. }