-- Copyright (c) 2024 Huawei Technologies Co., Ltd.
-- openUBMC is licensed under Mulan PSL v2.
-- You can use this software according to the terms and conditions of the Mulan PSL v2.
-- You may obtain a copy of Mulan PSL v2 at:
--         http://license.coscl.org.cn/MulanPSL2
-- THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
-- EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
-- MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
-- See the Mulan PSL v2 for more details.

local lu = require 'luaunit'
local smbus = require 'device.lib_pcie_oob_mgmt.smbus'

TestSmbus = {}

function TestSmbus:test_constuct_request()
    -- CAPABILITY
    local req_bin = smbus.constuct_request(0, 0, 8)
    local ret = {string.unpack('I2I2I4I4I4', req_bin)}
    lu.assertEquals(ret[1], 0)
    lu.assertEquals(ret[2], 0)
    lu.assertEquals(ret[3], 0)
    lu.assertEquals(ret[4], 8)
end

function TestSmbus:test_process_resp()
    local total_resp = {data = ''}
    local total_data_len = 0
    local resp = {error_code = 1, opcode = 5, total_length = 13, data_length = 12,
                  data = '\x01\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00'}
    local ok, is_completed = smbus.process_resp(total_resp, total_data_len, resp)
    total_data_len = total_data_len + resp.data_length
    lu.assertEquals(ok, true)
    lu.assertEquals(is_completed, false)
    lu.assertEquals(total_resp.error_code, 1)
    lu.assertEquals(total_resp.opcode, 5)
    lu.assertEquals(total_resp.total_length, 13)
    lu.assertEquals(total_resp.data_length, 12)
    lu.assertEquals(total_resp.data, '\x01\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00')
    lu.assertEquals(total_data_len, 12)

    local resp = {error_code = 1, opcode = 5, total_length = 13, data_length = 1,
                  data = '\x01'}
    local ok, is_completed = smbus.process_resp(total_resp, total_data_len, resp)
    total_data_len = total_data_len + resp.data_length
    lu.assertEquals(ok, true)
    lu.assertEquals(is_completed, true)
    lu.assertEquals(total_resp.data, '\x01\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x01')
    lu.assertEquals(total_data_len, 13)
end

function TestSmbus:test_check_error_code()
    local ok = smbus.check_error_code(0)
    lu.assertEquals(ok, true)
    local ok = smbus.check_error_code(1)
    lu.assertEquals(ok, false)
end