From f3798bfb639192d50831e39a91c3f93a27b3f048 Mon Sep 17 00:00:00 2001 From: JakobDev Date: Mon, 10 Jun 2019 15:31:38 +0200 Subject: [PATCH] Improve rename.lua's argument validation --- .../computercraft/lua/rom/programs/rename.lua | 9 ++++- .../test-rom/spec/programs/rename_spec.lua | 40 +++++++++++++++++++ 2 files changed, 48 insertions(+), 1 deletion(-) create mode 100644 src/test/resources/test-rom/spec/programs/rename_spec.lua diff --git a/src/main/resources/assets/computercraft/lua/rom/programs/rename.lua b/src/main/resources/assets/computercraft/lua/rom/programs/rename.lua index f22561c26..4583adf62 100644 --- a/src/main/resources/assets/computercraft/lua/rom/programs/rename.lua +++ b/src/main/resources/assets/computercraft/lua/rom/programs/rename.lua @@ -7,8 +7,15 @@ end local sSource = shell.resolve( tArgs[1] ) local sDest = shell.resolve( tArgs[2] ) -if fs.exists( sDest ) then +if not fs.exists( sSource ) then + printError( "No matching files" ) + return +elseif fs.exists( sDest ) then printError( "Destination exists" ) + return +elseif fs.isReadOnly( sDest ) then + printError( "Destination is read-only" ) + return end fs.move( sSource, sDest ) diff --git a/src/test/resources/test-rom/spec/programs/rename_spec.lua b/src/test/resources/test-rom/spec/programs/rename_spec.lua new file mode 100644 index 000000000..2ab955dab --- /dev/null +++ b/src/test/resources/test-rom/spec/programs/rename_spec.lua @@ -0,0 +1,40 @@ +local capture = require "test_helpers".capture_program + +describe("The rename program", function() + local function touch(file) + io.open(file, "w"):close() + end + + it("can rename a file", function() + touch("/test-files/rename/a.txt") + + shell.run("rename /test-files/rename/a.txt /test-files/rename/b.txt") + + expect(fs.exists("/test-files/rename/a.txt")):eq(false) + expect(fs.exists("/test-files/rename/b.txt")):eq(true) + end) + + it("fails when renaming a file which doesn't exist", function() + expect(capture(stub, "rename nothing destination")) + :matches { ok = true, output = "", error = "No matching files\n" } + end) + + it("fails when overwriting an existing file", function() + touch("/test-files/rename/c.txt") + + expect(capture(stub, "rename /test-files/rename/c.txt /test-files/rename/c.txt")) + :matches { ok = true, output = "", error = "Destination exists\n" } + end) + + it("fails when copying to read-only locations", function() + touch("/test-files/rename/d.txt") + + expect(capture(stub, "rename /test-files/rename/d.txt /rom/test.txt")) + :matches { ok = true, output = "", error = "Destination is read-only\n" } + end) + + it("displays the usage when given no arguments", function() + expect(capture(stub, "rename")) + :matches { ok = true, output = "Usage: rename \n", error = "" } + end) +end)