Skip to content

Commit

Permalink
[utils] Added file_to_set, set_to_file + test #19
Browse files Browse the repository at this point in the history
  • Loading branch information
nemesifier committed May 27, 2016
1 parent c68c5e3 commit bae3bb6
Show file tree
Hide file tree
Showing 2 changed files with 39 additions and 0 deletions.
18 changes: 18 additions & 0 deletions openwisp-config/files/lib/openwisp/utils.lua
Original file line number Diff line number Diff line change
Expand Up @@ -134,3 +134,21 @@ function file_exists(path)
if f ~= nil then io.close(f) return true end
return false
end

function file_to_set(path)
local f = io.open(path, 'r')
local set = {}
for line in f:lines() do
set[line] = true
end
return set
end

function set_to_file(set, path)
local f = io.open(path, 'w')
for file, bool in pairs(set) do
f:write(file, '\n')
end
io.close(f)
return true
end
21 changes: 21 additions & 0 deletions openwisp-config/tests/test_utils.lua
Original file line number Diff line number Diff line change
Expand Up @@ -247,4 +247,25 @@ function TestUtils.test_file_exists()
luaunit.assertEquals(file_exists('./WRONG'), false)
end

function TestUtils.test_file_to_set()
os.execute('echo "line1" > '..write_dir..'/read.list')
os.execute('echo "line2" >> '..write_dir..'/read.list')
os.execute('echo "line3" >> '..write_dir..'/read.list')
set = file_to_set(write_dir..'/read.list')
luaunit.assertEquals(set.line1, true)
luaunit.assertEquals(set.line2, true)
luaunit.assertEquals(set.line3, true)
luaunit.assertEquals(set.line4, nil)
end

function TestUtils.test_set_to_file()
write = {line1=true, line2=true}
result = set_to_file(write, write_dir..'/write.list')
luaunit.assertEquals(result, true)
read = file_to_set(write_dir..'/write.list')
luaunit.assertEquals(read.line1, true)
luaunit.assertEquals(read.line2, true)
luaunit.assertEquals(read.line3, nil)
end

os.exit(luaunit.LuaUnit.run())

0 comments on commit bae3bb6

Please sign in to comment.