diff --git a/lua/csv.lua b/lua/csv.lua index 0f7a5fa..53916d8 100644 --- a/lua/csv.lua +++ b/lua/csv.lua @@ -43,7 +43,7 @@ local function build_column_name_map(columns) t = { transform = v.transform, default = v.default } if v.name then names = { (v.name:gsub("_+", " ")) } - else + elseif v.names then names = v.names for i, n in ipairs(names) do names[i] = n:gsub("_+", " ") end end diff --git a/lua/test.lua b/lua/test.lua index 86656eb..327fab3 100644 --- a/lua/test.lua +++ b/lua/test.lua @@ -5,19 +5,26 @@ local errors = 0 local function test(filename, correct_result, parameters) local result = {} - local f = csv.open(filename) + local f = csv.open(filename, parameters) for r in f:lines() do + if not r[1] then + local r2 = {} + for k, v in pairs(r) do r2[#r2+1] = k..":"..tostring(v) end + table.sort(r2) + r = r2 + end result[#result+1] = table.concat(r, ",") end result = table.concat(result, "\n") if result ~= correct_result then io.stderr:write( - ("Error reading %s. Expected output\n%s\nActual output\n%s\n"): + ("Error reading '%s':\nExpected output:\n%s\n\nActual output:\n%s\n\n"): format(filename, correct_result, result)) errors = errors + 1 end end + test("../test-data/embedded-newlines.csv", [[ embedded newline,embedded @@ -28,6 +35,22 @@ newline,embedded newline,embedded newline]]) +test("../test-data/embedded-quotes.csv", [[ +embedded "quotes",embedded "quotes",embedded "quotes" +embedded "quotes",embedded "quotes",embedded "quotes"]]) + +test("../test-data/header.csv", [[ +alpha:ONE,bravo:two,charlie:3 +alpha:four,bravo:five,charlie:6]], {header=true}) + +test("../test-data/header.csv", [[ +apple:one,charlie:30 +apple:four,charlie:60]], +{ columns = { + apple = { name = "ALPHA", transform = string.lower }, + charlie = { transform = function(x) return tonumber(x) * 10 end }}}) + + if errors == 0 then io.stdout:write("Passed\n") elseif errors == 1 then diff --git a/test-data/embedded-quotes.csv b/test-data/embedded-quotes.csv new file mode 100644 index 0000000..e0c5c73 --- /dev/null +++ b/test-data/embedded-quotes.csv @@ -0,0 +1,2 @@ +"embedded ""quotes""","embedded ""quotes""","embedded ""quotes""" +"embedded ""quotes""","embedded ""quotes""","embedded ""quotes""" \ No newline at end of file diff --git a/test-data/header.csv b/test-data/header.csv new file mode 100644 index 0000000..89f702e --- /dev/null +++ b/test-data/header.csv @@ -0,0 +1,3 @@ +alpha,bravo,charlie +ONE,two,3 +four,five,6 \ No newline at end of file