AbstractFileTests.cs 2.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  1. using Lua.IO;
  2. using Lua.Platforms;
  3. using Lua.Standard;
  4. using Lua.Tests.Helpers;
  5. namespace Lua.Tests;
  6. public class AbstractFileTests
  7. {
  8. class ReadOnlyFileSystem(Dictionary<string, string> dictionary) : NotImplementedExceptionFileSystemBase
  9. {
  10. public override ILuaStream Open(string path, LuaFileMode mode)
  11. {
  12. if (!dictionary.TryGetValue(path, out var value))
  13. {
  14. throw new FileNotFoundException($"File {path} not found");
  15. }
  16. if (mode != LuaFileMode.ReadText)
  17. throw new IOException($"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(LuaPlatform.Default with{FileSystem = fileSystem});
  27. state.OpenStandardLibraries();
  28. try
  29. {
  30. await state.DoStringAsync(
  31. """
  32. local lines = {}
  33. for line in io.lines("test.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(LuaPlatform.Default with{FileSystem = fileSystem});
  55. state.OpenStandardLibraries();
  56. await state.DoStringAsync(
  57. """
  58. local file = io.open("test.txt", "r")
  59. assert(file, "Failed to open file")
  60. local content = file:read("*a")
  61. assert(content == "Hello, World!", "Expected 'Hello, World!'")
  62. file:close()
  63. file = io.open("test2.txt", "r")
  64. assert(file == nil, "Expected file to be nil")
  65. """);
  66. }
  67. }