TestUtils.cs 1.7 KB

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