2
0

AbstractFileTests.cs 2.3 KB

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