AbstractFileTests.cs 2.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182
  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. throw new IOException($"File {path} not opened in read mode");
  18. return new(ILuaStream.CreateFromMemory(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(new(
  27. fileSystem: fileSystem,
  28. osEnvironment: null!,
  29. standardIO: new ConsoleStandardIO(),
  30. timeProvider: TimeProvider.System
  31. ));
  32. state.OpenStandardLibraries();
  33. try
  34. {
  35. await state.DoStringAsync(
  36. """
  37. local lines = {}
  38. for line in io.lines("test.txt") do
  39. table.insert(lines, line)
  40. print(line)
  41. end
  42. assert(#lines == 3, "Expected 3 lines")
  43. assert(lines[1] == "line1", "Expected line1")
  44. assert(lines[2] == "line2", "Expected line2")
  45. assert(lines[3] == "line3", "Expected line3")
  46. """);
  47. }
  48. catch (Exception e)
  49. {
  50. Console.WriteLine(e);
  51. throw;
  52. }
  53. }
  54. [Test]
  55. public async Task ReadFileTest()
  56. {
  57. var fileContent = "Hello, World!";
  58. var fileSystem = new ReadOnlyFileSystem(new() { { "test.txt", fileContent } });
  59. var state = LuaState.Create(new(
  60. fileSystem: fileSystem,
  61. osEnvironment: null!,
  62. standardIO: new ConsoleStandardIO(),
  63. timeProvider: TimeProvider.System));
  64. state.OpenStandardLibraries();
  65. await state.DoStringAsync(
  66. """
  67. local file = io.open("test.txt", "r")
  68. assert(file, "Failed to open file")
  69. local content = file:read("*a")
  70. assert(content == "Hello, World!", "Expected 'Hello, World!'")
  71. file:close()
  72. file = io.open("test2.txt", "r")
  73. assert(file == nil, "Expected file to be nil")
  74. """);
  75. }
  76. }