AbstractFileTests.cs 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  1. using Lua.IO;
  2. using Lua.Standard;
  3. using Lua.Tests.Helpers;
  4. namespace Lua.Tests;
  5. public class AbstractFileTests
  6. {
  7. class ReadOnlyFileSystem(Dictionary<string, string> dictionary) : NotImplementedExceptionFileSystemBase
  8. {
  9. public override ILuaIOStream? Open(string path, LuaFileOpenMode mode, bool throwError)
  10. {
  11. if (!dictionary.TryGetValue(path, out var value))
  12. {
  13. if (!throwError) return null;
  14. throw new FileNotFoundException($"File {path} not found");
  15. }
  16. if (mode != LuaFileOpenMode.Read)
  17. throw new NotSupportedException($"File {path} not opened in read mode");
  18. return new ReadOnlyCharMemoryLuaIOStream(value.AsMemory());
  19. }
  20. }
  21. [Test]
  22. public async Task ReadLinesTest()
  23. {
  24. var fileContent = "line1\nline2\r\nline3";
  25. var fileSystem = new ReadOnlyFileSystem(new() { { "test.txt", fileContent } });
  26. var state = LuaState.Create();
  27. state.FileSystem = fileSystem;
  28. state.OpenStandardLibraries();
  29. try
  30. {
  31. await state.DoStringAsync(
  32. """
  33. local lines = {}
  34. for line in io.lines("test1.txt") do
  35. table.insert(lines, line)
  36. print(line)
  37. end
  38. assert(#lines == 3, "Expected 3 lines")
  39. assert(lines[1] == "line1", "Expected line1")
  40. assert(lines[2] == "line2", "Expected line2")
  41. assert(lines[3] == "line3", "Expected line3")
  42. """);
  43. }
  44. catch (Exception e)
  45. {
  46. Console.WriteLine(e);
  47. throw;
  48. }
  49. }
  50. [Test]
  51. public async Task ReadFileTest()
  52. {
  53. var fileContent = "Hello, World!";
  54. var fileSystem = new ReadOnlyFileSystem(new() { { "test.txt", fileContent } });
  55. var state = LuaState.Create();
  56. state.FileSystem = fileSystem;
  57. state.OpenStandardLibraries();
  58. await state.DoStringAsync(
  59. """
  60. local file = io.open("test.txt", "r")
  61. assert(file, "Failed to open file")
  62. local content = file:read("*a")
  63. assert(content == "Hello, World!", "Expected 'Hello, World!'")
  64. file:close()
  65. file = io.open("test2.txt", "r")
  66. assert(file == nil, "Expected file to be nil")
  67. """);
  68. }
  69. }