-- test/test-gall.util.lua
--
-- Git Abstraction layer for Lua - Utility function tests
--
-- Copyright 2012 Daniel Silverstone <dsilvers@digital-scurf.org>
--
-- For Licence terms, see COPYING
--

-- Step one, start coverage

pcall(require, 'luacov')

local util = require 'gall.util'

local testnames = {}

local real_assert = assert
local total_asserts = 0
local function assert(...)
   local retval = real_assert(...)
   total_asserts = total_asserts + 1
   return retval
end

local function add_test(suite, name, value)
   rawset(suite, name, value)
   testnames[#testnames+1] = name
end

local suite = setmetatable({}, {__newindex = add_test})

function suite.test_deep_copy_simple()
   local intab = { "a", "b" }
   local outtab = util.deep_copy(intab)
   assert(intab ~= outtab)
   assert(outtab[1] == "a")
   assert(outtab[2] == "b")
end

function suite.test_deep_copy_recurse()
   local intab = { { "a" } }
   local outtab = util.deep_copy(intab)
   assert(intab ~= outtab)
   assert(intab[1] ~= outtab[1])
   assert(outtab[1][1] == "a")
end

function suite.test_deep_copy_recurse_key()
   local intab = { [{"a"}] = {"b"} }
   local outtab = util.deep_copy(intab)
   assert(intab ~= outtab)
   local inkey, inval = next(intab)
   local outkey, outval = next(outtab)
   assert(inkey ~= outkey)
   assert(outkey[1] == "a")
   assert(inval ~= outval)
   assert(outval[1] == "b")
end

function suite.test_deep_copy_memo()
   local intab = { a = {} }
   intab.b = intab.a
   local outtab = util.deep_copy(intab)
   assert(intab ~= outtab)
   assert(outtab.a == outtab.b)
end

function suite.test_deep_copy_memo_loop()
   local intab = {}
   intab.a = intab
   local outtab = util.deep_copy(intab)
   assert(intab ~= outtab)
   assert(outtab == outtab.a)
end

local count_ok = 0
for _, testname in ipairs(testnames) do
--   print("Run: " .. testname)
   local ok, err = xpcall(suite[testname], debug.traceback)
   if not ok then
      print(err)
      print()
   else
      count_ok = count_ok + 1
   end
end

print(tostring(count_ok) .. "/" .. tostring(#testnames) .. " [" .. tostring(total_asserts) .. "] OK")

os.exit(count_ok == #testnames and 0 or 1)
