AbstractFileTests.cs 2.7 KB

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